Skip to main content

domainforge_core/module/
resolver.rs

1use crate::application::diagnostic::{
2    ApplicationDiagnostic, APP014_IMPORT_CYCLE, APP014_NOT_EXPORTED, APP014_SYMBOL_COLLISION,
3    APP014_UNRESOLVED_ALIAS, APP014_UNRESOLVED_SPECIFIER,
4};
5use crate::application::ApplicationDiagnosticCode;
6use crate::error::fuzzy::levenshtein_distance;
7use crate::parser::ast::{Ast, AstNode, ImportDecl, ImportSpecifier};
8use crate::parser::{parse_source, ParseError, ParseOptions, ParseResult};
9use crate::registry::{NamespaceBinding, NamespaceRegistry};
10use indexmap::IndexMap;
11use sha2::{Digest, Sha256};
12use std::collections::{HashMap, HashSet};
13use std::fs;
14use std::path::{Path, PathBuf};
15use unicode_normalization::UnicodeNormalization;
16
17#[derive(Debug, Clone)]
18pub struct ModuleInfo {
19    pub namespace: String,
20    pub exports: HashSet<String>,
21    pub ast: Ast,
22}
23
24#[derive(Debug)]
25pub struct ModuleResolver<'a> {
26    registry: &'a NamespaceRegistry,
27    bindings: Vec<NamespaceBinding>,
28    loaded_modules: HashMap<PathBuf, ModuleInfo>,
29    visiting: HashSet<PathBuf>,
30}
31
32impl<'a> ModuleResolver<'a> {
33    pub fn new(registry: &'a NamespaceRegistry) -> ParseResult<Self> {
34        let bindings = registry
35            .resolve_files()
36            .map_err(|e| ParseError::GrammarError(e.to_string()))?;
37        Ok(Self {
38            registry,
39            bindings,
40            loaded_modules: HashMap::new(),
41            visiting: HashSet::new(),
42        })
43    }
44
45    pub fn validate_entry(
46        &mut self,
47        entry_path: impl AsRef<Path>,
48        source: &str,
49    ) -> ParseResult<Ast> {
50        let path = entry_path
51            .as_ref()
52            .canonicalize()
53            .unwrap_or_else(|_| entry_path.as_ref().to_path_buf());
54        let ast = parse_source(source)?;
55        self.visit(&path, &ast)?;
56        Ok(ast)
57    }
58
59    pub fn validate_dependencies(
60        &mut self,
61        entry_path: impl AsRef<Path>,
62        ast: &Ast,
63    ) -> ParseResult<()> {
64        let path = entry_path
65            .as_ref()
66            .canonicalize()
67            .unwrap_or_else(|_| entry_path.as_ref().to_path_buf());
68        self.visit(&path, ast)
69    }
70
71    fn visit(&mut self, path: &Path, ast: &Ast) -> ParseResult<()> {
72        let canonical = if path.to_string_lossy().starts_with("__std__") {
73            path.to_path_buf()
74        } else {
75            path.canonicalize().unwrap_or_else(|_| path.to_path_buf())
76        };
77
78        if self.visiting.contains(&canonical) {
79            // Build the cycle path from currently visiting modules
80            let cycle: Vec<String> = self
81                .visiting
82                .iter()
83                .map(|p| p.to_string_lossy().to_string())
84                .chain(std::iter::once(canonical.to_string_lossy().to_string()))
85                .collect();
86            return Err(ParseError::circular_dependency(cycle));
87        }
88        if self.loaded_modules.contains_key(&canonical) {
89            return Ok(());
90        }
91
92        self.visiting.insert(canonical.clone());
93        let namespace = ast.metadata.namespace.clone().unwrap_or_else(|| {
94            self.registry
95                .namespace_for(path)
96                .unwrap_or(self.registry.default_namespace())
97                .to_string()
98        });
99        let exports = collect_exports(ast);
100
101        for import in &ast.metadata.imports {
102            let dep_path = self.resolve_module_path(&import.from_module)?;
103            let dependency_ast = self.parse_file(&dep_path)?;
104            self.visit(&dep_path, &dependency_ast)?;
105            self.validate_import_targets(import, &dep_path)?;
106        }
107
108        self.loaded_modules.insert(
109            canonical.clone(),
110            ModuleInfo {
111                namespace,
112                exports,
113                ast: ast.clone(),
114            },
115        );
116        self.visiting.remove(&canonical);
117        Ok(())
118    }
119
120    fn parse_file(&self, path: &Path) -> ParseResult<Ast> {
121        let path_str = path.to_string_lossy();
122        if path_str.starts_with("__std__") {
123            let namespace = path_str.strip_prefix("__std__").unwrap();
124            let content = match namespace {
125                "std" | "std:core" => include_str!("../../std/core.sea"),
126                "std:http" => include_str!("../../std/http.sea"),
127                "std:aws" => include_str!("../../std/aws.sea"),
128                _ => {
129                    return Err(ParseError::GrammarError(format!(
130                        "Unknown std module: {}",
131                        namespace
132                    )))
133                }
134            };
135            return parse_source(content);
136        }
137
138        let content = fs::read_to_string(path).map_err(|e| {
139            ParseError::GrammarError(format!("Failed to read module {}: {}", path.display(), e))
140        })?;
141        parse_source(&content)
142    }
143
144    fn resolve_module_path(&self, namespace: &str) -> ParseResult<PathBuf> {
145        if namespace == "std" || namespace.starts_with("std:") {
146            return Ok(PathBuf::from(format!("__std__{}", namespace)));
147        }
148
149        self.bindings
150            .iter()
151            .find(|binding| binding.namespace == namespace)
152            .map(|binding| binding.path.clone())
153            .ok_or_else(|| {
154                // Find similar namespace for suggestion
155                let suggestion = self.suggest_similar_namespace(namespace);
156                ParseError::namespace_not_found(namespace, 0, 0, suggestion)
157            })
158    }
159
160    fn validate_import_targets(&self, import: &ImportDecl, dep_path: &Path) -> ParseResult<()> {
161        let canonical = if dep_path.to_string_lossy().starts_with("__std__") {
162            dep_path.to_path_buf()
163        } else {
164            dep_path
165                .canonicalize()
166                .unwrap_or_else(|_| dep_path.to_path_buf())
167        };
168        let module = self.loaded_modules.get(&canonical).ok_or_else(|| {
169            ParseError::GrammarError(format!(
170                "Expected module '{}' to be loaded before validating imports",
171                dep_path.display()
172            ))
173        })?;
174
175        match &import.specifier {
176            ImportSpecifier::Wildcard(_) => Ok(()),
177            ImportSpecifier::Named(items) => {
178                for item in items {
179                    if !module.exports.contains(&item.name) {
180                        return Err(ParseError::symbol_not_exported(
181                            &item.name,
182                            &module.namespace,
183                            0, // TODO: Extract line from import.location if available
184                            0,
185                            module.exports.iter().cloned().collect(),
186                        ));
187                    }
188                }
189                Ok(())
190            }
191        }
192    }
193
194    /// Find a similar namespace name for error suggestions using Levenshtein distance
195    fn suggest_similar_namespace(&self, target: &str) -> Option<String> {
196        let available: Vec<&str> = self.bindings.iter().map(|b| b.namespace.as_str()).collect();
197
198        available
199            .iter()
200            .filter_map(|ns| {
201                let distance = levenshtein_distance(target, ns);
202                if distance <= 2 {
203                    Some((*ns, distance))
204                } else {
205                    None
206                }
207            })
208            .min_by_key(|(_, d)| *d)
209            .map(|(ns, _)| ns.to_string())
210    }
211}
212
213fn collect_exports(ast: &Ast) -> HashSet<String> {
214    let mut exports = HashSet::new();
215    for node in &ast.declarations {
216        if let AstNode::Export(inner) = &node.node {
217            if let Some(name) = declaration_name(&inner.node) {
218                exports.insert(name.to_string());
219            }
220        }
221    }
222    exports
223}
224
225fn declaration_name(node: &AstNode) -> Option<&str> {
226    match node {
227        AstNode::Entity { name, .. }
228        | AstNode::Resource { name, .. }
229        | AstNode::Flow {
230            resource_name: name,
231            ..
232        }
233        | AstNode::Pattern { name, .. }
234        | AstNode::Role { name, .. }
235        | AstNode::Relation { name, .. }
236        | AstNode::Dimension { name }
237        | AstNode::UnitDeclaration { symbol: name, .. }
238        | AstNode::Policy { name, .. }
239        | AstNode::Instance { name, .. }
240        | AstNode::ConceptChange { name, .. }
241        | AstNode::Metric { name, .. }
242        | AstNode::MappingDecl { name, .. }
243        | AstNode::ProjectionDecl { name, .. }
244        | AstNode::Cell { name, .. }
245        | AstNode::SystemDependency { name, .. }
246        | AstNode::Runtime { name, .. }
247        | AstNode::Tool { name, .. }
248        | AstNode::DependencySet { name, .. }
249        | AstNode::Service { name, .. }
250        | AstNode::Mount { name, .. }
251        | AstNode::Endpoint { name, .. }
252        | AstNode::NetworkFlow { name, .. }
253        | AstNode::Credential { name, .. } => Some(name),
254        AstNode::Export(inner) => declaration_name(&inner.node),
255        AstNode::Record(r) => Some(&r.name),
256        AstNode::Enum(e) => Some(&e.name),
257        AstNode::Operation(o) => Some(&o.name),
258    }
259}
260
261// ---- Source-map closure resolution (ADR-013, reference §7/§8) ----
262//
263// `ResolvedModuleSet` is the single resolver output consumed by both Graph
264// and ApplicationContract construction. It stays crate-private; the public
265// boundary is `application::resolve`.
266
267#[derive(Debug, Clone, PartialEq, Eq)]
268// ponytail: consumed by application resolution in Task 7.
269#[allow(dead_code)]
270pub(crate) struct OriginRef {
271    pub logical_module_id: String,
272    pub line: usize,
273    pub column: usize,
274}
275
276#[derive(Debug, Clone, Copy, PartialEq, Eq)]
277// ponytail: consumed by application resolution in Task 7.
278#[allow(dead_code)]
279pub(crate) enum ResolvedDeclarationKind {
280    ExistingConcept,
281    Record,
282    Enum,
283    Operation,
284}
285
286#[derive(Debug, Clone)]
287// ponytail: consumed by application resolution in Task 7.
288#[allow(dead_code)]
289pub(crate) struct ResolvedSymbol {
290    pub qualified_id: String,
291    pub kind: ResolvedDeclarationKind,
292    pub exported: bool,
293    pub origin: OriginRef,
294    pub module_index: usize,
295    pub declaration_index: usize,
296}
297
298#[derive(Debug, Clone)]
299// ponytail: consumed by application resolution in Task 7.
300#[allow(dead_code)]
301pub(crate) struct ResolvedModule {
302    pub logical_id: String,
303    pub source_hash: String, // "sha256:<lowercase-hex>"
304    pub ast: Ast,
305}
306
307#[derive(Debug, Clone, PartialEq, Eq)]
308// ponytail: consumed by application resolution in Task 7.
309#[allow(dead_code)]
310pub(crate) struct ImportEdge {
311    pub importer: String,
312    pub imported: String,
313}
314
315#[derive(Debug, Clone, PartialEq, Eq)]
316// ponytail: consumed by application resolution in Task 7.
317#[allow(dead_code)]
318pub(crate) struct AliasBinding {
319    pub importer: String,
320    pub alias: String,
321    pub target: String,
322}
323
324#[derive(Debug, Clone)]
325// ponytail: consumed by application resolution in Task 7.
326#[allow(dead_code)]
327pub(crate) struct ResolvedModuleSet {
328    pub modules: Vec<ResolvedModule>,
329    pub import_graph: Vec<ImportEdge>,
330    pub symbols: IndexMap<String, ResolvedSymbol>,
331    pub aliases: Vec<AliasBinding>,
332}
333
334/// Ordered, validated in-memory source set keyed by normalized logical path.
335#[derive(Debug, Clone)]
336// ponytail: consumed by application resolution in Task 7.
337#[allow(dead_code)]
338pub(crate) struct SourceMap(pub(crate) IndexMap<String, String>);
339
340impl SourceMap {
341    #[allow(dead_code)]
342    /// Parse `sources_json` per reference §7: reject non-object input,
343    /// duplicate raw keys, duplicate normalized logical IDs, non-string
344    /// values, and invalid logical paths.
345    pub(crate) fn parse_json(json: &str) -> Result<Self, Vec<ApplicationDiagnostic>> {
346        let pairs = raw_json_object_pairs(json).map_err(|msg| {
347            vec![ApplicationDiagnostic::closure_error(
348                APP014_UNRESOLVED_SPECIFIER,
349                format!("sources_json is not a valid JSON object of strings: {msg}"),
350            )]
351        })?;
352        let mut raw_seen = HashSet::new();
353        let mut map = IndexMap::new();
354        let mut diags = Vec::new();
355        for (raw_key, value) in pairs {
356            if !raw_seen.insert(raw_key.clone()) {
357                diags.push(ApplicationDiagnostic::closure_error(
358                    APP014_SYMBOL_COLLISION,
359                    format!("duplicate raw source key '{raw_key}'"),
360                ));
361                continue;
362            }
363            let normalized = match normalize_logical_path(&raw_key) {
364                Ok(p) => p,
365                Err(reason) => {
366                    diags.push(ApplicationDiagnostic::closure_error(
367                        APP014_UNRESOLVED_SPECIFIER,
368                        format!("invalid logical path '{raw_key}': {reason}"),
369                    ));
370                    continue;
371                }
372            };
373            if map.insert(normalized.clone(), value).is_some() {
374                diags.push(ApplicationDiagnostic::closure_error(
375                    APP014_SYMBOL_COLLISION,
376                    format!("duplicate normalized logical ID '{normalized}'"),
377                ));
378            }
379        }
380        if diags.is_empty() {
381            Ok(Self(map))
382        } else {
383            Err(diags)
384        }
385    }
386}
387
388/// Deserialize a JSON object into ordered (key, string-value) pairs without
389/// silently collapsing duplicate keys the way `serde_json` maps do.
390// ponytail: consumed by application resolution in Task 7.
391#[allow(dead_code)]
392fn raw_json_object_pairs(json: &str) -> Result<Vec<(String, String)>, String> {
393    struct Pairs;
394    impl<'de> serde::de::Visitor<'de> for Pairs {
395        type Value = Vec<(String, String)>;
396        fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
397            f.write_str("a JSON object mapping logical paths to source strings")
398        }
399        fn visit_map<A: serde::de::MapAccess<'de>>(
400            self,
401            mut map: A,
402        ) -> Result<Self::Value, A::Error> {
403            let mut out = Vec::new();
404            while let Some((k, v)) = map.next_entry::<String, serde_json::Value>()? {
405                match v {
406                    serde_json::Value::String(s) => out.push((k, s)),
407                    other => {
408                        return Err(serde::de::Error::custom(format!(
409                            "source '{k}' must be a string, found {other}"
410                        )))
411                    }
412                }
413            }
414            Ok(out)
415        }
416    }
417    let mut de = serde_json::Deserializer::from_str(json);
418    let pairs =
419        serde::de::Deserializer::deserialize_map(&mut de, Pairs).map_err(|e| e.to_string())?;
420    de.end().map_err(|e| e.to_string())?;
421    Ok(pairs)
422}
423
424/// Reference §7 logical-path algorithm: NFC, `/` separators, case preserved,
425/// `.` segments dropped, `..` resolved without escaping the root; `\`,
426/// absolute paths, and empty segments rejected.
427// ponytail: consumed by application resolution in Task 7.
428#[allow(dead_code)]
429fn normalize_logical_path(raw: &str) -> Result<String, String> {
430    let path: String = raw.nfc().collect();
431    if path.is_empty() {
432        return Err("empty path".to_string());
433    }
434    if path.contains('\\') {
435        return Err("backslash separators are not allowed".to_string());
436    }
437    if path.starts_with('/') {
438        return Err("absolute paths are not allowed".to_string());
439    }
440    let mut segments: Vec<&str> = Vec::new();
441    for segment in path.split('/') {
442        match segment {
443            "" => return Err("empty path segment".to_string()),
444            "." => {}
445            ".." => {
446                if segments.pop().is_none() {
447                    return Err("path escapes the source-map root".to_string());
448                }
449            }
450            s => segments.push(s),
451        }
452    }
453    if segments.is_empty() {
454        return Err("path resolves to the source-map root".to_string());
455    }
456    Ok(segments.join("/"))
457}
458
459/// The logical directory of a module ID ("flagship/a.sea" -> "flagship").
460// ponytail: consumed by application resolution in Task 7.
461#[allow(dead_code)]
462fn logical_dir(logical_id: &str) -> &str {
463    logical_id.rfind('/').map_or("", |i| &logical_id[..i])
464}
465
466// ponytail: consumed by application resolution in Task 7.
467#[allow(dead_code)]
468fn source_hash(source: &str) -> String {
469    format!("sha256:{:x}", Sha256::digest(source.as_bytes()))
470}
471
472// ponytail: consumed by application resolution in Task 7.
473#[allow(dead_code)]
474fn declaration_kind(node: &AstNode) -> ResolvedDeclarationKind {
475    match node {
476        AstNode::Export(inner) => declaration_kind(&inner.node),
477        AstNode::Record(_) => ResolvedDeclarationKind::Record,
478        AstNode::Enum(_) => ResolvedDeclarationKind::Enum,
479        AstNode::Operation(_) => ResolvedDeclarationKind::Operation,
480        _ => ResolvedDeclarationKind::ExistingConcept,
481    }
482}
483
484// ponytail: consumed by application resolution in Task 7.
485#[allow(dead_code)]
486fn kind_slug(node: &AstNode) -> &'static str {
487    match node {
488        AstNode::Export(inner) => kind_slug(&inner.node),
489        AstNode::Entity { .. } => "entity",
490        AstNode::Resource { .. } => "resource",
491        AstNode::Flow { .. } => "flow",
492        AstNode::Pattern { .. } => "pattern",
493        AstNode::Role { .. } => "role",
494        AstNode::Relation { .. } => "relation",
495        AstNode::Dimension { .. } => "dimension",
496        AstNode::UnitDeclaration { .. } => "unit",
497        AstNode::Policy { .. } => "policy",
498        AstNode::Instance { .. } => "instance",
499        AstNode::ConceptChange { .. } => "concept_change",
500        AstNode::Metric { .. } => "metric",
501        AstNode::MappingDecl { .. } => "mapping",
502        AstNode::ProjectionDecl { .. } => "projection",
503        AstNode::Cell { .. } => "cell",
504        AstNode::SystemDependency { .. } => "system_dependency",
505        AstNode::Runtime { .. } => "runtime",
506        AstNode::Tool { .. } => "tool",
507        AstNode::DependencySet { .. } => "dependency_set",
508        AstNode::Service { .. } => "service",
509        AstNode::Mount { .. } => "mount",
510        AstNode::Endpoint { .. } => "endpoint",
511        AstNode::NetworkFlow { .. } => "network_flow",
512        AstNode::Credential { .. } => "credential",
513        AstNode::Record(_) => "record",
514        AstNode::Enum(_) => "enum",
515        AstNode::Operation(_) => "operation",
516    }
517}
518
519// ponytail: consumed by application resolution in Task 7.
520#[allow(dead_code)]
521fn builtin_std_source(specifier: &str) -> Option<&'static str> {
522    match specifier {
523        "std" | "std:core" => Some(include_str!("../../std/core.sea")),
524        "std:http" => Some(include_str!("../../std/http.sea")),
525        "std:aws" => Some(include_str!("../../std/aws.sea")),
526        _ => None,
527    }
528}
529
530/// Resolve one deterministic semantic closure from an in-memory source map
531/// (reference §7). All diagnostics are APP014 with a closed reason value,
532/// except parse failures which are APP015 (the module fails its language
533/// schema before closure identity exists).
534// ponytail: consumed by application resolution in Task 7.
535#[allow(dead_code)]
536pub(crate) fn resolve_source_map(
537    entry_logical_path: &str,
538    sources: &SourceMap,
539) -> Result<ResolvedModuleSet, Vec<ApplicationDiagnostic>> {
540    let mut diags: Vec<ApplicationDiagnostic> = Vec::new();
541
542    // Parse every module up front; the set is closed and namespace imports
543    // need every module's declared namespace anyway.
544    let mut parsed: IndexMap<String, (String, Ast)> = IndexMap::new();
545    for (logical_id, source) in &sources.0 {
546        match parse_source(source) {
547            Ok(ast) => {
548                parsed.insert(logical_id.clone(), (source.clone(), ast));
549            }
550            Err(e) => {
551                let mut d = ApplicationDiagnostic::new(
552                    ApplicationDiagnosticCode::App015,
553                    format!("module '{logical_id}' failed to parse: {e}"),
554                )
555                .with_document_kind("authored_source");
556                d.context.logical_module_id = Some(logical_id.clone());
557                diags.push(d);
558            }
559        }
560    }
561    if !diags.is_empty() {
562        return Err(diags);
563    }
564
565    let entry = normalize_logical_path(entry_logical_path).map_err(|reason| {
566        vec![ApplicationDiagnostic::closure_error(
567            APP014_UNRESOLVED_SPECIFIER,
568            format!("invalid entry logical path '{entry_logical_path}': {reason}"),
569        )]
570    })?;
571    if !parsed.contains_key(&entry) {
572        return Err(vec![ApplicationDiagnostic::closure_error(
573            APP014_UNRESOLVED_SPECIFIER,
574            format!("entry '{entry}' is not present in sources_json"),
575        )]);
576    }
577
578    // DFS closure walk from the entry.
579    let mut std_modules: IndexMap<String, (String, Ast)> = IndexMap::new();
580    let mut reachable: HashSet<String> = HashSet::new();
581    let mut visiting: Vec<String> = Vec::new();
582    let mut import_graph: Vec<ImportEdge> = Vec::new();
583    let mut aliases: Vec<AliasBinding> = Vec::new();
584
585    #[allow(clippy::too_many_arguments)]
586    fn visit(
587        logical_id: &str,
588        parsed: &IndexMap<String, (String, Ast)>,
589        std_modules: &mut IndexMap<String, (String, Ast)>,
590        reachable: &mut HashSet<String>,
591        visiting: &mut Vec<String>,
592        import_graph: &mut Vec<ImportEdge>,
593        aliases: &mut Vec<AliasBinding>,
594        diags: &mut Vec<ApplicationDiagnostic>,
595    ) {
596        if visiting.iter().any(|m| m == logical_id) {
597            let cycle: Vec<&str> = visiting
598                .iter()
599                .map(String::as_str)
600                .chain(std::iter::once(logical_id))
601                .collect();
602            diags.push(ApplicationDiagnostic::closure_error(
603                APP014_IMPORT_CYCLE,
604                format!("import cycle: {}", cycle.join(" -> ")),
605            ));
606            return;
607        }
608        if reachable.contains(logical_id) {
609            return;
610        }
611        reachable.insert(logical_id.to_string());
612        let ast = match parsed
613            .get(logical_id)
614            .or_else(|| std_modules.get(logical_id))
615        {
616            Some((_, ast)) => ast.clone(),
617            None => return,
618        };
619        visiting.push(logical_id.to_string());
620        for import in &ast.metadata.imports {
621            let spec = &import.from_module;
622            let target: Option<String> = if spec.starts_with("./") || spec.starts_with("../") {
623                let joined = if logical_dir(logical_id).is_empty() {
624                    spec.clone()
625                } else {
626                    format!("{}/{}", logical_dir(logical_id), spec)
627                };
628                match normalize_logical_path(&joined) {
629                    Ok(p) if parsed.contains_key(&p) => Some(p),
630                    Ok(p) => {
631                        diags.push(ApplicationDiagnostic::closure_error(
632                            APP014_UNRESOLVED_SPECIFIER,
633                            format!(
634                                "import '{spec}' in '{logical_id}' resolves to '{p}', which is not in sources_json"
635                            ),
636                        ));
637                        None
638                    }
639                    Err(reason) => {
640                        diags.push(ApplicationDiagnostic::closure_error(
641                            APP014_UNRESOLVED_SPECIFIER,
642                            format!("import '{spec}' in '{logical_id}' is invalid: {reason}"),
643                        ));
644                        None
645                    }
646                }
647            } else if spec == "std" || spec.starts_with("std:") {
648                match builtin_std_source(spec) {
649                    Some(source) => {
650                        if !std_modules.contains_key(spec) {
651                            // std sources are maintained in-repo and always parse.
652                            let ast = parse_source(source).expect("builtin std module parses");
653                            std_modules.insert(spec.clone(), (source.to_string(), ast));
654                        }
655                        Some(spec.clone())
656                    }
657                    None => {
658                        diags.push(ApplicationDiagnostic::closure_error(
659                            APP014_UNRESOLVED_SPECIFIER,
660                            format!("unknown std module '{spec}' imported by '{logical_id}'"),
661                        ));
662                        None
663                    }
664                }
665            } else {
666                // Namespace import: exactly one source-map module whose declared
667                // namespace equals the specifier's exact bytes.
668                let matches: Vec<&String> = parsed
669                    .iter()
670                    .filter(|(_, (_, ast))| ast.metadata.namespace.as_deref() == Some(spec))
671                    .map(|(id, _)| id)
672                    .collect();
673                match matches.as_slice() {
674                    [one] => Some((*one).clone()),
675                    [] => {
676                        diags.push(ApplicationDiagnostic::closure_error(
677                            APP014_UNRESOLVED_SPECIFIER,
678                            format!(
679                                "namespace import '{spec}' in '{logical_id}' matches no source-map module"
680                            ),
681                        ));
682                        None
683                    }
684                    _ => {
685                        diags.push(ApplicationDiagnostic::closure_error(
686                            APP014_UNRESOLVED_SPECIFIER,
687                            format!(
688                                "namespace import '{spec}' in '{logical_id}' matches more than one source-map module"
689                            ),
690                        ));
691                        None
692                    }
693                }
694            };
695            let Some(target) = target else { continue };
696            import_graph.push(ImportEdge {
697                importer: logical_id.to_string(),
698                imported: target.clone(),
699            });
700            if let ImportSpecifier::Wildcard(alias) = &import.specifier {
701                aliases.push(AliasBinding {
702                    importer: logical_id.to_string(),
703                    alias: alias.clone(),
704                    target: target.clone(),
705                });
706            }
707            visit(
708                &target,
709                parsed,
710                std_modules,
711                reachable,
712                visiting,
713                import_graph,
714                aliases,
715                diags,
716            );
717            // Named import visibility against the resolved target.
718            if let ImportSpecifier::Named(items) = &import.specifier {
719                if let Some((_, target_ast)) =
720                    parsed.get(&target).or_else(|| std_modules.get(&target))
721                {
722                    let exports = collect_exports(target_ast);
723                    let declared: HashSet<&str> = target_ast
724                        .declarations
725                        .iter()
726                        .filter_map(|d| declaration_name(&d.node))
727                        .collect();
728                    for item in items {
729                        if exports.contains(&item.name) {
730                            continue;
731                        }
732                        if declared.contains(item.name.as_str()) {
733                            diags.push(ApplicationDiagnostic::closure_error(
734                                APP014_NOT_EXPORTED,
735                                format!("'{}' exists in '{target}' but is not exported", item.name),
736                            ));
737                        } else {
738                            diags.push(ApplicationDiagnostic::closure_error(
739                                APP014_UNRESOLVED_ALIAS,
740                                format!(
741                                    "named import '{}' in '{logical_id}' binds no declaration in '{target}'",
742                                    item.name
743                                ),
744                            ));
745                        }
746                    }
747                }
748            }
749        }
750        visiting.pop();
751    }
752
753    visit(
754        &entry,
755        &parsed,
756        &mut std_modules,
757        &mut reachable,
758        &mut visiting,
759        &mut import_graph,
760        &mut aliases,
761        &mut diags,
762    );
763
764    if !diags.is_empty() {
765        crate::application::diagnostic::sort_diagnostics(&mut diags);
766        return Err(diags);
767    }
768
769    // Deterministic module order: logical ID, bytewise ascending.
770    let mut logical_ids: Vec<String> = reachable.into_iter().collect();
771    logical_ids.sort();
772    let modules: Vec<ResolvedModule> = logical_ids
773        .iter()
774        .map(|id| {
775            let (source, ast) = parsed
776                .get(id)
777                .or_else(|| std_modules.get(id))
778                .expect("reachable module was parsed");
779            ResolvedModule {
780                logical_id: id.clone(),
781                source_hash: source_hash(source),
782                ast: ast.clone(),
783            }
784        })
785        .collect();
786
787    import_graph.sort_by(|a, b| (&a.importer, &a.imported).cmp(&(&b.importer, &b.imported)));
788    import_graph.dedup();
789    aliases.sort_by(|a, b| (&a.importer, &a.alias).cmp(&(&b.importer, &b.alias)));
790
791    // One qualified symbol table across the closure. Application declaration
792    // names are NFC-normalized; existing concept names keep exact bytes.
793    let mut symbols: IndexMap<String, ResolvedSymbol> = IndexMap::new();
794    for (module_index, module) in modules.iter().enumerate() {
795        let namespace = module
796            .ast
797            .metadata
798            .namespace
799            .clone()
800            // ponytail: modules without @namespace use their logical ID as the
801            // qualification root; the reference leaves this case to APP014 later.
802            .unwrap_or_else(|| module.logical_id.clone());
803        let exports = collect_exports(&module.ast);
804        for (declaration_index, decl) in module.ast.declarations.iter().enumerate() {
805            let Some(name) = declaration_name(&decl.node) else {
806                continue;
807            };
808            // Flows are occurrence-identified (reference §8): equal flows are
809            // legal repetitions, not qualified-ID collisions.
810            let inner = match &decl.node {
811                crate::parser::ast::AstNode::Export(inner) => &inner.node,
812                other => other,
813            };
814            if matches!(inner, crate::parser::ast::AstNode::Flow { .. }) {
815                continue;
816            }
817            let kind = declaration_kind(&decl.node);
818            let name = if kind == ResolvedDeclarationKind::ExistingConcept {
819                name.to_string()
820            } else {
821                name.nfc().collect()
822            };
823            let qualified_id = format!("{namespace}.{}.{name}", kind_slug(&decl.node));
824            let symbol = ResolvedSymbol {
825                qualified_id: qualified_id.clone(),
826                kind,
827                exported: exports.contains(name.as_str()),
828                origin: OriginRef {
829                    logical_module_id: module.logical_id.clone(),
830                    line: decl.line,
831                    column: decl.column,
832                },
833                module_index,
834                declaration_index,
835            };
836            if let Some(existing) = symbols.get(&qualified_id) {
837                diags.push(ApplicationDiagnostic::closure_error(
838                    APP014_SYMBOL_COLLISION,
839                    format!(
840                        "distinct declarations share qualified ID '{qualified_id}' ('{}' line {} and '{}' line {})",
841                        existing.origin.logical_module_id,
842                        existing.origin.line,
843                        module.logical_id,
844                        decl.line
845                    ),
846                ));
847            } else {
848                symbols.insert(qualified_id, symbol);
849            }
850        }
851    }
852
853    if diags.is_empty() {
854        Ok(ResolvedModuleSet {
855            modules,
856            import_graph,
857            symbols,
858            aliases,
859        })
860    } else {
861        crate::application::diagnostic::sort_diagnostics(&mut diags);
862        Err(diags)
863    }
864}
865
866pub fn parse_with_registry(
867    path: &Path,
868    registry: &NamespaceRegistry,
869) -> ParseResult<(Ast, ParseOptions)> {
870    let content = fs::read_to_string(path).map_err(|e| {
871        ParseError::GrammarError(format!("Failed to read {}: {}", path.display(), e))
872    })?;
873
874    // `ParseOptions` are constructed here to be returned to the caller,
875    // even though `parse_source` currently doesn't use them. Initialize
876    // fields directly in the `ParseOptions` construction to avoid
877    // field reassignment lint from clippy (clippy::field-reassign-with-default).
878    let options = ParseOptions {
879        namespace_registry: Some(registry.clone()),
880        entry_path: Some(path.to_path_buf()),
881        ..Default::default()
882    };
883
884    let ast = parse_source(&content)?;
885    Ok((ast, options))
886}
887
888#[cfg(test)]
889mod source_map_tests {
890    use super::*;
891
892    fn resolve(
893        entry: &str,
894        sources_json: &str,
895    ) -> Result<ResolvedModuleSet, Vec<ApplicationDiagnostic>> {
896        let sources = SourceMap::parse_json(sources_json)?;
897        resolve_source_map(entry, &sources)
898    }
899
900    fn reason(err: &[ApplicationDiagnostic]) -> &str {
901        err[0].context.reason.as_deref().unwrap()
902    }
903
904    #[test]
905    fn resolves_named_relative_import_into_one_symbol_table() {
906        let sources = serde_json::json!({
907            "flagship/command-write.sea": include_str!(
908                "../../../fixtures/application_generation/flagship/command-write.sea"),
909            "flagship/query-read.sea": include_str!(
910                "../../../fixtures/application_generation/flagship/query-read.sea"),
911        })
912        .to_string();
913        let set = resolve("flagship/query-read.sea", &sources).unwrap();
914        assert_eq!(
915            set.modules
916                .iter()
917                .map(|m| m.logical_id.as_str())
918                .collect::<Vec<_>>(),
919            ["flagship/command-write.sea", "flagship/query-read.sea"]
920        );
921        assert!(set.symbols.contains_key("flagship.orders.entity.Order"));
922        assert!(set
923            .symbols
924            .contains_key("flagship.orders.record.PlaceOrderInput"));
925        assert!(set
926            .symbols
927            .contains_key("flagship.orders.operation.get_order_status"));
928        assert_eq!(set.import_graph.len(), 1);
929        assert!(set
930            .modules
931            .iter()
932            .all(|m| m.source_hash.starts_with("sha256:")));
933    }
934
935    #[test]
936    fn relative_import_escaping_root_is_unresolved_specifier() {
937        let sources = serde_json::json!({
938            "a.sea": "@namespace \"ns.a\"\nimport { X } from \"../outside.sea\"\n",
939        })
940        .to_string();
941        let err = resolve("a.sea", &sources).unwrap_err();
942        assert_eq!(reason(&err), "unresolved_specifier");
943        assert!(err[0].message.contains("escapes"));
944    }
945
946    #[test]
947    fn duplicate_normalized_source_key_is_rejected() {
948        let sources = r#"{"a/./x.sea": "@namespace \"n\"", "a/x.sea": "@namespace \"n\""}"#;
949        let err = SourceMap::parse_json(sources).unwrap_err();
950        assert_eq!(reason(&err), "symbol_collision");
951        assert!(err[0].message.contains("duplicate normalized logical ID"));
952    }
953
954    #[test]
955    fn duplicate_raw_source_key_is_rejected() {
956        let sources = r#"{"a.sea": "x", "a.sea": "y"}"#;
957        let err = SourceMap::parse_json(sources).unwrap_err();
958        assert_eq!(reason(&err), "symbol_collision");
959        assert!(err[0].message.contains("duplicate raw source key"));
960    }
961
962    #[test]
963    fn named_import_of_unexported_symbol_is_not_exported() {
964        let sources = serde_json::json!({
965            "a.sea": "@namespace \"ns.a\"\nimport { Hidden } from \"./b.sea\"\n",
966            "b.sea": "@namespace \"ns.b\"\nrecord Hidden {\n    x: string\n}\n",
967        })
968        .to_string();
969        let err = resolve("a.sea", &sources).unwrap_err();
970        assert_eq!(reason(&err), "not_exported");
971    }
972
973    #[test]
974    fn named_import_binding_nothing_is_unresolved_alias() {
975        let sources = serde_json::json!({
976            "a.sea": "@namespace \"ns.a\"\nimport { Ghost } from \"./b.sea\"\n",
977            "b.sea": "@namespace \"ns.b\"\nexport record Real {\n    x: string\n}\n",
978        })
979        .to_string();
980        let err = resolve("a.sea", &sources).unwrap_err();
981        assert_eq!(reason(&err), "unresolved_alias");
982    }
983
984    #[test]
985    fn wildcard_import_records_alias_binding() {
986        let sources = serde_json::json!({
987            "a.sea": "@namespace \"ns.a\"\nimport * as b from \"./b.sea\"\n",
988            "b.sea": "@namespace \"ns.b\"\nexport record Real {\n    x: string\n}\n",
989        })
990        .to_string();
991        let set = resolve("a.sea", &sources).unwrap();
992        assert_eq!(
993            set.aliases,
994            vec![AliasBinding {
995                importer: "a.sea".to_string(),
996                alias: "b".to_string(),
997                target: "b.sea".to_string(),
998            }]
999        );
1000    }
1001
1002    #[test]
1003    fn unresolved_relative_specifier_is_reported() {
1004        let sources = serde_json::json!({
1005            "a.sea": "@namespace \"ns.a\"\nimport { X } from \"./missing.sea\"\n",
1006        })
1007        .to_string();
1008        let err = resolve("a.sea", &sources).unwrap_err();
1009        assert_eq!(reason(&err), "unresolved_specifier");
1010    }
1011
1012    #[test]
1013    fn import_cycle_is_reported() {
1014        let sources = serde_json::json!({
1015            "a.sea": "@namespace \"ns.a\"\nimport * as b from \"./b.sea\"\n",
1016            "b.sea": "@namespace \"ns.b\"\nimport * as a from \"./a.sea\"\n",
1017        })
1018        .to_string();
1019        let err = resolve("a.sea", &sources).unwrap_err();
1020        assert_eq!(reason(&err), "import_cycle");
1021    }
1022
1023    #[test]
1024    fn distinct_declarations_with_one_qualified_id_collide() {
1025        let sources = serde_json::json!({
1026            "a.sea": "@namespace \"ns.shared\"\nimport * as b from \"./b.sea\"\nexport record Same {\n    x: string\n}\n",
1027            "b.sea": "@namespace \"ns.shared\"\nexport record Same {\n    x: string\n}\n",
1028        })
1029        .to_string();
1030        let err = resolve("a.sea", &sources).unwrap_err();
1031        assert_eq!(reason(&err), "symbol_collision");
1032    }
1033
1034    #[test]
1035    fn diamond_origin_collapses_to_one_symbol() {
1036        let sources = serde_json::json!({
1037            "a.sea": "@namespace \"ns.a\"\nimport * as b from \"./b.sea\"\nimport * as c from \"./c.sea\"\n",
1038            "b.sea": "@namespace \"ns.b\"\nimport { Shared } from \"./d.sea\"\n",
1039            "c.sea": "@namespace \"ns.c\"\nimport { Shared } from \"./d.sea\"\n",
1040            "d.sea": "@namespace \"ns.d\"\nexport record Shared {\n    x: string\n}\n",
1041        })
1042        .to_string();
1043        let set = resolve("a.sea", &sources).unwrap();
1044        assert_eq!(
1045            set.symbols
1046                .values()
1047                .filter(|s| s.qualified_id.ends_with(".Shared"))
1048                .count(),
1049            1
1050        );
1051        assert_eq!(set.modules.len(), 4);
1052    }
1053
1054    #[test]
1055    fn entry_missing_from_sources_is_unresolved_specifier() {
1056        let err = resolve("missing.sea", r#"{"a.sea": "@namespace \"n\""}"#).unwrap_err();
1057        assert_eq!(reason(&err), "unresolved_specifier");
1058    }
1059}