forked from nulang-org/nulang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtypechecker.rs
More file actions
4760 lines (4418 loc) · 181 KB
/
Copy pathtypechecker.rs
File metadata and controls
4760 lines (4418 loc) · 181 KB
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
//! Hindley-Milner type checker (Algorithm W) for Nulang.
//!
//! Implements classical Damas-Milner type inference with support for:
//! - Primitive types (Int, Float, Bool, String, Unit, Never, Address)
//! - Polymorphism via type schemes (forall vars. Type)
//! - Tuples, Records, Variants, Arrays
//! - Functions with effect rows and capability annotations
//! - Reference types with capabilities
//! - Actor types
//! - Pattern matching
//! - Binary and unary operators
//!
//! The algorithm follows the standard substitution-based approach:
//! 1. `infer` computes a type and a substitution
//! 2. `mgu` (most general unifier) produces substitutions from equality constraints
//! 3. `apply_subst` propagates substitutions through types
//! 4. `generalize` creates polymorphic schemes from free variables
//! 5. `instantiate` creates fresh type variables from schemes
use crate::ast::*;
use crate::types::*;
use std::collections::HashSet;
// ---------------------------------------------------------------------------
// Substitution
// ---------------------------------------------------------------------------
/// A substitution maps type variables to types.
/// Ordered list: earlier substitutions take precedence.
pub type Substitution = Vec<(TypeVar, Type)>;
// Fast hashing for compiler-internal maps (keys are not attacker-controlled).
type FxHashMap<K, V> =
std::collections::HashMap<K, V, std::hash::BuildHasherDefault<rustc_hash::FxHasher>>;
type FxHashSet<T> =
std::collections::HashSet<T, std::hash::BuildHasherDefault<rustc_hash::FxHasher>>;
/// Apply a substitution to a type, replacing any type variables that appear
/// in the substitution with their mapped types.
pub(crate) fn apply_subst(ty: &Type, subst: &Substitution) -> Type {
match ty {
Type::Var(v) => {
// Find the first mapping for this variable
for (var, replacement) in subst {
if var == v {
// Apply recursively in case the replacement contains vars
// that are also in the substitution
return apply_subst(replacement, subst);
}
}
Type::Var(*v)
}
Type::Primitive(_) => ty.clone(),
Type::Tuple(ts) => Type::Tuple(ts.iter().map(|t| apply_subst(t, subst)).collect()),
Type::Record(fs) => Type::Record(
fs.iter()
.map(|(name, t)| (name.clone(), apply_subst(t, subst)))
.collect(),
),
Type::Variant(vs) => Type::Variant(
vs.iter()
.map(|(name, t)| (name.clone(), t.as_ref().map(|t| apply_subst(t, subst))))
.collect(),
),
Type::Array(t) => Type::Array(Box::new(apply_subst(t, subst))),
Type::Function {
param,
ret,
effect,
cap,
} => Type::Function {
param: Box::new(apply_subst(param, subst)),
ret: Box::new(apply_subst(ret, subst)),
effect: effect.clone(),
cap: *cap,
},
Type::Actor { state, behavior } => Type::Actor {
state: Box::new(apply_subst(state, subst)),
behavior: Box::new(apply_subst(behavior, subst)),
},
Type::App { constructor, args } => Type::App {
constructor: Box::new(apply_subst(constructor, subst)),
args: args.iter().map(|a| apply_subst(a, subst)).collect(),
},
Type::Reference { cap, inner } => Type::Reference {
cap: *cap,
inner: Box::new(apply_subst(inner, subst)),
},
Type::Scheme { vars, body } => {
// Remove substitutions for bound variables
let filtered: Substitution = subst
.iter()
.filter(|(v, _)| !vars.contains(v))
.cloned()
.collect();
Type::Scheme {
vars: vars.clone(),
body: Box::new(apply_subst(body, &filtered)),
}
}
Type::Nominal { name, underlying } => Type::Nominal {
name: name.clone(),
underlying: Box::new(apply_subst(underlying, subst)),
},
}
}
/// Apply a substitution to a type context, returning the updated context.
/// Every binding's type is substituted so constraints inferred from earlier
/// subexpressions are visible at later uses of the same variable.
fn apply_subst_to_ctx(ctx: &TypeContext, subst: &Substitution) -> TypeContext {
if subst.is_empty() {
return ctx.clone();
}
let mut result = TypeContext::new();
result.entity_events = ctx.entity_events.clone();
for (name, (ty, cap, mutable)) in ctx.iter() {
result.bind(name.clone(), apply_subst(ty, subst), *cap, *mutable);
}
// Propagate constraints through substitution: if a constrained type
// variable is substituted to another variable, transfer the constraints.
for (tv, class_names) in &ctx.constraints {
let resolved = apply_subst(&Type::Var(*tv), subst);
match resolved {
Type::Var(tv2) => {
for cn in class_names {
result.add_constraint(tv2, cn);
}
}
// If substituted to a concrete type, drop the constraint — it
// is resolved by the instance-lookup in B.4 when the caller
// checks for a matching instance.
_ => {}
}
}
result
}
/// Strip the first (self) parameter from a function parameter type.
/// `fn(Self, A) -> Ret` becomes `fn(A) -> Ret`.
/// `fn(Self, A, B) -> Ret` becomes `fn((A, B)) -> Ret`.
/// `fn(Self) -> Ret` becomes `fn(Unit) -> Ret` (nullary after self removal).
fn strip_first_param(param: &Type) -> Type {
match param {
Type::Tuple(params) if params.len() > 2 => Type::Tuple(params[1..].to_vec()),
Type::Tuple(params) if params.len() == 2 => {
params[1].clone() // single remaining param, unwrapped
}
Type::Tuple(_) => Type::unit(), // only self, nullary
_ => Type::unit(),
}
}
/// Compose two substitutions: s2 after s1.
/// Result: first apply s1, then apply s2 to the result.
/// Formally: (s2 ∘ s1)(t) = s2(s1(t))
///
/// If a variable is bound by both substitutions, the two mappings are unified
/// and the unifier is composed through the result, so constraints from both
/// sides propagate (e.g. `a := (b, c)` from s1 and `a := (Int, Bool)` from s2
/// yields `b := Int, c := Bool`). Previously s2's mapping was silently
/// discarded, losing those constraints.
fn compose_subst(s2: &Substitution, s1: &Substitution) -> Substitution {
// Apply s2 to all types in s1
let mut s1_substituted: Substitution =
s1.iter().map(|(v, t)| (*v, apply_subst(t, s2))).collect();
for (v, t) in s2 {
match s1_substituted.iter().position(|(rv, _)| rv == v) {
// New binding from s2: keep it.
None => s1_substituted.push((*v, t.clone())),
// v is bound by both: unify the two mappings so neither
// constraint is lost.
Some(pos) => {
let existing = s1_substituted[pos].1.clone();
if let Ok(s) = mgu(&existing, t, Span::default()) {
let unified = apply_subst(&existing, &s);
s1_substituted.remove(pos);
s1_substituted.push((*v, unified));
s1_substituted = compose_subst(&s, &s1_substituted);
}
// Irreconcilable mappings cannot occur when contexts are
// substituted eagerly (`apply_subst_to_ctx`): the conflicting
// unification fails earlier, at the use site. Keep s1's
// mapping rather than inventing a type.
}
}
}
s1_substituted
}
// ---------------------------------------------------------------------------
// Unification (Most General Unifier)
// ---------------------------------------------------------------------------
/// Check if two effect rows are compatible (can be unified).
/// For closed rows, they must have exactly the same effects.
/// For open rows, we check that the fixed effects are compatible.
fn effect_row_compatible(e1: &EffectRow, e2: &EffectRow) -> bool {
match (e1, e2) {
(EffectRow::Closed(a), EffectRow::Closed(b)) => {
let mut a_sorted = a.clone();
let mut b_sorted = b.clone();
a_sorted.sort();
b_sorted.sort();
a_sorted == b_sorted
}
(EffectRow::Open(a, _), EffectRow::Closed(b))
| (EffectRow::Closed(b), EffectRow::Open(a, _)) => b.iter().all(|e| a.contains(e)),
(EffectRow::Open(a, _), EffectRow::Open(b, _)) => {
// Both sides must agree on fixed effects; row variables are
// assumed compatible (full row unification requires Region
// to participate in the Type::Var substitution machinery,
// which is a larger refactor — see REVIEW plan Phase 1 item 3).
a.iter().all(|e| b.contains(e)) && b.iter().all(|e| a.contains(e))
}
}
}
/// Compute the most general unifier of two types.
/// Returns a substitution `s` such that `apply_subst(t1, s) == apply_subst(t2, s)`.
fn mgu(t1: &Type, t2: &Type, span: Span) -> NuResult<Substitution> {
// Never is a subtype of everything — unify trivially.
if matches!(t1, Type::Primitive(PrimitiveType::Never))
|| matches!(t2, Type::Primitive(PrimitiveType::Never))
{
return Ok(vec![]);
}
if t1 == t2 || (t1.is_ground() && t2.is_ground() && t1.to_ntir().hash() == t2.to_ntir().hash())
{
return Ok(vec![]);
}
match (t1, t2) {
// Identical primitives unify trivially
(Type::Primitive(a), Type::Primitive(b)) if a == b => Ok(vec![]),
// Type variable unification
(Type::Var(v), t) | (t, Type::Var(v)) => var_subst(*v, t, span),
// Functions: unify parameters, returns, effects, and capabilities
(
Type::Function {
param: p1,
ret: r1,
effect: e1,
cap: c1,
},
Type::Function {
param: p2,
ret: r2,
effect: e2,
cap: c2,
},
) => {
if c1 != c2 {
return Err(NuError::type_mismatch(
format!("function with capability {}", c1),
format!("function with capability {}", c2),
span,
));
}
// Check effect row compatibility
if !effect_row_compatible(e1, e2) {
return Err(NuError::type_mismatch(
format!("function with effects {}", e1),
format!("function with effects {}", e2),
span,
));
}
let s1 = mgu(p1, p2, span)?;
let s2 = mgu(&apply_subst(r1, &s1), &apply_subst(r2, &s1), span)?;
Ok(compose_subst(&s2, &s1))
}
// `opaque type X = Y` currently provides ZERO type-level opacity:
// `X` unifies transparently with `Y` (and anything `Y` unifies
// with) everywhere, with no distinction between "inside the
// defining module" and "outside" — there is no enforcement at all
// today, not even a partial/best-effort form. The `opaque` keyword
// is accepted at parse time and carried through the AST/HIR
// (`Type::Nominal`) but is presently equivalent to a plain
// `type X = Y` alias.
//
// Not documented in SPEC2.md or any public-facing doc as a working
// feature (verified 2026-08-01) — this is not a truth-in-advertising
// gap, just an incomplete Experimental-tier feature. Real opacity
// requires module-defining-scope tracking that does not exist
// anywhere in TypeChecker today (mgu has no notion of "which module
// is currently being checked"), which is real design + implementation
// work, not a one-line fix — see the "Future" line above for the
// target shape. Tracked as a real gap; do not read the presence of
// `Type::Nominal` as evidence opacity is enforced.
//
// Future: transparent inside the defining module, opaque outside it.
(Type::Nominal { name, underlying }, other)
| (other, Type::Nominal { name, underlying }) => {
let _ = (name, span);
mgu(underlying, other, span)
}
// Tuples
(Type::Tuple(ts1), Type::Tuple(ts2)) => {
if ts1.len() != ts2.len() {
return Err(NuError::type_mismatch(
format!("tuple of {} elements", ts1.len()),
format!("tuple of {} elements", ts2.len()),
span,
));
}
unify_many(ts1, ts2, span)
}
// Records. Closed records (from literals and annotations) unify
// exactly: identical field sets, pairwise field unification. Records
// with an open row tail (produced by field access on a record of
// not-yet-known shape) unify with scoped rows: shared fields unify
// pairwise and the row variables absorb each other's extra fields; a
// closed record unified with an open one must provide all of the open
// record's fields and closes the row.
(Type::Record(fs1), Type::Record(fs2)) => {
let (fields1, tail1) = split_record(fs1);
let (fields2, tail2) = split_record(fs2);
match (&tail1, &tail2) {
(None, None) => unify_closed_records(&fields1, &fields2, span),
_ => unify_open_records(&fields1, &tail1, &fields2, &tail2, span),
}
}
// Arrays
(Type::Array(t1_inner), Type::Array(t2_inner)) => mgu(t1_inner, t2_inner, span),
// Actors
(
Type::Actor {
state: s1,
behavior: b1,
},
Type::Actor {
state: s2,
behavior: b2,
},
) => {
let s_state = mgu(s1, s2, span)?;
let s_beh = mgu(&apply_subst(b1, &s_state), &apply_subst(b2, &s_state), span)?;
Ok(compose_subst(&s_beh, &s_state))
}
// Reference types
(Type::Reference { cap: c1, inner: i1 }, Type::Reference { cap: c2, inner: i2 }) => {
if c1 != c2 {
return Err(NuError::type_mismatch(
format!("reference with capability {}", c1),
format!("reference with capability {}", c2),
span,
));
}
mgu(i1, i2, span)
}
// Generic type application
(
Type::App {
constructor: c1,
args: a1,
},
Type::App {
constructor: c2,
args: a2,
},
) => {
let s1 = mgu(c1, c2, span)?;
let applied1: Vec<Type> = a1.iter().map(|t| apply_subst(t, &s1)).collect();
let applied2: Vec<Type> = a2.iter().map(|t| apply_subst(t, &s1)).collect();
let s2 = unify_many_app(&applied1, &applied2, span)?;
Ok(compose_subst(&s2, &s1))
}
// Variants: same constructor set, payloads unify pairwise. Required
// for declared variant types (SPEC2 §3.4.1), e.g. unifying the two
// branches of `if b then Some(1) else None`.
(Type::Variant(vs1), Type::Variant(vs2)) => {
if vs1.len() != vs2.len() {
return Err(NuError::type_mismatch(
format!("variant type with {} constructors", vs1.len()),
format!("variant type with {} constructors", vs2.len()),
span,
));
}
// Sort by constructor name so declaration order does not matter.
let mut sorted1 = vs1.clone();
let mut sorted2 = vs2.clone();
sorted1.sort_by(|(a, _), (b, _)| a.cmp(b));
sorted2.sort_by(|(a, _), (b, _)| a.cmp(b));
let mut subst = vec![];
for ((n1, p1), (n2, p2)) in sorted1.iter().zip(sorted2.iter()) {
if n1 != n2 {
return Err(NuError::type_mismatch(
format!("constructor '{}'", n1),
format!("constructor '{}'", n2),
span,
));
}
let s = match (p1, p2) {
(None, None) => continue,
(Some(a), Some(b)) => {
mgu(&apply_subst(a, &subst), &apply_subst(b, &subst), span)?
}
_ => {
return Err(NuError::type_mismatch(
format!("constructor '{}' with payload", n1),
format!("constructor '{}' without payload", n1),
span,
));
}
};
subst = compose_subst(&s, &subst);
}
Ok(subst)
}
// Anything else is a unification error
_ => Err(NuError::type_mismatch(
format!("{}", t1),
format!("{}", t2),
span,
)),
}
}
/// Split a record type's field list into its real fields and its optional
/// row tail, flattening nested record tails (`rho := { y: b | rho2 }`)
/// produced by row unification. A `None` tail means the record is closed.
/// See [`RECORD_ROW_TAIL_FIELD`] for the encoding.
fn split_record(fs: &[(String, Type)]) -> (Vec<(String, Type)>, Option<Type>) {
let mut fields: Vec<(String, Type)> = Vec::new();
let mut current: Vec<(String, Type)> = fs.to_vec();
let tail = loop {
let mut next_tail: Option<Type> = None;
let mut rest: Vec<(String, Type)> = Vec::new();
for (name, ty) in current {
if name == RECORD_ROW_TAIL_FIELD {
next_tail = Some(ty);
} else {
rest.push((name, ty));
}
}
fields.extend(rest);
match next_tail {
Some(Type::Record(inner)) => current = inner,
other => break other,
}
};
(fields, tail)
}
/// Unify two closed records: identical field sets, pairwise field
/// unification. This is the exact pre-row-polymorphism behavior.
fn unify_closed_records(
fs1: &[(String, Type)],
fs2: &[(String, Type)],
span: Span,
) -> NuResult<Substitution> {
if fs1.len() != fs2.len() {
return Err(NuError::type_mismatch(
format!("record with {} fields", fs1.len()),
format!("record with {} fields", fs2.len()),
span,
));
}
// Sort by field name and unify corresponding fields
let mut sorted1 = fs1.to_vec();
let mut sorted2 = fs2.to_vec();
sorted1.sort_by(|(a, _), (b, _)| a.cmp(b));
sorted2.sort_by(|(a, _), (b, _)| a.cmp(b));
let mut subst = vec![];
for ((n1, t1f), (n2, t2f)) in sorted1.iter().zip(sorted2.iter()) {
if n1 != n2 {
return Err(NuError::type_mismatch(
format!("record with field '{}'", n1),
format!("record with field '{}'", n2),
span,
));
}
let s = mgu(&apply_subst(t1f, &subst), &apply_subst(t2f, &subst), span)?;
subst = compose_subst(&s, &subst);
}
Ok(subst)
}
/// Unify two record types where at least one side has an open row tail
/// (standard scoped-rows unification). `fields*` are the real fields and
/// `tail*` the optional row tail as returned by [`split_record`].
///
/// - open ~ open: shared fields unify; each row variable is bound to the
/// other side's extra fields extended with a shared fresh row variable.
/// - open ~ closed: the closed record must provide every field the open
/// side demands; its remaining fields close the row.
fn unify_open_records(
fields1: &[(String, Type)],
tail1: &Option<Type>,
fields2: &[(String, Type)],
tail2: &Option<Type>,
span: Span,
) -> NuResult<Substitution> {
let names1: HashSet<&str> = fields1.iter().map(|(n, _)| n.as_str()).collect();
let names2: HashSet<&str> = fields2.iter().map(|(n, _)| n.as_str()).collect();
// Shared fields unify pairwise (sorted for determinism).
let mut shared: Vec<&str> = names1.intersection(&names2).copied().collect();
shared.sort_unstable();
let lookup = |fs: &[(String, Type)], name: &str| {
fs.iter()
.find(|(n, _)| n == name)
.map(|(_, t)| t.clone())
.expect("shared field must exist")
};
let mut subst: Substitution = vec![];
for name in shared {
let t1f = apply_subst(&lookup(fields1, name), &subst);
let t2f = apply_subst(&lookup(fields2, name), &subst);
let s = mgu(&t1f, &t2f, span)?;
subst = compose_subst(&s, &subst);
}
// Fields present on only one side must be absorbed by the other side's
// row tail.
let extras = |fs: &[(String, Type)], other: &HashSet<&str>| -> Vec<(String, Type)> {
fs.iter()
.filter(|(n, _)| !other.contains(n.as_str()))
.map(|(n, t)| (n.clone(), apply_subst(t, &subst)))
.collect()
};
let extras1 = extras(fields1, &names2);
let extras2 = extras(fields2, &names1);
match (tail1, tail2) {
(Some(Type::Var(r1)), Some(Type::Var(r2))) => {
if r1 == r2 {
// Same row variable on both sides: only unifiable when the
// field sets already agree (otherwise the row would be
// ill-formed, the row analogue of an occurs failure).
if extras1.is_empty() && extras2.is_empty() {
return Ok(subst);
}
return Err(NuError::type_error(
"Incompatible record types: both sides require additional fields \
that cannot be reconciled"
.to_string(),
span,
));
}
let fresh_row = TypeVar::fresh();
let s = mgu(
&Type::Var(*r1),
&Type::record_open(extras2, fresh_row),
span,
)?;
subst = compose_subst(&s, &subst);
let s = mgu(
&Type::Var(*r2),
&Type::record_open(extras1, fresh_row),
span,
)?;
subst = compose_subst(&s, &subst);
Ok(subst)
}
(Some(Type::Var(r)), None) => {
if let Some((missing, _)) = extras1.first() {
let available: Vec<String> = fields2.iter().map(|(n, _)| n.clone()).collect();
return Err(NuError::field_not_found(
missing.clone(),
span,
Some(available),
));
}
let s = mgu(&Type::Var(*r), &Type::record(extras2), span)?;
Ok(compose_subst(&s, &subst))
}
(None, Some(Type::Var(r))) => {
if let Some((missing, _)) = extras2.first() {
let available: Vec<String> = fields1.iter().map(|(n, _)| n.clone()).collect();
return Err(NuError::field_not_found(
missing.clone(),
span,
Some(available),
));
}
let s = mgu(&Type::Var(*r), &Type::record(extras1), span)?;
Ok(compose_subst(&s, &subst))
}
// Row tails are always fresh type variables by construction; a
// residual non-variable tail cannot absorb fields.
_ => Err(NuError::type_error(
"Incompatible record types: the rows cannot be unified".to_string(),
span,
)),
}
}
/// Unify a list of type variable / type pairs (common sub-structures).
fn unify_many_app(types1: &[Type], types2: &[Type], span: Span) -> NuResult<Substitution> {
if types1.len() != types2.len() {
return Err(NuError::type_mismatch(
format!("type list of length {}", types1.len()),
format!("type list of length {}", types2.len()),
span,
));
}
let mut subst = vec![];
for (t1, t2) in types1.iter().zip(types2.iter()) {
let s = mgu(&apply_subst(t1, &subst), &apply_subst(t2, &subst), span)?;
subst = compose_subst(&s, &subst);
}
Ok(subst)
}
/// Unify two lists of types pairwise.
fn unify_many(types1: &[Type], types2: &[Type], span: Span) -> NuResult<Substitution> {
if types1.len() != types2.len() {
return Err(NuError::type_mismatch(
format!("list of {} types", types1.len()),
format!("list of {} types", types2.len()),
span,
));
}
let mut subst = vec![];
for (t1, t2) in types1.iter().zip(types2.iter()) {
let s = mgu(&apply_subst(t1, &subst), &apply_subst(t2, &subst), span)?;
subst = compose_subst(&s, &subst);
}
Ok(subst)
}
/// Create a substitution for a single type variable, with occurs check.
fn var_subst(v: TypeVar, t: &Type, span: Span) -> NuResult<Substitution> {
match t {
Type::Var(v2) if *v2 == v => Ok(vec![]), // t = t
t => {
if occurs_in(v, t) {
return Err(NuError::TypeError {
msg: format!(
"Infinite type: this expression's type references itself. \
This often happens with self-referential definitions \
(e.g., a record that contains itself, or `let f = f`). \
(Type variable {} occurs in {})",
v, t
),
span,
expected_type: None,
found_type: None,
similar_names: None,
});
}
Ok(vec![(v, t.clone())])
}
}
}
/// Check if a type variable occurs within a type (occurs check).
fn occurs_in(v: TypeVar, t: &Type) -> bool {
match t {
Type::Var(v2) => *v2 == v,
Type::Primitive(_) => false,
Type::Tuple(ts) => ts.iter().any(|t| occurs_in(v, t)),
Type::Record(fs) => fs.iter().any(|(_, t)| occurs_in(v, t)),
Type::Variant(vs) => vs
.iter()
.any(|(_, t)| t.as_ref().map_or(false, |t| occurs_in(v, t))),
Type::Array(t) => occurs_in(v, t),
Type::Function { param, ret, .. } => occurs_in(v, param) || occurs_in(v, ret),
Type::Actor { state, behavior } => occurs_in(v, state) || occurs_in(v, behavior),
Type::App { constructor, args } => {
occurs_in(v, constructor) || args.iter().any(|a| occurs_in(v, a))
}
Type::Reference { inner, .. } => occurs_in(v, inner),
Type::Scheme { vars, body } => !vars.contains(&v) && occurs_in(v, body),
Type::Nominal { underlying, .. } => occurs_in(v, underlying),
}
}
// ---------------------------------------------------------------------------
// Instantiation
// ---------------------------------------------------------------------------
/// Instantiate a scheme by replacing all bound type variables with fresh ones.
fn instantiate(ty: &Type) -> Type {
match ty {
Type::Scheme { vars, body } => {
let subst: Substitution = vars
.iter()
.map(|v| (*v, Type::Var(TypeVar::fresh())))
.collect();
apply_subst(body, &subst)
}
_ => ty.clone(),
}
}
// ---------------------------------------------------------------------------
// TypeChecker
// ---------------------------------------------------------------------------
/// Metadata for a registered typeclass.
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct ClassInfo {
pub type_params: Vec<String>,
pub super_classes: Vec<String>,
pub methods: Vec<ClassMethod>,
}
/// Hindley-Milner type checker implementing Algorithm W.
pub struct TypeChecker {
/// Registered typeclass declarations.
pub class_table: FxHashMap<String, ClassInfo>,
/// Registered instance declarations: (class_name, type_name) → methods.
pub instance_table: FxHashMap<(String, String), Vec<ImplMethod>>,
/// Inferred types for top-level declarations, populated by `check_module`.
/// Keyed by declaration name; for functions this is the function type,
/// for let bindings this is the inferred value type.
pub inferred_decl_types: FxHashMap<String, Type>,
/// Contextual `given` bindings: name → (type annotation, value expression).
pub given_bindings: FxHashMap<String, (Option<Type>, Expr)>,
/// Functions with `using` params: fn_name → using param names.
pub fn_using_params: FxHashMap<String, Vec<String>>,
}
/// Pre-computed class and instance tables extracted from an AST module.
/// Shared between the typechecker and HIR lowering so both can resolve
/// typeclass method calls.
#[derive(Debug, Clone, Default)]
pub struct ClassTables {
pub class_table: FxHashMap<String, ClassInfo>,
pub instance_table: FxHashMap<(String, String), Vec<ImplMethod>>,
}
/// Build class and instance tables by scanning a module's declarations.
/// This is the shared extraction logic — `TypeChecker::register_class_decls`
/// delegates to it, and `hir_lower::lower_module` calls it independently.
pub fn build_class_tables(module: &AstModule) -> ClassTables {
let mut tables = ClassTables::default();
for decl in flatten_decls(&module.decls) {
match decl {
Decl::Class {
name,
type_params,
super_classes,
methods,
..
} => {
tables.class_table.insert(
name.clone(),
ClassInfo {
type_params: type_params.clone(),
super_classes: super_classes.clone(),
methods: methods.clone(),
},
);
}
Decl::Impl {
class_name,
for_type,
methods,
..
} => {
let type_key = format!("{}", for_type);
tables
.instance_table
.insert((class_name.clone(), type_key), methods.clone());
}
_ => {}
}
}
tables
}
/// Recursively splice any `Decl::Module { decls, .. }` in place with its own
/// contents, in source order, leaving every other declaration untouched.
///
/// This mirrors the stable compiler's `collect_functions`/`compile_decl`,
/// which recurse into nested modules and register their contents in the same
/// flat, unqualified namespace as top-level decls — modules are a namespacing
/// construct only, with no enforced visibility boundary.
fn flatten_decls(decls: &[Decl]) -> Vec<&Decl> {
let mut out = Vec::with_capacity(decls.len());
for decl in decls {
match decl {
Decl::Module { decls: inner, .. } => out.extend(flatten_decls(inner)),
_ => out.push(decl),
}
}
out
}
impl TypeChecker {
/// Create a new type checker with an empty context.
pub fn new() -> Self {
TypeChecker {
class_table: FxHashMap::default(),
instance_table: FxHashMap::default(),
inferred_decl_types: FxHashMap::default(),
given_bindings: FxHashMap::default(),
fn_using_params: FxHashMap::default(),
}
}
/// Type-check an entire module, returning the type of the last declaration.
///
pub fn register_class_decls(&mut self, module: &AstModule) {
let tables = build_class_tables(module);
self.class_table = tables.class_table;
self.instance_table = tables.instance_table;
}
/// Type-check an entire module, returning the type of the last declaration.
pub fn check_module(&mut self, module: &AstModule) -> NuResult<Type> {
self.register_class_decls(module);
let mut ctx = TypeContext::new();
let mut last_type = Type::unit();
for decl in flatten_decls(&module.decls) {
let (s, ty) = self.infer_decl(&ctx, decl)?;
ctx = apply_subst_to_ctx(&ctx, &s);
let final_ty = apply_subst(&ty, &s);
match decl {
Decl::Function {
name, using_params, ..
} => {
if !using_params.is_empty() {
self.fn_using_params.insert(
name.clone(),
using_params.iter().map(|(n, _)| n.clone()).collect(),
);
}
self.inferred_decl_types
.insert(name.clone(), final_ty.clone());
let gen_ty = self.do_generalize(&ctx, &final_ty);
ctx.bind(name.clone(), gen_ty, Capability::Ref, false);
}
Decl::Actor { name, .. } => {
ctx.bind(name.clone(), final_ty.clone(), Capability::Ref, false);
}
Decl::StateMachine { name, .. } => {
ctx.bind(name.clone(), final_ty.clone(), Capability::Ref, false);
}
Decl::Extern { funcs, .. } => {
for func in funcs {
let param_types: Vec<Type> =
func.params.iter().map(|(_, t)| t.clone()).collect();
let param_ty = if param_types.len() == 1 {
param_types[0].clone()
} else {
Type::Tuple(param_types)
};
let func_ty = Type::Function {
param: Box::new(param_ty),
ret: Box::new(func.ret.clone()),
effect: EffectRow::singleton(Effect::FFI),
cap: Capability::Ref,
};
ctx.bind(func.name.clone(), func_ty, Capability::Ref, false);
}
}
Decl::Workflow { name, .. } => {
ctx.bind(name.clone(), final_ty.clone(), Capability::Ref, false);
}
Decl::Agent { name, .. } => {
ctx.bind(name.clone(), final_ty.clone(), Capability::Ref, false);
}
Decl::VariantType { variants, .. } => {
// Bind each constructor (SPEC2 §3.4.1): a constructor with
// a payload is a function from the payload type to the
// variant type; a nullary constructor is a plain value of
// the variant type. Declared type parameters (e.g. `T` in
// `Option[T]`) stay free in the payload types parsed from
// the declaration and are generalized per constructor, so
// each use instantiates them fresh.
let variant_ty = Type::Variant(variants.clone());
for (ctor_name, payload) in variants {
let ctor_ty = match payload {
Some(payload_ty) => Type::Function {
param: Box::new(payload_ty.clone()),
ret: Box::new(variant_ty.clone()),
effect: EffectRow::empty(),
cap: Capability::Ref,
},
None => variant_ty.clone(),
};
let gen_ty = self.do_generalize(&ctx, &ctor_ty);
ctx.bind(ctor_name.clone(), gen_ty, Capability::Ref, false);
}
}
Decl::Class { name, .. } => {
// Bind class name as a type-level marker; runtime value
// is unit — classes constrain type variables at compile
// time and have no runtime representation.
ctx.bind(name.clone(), Type::unit(), Capability::Ref, false);
}
Decl::Impl {
class_name,
for_type,
..
} => {
// Bind the instance dictionary under a synthetic name
// so instance-lookup can resolve it at call sites.
let dict_name = format!("_impl_{}_{}", class_name, for_type);
ctx.bind(dict_name, final_ty.clone(), Capability::Ref, false);
}
Decl::LetBinding { name, .. } => {
self.inferred_decl_types
.insert(name.clone(), final_ty.clone());
let gen_ty = self.do_generalize(&ctx, &final_ty);
ctx.bind(name.clone(), gen_ty, Capability::Ref, false);
}
_ => {}
}
last_type = final_ty;
}
// Verify behavior contracts for actors with `implements` clauses.
self.verify_behavior_contracts(module)?;
Ok(last_type)
}
/// Verify that every actor declaring `implements <contract>` actually
/// provides all required handler behaviors with compatible signatures.
fn verify_behavior_contracts(&self, module: &AstModule) -> NuResult<()> {
for decl in &module.decls {
self.verify_decl_contracts(decl)?;
}
Ok(())
}
fn verify_decl_contracts(&self, decl: &Decl) -> NuResult<()> {
match decl {
Decl::Actor {
name,
behaviors,
implements,
span,
..
} => {
if let Some(contract_name) = implements {
let contract = crate::stdlib::lookup_contract(contract_name);
match contract {
Some(c) => {
for &(handler_name, param_count) in c.required_handlers {
let found = behaviors.iter().any(|b| {
b.name == handler_name && b.params.len() == param_count
});
if !found {
let msg = format!(
"actor '{}' declares it implements '{}' but is missing required handler '{}' (expects {} parameter(s))",
name, contract_name, handler_name, param_count
);
return Err(NuError::TypeError {
msg,
span: *span,
expected_type: None,
found_type: None,
similar_names: None,
});
}
}
}
None => {
let msg = format!(
"unknown behavior contract '{}' in actor '{}'",
contract_name, name
);
return Err(NuError::TypeError {
msg,
span: *span,
expected_type: None,
found_type: None,
similar_names: None,
});
}
}
}
}
Decl::Module { decls, .. } => {
for d in decls {
self.verify_decl_contracts(d)?;
}
}
_ => {}
}
Ok(())
}
/// Infer the type of a declaration.
pub(crate) fn infer_decl(
&mut self,
ctx: &TypeContext,
decl: &Decl,
) -> NuResult<(Substitution, Type)> {
match decl {
Decl::Function {
name,