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