buildlang 1.15.0

BuildLang (buildc): an effects-oriented compiler with a verified C path, shader output, experimental backends, opt-in linear types, and re-checkable accountability + scientific-runtime receipts
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
// ===============================================================================
// BUILDLANG TYPE SYSTEM - TYPE CONTEXT
// ===============================================================================
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2022-2026 Zain Dana Harper.
// ===============================================================================

//! Type context and environment for type checking.
//!
//! The type context maintains:
//! - Variable bindings (name -> type)
//! - Type definitions (structs, enums, type aliases)
//! - Trait definitions and implementations
//! - Generic instantiations

use std::collections::{HashMap, HashSet};
use std::sync::Arc;

use super::ty::*;

/// The type context holds all type information during type checking.
#[derive(Debug)]
pub struct TypeContext {
    /// Stack of scopes for variable bindings.
    scopes: Vec<Scope>,

    /// Resolved references to module-scope names, in check order: the name,
    /// the byte span of the use and whether it is the callee of a call. The
    /// BuildDB store reads them as its `refs` table. A use that a local,
    /// parameter or pattern binding shadows resolves to that binding and is
    /// not recorded.
    module_refs: Vec<(Arc<str>, u32, u32, bool)>,
    /// Set by call inference just before it infers a bare-name callee.
    ref_in_call: bool,

    /// Type definitions (structs, enums).
    types: HashMap<DefId, TypeDef>,

    /// Trait definitions.
    traits: HashMap<DefId, TraitDef>,

    /// Trait implementations.
    impls: Vec<TraitImpl>,

    /// Type aliases.
    aliases: HashMap<DefId, TypeAlias>,

    /// Function signatures.
    functions: HashMap<DefId, FnSig>,

    /// Next definition ID.
    next_def_id: u32,

    /// Type DefIds marked `#[linear]`: values of these types may be moved /
    /// consumed at most once (no-cloning / no-double-spend / resource safety).
    linear_defs: HashSet<DefId>,

    /// The current Self type (set when inside an impl block).
    current_self_ty: Option<Ty>,

    /// Inherent methods: (type_def_id, method_name) → method signature.
    /// Keyed by DefId (not type name string) to avoid collisions when
    /// multiple types in different modules share the same name.
    inherent_methods: HashMap<(DefId, Arc<str>), TraitMethod>,

    /// Type parameter trait bounds: param_name → [trait_name, ...].
    /// Populated when entering a generic function so that lookup_method can
    /// resolve trait methods on type parameters through their bounds.
    param_trait_bounds: HashMap<Arc<str>, Vec<Arc<str>>>,

    /// Module registry: module_name -> (variable bindings, type definitions).
    /// Populated by check_mod so that `use` statements can import names.
    module_bindings: HashMap<Arc<str>, HashMap<Arc<str>, TypeScheme>>,

    /// Foreign function names declared by extern blocks.
    foreign_functions: HashSet<Arc<str>>,

    /// Top-level generic functions and the type they were declared with. A
    /// reference to one gets fresh type variables for its parameters, so each
    /// call site is checked on its own (spec 2.4: one instantiation per call).
    generic_function_types: HashMap<Arc<str>, Ty>,

    /// Foreign static names declared by extern blocks.
    foreign_statics: HashSet<Arc<str>>,

    /// Multiple-dispatch registry: function name -> all candidate methods that
    /// share it. Populated at `collect_function`. A name with exactly one
    /// candidate behaves identically to today (single dispatch, plain binding);
    /// a name with two or more is resolved by the argument-type tuple in
    /// `infer_call` via the shared `resolve_overload`.
    multi_methods: HashMap<Arc<str>, Vec<MethodCandidate>>,

    /// Integer type the checker inferred for an unannotated `let NAME = ...`,
    /// keyed by the binding pattern's span. Lowering reads it so the emitted
    /// C type matches the checked type (issue #159). `None` marks a span that
    /// two checks resolved differently; lowering then keeps its own typing.
    inferred_local_ints: HashMap<crate::lexer::Span, Option<IntTy>>,

    /// Float type the checker inferred for an unannotated `let` whose
    /// initializer is an unsuffixed integer literal, as in `let mut c = 0;`
    /// used against an `f64` (issue #167). Same conflict rule as above.
    inferred_local_floats: HashMap<crate::lexer::Span, Option<super::ty::FloatTy>>,
}

/// One candidate method for an overloaded (or singly-defined) function name.
///
/// Recorded per definition so `infer_call` can rank candidates by the argument
/// tuple and hand codegen the selected definition. Codegen reconstructs the
/// same candidate set from the AST and runs the identical resolver, so the two
/// sides agree on the winner without a fragile side-channel.
#[derive(Debug, Clone)]
pub struct MethodCandidate {
    /// The definition id (also the key in `functions`).
    pub def_id: DefId,
    /// Parameter types (positional), used for arity + specificity ranking.
    pub param_tys: Vec<Ty>,
    /// Return type of this candidate.
    pub ret: Ty,
    /// The full signature (generics, effects, lifetimes).
    pub sig: FnSig,
}

/// A scope containing variable bindings.
#[derive(Debug, Clone)]
struct Scope {
    /// Variable bindings: name -> type scheme.
    bindings: HashMap<Arc<str>, TypeScheme>,
    /// Type parameters in scope.
    type_params: HashMap<Arc<str>, Ty>,
    /// Kind of scope.
    kind: ScopeKind,
    /// Bindings in this scope declared without `mut` and initialised, which
    /// an assignment may not change.
    immutable: std::collections::HashSet<Arc<str>>,
}

/// Kind of scope.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScopeKind {
    /// Global/module scope.
    Module,
    /// Function body scope.
    Function,
    /// Block scope.
    Block,
    /// Loop scope.
    Loop,
    /// Match arm scope.
    Match,
}

impl Scope {
    fn new(kind: ScopeKind) -> Self {
        Self {
            bindings: HashMap::new(),
            type_params: HashMap::new(),
            kind,
            immutable: std::collections::HashSet::new(),
        }
    }
}

/// A type definition (struct or enum).
#[derive(Debug, Clone)]
pub struct TypeDef {
    /// Definition ID.
    pub def_id: DefId,
    /// Name.
    pub name: Arc<str>,
    /// Generic parameters.
    pub generics: Vec<GenericParam>,
    /// Kind of type.
    pub kind: TypeDefKind,
}

/// Kind of type definition.
#[derive(Debug, Clone)]
pub enum TypeDefKind {
    /// Struct.
    Struct(StructDef),
    /// Enum.
    Enum(EnumDef),
}

/// Struct definition.
#[derive(Debug, Clone)]
pub struct StructDef {
    /// Fields (name -> type).
    pub fields: Vec<(Arc<str>, Ty)>,
    /// Is this a tuple struct?
    pub is_tuple: bool,
}

/// Enum definition.
#[derive(Debug, Clone)]
pub struct EnumDef {
    /// Variants.
    pub variants: Vec<EnumVariant>,
}

/// Enum variant.
#[derive(Debug, Clone)]
pub struct EnumVariant {
    /// Variant name.
    pub name: Arc<str>,
    /// Fields (if any).
    pub fields: Vec<(Option<Arc<str>>, Ty)>,
    /// Discriminant (if specified).
    pub discriminant: Option<i128>,
}

/// A generic parameter.
#[derive(Debug, Clone)]
pub struct GenericParam {
    /// Parameter name.
    pub name: Arc<str>,
    /// Parameter index.
    pub index: u32,
    /// Kind of parameter.
    pub kind: GenericParamKind,
}

/// Kind of generic parameter.
#[derive(Debug, Clone)]
pub enum GenericParamKind {
    /// Type parameter with optional bounds.
    Type { bounds: Vec<TraitBound> },
    /// Lifetime parameter.
    Lifetime,
    /// Const parameter.
    Const { ty: Ty },
}

/// A trait bound.
#[derive(Debug, Clone)]
pub struct TraitBound {
    /// The trait being bounded.
    pub trait_id: DefId,
    /// Type arguments for the trait.
    pub args: Vec<Ty>,
}

/// A trait definition.
#[derive(Debug, Clone)]
pub struct TraitDef {
    /// Definition ID.
    pub def_id: DefId,
    /// Name.
    pub name: Arc<str>,
    /// Generic parameters.
    pub generics: Vec<GenericParam>,
    /// Super traits.
    pub supertraits: Vec<TraitBound>,
    /// Associated types.
    pub assoc_types: Vec<AssocType>,
    /// Methods.
    pub methods: Vec<TraitMethod>,
}

/// An associated type in a trait.
#[derive(Debug, Clone)]
pub struct AssocType {
    /// Name.
    pub name: Arc<str>,
    /// Bounds.
    pub bounds: Vec<TraitBound>,
    /// Default type (if any).
    pub default: Option<Ty>,
}

/// A method in a trait.
#[derive(Debug, Clone)]
pub struct TraitMethod {
    /// Name.
    pub name: Arc<str>,
    /// Signature.
    pub sig: FnSig,
    /// Has default implementation?
    pub has_default: bool,
}

/// A trait implementation.
#[derive(Debug, Clone)]
pub struct TraitImpl {
    /// The trait being implemented.
    pub trait_id: DefId,
    /// The type implementing the trait.
    pub self_ty: Ty,
    /// Generic parameters on the impl.
    pub generics: Vec<GenericParam>,
    /// Associated type values.
    pub assoc_types: HashMap<Arc<str>, Ty>,
    /// Method implementations.
    pub methods: HashMap<Arc<str>, DefId>,
    /// Where clauses.
    pub where_clauses: Vec<WhereClause>,
}

/// A where clause.
#[derive(Debug, Clone)]
pub struct WhereClause {
    /// The type being constrained.
    pub ty: Ty,
    /// The bounds.
    pub bounds: Vec<TraitBound>,
}

/// A type alias.
#[derive(Debug, Clone)]
pub struct TypeAlias {
    /// Definition ID.
    pub def_id: DefId,
    /// Name.
    pub name: Arc<str>,
    /// Generic parameters.
    pub generics: Vec<GenericParam>,
    /// The aliased type.
    pub ty: Ty,
}

/// A function signature.
#[derive(Debug, Clone)]
pub struct FnSig {
    /// Generic parameters.
    pub generics: Vec<GenericParam>,
    /// Lifetime parameters (e.g., 'a, 'b in `fn foo<'a, 'b>(...)`)
    pub lifetime_params: Vec<Arc<str>>,
    /// Parameter types (with names).
    pub params: Vec<(Arc<str>, Ty)>,
    /// Return type.
    pub ret: Ty,
    /// Declared effects in the callable signature.
    pub effects: super::effects::EffectRow,
    /// Is unsafe?
    pub is_unsafe: bool,
    /// Is async?
    pub is_async: bool,
    /// Is const?
    pub is_const: bool,
    /// Where clauses.
    pub where_clauses: Vec<WhereClause>,
}

impl TypeContext {
    /// Create a new type context.
    pub fn new() -> Self {
        super::ty::clear_def_names();
        let mut ctx = Self {
            scopes: vec![Scope::new(ScopeKind::Module)],
            module_refs: Vec::new(),
            ref_in_call: false,
            types: HashMap::new(),
            traits: HashMap::new(),
            impls: Vec::new(),
            aliases: HashMap::new(),
            functions: HashMap::new(),
            next_def_id: 0,
            linear_defs: HashSet::new(),
            current_self_ty: None,
            inherent_methods: HashMap::new(),
            param_trait_bounds: HashMap::new(),
            module_bindings: HashMap::new(),
            foreign_functions: HashSet::new(),
            generic_function_types: HashMap::new(),
            foreign_statics: HashSet::new(),
            multi_methods: HashMap::new(),
            inferred_local_ints: HashMap::new(),
            inferred_local_floats: HashMap::new(),
        };
        ctx.init_builtins();
        ctx
    }

    /// Initialize built-in types.
    fn init_builtins(&mut self) {
        // Trait stubs are registered lazily during check_module to avoid
        // shifting DefIds for user types. See register_builtin_traits().
    }

    /// Register common trait stubs so ecosystem code can use `impl Default for X` etc.
    /// Called during check_module AFTER user types are collected.
    pub fn register_builtin_traits(&mut self) {
        let common_traits = [
            "Default",
            "Display",
            "Debug",
            "Clone",
            "Copy",
            "PartialEq",
            "Eq",
            "PartialOrd",
            "Ord",
            "Hash",
            "Send",
            "Sync",
            "Sized",
            "Drop",
            "Iterator",
            "IntoIterator",
            "FromIterator",
            "From",
            "Into",
            "TryFrom",
            "TryInto",
            "AsRef",
            "AsMut",
            "Deref",
            "DerefMut",
            "Add",
            "Sub",
            "Mul",
            "Div",
            "Rem",
            "Neg",
            "Serialize",
            "Deserialize",
        ];
        for name in &common_traits {
            // Only register if not already defined by user code
            if self.lookup_trait_by_name(name).is_none() {
                let def_id = self.fresh_def_id();
                self.register_trait(TraitDef {
                    def_id,
                    name: Arc::from(*name),
                    generics: Vec::new(),
                    supertraits: Vec::new(),
                    methods: Vec::new(),
                    assoc_types: Vec::new(),
                });
            }
        }
    }

    /// Generate a fresh definition ID.
    pub fn fresh_def_id(&mut self) -> DefId {
        let id = DefId::new(0, self.next_def_id);
        self.next_def_id += 1;
        id
    }

    /// Mark a type definition as `#[linear]`.
    pub fn mark_linear(&mut self, def_id: DefId) {
        self.linear_defs.insert(def_id);
    }

    /// Whether a type definition is marked `#[linear]`.
    pub fn is_linear_def(&self, def_id: DefId) -> bool {
        self.linear_defs.contains(&def_id)
    }

    // =========================================================================
    // SCOPE MANAGEMENT
    // =========================================================================

    /// Push a new scope.
    pub fn push_scope(&mut self, kind: ScopeKind) {
        self.scopes.push(Scope::new(kind));
    }

    /// Pop the current scope.
    pub fn pop_scope(&mut self) {
        if self.scopes.len() > 1 {
            self.scopes.pop();
        }
    }

    /// Get the current scope kind.
    pub fn current_scope_kind(&self) -> ScopeKind {
        self.scopes
            .last()
            .map(|s| s.kind)
            .unwrap_or(ScopeKind::Module)
    }

    /// Check if we're inside a loop.
    pub fn in_loop(&self) -> bool {
        self.scopes.iter().any(|s| s.kind == ScopeKind::Loop)
    }

    /// Check if we're inside a function.
    pub fn in_function(&self) -> bool {
        self.scopes.iter().any(|s| s.kind == ScopeKind::Function)
    }

    // =========================================================================
    // SELF TYPE
    // =========================================================================

    /// Set the current Self type (used when entering an impl block).
    pub fn set_self_ty(&mut self, ty: Option<Ty>) {
        self.current_self_ty = ty;
    }

    /// Get the current Self type.
    pub fn get_self_ty(&self) -> Option<&Ty> {
        self.current_self_ty.as_ref()
    }

    // =========================================================================
    // VARIABLE BINDINGS
    // =========================================================================

    /// Define a variable in the current scope.
    pub fn define_var(&mut self, name: impl Into<Arc<str>>, ty: Ty) {
        let name = name.into();
        if let Some(scope) = self.scopes.last_mut() {
            scope.bindings.insert(name, TypeScheme::mono(ty));
        }
    }

    /// Define a variable with a type scheme (polymorphic).
    pub fn define_var_scheme(&mut self, name: impl Into<Arc<str>>, scheme: TypeScheme) {
        let name = name.into();
        if let Some(scope) = self.scopes.last_mut() {
            scope.bindings.insert(name, scheme);
        }
    }

    /// Record the integer type inferred for the unannotated `let` binding at
    /// `span`. A second, different record for the same span clears it.
    pub fn record_inferred_local_int(&mut self, span: crate::lexer::Span, ty: IntTy) {
        self.inferred_local_ints
            .entry(span)
            .and_modify(|e| {
                if *e != Some(ty) {
                    *e = None;
                }
            })
            .or_insert(Some(ty));
    }

    /// Record the float type inferred for the unannotated `let` binding at
    /// `span`. A second, different record for the same span clears it.
    pub fn record_inferred_local_float(
        &mut self,
        span: crate::lexer::Span,
        ty: super::ty::FloatTy,
    ) {
        self.inferred_local_floats
            .entry(span)
            .and_modify(|e| {
                if *e != Some(ty) {
                    *e = None;
                }
            })
            .or_insert(Some(ty));
    }

    /// The float type the checker inferred for the unannotated `let` binding
    /// at `span`, if one was recorded without conflict.
    pub fn inferred_local_float(&self, span: crate::lexer::Span) -> Option<super::ty::FloatTy> {
        self.inferred_local_floats.get(&span).copied().flatten()
    }

    /// The integer type the checker inferred for the unannotated `let`
    /// binding at `span`, if one was recorded without conflict.
    pub fn inferred_local_int(&self, span: crate::lexer::Span) -> Option<IntTy> {
        self.inferred_local_ints.get(&span).copied().flatten()
    }

    /// Mark whether the binding `name` in the current scope may be assigned.
    pub fn set_var_immutable(&mut self, name: &str, immutable: bool) {
        if let Some(scope) = self.scopes.last_mut() {
            if immutable {
                scope.immutable.insert(Arc::from(name));
            } else {
                scope.immutable.remove(name);
            }
        }
    }

    /// Whether the nearest binding of `name` was declared without `mut` and
    /// initialised (so `name = v` is refused).
    pub fn var_is_immutable(&self, name: &str) -> bool {
        for scope in self.scopes.iter().rev() {
            if scope.bindings.contains_key(name) {
                return scope.immutable.contains(name);
            }
        }
        false
    }

    /// Look up a variable.
    pub fn lookup_var(&self, name: &str) -> Option<Ty> {
        for scope in self.scopes.iter().rev() {
            if let Some(scheme) = scope.bindings.get(name) {
                return Some(scheme.instantiate());
            }
        }
        None
    }

    /// True when the innermost binding of `name` is in the module scope, so a
    /// use of `name` here refers to a top-level definition.
    pub fn binds_at_module_scope(&self, name: &str) -> bool {
        for (depth, scope) in self.scopes.iter().enumerate().rev() {
            if scope.bindings.contains_key(name) {
                return depth == 0;
            }
        }
        false
    }

    /// Record a resolved reference to a module-scope name.
    pub fn record_module_ref(&mut self, name: &str, start: u32, end: u32) {
        let call = std::mem::take(&mut self.ref_in_call);
        self.module_refs.push((Arc::from(name), start, end, call));
    }

    /// Mark the next recorded reference as the callee of a call.
    pub fn set_ref_in_call(&mut self, on: bool) {
        self.ref_in_call = on;
    }

    /// Every resolved reference to a module-scope name, in check order.
    pub fn module_refs(&self) -> &[(Arc<str>, u32, u32, bool)] {
        &self.module_refs
    }

    /// Look up a variable's type scheme.
    pub fn lookup_var_scheme(&self, name: &str) -> Option<&TypeScheme> {
        for scope in self.scopes.iter().rev() {
            if let Some(scheme) = scope.bindings.get(name) {
                return Some(scheme);
            }
        }
        None
    }

    /// Mark a function name as originating from an extern block.
    pub fn register_foreign_function(&mut self, name: impl Into<Arc<str>>) {
        self.foreign_functions.insert(name.into());
    }

    /// Record a top-level generic function and its declared type.
    pub fn register_generic_function(&mut self, name: impl Into<Arc<str>>, ty: Ty) {
        self.generic_function_types.insert(name.into(), ty);
    }

    /// The declared type of a top-level generic function, if `name` is one.
    pub fn generic_function_type(&self, name: &str) -> Option<&Ty> {
        self.generic_function_types.get(name)
    }

    /// Return true when a function name was declared in an extern block.
    pub fn is_foreign_function(&self, name: &str) -> bool {
        self.foreign_functions.contains(name)
    }

    /// Mark a static name as originating from an extern block.
    pub fn register_foreign_static(&mut self, name: impl Into<Arc<str>>) {
        self.foreign_statics.insert(name.into());
    }

    /// Return true when a static name was declared in an extern block.
    pub fn is_foreign_static(&self, name: &str) -> bool {
        self.foreign_statics.contains(name)
    }

    // =========================================================================
    // TYPE PARAMETERS
    // =========================================================================

    /// Define a type parameter in the current scope.
    pub fn define_type_param(&mut self, name: impl Into<Arc<str>>, ty: Ty) {
        let name = name.into();
        if let Some(scope) = self.scopes.last_mut() {
            scope.type_params.insert(name, ty);
        }
    }

    /// Look up a type parameter.
    pub fn lookup_type_param(&self, name: &str) -> Option<&Ty> {
        for scope in self.scopes.iter().rev() {
            if let Some(ty) = scope.type_params.get(name) {
                return Some(ty);
            }
        }
        None
    }

    // =========================================================================
    // TYPE DEFINITIONS
    // =========================================================================

    /// Register a type definition.
    pub fn register_type(&mut self, def: TypeDef) {
        super::ty::register_def_name(def.def_id, def.name.clone());
        self.types.insert(def.def_id, def);
    }

    /// Look up a type definition by ID.
    pub fn lookup_type(&self, def_id: DefId) -> Option<&TypeDef> {
        self.types.get(&def_id)
    }

    /// Look up a type definition by name.
    /// When multiple types share the same name (e.g., in different modules),
    /// returns the one with the lowest DefId for deterministic behavior.
    pub fn lookup_type_by_name(&self, name: &str) -> Option<&TypeDef> {
        self.types
            .iter()
            .filter(|(_, t)| t.name.as_ref() == name)
            .min_by_key(|(def_id, _)| *def_id)
            .map(|(_, t)| t)
    }

    // =========================================================================
    // TRAIT DEFINITIONS
    // =========================================================================

    /// Register a trait definition.
    pub fn register_trait(&mut self, def: TraitDef) {
        self.traits.insert(def.def_id, def);
    }

    /// Look up a trait definition.
    pub fn lookup_trait(&self, def_id: DefId) -> Option<&TraitDef> {
        self.traits.get(&def_id)
    }

    /// Look up a trait by name (deterministic: lowest DefId wins).
    pub fn lookup_trait_by_name(&self, name: &str) -> Option<&TraitDef> {
        self.traits
            .iter()
            .filter(|(_, t)| t.name.as_ref() == name)
            .min_by_key(|(def_id, _)| *def_id)
            .map(|(_, t)| t)
    }

    // =========================================================================
    // TRAIT IMPLEMENTATIONS
    // =========================================================================

    /// Register a trait implementation.
    pub fn register_impl(&mut self, impl_: TraitImpl) {
        self.impls.push(impl_);
    }

    /// Find implementations of a trait for a type.
    pub fn find_impls(&self, trait_id: DefId, _self_ty: &Ty) -> Vec<&TraitImpl> {
        self.impls
            .iter()
            .filter(|impl_| impl_.trait_id == trait_id)
            .collect()
    }

    /// Look up a method available on a type via trait implementations.
    ///
    /// Searches all registered trait impls whose `self_ty` matches the given
    /// type and returns the trait method signature if found.
    pub fn lookup_trait_method(&self, self_ty: &Ty, method_name: &str) -> Option<&TraitMethod> {
        // Auto-deref the receiver: a `&self`/`&mut self` method is invoked on a
        // `&T`/`&mut T`, but the impl's `self_ty` is the bare `T`. Look through
        // one layer of reference (or raw pointer) so reference receivers match.
        let lookup_ty = match &self_ty.kind {
            TyKind::Ref(_, _, inner) | TyKind::Ptr(_, inner) => inner.as_ref(),
            _ => self_ty,
        };
        // Find trait impls whose self_ty matches
        for impl_ in &self.impls {
            let matches = match (&impl_.self_ty.kind, &lookup_ty.kind) {
                (TyKind::Adt(d1, _), TyKind::Adt(d2, _)) => d1 == d2,
                _ => false,
            };
            if !matches {
                continue;
            }
            // Look up the method signature from the trait definition.
            let Some(trait_def) = self.traits.get(&impl_.trait_id) else {
                continue;
            };
            let Some(method) = trait_def
                .methods
                .iter()
                .find(|m| m.name.as_ref() == method_name)
            else {
                continue;
            };
            // The method is callable on this type if either the impl provides
            // its own definition, or the trait supplies a default body. The
            // latter is what makes provided/default trait methods such as
            // `PartialEq::ne` resolve when an `impl` only overrides `eq`.
            if impl_.methods.contains_key(method_name) || method.has_default {
                return Some(method);
            }
        }
        None
    }

    // =========================================================================
    // INHERENT METHODS
    // =========================================================================

    /// Register an inherent method on a user-defined type.
    /// This is used for `impl Type { fn method(...) }` without a trait.
    pub fn register_inherent_method(
        &mut self,
        type_def_id: DefId,
        method_name: Arc<str>,
        sig: FnSig,
    ) {
        self.inherent_methods.insert(
            (type_def_id, method_name.clone()),
            TraitMethod {
                name: method_name,
                sig,
                has_default: false,
            },
        );
    }

    /// Look up an inherent method on a type by DefId.
    pub fn lookup_inherent_method(
        &self,
        type_def_id: DefId,
        method_name: &str,
    ) -> Option<&TraitMethod> {
        self.inherent_methods
            .get(&(type_def_id, Arc::from(method_name)))
    }

    /// Look up an inherent method by type name string (fallback for path-based resolution).
    /// Looks up the type's DefId first, then searches by DefId.
    pub fn lookup_inherent_method_by_name(
        &self,
        type_name: &str,
        method_name: &str,
    ) -> Option<&TraitMethod> {
        // Find the type's DefId by name
        if let Some(type_def) = self.lookup_type_by_name(type_name) {
            let def_id = type_def.def_id;
            return self.lookup_inherent_method(def_id, method_name);
        }
        None
    }

    // =========================================================================
    // TYPE PARAMETER TRAIT BOUNDS
    // =========================================================================

    /// Register trait bounds for a type parameter (e.g., `T: Clone + Debug`).
    ///
    /// Bounds accumulate: a parameter can gather bounds from several sources
    /// (an inline `T: A`, a where-clause `where T: B`, and an enclosing impl's
    /// `impl<T: C>`). Each call adds to the parameter's existing set rather than
    /// replacing it, so none of those sources clobbers another.
    pub fn register_param_bounds(&mut self, param_name: Arc<str>, trait_names: Vec<Arc<str>>) {
        let entry = self.param_trait_bounds.entry(param_name).or_default();
        for name in trait_names {
            if !entry.contains(&name) {
                entry.push(name);
            }
        }
    }

    /// Clear all type parameter trait bounds (call when leaving a generic scope).
    pub fn clear_param_bounds(&mut self) {
        self.param_trait_bounds.clear();
    }

    /// Clone the current type-parameter trait bounds so they can be restored
    /// later. Used to layer a method's own bounds on top of an enclosing impl's
    /// bounds and then unwind cleanly without disturbing what is in scope now.
    pub fn param_bounds_snapshot(&self) -> HashMap<Arc<str>, Vec<Arc<str>>> {
        self.param_trait_bounds.clone()
    }

    /// Restore a previously snapshotted type-parameter trait-bound map.
    pub fn restore_param_bounds(&mut self, bounds: HashMap<Arc<str>, Vec<Arc<str>>>) {
        self.param_trait_bounds = bounds;
    }

    /// Look up a method on a type parameter by searching its trait bounds.
    ///
    /// For `T: Ord + Display`, this searches the `Ord` and `Display` trait
    /// definitions for the named method and returns the first match.
    pub fn lookup_param_method(&self, param_name: &str, method_name: &str) -> Option<&TraitMethod> {
        let bounds = self.param_trait_bounds.get(param_name)?;
        for trait_name in bounds {
            // Find the trait definition by name
            if let Some(trait_def) = self.lookup_trait_by_name(trait_name) {
                // Search the trait's methods
                if let Some(method) = trait_def
                    .methods
                    .iter()
                    .find(|m| m.name.as_ref() == method_name)
                {
                    return Some(method);
                }
            }
        }
        None
    }

    // =========================================================================
    // MODULE BINDINGS
    // =========================================================================

    /// Register a module's exported bindings for use-statement resolution.
    pub fn register_module_bindings(
        &mut self,
        name: Arc<str>,
        bindings: HashMap<Arc<str>, TypeScheme>,
    ) {
        self.module_bindings.insert(name, bindings);
    }

    /// Look up a binding in a named module.
    pub fn lookup_module_binding(&self, module: &str, name: &str) -> Option<Ty> {
        self.module_bindings
            .get(module)?
            .get(name)
            .map(|scheme| scheme.instantiate())
    }

    /// Return a clone of the current scope's variable bindings.
    pub fn current_scope_bindings(&self) -> HashMap<Arc<str>, TypeScheme> {
        self.scopes
            .last()
            .map(|s| s.bindings.clone())
            .unwrap_or_default()
    }

    /// Return a clone of a named module's bindings (for glob imports).
    pub fn clone_module_bindings(&self, module: &str) -> Option<HashMap<Arc<str>, TypeScheme>> {
        self.module_bindings.get(module).cloned()
    }

    // =========================================================================
    // TYPE ALIASES
    // =========================================================================

    /// Register a type alias.
    pub fn register_alias(&mut self, alias: TypeAlias) {
        self.aliases.insert(alias.def_id, alias);
    }

    /// Look up a type alias.
    pub fn lookup_alias(&self, def_id: DefId) -> Option<&TypeAlias> {
        self.aliases.get(&def_id)
    }

    // =========================================================================
    // FUNCTIONS
    // =========================================================================

    /// Register a function signature.
    pub fn register_function(&mut self, def_id: DefId, sig: FnSig) {
        self.functions.insert(def_id, sig);
    }

    /// Look up a function signature.
    pub fn lookup_function(&self, def_id: DefId) -> Option<&FnSig> {
        self.functions.get(&def_id)
    }

    /// Append a dispatch candidate for `name` (multiple-dispatch registry).
    /// Called once per function definition at collection time.
    pub fn register_method_candidate(&mut self, name: Arc<str>, candidate: MethodCandidate) {
        let candidates = self.multi_methods.entry(name).or_default();
        // Multiple dispatch selects a method by the tuple of argument types, so
        // two candidates with an identical parameter-type signature are
        // indistinguishable and can never form a legitimate overload set. Such an
        // exact duplicate is a redundant re-registration (most commonly an
        // external `mod foo;` module, which the type checker loads and registers
        // in BOTH the collect pass and the check pass), not a new method. Keeping
        // it would make every call to that name a spurious "equally-specific
        // candidates" ambiguity. Drop the duplicate; keep the first. Genuine
        // overloads differ in parameter types and are unaffected. (Before
        // multiple dispatch a second same-signature definition silently
        // overwrote the first, so this preserves the historical single-method
        // behavior for that case.)
        // Unresolved type variables are compared by position, not by number:
        // the two loads of one module give a parameter whose type is not known
        // yet a fresh variable each time (`?T96` and `?T310`), and those copies
        // made `jnum_at(items, 0, 0.0)` ambiguous with itself.
        let shape = |tys: &[Ty]| -> Vec<String> {
            tys.iter()
                .map(|t| erase_type_vars(&t.to_string()))
                .collect()
        };
        let new_shape = shape(&candidate.param_tys);
        if candidates
            .iter()
            .any(|c| c.param_tys == candidate.param_tys || shape(&c.param_tys) == new_shape)
        {
            return;
        }
        candidates.push(candidate);
    }

    /// All dispatch candidates registered under `name`, if any.
    pub fn method_candidates(&self, name: &str) -> Option<&[MethodCandidate]> {
        self.multi_methods.get(name).map(|v| v.as_slice())
    }

    // =========================================================================
    // GENERALIZATION
    // =========================================================================

    /// Generalize a type to a type scheme by quantifying over free variables
    /// that are not in the environment.
    pub fn generalize(&self, ty: &Ty) -> TypeScheme {
        let free_in_ty = ty.free_vars();
        let free_in_env = self.free_vars_in_env();

        let vars: Vec<_> = free_in_ty.difference(&free_in_env).cloned().collect();

        TypeScheme::poly(vars, ty.clone())
    }

    /// Collect all free type variables in the environment.
    fn free_vars_in_env(&self) -> std::collections::HashSet<TyVarId> {
        let mut vars = std::collections::HashSet::new();
        for scope in &self.scopes {
            for scheme in scope.bindings.values() {
                // Don't include bound variables from the scheme
                let free = scheme.ty.free_vars();
                for var in free {
                    if !scheme.vars.contains(&var) {
                        vars.insert(var);
                    }
                }
            }
        }
        vars
    }
}

impl Default for TypeContext {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_scope_management() {
        let mut ctx = TypeContext::new();

        ctx.define_var("x", Ty::int(IntTy::I32));
        assert!(ctx.lookup_var("x").is_some());

        ctx.push_scope(ScopeKind::Block);
        ctx.define_var("y", Ty::bool());
        assert!(ctx.lookup_var("x").is_some());
        assert!(ctx.lookup_var("y").is_some());

        ctx.pop_scope();
        assert!(ctx.lookup_var("x").is_some());
        assert!(ctx.lookup_var("y").is_none()); // y is out of scope
    }

    #[test]
    fn test_generalization() {
        let ctx = TypeContext::new();

        let v = TyVarId::fresh();
        let ty = Ty::function(vec![Ty::var(v)], Ty::var(v));

        let scheme = ctx.generalize(&ty);
        assert_eq!(scheme.vars.len(), 1);
    }
}

/// A type's text with every inference variable (`?T12`) written as `?`.
fn erase_type_vars(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    let mut chars = text.chars().peekable();
    while let Some(c) = chars.next() {
        if c == '?' && chars.peek() == Some(&'T') {
            chars.next();
            while chars.peek().is_some_and(|d| d.is_ascii_digit()) {
                chars.next();
            }
            out.push('?');
        } else {
            out.push(c);
        }
    }
    out
}