forked from nulang-org/nulang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtypes.rs
More file actions
2335 lines (2180 loc) · 82.3 KB
/
Copy pathtypes.rs
File metadata and controls
2335 lines (2180 loc) · 82.3 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
//! Shared type definitions used across all Nulang compiler and runtime modules.
use crate::type_ir::NtirNode;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
// 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 Variables & Regions
// ---------------------------------------------------------------------------
static TYPE_VAR_COUNTER: AtomicU64 = AtomicU64::new(1);
static REGION_COUNTER: AtomicU64 = AtomicU64::new(1);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct TypeVar(pub u64);
impl std::fmt::Display for TypeVar {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "'_")
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Region(pub u64);
impl TypeVar {
pub fn fresh() -> Self {
TypeVar(TYPE_VAR_COUNTER.fetch_add(1, Ordering::Relaxed))
}
}
impl Region {
pub fn fresh() -> Region {
Region(REGION_COUNTER.fetch_add(1, Ordering::Relaxed))
}
}
// ---------------------------------------------------------------------------
// Primitive Types
// ---------------------------------------------------------------------------
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum PrimitiveType {
Int,
Float,
Bool,
String,
Nil,
Unit,
Never,
Address, // Actor address
}
// ---------------------------------------------------------------------------
// Reference Capabilities (Pony-inspired)
// ---------------------------------------------------------------------------
/// Reference capability lattice:
/// ```text
/// LinearIso
/// / \
/// Iso Linear
/// / \ /
/// Trn Val<--/
/// | |
/// Ref Box
/// \ /
/// Tag
/// ```
/// Subtyping: lineariso <: iso <: trn <: ref <: box, linear <: val <: box, ref <: tag, val <: tag, box <: tag
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Capability {
LinearIso, // Unique ownership with linear type tracking (provably consumed exactly once)
Linear, // Immutable + linear-tracked + remote-sendable ("linear Val")
Iso, // Unique ownership (can be sent to another actor)
Trn, // Unique writer (can be recovered to iso)
Ref, // Shared read/write reference
Val, // Immutable shared reference (sendable)
Box, // Read-only reference (any cap except tag can be read as box)
Tag, // Opaque identity only (tagged pointer, no dereference)
}
impl std::fmt::Display for Capability {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Capability::LinearIso => write!(f, "lineariso"),
Capability::Linear => write!(f, "linear"),
Capability::Iso => write!(f, "iso"),
Capability::Trn => write!(f, "trn"),
Capability::Ref => write!(f, "ref"),
Capability::Val => write!(f, "val"),
Capability::Box => write!(f, "box"),
Capability::Tag => write!(f, "tag"),
}
}
}
impl Capability {
/// Least upper bound (join) of two capabilities.
///
/// LinearIso behaves like Iso in joins, except LinearIso ⊔ LinearIso = LinearIso.
pub fn join(self, other: Capability) -> Capability {
use Capability::*;
match (self, other) {
// LinearIso joins: LinearIso + LinearIso stays LinearIso
(LinearIso, LinearIso) => LinearIso,
// LinearIso + Iso promotes to Iso (linear obligation can be discharged)
(LinearIso, Iso) | (Iso, LinearIso) => Iso,
// LinearIso with Trn (same as Iso with Trn)
(LinearIso, Trn) | (Trn, LinearIso) => Trn,
// LinearIso with Ref (same as Iso with Ref)
(LinearIso, Ref) | (Ref, LinearIso) => Ref,
// LinearIso with Val (same as Iso with Val)
(LinearIso, Val) | (Val, LinearIso) => Val,
// LinearIso with Box (same as Iso with Box)
(LinearIso, Box) | (Box, LinearIso) => Box,
// LinearIso with Tag (same as Iso with Tag)
(LinearIso, Tag) | (Tag, LinearIso) => LinearIso,
// Linear joins: Linear behaves like Val except Linear join Linear = Linear
(Linear, Linear) => Linear,
(Linear, Val) | (Val, Linear) => Val,
(Linear, LinearIso) | (LinearIso, Linear) => Val,
(Linear, Iso) | (Iso, Linear) => Val,
(Linear, Trn) | (Trn, Linear) => Val,
(Linear, Ref) | (Ref, Linear) => Box,
(Linear, Box) | (Box, Linear) => Box,
(Linear, Tag) | (Tag, Linear) => Linear,
// Original capability joins (unchanged)
(Iso, Iso) => Iso,
(Iso, Trn) | (Trn, Iso) | (Trn, Trn) => Trn,
(Iso, Ref) | (Ref, Iso) | (Trn, Ref) | (Ref, Trn) | (Ref, Ref) => Ref,
(Iso, Val) | (Val, Iso) | (Trn, Val) | (Val, Trn) | (Val, Val) => Val,
(Ref, Val) | (Val, Ref) => Box,
(Iso, Box)
| (Box, Iso)
| (Trn, Box)
| (Box, Trn)
| (Ref, Box)
| (Box, Ref)
| (Val, Box)
| (Box, Val)
| (Box, Box) => Box,
(Tag, c) | (c, Tag) if c == Tag => Tag,
(Tag, c) | (c, Tag) => c, // tag is bottom-ish for read-only
}
}
/// Check if self <: other (self is a subtype of other).
pub fn is_subtype_of(self, other: Capability) -> bool {
self.join(other) == other
}
/// Can this capability be sent to another actor?
pub fn is_sendable(self) -> bool {
matches!(
self,
Capability::LinearIso
| Capability::Linear
| Capability::Iso
| Capability::Val
| Capability::Tag
)
}
/// Can this capability be sent over the network (serializable)?
pub fn is_remote_sendable(self) -> bool {
matches!(self, Capability::Linear | Capability::Val | Capability::Tag)
}
/// Can this capability be read through?
pub fn is_readable(self) -> bool {
!matches!(self, Capability::Tag)
}
/// Can this capability be written through?
pub fn is_writable(self) -> bool {
matches!(
self,
Capability::LinearIso | Capability::Iso | Capability::Trn | Capability::Ref
)
}
/// Is this a linear capability (requires exactly-one consumption tracking)?
pub fn is_linear(self) -> bool {
matches!(self, Capability::LinearIso | Capability::Linear)
}
/// Discharge linear tracking: LinearIso→Iso, Linear→Val.
pub fn discharge_linear(self) -> Capability {
match self {
Capability::LinearIso => Capability::Iso,
Capability::Linear => Capability::Val,
other => other,
}
}
#[deprecated(note = "use discharge_linear")]
pub fn promote_to_iso(self) -> Capability {
self.discharge_linear()
}
}
// ---------------------------------------------------------------------------
// Effect Rows (Koka-inspired, row polymorphism)
// ---------------------------------------------------------------------------
/// A built-in or user-defined effect.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Effect {
IO,
Net,
String,
FS,
Rand,
Time,
Spawn,
Send,
Receive,
Migrate,
STM,
Async,
Inference,
Cost,
Event,
Array,
FFI,
Test,
DB,
Env,
Process,
System,
UserDefined(String),
}
impl std::fmt::Display for Effect {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Effect::IO => write!(f, "IO"),
Effect::Net => write!(f, "Net"),
Effect::String => write!(f, "String"),
Effect::FS => write!(f, "FS"),
Effect::Array => write!(f, "Array"),
Effect::Rand => write!(f, "Rand"),
Effect::Time => write!(f, "Time"),
Effect::Spawn => write!(f, "Spawn"),
Effect::Send => write!(f, "Send"),
Effect::Receive => write!(f, "Receive"),
Effect::Migrate => write!(f, "Migrate"),
Effect::STM => write!(f, "STM"),
Effect::Async => write!(f, "Async"),
Effect::Inference => write!(f, "Inference"),
Effect::Cost => write!(f, "Cost"),
Effect::Event => write!(f, "Event"),
Effect::FFI => write!(f, "FFI"),
Effect::Test => write!(f, "Test"),
Effect::DB => write!(f, "DB"),
Effect::Env => write!(f, "Env"),
Effect::Process => write!(f, "Process"),
Effect::System => write!(f, "System"),
Effect::UserDefined(s) => write!(f, "{}", s),
}
}
}
/// Effect row: either closed (fixed set) or open (set + row variable).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum EffectRow {
Closed(Vec<Effect>),
Open(Vec<Effect>, Region),
}
impl std::fmt::Display for EffectRow {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
EffectRow::Closed(effects) => {
write!(f, "{{")?;
for (i, e) in effects.iter().enumerate() {
if i > 0 {
write!(f, ", ")?;
}
write!(f, "{}", e)?;
}
write!(f, "}}")
}
EffectRow::Open(effects, _) => {
write!(f, "{{")?;
for (i, e) in effects.iter().enumerate() {
if i > 0 {
write!(f, ", ")?;
}
write!(f, "{}", e)?;
}
if !effects.is_empty() {
write!(f, ", ")?;
}
write!(f, "..}}")
}
}
}
}
impl EffectRow {
pub fn empty() -> Self {
EffectRow::Closed(vec![])
}
pub fn singleton(e: Effect) -> Self {
EffectRow::Closed(vec![e])
}
/// Row concatenation.
pub fn combine(self, other: EffectRow) -> EffectRow {
match (self, other) {
(EffectRow::Closed(mut a), EffectRow::Closed(b)) => {
a.extend(b);
EffectRow::Closed(a)
}
(EffectRow::Closed(mut a), EffectRow::Open(b, r))
| (EffectRow::Open(mut a, r), EffectRow::Closed(b)) => {
a.extend(b);
EffectRow::Open(a, r)
}
(EffectRow::Open(mut a, r1), EffectRow::Open(b, _)) => {
// Open rows share the same row variable convention
a.extend(b);
EffectRow::Open(a, r1)
}
}
}
/// Check if a specific effect is in this row.
pub fn contains(&self, eff: &Effect) -> bool {
match self {
EffectRow::Closed(effects) => effects.contains(eff),
EffectRow::Open(effects, _) => effects.contains(eff),
}
}
/// Remove an effect from this row (for handled effects).
pub fn remove(self, eff: &Effect) -> EffectRow {
match self {
EffectRow::Closed(effects) => {
EffectRow::Closed(effects.into_iter().filter(|e| e != eff).collect())
}
EffectRow::Open(effects, r) => {
EffectRow::Open(effects.into_iter().filter(|e| e != eff).collect(), r)
}
}
}
/// Get the set of effects (ignoring row variable).
pub fn effects(&self) -> &[Effect] {
match self {
EffectRow::Closed(effects) => effects,
EffectRow::Open(effects, _) => effects,
}
}
}
// ---------------------------------------------------------------------------
// Core Type
// ---------------------------------------------------------------------------
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Type {
/// Type variable (for inference)
Var(TypeVar),
/// Primitive type
Primitive(PrimitiveType),
/// Tuple (A, B, ...)
Tuple(Vec<Type>),
/// Record { field: Type, ... }
///
/// A record whose field list ends with the reserved pseudo-field
/// [`RECORD_ROW_TAIL_FIELD`] is an *open* record: the pseudo-field's type
/// is a row variable standing for "possibly more fields". Records from
/// literals and annotations are always closed (no tail).
Record(Vec<(String, Type)>),
/// Variant Type1 | Type2 | ...
Variant(Vec<(String, Option<Type>)>),
/// Array [Type]
Array(Box<Type>),
/// Function: arg type -> return type with effect row and capability
Function {
param: Box<Type>,
ret: Box<Type>,
effect: EffectRow,
cap: Capability,
},
/// Actor[State, Behavior]
Actor {
state: Box<Type>,
behavior: Box<Type>,
},
/// Generic type application: List[Int], Map[String, Int]
App {
constructor: Box<Type>,
args: Vec<Type>,
},
/// Reference type with capability: &cap Type
Reference { cap: Capability, inner: Box<Type> },
/// Existential / type scheme: forall vars. Type
Scheme { vars: Vec<TypeVar>, body: Box<Type> },
/// Nominal (opaque) type: `opaque type UserId = Int`.
/// Distinct from its underlying type at compile time, erases at runtime.
Nominal { name: String, underlying: Box<Type> },
}
impl std::fmt::Display for Type {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Type::Var(v) => write!(f, "{}", v),
Type::Primitive(p) => match p {
PrimitiveType::Int => write!(f, "Int"),
PrimitiveType::Float => write!(f, "Float"),
PrimitiveType::Bool => write!(f, "Bool"),
PrimitiveType::String => write!(f, "String"),
PrimitiveType::Unit => write!(f, "Unit"),
PrimitiveType::Nil => write!(f, "Nil"),
PrimitiveType::Never => write!(f, "Never"),
PrimitiveType::Address => write!(f, "Address"),
},
Type::Tuple(ts) => {
write!(f, "(")?;
for (i, t) in ts.iter().enumerate() {
if i > 0 {
write!(f, ", ")?;
}
write!(f, "{}", t)?;
}
write!(f, ")")
}
Type::Record(fs) => {
write!(f, "{{ ")?;
for (i, (n, t)) in fs.iter().enumerate() {
if i > 0 {
write!(f, ", ")?;
}
write!(f, "{}: {}", n, t)?;
}
write!(f, " }}")
}
Type::Variant(vs) => {
for (i, (n, t)) in vs.iter().enumerate() {
if i > 0 {
write!(f, " | ")?;
}
match t {
Some(t) => write!(f, "{} {}", n, t)?,
None => write!(f, "{}", n)?,
}
}
Ok(())
}
Type::Array(t) => write!(f, "[{}]", t),
Type::Function {
param,
ret,
effect: _,
cap: _,
} => {
write!(f, "{} -> {}", param, ret)
}
Type::Actor { state, behavior } => {
write!(f, "Actor[{}, {}]", state, behavior)
}
Type::App { constructor, args } => {
write!(f, "{}", constructor)?;
if !args.is_empty() {
write!(f, "[")?;
for (i, a) in args.iter().enumerate() {
if i > 0 {
write!(f, ", ")?;
}
write!(f, "{}", a)?;
}
write!(f, "]")?;
}
Ok(())
}
Type::Reference { cap, inner } => write!(f, "&{} {}", cap, inner),
Type::Scheme { vars, body } => {
write!(f, "forall ")?;
for (i, v) in vars.iter().enumerate() {
if i > 0 {
write!(f, ", ")?;
}
write!(f, "'t{}", v.0)?;
}
write!(f, ". {}", body)
}
Type::Nominal { name, .. } => write!(f, "{}", name),
}
}
}
/// Reserved pseudo-field name carrying the *row tail* of an open record type.
///
/// Record row polymorphism is encoded without changing the shape of
/// `Type::Record(Vec<(String, Type)>)` — exhaustive matches on `Type` exist
/// across the crate (`main.rs`, `repl.rs`, `mir_codegen.rs`, `tool_schema.rs`),
/// so the representation stays additive. An open record `{ x: a | rho }` is
/// represented as `Record([("x", a), ("..", Var(rho))])`. The name `".."`
/// can never collide with a user field: record field names are parsed with
/// `expect_ident`, and `".."` is not a valid identifier.
///
/// The tail's type is a fresh `Type::Var` when produced; record unification
/// may substitute it with an open record (row extension) or a closed record
/// (row closing). Because the row variable is an ordinary type variable in an
/// ordinary field, `free_vars`, `ref_free_vars`, substitution, the occurs
/// check, and generalization all handle it with no special casing.
pub const RECORD_ROW_TAIL_FIELD: &str = "..";
impl Type {
/// Convert to an NTIR structural representation for content-addressed hashing.
pub fn to_ntir(&self) -> NtirNode {
self.to_ntir_with_stack(&mut Vec::new())
}
fn to_ntir_with_stack(&self, stack: &mut Vec<TypeVar>) -> NtirNode {
if let Type::Var(v) = self {
if let Some(pos) = stack.iter().rev().position(|x| x == v) {
return NtirNode::Cycle(pos as u64);
}
}
let push_var = if let Type::Var(v) = self {
stack.push(*v);
true
} else {
false
};
let res = match self {
Type::Var(_) => NtirNode::Primitive(PrimitiveType::Unit),
Type::Primitive(p) => NtirNode::Primitive(p.clone()),
Type::Tuple(ts) => {
NtirNode::Tuple(ts.iter().map(|t| t.to_ntir_with_stack(stack)).collect())
}
Type::Record(fs) => {
let mut mapped: Vec<_> = fs
.iter()
.map(|(n, t)| (n.clone(), t.to_ntir_with_stack(stack)))
.collect();
mapped.sort_by(|a, b| a.0.cmp(&b.0));
NtirNode::Record(mapped)
}
Type::Variant(vs) => {
let mut mapped: Vec<_> = vs
.iter()
.map(|(n, t_opt)| {
let t_ntir = match t_opt {
Some(t) => t.to_ntir_with_stack(stack),
None => NtirNode::Primitive(PrimitiveType::Unit),
};
(n.clone(), t_ntir)
})
.collect();
mapped.sort_by(|a, b| a.0.cmp(&b.0));
NtirNode::Variant(mapped)
}
Type::Array(inner) => NtirNode::Tuple(vec![inner.to_ntir_with_stack(stack)]),
Type::Function {
param, ret, cap, ..
} => NtirNode::Capability(
*cap,
Box::new(NtirNode::Tuple(vec![
param.to_ntir_with_stack(stack),
ret.to_ntir_with_stack(stack),
])),
),
Type::Actor { state, behavior } => NtirNode::Tuple(vec![
state.to_ntir_with_stack(stack),
behavior.to_ntir_with_stack(stack),
]),
Type::App { constructor, args } => {
let mut elems = vec![constructor.to_ntir_with_stack(stack)];
for a in args {
elems.push(a.to_ntir_with_stack(stack));
}
NtirNode::Tuple(elems)
}
Type::Reference { cap, inner } => {
NtirNode::Capability(*cap, Box::new(inner.to_ntir_with_stack(stack)))
}
Type::Scheme { body, .. } => body.to_ntir_with_stack(stack),
Type::Nominal { underlying, .. } => underlying.to_ntir_with_stack(stack),
};
if push_var {
stack.pop();
}
res
}
/// True if the type contains no free type variables.
pub fn is_ground(&self) -> bool {
let mut fv = Vec::new();
self.collect_free_vars(&mut fv);
fv.is_empty()
}
pub fn int() -> Type {
Type::Primitive(PrimitiveType::Int)
}
/// A closed record type: exactly the given fields. Record literals and
/// annotations are always closed.
pub fn record(fields: Vec<(String, Type)>) -> Type {
Type::Record(fields)
}
/// An open record type: the given fields plus a fresh row variable
/// standing for "possibly more fields". Produced by field access on a
/// record of not-yet-known shape; see [`RECORD_ROW_TAIL_FIELD`].
pub fn record_open(fields: Vec<(String, Type)>, row: TypeVar) -> Type {
let mut fields = fields;
fields.push((RECORD_ROW_TAIL_FIELD.to_string(), Type::Var(row)));
Type::Record(fields)
}
pub fn float() -> Type {
Type::Primitive(PrimitiveType::Float)
}
pub fn bool() -> Type {
Type::Primitive(PrimitiveType::Bool)
}
pub fn string() -> Type {
Type::Primitive(PrimitiveType::String)
}
pub fn nil() -> Type {
Type::Primitive(PrimitiveType::Nil)
}
pub fn unit() -> Type {
Type::Primitive(PrimitiveType::Unit)
}
/// Free type variables in this type.
pub fn free_vars(&self) -> Vec<TypeVar> {
let mut vars = vec![];
self.collect_free_vars(&mut vars);
vars.sort_by_key(|v| v.0);
vars.dedup_by_key(|v| v.0);
vars
}
/// Free type variables that occur underneath a `Reference` constructor.
///
/// Used for the value restriction at generalization: a reference cell is
/// created once at binding time and shared by every use of the binding, so
/// quantifying a variable under a `Reference` would let one cell be used at
/// incompatible types. Function types are not descended into — a reference
/// in a function's parameter or return type is created per call, so
/// quantifying it is sound.
pub fn ref_free_vars(&self) -> Vec<TypeVar> {
let mut vars = vec![];
self.collect_ref_free_vars(&mut vars);
vars.sort_by_key(|v| v.0);
vars.dedup_by_key(|v| v.0);
vars
}
fn collect_ref_free_vars(&self, acc: &mut Vec<TypeVar>) {
match self {
// The shared cell: every free variable inside must stay monomorphic.
Type::Reference { inner, .. } => inner.collect_free_vars(acc),
// Function values are created per call — refs in their types are safe.
Type::Function { .. } => {}
Type::Tuple(ts) => ts.iter().for_each(|t| t.collect_ref_free_vars(acc)),
Type::Record(fs) => fs.iter().for_each(|(_, t)| t.collect_ref_free_vars(acc)),
Type::Variant(vs) => vs.iter().for_each(|(_, t)| {
if let Some(t) = t {
t.collect_ref_free_vars(acc)
}
}),
Type::Array(t) => t.collect_ref_free_vars(acc),
Type::Actor { state, behavior } => {
state.collect_ref_free_vars(acc);
behavior.collect_ref_free_vars(acc);
}
Type::App { constructor, args } => {
constructor.collect_ref_free_vars(acc);
args.iter().for_each(|a| a.collect_ref_free_vars(acc));
}
Type::Scheme { body, .. } => body.collect_ref_free_vars(acc),
Type::Nominal { underlying, .. } => underlying.collect_ref_free_vars(acc),
Type::Var(_) | Type::Primitive(_) => {}
}
}
fn collect_free_vars(&self, acc: &mut Vec<TypeVar>) {
match self {
Type::Var(v) => acc.push(*v),
Type::Primitive(_) => {}
Type::Tuple(ts) => ts.iter().for_each(|t| t.collect_free_vars(acc)),
Type::Record(fs) => fs.iter().for_each(|(_, t)| t.collect_free_vars(acc)),
Type::Variant(vs) => vs.iter().for_each(|(_, t)| {
if let Some(t) = t {
t.collect_free_vars(acc)
}
}),
Type::Array(t) => t.collect_free_vars(acc),
Type::Function { param, ret, .. } => {
param.collect_free_vars(acc);
ret.collect_free_vars(acc);
}
Type::Actor { state, behavior } => {
state.collect_free_vars(acc);
behavior.collect_free_vars(acc);
}
Type::App { constructor, args } => {
constructor.collect_free_vars(acc);
args.iter().for_each(|a| a.collect_free_vars(acc));
}
Type::Reference { inner, .. } => inner.collect_free_vars(acc),
Type::Scheme { vars, body } => {
body.collect_free_vars(acc);
// Remove bound vars
acc.retain(|v| !vars.contains(v));
}
Type::Nominal { underlying, .. } => underlying.collect_free_vars(acc),
}
}
}
// ---------------------------------------------------------------------------
// Type Context (Gamma)
// ---------------------------------------------------------------------------
/// Typing context: maps variable names to their (type, capability) bindings.
///
/// Linear (`LinearIso`) consumption is tracked separately by the capability
/// analyzer (`CapabilityAnalyzer` in `src/effect_checker.rs`), not here.
#[derive(Debug, Clone, Default)]
pub struct TypeContext {
bindings: HashMap<String, (Type, Capability, bool)>,
/// Event declarations from the enclosing entity (if any). Used by the
/// typechecker to validate `emit EventName(args)` calls. Stored as
/// `(event_name, [(param_name, param_type)])`.
pub entity_events: Option<Vec<(String, Vec<(String, Type)>)>>,
/// Typeclass constraints on type variables: maps each type variable to
/// the list of class names it must satisfy. Populated when a function
/// signature declares `fn f[T: Eq, Ord](...)` or through `where` clauses.
/// Checked by instance-lookup (B.4) when a concrete type is substituted.
pub constraints: FxHashMap<TypeVar, Vec<String>>,
}
impl TypeContext {
pub fn new() -> Self {
Self::default()
}
/// Bind a variable name to a type, capability, and mutability.
pub fn bind(&mut self, name: impl Into<String>, ty: Type, cap: Capability, mutable: bool) {
let name = name.into();
self.bindings.insert(name, (ty, cap, mutable));
}
/// Look up a variable's type, capability, and mutability.
pub fn lookup(&self, name: &str) -> Option<&(Type, Capability, bool)> {
self.bindings.get(name)
}
/// Create an extended context with an additional binding.
pub fn extend(
&self,
name: impl Into<String>,
ty: Type,
cap: Capability,
mutable: bool,
) -> Self {
let mut ctx = self.clone();
ctx.bind(name, ty, cap, mutable);
ctx
}
/// Set the entity event declarations for emit validation.
pub fn set_entity_events(&mut self, events: Vec<(String, Vec<(String, Type)>)>) {
self.entity_events = Some(events);
}
/// Record that a type variable must satisfy a class constraint.
/// Multiple constraints on the same variable are accumulated.
pub fn add_constraint(&mut self, tv: TypeVar, class_name: &str) {
self.constraints
.entry(tv)
.or_default()
.push(class_name.to_string());
}
/// Look up the constraints on a type variable, if any.
pub fn get_constraints(&self, tv: &TypeVar) -> Option<&Vec<String>> {
self.constraints.get(tv)
}
/// Iterate over all bindings as `(name, (type, capability, mutable))` tuples.
pub fn iter(&self) -> impl Iterator<Item = (&String, &(Type, Capability, bool))> {
self.bindings.iter()
}
/// Free type variables occurring in any binding in the context.
pub fn free_vars(&self) -> Vec<TypeVar> {
let mut vars = vec![];
for (ty, _, _) in self.bindings.values() {
vars.extend(ty.free_vars());
}
vars.sort_by_key(|v| v.0);
vars.dedup_by_key(|v| v.0);
vars
}
}
// ---------------------------------------------------------------------------
// Source Location
// ---------------------------------------------------------------------------
// Source Map (offset -> line/column resolution)
// ---------------------------------------------------------------------------
use std::cell::RefCell;
thread_local! {
/// Thread-local source map used by Span::line()/column() to resolve byte
/// offsets into human-readable positions. Set once per compilation unit
/// (by the lexer or test harness) before any Span display.
static SOURCE_MAP: RefCell<Option<SourceMap>> = RefCell::new(None);
}
/// Maps byte offsets to line:column positions for error reporting.
///
/// Retains the full source text so that error formatters can produce
/// source-code excerpts without re-reading from disk.
#[derive(Debug, Clone)]
pub struct SourceMap {
/// Byte offset of the start of each line. line_starts[0] is always 0.
line_starts: Vec<u32>,
/// The full source text (retained for source excerpts in error messages).
source: String,
/// Optional file path (e.g. "main.nula"); used in `--> file:line:col`.
file_path: Option<String>,
}
impl SourceMap {
/// Build a source map from source text. Line endings are `\n` only.
pub fn new(source: &str) -> Self {
Self::with_file(source, None)
}
/// Build a source map with an optional file path for richer diagnostics.
pub fn with_file(source: &str, file_path: Option<&str>) -> Self {
let mut line_starts = vec![0u32];
for (i, &b) in source.as_bytes().iter().enumerate() {
if b == b'\n' {
line_starts.push(i as u32 + 1);
}
}
SourceMap {
line_starts,
source: source.to_string(),
file_path: file_path.map(|s| s.to_string()),
}
}
/// Resolve a byte offset to (1-indexed line, 1-indexed column).
pub fn line_col(&self, offset: u32) -> (usize, usize) {
let idx = match self.line_starts.binary_search(&offset) {
Ok(i) => i,
Err(i) => i.saturating_sub(1),
};
let line = idx + 1;
let col = offset.saturating_sub(self.line_starts[idx]) + 1;
(line, col as usize)
}
/// Return the 1-indexed source line (without trailing newline), if in range.
pub fn source_line(&self, line: usize) -> Option<&str> {
if line == 0 || line > self.line_starts.len() {
return None;
}
let start = self.line_starts[line - 1] as usize;
let end = if line < self.line_starts.len() {
// End before the next line's start, skipping the `\n`.
(self.line_starts[line] as usize).saturating_sub(1)
} else {
self.source.len()
};
if start <= end && start <= self.source.len() {
Some(&self.source[start..end.min(self.source.len())])
} else {
None
}
}
/// Return a slice of source text from `offset` for `len` bytes.
pub fn source_slice(&self, offset: u32, len: u32) -> Option<&str> {
let start = offset as usize;
let end = (start + len as usize).min(self.source.len());
if start < self.source.len() {
Some(&self.source[start..end])
} else {
None
}
}
/// Return the optional file path stored in this map.
pub fn file_path(&self) -> Option<&str> {
self.file_path.as_deref()
}
}
/// Install a SourceMap for the current thread, consuming the source string
/// to build line-start offsets. Call before any Span display.
pub fn set_source_map(source: &str) {
set_source_map_with_file(source, None);
}
pub fn source_map_file() -> Option<String> {
SOURCE_MAP.with(|slot| {
slot.borrow()
.as_ref()
.and_then(|sm| sm.file_path().map(|s| s.to_string()))
})
}
/// Install a SourceMap with an optional file path (e.g. "main.nula").
/// Call before any Span display for richer diagnostics.
pub fn set_source_map_with_file(source: &str, file: Option<&str>) {
let sm = SourceMap::with_file(source, file);
SOURCE_MAP.with(|slot| {
*slot.borrow_mut() = Some(sm);
});
}
/// Clear the thread-local source map (e.g. between tests).
pub fn clear_source_map() {
SOURCE_MAP.with(|slot| {
*slot.borrow_mut() = None;
});
}
/// Return the source text for a byte-offset span using the thread-local
/// SourceMap, if one is installed. Returns `None` when no SourceMap is set
/// (e.g. in synthetic contexts) or the span extends beyond the source.
pub fn source_slice_for_span(span: Span) -> Option<String> {
SOURCE_MAP.with(|slot| {
slot.borrow().as_ref().and_then(|sm| {
sm.source_slice(span.start, span.end.saturating_sub(span.start))
.map(|s| s.to_string())
})
})
}
/// Compact source span — just byte offsets. Line/column are resolved on
/// demand via the thread-local SourceMap (set by the lexer or test harness).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Span {
pub start: u32,
pub end: u32,
}
impl Span {
pub fn new(start: u32, end: u32) -> Self {
Span { start, end }
}
/// 1-indexed line number (reads from thread-local SourceMap; returns 0
/// if none is set).
pub fn line(&self) -> usize {
SOURCE_MAP.with(|slot| {
slot.borrow()
.as_ref()
.map(|sm| sm.line_col(self.start).0)
.unwrap_or(0)
})
}
/// 1-indexed column (reads from thread-local SourceMap; returns 0 if
/// none is set).
pub fn column(&self) -> usize {
SOURCE_MAP.with(|slot| {
slot.borrow()
.as_ref()
.map(|sm| sm.line_col(self.start).1)
.unwrap_or(0)
})
}
/// 1-indexed line number of span end (reads from thread-local SourceMap).
pub fn end_line(&self) -> usize {
SOURCE_MAP.with(|slot| {
slot.borrow()
.as_ref()
.map(|sm| sm.line_col(self.end).0)
.unwrap_or(0)