Skip to main content

tenferro_ad/
context.rs

1//! Explicit ownership for automatic-differentiation rule sets.
2
3use std::sync::Arc;
4
5use tenferro_runtime::program::FrozenProgram;
6use tenferro_runtime::{CacheStats, Result, TracedTensor};
7
8// SemanticCompatDispatcher removed in Unification 7.
9// Extension AD is handled exclusively by SemanticExtensionRuleSet.
10use crate::semantic_extension::{SemanticExtensionRegistryError, SemanticExtensionRuleSet};
11use crate::semantic_transform::{
12    semantic_jvp, semantic_vjp, SemanticAdProgram, SemanticAdTransformError,
13};
14use crate::transform_cache::{
15    AdTransformCache, AdTransformCacheLimits, SemanticAdTransformCacheKey,
16};
17
18/// Stats for caches owned by an [`AdContext`].
19///
20/// `retained_bytes` fields are logical payload estimates, not process RSS.
21///
22/// # Examples
23///
24/// ```rust
25/// use tenferro_ad::AdContext;
26///
27/// let ad = AdContext::builder().build().unwrap();
28/// assert_eq!(ad.cache_stats().unwrap().ad_transforms.entries, 0);
29/// ```
30#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
31pub struct AdContextCacheStats {
32    /// AD transform graph memoization cache.
33    pub ad_transforms: CacheStats,
34}
35
36/// Explicit automatic-differentiation context.
37///
38/// `AdContext` owns the extension AD rules used by traced AD transforms.
39/// It also owns the AD transform cache shared by context-driven traced AD and
40/// eager runtimes created from this context.
41///
42/// # Examples
43///
44/// ```rust
45/// use tenferro_ad::AdContext;
46///
47/// let ad = AdContext::builder().build().unwrap();
48/// assert!(ad
49///     .semantic_extension_rules()
50///     .lookup_linearize("example.missing.v1")
51///     .is_none());
52/// ```
53#[derive(Clone, Debug)]
54pub struct AdContext {
55    semantic_extension_rules: SemanticExtensionRuleSet,
56    ad_transform_cache: Arc<AdTransformCache>,
57}
58
59impl AdContext {
60    /// Start building an explicit AD context.
61    ///
62    /// # Examples
63    ///
64    /// ```rust
65    /// use tenferro_ad::AdContext;
66    ///
67    /// let _builder = AdContext::builder();
68    /// ```
69    pub fn builder() -> AdContextBuilder {
70        AdContextBuilder::default()
71    }
72
73    pub(crate) fn with_rules_and_transform_cache(
74        semantic_extension_rules: SemanticExtensionRuleSet,
75        ad_transform_cache: Arc<AdTransformCache>,
76    ) -> Self {
77        Self {
78            semantic_extension_rules,
79            ad_transform_cache,
80        }
81    }
82
83    /// Return semantic-program extension AD rules owned by this context.
84    ///
85    /// # Examples
86    ///
87    /// ```rust
88    /// use tenferro_ad::AdContext;
89    ///
90    /// let ad = AdContext::builder().build().unwrap();
91    /// assert!(ad
92    ///     .semantic_extension_rules()
93    ///     .lookup_linearize("example.missing.v1")
94    ///     .is_none());
95    /// ```
96    pub fn semantic_extension_rules(&self) -> &SemanticExtensionRuleSet {
97        &self.semantic_extension_rules
98    }
99
100    /// Transform a frozen semantic program into its forward-mode derivative.
101    ///
102    /// `active_inputs` follows source-program input order. Active tangent
103    /// seeds are appended after all primal inputs.
104    ///
105    /// # Errors
106    ///
107    /// Returns [`SemanticAdTransformError::ActivityArity`] when
108    /// `active_inputs` has the wrong length,
109    /// [`SemanticAdTransformError::Extension`] when an extension rule rejects
110    /// the transform, or the corresponding `Query`, `Build`, `Finish`, or
111    /// `Cache` variant when program import, construction, finalization, or
112    /// cache access fails.
113    pub fn jvp_program(
114        &self,
115        input: &FrozenProgram,
116        active_inputs: &[bool],
117    ) -> std::result::Result<SemanticAdProgram, SemanticAdTransformError> {
118        let key = SemanticAdTransformCacheKey::jvp(input, active_inputs);
119        if let Some(cached) = self
120            .ad_transform_cache
121            .get_semantic(&key, input)
122            .map_err(SemanticAdTransformError::Cache)?
123        {
124            return cached
125                .as_ref()
126                .with_input_prefix_bindings_from(input)
127                .map_err(SemanticAdTransformError::from);
128        }
129        let transformed = semantic_jvp(input, active_inputs, &self.semantic_extension_rules)?;
130        self.ad_transform_cache
131            .put_semantic(key, input, Arc::new(transformed.clone()))
132            .map_err(SemanticAdTransformError::Cache)?;
133        Ok(transformed)
134    }
135
136    /// Transform a frozen semantic program into its reverse-mode derivative.
137    ///
138    /// `active_inputs` selects requested primal-input cotangents and
139    /// `active_outputs` selects primal outputs that receive appended seeds.
140    ///
141    /// # Errors
142    ///
143    /// Returns [`SemanticAdTransformError::ActivityArity`] when either activity
144    /// mask has the wrong length,
145    /// [`SemanticAdTransformError::Extension`] when an extension rule rejects
146    /// the transform, or the corresponding `Query`, `Build`, `Finish`, or
147    /// `Cache` variant when program import, construction, finalization, or
148    /// cache access fails.
149    pub fn vjp_program(
150        &self,
151        input: &FrozenProgram,
152        active_inputs: &[bool],
153        active_outputs: &[bool],
154    ) -> std::result::Result<SemanticAdProgram, SemanticAdTransformError> {
155        let key = SemanticAdTransformCacheKey::vjp(input, active_inputs, active_outputs);
156        if let Some(cached) = self
157            .ad_transform_cache
158            .get_semantic(&key, input)
159            .map_err(SemanticAdTransformError::Cache)?
160        {
161            return cached
162                .as_ref()
163                .with_input_prefix_bindings_from(input)
164                .map_err(SemanticAdTransformError::from);
165        }
166        let transformed = semantic_vjp(
167            input,
168            active_inputs,
169            active_outputs,
170            &self.semantic_extension_rules,
171        )?;
172        self.ad_transform_cache
173            .put_semantic(key, input, Arc::new(transformed.clone()))
174            .map_err(SemanticAdTransformError::Cache)?;
175        Ok(transformed)
176    }
177
178    pub(crate) fn ad_transform_cache(&self) -> Arc<AdTransformCache> {
179        Arc::clone(&self.ad_transform_cache)
180    }
181
182    /// Return AD transform cache retention limits.
183    ///
184    /// # Examples
185    ///
186    /// ```rust
187    /// use tenferro_ad::AdContext;
188    ///
189    /// let ad = AdContext::builder().build().unwrap();
190    /// assert!(ad.ad_transform_cache_limits().unwrap().max_entries().get() > 0);
191    /// ```
192    ///
193    /// # Errors
194    ///
195    /// Returns [`tenferro_runtime::Error::RuntimeState`] if the cache lock is
196    /// poisoned or its state cannot be inspected.
197    pub fn ad_transform_cache_limits(&self) -> Result<AdTransformCacheLimits> {
198        self.ad_transform_cache.limits()
199    }
200
201    /// Replace AD transform cache retention limits.
202    ///
203    /// # Examples
204    ///
205    /// ```rust
206    /// use std::num::NonZeroUsize;
207    /// use tenferro_ad::{AdContext, AdTransformCacheLimits};
208    ///
209    /// let ad = AdContext::builder().build().unwrap();
210    /// let limits = AdTransformCacheLimits::new(NonZeroUsize::new(1).unwrap());
211    /// ad.set_ad_transform_cache_limits(limits).unwrap();
212    /// assert_eq!(ad.ad_transform_cache_limits().unwrap(), limits);
213    /// ```
214    ///
215    /// # Errors
216    ///
217    /// Returns [`tenferro_runtime::Error::RuntimeState`] if the cache lock is
218    /// poisoned while updating the limits.
219    pub fn set_ad_transform_cache_limits(&self, limits: AdTransformCacheLimits) -> Result<()> {
220        self.ad_transform_cache.set_limits(limits)
221    }
222
223    /// Clear AD transform cache entries owned by this context.
224    ///
225    /// # Examples
226    ///
227    /// ```rust
228    /// use tenferro_ad::AdContext;
229    ///
230    /// let ad = AdContext::builder().build().unwrap();
231    /// ad.clear_ad_transform_caches().unwrap();
232    /// assert_eq!(ad.ad_transform_cache_stats().unwrap().entries, 0);
233    /// ```
234    ///
235    /// # Errors
236    ///
237    /// Returns [`tenferro_runtime::Error::RuntimeState`] if the cache lock is
238    /// poisoned while clearing entries.
239    pub fn clear_ad_transform_caches(&self) -> Result<()> {
240        self.ad_transform_cache.clear()
241    }
242
243    /// Return AD transform cache-entry and retained-byte stats.
244    ///
245    /// # Examples
246    ///
247    /// ```rust
248    /// use tenferro_ad::AdContext;
249    ///
250    /// let ad = AdContext::builder().build().unwrap();
251    /// assert_eq!(ad.ad_transform_cache_stats().unwrap().entries, 0);
252    /// ```
253    ///
254    /// # Errors
255    ///
256    /// Returns [`tenferro_runtime::Error::RuntimeState`] if the cache lock is
257    /// poisoned while collecting statistics.
258    pub fn ad_transform_cache_stats(&self) -> Result<CacheStats> {
259        self.ad_transform_cache.stats()
260    }
261
262    /// Clear every cache owned by this AD context.
263    ///
264    /// # Examples
265    ///
266    /// ```rust
267    /// use tenferro_ad::AdContext;
268    ///
269    /// let ad = AdContext::builder().build().unwrap();
270    /// ad.clear_caches().unwrap();
271    /// assert_eq!(ad.cache_stats().unwrap().ad_transforms.entries, 0);
272    /// ```
273    ///
274    /// # Errors
275    ///
276    /// Returns [`tenferro_runtime::Error::RuntimeState`] if either owned cache
277    /// cannot be locked because its state is poisoned.
278    pub fn clear_caches(&self) -> Result<()> {
279        self.clear_ad_transform_caches()
280    }
281
282    /// Return aggregate cache-entry and retained-byte stats for this AD context.
283    ///
284    /// # Examples
285    ///
286    /// ```rust
287    /// use tenferro_ad::AdContext;
288    ///
289    /// let ad = AdContext::builder().build().unwrap();
290    /// assert_eq!(ad.cache_stats().unwrap().ad_transforms.retained_bytes, 0);
291    /// ```
292    ///
293    /// # Errors
294    ///
295    /// Returns [`tenferro_runtime::Error::RuntimeState`] if an owned cache lock
296    /// is poisoned while collecting statistics.
297    pub fn cache_stats(&self) -> Result<AdContextCacheStats> {
298        Ok(AdContextCacheStats {
299            ad_transforms: self.ad_transform_cache_stats()?,
300        })
301    }
302
303    /// Gradient of a scalar traced output with respect to a traced input.
304    ///
305    /// For complex scalar outputs, tenferro returns the Hermitian-adjoint
306    /// cotangent. To compare seed-`1` scalar gradients with JAX's public
307    /// `grad` values, use the complex conjugate of this result. See
308    /// <https://tensor4all.org/tenferro-rs/guides/complex-ad.html>.
309    ///
310    /// # Examples
311    ///
312    /// ```rust
313    /// use tenferro_ad::AdContext;
314    /// use tenferro_runtime::{TraceContext, TracedTensor};
315    ///
316    /// let ad = AdContext::builder().build().unwrap();
317    /// let trace = TraceContext::new();
318    /// let x = trace.from_vec_col_major(vec![], vec![3.0_f64]).unwrap();
319    /// let loss = (&x * &x).unwrap();
320    /// let grad = ad.grad(&loss, &x).unwrap();
321    /// assert_eq!(grad.rank(), 0);
322    /// ```
323    ///
324    /// # Errors
325    ///
326    /// Returns [`tenferro_runtime::Error::NonScalarGrad`] when `output` is not
327    /// scalar, [`tenferro_runtime::Error::UnsupportedAdRule`] when a graph op
328    /// lacks a registered rule, or a typed [`tenferro_runtime::Error::Validation`]
329    /// / backend error when graph metadata or execution is invalid. An inactive
330    /// `wrt` returns [`tenferro_runtime::Error::Validation`] with
331    /// `argument: "wrt"`; use [`grad_optional`](Self::grad_optional) to observe
332    /// that state.
333    pub fn grad(&self, output: &TracedTensor, wrt: &TracedTensor) -> Result<TracedTensor> {
334        crate::traced::grad_with_rules_and_cache(
335            output,
336            wrt,
337            &self.semantic_extension_rules,
338            Some(&self.ad_transform_cache),
339        )
340    }
341
342    /// Gradient that returns `None` when `wrt` is inactive.
343    ///
344    /// # Examples
345    ///
346    /// ```rust
347    /// use tenferro_ad::AdContext;
348    /// use tenferro_runtime::{TraceContext, TracedTensor};
349    ///
350    /// let ad = AdContext::builder().build().unwrap();
351    /// let trace = TraceContext::new();
352    /// let x = trace.from_vec_col_major(vec![], vec![3.0_f64]).unwrap();
353    /// let loss = (&x * &x).unwrap();
354    /// assert!(ad.grad_optional(&loss, &x).unwrap().is_some());
355    /// ```
356    ///
357    /// # Errors
358    ///
359    /// Returns [`tenferro_runtime::Error::NonScalarGrad`] for a non-scalar
360    /// output, [`tenferro_runtime::Error::UnsupportedAdRule`] for an
361    /// unregistered AD rule, or a typed [`tenferro_runtime::Error::Validation`]
362    /// / backend error from graph construction and
363    /// execution.
364    pub fn grad_optional(
365        &self,
366        output: &TracedTensor,
367        wrt: &TracedTensor,
368    ) -> Result<Option<TracedTensor>> {
369        crate::traced::grad_optional_with_rules_and_cache(
370            output,
371            wrt,
372            &self.semantic_extension_rules,
373            Some(&self.ad_transform_cache),
374        )
375    }
376
377    /// Forward-mode Jacobian-vector product.
378    ///
379    /// # Examples
380    ///
381    /// ```rust
382    /// use tenferro_ad::AdContext;
383    /// use tenferro_runtime::{TraceContext, TracedTensor};
384    ///
385    /// let ad = AdContext::builder().build().unwrap();
386    /// let trace = TraceContext::new();
387    /// let x = trace.from_vec_col_major(vec![], vec![3.0_f64]).unwrap();
388    /// let dx = trace.from_vec_col_major(vec![], vec![1.0_f64]).unwrap();
389    /// let y = (&x * &x).unwrap();
390    /// let dy = ad.jvp(&y, &x, &dx).unwrap();
391    /// assert_eq!(dy.rank(), 0);
392    /// ```
393    ///
394    /// # Errors
395    ///
396    /// Returns [`tenferro_runtime::Error::UnsupportedAdRule`] when the graph
397    /// has no JVP rule, [`tenferro_runtime::Error::Validation`] for
398    /// inconsistent tangent metadata, or a typed backend/runtime-state error
399    /// during evaluation. An inactive `wrt` returns
400    /// [`tenferro_runtime::Error::Validation`] with `argument: "wrt"`; use
401    /// [`jvp_optional`](Self::jvp_optional) to observe that state.
402    pub fn jvp(
403        &self,
404        output: &TracedTensor,
405        wrt: &TracedTensor,
406        tangent: &TracedTensor,
407    ) -> Result<TracedTensor> {
408        crate::traced::jvp_with_rules_and_cache(
409            output,
410            wrt,
411            tangent,
412            &self.semantic_extension_rules,
413            Some(&self.ad_transform_cache),
414        )
415    }
416
417    /// Forward-mode Jacobian-vector product that returns `None` for inactive output.
418    ///
419    /// # Examples
420    ///
421    /// ```rust
422    /// use tenferro_ad::AdContext;
423    /// use tenferro_runtime::{TraceContext, TracedTensor};
424    ///
425    /// let ad = AdContext::builder().build().unwrap();
426    /// let trace = TraceContext::new();
427    /// let x = trace.from_vec_col_major(vec![], vec![3.0_f64]).unwrap();
428    /// let dx = trace.from_vec_col_major(vec![], vec![1.0_f64]).unwrap();
429    /// let y = (&x * &x).unwrap();
430    /// assert!(ad.jvp_optional(&y, &x, &dx).unwrap().is_some());
431    /// ```
432    ///
433    /// # Errors
434    ///
435    /// Returns [`tenferro_runtime::Error::UnsupportedAdRule`] when the graph
436    /// has no JVP rule, [`tenferro_runtime::Error::Validation`] for
437    /// inconsistent tangent metadata, or a typed backend/runtime-state error
438    /// during evaluation.
439    pub fn jvp_optional(
440        &self,
441        output: &TracedTensor,
442        wrt: &TracedTensor,
443        tangent: &TracedTensor,
444    ) -> Result<Option<TracedTensor>> {
445        crate::traced::jvp_optional_with_rules_and_cache(
446            output,
447            wrt,
448            tangent,
449            &self.semantic_extension_rules,
450            Some(&self.ad_transform_cache),
451        )
452    }
453
454    /// Forward-mode directional derivative for multiple distinct traced leaves.
455    ///
456    /// Reachable leaves are transformed together in one derivative graph.
457    /// Unreachable leaves contribute nothing; an empty or fully unreachable
458    /// request returns `None`. Duplicate `wrt` leaves are rejected before the
459    /// transform because one semantic seed slot cannot accept two tangents.
460    ///
461    /// # Examples
462    ///
463    /// ```rust
464    /// use tenferro_ad::AdContext;
465    /// use tenferro_runtime::{TraceContext, TracedTensor};
466    ///
467    /// let ad = AdContext::builder().build().unwrap();
468    /// let trace = TraceContext::new();
469    /// let x = trace.from_vec_col_major(vec![], vec![2.0_f64]).unwrap();
470    /// let y = trace.from_vec_col_major(vec![], vec![3.0_f64]).unwrap();
471    /// let dx = trace.from_vec_col_major(vec![], vec![1.0_f64]).unwrap();
472    /// let dy = trace.from_vec_col_major(vec![], vec![4.0_f64]).unwrap();
473    /// let output = (&x * &y).unwrap();
474    /// assert!(ad.jvp_many(&output, &[(&x, &dx), (&y, &dy)]).unwrap().is_some());
475    /// ```
476    ///
477    /// # Errors
478    ///
479    /// Returns [`tenferro_runtime::Error::Validation`] for duplicate leaves or
480    /// incompatible tangent metadata, [`tenferro_runtime::Error::UnsupportedAdRule`]
481    /// when a required rule is unavailable, or a typed runtime-state error when
482    /// derivative graph construction fails.
483    ///
484    /// # Deferred errors
485    ///
486    /// Symbolic shape constraints may fail during later compilation or execution.
487    pub fn jvp_many(
488        &self,
489        output: &TracedTensor,
490        wrt_tangents: &[(&TracedTensor, &TracedTensor)],
491    ) -> Result<Option<TracedTensor>> {
492        crate::traced::jvp_many_with_rules_and_cache(
493            output,
494            wrt_tangents,
495            &self.semantic_extension_rules,
496            Some(&self.ad_transform_cache),
497        )
498    }
499
500    /// Reverse-mode vector-Jacobian product.
501    ///
502    /// Complex cotangents use tenferro's Hermitian real-inner-product
503    /// convention. Non-real complex cotangent seeds therefore need an explicit
504    /// seed-convention comparison when matching JAX. See
505    /// <https://tensor4all.org/tenferro-rs/guides/complex-ad.html>.
506    ///
507    /// # Examples
508    ///
509    /// ```rust
510    /// use tenferro_ad::AdContext;
511    /// use tenferro_runtime::{TraceContext, TracedTensor};
512    ///
513    /// let ad = AdContext::builder().build().unwrap();
514    /// let trace = TraceContext::new();
515    /// let x = trace.from_vec_col_major(vec![], vec![3.0_f64]).unwrap();
516    /// let dy = trace.from_vec_col_major(vec![], vec![1.0_f64]).unwrap();
517    /// let y = (&x * &x).unwrap();
518    /// let dx = ad.vjp(&y, &x, &dy).unwrap();
519    /// assert_eq!(dx.rank(), 0);
520    /// ```
521    ///
522    /// # Errors
523    ///
524    /// Returns [`tenferro_runtime::Error::Validation`] when the cotangent
525    /// metadata is incompatible, [`tenferro_runtime::Error::UnsupportedAdRule`]
526    /// when a VJP rule is unavailable, or a typed backend/runtime-state error
527    /// during execution. An inactive `wrt` returns
528    /// [`tenferro_runtime::Error::Validation`] with `argument: "wrt"`; use
529    /// [`vjp_optional`](Self::vjp_optional) to observe that state.
530    pub fn vjp(
531        &self,
532        output: &TracedTensor,
533        wrt: &TracedTensor,
534        cotangent: &TracedTensor,
535    ) -> Result<TracedTensor> {
536        crate::traced::vjp_with_rules_and_cache(
537            output,
538            wrt,
539            cotangent,
540            &self.semantic_extension_rules,
541            Some(&self.ad_transform_cache),
542        )
543    }
544
545    /// Reverse-mode vector-Jacobian product that returns `None` for inactive input.
546    ///
547    /// # Examples
548    ///
549    /// ```rust
550    /// use tenferro_ad::AdContext;
551    /// use tenferro_runtime::{TraceContext, TracedTensor};
552    ///
553    /// let ad = AdContext::builder().build().unwrap();
554    /// let trace = TraceContext::new();
555    /// let x = trace.from_vec_col_major(vec![], vec![3.0_f64]).unwrap();
556    /// let dy = trace.from_vec_col_major(vec![], vec![1.0_f64]).unwrap();
557    /// let y = (&x * &x).unwrap();
558    /// assert!(ad.vjp_optional(&y, &x, &dy).unwrap().is_some());
559    /// ```
560    ///
561    /// # Errors
562    ///
563    /// Returns [`tenferro_runtime::Error::Validation`] when the cotangent
564    /// metadata is incompatible, [`tenferro_runtime::Error::UnsupportedAdRule`]
565    /// when a VJP rule is unavailable, or a typed backend/runtime-state error
566    /// during execution.
567    pub fn vjp_optional(
568        &self,
569        output: &TracedTensor,
570        wrt: &TracedTensor,
571        cotangent: &TracedTensor,
572    ) -> Result<Option<TracedTensor>> {
573        crate::traced::vjp_optional_with_rules_and_cache(
574            output,
575            wrt,
576            cotangent,
577            &self.semantic_extension_rules,
578            Some(&self.ad_transform_cache),
579        )
580    }
581
582    /// Reverse-mode products for multiple traced leaves in one derivative graph.
583    ///
584    /// Results align with `wrts`; unreachable leaves produce `None`. Duplicate
585    /// leaves are allowed and repeat the same traced derivative without
586    /// accumulating the cotangent twice. An empty request validates that the
587    /// cotangent has concrete data, then returns an empty vector.
588    ///
589    /// # Examples
590    ///
591    /// ```rust
592    /// use tenferro_ad::AdContext;
593    /// use tenferro_runtime::{TraceContext, TracedTensor};
594    ///
595    /// let ad = AdContext::builder().build().unwrap();
596    /// let trace = TraceContext::new();
597    /// let x = trace.from_vec_col_major(vec![], vec![2.0_f64]).unwrap();
598    /// let y = trace.from_vec_col_major(vec![], vec![3.0_f64]).unwrap();
599    /// let seed = trace.from_vec_col_major(vec![], vec![1.0_f64]).unwrap();
600    /// let output = (&x * &y).unwrap();
601    /// let products = ad.vjp_many(&output, &[&x, &y], &seed).unwrap();
602    /// assert!(products.iter().all(Option::is_some));
603    /// ```
604    ///
605    /// # Errors
606    ///
607    /// Returns [`tenferro_runtime::Error::Validation`] for invalid cotangent
608    /// metadata, [`tenferro_runtime::Error::UnsupportedAdRule`] when a required
609    /// rule is unavailable, or a typed runtime-state error when derivative graph
610    /// construction fails.
611    ///
612    /// # Deferred errors
613    ///
614    /// Symbolic shape constraints may fail during later compilation or execution.
615    pub fn vjp_many(
616        &self,
617        output: &TracedTensor,
618        wrts: &[&TracedTensor],
619        cotangent: &TracedTensor,
620    ) -> Result<Vec<Option<TracedTensor>>> {
621        crate::traced::vjp_many_with_rules_and_cache(
622            output,
623            wrts,
624            cotangent,
625            &self.semantic_extension_rules,
626            Some(&self.ad_transform_cache),
627        )
628    }
629}
630
631/// Builder for [`AdContext`].
632///
633/// # Examples
634///
635/// ```rust
636/// use tenferro_ad::AdContextBuilder;
637///
638/// let ad = AdContextBuilder::new().build().unwrap();
639/// assert!(ad
640///     .semantic_extension_rules()
641///     .lookup_linearize("example.missing.v1")
642///     .is_none());
643/// ```
644#[derive(Clone, Debug, Default)]
645pub struct AdContextBuilder {
646    semantic_extension_rules: SemanticExtensionRuleSet,
647}
648
649impl AdContextBuilder {
650    /// Create an empty builder.
651    ///
652    /// # Examples
653    ///
654    /// ```rust
655    /// use tenferro_ad::AdContextBuilder;
656    ///
657    /// let _builder = AdContextBuilder::new();
658    /// ```
659    pub fn new() -> Self {
660        Self::default()
661    }
662
663    /// Include an owned semantic-program extension AD rule set.
664    ///
665    /// # Errors
666    ///
667    /// Returns [`SemanticExtensionRegistryError::MalformedFamilyId`] when a
668    /// family identifier is invalid, or
669    /// [`SemanticExtensionRegistryError::DuplicateRule`] when the same family
670    /// and role were already supplied.
671    pub fn with_semantic_extension_rules(
672        mut self,
673        rules: SemanticExtensionRuleSet,
674    ) -> std::result::Result<Self, SemanticExtensionRegistryError> {
675        self.semantic_extension_rules.merge(rules)?;
676        Ok(self)
677    }
678
679    /// Build the context.
680    ///
681    /// Semantic extension rules have already been validated and merged by
682    /// [`Self::with_semantic_extension_rules`].
683    ///
684    /// # Examples
685    ///
686    /// ```rust
687    /// use tenferro_ad::AdContext;
688    ///
689    /// let ad = AdContext::builder().build().unwrap();
690    /// assert!(ad
691    ///     .semantic_extension_rules()
692    ///     .lookup_linearize("example.missing.v1")
693    ///     .is_none());
694    /// ```
695    ///
696    /// # Errors
697    ///
698    /// The error type is [`std::convert::Infallible`], so this finalization step
699    /// never returns `Err` after semantic rule registration. It retains a
700    /// `Result` so callers can compose it with the fallible registration step.
701    pub fn build(self) -> std::result::Result<AdContext, std::convert::Infallible> {
702        Ok(AdContext {
703            semantic_extension_rules: self.semantic_extension_rules,
704            ad_transform_cache: Arc::new(AdTransformCache::new()),
705        })
706    }
707}