Skip to main content

adam_lang/
module.rs

1//! Compiles supplied modules into immutable factories without filesystem access or execution.
2//!
3//! ```
4//! use adam_lang::{ModuleCompiler, ModulePath, ModuleSet, TypeRegistry};
5//! let path: ModulePath = "constraints".parse()?;
6//! let mut modules = ModuleSet::new();
7//! modules.insert_source(path.clone(), "constraints.adm2", "sheet empty() {}")?;
8//! modules.check_resolution().map_err(|errors| errors.into_iter().next().unwrap())?;
9//! let compiled = ModuleCompiler::new(TypeRegistry::new(), cel_parser::OpLookup::new())
10//!     .compile(modules).map_err(|mut errors| errors.remove(0))?;
11//! assert!(compiled.template(&path, "empty").is_some());
12//! # Ok::<(), adam_lang::ModuleDiagnostic>(())
13//! ```
14
15mod analysis;
16pub(crate) mod checking;
17pub(crate) mod compile;
18mod resolve;
19
20pub use checking::{
21    ModuleCheckingReport, check_module, check_module_with_environment,
22    check_recovered_source_with_environment,
23};
24pub use compile::{CompiledModules, ModuleCompiler, PreparedRoot, RootCell};
25
26use std::{collections::HashMap, fmt, str::FromStr};
27
28use cel_parser::SourceSpan;
29
30use crate::{
31    AdamAstParser, ModuleDiagnostic, SourceId, SourceLabel, SourceLocation, SourceMap,
32    TypedTemplate, ast,
33};
34
35/// Identifies a supplied module by nonempty, `::`-separated identifiers.
36///
37/// Whitespace, literal tokens, raw identifiers, `_` alone, and `sheet`, `use`, `as`
38/// are not path segments.
39/// See the [module example](self).
40#[derive(Clone, Debug, Eq, Hash, PartialEq)]
41pub struct ModulePath(Vec<String>);
42
43impl FromStr for ModulePath {
44    /// Reports an invalid externally supplied module path.
45    type Err = ModuleDiagnostic;
46
47    /// Validates and retains every identifier segment.
48    ///
49    /// # Errors
50    /// Rejects empty paths or invalid segments.
51    /// - Complexity: O(n) path bytes.
52    fn from_str(path: &str) -> Result<Self, Self::Err> {
53        let segments: Vec<_> = path.split("::").collect();
54        if !segments.iter().all(|segment| valid_identifier(segment)) {
55            return Err(crate::composition::diagnostic("invalid module path"));
56        }
57        Ok(Self(segments.into_iter().map(str::to_owned).collect()))
58    }
59}
60
61#[cfg(test)]
62mod identifier_tests {
63    use super::*;
64
65    /// Module paths require lexical identifiers, not Boolean literal tokens.
66    #[test]
67    fn module_paths_reject_literal_tokens() {
68        for path in ["true", "false", "a::true", "false::b"] {
69            assert!(path.parse::<ModulePath>().is_err(), "{path}");
70        }
71        for path in ["if", "else", "Δ::constraints"] {
72            assert_eq!(path.parse::<ModulePath>().unwrap().to_string(), path);
73        }
74    }
75}
76
77impl fmt::Display for ModulePath {
78    /// Writes the validated path with `::` separators.
79    ///
80    /// - Complexity: O(n) path bytes.
81    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
82        for (index, segment) in self.0.iter().enumerate() {
83            if index != 0 {
84                formatter.write_str("::")?;
85            }
86            formatter.write_str(segment)?;
87        }
88        Ok(())
89    }
90}
91
92/// Checks one complete nonreserved module identifier without surrounding whitespace.
93///
94/// - Complexity: O(n) identifier bytes.
95pub(crate) fn valid_identifier(name: &str) -> bool {
96    if matches!(name, "" | "_" | "sheet" | "use" | "as") || name.starts_with("r#") {
97        return false;
98    }
99    let Ok(stream) = name.parse::<proc_macro2::TokenStream>() else {
100        return false;
101    };
102    let mut tokens = cel_parser::lex_lexer::LexLexer::new(stream.into_iter());
103    matches!(tokens.next(), Some(cel_parser::lex_lexer::Token::Identifier(ident)) if ident == name)
104        && tokens.next().is_none()
105}
106
107/// Owns parsed and native declarations under explicit module paths.
108///
109/// A module has at most one source file and may also contain native definitions.
110/// Insertion parses syntax only. [`Self::check_resolution`] checks names and cycles,
111/// not types, actual cells, executable bodies or graph solvability.
112/// [`check_module`] adds borrowed, nonexecuting signature and body analysis.
113/// See the [module example](self).
114#[derive(Default)]
115pub struct ModuleSet {
116    entries: Vec<ModuleEntry>,
117    indices: HashMap<ModulePath, usize>,
118    sources: SourceMap,
119    native_binding: Option<cel_parser::checking::HostTypeBinding>,
120}
121
122/// Owns a module's declared exports and explicit imports in authored order.
123struct ModuleEntry {
124    path: ModulePath,
125    source: Option<SourceId>,
126    imports: Vec<ast::UseDecl>,
127    definitions: Vec<Definition>,
128}
129
130/// Owns one source or native definition without expanding inclusion edges.
131struct Definition {
132    name: String,
133    body: DefinitionBody,
134}
135
136/// Distinguishes retained authored bodies from already checked native recipes.
137enum DefinitionBody {
138    Parsed {
139        sheet: Box<ast::Sheet>,
140        label: SourceLabel,
141    },
142    Native(TypedTemplate),
143}
144
145impl Definition {
146    /// Borrows the parsed declaration's or programmatic template's genuine label.
147    fn label(&self) -> &SourceLabel {
148        match &self.body {
149            DefinitionBody::Parsed { label, .. } => label,
150            DefinitionBody::Native(template) => template.definition_label(),
151        }
152    }
153}
154
155impl ModuleSet {
156    /// Selects the explicit catalog binding used for native-template type signatures.
157    ///
158    /// The binding belongs to the Adam checking environment's inner CEL catalog.
159    /// A binding from another catalog produces incomplete checking, never guessed identity.
160    /// - Complexity: O(n) destruction of any replaced binding's n nominal entries.
161    ///
162    /// # Examples
163    /// ```
164    /// let mut modules = adam_lang::ModuleSet::new();
165    /// let environment = adam_lang::checking_environment(
166    ///     &adam_lang::TypeRegistry::new(), &cel_parser::OpLookup::new()).unwrap();
167    /// modules.set_native_binding(cel_parser::checking::HostTypeBinding::new(environment.cel()));
168    /// ```
169    pub fn set_native_binding(&mut self, binding: cel_parser::checking::HostTypeBinding) {
170        self.native_binding = Some(binding);
171    }
172
173    /// Creates an empty supplied module collection.
174    ///
175    /// # Examples
176    /// See the [module example](self).
177    pub fn new() -> Self {
178        Self::default()
179    }
180
181    /// Parses one source file and adds its declarations without executing expressions.
182    ///
183    /// A rejected insertion leaves existing declarations unchanged.
184    /// # Errors
185    /// Rejects malformed syntax or a second source file for the same module.
186    /// Diagnostics own their source even after this collection is dropped.
187    /// The collection does not retain rejected malformed source revisions.
188    /// - Complexity: O(n) source and AST size, excluding embedded CEL parsing.
189    ///
190    /// # Examples
191    /// See the [module example](self).
192    pub fn insert_source(
193        &mut self,
194        path: ModulePath,
195        file_name: &str,
196        source: &str,
197    ) -> Result<(), ModuleDiagnostic> {
198        if let Some(index) = self.indices.get(&path)
199            && self.entries[*index].source.is_some()
200        {
201            return Err(crate::composition::diagnostic(
202                "module already has a source file",
203            ));
204        }
205        let parsed = AdamAstParser::new()
206            .parse_module_str(source)
207            .map_err(|error| rejected_source_error(file_name, source, &error))?;
208        if let Some(error) = parsed.errors.first() {
209            return Err(rejected_source_error(file_name, source, error));
210        }
211        let owner = self.sources.insert(file_name, source);
212        let entry = self.entry(path);
213        entry.source = Some(owner.clone());
214        for item in parsed.items {
215            match item {
216                ast::ModuleItem::Use(import) => entry.imports.push(import),
217                ast::ModuleItem::Sheet(sheet) => entry.definitions.push(Definition {
218                    name: sheet.name.clone(),
219                    body: DefinitionBody::Parsed {
220                        label: label(&owner, sheet.name_span, &sheet.name),
221                        sheet: Box::new(sheet),
222                    },
223                }),
224                ast::ModuleItem::Error(_) => unreachable!("recovered errors rejected above"),
225            }
226        }
227        Ok(())
228    }
229
230    /// Adds an immutable source-free definition to a supplied module.
231    ///
232    /// Native and parsed definitions share the module's export namespace.
233    /// # Errors
234    /// Rejects invalid identifiers or an already declared local definition.
235    /// Duplicate errors retain the incoming and earlier declaration labels.
236    /// - Complexity: O(d + b) existing local definitions and compared/copied name/label bytes.
237    ///
238    /// # Examples
239    /// ```
240    /// let mut modules = adam_lang::ModuleSet::new();
241    /// let native = adam_lang::CompositionBuilder::new(adam_lang::TypeRegistry::new()).finish()?;
242    /// modules.insert_template("native".parse()?, "empty", native)?;
243    /// # Ok::<(), adam_lang::ModuleDiagnostic>(())
244    /// ```
245    pub fn insert_template(
246        &mut self,
247        path: ModulePath,
248        name: &str,
249        template: TypedTemplate,
250    ) -> Result<(), ModuleDiagnostic> {
251        if !valid_identifier(name) {
252            return Err(crate::composition::diagnostic("invalid definition name"));
253        }
254        let entry = self.entry(path);
255        if let Some(existing) = entry
256            .definitions
257            .iter()
258            .find(|definition| definition.name == name)
259        {
260            return Err(ModuleDiagnostic {
261                cause: None,
262                message: "duplicate local definition".into(),
263                labels: vec![
264                    template.definition_label().clone(),
265                    existing.label().clone(),
266                ],
267            });
268        }
269        entry.definitions.push(Definition {
270            name: name.into(),
271            body: DefinitionBody::Native(template),
272        });
273        Ok(())
274    }
275
276    /// Checks definition names, explicit imports and actual component-use cycles.
277    ///
278    /// Resolves imported bodies in their defining module. Aliases do not re-export.
279    /// Checks every authored use, including unused definitions and conditional
280    /// branches. Import-only cycles are valid. No expression executes.
281    /// This phase does not check types, actual-cell bindings, executable bodies,
282    /// branch eligibility or whole-graph validity.
283    ///
284    /// # Errors
285    /// Reports duplicate names, missing modules/exports, uses of roots and actual-use
286    /// cycles. Returned labels retain sources independently of this collection.
287    /// - Complexity: O(n + p) time for file/body/branch declarations n and
288    ///   qualified-name bytes p; O(d + i + u + p) additional space for definitions,
289    ///   imports, uses and names.
290    ///
291    /// # Examples
292    /// See the [module example](self).
293    pub fn check_resolution(&self) -> Result<(), Vec<ModuleDiagnostic>> {
294        resolve::resolve(self).map(|_| ())
295    }
296
297    /// Returns or creates the unique module entry for a validated path.
298    ///
299    /// - Complexity: Amortized O(p) path bytes.
300    fn entry(&mut self, path: ModulePath) -> &mut ModuleEntry {
301        let index = *self.indices.entry(path.clone()).or_insert_with(|| {
302            let index = self.entries.len();
303            self.entries.push(ModuleEntry {
304                path,
305                source: None,
306                imports: Vec::new(),
307                definitions: Vec::new(),
308            });
309            index
310        });
311        &mut self.entries[index]
312    }
313}
314
315/// Labels an authored span while retaining its source owner.
316///
317/// - Complexity: O(n) label bytes.
318fn label(source: &SourceId, span: ast::ExprSpan, text: &str) -> SourceLabel {
319    SourceLabel {
320        location: Some(SourceLocation {
321            source: source.clone(),
322            span: SourceSpan::from_proc_macro2_range(span.start, span.end),
323        }),
324        label: text.into(),
325    }
326}
327
328/// Produces an owning diagnostic for a parser or CEL compiler span.
329///
330/// - Complexity: O(n) message bytes.
331fn source_error(
332    source: &SourceId,
333    span: SourceSpan,
334    message: impl fmt::Display,
335) -> ModuleDiagnostic {
336    let message = message.to_string();
337    ModuleDiagnostic {
338        cause: None,
339        labels: vec![SourceLabel {
340            location: Some(SourceLocation {
341                source: source.clone(),
342                span,
343            }),
344            label: message.clone(),
345        }],
346        message,
347    }
348}
349
350/// Retains the parser's primary range and every secondary source label.
351///
352/// - Complexity: O(n) message and label bytes.
353fn parse_error(source: &SourceId, error: &crate::ParseError) -> ModuleDiagnostic {
354    let span = SourceSpan::from_proc_macro2_range(
355        error.span(),
356        error.end_span().unwrap_or_else(|| error.span()),
357    );
358    let mut diagnostic = source_error(source, span, error.message());
359    diagnostic
360        .labels
361        .extend(error.secondary().iter().map(|secondary| SourceLabel {
362            location: Some(SourceLocation {
363                source: source.clone(),
364                span: secondary.span,
365            }),
366            label: secondary.label.clone(),
367        }));
368    diagnostic
369}
370
371/// Owns rejected text exclusively through the returned diagnostic's genuine labels.
372///
373/// - Complexity: O(f + t + l) file name, source text and diagnostic label bytes.
374fn rejected_source_error(
375    file_name: &str,
376    text: &str,
377    error: &crate::ParseError,
378) -> ModuleDiagnostic {
379    let owner = SourceMap::new().insert(file_name, text);
380    parse_error(&owner, error)
381}
382
383#[cfg(test)]
384mod tests {
385    use super::*;
386
387    /// Retains only accepted source revisions while each failure owns its diagnostic source.
388    #[test]
389    fn rejected_source_revisions_do_not_enter_the_source_collection() {
390        let mut modules = ModuleSet::new();
391        let template = crate::CompositionBuilder::new(crate::TypeRegistry::new())
392            .finish()
393            .unwrap();
394        modules
395            .insert_template("app".parse().unwrap(), "helper", template)
396            .unwrap();
397        let mut retained_error = None;
398        for revision in 0..8usize {
399            let source = if revision % 2 == 0 {
400                format!("sheet broken( // revision {revision}")
401            } else {
402                format!("sheet broken {{ cell x: ; }} // revision {revision}")
403            };
404            let error = modules
405                .insert_source(
406                    "app".parse().unwrap(),
407                    &format!("rejected-{revision}.adm2"),
408                    &source,
409                )
410                .unwrap_err();
411            assert_eq!(
412                modules.sources.sources().len(),
413                0,
414                "failed revision {revision} retained"
415            );
416            retained_error = Some(error);
417        }
418        modules
419            .insert_source(
420                "app".parse().unwrap(),
421                "accepted.adm2",
422                "sheet wrapper() { relationship helper(); }",
423            )
424            .unwrap();
425        assert_eq!(modules.sources.sources().len(), 1);
426        assert_eq!(modules.sources.sources()[0].file_name(), "accepted.adm2");
427        modules.check_resolution().unwrap();
428        drop(modules);
429
430        let error = retained_error.unwrap();
431        let location = error.labels[0].location.as_ref().unwrap();
432        assert_eq!(location.source.file_name(), "rejected-7.adm2");
433        assert_eq!(
434            location.source.text(),
435            "sheet broken { cell x: ; } // revision 7"
436        );
437        assert_eq!(
438            &location.source.text()[location.span.to_byte_range(location.source.text())],
439            ";"
440        );
441    }
442}