Skip to main content

oxdock_core/exec/
typing.rs

1//! Type-system integration for the executor.
2//!
3//! Name directories (which descriptor answers for `"TAG"`) live per
4//! execution state: one `HashMap` seeded with the startup descriptors,
5//! extended by the run's host descriptors. Words carry their own vtable,
6//! so lifecycle never consults any table; only name resolution (declaration
7//! checking, `TYPES()`, `TYPE_DESCRIBE`) reads the state map.
8
9pub use oxdock_parser::{
10    Field, HANDLE_TYPE_NAME, LIST_TAG, LIST_TYPE_NAME, MAP_TAG, MAP_TYPE_NAME, OxDockType,
11    TypeDescriptor, TypeTag, Value, ValuePayload, check_value, check_value_at, clone_boxed,
12    clone_copy, clone_shared, drop_boxed, drop_noop, drop_shared, eq_boxed, eq_inline, eq_shared,
13    fmt_boxed, fmt_inline, fmt_shared, load_inline, startup_descriptors, store_inline, type_anchor,
14    unshare_boxed, unshare_inline, unshare_shared,
15};
16
17use std::collections::{HashMap, HashSet};
18
19use oxdock_diagnostics::DiagnosticResult;
20use oxdock_parser::{
21    MAX_GENERIC_DEPTH, MODULE_SEPARATOR, Spelled, SpelledField, Step, StepKind,
22    canonicalize_spelling, intern_rendered, lookup_rendered, parse_spelling, render_structural,
23};
24use oxdock_process::ProcessManager;
25
26use super::diagnostics as typing_diag;
27use super::native::AliasTargets;
28use super::state::ExecState;
29use super::state::TypeSnapshot;
30
31/// Site label for declaration-position tag validation. Single owner
32/// so resolve paths never restate the string.
33const DECLARATION_SITE: &str = "declaration";
34
35/// Single owner for bare `LIST`/`MAP`/`HANDLE` rejection. Every bare
36/// and qualified-base lookup routes here, so a new bare container
37/// spells its error once. Returns `Err` for bare containers, `Ok`
38/// otherwise.
39fn check_bare_payload(name: &str) -> DiagnosticResult<()> {
40    if name == MAP_TYPE_NAME {
41        return Err(typing_diag::typing_bare_map());
42    }
43    if name == LIST_TYPE_NAME {
44        return Err(typing_diag::typing_bare_list());
45    }
46    if name == HANDLE_TYPE_NAME {
47        return Err(typing_diag::typing_bare_handle());
48    }
49    Ok(())
50}
51
52/// Check an options map against its declared keys: unknown keys fail
53/// listing the known ones, so script typos fail fast instead of
54/// silently ignored. Shared by generated extractors and hand-built
55/// entries alike: both validate against the same `ParamOption`
56/// statics the metadata renders, so the documented keys and the
57/// enforced keys cannot drift apart. Present values check against
58/// the declared `ParamOption.value` through the single shape path,
59/// so a wrong-typed option fails here naming func, key, expected,
60/// and actual instead of deeper in the body. Absent keys pass here:
61/// defaults, coercion, and cross-key rules stay function logic.
62pub fn check_options(
63    map: &std::collections::BTreeMap<String, Value>,
64    options: &[crate::ParamOption],
65    func: &str,
66) -> DiagnosticResult<()> {
67    for key in map.keys() {
68        if !options.iter().any(|known| known.name == key) {
69            let known: Vec<&str> = options.iter().map(|known| known.name).collect();
70            return Err(typing_diag::check_unknown_option(func, key, &known));
71        }
72    }
73    for (key, value) in map.iter() {
74        let option = options
75            .iter()
76            .find(|known| known.name == *key)
77            .expect("unknown keys rejected above");
78        crate::check_value_at(&option.value, value, &format!("{func}() option '{key}'"))
79            .map_err(|err| typing_diag::check_option_value(&err))?;
80    }
81    Ok(())
82}
83
84/// Pure entry hash for the environment digest: the namespace byte
85/// names the collection (`b'a'` aliases, `b's'` schemas, `b't'`
86/// custom types), never the action. Set and removal of the same
87/// entry hash identically, so removal backs the insertion out
88/// exactly and the digest always mirrors current content.
89fn hash_env_entry(namespace: u8, name: &str, value: &str) -> u64 {
90    use std::hash::{DefaultHasher, Hasher};
91    let mut hasher = DefaultHasher::new();
92    hasher.write_u8(namespace);
93    hasher.write(name.as_bytes());
94    hasher.write(value.as_bytes());
95    hasher.finish()
96}
97
98/// Fresh name directory seeded with the startup descriptors.
99pub(super) fn startup_type_map() -> HashMap<String, super::state::HostTypeEntry> {
100    startup_descriptors()
101        .into_iter()
102        .map(|(name, descriptor)| {
103            (
104                name.to_string(),
105                super::state::HostTypeEntry {
106                    descriptor,
107                    module: String::new(),
108                },
109            )
110        })
111        .collect()
112}
113
114/// Type exports per file key from live modules: shared helper so
115/// both the associated method and static-check single-file paths
116/// read the same table without restating the loop.
117pub(crate) fn module_type_exports_map<P: ProcessManager>(
118    state: &ExecState<P>,
119) -> HashMap<String, Vec<String>> {
120    let mut out = HashMap::new();
121    for (key, record) in &state.modules {
122        out.insert(key.clone(), record.exports.types.clone());
123    }
124    out
125}
126
127/// Shared immutable scope for target-explicit type resolution: the
128/// resolving unit, its live alias targets, and the per-file
129/// type-export table. One param for the whole `*_with_targets`
130/// family instead of three restated at every hop, so the recursion
131/// stays under the argument-count lint without an `allow`.
132struct TargetScope<'a> {
133    unit: &'a str,
134    alias_targets: &'a AliasTargets,
135    exports: &'a HashMap<String, Vec<String>>,
136}
137
138impl TypeSnapshot {
139    /// Register a host-defined type descriptor (usually `T::descriptor()`
140    /// for a `#[oxdock_type]` payload). Makes the name visible to `TYPES()`
141    /// and valid for `LET $x: NAME` declarations carrying same-named
142    /// payloads. Re-registering a name returns silently when the descriptor
143    /// is identical; a different descriptor under a live name panics
144    /// instead of aliasing two layouts.
145    pub fn register_type(&mut self, descriptor: &'static TypeDescriptor) {
146        if let Some(live) = self.types.get(descriptor.name) {
147            if !std::ptr::eq(live.descriptor, descriptor) {
148                panic!(
149                    "type name `{}` already registered for a different descriptor",
150                    descriptor.name
151                );
152            }
153            return;
154        }
155        self.types.insert(
156            descriptor.name.to_string(),
157            super::state::HostTypeEntry {
158                descriptor,
159                module: String::new(),
160            },
161        );
162        self.type_env_digest ^= hash_env_entry(b't', descriptor.name, descriptor.name);
163    }
164
165    /// True when `name` names a registered type (startup or host).
166    pub fn is_known_type(&self, name: &str) -> bool {
167        self.types.contains_key(name)
168    }
169
170    /// Register a named record schema for shaped MAP bindings (usually
171    /// alongside the module that produces them). Makes the name valid
172    /// for `LET $x: NAME` declarations carrying conforming maps. A
173    /// different field table under a live name panics instead of
174    /// aliasing two shapes.
175    pub fn register_record_schema(&mut self, name: &'static str, fields: std::sync::Arc<[Field]>) {
176        if let Some(live) = self.record_schemas.get(name) {
177            if live.fields.len() != fields.len()
178                || live
179                    .fields
180                    .iter()
181                    .zip(fields.iter())
182                    .any(|(a, b)| a.name != b.name)
183            {
184                panic!("record schema `{name}` already registered with different fields");
185            }
186            return;
187        }
188        let rendered = render_structural(&TypeTag::Record(fields.clone()));
189        self.record_schemas.insert(
190            name.to_string(),
191            super::state::RecordSchemaEntry {
192                fields,
193                module: String::new(),
194            },
195        );
196        self.type_env_digest ^= hash_env_entry(b's', name, &rendered);
197    }
198
199    /// Every registered schema name, sorted. Backs discovery listings.
200    pub fn schema_names(&self) -> Vec<String> {
201        let mut names: Vec<String> = self.record_schemas.keys().cloned().collect();
202        names.sort();
203        names
204    }
205
206    /// Every script alias name, sorted. Backs discovery listings
207    /// and unknown-type errors alongside schemas.
208    pub fn alias_names(&self) -> Vec<String> {
209        let mut names: Vec<String> = self.type_aliases.keys().cloned().collect();
210        names.sort();
211        names
212    }
213
214    /// The canonical target spelling of one script alias, if defined.
215    /// Backs `TYPE_DESCRIBE` so aliases introspect like named types.
216    pub fn alias_target(&self, name: &str) -> Option<String> {
217        self.type_aliases.get(name).cloned()
218    }
219
220    /// Resolve a source-level type name to its tag: builtins by closed
221    /// match, customs through the type directory, named schemas through
222    /// the schema directory, script aliases through the alias directory,
223    /// generic spellings (`LIST<MAP>`, `MAP<name: STRING>`) rendered
224    /// structurally, and unions (`STRING|PIPE`, including inside
225    /// generics) with one interned entry per distinct spelling.
226    /// Anything else bails listing every known type, schema, and alias.
227    /// Single choke for every `LET`/`FUNC` declaration. Signature is
228    /// stable: alias cycles and shared depth accounting thread
229    /// internally, so all call sites gain generics with zero edits.
230    /// Explicit-target resolution shared by runtime and static check:
231    /// runtime passes `unit_alias_targets`, static passes
232    /// `effective_alias_targets` (unit-top plus walk frames). Single
233    /// owner for the bare/qualified split so the twins cannot drift.
234    /// Pure query over a closure snapshot for LSP hover and completion.
235    pub fn resolve_tag_with_targets(
236        &self,
237        unit: &str,
238        alias_targets: &AliasTargets,
239        exports: &HashMap<String, Vec<String>>,
240        name: &str,
241    ) -> DiagnosticResult<TypeTag> {
242        let canonical = canonicalize_spelling(name);
243        let scope = TargetScope {
244            unit,
245            alias_targets,
246            exports,
247        };
248        if canonical.contains('<') || canonical.contains('|') {
249            return self.resolve_spelling_with_targets(&scope, &canonical, &mut Vec::new(), 0);
250        }
251        self.resolve_named_with_targets(&scope, &canonical, &mut Vec::new(), 0)
252    }
253
254    /// Host-owned tag for `HM::T`: builtins always, plus the named
255    /// custom or schema when its entry module matches `host` or is
256    /// empty. Empty module means global registration (`register_type`,
257    /// startup descriptors): globally visible, so any host alias may
258    /// serve it. A non-empty foreign module never leaks across hosts.
259    /// Ownership lives on the descriptor entry, never a side map.
260    /// Single owner for host-module attribution: qualified reads and
261    /// harvest roots both run here.
262    pub(super) fn host_owned_tag_free(&self, host: &str, name: &str) -> Option<TypeTag> {
263        if let Some(tag) = TypeTag::builtin(name) {
264            return Some(tag);
265        }
266        if let Some(entry) = self.types.get(name) {
267            if entry.module == host || entry.module.is_empty() {
268                return Some(TypeTag::Custom(entry.descriptor));
269            }
270            return None;
271        }
272        if let Some(entry) = self.record_schemas.get(name) {
273            if entry.module == host || entry.module.is_empty() {
274                return Some(TypeTag::Record(entry.fields.clone()));
275            }
276            return None;
277        }
278        None
279    }
280
281    /// Bare global lookup: builtins, host customs, record schemas.
282    /// Single owner for this prefix so scoped and legacy paths plus
283    /// the clean resolver never restate it. Returns the raw tag;
284    /// callers run `check_tag_known` for records.
285    fn bare_builtin_host_schema(&self, name: &str) -> Option<TypeTag> {
286        if let Some(tag) = TypeTag::builtin(name) {
287            return Some(tag);
288        }
289        if let Some(entry) = self.types.get(name) {
290            return Some(TypeTag::Custom(entry.descriptor));
291        }
292        if let Some(entry) = self.record_schemas.get(name) {
293            return Some(TypeTag::Record(entry.fields.clone()));
294        }
295        None
296    }
297
298    /// Qualified `ALIAS::BASE` through the active `AliasTargets`:
299    /// every target exporting `BASE` contributes its tag plus guard;
300    /// 0 matches unknown, 1 returns, same-shape collapses, distinct
301    /// shapes are ambiguous regardless of guards: types never degrade
302    /// to `Any`, so platform-conditional branches must agree on shape.
303    fn resolve_qualified_frozen(
304        &self,
305        scope: &TargetScope<'_>,
306        alias: &str,
307        base: &str,
308    ) -> DiagnosticResult<TypeTag> {
309        let Some(entries) = scope.alias_targets.get(alias) else {
310            return Err(typing_diag::typing_unknown(
311                &format!(
312                    "{}{MODULE_SEPARATOR}{alias}{MODULE_SEPARATOR}{base}",
313                    scope.unit
314                ),
315                &self.type_names(),
316                &self.schema_names(),
317                &self.alias_names(),
318            ));
319        };
320        let mut matches: Vec<(TypeTag, Option<oxdock_parser::GuardExpr>)> = Vec::new();
321        for target in entries {
322            if let Some(fkey) = &target.file {
323                let is_exported = scope
324                    .exports
325                    .get(fkey)
326                    .is_some_and(|v| v.iter().any(|e| e == base));
327                if !is_exported {
328                    continue;
329                }
330                if let Some(tag) = self
331                    .type_registry
332                    .units
333                    .get(fkey)
334                    .and_then(|m| m.get(base))
335                    .cloned()
336                {
337                    matches.push((tag, target.guard.clone()));
338                    continue;
339                }
340                // Exported but absent from the unit table: a broken
341                // export with no local definition. The parser gates
342                // `EXPORT TYPE` on a local `TYPE`, so no re-export path
343                // exists here; fail closed instead of consulting another
344                // unit's harvests.
345                return Err(typing_diag::typing_unknown(
346                    &format!(
347                        "{}{MODULE_SEPARATOR}{alias}{MODULE_SEPARATOR}{base}",
348                        scope.unit
349                    ),
350                    &self.type_names(),
351                    &self.schema_names(),
352                    &self.alias_names(),
353                ));
354            } else if let Some(host) = &target.host
355                && let Some(tag) = self.host_owned_tag_free(host, base)
356            {
357                matches.push((tag, target.guard.clone()));
358            }
359        }
360        if matches.is_empty() {
361            return Err(typing_diag::typing_unknown(
362                &format!(
363                    "{}{MODULE_SEPARATOR}{alias}{MODULE_SEPARATOR}{base}",
364                    scope.unit
365                ),
366                &self.type_names(),
367                &self.schema_names(),
368                &self.alias_names(),
369            ));
370        }
371        let first = render_structural(&matches[0].0);
372        if matches.iter().all(|(t, _)| render_structural(t) == first) {
373            return Ok(matches.into_iter().next().expect("nonempty checked").0);
374        }
375        // Distinct shapes never degrade to `Any`: no escape hatch for
376        // types. Guards decide which branch runs, never what the name
377        // means, so disjoint distinct shapes fail exactly like
378        // overlapping ones.
379        Err(typing_diag::typing_ambiguous(alias, base))
380    }
381
382    /// Resolve one bare name through the frozen registry: unit table,
383    /// that unit's harvested imports, builtins and global host types.
384    /// When no table covers the unit (direct API without a closure),
385    /// falls back to the legacy global alias directory.
386    fn resolve_bare_frozen(
387        &self,
388        scope: &TargetScope<'_>,
389        name: &str,
390        resolving: &mut Vec<String>,
391        depth: usize,
392    ) -> DiagnosticResult<TypeTag> {
393        if depth > MAX_GENERIC_DEPTH {
394            return Err(typing_diag::typing_max_depth(MAX_GENERIC_DEPTH, name));
395        }
396        check_bare_payload(name)?;
397        if let Some(tag) = self
398            .type_registry
399            .units
400            .get(scope.unit)
401            .and_then(|m| m.get(name))
402            .cloned()
403        {
404            return Ok(tag);
405        }
406        if let Some(tag) = self
407            .type_registry
408            .harvested
409            .get(scope.unit)
410            .and_then(|m| m.get(name))
411            .cloned()
412        {
413            return Ok(tag);
414        }
415        if self.type_registry.units.contains_key(scope.unit) {
416            if let Some(tag) = self.bare_builtin_host_schema(name) {
417                if matches!(tag, TypeTag::Record(_)) {
418                    self.check_tag_known(DECLARATION_SITE, &tag, false)?;
419                }
420                return Ok(tag);
421            }
422            // Tables built: file-private aliases stay per unit, never
423            // global. Qualified handled by caller; bare misses here.
424            return Err(typing_diag::typing_unknown(
425                name,
426                &self.type_names(),
427                &self.schema_names(),
428                &self.alias_names(),
429            ));
430        }
431        // No table: legacy single-file path with global aliases.
432        if let Some(tag) = self.bare_builtin_host_schema(name) {
433            if matches!(tag, TypeTag::Record(_)) {
434                self.check_tag_known(DECLARATION_SITE, &tag, false)?;
435            }
436            return Ok(tag);
437        }
438        if let Some(target) = self.type_aliases.get(name).cloned() {
439            if resolving.iter().any(|s| s.as_str() == name) {
440                resolving.push(name.to_string());
441                return Err(typing_diag::alias_cycle(resolving));
442            }
443            resolving.push(name.to_string());
444            let out = self.resolve_spelling_with_targets(scope, &target, resolving, depth + 1);
445            resolving.pop();
446            return out;
447        }
448        Err(typing_diag::typing_unknown(
449            name,
450            &self.type_names(),
451            &self.schema_names(),
452            &self.alias_names(),
453        ))
454    }
455
456    /// Resolve one bare or qualified leaf through the frozen tables.
457    /// Alias targets loop back through the spelling path, so
458    /// `LIST<PERSON>` combines; each alias hop costs 1 of the shared
459    /// depth budget and repeats bail naming the cycle.
460    fn resolve_named_with_targets(
461        &self,
462        scope: &TargetScope<'_>,
463        name: &str,
464        resolving: &mut Vec<String>,
465        depth: usize,
466    ) -> DiagnosticResult<TypeTag> {
467        if depth > MAX_GENERIC_DEPTH {
468            return Err(typing_diag::typing_max_depth(MAX_GENERIC_DEPTH, name));
469        }
470        if let Some((alias, base)) = name.split_once(MODULE_SEPARATOR) {
471            // Bare LIST/MAP/HANDLE never qualified: reject like bare.
472            check_bare_payload(base)?;
473            return self.resolve_qualified_frozen(scope, alias, base);
474        }
475        self.resolve_bare_frozen(scope, name, resolving, depth)
476    }
477
478    /// Resolve one canonical spelling that may carry `<...>` args.
479    /// Frozen units never touch the process-global intern table:
480    /// that table keys on spelling plus run digest only, so one
481    /// unit's `LIST<INNER>` would poison another unit (or another
482    /// function-local `IMPORT` frame) sharing the spelling. Scoped
483    /// resolution builds fresh tags per call instead; the legacy
484    /// single-file path (empty registry) keeps interning.
485    fn resolve_spelling_with_targets(
486        &self,
487        scope: &TargetScope<'_>,
488        canonical: &str,
489        resolving: &mut Vec<String>,
490        depth: usize,
491    ) -> DiagnosticResult<TypeTag> {
492        if !self.type_registry.units.is_empty() {
493            let spelled = parse_spelling(canonical)?;
494            return self.build_rendered_with_targets(scope, &spelled, resolving, depth);
495        }
496        let key = format!("{}\x1f{:016x}", canonical, self.type_env_digest);
497        if let Some(hit) = lookup_rendered(&key) {
498            return Ok(hit);
499        }
500        let spelled = parse_spelling(canonical)?;
501        let tag = self.build_rendered_with_targets(scope, &spelled, resolving, depth)?;
502        Ok(intern_rendered(key, tag))
503    }
504
505    /// Record one alias binding, folding it into the digest. An
506    /// overwrite backs the old target out before mixing the new one
507    /// in, so the digest always mirrors current content; identical
508    /// re-registration folds nothing, so re-importing the same file
509    /// shares cache entries instead of forking them.
510    pub(super) fn register_alias(&mut self, name: String, target: String) {
511        if let Some(old) = self.type_aliases.insert(name.clone(), target.clone()) {
512            if old == target {
513                return;
514            }
515            self.type_env_digest ^= hash_env_entry(b'a', &name, &old);
516        }
517        self.type_env_digest ^= hash_env_entry(b'a', &name, &target);
518    }
519
520    /// Drop one alias binding, backing its hash out of the digest.
521    /// Absent names change nothing and fold nothing.
522    pub(super) fn remove_alias(&mut self, name: &str) {
523        if let Some(old) = self.type_aliases.remove(name) {
524            self.type_env_digest ^= hash_env_entry(b'a', name, &old);
525        }
526    }
527
528    /// Replace the whole alias directory (save/restore paths). Backs
529    /// the entire current directory out and mixes the entire next
530    /// one in: swaps are bounded and infrequent next to lookups, and
531    /// the digest stays an exact mirror of content either way.
532    pub(super) fn restore_aliases(&mut self, next: HashMap<String, String>) {
533        for (name, target) in &self.type_aliases {
534            self.type_env_digest ^= hash_env_entry(b'a', name, target);
535        }
536        for (name, target) in &next {
537            self.type_env_digest ^= hash_env_entry(b'a', name, target);
538        }
539        self.type_aliases = next;
540    }
541
542    /// Target-explicit rendering shared by runtime and static check.
543    fn build_rendered_with_targets(
544        &self,
545        scope: &TargetScope<'_>,
546        spelled: &Spelled,
547        resolving: &mut Vec<String>,
548        depth: usize,
549    ) -> DiagnosticResult<TypeTag> {
550        if depth > MAX_GENERIC_DEPTH {
551            return Err(typing_diag::typing_max_depth_spelled(
552                MAX_GENERIC_DEPTH,
553                spelled,
554            ));
555        }
556        match spelled {
557            Spelled::Named(name) => self.resolve_named_with_targets(scope, name, resolving, depth),
558            Spelled::Generic { name, args } => {
559                self.build_generic_with_targets(scope, name, args, resolving, depth)
560            }
561            Spelled::Union(members) => {
562                let mut resolved = Vec::with_capacity(members.len());
563                for member in members {
564                    resolved
565                        .push(self.build_rendered_with_targets(scope, member, resolving, depth)?);
566                }
567                Ok(finish_union(resolved)?)
568            }
569        }
570    }
571
572    /// Target-explicit generic builder shared by runtime and static.
573    #[allow(clippy::disallowed_methods)]
574    fn build_generic_with_targets(
575        &self,
576        scope: &TargetScope<'_>,
577        name: &str,
578        args: &[SpelledField],
579        resolving: &mut Vec<String>,
580        depth: usize,
581    ) -> DiagnosticResult<TypeTag> {
582        // Qualified `ALIAS::BASE` heads never build builtins and never
583        // strip `ALIAS` blindly. Multi-separator names fail unknown;
584        // `LIST`/`MAP`/`HANDLE` heads resolve to name the real problem
585        // then fail `no_args`: file-owned `BASE` is a custom type taking
586        // no args, and host aliases never own builtin constructors, so
587        // the bare `LIST<...>` spelling is the only builder. Single
588        // owner with `CleanResolver::resolve_spelled` below.
589        if let Some((_alias, base)) = name.split_once(MODULE_SEPARATOR) {
590            if base.contains(MODULE_SEPARATOR) {
591                return Err(typing_diag::typing_unknown(
592                    name,
593                    &self.type_names(),
594                    &self.schema_names(),
595                    &self.alias_names(),
596                ));
597            }
598            self.resolve_named_with_targets(scope, name, resolving, depth)?;
599            return Err(typing_diag::typing_no_args(name));
600        }
601        if name != LIST_TYPE_NAME && name != MAP_TYPE_NAME && name != HANDLE_TYPE_NAME {
602            self.resolve_named_with_targets(scope, name, resolving, depth)?;
603            return Err(typing_diag::typing_no_args(name));
604        }
605        if name == HANDLE_TYPE_NAME {
606            let [
607                SpelledField {
608                    name: None,
609                    ty: payload,
610                    ..
611                },
612            ] = args
613            else {
614                return Err(typing_diag::typing_handle_arity());
615            };
616            let payload = self.build_rendered_with_targets(scope, payload, resolving, depth + 1)?;
617            return Ok(TypeTag::HandleOf(std::sync::Arc::new(payload)));
618        }
619        if name == LIST_TYPE_NAME {
620            let [
621                SpelledField {
622                    name: None,
623                    ty: element,
624                    ..
625                },
626            ] = args
627            else {
628                return Err(typing_diag::typing_list_arity());
629            };
630            let element = self.build_rendered_with_targets(scope, element, resolving, depth + 1)?;
631            return Ok(TypeTag::ListOf(std::sync::Arc::new(element)));
632        }
633        if name == MAP_TYPE_NAME
634            && let [
635                SpelledField {
636                    name: None,
637                    ty: inner,
638                    ..
639                },
640            ] = args
641        {
642            // Homogeneous map: a single bare value type (`MAP<INT>`,
643            // `MAP<STRING>`, `MAP<ANY>`) is the unknown-key map with
644            // that value type. Named `name: TYPE` fields still build
645            // records below; plain `MAP` never resolves.
646            let value_tag = self.build_rendered_with_targets(scope, inner, resolving, depth + 1)?;
647            return Ok(TypeTag::MapOf(std::sync::Arc::new(value_tag)));
648        }
649        let mut fields = Vec::with_capacity(args.len());
650        for arg in args {
651            let Some(field_name) = arg.name.as_ref() else {
652                return Err(typing_diag::typing_map_bare(name));
653            };
654            let ty = self.build_rendered_with_targets(scope, &arg.ty, resolving, depth + 1)?;
655            let default = match &arg.default {
656                None => None,
657                Some(lit) => {
658                    let value = lit.to_value();
659                    check_value(&ty, &value).map_err(|_| {
660                        typing_diag::typing_default_mismatch(
661                            field_name,
662                            &oxdock_parser::render_structural(&ty),
663                        )
664                    })?;
665                    Some(value)
666                }
667            };
668            fields.push(Field {
669                name: field_name.clone(),
670                ty,
671                docs: "",
672                optional: arg.optional,
673                default,
674                alias: arg.alias.clone(),
675            });
676        }
677        // Alias uniqueness: one spelling maps to one field. Canonical
678        // names and aliases share one namespace, so a clash fails here
679        // naming both sides instead of shadowing at parse time.
680        // Owner: typing. Single constructors, stable keys, no ad hoc
681        // strings at call sites.
682        {
683            use std::collections::HashMap;
684            let mut seen: HashMap<&str, &str> = HashMap::new();
685            for field in &fields {
686                if let Some(prev) = seen.insert(field.name.as_str(), field.name.as_str()) {
687                    let _ = prev;
688                    return Err(typing_diag::map_duplicate_field(&field.name));
689                }
690                if let Some(alias) = field.alias.as_ref() {
691                    if alias == &field.name {
692                        return Err(typing_diag::alias_self(&field.name, alias));
693                    }
694                    if let Some(owner) = seen.insert(alias.as_str(), field.name.as_str()) {
695                        return Err(typing_diag::alias_clash(alias, &field.name, owner));
696                    }
697                }
698            }
699        }
700        Ok(TypeTag::Record(std::sync::Arc::from(fields)))
701    }
702}
703
704/// Normalize resolved union members into one tag: flatten nested
705/// unions, absorb on `ANY`, deduplicate, collapse lone survivors.
706/// Members keep written order while every comparison stays
707/// order-free, so all spellings behave identically. The tag owns
708/// everything through `Arc`: shared on clone, freed with the last
709/// owner, never leaked.
710fn finish_union(members: Vec<TypeTag>) -> DiagnosticResult<TypeTag> {
711    let mut flat: Vec<TypeTag> = Vec::with_capacity(members.len());
712    for member in members {
713        // Nested unions splice flat: members never nest, so every
714        // comparison stays one level deep by construction.
715        if let TypeTag::Union(_, nested) = member {
716            flat.extend(nested.iter().cloned());
717        } else {
718            flat.push(member);
719        }
720    }
721    if flat.is_empty() {
722        return Err(typing_diag::typing_empty_union());
723    }
724    // `ANY` absorbs the set: admitting everything is `ANY`.
725    if flat.iter().any(|member| matches!(member, TypeTag::Any)) {
726        return Ok(TypeTag::Any);
727    }
728    // Full (not just consecutive) deduplication: order-free
729    // comparisons make every permutation behave identically.
730    let mut unique: Vec<TypeTag> = Vec::with_capacity(flat.len());
731    for member in flat {
732        if !unique
733            .iter()
734            .any(|seen| super::static_check::tags_equal(seen, &member))
735        {
736            unique.push(member);
737        }
738    }
739    if unique.len() == 1 {
740        return Ok(unique.pop().expect("single survivor checked above"));
741    }
742    Ok(TypeTag::union(unique))
743}
744
745/// Collect top-level `TYPE` alias definitions into the run's
746/// alias directory: name to canonical target spelling. Runs
747/// before the static pass so forward references resolve
748/// run-wide. Duplicates and collisions with builtin, host,
749/// schema, and top-level `FUNC` names are static errors
750/// naming the offender. Nested `TYPE` steps cannot occur
751/// (the parser rejects them); hand-built ones never resolve.
752/// Takes only the snapshot so LSP builds aliases without an
753/// `ExecState`.
754pub fn collect_type_aliases(
755    steps: &[Step],
756    type_env: &TypeSnapshot,
757) -> DiagnosticResult<HashMap<String, String>> {
758    let mut func_names = HashSet::new();
759    for step in steps {
760        if let StepKind::FuncDef { name, .. } = &step.kind {
761            func_names.insert(name.clone());
762        }
763    }
764    let mut aliases = HashMap::new();
765    for step in steps {
766        let StepKind::TypeAlias { name, target } = &step.kind else {
767            continue;
768        };
769        if aliases.contains_key(name) {
770            return Err(typing_diag::alias_already_defined(name));
771        }
772        if TypeTag::builtin(name).is_some() {
773            return Err(typing_diag::alias_builtin_collision(name));
774        }
775        if type_env.types.contains_key(name) {
776            return Err(typing_diag::alias_host_collision(name));
777        }
778        if type_env.record_schemas.contains_key(name) {
779            return Err(typing_diag::alias_schema_collision(name));
780        }
781        if func_names.contains(name) {
782            return Err(typing_diag::alias_func_collision(name));
783        }
784        aliases.insert(name.clone(), canonicalize_spelling(target));
785    }
786    Ok(aliases)
787}
788
789/// One bare `IMPORT [TYPE T FROM "file"]` harvest request: the
790/// importing unit, the defining file key and the host module name
791/// (`None` for file harvests, `Some` for host harvests; exactly one
792/// is set). Bare names collide closure-wide across units (mirroring the
793/// runtime bare-global merge) while resolution stays per importing unit.
794pub struct HarvestRequest {
795    pub importer: String,
796    pub defining: Option<String>,
797    pub host: Option<String>,
798    pub name: String,
799}
800
801/// Clean per-unit resolver: resolves a bare name in its defining
802/// unit's namespace (locals plus that unit's own qualified imports
803/// plus harvested globals plus host/builtins), never caller entries.
804/// Stores `TypeTag` directly so defaults and field aliases survive.
805/// Every failure propagates: broken exports fail the closure even
806/// when unused, so no dead code hides a bad shape.
807struct CleanResolver<'a> {
808    state: &'a TypeSnapshot,
809    raw_bare: &'a HashMap<String, HashMap<String, String>>,
810    targets: &'a HashMap<String, super::native::AliasTargets>,
811    exports: &'a HashMap<String, Vec<String>>,
812    harvests: HashMap<(String, String), (Option<String>, Option<String>)>,
813    bare_cache: HashMap<(String, String), TypeTag>,
814    stack: Vec<(String, String)>,
815    harvested: HashMap<(String, String), TypeTag>,
816}
817
818impl<'a> CleanResolver<'a> {
819    fn builtin_or_host(&self, name: &str) -> Option<TypeTag> {
820        // Bare LIST/MAP/HANDLE never resolve here: they need payloads.
821        // Returning them would let `TYPE H = HANDLE` slip through the
822        // per-unit tables and pass the declaration gate later.
823        if check_bare_payload(name).is_err() {
824            return None;
825        }
826        self.state.bare_builtin_host_schema(name)
827    }
828
829    /// Host-owned tag for the resolver: the shared
830    /// [`TypeSnapshot::host_owned_tag_free`] rule, minus bare
831    /// `LIST`/`MAP`/`HANDLE`, which need payloads and fail with their
832    /// declaration errors instead of resolving here.
833    fn host_owned_tag(&self, host: &str, name: &str) -> Option<TypeTag> {
834        // Bare LIST/MAP/HANDLE need payloads: fail with the
835        // declaration error downstream instead of resolving here.
836        if check_bare_payload(name).is_err() {
837            return None;
838        }
839        self.state.host_owned_tag_free(host, name)
840    }
841
842    /// Resolve one bare harvest request in its home namespace:
843    /// file harvests resolve in the defining file (recursing through
844    /// further harvests with cycle detection). Host harvests resolve
845    /// through the shared host-ownership rule, so `HOST_A` can never
846    /// lift a type owned by `HOST_B`, while empty-module (global)
847    /// registrations stay visible everywhere. Single owner for
848    /// harvest roots: the build pre-pass and the on-demand use-site
849    /// path both run here, so eager and lazy harvests cannot drift.
850    /// Anything unresolvable fails closed.
851    fn harvest_tag(
852        &mut self,
853        defining: &Option<String>,
854        host: &Option<String>,
855        name: &str,
856    ) -> DiagnosticResult<TypeTag> {
857        if let Some(fkey) = defining {
858            // Export gate: a bare harvest only serves exported types,
859            // mirroring the runtime import gate. Unexported names fail
860            // closed here instead of leaking file-private aliases.
861            let exported = self
862                .exports
863                .get(fkey)
864                .is_some_and(|v| v.iter().any(|e| e == name));
865            if !exported {
866                return Err(typing_diag::typing_unknown(
867                    name,
868                    &self.state.type_names(),
869                    &self.state.schema_names(),
870                    &self.state.alias_names(),
871                ));
872            }
873            return self.resolve_bare(fkey, name);
874        }
875        if let Some(host_name) = host
876            && let Some(tag) = self.host_owned_tag(host_name, name)
877        {
878            return Ok(tag);
879        }
880        // No defining file and no owning host answers: fail closed.
881        // (Unresolvable bare harvest lines with no referencing
882        // definition never reach here; the runtime import gate reports
883        // those naming the host.)
884        Err(typing_diag::typing_unknown(
885            name,
886            &self.state.type_names(),
887            &self.state.schema_names(),
888            &self.state.alias_names(),
889        ))
890    }
891
892    fn resolve_bare(&mut self, unit: &str, name: &str) -> DiagnosticResult<TypeTag> {
893        let key = (unit.to_string(), name.to_string());
894        if let Some(hit) = self.bare_cache.get(&key) {
895            return Ok(hit.clone());
896        }
897        if self.stack.iter().any(|(u, n)| u == unit && n == name) {
898            let mut chain: Vec<String> = self
899                .stack
900                .iter()
901                .map(|(u, n)| format!("{u}{MODULE_SEPARATOR}{n}"))
902                .collect();
903            chain.push(format!("{unit}{MODULE_SEPARATOR}{name}"));
904            return Err(typing_diag::alias_cycle(&chain));
905        }
906        if let Some(target) = self.raw_bare.get(unit).and_then(|m| m.get(name)).cloned() {
907            self.stack.push((unit.to_string(), name.to_string()));
908            let spelled = parse_spelling(&target)?;
909            let out = self.resolve_spelled(unit, &spelled, 0);
910            self.stack.pop();
911            let tag = out?;
912            self.bare_cache.insert(key, tag.clone());
913            return Ok(tag);
914        }
915        if let Some(tag) = self.harvested.get(&key).cloned() {
916            return Ok(tag);
917        }
918        // Bare harvests resolve on demand in the importing unit's
919        // namespace (single pass: no build-then-lift-then-rebuild).
920        // Cycles thread through `self.stack` like every other alias
921        // hop; genuinely unknown names fail closed below with zero
922        // suppression. Harvests stay per-unit, so one file's bare
923        // import never leaks into a sibling.
924        if let Some((defining, host)) = self.harvests.get(&key).cloned() {
925            self.stack.push((unit.to_string(), name.to_string()));
926            let out = self.harvest_tag(&defining, &host, name);
927            self.stack.pop();
928            let tag = out?;
929            self.harvested.insert(key.clone(), tag.clone());
930            return Ok(tag);
931        }
932        // Bare LIST/MAP/HANDLE need payloads: fail here with the
933        // declaration error so `TYPE H = HANDLE` names the rule
934        // instead of falling through to `unknown type`.
935        check_bare_payload(name)?;
936        if let Some(tag) = self.builtin_or_host(name) {
937            // Bare host/builtins are global; collapsing across units is
938            // intended (they are not file-private). Every composite
939            // tag validates like the frozen path, so unknown nested
940            // customs fail here instead of slipping through.
941            self.state.check_tag_known(DECLARATION_SITE, &tag, false)?;
942            return Ok(tag);
943        }
944        // Missing bare name fails closed here; the closure propagates
945        // it even when unused, so no broken export hides. Cycles use
946        // `alias_cycle` above and propagate the same way.
947        Err(typing_diag::typing_unknown(
948            &format!("{unit}{MODULE_SEPARATOR}{name}"),
949            &self.state.type_names(),
950            &self.state.schema_names(),
951            &self.state.alias_names(),
952        ))
953    }
954
955    fn resolve_spelled(
956        &mut self,
957        unit: &str,
958        spelled: &Spelled,
959        depth: usize,
960    ) -> DiagnosticResult<TypeTag> {
961        if depth > MAX_GENERIC_DEPTH {
962            return Err(typing_diag::typing_max_depth_spelled(
963                MAX_GENERIC_DEPTH,
964                spelled,
965            ));
966        }
967        match spelled {
968            Spelled::Named(name) => {
969                if let Some((alias, base)) = name.split_once(MODULE_SEPARATOR) {
970                    self.resolve_qualified(unit, alias, base)
971                } else {
972                    self.resolve_bare(unit, name)
973                }
974            }
975            Spelled::Generic { name, args } => {
976                if name == LIST_TYPE_NAME {
977                    let [field] = args.as_slice() else {
978                        return Err(typing_diag::typing_list_arity());
979                    };
980                    if field.name.is_some() {
981                        return Err(typing_diag::typing_list_arity());
982                    }
983                    let inner = self.resolve_spelled(unit, &field.ty, depth + 1)?;
984                    return Ok(TypeTag::ListOf(std::sync::Arc::new(inner)));
985                }
986                if name == HANDLE_TYPE_NAME {
987                    let [field] = args.as_slice() else {
988                        return Err(typing_diag::typing_handle_arity());
989                    };
990                    if field.name.is_some() {
991                        return Err(typing_diag::typing_handle_arity());
992                    }
993                    let inner = self.resolve_spelled(unit, &field.ty, depth + 1)?;
994                    return Ok(TypeTag::HandleOf(std::sync::Arc::new(inner)));
995                }
996                if name == MAP_TYPE_NAME {
997                    if let [field] = args.as_slice()
998                        && field.name.is_none()
999                    {
1000                        let inner = self.resolve_spelled(unit, &field.ty, depth + 1)?;
1001                        return Ok(TypeTag::MapOf(std::sync::Arc::new(inner)));
1002                    }
1003                    let mut fields = Vec::with_capacity(args.len());
1004                    for arg in args {
1005                        let Some(fname) = arg.name.as_ref() else {
1006                            return Err(typing_diag::typing_map_bare(name));
1007                        };
1008                        let ty = self.resolve_spelled(unit, &arg.ty, depth + 1)?;
1009                        let default = match &arg.default {
1010                            None => None,
1011                            Some(lit) => {
1012                                let v = lit.to_value();
1013                                check_value(&ty, &v).map_err(|_| {
1014                                    typing_diag::typing_default_mismatch(
1015                                        fname,
1016                                        &render_structural(&ty),
1017                                    )
1018                                })?;
1019                                Some(v)
1020                            }
1021                        };
1022                        fields.push(Field {
1023                            name: fname.clone(),
1024                            ty,
1025                            docs: "",
1026                            optional: arg.optional,
1027                            default,
1028                            alias: arg.alias.clone(),
1029                        });
1030                    }
1031                    // Alias uniqueness mirrors `build_rendered`.
1032                    {
1033                        use std::collections::HashSet;
1034                        let mut seen = HashSet::new();
1035                        for f in &fields {
1036                            if !seen.insert(f.name.clone()) {
1037                                return Err(typing_diag::alias_func_collision(&f.name));
1038                            }
1039                            if let Some(a) = &f.alias
1040                                && !seen.insert(a.clone())
1041                            {
1042                                return Err(typing_diag::alias_func_collision(a));
1043                            }
1044                        }
1045                    }
1046                    return Ok(TypeTag::Record(std::sync::Arc::from(fields)));
1047                }
1048                // Any other head resolves to name the real problem.
1049                // Qualified heads never strip `ALIAS` blindly and never
1050                // build builtins: multi-separator names fail unknown, and
1051                // `LIST`/`MAP`/`HANDLE` heads resolve to name the real
1052                // problem then fail `no_args`. Host aliases never own
1053                // builtin constructors, so bare `LIST<...>` is the only
1054                // builder. Single owner with
1055                // `ExecState::build_generic_with_targets` above.
1056                if let Some((alias, base)) = name.split_once(MODULE_SEPARATOR) {
1057                    if base.contains(MODULE_SEPARATOR) {
1058                        return Err(typing_diag::typing_unknown(
1059                            name,
1060                            &self.state.type_names(),
1061                            &self.state.schema_names(),
1062                            &self.state.alias_names(),
1063                        ));
1064                    }
1065                    let _ = self.resolve_qualified(unit, alias, base)?;
1066                    return Err(typing_diag::typing_no_args(name));
1067                }
1068                let _ = self.resolve_bare(unit, name)?;
1069                Err(typing_diag::typing_no_args(name))
1070            }
1071            Spelled::Union(members) => {
1072                let mut out = Vec::with_capacity(members.len());
1073                for m in members {
1074                    out.push(self.resolve_spelled(unit, m, depth)?);
1075                }
1076                finish_union(out)
1077            }
1078        }
1079    }
1080
1081    fn resolve_qualified(
1082        &mut self,
1083        importer_unit: &str,
1084        alias: &str,
1085        base: &str,
1086    ) -> DiagnosticResult<TypeTag> {
1087        let targets = self.targets.get(importer_unit);
1088        let Some(entries) = targets.and_then(|m| m.get(alias)) else {
1089            return Err(typing_diag::typing_unknown(
1090                &format!("{importer_unit}{MODULE_SEPARATOR}{alias}{MODULE_SEPARATOR}{base}"),
1091                &self.state.type_names(),
1092                &self.state.schema_names(),
1093                &self.state.alias_names(),
1094            ));
1095        };
1096        // Collect every target exporting FOO: 0 matches unknown,
1097        // 1 match returns, same-shape collapses, distinct shapes are
1098        // ambiguous regardless of guards (no `Any` escape hatch for
1099        // types). Every failure propagates: no poison, no silent
1100        // skips, so broken exports fail the closure even when unused.
1101        // Same-shape matches collapse regardless of guards.
1102        let mut matches: Vec<(TypeTag, Option<oxdock_parser::GuardExpr>)> = Vec::new();
1103        for target in entries {
1104            if let Some(fkey) = &target.file {
1105                let exported = self.exports.get(fkey);
1106                let is_exported = exported.is_some_and(|v| v.iter().any(|e| e == base));
1107                if !is_exported {
1108                    continue;
1109                }
1110                let tag = self.resolve_bare(fkey, base)?;
1111                matches.push((tag, target.guard.clone()));
1112            } else if let Some(host) = &target.host
1113                && let Some(tag) = self.host_owned_tag(host, base)
1114            {
1115                matches.push((tag, target.guard.clone()));
1116            }
1117        }
1118        if matches.is_empty() {
1119            return Err(typing_diag::typing_unknown(
1120                &format!("{importer_unit}{MODULE_SEPARATOR}{alias}{MODULE_SEPARATOR}{base}"),
1121                &self.state.type_names(),
1122                &self.state.schema_names(),
1123                &self.state.alias_names(),
1124            ));
1125        }
1126        // Same shape everywhere: one tag regardless of guards.
1127        let first_render = render_structural(&matches[0].0);
1128        if matches
1129            .iter()
1130            .all(|(tag, _)| render_structural(tag) == first_render)
1131        {
1132            return Ok(matches.into_iter().next().expect("nonempty checked").0);
1133        }
1134        // Distinct shapes never degrade to `Any`: no escape hatch for
1135        // types. Guards decide which branch runs, never what the name
1136        // means, so disjoint distinct shapes fail exactly like
1137        // overlapping ones.
1138        Err(typing_diag::typing_ambiguous(alias, base))
1139    }
1140}
1141
1142/// Frozen per-unit type registry: each unit's bare names resolve to
1143/// `TypeTag` directly in the defining file's namespace (never the
1144/// importer's), preserving defaults and field aliases without string
1145/// round-tripping. Built once per closure in a single pass:
1146/// `harvests` lets bare `IMPORT [TYPE T FROM "f"]` names resolve on
1147/// demand in their defining file's namespace, so no
1148/// build-then-lift-then-rebuild race. Qualified `ALIAS::NAME`
1149/// resolves on demand through live `AliasTargets`, never from a
1150/// precomputed table. Every failure propagates: broken exports fail
1151/// the closure even when unused, so no dead code hides a bad shape.
1152fn describe_harvest_source(defining: &Option<String>, host: &Option<String>) -> String {
1153    if let Some(defining) = defining {
1154        defining.clone()
1155    } else if let Some(host) = host {
1156        host.clone()
1157    } else {
1158        String::new()
1159    }
1160}
1161
1162/// Build per-unit bare tables directly on a snapshot so LSP can
1163/// construct type environments without an `ExecState`.
1164pub fn build_unit_tables(
1165    type_env: &mut TypeSnapshot,
1166    raw_bare: &HashMap<String, HashMap<String, String>>,
1167    targets: &HashMap<String, super::native::AliasTargets>,
1168    exports: &HashMap<String, Vec<String>>,
1169    harvests: &[HarvestRequest],
1170) -> DiagnosticResult<()> {
1171    let mut bare_tags: HashMap<String, HashMap<String, TypeTag>> = HashMap::new();
1172    // Bare namespace is global at runtime (`type_aliases` merges bare
1173    // harvests globally, collision-checked). Static mirrors that: the
1174    // same bare name from distinct sources collides closure-wide,
1175    // even across units. Resolution stays per-unit below so qualified
1176    // reads never leak through unrelated harvests.
1177    let mut harvest_sources: HashMap<String, (Option<String>, Option<String>)> = HashMap::new();
1178    for req in harvests {
1179        match harvest_sources.get(&req.name) {
1180            None => {
1181                harvest_sources.insert(req.name.clone(), (req.defining.clone(), req.host.clone()));
1182            }
1183            Some((defining, host)) if defining == &req.defining && host == &req.host => {
1184                // Same source harvested twice: idempotent.
1185            }
1186            Some((defining, host)) => {
1187                return Err(typing_diag::typing_harvest_collision(
1188                    &req.name,
1189                    &describe_harvest_source(defining, host),
1190                    &describe_harvest_source(&req.defining, &req.host),
1191                ));
1192            }
1193        }
1194    }
1195    let mut harvest_map: HashMap<(String, String), (Option<String>, Option<String>)> =
1196        HashMap::new();
1197    for req in harvests {
1198        harvest_map.insert(
1199            (req.importer.clone(), req.name.clone()),
1200            (req.defining.clone(), req.host.clone()),
1201        );
1202    }
1203    let mut resolver = CleanResolver {
1204        state: &*type_env,
1205        raw_bare,
1206        targets,
1207        exports,
1208        harvests: harvest_map,
1209        bare_cache: HashMap::new(),
1210        stack: Vec::new(),
1211        harvested: type_env
1212            .type_registry
1213            .harvested
1214            .iter()
1215            .flat_map(|(unit, map)| {
1216                map.iter()
1217                    .map(|(name, tag)| ((unit.clone(), name.clone()), tag.clone()))
1218            })
1219            .collect(),
1220    };
1221    // Eager file-harvest roots first: every file harvest resolves up
1222    // front through the same `harvest_tag` owner the on-demand path
1223    // uses, so both `TYPE` definitions referencing harvests and later
1224    // use sites (`LET`, params) see them in this single pass. Nested
1225    // harvests recurse with cycle detection; anything unresolvable
1226    // fails the closure here even when unused. Host harvests skip
1227    // this pass: the runtime import gate owns their "no such TYPE"
1228    // report, and use sites resolve them per-unit on demand.
1229    for req in harvests {
1230        if req.defining.is_none() {
1231            continue;
1232        }
1233        let key = (req.importer.clone(), req.name.clone());
1234        if resolver.harvested.contains_key(&key) {
1235            continue;
1236        }
1237        let tag = resolver.harvest_tag(&req.defining, &req.host, &req.name)?;
1238        resolver.harvested.insert(key, tag);
1239    }
1240    for (unit, names) in raw_bare {
1241        for name in names.keys() {
1242            // Every failure propagates: broken exports fail the closure
1243            // even when unused. No poison, no silent skips.
1244            let tag = resolver.resolve_bare(unit, name)?;
1245            bare_tags
1246                .entry(unit.clone())
1247                .or_default()
1248                .insert(name.clone(), tag);
1249        }
1250    }
1251    let harvested = std::mem::take(&mut resolver.harvested);
1252    // Ensure every unit has an entry (even empty) so scoped lookup
1253    // fails closed instead of falling back to global aliases.
1254    for unit in raw_bare.keys() {
1255        bare_tags.entry(unit.clone()).or_default();
1256    }
1257    for importer in targets.keys() {
1258        bare_tags.entry(importer.clone()).or_default();
1259    }
1260    // Entry unit always present for the `None` path.
1261    bare_tags
1262        .entry(super::import::ENTRY_UNIT.to_string())
1263        .or_default();
1264    drop(resolver);
1265    type_env.type_registry.units = bare_tags;
1266    // Merge per-unit harvested imports back into the registry.
1267    for ((unit, name), tag) in harvested {
1268        type_env
1269            .type_registry
1270            .harvested
1271            .entry(unit)
1272            .or_default()
1273            .insert(name, tag);
1274    }
1275    Ok(())
1276}
1277
1278impl TypeSnapshot {
1279    /// Check one tag against the directories: customs must name a
1280    /// registered descriptor, shaped tags recurse into fields and
1281    /// elements, builtins are variants and cannot be misspelled.
1282    /// Unknown names bail naming the use site and every known type.
1283    /// Single choke for declaration validity: known customs plus
1284    /// the VOID position rule. VOID is legal only as a bare function
1285    /// return (`top_void` covers exactly that call) or as the direct
1286    /// payload of HANDLE (`HANDLE<VOID>`). Every other position is a
1287    /// static error naming the site: variable, parameter, record
1288    /// field, union member, container element, or anything nested
1289    /// deeper. One recursion serves all declaration sites, so the
1290    /// rule cannot drift between LET, params, returns, schemas, and
1291    /// aliases: resolve first, then validate here.
1292    fn check_tag_known(&self, what: &str, tag: &TypeTag, top_void: bool) -> DiagnosticResult<()> {
1293        match tag {
1294            TypeTag::Custom(descriptor) => {
1295                if !self.types.contains_key(descriptor.name) {
1296                    return Err(typing_diag::typing_unregistered(
1297                        what,
1298                        descriptor.name,
1299                        &self.type_names(),
1300                    ));
1301                }
1302            }
1303            TypeTag::Void if !top_void => {
1304                return Err(typing_diag::typing_void_position(what));
1305            }
1306            TypeTag::Void => {}
1307            TypeTag::ListOf(element) => self.check_tag_known(what, element, false)?,
1308            TypeTag::HandleOf(payload) => self.check_tag_known(what, payload, true)?,
1309            TypeTag::MapOf(values) => self.check_tag_known(what, values, false)?,
1310            TypeTag::Record(fields) => {
1311                for field in fields.iter() {
1312                    self.check_tag_known(what, &field.ty, false)?;
1313                }
1314            }
1315            // Union members recurse like shaped tags: every member
1316            // must name a known type, so no unknown hides in a set.
1317            // A VOID member is never admitted: unions of handles stay
1318            // inside the payload (HANDLE<INT|STRING>), never at the
1319            // root or beside a value type.
1320            TypeTag::Union(_, members) => {
1321                for member in members.iter() {
1322                    self.check_tag_known(what, member, false)?;
1323                }
1324            }
1325            // Bare words are variants and cannot be misspelled: every
1326            // builtin is listed so a new word kind fails here until
1327            // its directory rule is explicit.
1328            TypeTag::String
1329            | TypeTag::Int
1330            | TypeTag::Float
1331            | TypeTag::Bool
1332            | TypeTag::List
1333            | TypeTag::Map
1334            | TypeTag::Pipe
1335            | TypeTag::Handle
1336            | TypeTag::Duration
1337            | TypeTag::Path
1338            | TypeTag::Semaphore
1339            | TypeTag::Permit
1340            | TypeTag::Any => {}
1341        }
1342        Ok(())
1343    }
1344
1345    /// Declaration-site gate for everything that is not a function
1346    /// return: LET bindings, parameters, schemas, aliases at use.
1347    /// Single choke so the VOID position rule cannot drift between
1348    /// the static checker and runtime definition paths.
1349    pub fn check_declaration_tag(&self, what: &str, tag: &TypeTag) -> DiagnosticResult<()> {
1350        self.check_tag_known(what, tag, false)
1351    }
1352
1353    /// Return-position gate: bare VOID is legal here (and only
1354    /// here, besides HANDLE payloads). Same single recursion as
1355    /// every other declaration site.
1356    pub fn check_return_tag(&self, what: &str, tag: &TypeTag) -> DiagnosticResult<()> {
1357        self.check_tag_known(what, tag, true)
1358    }
1359
1360    /// Resolve a descriptor by name, or `None` when unregistered.
1361    pub fn describe_type(&self, name: &str) -> Option<&'static TypeDescriptor> {
1362        self.types.get(name).map(|e| e.descriptor)
1363    }
1364
1365    /// Every registered type name: startup descriptors first, then hosts in
1366    /// registration order, then script aliases.
1367    pub fn type_names(&self) -> Vec<String> {
1368        let mut names: Vec<String> = startup_descriptors()
1369            .into_iter()
1370            .map(|(name, _)| name.to_string())
1371            .collect();
1372        for name in self.types.keys() {
1373            if !names.iter().any(|n| n == name) {
1374                names.push(name.clone());
1375            }
1376        }
1377        for name in self.alias_names() {
1378            if !names.contains(&name) {
1379                names.push(name);
1380            }
1381        }
1382        names
1383    }
1384}
1385
1386impl<P: ProcessManager> ExecState<P> {
1387    /// Resolve a source-level type name via live alias targets.
1388    /// Impure wrapper around the pure snapshot query: derives
1389    /// targets from import state, then delegates to
1390    /// `TypeSnapshot::resolve_tag_with_targets` so LSP and runtime
1391    /// share one owner.
1392    pub fn resolve_tag(&self, name: &str) -> DiagnosticResult<TypeTag> {
1393        let unit = super::import::active_unit_key(self);
1394        let alias_targets = super::import::unit_alias_targets(self, &unit);
1395        let exports = Self::module_type_exports(self);
1396        self.type_env
1397            .resolve_tag_with_targets(&unit, &alias_targets, &exports, name)
1398    }
1399
1400    /// Unit-scoped resolution for checkers holding only `&ExecState`.
1401    /// Derives live targets for `unit`, then delegates to the snapshot.
1402    pub fn resolve_tag_for_unit(&self, unit: &str, name: &str) -> DiagnosticResult<TypeTag> {
1403        let alias_targets = super::import::unit_alias_targets(self, unit);
1404        let exports = Self::module_type_exports(self);
1405        self.type_env
1406            .resolve_tag_with_targets(unit, &alias_targets, &exports, name)
1407    }
1408
1409    /// Type exports per file key from live modules.
1410    pub(crate) fn module_type_exports(state: &ExecState<P>) -> HashMap<String, Vec<String>> {
1411        module_type_exports_map(state)
1412    }
1413
1414    /// Explicit delegation to the embedded snapshot: `ExecState` is
1415    /// not a smart pointer to `TypeSnapshot`, so each forwarded query
1416    /// names its owner instead of relying on `Deref` coercion.
1417    pub fn register_type(&mut self, descriptor: &'static TypeDescriptor) {
1418        self.type_env.register_type(descriptor);
1419    }
1420
1421    pub fn is_known_type(&self, name: &str) -> bool {
1422        self.type_env.is_known_type(name)
1423    }
1424
1425    pub fn register_record_schema(&mut self, name: &'static str, fields: std::sync::Arc<[Field]>) {
1426        self.type_env.register_record_schema(name, fields);
1427    }
1428
1429    pub fn schema_names(&self) -> Vec<String> {
1430        self.type_env.schema_names()
1431    }
1432
1433    pub fn alias_names(&self) -> Vec<String> {
1434        self.type_env.alias_names()
1435    }
1436
1437    pub fn alias_target(&self, name: &str) -> Option<String> {
1438        self.type_env.alias_target(name)
1439    }
1440
1441    pub fn resolve_tag_with_targets(
1442        &self,
1443        unit: &str,
1444        alias_targets: &AliasTargets,
1445        exports: &HashMap<String, Vec<String>>,
1446        name: &str,
1447    ) -> DiagnosticResult<TypeTag> {
1448        self.type_env
1449            .resolve_tag_with_targets(unit, alias_targets, exports, name)
1450    }
1451
1452    pub(super) fn register_alias(&mut self, name: String, target: String) {
1453        self.type_env.register_alias(name, target);
1454    }
1455
1456    pub(super) fn remove_alias(&mut self, name: &str) {
1457        self.type_env.remove_alias(name);
1458    }
1459
1460    pub(super) fn restore_aliases(&mut self, next: HashMap<String, String>) {
1461        self.type_env.restore_aliases(next);
1462    }
1463
1464    pub fn check_declaration_tag(&self, what: &str, tag: &TypeTag) -> DiagnosticResult<()> {
1465        self.type_env.check_declaration_tag(what, tag)
1466    }
1467
1468    pub fn check_return_tag(&self, what: &str, tag: &TypeTag) -> DiagnosticResult<()> {
1469        self.type_env.check_return_tag(what, tag)
1470    }
1471
1472    pub fn describe_type(&self, name: &str) -> Option<&'static TypeDescriptor> {
1473        self.type_env.describe_type(name)
1474    }
1475
1476    pub fn type_names(&self) -> Vec<String> {
1477        self.type_env.type_names()
1478    }
1479
1480    /// Fail fast when any registered function declares param or return
1481    /// type names outside the type directory. Runs once per run before
1482    /// the first step executes: param arity and `LET` coercion already
1483    /// check values at use time, but a typo'd `returns` label otherwise
1484    /// lives forever as a lie in `DESCRIBE` output and generated
1485    /// references. Unknown names bail listing every known type. A
1486    /// closed `allowed` set without a type is rejected too: the set
1487    /// only means something alongside the `STRING` check that enforces
1488    /// it, so hand-built entries cannot render a set they never check.
1489    pub fn validate_function_type_tags(&self) -> DiagnosticResult<()> {
1490        for meta in self.functions.all_metas() {
1491            if let Some(params) = meta.params.as_deref() {
1492                for (position, param) in params.iter().enumerate() {
1493                    if let Some(expected) = param.param_type.as_ref() {
1494                        let what = format!("param '{}' of '{}'", param.name, meta.name);
1495                        self.type_env.check_tag_known(&what, expected, false)?;
1496                    }
1497                    if param.param_type.is_none() && param.allowed.is_some() {
1498                        return Err(typing_diag::func_param_values_without_type(
1499                            &param.name,
1500                            &meta.name,
1501                        ));
1502                    }
1503                    if param.optional {
1504                        // Omission fills an empty MAP, so only trailing
1505                        // MAP params qualify: anything else would fill a
1506                        // value the caller never chose.
1507                        let trails = params[position..].iter().all(|later| later.optional);
1508                        if !trails {
1509                            return Err(typing_diag::func_optional_before_required(
1510                                &param.name,
1511                                &meta.name,
1512                            ));
1513                        }
1514                        // Omission fills an empty MAP, so the param type
1515                        // must admit one: checked semantically (empty MAP
1516                        // against the type) instead of naming admissible
1517                        // constructors, so defaulted shapes and unions
1518                        // qualify exactly when the fill verifies.
1519                        let fills = param.param_type.as_ref().is_some_and(|expected| {
1520                            check_value(expected, &Value::map(std::collections::BTreeMap::new()))
1521                                .is_ok()
1522                        });
1523                        if !fills {
1524                            return Err(typing_diag::func_optional_without_map(
1525                                &param.name,
1526                                &meta.name,
1527                            ));
1528                        }
1529                    }
1530                }
1531            }
1532            if let Some(returns) = meta.returns.as_ref() {
1533                let what = format!("return of '{}'", meta.name);
1534                self.type_env.check_tag_known(&what, returns, true)?;
1535            }
1536        }
1537        Ok(())
1538    }
1539}