Skip to main content

adam_lang/module/
checking.rs

1//! Checks symbolic Adam definitions using only CEL type facts and dependency edges.
2//!
3//! The public entry points accept an immutable catalog; no executable expression
4//! compiler, live sheet, or application callback participates in this pass.
5
6use super::*;
7use crate::TypeRegistry;
8use crate::checking::{AdamCheckingEnvironment, checking_environment_with_binding};
9use cel_parser::{
10    Expr, ExprSpan, OpLookup, ParseError, Ty,
11    checking::{CheckingReport, MetadataAvailability, check_expr_with_environment},
12};
13use std::{
14    borrow::Cow,
15    cell::RefCell,
16    collections::{HashMap, HashSet},
17};
18
19mod structure;
20
21/// Retains definite failures separately from checks requiring unavailable metadata.
22///
23/// # Examples
24/// See [`check_module_with_environment`].
25#[derive(Default)]
26pub struct ModuleCheckingReport {
27    /// Definite source and structural errors.
28    pub diagnostics: Vec<ModuleDiagnostic>,
29    /// Checks blocked by missing metadata or failed prerequisites.
30    pub incomplete: Vec<ModuleDiagnostic>,
31}
32
33/// Projects runtime registrations and checks all supplied definitions without callbacks.
34///
35/// Projection failures are explicit diagnostics. Match-key comparisons and
36/// whole-graph solvability remain runtime checks.
37///
38/// - Complexity: Environment projection plus [`check_module_with_environment`].
39///
40/// # Examples
41/// ```
42/// let mut modules = adam_lang::ModuleSet::new();
43/// let path = "app".parse().unwrap();
44/// modules.insert_source(path, "app.adm2", "sheet app {}").unwrap();
45/// assert!(adam_lang::check_module(&"app".parse().unwrap(), &modules,
46///     &adam_lang::TypeRegistry::new(), &cel_parser::OpLookup::new()).is_empty());
47/// ```
48pub fn check_module(
49    module: &ModulePath,
50    modules: &ModuleSet,
51    types: &TypeRegistry,
52    lookup: &OpLookup,
53) -> Vec<ModuleDiagnostic> {
54    match checking_environment_with_binding(types, lookup) {
55        Ok((environment, binding)) => {
56            let report = check_bound_module(
57                module,
58                modules,
59                &environment,
60                MetadataAvailability::Complete,
61                Some(&binding),
62            );
63            report
64                .diagnostics
65                .into_iter()
66                .chain(report.incomplete)
67                .collect()
68        }
69        Err(error) => {
70            let mut errors = vec![crate::composition::diagnostic(error)];
71            if let Ok((environment, binding)) =
72                checking_environment_with_binding(types, &OpLookup::new())
73            {
74                let report = check_bound_module(
75                    module,
76                    modules,
77                    &environment,
78                    MetadataAvailability::Unavailable,
79                    Some(&binding),
80                );
81                errors.extend(report.diagnostics);
82                errors.extend(report.incomplete);
83            }
84            errors
85        }
86    }
87}
88
89/// Checks every registered definition and composed root with a data-only environment.
90///
91/// Definitions use the resolver's dependency postorder and ordinary source-mask
92/// policy. Every branch contributes structure, including inactive/default branches.
93/// Match-key value comparisons and whole-graph solvability remain runtime checks.
94/// Labels retain genuine source and invocation ownership independently of `modules`.
95///
96/// Equivalent component uses share structural facts. Diagnostics retain deduplicated
97/// authored labels and a deterministic representative invocation chain, not one
98/// copy per expanded occurrence or an expanded graph's shortest explanation.
99///
100/// - Complexity: Expression checking plus expected O(B(V + E) + B² + N + A)
101///   time per distinct reachable definition/formal-source specialization, where B
102///   counts formals plus one write entry, V and E count compact local vertices and
103///   edges (including direct child summaries), N body nodes and authored method/guard
104///   endpoints, and A direct argument endpoints. Retains O(BV + B² + E + N + A)
105///   storage per specialization plus diagnostic output. Materializing each diagnostic
106///   visits its shared witnesses once. Distinct source masks can be exponentially
107///   numerous; repeated equivalent uses do not expand occurrences. Construction
108///   and witness traversal are iterative.
109///
110/// # Examples
111/// ```
112/// use adam_lang::*;
113/// use cel_parser::checking::MetadataAvailability;
114/// let mut modules = ModuleSet::new();
115/// let path = "app".parse().unwrap();
116/// modules.insert_source(path, "app.adm2", "sheet app { cell x: i32; }").unwrap();
117/// let environment = checking_environment(&TypeRegistry::new(), &cel_parser::OpLookup::new()).unwrap();
118/// let report = check_module_with_environment(&"app".parse().unwrap(), &modules,
119///     &environment, MetadataAvailability::Complete);
120/// assert!(report.diagnostics.is_empty() && report.incomplete.is_empty());
121/// ```
122pub fn check_module_with_environment(
123    module: &ModulePath,
124    modules: &ModuleSet,
125    environment: &AdamCheckingEnvironment,
126    availability: MetadataAvailability,
127) -> ModuleCheckingReport {
128    check_bound_module(
129        module,
130        modules,
131        environment,
132        availability,
133        modules.native_binding.as_ref(),
134    )
135}
136
137/// Checks recovered source bodies without resolving or certifying component composition.
138///
139/// Retains every recovered syntax error and independently decidable body error.
140/// Imports and component uses remain unresolved; the report always marks composition
141/// incomplete. Every label retains the supplied immutable source owner. No runtime
142/// lowering, value construction, or host callback participates in checking.
143///
144/// - Complexity: Module parsing plus expression checking and compact local graph
145///   validation as specified by [`check_module_with_environment`], plus retained
146///   source diagnostics; no composed dependency expansion.
147///
148/// # Examples
149/// ```
150/// use adam_lang::{SourceMap, check_recovered_source_with_environment};
151/// use cel_parser::checking::MetadataAvailability;
152/// let source = SourceMap::new().insert("app.adm2",
153///     "sheet app { cell x: i32 = true; cell y malformed; }");
154/// let environment = adam_lang::checking_environment(
155///     &adam_lang::TypeRegistry::new(), &cel_parser::OpLookup::new()).unwrap();
156/// let report = check_recovered_source_with_environment(
157///     &source, &environment, MetadataAvailability::Complete);
158/// assert_eq!(report.diagnostics.len(), 2);
159/// assert!(!report.incomplete.is_empty());
160/// ```
161pub fn check_recovered_source_with_environment(
162    source: &SourceId,
163    environment: &AdamCheckingEnvironment,
164    availability: MetadataAvailability,
165) -> ModuleCheckingReport {
166    let mut report = ModuleCheckingReport {
167        diagnostics: Vec::new(),
168        incomplete: vec![source_error(
169            source,
170            SourceSpan::new(1, 0, 1, 0),
171            "incomplete checking: source installation failed; component resolution and composed dependency checks are unavailable",
172        )],
173    };
174    match AdamAstParser::new().parse_module_str(source.text()) {
175        Ok(module) => {
176            report
177                .diagnostics
178                .extend(module.errors.iter().map(|error| parse_error(source, error)));
179            for item in &module.items {
180                if let ast::ModuleItem::Sheet(sheet) = item {
181                    let plan = check_unresolved_sheet(
182                        sheet,
183                        source,
184                        environment,
185                        availability,
186                        &mut report,
187                    );
188                    validate_graph(0, &[plan], &mut report);
189                }
190            }
191        }
192        Err(error) => report.diagnostics.push(parse_error(source, &error)),
193    }
194    report
195}
196
197/// Checks one definition's independent bodies without guessing component bindings.
198///
199/// - Complexity: Annotation and expression checking plus symbolic local body storage.
200fn check_unresolved_sheet<'a>(
201    sheet: &'a ast::Sheet,
202    owner: &SourceId,
203    environment: &AdamCheckingEnvironment,
204    availability: MetadataAvailability,
205    report: &mut ModuleCheckingReport,
206) -> Plan<'a> {
207    let mut plan = Plan::new(label(owner, sheet.name_span, &sheet.name));
208    let mut spans = Vec::new();
209    let mut checker = Checker {
210        environment,
211        availability,
212        owner,
213        report,
214        plan: &mut plan,
215        spans: &mut spans,
216        resolution_failed: true,
217    };
218    for formal in sheet.parameters.iter().flatten() {
219        let ty = checker.annotation(&formal.type_name);
220        checker.declare(&formal.name, ty, Kind::Parameter, formal.name_span);
221    }
222    for item in &sheet.items {
223        checker.item(item, &[], &[], &mut 0);
224    }
225    plan
226}
227
228/// Checks parsed and explicitly bound native definitions with one symbolic backend.
229///
230/// - Complexity: As [`check_module_with_environment`].
231fn check_bound_module(
232    module: &ModulePath,
233    modules: &ModuleSet,
234    environment: &AdamCheckingEnvironment,
235    availability: MetadataAvailability,
236    binding: Option<&cel_parser::checking::HostTypeBinding>,
237) -> ModuleCheckingReport {
238    if !modules.indices.contains_key(module) {
239        return ModuleCheckingReport {
240            diagnostics: vec![crate::composition::diagnostic(format!(
241                "unknown requested module `{module}`"
242            ))],
243            incomplete: Vec::new(),
244        };
245    }
246    let resolved = match resolve::resolve(modules) {
247        Ok(resolved) => resolved,
248        Err(diagnostics) => {
249            let mut report = ModuleCheckingReport {
250                diagnostics,
251                incomplete: vec![crate::composition::diagnostic(
252                    "incomplete checking: component resolution failed; composed dependency checks are unavailable",
253                )],
254            };
255            for entry in &modules.entries {
256                for definition in &entry.definitions {
257                    if let DefinitionBody::Parsed { sheet, .. } = &definition.body {
258                        let owner = entry.source.as_ref().expect("parsed source");
259                        let plan = check_unresolved_sheet(
260                            sheet,
261                            owner,
262                            environment,
263                            availability,
264                            &mut report,
265                        );
266                        validate_graph(0, &[plan], &mut report);
267                    } else if let DefinitionBody::Native(template) = &definition.body {
268                        let mut plans = vec![Plan::new(definition.label().clone())];
269                        append_native_plans(
270                            0,
271                            template,
272                            &mut plans,
273                            environment,
274                            binding,
275                            availability,
276                            &mut report,
277                        );
278                        validate_plans(&mut plans, &mut report);
279                    }
280                }
281            }
282            return report;
283        }
284    };
285    let mut report = ModuleCheckingReport::default();
286    let mut spans = Vec::new();
287    let mut plans: Vec<_> = resolved
288        .definitions
289        .iter()
290        .map(|&(module, local)| {
291            let definition = &modules.entries[module].definitions[local];
292            let mut plan = Plan::new(definition.label().clone());
293            match &definition.body {
294                DefinitionBody::Parsed { sheet, .. } => {
295                    let owner = modules.entries[module]
296                        .source
297                        .as_ref()
298                        .expect("parsed source");
299                    let mut checker = Checker {
300                        environment,
301                        availability,
302                        owner,
303                        report: &mut report,
304                        plan: &mut plan,
305                        spans: &mut spans,
306                        resolution_failed: false,
307                    };
308                    for formal in sheet.parameters.iter().flatten() {
309                        let ty = checker.annotation(&formal.type_name);
310                        checker.declare(&formal.name, ty, Kind::Parameter, formal.name_span);
311                    }
312                    plan.formals = plan.cells.len();
313                }
314                DefinitionBody::Native(_) => {}
315            }
316            plan
317        })
318        .collect();
319    for (id, &(module, local)) in resolved.definitions.iter().enumerate() {
320        if let DefinitionBody::Native(template) = &modules.entries[module].definitions[local].body {
321            append_native_plans(
322                id,
323                template,
324                &mut plans,
325                environment,
326                binding,
327                availability,
328                &mut report,
329            );
330        }
331    }
332    for &id in &resolved.order {
333        let (module, local) = resolved.definitions[id];
334        if let DefinitionBody::Parsed { sheet, .. } =
335            &modules.entries[module].definitions[local].body
336        {
337            let owner = modules.entries[module]
338                .source
339                .as_ref()
340                .expect("parsed source");
341            let site = plans[id].label.clone();
342            let mut plan = std::mem::replace(&mut plans[id], Plan::new(site));
343            let mut checker = Checker {
344                environment,
345                availability,
346                owner,
347                report: &mut report,
348                plan: &mut plan,
349                spans: &mut spans,
350                resolution_failed: false,
351            };
352            let mut edge = 0;
353            for item in &sheet.items {
354                checker.item(item, &plans, &resolved.edges[id], &mut edge);
355            }
356            plans[id] = plan;
357        }
358    }
359    validate_plans(&mut plans, &mut report);
360    report
361}
362
363/// Checks every definition through one cache of source-specialized structural summaries.
364///
365/// - Complexity: As [`check_module_with_environment`].
366fn validate_plans(plans: &mut [Plan<'_>], report: &mut ModuleCheckingReport) {
367    let order = plan_order(plans);
368    structure::validate(plans, order.into_iter().rev(), report);
369}
370
371/// Checks a standalone AST with the same symbolic body and graph checker.
372///
373/// - Complexity: Expression checking plus compact dependency projection as in
374///   [`check_module_with_environment`].
375pub(crate) fn check_single(
376    sheet: &ast::Sheet,
377    environment: &AdamCheckingEnvironment,
378    availability: MetadataAvailability,
379) -> CheckingReport<()> {
380    let owner = SourceMap::new().insert("<sheet>", "");
381    let mut report = ModuleCheckingReport::default();
382    let mut plan = Plan::new(label(&owner, sheet.name_span, "sheet"));
383    let mut spans = Vec::new();
384    let mut checker = Checker {
385        environment,
386        availability,
387        owner: &owner,
388        report: &mut report,
389        plan: &mut plan,
390        spans: &mut spans,
391        resolution_failed: false,
392    };
393    if sheet.parameters.is_some() {
394        checker.error(
395            "parameterized definitions require module lowering",
396            sheet.name_span,
397        );
398    }
399    for item in &sheet.items {
400        checker.item(item, &[], &[], &mut 0);
401    }
402    validate_graph(0, &[plan], &mut report);
403    CheckingReport {
404        value: (),
405        diagnostics: report
406            .diagnostics
407            .into_iter()
408            .map(|error| single_error(error, &spans))
409            .collect(),
410        incomplete: report
411            .incomplete
412            .into_iter()
413            .map(|error| single_error(error, &spans))
414            .collect(),
415    }
416}
417
418/// Converts symbolic labels to a standalone expression diagnostic without losing ranges.
419///
420/// - Complexity: O(s + l + b) retained spans s, labels l and message bytes b.
421fn single_error(error: ModuleDiagnostic, spans: &[(SourceSpan, ExprSpan)]) -> ParseError {
422    let mut sites = error.labels.iter().filter_map(|label| {
423        label
424            .location
425            .as_ref()
426            .map(|location| (location, &label.label))
427    });
428    let Some((primary, _)) = sites.next() else {
429        return ParseError::new(error.message, proc_macro2::Span::call_site());
430    };
431    let span = spans
432        .iter()
433        .find(|(source, _)| *source == primary.span)
434        .map(|(_, span)| *span)
435        .unwrap_or(ExprSpan {
436            start: proc_macro2::Span::call_site(),
437            end: proc_macro2::Span::call_site(),
438        });
439    ParseError::new_range(error.message, span.start, span.end).with_secondary(
440        sites
441            .map(|(site, label)| cel_parser::SpanLabel {
442                span: site.span,
443                label: label.clone(),
444            })
445            .collect(),
446    )
447}
448
449/// Distinguishes fixed sources, writable cells, output cells, and bound parameters.
450#[derive(Clone, Copy, PartialEq, Eq)]
451enum Kind {
452    Parameter,
453    Cell,
454    Source,
455    Out,
456}
457
458/// Retains a symbolic cell's complete type and declaration provenance.
459struct Cell<'a> {
460    name: Cow<'a, str>,
461    ty: Ty,
462    kind: Kind,
463    label: SourceLabel,
464}
465
466/// Retains authored edges and source-specialization boundaries without values.
467enum Body {
468    Relationship {
469        methods: Vec<Method>,
470        label: SourceLabel,
471    },
472    Filter {
473        cell: usize,
474        inputs: Vec<usize>,
475        label: SourceLabel,
476    },
477    Conditional {
478        inputs: Vec<usize>,
479        body: Vec<Body>,
480        label: SourceLabel,
481    },
482    Use {
483        target: usize,
484        bindings: Vec<usize>,
485        label: SourceLabel,
486    },
487}
488
489/// Retains one authored method's reads, writes, and owning range.
490struct Method {
491    inputs: Vec<usize>,
492    outputs: Vec<usize>,
493    label: SourceLabel,
494}
495
496/// Owns one checked definition's local symbolic namespace.
497struct Plan<'a> {
498    cells: Vec<Cell<'a>>,
499    names: HashMap<Cow<'a, str>, usize>,
500    formals: usize,
501    body: Vec<Body>,
502    label: SourceLabel,
503    ineligible: Option<SourceLabel>,
504    blocked: bool,
505}
506
507impl Plan<'_> {
508    /// Creates an empty definition namespace at its owning site.
509    fn new(label: SourceLabel) -> Self {
510        Self {
511            cells: Vec::new(),
512            names: HashMap::new(),
513            formals: 0,
514            body: Vec::new(),
515            label,
516            ineligible: None,
517            blocked: false,
518        }
519    }
520}
521
522/// Borrows the catalog and accumulates independent body diagnostics and symbolic edges.
523struct Checker<'a, 'b> {
524    environment: &'b AdamCheckingEnvironment,
525    availability: MetadataAvailability,
526    owner: &'b SourceId,
527    report: &'b mut ModuleCheckingReport,
528    plan: &'b mut Plan<'a>,
529    spans: &'b mut Vec<(SourceSpan, ExprSpan)>,
530    resolution_failed: bool,
531}
532
533impl<'a> Checker<'a, '_> {
534    /// Records a definite authored error while leaving independent bodies checkable.
535    ///
536    /// - Complexity: O(b) message bytes.
537    fn error(&mut self, message: impl Into<String>, span: ExprSpan) {
538        self.spans.push((
539            SourceSpan::from_proc_macro2_range(span.start, span.end),
540            span,
541        ));
542        self.report.diagnostics.push(ModuleDiagnostic {
543            message: message.into(),
544            labels: vec![label(self.owner, span, "declaration")],
545            cause: None,
546        });
547    }
548
549    /// Resolves an annotation through the shared CEL checker and availability policy.
550    ///
551    /// - Complexity: CEL annotation resolution and error projection.
552    fn annotation(&mut self, annotation: &ast::TypeExpr) -> Ty {
553        let result = self
554            .environment
555            .cel()
556            .check_annotation(annotation, self.availability);
557        self.extend(result.diagnostics, result.incomplete);
558        result.value
559    }
560
561    /// Projects expression findings to genuine source ownership.
562    ///
563    /// - Complexity: O(e + b) errors and label/message bytes.
564    fn extend(&mut self, errors: Vec<ParseError>, incomplete: Vec<ParseError>) {
565        for error in errors.iter().chain(&incomplete) {
566            let span = ExprSpan {
567                start: error.span(),
568                end: error.end_span().unwrap_or(error.span()),
569            };
570            self.spans.push((
571                SourceSpan::from_proc_macro2_range(span.start, span.end),
572                span,
573            ));
574        }
575        if !incomplete.is_empty() {
576            self.plan.blocked = true;
577        }
578        self.report
579            .diagnostics
580            .extend(errors.iter().map(|error| parse_error(self.owner, error)));
581        self.report.incomplete.extend(
582            incomplete
583                .iter()
584                .map(|error| parse_error(self.owner, error)),
585        );
586    }
587
588    /// Checks an expression and collects only references resolved by CEL's lexical rules.
589    ///
590    /// - Complexity: CEL checking plus O(r²) first-use deduplication for r references.
591    fn expression(
592        &mut self,
593        syntax: &Expr,
594        capture: bool,
595        candidate: Option<&Ty>,
596    ) -> (Ty, Vec<usize>, bool) {
597        let inputs = RefCell::new(Vec::new());
598        let used = std::cell::Cell::new(false);
599        let dependent = std::cell::Cell::new(false);
600        let report = check_expr_with_environment(
601            syntax,
602            &|name| {
603                if name == "_"
604                    && let Some(ty) = candidate
605                {
606                    used.set(true);
607                    return Some(ty.clone());
608                }
609                self.plan.names.get(name).map(|&id| {
610                    if capture {
611                        let mut inputs = inputs.borrow_mut();
612                        if !inputs.contains(&id) {
613                            inputs.push(id);
614                        }
615                    } else {
616                        dependent.set(true);
617                    }
618                    self.plan.cells[id].ty.clone()
619                })
620            },
621            self.environment.cel(),
622            self.availability,
623        );
624        self.extend(report.diagnostics, report.incomplete);
625        if dependent.get() {
626            self.error("cell-dependent initializers are unsupported", syntax.span());
627        }
628        (report.value, inputs.into_inner(), used.get())
629    }
630
631    /// Registers a declaration unless its local name is already bound.
632    ///
633    /// - Complexity: Expected O(n + t log(m + 1) + b) time and O(t + b) space for
634    ///   name bytes n, type nodes t, registered leaves m, and diagnostic bytes b.
635    fn declare(&mut self, name: &'a str, ty: Ty, kind: Kind, span: ExprSpan) -> Option<usize> {
636        self.spans.push((
637            SourceSpan::from_proc_macro2_range(span.start, span.end),
638            span,
639        ));
640        if self.plan.names.contains_key(name) {
641            self.error(format!("duplicate cell `{name}`"), span);
642            self.plan.blocked = true;
643            return None;
644        }
645        self.storage_membership(&ty, span);
646        self.capabilities(&ty, false, span);
647        let id = self.plan.cells.len();
648        self.plan.cells.push(Cell {
649            name: Cow::Borrowed(name),
650            ty,
651            kind,
652            label: label(self.owner, span, "cell declaration"),
653        });
654        self.plan.names.insert(Cow::Borrowed(name), id);
655        Some(id)
656    }
657
658    /// Checks canonical cell capabilities and, where required, default availability.
659    ///
660    /// - Complexity: O(t) recursive type nodes, excluding name formatting.
661    fn capabilities(&mut self, ty: &Ty, default: bool, span: ExprSpan) {
662        let failure = match ty {
663            Ty::Any => None,
664            Ty::Tuple(elements) => {
665                for element in elements {
666                    self.capabilities(element, default, span);
667                }
668                None
669            }
670            Ty::Array(_) if default => None,
671            Ty::Array(element) => {
672                self.capabilities(element, false, span);
673                None
674            }
675            Ty::Callable(..) => Some(if default {
676                "callable has no default; provide an initializer `= ...`".into()
677            } else {
678                "Adam cell equality capability unavailable for callable".into()
679            }),
680            _ => self.environment.cel().capabilities(ty).and_then(|caps| {
681                if !default
682                    && let Err(capability) = crate::cell_value::validate_cell_capabilities(
683                        caps.cloneable,
684                        caps.comparable,
685                    )
686                {
687                    Some(format!(
688                        "Adam cell {capability} capability unavailable for `{}`",
689                        ty.name()
690                    ))
691                } else if default && !caps.default_available {
692                    Some(format!(
693                        "type `{}` has no default; provide `= ...`",
694                        ty.name()
695                    ))
696                } else {
697                    None
698                }
699            }),
700        };
701        if let Some(message) = failure {
702            self.error(message, span);
703        }
704    }
705
706    /// Checks every known stored leaf without suppressing unresolved siblings.
707    ///
708    /// Unavailable membership produces incomplete findings rather than certification.
709    /// - Complexity: O(t log(n + 1) + b) time and O(d + b) space for t shape nodes,
710    ///   n registered leaves, depth d, and diagnostic bytes b.
711    fn storage_membership(&mut self, ty: &Ty, span: ExprSpan) {
712        self.environment.visit_unregistered_leaves(ty, &mut |leaf| {
713            let message = format!("unregistered Adam cell storage type `{}`", leaf.name());
714            if self.availability == MetadataAvailability::Complete {
715                self.error(message, span);
716            } else {
717                self.plan.blocked = true;
718                self.report.incomplete.push(ModuleDiagnostic {
719                    message,
720                    labels: vec![label(self.owner, span, "cell storage")],
721                    cause: None,
722                });
723            }
724        });
725    }
726
727    /// Reports incompatible known result shapes while ignoring unknown portions.
728    ///
729    /// - Complexity: O(t) compared/formatted type nodes.
730    fn expect(&mut self, actual: &Ty, expected: &Ty, span: ExprSpan, context: &str) {
731        if !actual.unifies_with(expected) {
732            let detail = match (expected, actual) {
733                (Ty::Tuple(expected), Ty::Tuple(actual)) if expected.len() != actual.len() => {
734                    format!(
735                        "tuple arity mismatch: expected {}, got {}",
736                        expected.len(),
737                        actual.len()
738                    )
739                }
740                _ => format!(
741                    "type mismatch: expected `{}`, got `{}`",
742                    expected.name(),
743                    actual.name()
744                ),
745            };
746            self.error(format!("{context}: {detail}"), span);
747        }
748    }
749
750    /// Checks independently typed result arms and tuple elements against their expected types.
751    ///
752    /// - Complexity: CEL checking of disjoint results plus compared type sizes;
753    ///   O(b · d) suppression checks for b contextual branches and d diagnostics.
754    fn expect_result(
755        &mut self,
756        syntax: &Expr,
757        actual: &Ty,
758        expected: &Ty,
759        span: ExprSpan,
760        context: &str,
761        expression_start: usize,
762    ) {
763        if !matches!(syntax, Expr::If { .. } | Expr::Tuple { .. }) {
764            self.expect(actual, expected, span, context);
765            return;
766        }
767        let before = self.report.diagnostics.len();
768        let mut pending = vec![(syntax, expected)];
769        let mut contextual_branches = Vec::new();
770        while let Some((branch, expected)) = pending.pop() {
771            if let Expr::If {
772                then_branch,
773                else_branch,
774                ..
775            } = branch
776            {
777                if let Some(otherwise) = else_branch.as_deref() {
778                    let span = branch.span();
779                    contextual_branches
780                        .push(SourceSpan::from_proc_macro2_range(span.start, span.end));
781                    pending.push((otherwise, expected));
782                }
783                pending.push((then_branch, expected));
784                continue;
785            }
786            if let (Expr::Tuple { elements, .. }, Ty::Tuple(types)) = (branch, expected)
787                && elements.len() == types.len()
788            {
789                pending.extend(elements.iter().zip(types).rev());
790                continue;
791            }
792            let result = check_expr_with_environment(
793                branch,
794                &|name| {
795                    self.plan
796                        .names
797                        .get(name)
798                        .map(|id| self.plan.cells[*id].ty.clone())
799                },
800                self.environment.cel(),
801                self.availability,
802            );
803            self.expect(&result.value, expected, branch.span(), context);
804        }
805        if self.report.diagnostics.len() != before {
806            let mut findings = self.report.diagnostics.split_off(expression_start);
807            findings.retain(|finding| {
808                finding.message != "if branch type mismatch"
809                    || !finding.labels.iter().any(|label| {
810                        label
811                            .location
812                            .as_ref()
813                            .is_some_and(|location| contextual_branches.contains(&location.span))
814                    })
815            });
816            self.report.diagnostics.extend(findings);
817        }
818    }
819
820    /// Resolves a cell reference without treating labels or function names as cells.
821    ///
822    /// - Complexity: Expected O(n) name bytes.
823    fn cell(&mut self, name: &str, span: ExprSpan) -> Option<usize> {
824        let cell = self.plan.names.get(name).copied();
825        if cell.is_none() {
826            self.error(format!("undeclared cell `{name}`"), span);
827            self.plan.blocked = true;
828        }
829        cell
830    }
831
832    /// Checks a declaration, its initializer and every policy independently.
833    ///
834    /// - Complexity: Expression checks plus canonical type/capability checks.
835    fn declaration(
836        &mut self,
837        binding: (&'a str, ExprSpan),
838        annotation: Option<&ast::TypeExpr>,
839        initializer: Option<&Expr>,
840        filter: Option<&ast::CellFilter>,
841        requirements: Option<&ast::RequireBlock>,
842        kind: Kind,
843    ) {
844        let (name, span) = binding;
845        let annotated = annotation.map(|ty| self.annotation(ty));
846        let expression_start = self.report.diagnostics.len();
847        let result = initializer.map(|expr| self.expression(expr, kind == Kind::Out, None));
848        let ty = annotated
849            .clone()
850            .or_else(|| result.as_ref().map(|(ty, ..)| ty.clone()))
851            .unwrap_or(Ty::Any);
852        if let Some((actual, ..)) = &result {
853            let expression = initializer.expect("initializer result");
854            self.expect_result(
855                expression,
856                actual,
857                &ty,
858                expression.span(),
859                &format!(
860                    "{} `{name}`: initializer",
861                    if kind == Kind::Out { "out" } else { "cell" }
862                ),
863                expression_start,
864            );
865        }
866        if initializer.is_none() || kind == Kind::Out {
867            self.capabilities(&ty, true, span);
868        }
869        let id = self.declare(name, ty.clone(), kind, span);
870        self.plan
871            .ineligible
872            .get_or_insert_with(|| label(self.owner, span, "private declaration"));
873        if kind == Kind::Out
874            && let Some(id) = id
875            && let Some((_, inputs, _)) = result
876        {
877            self.plan.body.push(Body::Relationship {
878                methods: vec![Method {
879                    inputs,
880                    outputs: vec![id],
881                    label: label(self.owner, span, "output writer"),
882                }],
883                label: label(self.owner, span, "output writer"),
884            });
885        }
886        if let Some(filter) = filter {
887            let (actual, inputs, used) = self.expression(&filter.body, true, Some(&ty));
888            if let Some(element) = self.environment.cel().range_element(&actual) {
889                self.expect(&element, &ty, filter.span, "filter range bounds");
890            } else {
891                self.expect(&actual, &ty, filter.span, "filter");
892                if !used && actual != Ty::Any {
893                    self.error("value filter must reference `_`", filter.span);
894                }
895            }
896            if let Some(id) = id {
897                self.plan.body.push(Body::Filter {
898                    cell: id,
899                    inputs,
900                    label: label(self.owner, filter.span, "filter guard"),
901                });
902            }
903        }
904        let mut names = HashSet::new();
905        for requirement in requirements
906            .into_iter()
907            .flat_map(|block| &block.requirements)
908        {
909            if let Some(name) = &requirement.name
910                && !names.insert(name)
911            {
912                self.error(
913                    format!("duplicate requirement `{name}`"),
914                    requirement.name_span.unwrap_or(requirement.span),
915                );
916            }
917            let expression_start = self.report.diagnostics.len();
918            let (actual, _, _) = self.expression(&requirement.body, true, None);
919            let context = requirement
920                .name
921                .as_ref()
922                .map(|name| format!("requirement `{name}` must be bool"));
923            self.expect_result(
924                &requirement.body,
925                &actual,
926                &Ty::Bool,
927                requirement.body.span(),
928                context.as_deref().unwrap_or("requirement must be bool"),
929                expression_start,
930            );
931        }
932    }
933
934    /// Checks all authored directions before any whole-method source specialization.
935    ///
936    /// - Complexity: CEL checking plus the shared relationship validator.
937    fn relationship(&mut self, relationship: &ast::RelationshipDecl) -> Body {
938        let mut methods = Vec::new();
939        let mut complete = true;
940        for binding in &relationship.bindings {
941            let outputs = binding
942                .outputs
943                .iter()
944                .filter_map(|(name, span)| self.cell(name, *span))
945                .collect::<Vec<_>>();
946            let expression_start = self.report.diagnostics.len();
947            let (actual, inputs, _) = self.expression(&binding.body, true, None);
948            if outputs.len() != binding.outputs.len() {
949                complete = false;
950                continue;
951            }
952            if outputs
953                .iter()
954                .any(|id| self.plan.cells[*id].kind == Kind::Out)
955            {
956                self.error("out cell already has its sole writer", binding.span);
957            }
958            let shapes: Vec<_> = outputs
959                .iter()
960                .map(|id| self.plan.cells[*id].ty.clone())
961                .collect();
962            let expected = if binding.destructure {
963                Ty::Tuple(shapes)
964            } else {
965                shapes[0].clone()
966            };
967            self.expect_result(
968                &binding.body,
969                &actual,
970                &expected,
971                binding.outputs[0].1,
972                &format!("output `{}`", binding.outputs[0].0),
973                expression_start,
974            );
975            methods.push(Method {
976                inputs,
977                outputs,
978                label: label(self.owner, binding.span, "method"),
979            });
980        }
981        if complete {
982            let edges: Vec<_> = methods
983                .iter()
984                .map(|method| (method.inputs.as_slice(), method.outputs.as_slice()))
985                .collect();
986            if let Err(message) = adam_rs::template::check_relationship_edges(&edges) {
987                let error =
988                    analysis::relationship_error(self.owner, relationship, &edges, message, |id| {
989                        let cell = &self.plan.cells[id];
990                        (&cell.name, &cell.label)
991                    });
992                self.spans
993                    .extend(relationship.bindings.iter().map(|binding| {
994                        (
995                            SourceSpan::from_proc_macro2_range(
996                                binding.span.start,
997                                binding.span.end,
998                            ),
999                            binding.span,
1000                        )
1001                    }));
1002                self.report.diagnostics.push(error);
1003                methods.clear();
1004            }
1005        }
1006        Body::Relationship {
1007            methods,
1008            label: label(self.owner, relationship.span, "relationship"),
1009        }
1010    }
1011
1012    /// Substitutes complete named actuals using the existing resolved component edge.
1013    ///
1014    /// - Complexity: O(af) actual/formal name and shape comparisons.
1015    fn invocation(
1016        &mut self,
1017        invocation: &ast::RelationshipUse,
1018        plans: &[Plan<'a>],
1019        edges: &[resolve::Edge],
1020        edge: &mut usize,
1021        conditional: bool,
1022    ) -> Option<Body> {
1023        let Some(resolved) = edges.get(*edge) else {
1024            if !self.resolution_failed {
1025                self.error("relationship uses require module lowering", invocation.span);
1026            }
1027            self.plan.blocked = true;
1028            return None;
1029        };
1030        *edge += 1;
1031        let child = &plans[resolved.target];
1032        if conditional && let Some(site) = &child.ineligible {
1033            self.report.diagnostics.push(ModuleDiagnostic {
1034                message: "conditional use requires a relationship-only component".into(),
1035                labels: vec![
1036                    label(self.owner, invocation.span, "component use"),
1037                    site.clone(),
1038                ],
1039                cause: None,
1040            });
1041        }
1042        let mut bindings = vec![None; child.formals];
1043        let mut seen = HashSet::new();
1044        let errors_before = self.report.diagnostics.len();
1045        for argument in &invocation.arguments {
1046            let Some(formal) = child.cells[..child.formals]
1047                .iter()
1048                .position(|cell| cell.name == argument.name)
1049            else {
1050                self.error(
1051                    format!("unknown parameter `{}`", argument.name),
1052                    argument.name_span,
1053                );
1054                continue;
1055            };
1056            let Some(actual) = self.cell(&argument.cell, argument.cell_span) else {
1057                continue;
1058            };
1059            if bindings[formal].replace(actual).is_some() || !seen.insert(actual) {
1060                self.error("repeated parameter or aliased actual cell", invocation.span);
1061            }
1062            if self.plan.cells[actual].kind == Kind::Out {
1063                self.error("out-cell arguments are unsupported", argument.cell_span);
1064            }
1065            let actual_ty = self.plan.cells[actual].ty.clone();
1066            if !actual_ty.unifies_with(&child.cells[formal].ty) {
1067                self.spans.push((
1068                    SourceSpan::from_proc_macro2_range(
1069                        argument.cell_span.start,
1070                        argument.cell_span.end,
1071                    ),
1072                    argument.cell_span,
1073                ));
1074                self.report.diagnostics.push(ModuleDiagnostic {
1075                    message: "component argument type mismatch".into(),
1076                    labels: vec![
1077                        label(self.owner, argument.cell_span, "actual cell"),
1078                        child.cells[formal].label.clone(),
1079                    ],
1080                    cause: None,
1081                });
1082            }
1083        }
1084        let Some(bindings) = bindings.into_iter().collect::<Option<Vec<_>>>() else {
1085            self.error("missing component parameter", invocation.span);
1086            self.plan.blocked = true;
1087            return None;
1088        };
1089        if self.report.diagnostics.len() != errors_before {
1090            self.plan.blocked = true;
1091            return None;
1092        }
1093        if let Some(site) = &child.ineligible {
1094            self.plan.ineligible.get_or_insert_with(|| site.clone());
1095        }
1096        Some(Body::Use {
1097            target: resolved.target,
1098            bindings,
1099            label: label(self.owner, invocation.span, "component use"),
1100        })
1101    }
1102
1103    /// Checks all branch keys and every branch/default relationship without evaluating keys.
1104    ///
1105    /// - Complexity: Sum of expression, relationship and invocation checking costs.
1106    fn conditional(
1107        &mut self,
1108        conditional: &ast::ConditionalDecl,
1109        plans: &[Plan<'a>],
1110        edges: &[resolve::Edge],
1111        edge: &mut usize,
1112    ) -> Body {
1113        let (ty, inputs, _) = self.expression(&conditional.match_expr, true, None);
1114        self.capabilities(&ty, false, conditional.match_expr.span());
1115        let mut body = Vec::new();
1116        for branch in &conditional.branches {
1117            match cel_parser::literal_pattern_expr(
1118                &branch.literal,
1119                branch.negated,
1120                ExprSpan {
1121                    start: branch.span.start,
1122                    end: branch.literal_span.end,
1123                },
1124            ) {
1125                Ok(expr) => {
1126                    let (key, _, _) = self.expression(&expr, false, None);
1127                    self.expect(&key, &ty, branch.literal_span, "conditional branch");
1128                }
1129                Err(error) => self.error(error.to_string(), branch.literal_span),
1130            }
1131        }
1132        for branch in conditional
1133            .branches
1134            .iter()
1135            .map(|branch| &branch.relationships)
1136            .chain(
1137                conditional
1138                    .default
1139                    .iter()
1140                    .map(|branch| &branch.relationships),
1141            )
1142        {
1143            for item in branch {
1144                match item {
1145                    ast::BranchItem::Relationship(relationship) => {
1146                        body.push(self.relationship(relationship))
1147                    }
1148                    ast::BranchItem::RelationshipUse(invocation) => {
1149                        if let Some(item) = self.invocation(invocation, plans, edges, edge, true) {
1150                            body.push(item);
1151                        }
1152                    }
1153                }
1154            }
1155        }
1156        self.plan
1157            .ineligible
1158            .get_or_insert_with(|| label(self.owner, conditional.span, "conditional declaration"));
1159        Body::Conditional {
1160            inputs,
1161            body,
1162            label: label(self.owner, conditional.span, "conditional guard"),
1163        }
1164    }
1165
1166    /// Checks one item while retaining independent findings after prerequisite failures.
1167    ///
1168    /// - Complexity: The selected declaration/body check.
1169    fn item(
1170        &mut self,
1171        item: &'a ast::SheetItem,
1172        plans: &[Plan<'a>],
1173        edges: &[resolve::Edge],
1174        edge: &mut usize,
1175    ) {
1176        match item {
1177            ast::SheetItem::Cell(cell) => self.declaration(
1178                (&cell.name, cell.name_span),
1179                cell.type_name.as_ref(),
1180                cell.initializer.as_ref(),
1181                cell.filter.as_ref(),
1182                cell.require.as_ref(),
1183                Kind::Cell,
1184            ),
1185            ast::SheetItem::Source(cell) => self.declaration(
1186                (&cell.name, cell.name_span),
1187                cell.type_name.as_ref(),
1188                cell.initializer.as_ref(),
1189                cell.filter.as_ref(),
1190                cell.require.as_ref(),
1191                Kind::Source,
1192            ),
1193            ast::SheetItem::Out(cell) => self.declaration(
1194                (&cell.name, cell.name_span),
1195                cell.type_name.as_ref(),
1196                Some(&cell.initializer),
1197                cell.filter.as_ref(),
1198                cell.require.as_ref(),
1199                Kind::Out,
1200            ),
1201            ast::SheetItem::Relationship(relationship) => {
1202                let body = self.relationship(relationship);
1203                self.plan.body.push(body);
1204            }
1205            ast::SheetItem::RelationshipUse(invocation) => {
1206                if let Some(body) = self.invocation(invocation, plans, edges, edge, false) {
1207                    self.plan.body.push(body);
1208                }
1209            }
1210            ast::SheetItem::Conditional(conditional) => {
1211                let body = self.conditional(conditional, plans, edges, edge);
1212                self.plan.body.push(body);
1213            }
1214            ast::SheetItem::Error { .. } => {}
1215        }
1216    }
1217}
1218
1219/// Resolves bound native leaves and marks missing bindings while retaining unknown leaves as `Any`.
1220///
1221/// - Complexity: O(t) recursive shape nodes and result storage.
1222fn native_type(
1223    shape: &crate::type_registry::TypeShape,
1224    environment: &AdamCheckingEnvironment,
1225    binding: Option<&cel_parser::checking::HostTypeBinding>,
1226    missing: &mut bool,
1227) -> Ty {
1228    use crate::type_registry::TypeShape;
1229    match shape {
1230        TypeShape::Named(id) => binding
1231            .and_then(|binding| binding.resolve(environment.cel(), *id))
1232            .unwrap_or_else(|| {
1233                *missing = true;
1234                Ty::Any
1235            }),
1236        TypeShape::Array(element) => Ty::Array(Box::new(native_type(
1237            element,
1238            environment,
1239            binding,
1240            missing,
1241        ))),
1242        TypeShape::Tuple(elements) => Ty::Tuple(
1243            elements
1244                .iter()
1245                .map(|ty| native_type(ty, environment, binding, missing))
1246                .collect(),
1247        ),
1248        TypeShape::Callable(parameters, result) => Ty::Callable(
1249            parameters
1250                .iter()
1251                .map(|ty| native_type(ty, environment, binding, missing))
1252                .collect(),
1253            Box::new(native_type(result, environment, binding, missing)),
1254        ),
1255    }
1256}
1257
1258/// Projects a compact native DAG into the same local symbolic plans as parsed bodies.
1259///
1260/// - Complexity: Native snapshot costs plus O(n log(n + 1) + e + t log(m + 1) + b)
1261///   time and O(n + e + t + b) space for n declarations, e endpoints, t type nodes,
1262///   m registered leaves and b diagnostic bytes; shared definitions remain unexpanded.
1263fn append_native_plans<'a>(
1264    root: usize,
1265    template: &TypedTemplate,
1266    plans: &mut Vec<Plan<'a>>,
1267    environment: &AdamCheckingEnvironment,
1268    binding: Option<&cel_parser::checking::HostTypeBinding>,
1269    availability: MetadataAvailability,
1270    report: &mut ModuleCheckingReport,
1271) {
1272    use adam_rs::template::structure::RelationshipStructure;
1273    let definitions = template.checking_definitions();
1274    let base = plans.len();
1275    let indices: Vec<_> = (0..definitions.len())
1276        .map(|id| if id == 0 { root } else { base + id - 1 })
1277        .collect();
1278    let remaps: Vec<Vec<usize>> = definitions
1279        .iter()
1280        .map(|definition| {
1281            let cells = &definition.structure.cells;
1282            let order: Vec<_> = (0..cells.len())
1283                .filter(|id| cells[*id].parameter)
1284                .chain((0..cells.len()).filter(|id| !cells[*id].parameter))
1285                .collect();
1286            let mut map = vec![0; cells.len()];
1287            for (new, old) in order.into_iter().enumerate() {
1288                map[old] = new;
1289            }
1290            map
1291        })
1292        .collect();
1293    let formal_counts: Vec<_> = definitions
1294        .iter()
1295        .map(|definition| {
1296            definition
1297                .structure
1298                .cells
1299                .iter()
1300                .filter(|cell| cell.parameter)
1301                .count()
1302        })
1303        .collect();
1304    for (id, definition) in definitions.into_iter().enumerate() {
1305        let mut plan = Plan::new(definition.label.clone());
1306        let mut missing_binding = false;
1307        plan.formals = formal_counts[id];
1308        let map = &remaps[id];
1309        let mut cells: Vec<_> = definition
1310            .structure
1311            .cells
1312            .into_iter()
1313            .zip(definition.cells)
1314            .enumerate()
1315            .map(|(old, (cell, (shape, label)))| {
1316                let ty = native_type(&shape, environment, binding, &mut missing_binding);
1317                environment.visit_unregistered_leaves(&ty, &mut |leaf| {
1318                    let finding = ModuleDiagnostic {
1319                        message: format!("unregistered Adam cell storage type `{}`", leaf.name()),
1320                        labels: vec![label.clone()],
1321                        cause: None,
1322                    };
1323                    if availability == MetadataAvailability::Complete {
1324                        report.diagnostics.push(finding);
1325                    } else {
1326                        plan.blocked = true;
1327                        report.incomplete.push(finding);
1328                    }
1329                });
1330                let kind = if cell.parameter {
1331                    Kind::Parameter
1332                } else {
1333                    match cell.kind {
1334                        adam_rs::CellKind::Source => Kind::Source,
1335                        adam_rs::CellKind::Out => Kind::Out,
1336                        _ => Kind::Cell,
1337                    }
1338                };
1339                (
1340                    map[old],
1341                    Cell {
1342                        name: Cow::Owned(cell.name),
1343                        ty,
1344                        kind,
1345                        label,
1346                    },
1347                )
1348            })
1349            .collect();
1350        cells.sort_unstable_by_key(|(id, _)| *id);
1351        plan.cells = cells.into_iter().map(|(_, cell)| cell).collect();
1352        if missing_binding {
1353            plan.blocked = true;
1354            report.incomplete.push(ModuleDiagnostic { message: "incomplete checking: native signature requires an explicit binding to this checking catalog".into(), labels: vec![plan.label.clone()], cause: None });
1355        }
1356        let convert_method = |method: adam_rs::template::structure::MethodStructure| Method {
1357            inputs: method.inputs.iter().map(|id| map[*id]).collect(),
1358            outputs: method.outputs.iter().map(|id| map[*id]).collect(),
1359            label: plan.label.clone(),
1360        };
1361        let mut groups: Vec<_> = definition
1362            .structure
1363            .relationships
1364            .into_iter()
1365            .map(|relationship| {
1366                Some(match relationship {
1367                    RelationshipStructure::Methods(methods) => Body::Relationship {
1368                        methods: methods.into_iter().map(convert_method).collect(),
1369                        label: plan.label.clone(),
1370                    },
1371                    RelationshipStructure::Out(method) => Body::Relationship {
1372                        methods: vec![convert_method(method)],
1373                        label: plan.label.clone(),
1374                    },
1375                    RelationshipStructure::Include {
1376                        definition,
1377                        bindings,
1378                    } => {
1379                        let mut actuals = vec![0; formal_counts[definition]];
1380                        for (formal, actual) in bindings {
1381                            actuals[remaps[definition][formal]] = map[actual];
1382                        }
1383                        Body::Use {
1384                            target: indices[definition],
1385                            bindings: actuals,
1386                            label: plan.label.clone(),
1387                        }
1388                    }
1389                })
1390            })
1391            .collect();
1392        let mut conditionals = Vec::new();
1393        for conditional in definition.structure.conditionals {
1394            let mut body = Vec::new();
1395            for group in conditional
1396                .branches
1397                .into_iter()
1398                .flatten()
1399                .chain(conditional.default)
1400            {
1401                body.push(
1402                    groups[group]
1403                        .take()
1404                        .expect("native conditional groups are disjoint"),
1405                );
1406            }
1407            conditionals.push(Body::Conditional {
1408                inputs: conditional.inputs.iter().map(|id| map[*id]).collect(),
1409                body,
1410                label: plan.label.clone(),
1411            });
1412        }
1413        plan.body.extend(groups.into_iter().flatten());
1414        for policy in definition.structure.policies {
1415            if policy.is_filter {
1416                plan.body.push(Body::Filter {
1417                    cell: map[policy.cell],
1418                    inputs: policy.inputs.iter().map(|id| map[*id]).collect(),
1419                    label: plan.label.clone(),
1420                });
1421            }
1422        }
1423        plan.body.extend(conditionals);
1424        if id == 0 && !template.is_relationship_only() {
1425            plan.ineligible = Some(plan.label.clone());
1426        }
1427        if id == 0 {
1428            plans[root] = plan;
1429        } else {
1430            plans.push(plan);
1431        }
1432    }
1433}
1434
1435/// Collects direct symbolic invocation targets without expanding their definitions.
1436///
1437/// - Complexity: O(b) local body nodes and pending node references.
1438fn targets(body: &[Body]) -> Vec<usize> {
1439    let mut pending = vec![body];
1440    let mut targets = Vec::new();
1441    while let Some(body) = pending.pop() {
1442        for item in body {
1443            match item {
1444                Body::Use { target, .. } => targets.push(*target),
1445                Body::Conditional { body, .. } => pending.push(body),
1446                _ => {}
1447            }
1448        }
1449    }
1450    targets
1451}
1452
1453/// Reuses component postorder for parsed and projected-native symbolic definitions.
1454///
1455/// - Complexity: O(d + u) definitions and direct use edges.
1456fn plan_order(plans: &[Plan<'_>]) -> Vec<usize> {
1457    let edges: Vec<_> = plans
1458        .iter()
1459        .map(|plan| {
1460            targets(&plan.body)
1461                .into_iter()
1462                .map(|target| resolve::Edge {
1463                    target,
1464                    label: plan.label.clone(),
1465                })
1466                .collect()
1467        })
1468        .collect();
1469    resolve::postorder(&edges).expect("resolved source and native recipe DAGs are acyclic")
1470}
1471
1472/// Validates a local/unresolved definition through the same structural summary cache.
1473///
1474/// - Complexity: As [`check_module_with_environment`].
1475fn validate_graph(id: usize, plans: &[Plan<'_>], report: &mut ModuleCheckingReport) {
1476    structure::validate(plans, [id], report);
1477}