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