logicaffeine_language/analysis/registry.rs
1//! Type registry for tracking user-defined types during parsing.
2//!
3//! The registry stores type definitions discovered during the discovery pass
4//! and provides lookup during parsing and code generation. It supports:
5//!
6//! - **Primitives**: Nat, Int, Text, Bool (built-in)
7//! - **Structs**: Named records with typed fields
8//! - **Enums**: Sum types with variants (unit or tuple)
9//! - **Generics**: Parameterized types (List of T, Pair of T and U)
10//!
11//! The registry is populated by [`super::DiscoveryPass`] before main parsing begins.
12
13use crate::token::Span;
14use indexmap::IndexMap;
15use logicaffeine_base::{Interner, Symbol};
16use std::collections::{HashMap, HashSet};
17
18/// The structs the compiler hands to author code fully formed, rather than one an `## An X has:`
19/// declaration writes — the one list [`TypeRegistry::with_primitives`] registers them from and
20/// [`TypeRegistry::is_builtin_struct`] answers against, so a consumer never has to know their
21/// names itself. `crates/logicaffeine_compile/src/vm/wasm/kind.rs`'s `builtin_struct_types()`
22/// carries the same two shapes for the wasm backend's own boundary-type resolution.
23pub const BUILTIN_STRUCT_NAMES: &[&str] = &["HttpError", "File"];
24
25/// Type reference for struct fields (avoids circular deps with ast::TypeExpr)
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub enum FieldType {
28 /// Primitive type name (Int, Nat, Text, Bool, etc.)
29 Primitive(Symbol),
30 /// User-defined type name
31 Named(Symbol),
32 /// Generic type with parameters (List of Int, Seq of Text)
33 Generic {
34 base: Symbol,
35 params: Vec<FieldType>,
36 },
37 /// Phase 34: Type parameter reference (T, U, etc.)
38 TypeParam(Symbol),
39 /// An anonymous tuple: `(Int, Text)`.
40 Tuple(Vec<FieldType>),
41 /// A named tuple: `(quotient: Int, remainder: Int)`.
42 Record(Vec<(Symbol, FieldType)>),
43}
44
45/// How many type parameters a BUILT-IN generic takes — the one table the whole compiler asks.
46///
47/// ★ IT LIVES HERE BECAUSE IT WAS ANSWERED IN THREE PLACES AND THEY DISAGREED. The type-expression
48/// parser knew `Result` takes two; the two record-FIELD parsers knew only that `Map` does, so a
49/// field typed `Result of Int and E` read as a ONE-parameter Result and silently dropped its error
50/// type — and with it the whole record, since a field whose type will not resolve takes its struct
51/// out of the layout tables. `Pair`/`Triple` fields went the same way. A field declaring a type the
52/// language accepts everywhere else must mean the same thing here.
53///
54/// A registry lookup takes precedence for a USER generic; this answers for the built-ins only.
55pub fn builtin_generic_param_count(name: &str) -> Option<usize> {
56 Some(match name {
57 "Result" => 2,
58 "Option" | "Maybe" => 1,
59 "Seq" | "List" | "Vec" => 1,
60 "Set" | "HashSet" => 1,
61 "Map" | "HashMap" => 2,
62 "Pair" => 2,
63 "Triple" => 3,
64 "SharedSet" | "ORSet" | "SharedSet_AddWins" | "SharedSet_RemoveWins" => 1,
65 "SharedSequence" | "RGA" | "SharedSequence_YATA" | "CollaborativeSequence" => 1,
66 "SharedMap" | "ORMap" => 2,
67 "Divergent" | "MVRegister" => 1,
68 _ => return None,
69 })
70}
71
72/// Field definition within a struct
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub struct FieldDef {
75 pub name: Symbol,
76 pub ty: FieldType,
77 pub is_public: bool,
78}
79
80/// Phase 33: Variant definition for sum types
81#[derive(Debug, Clone, PartialEq, Eq)]
82pub struct VariantDef {
83 pub name: Symbol,
84 pub fields: Vec<FieldDef>, // Empty for unit variants
85}
86
87#[derive(Debug, Clone, PartialEq, Eq)]
88pub enum TypeDef {
89 /// Primitive type (Nat, Int, Text, Bool)
90 Primitive,
91 /// Struct with named fields and visibility
92 /// Phase 34: Now includes optional type parameters
93 /// Phase 47: Added is_portable for serde derives
94 /// Phase 49: Added is_shared for CRDT Merge impl
95 Struct {
96 fields: Vec<FieldDef>,
97 generics: Vec<Symbol>, // [T, U] for "A Pair of [T] and [U] has:"
98 is_portable: bool, // Phase 47: Derives Serialize/Deserialize
99 is_shared: bool, // Phase 49: Generates impl Merge
100 },
101 /// Phase 33: Enum with variants (unit or with payload)
102 /// Phase 34: Now includes optional type parameters
103 /// Phase 47: Added is_portable for serde derives
104 /// Phase 49: Added is_shared for CRDT Merge impl
105 Enum {
106 variants: Vec<VariantDef>,
107 generics: Vec<Symbol>, // [T] for "A Maybe of [T] is either:"
108 is_portable: bool, // Phase 47: Derives Serialize/Deserialize
109 is_shared: bool, // Phase 49: Generates impl Merge
110 },
111 /// Built-in generic type (List, Option, Result)
112 Generic { param_count: usize },
113 /// Type alias
114 Alias { target: Symbol },
115}
116
117#[derive(Debug, Default, Clone)]
118pub struct TypeRegistry {
119 /// Every type, in the order it was registered: the builtins first, then each declaration as
120 /// discovery reaches it. Iteration follows that order, so everything built by walking the
121 /// registry (the bytecode's type tables, generated code, diagnostics) is the same on every run.
122 types: IndexMap<Symbol, TypeDef>,
123 /// Where a struct's own field was named in the source, keyed by `(type, field)`. Populated
124 /// only where a check needs to report AT a field rather than at the record as a whole
125 /// (`## Session`'s field-kind refusal); a field with no entry here has none to report.
126 field_spans: HashMap<(Symbol, Symbol), Span>,
127 /// [`BUILTIN_STRUCT_NAMES`], interned — a type registered here because the compiler always
128 /// provides it, not because this program declared or imported it. A consumer that lists or
129 /// emits "the types this program uses" (LSP completion, AOT/C codegen) must consult this
130 /// before including one, or every program pays for `HttpError`/`File` whether it uses them
131 /// or not.
132 builtin_structs: HashSet<Symbol>,
133}
134
135impl TypeRegistry {
136 pub fn new() -> Self {
137 Self::default()
138 }
139
140 /// Register a type definition
141 pub fn register(&mut self, name: Symbol, def: TypeDef) {
142 self.types.insert(name, def);
143 }
144
145 /// Record where `field` of `ty` was named in the source.
146 pub fn set_field_span(&mut self, ty: Symbol, field: Symbol, span: Span) {
147 self.field_spans.insert((ty, field), span);
148 }
149
150 /// Where `field` of `ty` was named in the source, if recorded.
151 pub fn field_span(&self, ty: Symbol, field: Symbol) -> Option<Span> {
152 self.field_spans.get(&(ty, field)).copied()
153 }
154
155 /// Check if a symbol is a known type
156 pub fn is_type(&self, name: Symbol) -> bool {
157 self.types.contains_key(&name)
158 }
159
160 /// Whether `name` is one of [`BUILTIN_STRUCT_NAMES`] — a struct the compiler always
161 /// registers, never one this program declared or imported.
162 pub fn is_builtin_struct(&self, name: Symbol) -> bool {
163 self.builtin_structs.contains(&name)
164 }
165
166 /// Check if a symbol is a generic type (takes parameters)
167 pub fn is_generic(&self, name: Symbol) -> bool {
168 match self.types.get(&name) {
169 Some(TypeDef::Generic { .. }) => true,
170 Some(TypeDef::Struct { generics, .. }) => !generics.is_empty(),
171 Some(TypeDef::Enum { generics, .. }) => !generics.is_empty(),
172 _ => false,
173 }
174 }
175
176 /// Phase 34: Get type parameters for a user-defined generic type
177 pub fn get_generics(&self, name: Symbol) -> Option<&[Symbol]> {
178 match self.types.get(&name)? {
179 TypeDef::Struct { generics, .. } => Some(generics),
180 TypeDef::Enum { generics, .. } => Some(generics),
181 _ => None,
182 }
183 }
184
185 /// Get type definition
186 pub fn get(&self, name: Symbol) -> Option<&TypeDef> {
187 self.types.get(&name)
188 }
189
190 /// Iterate over all registered types (for codegen)
191 pub fn iter_types(&self) -> impl Iterator<Item = (&Symbol, &TypeDef)> {
192 self.types.iter()
193 }
194
195 /// Every enum declaring a variant named `variant_name`, in a STABLE, deterministic order
196 /// — sorted by the enum's own `Symbol` (its intern index, fixed by the deterministic
197 /// sequence discovery interns names in, never by `self.types`' `HashMap` iteration order,
198 /// which is reseeded, and so reordered, every process run). Two (or more) enums sharing a
199 /// variant name is a real, checkable condition: empty means no such variant anywhere, one
200 /// entry means an ordinary unambiguous lookup, and more than one is an ambiguity a caller
201 /// can act on (an `Inspect` prefers whichever enum it has already established; a bare
202 /// construction with no such context has nothing to prefer and must refuse) — instead of a
203 /// coin flip that used to silently compile the same source differently from run to run.
204 pub fn find_variant_candidates(&self, variant_name: Symbol) -> Vec<(Symbol, &VariantDef)> {
205 let mut found: Vec<(Symbol, &VariantDef)> = self
206 .types
207 .iter()
208 .filter_map(|(enum_name, type_def)| match type_def {
209 TypeDef::Enum { variants, .. } => variants
210 .iter()
211 .find(|v| v.name == variant_name)
212 .map(|v| (*enum_name, v)),
213 _ => None,
214 })
215 .collect();
216 found.sort_by_key(|(enum_name, _)| *enum_name);
217 found
218 }
219
220 /// [`Self::find_variant_candidates`] with each twin pair (see [`Self::namespaced_twins`]) counted
221 /// once, as its namespaced member: `Colors::Filter` and the bare `Filter` the assembler spliced
222 /// beside it are one enum, so a variant both declare is not ambiguous.
223 pub fn find_distinct_variant_candidates(
224 &self,
225 variant_name: Symbol,
226 interner: &Interner,
227 ) -> Vec<(Symbol, &VariantDef)> {
228 let twins = self.namespaced_twins(interner);
229 let candidates = self.find_variant_candidates(variant_name);
230 let named: HashSet<Symbol> = candidates.iter().map(|(enum_name, _)| *enum_name).collect();
231 candidates
232 .into_iter()
233 .filter(|(enum_name, _)| {
234 !twins
235 .get(enum_name)
236 .is_some_and(|twin| named.contains(twin))
237 })
238 .collect()
239 }
240
241 /// Each bare type name that names a namespaced type, keyed by the bare name. The assembler
242 /// registers an imported module's type under both its simple name (`Point`, from the inline
243 /// splice) and its canonical `Geometry::Point`; when exactly one namespaced type is called
244 /// `Point`, the bare spelling IS that type, and every consumer — the parser's variant
245 /// resolution, the checker, the monomorphizer, the AOT emitter's alias — gives both spellings
246 /// one identity. A simple name two namespaced types share stays ambiguous and maps to nothing,
247 /// and a bare type is only ever the twin of a namespaced type of its own kind.
248 pub fn namespaced_twins(&self, interner: &Interner) -> HashMap<Symbol, Symbol> {
249 let mut by_simple: HashMap<&str, Vec<Symbol>> = HashMap::new();
250 for (sym, def) in &self.types {
251 if matches!(def, TypeDef::Struct { .. } | TypeDef::Enum { .. }) {
252 if let Some((_, simple)) = interner.resolve(*sym).rsplit_once("::") {
253 by_simple.entry(simple).or_default().push(*sym);
254 }
255 }
256 }
257 let same_kind = |a: Option<&TypeDef>, b: Option<&TypeDef>| {
258 matches!(
259 (a, b),
260 (Some(TypeDef::Struct { .. }), Some(TypeDef::Struct { .. }))
261 | (Some(TypeDef::Enum { .. }), Some(TypeDef::Enum { .. }))
262 )
263 };
264 by_simple
265 .into_iter()
266 .filter_map(|(simple, full)| match full.as_slice() {
267 [only] => interner
268 .lookup(simple)
269 .filter(|bare| same_kind(self.types.get(bare), self.types.get(only)))
270 .map(|bare| (bare, *only)),
271 _ => None,
272 })
273 .collect()
274 }
275
276 /// The one identity a type named `name` has: its namespaced twin when the bare spelling names
277 /// one (see [`Self::namespaced_twins`]), else itself.
278 pub fn canonical_type(&self, name: Symbol, interner: &Interner) -> Symbol {
279 self.namespaced_twins(interner)
280 .get(&name)
281 .copied()
282 .unwrap_or(name)
283 }
284
285 /// Phase 33: Check if a symbol is a known enum variant.
286 /// Returns `Some((enum_name, variant_def))` for the first candidate in
287 /// [`Self::find_variant_candidates`]'s own deterministic order when the variant name is
288 /// declared by more than one enum — callers that must tell the difference (an ambiguous
289 /// bare construction) use `find_variant_candidates` directly instead.
290 pub fn find_variant(&self, variant_name: Symbol) -> Option<(Symbol, &VariantDef)> {
291 self.find_variant_candidates(variant_name)
292 .into_iter()
293 .next()
294 }
295
296 /// Phase 33: Check if a symbol is an enum variant
297 pub fn is_variant(&self, name: Symbol) -> bool {
298 self.find_variant(name).is_some()
299 }
300
301 /// The variant named `variant_name` declared by `enum_name` SPECIFICALLY — for a
302 /// construction that already names its enum (`a new Failure from Outcome`), so the field
303 /// list checked against is the ONE the author pointed at, never
304 /// [`Self::find_variant`]'s own deterministic-first-candidate pick, which could be a
305 /// same-named variant of a DIFFERENT enum with a different field shape entirely.
306 pub fn variant_in(&self, enum_name: Symbol, variant_name: Symbol) -> Option<&VariantDef> {
307 match self.types.get(&enum_name) {
308 Some(TypeDef::Enum { variants, .. }) => {
309 variants.iter().find(|v| v.name == variant_name)
310 }
311 _ => None,
312 }
313 }
314
315 /// Every variant name `enum_name` declares, for a "did you mean" suggestion when `from
316 /// <enum_name>` names a real enum that does not declare the variant asked for. `None` when
317 /// `enum_name` is not an enum at all.
318 pub fn variant_names_of(&self, enum_name: Symbol) -> Option<Vec<Symbol>> {
319 match self.types.get(&enum_name) {
320 Some(TypeDef::Enum { variants, .. }) => Some(variants.iter().map(|v| v.name).collect()),
321 _ => None,
322 }
323 }
324
325 /// Pre-register primitives and intrinsic generics
326 pub fn with_primitives(interner: &mut Interner) -> Self {
327 let mut reg = Self::new();
328
329 // LOGOS Core Primitives
330 reg.register(interner.intern("Nat"), TypeDef::Primitive);
331 reg.register(interner.intern("Int"), TypeDef::Primitive);
332 reg.register(interner.intern("Text"), TypeDef::Primitive);
333 reg.register(interner.intern("Bool"), TypeDef::Primitive);
334 reg.register(interner.intern("Boolean"), TypeDef::Primitive);
335 reg.register(interner.intern("Unit"), TypeDef::Primitive);
336 reg.register(interner.intern("Real"), TypeDef::Primitive); // Floating point
337 reg.register(interner.intern("Char"), TypeDef::Primitive); // Character
338 reg.register(interner.intern("Byte"), TypeDef::Primitive); // 8-bit unsigned (0-255)
339 // Fixed-width machine words — the ℤ/2ⁿ wrapping ring (crypto substrate).
340 reg.register(interner.intern("Word8"), TypeDef::Primitive);
341 reg.register(interner.intern("Word16"), TypeDef::Primitive);
342 reg.register(interner.intern("Word32"), TypeDef::Primitive);
343 reg.register(interner.intern("Word64"), TypeDef::Primitive);
344 // SIMD lane vectors — one AVX2 register each.
345 reg.register(interner.intern("Lanes8Word32"), TypeDef::Primitive);
346 reg.register(interner.intern("Lanes4Word32"), TypeDef::Primitive);
347 reg.register(interner.intern("Lanes16Word8"), TypeDef::Primitive);
348 reg.register(interner.intern("Lanes4Word64"), TypeDef::Primitive);
349 reg.register(interner.intern("Lanes16Word16"), TypeDef::Primitive);
350
351 // Intrinsic Generics
352 reg.register(interner.intern("List"), TypeDef::Generic { param_count: 1 });
353 reg.register(interner.intern("Seq"), TypeDef::Generic { param_count: 1 }); // Phase 30: Sequences
354 reg.register(interner.intern("Map"), TypeDef::Generic { param_count: 2 }); // Phase 43D: Key-value maps
355 reg.register(interner.intern("Set"), TypeDef::Generic { param_count: 1 }); // Set collection (HashSet)
356 reg.register(
357 interner.intern("Option"),
358 TypeDef::Generic { param_count: 1 },
359 );
360 reg.register(
361 interner.intern("Maybe"),
362 TypeDef::Generic { param_count: 1 },
363 );
364 reg.register(
365 interner.intern("Result"),
366 TypeDef::Generic { param_count: 2 },
367 );
368 // A dimensioned quantity carries its dimension as a type parameter: `Quantity of Length`.
369 // Bare `Quantity` (no `of`) still parses as the dimension-polymorphic form.
370 reg.register(
371 interner.intern("Quantity"),
372 TypeDef::Generic { param_count: 1 },
373 );
374
375 // Every struct the compiler hands to author code fully formed, rather than one an
376 // `## An X has:` declaration (the page's own source, or an imported stdlib module)
377 // actually writes: `HttpError` (a typed fetch's `Err`, built by `http_error_expr`) and
378 // `File` (a `When a file is dropped …: (file: File)` binding). Neither one's fields were
379 // ever registered here, so `e's message`/`file's size` resolved to a struct NAME with no
380 // field LAYOUT — "field access with no static slot" on the wasm AOT backend
381 // (`HttpError`, `File`). `crates/logicaffeine_compile/src/vm/wasm/kind.rs`
382 // `builtin_struct_types()` carries the SAME two shapes, in the SAME field order, for the
383 // wasm backend's own boundary-type resolution; `assets/std/http.lg`'s own `An HttpError
384 // has:` declaration is the field order's source of truth. Marked in `builtin_structs` so a
385 // consumer can tell "the compiler always provides this" from "this program declared it".
386 for name in BUILTIN_STRUCT_NAMES {
387 reg.builtin_structs.insert(interner.intern(name));
388 }
389 reg.register(
390 interner.intern("HttpError"),
391 TypeDef::Struct {
392 fields: vec![
393 FieldDef {
394 name: interner.intern("status"),
395 ty: FieldType::Primitive(interner.intern("Int")),
396 is_public: true,
397 },
398 FieldDef {
399 name: interner.intern("message"),
400 ty: FieldType::Primitive(interner.intern("Text")),
401 is_public: true,
402 },
403 ],
404 generics: Vec::new(),
405 is_portable: false,
406 is_shared: false,
407 },
408 );
409 reg.register(
410 interner.intern("File"),
411 TypeDef::Struct {
412 fields: vec![
413 FieldDef {
414 name: interner.intern("name"),
415 ty: FieldType::Primitive(interner.intern("Text")),
416 is_public: true,
417 },
418 FieldDef {
419 name: interner.intern("size"),
420 ty: FieldType::Primitive(interner.intern("Int")),
421 is_public: true,
422 },
423 FieldDef {
424 name: interner.intern("type"),
425 ty: FieldType::Primitive(interner.intern("Text")),
426 is_public: true,
427 },
428 FieldDef {
429 name: interner.intern("bytes"),
430 ty: FieldType::Generic {
431 base: interner.intern("Seq"),
432 params: vec![FieldType::Primitive(interner.intern("Int"))],
433 },
434 is_public: true,
435 },
436 ],
437 generics: Vec::new(),
438 is_portable: false,
439 is_shared: false,
440 },
441 );
442
443 reg
444 }
445}
446
447#[cfg(test)]
448#[path = "../../../logicaffeine_tests/unit/logicaffeine_language/analysis/registry/tests.rs"]
449mod tests;