Skip to main content

adam_lang/
checking.rs

1//! Checks Adam syntax with a callback-free CEL environment.
2//!
3//! ```
4//! use adam_lang::{AdamAstParser, TypeRegistry, checking_environment, check_sheet_with_environment};
5//! use cel_parser::checking::MetadataAvailability;
6//! let environment = checking_environment(&TypeRegistry::new(), &cel_parser::OpLookup::new())?;
7//! let sheet = AdamAstParser::new().parse_str("sheet app { cell x: i32; }")?;
8//! let report = check_sheet_with_environment(&sheet, &environment, MetadataAvailability::Complete);
9//! assert!(report.diagnostics.is_empty() && report.incomplete.is_empty());
10//! # Ok::<(), Box<dyn std::error::Error>>(())
11//! ```
12
13pub mod metadata;
14
15use crate::{TypeRegistry, ast};
16use cel_parser::{
17    OpLookup,
18    checking::{
19        CheckingBuilder, CheckingEnvironment, CheckingReport, CheckingType, HostTypeBinding,
20        MetadataAvailability, MetadataError,
21    },
22};
23
24/// Owns CEL checking facts and explicit Adam-registered storage leaves.
25///
26/// Membership IDs belong to the inner CEL catalog, are unique, and are sorted.
27/// CEL capabilities and type-function results never imply Adam membership.
28///
29/// # Examples
30/// ```
31/// let environment = adam_lang::checking_environment(
32///     &adam_lang::TypeRegistry::new(), &cel_parser::OpLookup::new()).unwrap();
33/// assert!(environment.cel().resolve_type("i32").is_some());
34/// assert!(!environment.cell_types().is_empty());
35/// ```
36pub struct AdamCheckingEnvironment {
37    cel: CheckingEnvironment,
38    cell_types: Vec<u32>,
39}
40
41impl AdamCheckingEnvironment {
42    /// Owns the catalog and sorts explicitly supplied Adam leaf membership.
43    ///
44    /// # Errors
45    /// Rejects duplicate IDs and IDs absent from the CEL catalog.
46    ///
47    /// - Complexity: Expected O(n + m log(m + 1)) time and O(n + m) space for
48    ///   n catalog leaves and m membership IDs, including owned membership storage.
49    ///
50    /// # Examples
51    /// ```
52    /// use adam_lang::checking::AdamCheckingEnvironment;
53    /// let cel = cel_parser::checking::CheckingBuilder::new().finish().unwrap();
54    /// let environment = AdamCheckingEnvironment::from_parts(cel, vec![]).unwrap();
55    /// assert!(environment.cell_types().is_empty());
56    /// ```
57    pub fn from_parts(
58        cel: CheckingEnvironment,
59        mut cell_types: Vec<u32>,
60    ) -> Result<Self, MetadataError> {
61        cell_types.sort_unstable();
62        if cell_types.windows(2).any(|pair| pair[0] == pair[1]) {
63            return Err(MetadataError(
64                "cellTypes: duplicate Adam storage leaf ID".into(),
65            ));
66        }
67        let known: std::collections::HashSet<_> =
68            cel.description().types.iter().map(|leaf| leaf.id).collect();
69        if let Some(id) = cell_types.iter().find(|id| !known.contains(id)) {
70            return Err(MetadataError(format!(
71                "cellTypes: unknown Adam storage leaf ID {id}"
72            )));
73        }
74        Ok(Self { cel, cell_types })
75    }
76
77    /// Borrows the CEL catalog used by expression checks and native bindings.
78    ///
79    /// # Examples
80    /// See the [type example](Self).
81    pub fn cel(&self) -> &CheckingEnvironment {
82        &self.cel
83    }
84
85    /// Borrows the sorted, explicitly registered Adam leaf IDs.
86    ///
87    /// # Examples
88    /// See the [type example](Self).
89    pub fn cell_types(&self) -> &[u32] {
90        &self.cell_types
91    }
92
93    /// Tests membership of a leaf owned by this catalog.
94    ///
95    /// - Complexity: O(log(n + 1)) for n membership IDs.
96    pub(crate) fn contains_leaf(&self, ty: &cel_parser::Ty) -> bool {
97        matches!(self.cel.type_reference(ty), Some(CheckingType::Leaf(id))
98            if self.cell_types.binary_search(&id).is_ok())
99    }
100
101    /// Visits every known unregistered leaf, including callable parameters and results.
102    ///
103    /// Unknown leaves do not suppress visits to independently known siblings.
104    /// - Complexity: O(t log(n + 1)) time and O(d) traversal space for t shape nodes,
105    ///   n registered leaves, and shape depth d, excluding visitor costs.
106    pub(crate) fn visit_unregistered_leaves(
107        &self,
108        ty: &cel_parser::Ty,
109        visit: &mut impl FnMut(&cel_parser::Ty),
110    ) {
111        use cel_parser::Ty;
112        match ty {
113            Ty::Any => {}
114            Ty::Tuple(elements) => {
115                for element in elements {
116                    self.visit_unregistered_leaves(element, visit);
117                }
118            }
119            Ty::Array(element) => self.visit_unregistered_leaves(element, visit),
120            Ty::Callable(parameters, result) => {
121                for parameter in parameters {
122                    self.visit_unregistered_leaves(parameter, visit);
123                }
124                self.visit_unregistered_leaves(result, visit);
125            }
126            leaf if !self.contains_leaf(leaf) => visit(leaf),
127            _ => {}
128        }
129    }
130}
131
132/// Projects the effective runtime registrations without invoking application callbacks.
133///
134/// # Errors
135/// Rejects callback-only scopes and registrations without complete checking metadata.
136///
137/// - Complexity: [`checking_environment_with_binding`] projection costs.
138///
139/// # Examples
140/// See the [module example](self).
141pub fn checking_environment(
142    types: &TypeRegistry,
143    lookup: &OpLookup,
144) -> Result<AdamCheckingEnvironment, MetadataError> {
145    checking_environment_with_binding(types, lookup).map(|(environment, _)| environment)
146}
147
148/// Projects the effective registrations together with an explicit native catalog binding.
149///
150/// The binding is host-only data and never enters serialized metadata.
151/// # Errors
152/// Rejects unsupported scopes and incomplete registrations.
153/// - Complexity: Registry projection and catalog finalization plus expected
154///   O(n + m log(m + 1)) time and O(n + m) space for n catalog leaves and
155///   m Adam registrations.
156///
157/// # Examples
158/// ```
159/// let (_, binding) = adam_lang::checking_environment_with_binding(
160///     &adam_lang::TypeRegistry::new(), &cel_parser::OpLookup::new()).unwrap();
161/// let mut modules = adam_lang::ModuleSet::new();
162/// modules.set_native_binding(binding);
163/// ```
164pub fn checking_environment_with_binding(
165    types: &TypeRegistry,
166    lookup: &OpLookup,
167) -> Result<(AdamCheckingEnvironment, HostTypeBinding), MetadataError> {
168    let mut builder = CheckingBuilder::new();
169    types.register_checking_types(&mut builder)?;
170    builder.register_lookup(lookup)?;
171    let (cel, binding) = builder.finish_with_host_binding()?;
172    let cell_types = types
173        .cell_type_ids()
174        .map(|id| {
175            let ty = binding.resolve(&cel, id).ok_or_else(|| {
176                MetadataError("Adam registration has no CEL catalog binding".into())
177            })?;
178            match cel.type_reference(&ty) {
179                Some(CheckingType::Leaf(id)) => Ok(id),
180                _ => Err(MetadataError(
181                    "Adam registration is not a catalog leaf".into(),
182                )),
183            }
184        })
185        .collect::<Result<_, _>>()?;
186    Ok((
187        AdamCheckingEnvironment::from_parts(cel, cell_types)?,
188        binding,
189    ))
190}
191
192/// Checks every authored body and guard dependency without lowering executable code.
193///
194/// Missing host facts are reported in `incomplete` when metadata is unavailable.
195/// Every known leaf in a stored array, tuple, or callable shape requires explicit
196/// Adam membership. Missing membership is definite only with complete metadata;
197/// it does not suppress independent type or capability errors.
198/// Match-key value comparisons and whole-graph solvability remain runtime checks.
199/// Recovered syntax errors remain the parser's responsibility.
200///
201/// - Complexity: The symbolic module check's expression, specialization and graph costs.
202///
203/// # Examples
204/// See the [module example](self).
205pub fn check_sheet_with_environment(
206    sheet: &ast::Sheet,
207    environment: &AdamCheckingEnvironment,
208    availability: MetadataAvailability,
209) -> CheckingReport<()> {
210    crate::module::checking::check_single(sheet, environment, availability)
211}