Skip to main content

dive_eval/
stability.rs

1//! Optional, callback-free canonical producer closure for a private row driver.
2//!
3//! This is not a purity claim about arbitrary deferred providers. Unknown
4//! constructors/caches decline before the driver starts graph capture.
5
6use std::sync::{Arc, Weak};
7
8use dive_ir::ExprId;
9
10use crate::core::Core;
11use crate::{Evaluator, Scope};
12
13#[cfg(test)]
14#[path = "stability_tests.rs"]
15mod tests;
16
17mod budgeted;
18
19#[cfg(test)]
20#[path = "stability/budgeted_tests.rs"]
21mod budgeted_tests;
22
23/// A producer/atom closure checked without evaluation for one evaluator.
24///
25/// This fact covers only the supplied roots, ordinary cache domain, and the
26/// canonical representation capability. A driver must additionally prove its
27/// source roots are complete and its host/runtime is privately owned. There is
28/// no public constructor and this does not grant temporal error authority.
29///
30/// ```
31/// use dive_eval::{Evaluator, Scope};
32/// use dive_ir::ExprId;
33/// fn inspect(evaluator: &Evaluator, root: (ExprId, Scope)) -> dive_eval::Result<()> {
34///     if let Some(fact) = evaluator.canonical_producer_stability_budgeted(&[root], &[], None)? {
35///         assert!(fact.belongs_to(evaluator));
36///     }
37///     Ok(())
38/// }
39/// # let _ = inspect;
40/// ```
41#[derive(Clone)]
42pub struct ProducerStability {
43    owner: Weak<Core>,
44}
45
46impl std::fmt::Debug for ProducerStability {
47    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48        f.debug_struct("ProducerStability").finish_non_exhaustive()
49    }
50}
51
52impl ProducerStability {
53    /// Whether this fact belongs to the actual evaluator being inspected.
54    #[must_use]
55    pub fn belongs_to(&self, evaluator: &Evaluator) -> bool {
56        self.owner.ptr_eq(&Arc::downgrade(&evaluator.core))
57    }
58}
59
60#[derive(Clone, Copy, PartialEq, Eq)]
61enum Fact {
62    Canonical,
63    // Successful enumeration yields canonical elements, but the domain itself
64    // is not admitted to reordered predicates, captured values or caches.
65    YieldCanonical,
66}
67
68#[derive(Clone, Copy, PartialEq, Eq)]
69enum Mode {
70    Producer,
71    Reordered,
72}
73
74impl Evaluator {
75    /// Inspects a pure predicate closure over closed function-tree state inputs.
76    /// Immutable interval domains and stored closed general functions are
77    /// admitted. Function constructors, CHOOSE, EXCEPT, raw/symbolic set
78    /// history and ENABLED retain the existing explicit inspection refusal.
79    /// Callers must prove the actual input rows are closed and must preserve
80    /// EXCEPT warnings/errors through reference fallback. This is not the
81    /// canonical producer certificate and does not attest arbitrary providers.
82    ///
83    /// ```no_run
84    /// # fn inspect(ev: &dive_eval::Evaluator, scope: &dive_eval::Scope,
85    /// # expr: dive_ir::ExprId) -> dive_eval::Result<()> {
86    /// let eligible = ev.closed_predicate_stability_budgeted(scope, expr, None)?;
87    /// # let _ = eligible;
88    /// # Ok(()) }
89    /// ```
90    ///
91    /// # Errors
92    /// An original interruption or inspection allocation failure.
93    pub fn closed_predicate_stability_budgeted(
94        &self,
95        scope: &Scope,
96        expr: ExprId,
97        control: Option<&dyn crate::HostControl>,
98    ) -> crate::Result<bool> {
99        budgeted::closed_predicate(self, scope, expr, control)
100    }
101
102    /// Inspects an optional action closure whose single-key EXCEPT operations
103    /// require a separate compiler/runtime proof of closed base, immutable
104    /// interval binder, exact domain and scalar replacement. This fact alone
105    /// never licenses evaluating an update or skipping reference warnings.
106    /// The optional lane additionally inspects single scalar-bound interval
107    /// constructors/CHOOSE and local integer enumeration/difference domains.
108    /// A single-clause, single-key update may use lexical scalar `@`; runtime
109    /// guards must establish its actual old leaf and replacement without
110    /// skipping missing-key warnings. No real dynamic-`@` capture is admitted.
111    /// Recursive/nested updates, hidden queries, deferred providers and effects
112    /// remain refused. The canonical producer and closed-predicate certificates
113    /// keep their original boundaries. This inspection executes no constructor
114    /// or CHOOSE and does not prove an arbitrary raw-set history.
115    ///
116    /// ```no_run
117    /// # fn inspect(ev: &dive_eval::Evaluator, scope: &dive_eval::Scope, expr: dive_ir::ExprId) -> dive_eval::Result<()> {
118    /// let closure = ev.guarded_action_stability_budgeted(scope, expr, None)?;
119    /// // A successful inspection still requires compiler/runtime update guards.
120    /// # let _ = closure;
121    /// # Ok(()) }
122    /// ```
123    ///
124    /// # Errors
125    /// An original interruption or inspection allocation failure.
126    pub fn guarded_action_stability_budgeted(
127        &self,
128        scope: &Scope,
129        expr: ExprId,
130        control: Option<&dyn crate::HostControl>,
131    ) -> crate::Result<bool> {
132        budgeted::closed_action(self, scope, expr, control)
133    }
134
135    /// Inspects canonical producer and predicate storage under the run budget.
136    ///
137    /// This callback-free inspection uses explicit traversal stacks, without a
138    /// formula, value-depth or proof-work ceiling. Unknown representation or
139    /// transfer semantics still return `None`. An explicit control is polled
140    /// when supplied; otherwise the evaluator's installed control is polled.
141    /// No provider, expression or native permission callback is invoked.
142    /// This grants neither private-host ownership nor completeness of the
143    /// supplied producer roots.
144    /// A single scalar CHOOSE binder may consume its own closed integer
145    /// enumeration after element and scoped-body inspection. This does not
146    /// relabel a retained raw set or certify an error, truth or demand order.
147    ///
148    /// ```no_run
149    /// # fn inspect(ev: &dive_eval::Evaluator, root: (dive_ir::ExprId, dive_eval::Scope))
150    /// # -> dive_eval::Result<()> {
151    /// if let Some(fact) = ev.canonical_producer_stability_budgeted(&[root], &[], None)? {
152    ///     assert!(fact.belongs_to(ev));
153    /// }
154    /// # Ok(()) }
155    /// ```
156    ///
157    /// # Errors
158    /// The original typed interruption, or failed traversal allocation.
159    pub fn canonical_producer_stability_budgeted(
160        &self,
161        producers: &[(ExprId, Scope)],
162        predicates: &[(ExprId, Scope)],
163        control: Option<&dyn crate::HostControl>,
164    ) -> crate::Result<Option<ProducerStability>> {
165        budgeted::prove(self, producers, predicates, control)
166    }
167}
168
169// Private fixed-data/independence inspection. Boolean/totality follows only
170// from the original completed singleton predicate observations, not this fact.
171pub(crate) fn closed_subset_forall(
172    evaluator: &Evaluator,
173    original: Scope,
174    quantifier: ExprId,
175    body: ExprId,
176    outer_slot: usize,
177    state: &crate::St,
178    base: &[dive_value::Value],
179) -> crate::Result<bool> {
180    budgeted::closed_forall(
181        evaluator, original, quantifier, body, outer_slot, state, base,
182    )
183}