-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtypecheck.rs
More file actions
4390 lines (4068 loc) · 177 KB
/
typecheck.rs
File metadata and controls
4390 lines (4068 loc) · 177 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
use std::{
collections::{BTreeMap, BTreeSet, HashMap, HashSet},
rc::Rc,
};
use crate::try_with;
use crate::util::ErrTrace as _;
use crate::valuetype::{SeqBorrowHint, augmented::AugValueType};
use crate::{
Arith, BaseType, DynFormat, Expr, Format, FormatModule, Label, Pattern, UnaryOp, ValueType,
ViewExpr, ViewFormat,
};
use crate::{
base_set::PrimIntSet,
numeric::{
MachineRep, NumRep,
core::{BitWidth, Bounds as ZBounds, Expr as NExpr},
elaborator::{IntType, PrimInt},
},
};
pub mod base_set;
use base_set::{BaseSet, IntSet, UintSet};
pub(crate) mod error;
use error::{
CrossLayerNumericError, InferenceError, Polarity, TCError, TCErrorKind, UnificationError,
};
pub(crate) mod inference;
/// Helper function for constructing a tuple of the form `(min(a, b), max(a, b))`.
///
/// Used primarily for case-analysis in aliasing logic.
#[inline(always)]
fn min_max<T: PartialOrd>(a: T, b: T) -> (T, T) {
if a < b { (a, b) } else { (b, a) }
}
pub(crate) mod scope {
use std::collections::BTreeSet;
use super::UVar;
use crate::{FormatModule, Label};
#[derive(Debug, Clone, Copy, Default)]
pub(crate) enum UScope<'a> {
#[default]
Empty,
Multi(&'a UMultiScope<'a>),
Single(USingleScope<'a>),
}
impl<'a> UScope<'a> {
pub const fn new() -> Self {
Self::Empty
}
pub(crate) fn get_uvar_by_name(&self, name: &str) -> Option<UVar> {
match self {
UScope::Empty => None,
UScope::Multi(multi) => multi.get_uvar_by_name(name),
UScope::Single(single) => single.get_uvar_by_name(name),
}
}
}
#[derive(Debug, Clone)]
pub(crate) struct UMultiScope<'a> {
pub(crate) parent: &'a UScope<'a>,
pub(crate) entries: Vec<(Label, UVar)>,
}
impl<'a> UMultiScope<'a> {
pub fn new(parent: &'a UScope<'a>) -> Self {
Self {
parent,
entries: Vec::new(),
}
}
pub fn with_capacity(parent: &'a UScope<'a>, capacity: usize) -> Self {
Self {
parent,
entries: Vec::with_capacity(capacity),
}
}
pub fn push(&mut self, name: Label, v: UVar) {
self.entries.push((name, v));
}
pub(crate) fn get_uvar_by_name(&self, name: &str) -> Option<UVar> {
for (n, v) in self.entries.iter().rev() {
if n == name {
return Some(*v);
}
}
self.parent.get_uvar_by_name(name)
}
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct USingleScope<'a> {
pub(crate) parent: &'a UScope<'a>,
pub(crate) name: &'a str,
pub(crate) uvar: UVar,
}
impl<'a> USingleScope<'a> {
pub const fn new(parent: &'a UScope<'a>, name: &'a str, uvar: UVar) -> USingleScope<'a> {
Self { parent, name, uvar }
}
pub(crate) fn get_uvar_by_name(&self, name: &str) -> Option<UVar> {
if self.name == name {
return Some(self.uvar);
}
self.parent.get_uvar_by_name(name)
}
}
#[derive(Clone, Copy, Debug, Default)]
pub(crate) enum ViewScope<'a> {
#[default]
Empty,
Single(ViewSingleScope<'a>),
Multi(&'a ViewMultiScope<'a>),
}
impl<'a> ViewScope<'a> {
pub const fn new() -> Self {
Self::Empty
}
pub(crate) fn includes_name(&self, name: &str) -> bool {
match self {
ViewScope::Empty => false,
ViewScope::Single(s) => s.includes_name(name),
ViewScope::Multi(m) => m.includes_name(name),
}
}
}
#[derive(Debug, Clone)]
pub(crate) struct ViewMultiScope<'a> {
pub(crate) parent: &'a ViewScope<'a>,
pub(crate) entries: BTreeSet<Label>,
}
impl<'a> ViewMultiScope<'a> {
pub fn new(parent: &'a ViewScope<'a>) -> Self {
Self {
parent,
entries: BTreeSet::new(),
}
}
/// Records the presence of a view-kinded dep-format parameter in this scope.
///
/// # Panics
///
/// Will panic if the same identifier is added twice to the same local scope (but not if it is
/// re-used across layers of scope).
pub fn push_view(&mut self, name: Label) {
// FIXME - the clone cost ought to be avoidable but
let _name = name.clone();
if !self.entries.insert(name) {
unreachable!("duplicate parameter identifier in format view-params: {_name}");
}
}
pub(crate) fn includes_name(&self, name: &str) -> bool {
self.entries.contains(name) || self.parent.includes_name(name)
}
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct ViewSingleScope<'a> {
pub(crate) parent: &'a ViewScope<'a>,
pub(crate) name: &'a str,
}
impl<'a> ViewSingleScope<'a> {
pub const fn new(parent: &'a ViewScope<'a>, name: &'a str) -> ViewSingleScope<'a> {
Self { parent, name }
}
pub(crate) fn includes_name(&self, name: &str) -> bool {
self.name == name || self.parent.includes_name(name)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum DynScope<'a> {
Empty,
Single(DynSingleScope<'a>),
}
impl<'a> DynScope<'a> {
pub const fn new() -> Self {
Self::Empty
}
pub(crate) fn get_dynf_var_by_name(&self, label: &str) -> Option<UVar> {
match self {
DynScope::Empty => None,
DynScope::Single(single) => single.get_dynf_var_by_name(label),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct DynSingleScope<'a> {
pub(crate) parent: &'a DynScope<'a>,
pub(crate) name: &'a str,
pub(crate) dynf_var: UVar,
}
impl<'a> DynSingleScope<'a> {
pub const fn new(parent: &'a DynScope<'a>, name: &'a str, dynf_var: UVar) -> Self {
Self {
parent,
name,
dynf_var,
}
}
pub(crate) fn get_dynf_var_by_name(&self, label: &str) -> Option<UVar> {
if label == self.name {
Some(self.dynf_var)
} else {
self.parent.get_dynf_var_by_name(label)
}
}
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct Ctxt<'a> {
pub(crate) module: &'a FormatModule,
pub(crate) scope: &'a UScope<'a>,
pub(crate) dyn_s: DynScope<'a>,
pub(crate) views: ViewScope<'a>,
}
impl<'a> Ctxt<'a> {
pub const fn new(module: &'a FormatModule, scope: &'a UScope<'a>) -> Self {
Self {
module,
scope,
dyn_s: DynScope::new(),
views: ViewScope::new(),
}
}
/// Returns a copy of `self` with the given `UScope` instead of `self.scope`.
pub(crate) fn with_scope(&'a self, scope: &'a UScope<'a>) -> Ctxt<'a> {
Self {
module: self.module,
dyn_s: self.dyn_s,
views: self.views,
scope,
}
}
pub(crate) fn with_view_binding(&'a self, name: &'a str) -> Ctxt<'a> {
Self {
module: self.module,
dyn_s: self.dyn_s,
scope: self.scope,
views: ViewScope::Single(ViewSingleScope::new(&self.views, name)),
}
}
pub(crate) fn with_view_bindings(&'a self, views: &'a ViewMultiScope<'a>) -> Ctxt<'a> {
Self {
module: self.module,
dyn_s: self.dyn_s,
views: ViewScope::Multi(views),
scope: self.scope,
}
}
pub(crate) fn with_dyn_binding(&'a self, name: &'a str, dynf_var: UVar) -> Ctxt<'a> {
Self {
module: self.module,
dyn_s: DynScope::Single(DynSingleScope::new(&self.dyn_s, name, dynf_var)),
scope: self.scope,
views: self.views.clone(),
}
}
}
}
use scope::{Ctxt, UMultiScope, UScope, USingleScope, ViewMultiScope};
macro_rules! define_metavariable {
( $( $name:ident $(, $attr:meta )* );+ $(;)? ) => {
$(
$(
#[$attr]
)?
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
#[repr(transparent)]
pub struct $name(pub(crate) usize);
impl $name {
#[inline(always)]
pub const fn new(ix: usize) -> Self {
Self(ix)
}
#[inline(always)]
#[allow(deprecated)]
pub const fn to_usize(self) -> usize {
self.0
}
}
)+
};
}
define_metavariable! {
UVar, doc = "Generic unification metavariable used by [TypeChecker]";
// TVar, doc = "Tree (forest-index) metavariable used by [TypeChecker] to refer to (the root-type of) embedded numeric trees", deprecated;
NVar, doc = "Local unification metavariable used by [InferenceEngine]";
}
// SECTION - UType definition and impls
/// Unification type, equivalent to ValueType up to abstraction
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum UType {
/// Reserved case for Formats that fundamentally cannot be parsed successfully (Format::Fail and implied failure-cases)
Empty,
/// Anonymous type-hole for shape-only unifications (i.e. where we would want to use a meta-variable but don't have one available).
Hole,
/// Reserved case for View-Objects manifest through ViewFormat::ReifyView
ViewObj,
/// Indexed type-hole acting as a unification metavariable
Var(UVar),
Base(BaseType),
Tuple(Vec<Rc<UType>>),
Record(Vec<(Label, Rc<UType>)>),
Seq(Rc<UType>, SeqBorrowHint),
/// For `std::option::Option<InnerType>`
Option(Rc<UType>),
PhantomData(Rc<UType>),
// REVIEW[epic=embedded-num] - should this be PrimInt instead?
Int(IntType),
}
impl UType {
pub fn seq(self: Rc<Self>) -> Self {
Self::Seq(self, SeqBorrowHint::Constructed)
}
pub fn opt(self: Rc<Self>) -> Self {
Self::Option(self)
}
pub fn seq_view(self: Rc<Self>) -> Self {
Self::Seq(self, SeqBorrowHint::BufferView)
}
pub fn seq_array(self: Rc<Self>) -> Self {
Self::Seq(self, SeqBorrowHint::ReadArray)
}
}
impl UType {
pub const UNIT: Self = UType::Tuple(Vec::new());
pub fn tuple<T>(elems: impl IntoIterator<Item = T>) -> Self
where
T: Into<Rc<UType>>,
{
Self::Tuple(elems.into_iter().map(Into::into).collect())
}
/// Attempts to convert a `ValueType` to an `UType`, returning `Some(ut)` if the conversion was successful.
///
/// Will return `None` if the conversion failed due to the presence of a Union-type at any layer.
pub(crate) fn from_valuetype(vt: &ValueType) -> Option<UType> {
match vt {
ValueType::Any | ValueType::UnknownNumeric => Some(Self::Hole),
ValueType::Empty => Some(Self::Empty),
ValueType::ViewObj => Some(Self::ViewObj),
ValueType::PhantomData(inner) => {
let inner_t = Self::from_valuetype(inner)?;
Some(UType::PhantomData(Rc::new(inner_t)))
}
ValueType::Base(b) => Some(Self::Base(*b)),
ValueType::Tuple(vts) => {
let mut uts = Vec::with_capacity(vts.len());
for vt in vts.iter() {
uts.push(Rc::new(Self::from_valuetype(vt)?));
}
Some(Self::Tuple(uts))
}
ValueType::Record(vfs) => {
let mut ufs = Vec::with_capacity(vfs.len());
for (lab, vf) in vfs.iter() {
ufs.push((lab.clone(), Rc::new(Self::from_valuetype(vf)?)));
}
Some(Self::Record(ufs))
}
ValueType::Union(..) => None,
ValueType::Option(inner) => {
let inner_t = Self::from_valuetype(inner)?;
Some(UType::Option(Rc::new(inner_t)))
}
ValueType::Seq(inner) => Some(Self::seq(Rc::new(Self::from_valuetype(inner)?))),
}
}
}
impl UType {
/// Returns an iterator over any embedded UTypes during occurs-checks.
///
/// This method presents a context-agnostic view that merely guarantees that the embedded UTypes of
/// the receiver are all returned eventually, and in whatever order is most convenient.
pub fn iter_embedded<'a>(&'a self) -> Box<dyn Iterator<Item = Rc<UType>> + 'a> {
match self {
UType::Empty
| UType::ViewObj
| UType::Hole
| UType::Var(..)
| UType::Int(..)
| UType::Base(..) => Box::new(std::iter::empty()),
UType::Tuple(ts) => Box::new(ts.iter().cloned()),
UType::Record(fs) => Box::new(fs.iter().map(|(_l, t)| t.clone())),
UType::Seq(t, _) | UType::Option(t) | UType::PhantomData(t) => {
Box::new(std::iter::once(t.clone()))
}
}
}
}
// !SECTION
// SECTION - VType definition
/// Representation of an inferred type that is either fully-known or partly-known
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum VType {
Base(BaseSet),
Int(IntSet),
/// Leaf-node used for partial solutions whose complete form depends on a UType
Abstract(Rc<UType>),
ImplicitTuple(Vec<Rc<UType>>),
ImplicitRecord(Vec<(Label, Rc<UType>)>),
IndefiniteUnion(VMId),
}
// !SECTION
// SECTION - Alias definition and impls
/// Association type that identifies the relationship between a metavariable and the possibly-empty set
/// of other meta-variables that must agree in order for the tree to be well-typed.
#[derive(Clone, Debug, Default)]
enum Alias {
#[default]
Ground, // no aliases anywhere
BackRef(usize), // direct back-ref to earliest alias (which itself must be canonical)
Canonical(HashSet<usize>), // list of forward-references to update if usurped by an earlier canonical alias
}
impl Alias {
/// New, empty alias-set
pub const fn new() -> Alias {
Self::Ground
}
#[expect(dead_code)]
/// Returns `true` if `self` is [`Alias::Canonical`] or [`Alias::Ground`].
pub const fn is_canonical(&self) -> bool {
matches!(self, Alias::Canonical(..) | Alias::Ground)
}
/// Returns `true` if `self` is the canonical alias of at least one other metavariable (i.e. [`Alias::Canonical`] over a non-empty set).
pub fn is_canonical_nonempty(&self) -> bool {
match self {
Alias::Canonical(x) => !x.is_empty(),
_ => false,
}
}
/// Returns the index of the canonical back-reference if `self` is [`Alias::BackRef`], or `None` otherwise.
pub fn as_backref(&self) -> Option<usize> {
match self {
Alias::Ground | Alias::Canonical(_) => None,
Alias::BackRef(ix) => Some(*ix),
}
}
/// Adds a forward reference to a canonical-form Alias, forcing it to be [`Alias::Canonical`] if it is not already
///
/// # Panics
///
/// Will panic if `self` is [`Alias::BackRef`]
fn add_forward_ref(&mut self, tgt: usize) {
match self {
Alias::Ground => {
let _ = std::mem::replace(self, Alias::Canonical(HashSet::from([tgt])));
}
Alias::BackRef(_) => panic!("cannot add forward-ref to Alias::BackRef"),
Alias::Canonical(fwd_refs) => {
fwd_refs.insert(tgt);
}
}
}
/// Overwrites an Alias to be [`Alias::BackRef`] pointing to the specified index,
/// returning its old value.
fn set_backref(&mut self, tgt: usize) -> Alias {
std::mem::replace(self, Alias::BackRef(tgt))
}
/// Returns an iterator over the set of forward-references if `self` is [`Alias::Canonical`], or an empty iterator otherwise.
fn iter_fwd_refs<'a>(&'a self) -> Box<dyn Iterator<Item = usize> + 'a> {
match self {
Alias::Ground | Alias::BackRef(_) => Box::new(std::iter::empty()),
Alias::Canonical(fwd_refs) => Box::new(fwd_refs.iter().copied()),
}
}
/// Returns `true` iff `self` is [`Alias::Canonical`] and contains the specified forward-reference.
fn contains_fwd_ref(&self, tgt: usize) -> bool {
match self {
Alias::Ground | Alias::BackRef(_) => false,
Alias::Canonical(fwd_refs) => fwd_refs.contains(&tgt),
}
}
}
// !SECTION
// SECTION - VarMapMap definition and impls
/// Association table between the label for a branch-variant and the type of its contents
type VarMap = HashMap<Label, Rc<UType>>;
/// Bookkeeping structure that stores the association tables for each union-kinded metavariable constraint (as the underlying value of a VMId),
/// as well as keeping track of the next VMId to use if a novel union-kinded constraint is encountered
///
/// During type unification, co-aliased meta-variables that start out with distinct constraint VMIds will be merged, along with the
/// corresponding VarMaps in question (provided unification is non-conflicting), pruning the entry for one of the two key VMIds.
#[derive(Debug)]
struct VarMapMap {
/// Mapping from VMId to VarMap
store: HashMap<usize, VarMap>,
/// Next available VMId value to use
next_id: usize,
}
impl VarMapMap {
pub fn new() -> Self {
Self {
store: HashMap::new(),
next_id: 0,
}
}
pub fn as_inner(&self) -> &HashMap<usize, VarMap> {
&self.store
}
pub fn as_inner_mut(&mut self) -> &mut HashMap<usize, VarMap> {
&mut self.store
}
pub fn get_varmap(&self, id: VMId) -> &VarMap {
self.store
.get(&id.0)
.unwrap_or_else(|| unreachable!("missing varmap for {id}"))
}
pub fn get_varmap_mut(&mut self, id: VMId) -> &mut VarMap {
self.store
.get_mut(&id.0)
.unwrap_or_else(|| unreachable!("missing varmap for {id}"))
}
pub fn get_new_id(&mut self) -> VMId {
let ret = VMId(self.next_id);
self.next_id += 1;
ret
}
}
// !SECTIOn
// SECTIOn - Constraints definition and impls
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
#[repr(transparent)]
pub struct VMId(usize);
/// Type representing the general constraints on a metavariable.
///
/// By default, any meta-variable that is fully unconstrained will have `Constraints::Indefinite` as its value.
///
/// Otherwise, a metavariable will have either `Constraints::Variant` or `Constraints::Invariant` as its value,
/// depending on whether it is observed to be a tagged union-member or an untagged value, respectively.
#[derive(Clone, Debug, Default)]
pub enum Constraints {
#[default]
/// Default value before any inference is possible. Erased by any non-trivial unification
Indefinite,
/// Indirection via a VarMap Identifier (VMId) to a partial set of observed variants.
Variant(VMId),
/// Inferred constraints on a metavariable that is not a tagged union-member. Unification against `Constraints::Variant` may yet be possible but only in select cases.
Invariant(Constraint),
}
impl Constraints {
pub const fn new() -> Self {
Self::Indefinite
}
}
// !SECTION
// SECTION - Constraint definition and impls
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum Constraint {
/// Direct equivalence with a UType, which should not be a bare `UType::Var` (as that is implied by the independently-tracked Alias value for a metavariable)
Equiv(Rc<UType>),
/// Member of a set of ground-types (e.g. in the case of the inner expression of `Expr::AsU32(..)`)
Elem(BaseSet),
/// Constraints implied by projections into a parametric type (e.g. Option, Seq), a Tuple, or a Record
Proj(ProjShape),
/// Constraints applied to a known-numeric node
NumTree(IntSet),
}
impl Constraint {
/// Returns true if the constraint is vacuous and therefore equivalent to `Constraints::Indefinite`
///
/// Specifically checks for `Equiv` over `UType::Hole` or `UType::Empty`.
pub fn is_vacuous(&self) -> bool {
match self {
Constraint::Equiv(ut) => matches!(ut.as_ref(), UType::Hole | UType::Empty),
_ => false,
}
}
/// Normalizes a constraint so that effectively-identical constraints are structurally equivalent.
///
/// Specifically, `Constraint::Equiv(UType::Base(b))` is normalized to `Constraint::Elem(BaseSet::Single(b))`,
/// and all other constraints are returned unchanged.
pub fn normalize(self) -> Self {
if let Constraint::Equiv(ut) = &self
&& let UType::Base(b) = ut.as_ref()
{
Constraint::Elem(BaseSet::Single(*b))
} else {
self
}
}
}
// !SECTION
/// Type representing each possible shape of a projective constraint on a higher-order metavariable
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ProjShape {
TupleWith(BTreeMap<usize, UVar>), // required associations of meta-variables at given indices of an uncertain tuple
RecordWith(BTreeMap<Label, UVar>), // required associations of meta-variables at given fields of an uncertain record
SeqOf(UVar), // simple sequence element-type projection
OptOf(UVar), // simple Option param-type projection
}
impl ProjShape {
pub fn new_tuple() -> Self {
Self::TupleWith(BTreeMap::new())
}
pub fn new_record() -> Self {
Self::RecordWith(BTreeMap::new())
}
pub fn seq_of(elem: UVar) -> Self {
Self::SeqOf(elem)
}
pub fn opt_of(inner: UVar) -> Self {
Self::OptOf(inner)
}
fn as_tuple_mut(&mut self) -> &mut BTreeMap<usize, UVar> {
match self {
ProjShape::TupleWith(map) => map,
other => panic!("called as_tuple_mut on non-tuple {other:?}"),
}
}
fn as_record_mut(&mut self) -> &mut BTreeMap<Label, UVar> {
match self {
ProjShape::RecordWith(map) => map,
other => panic!("called as_record_mut on non-record {other:?}"),
}
}
}
/// Mutably updated state-engine for performing complete type-inference on a top-level `Format`.
#[derive(Debug)]
pub struct TypeChecker {
// TODO - implement segmented store to keep dep-format solving from interfering with proper sequencing
/// Stores, at each index `ix`, the incrementally refined constraints on the types that are valid assignments to meta-variable `?ix`
constraints: Vec<Constraints>,
/// Stores, at each index `ix`, the set of unique meta-variables that are aliased to meta-variable `?ix` (excluding `?ix` itself)
aliases: Vec<Alias>,
/// Associations between VMId in meta-variable constraints and the incrementally refined VarMap for the union-type it corresponds to
varmaps: VarMapMap,
/// Association between ItemVar/FormatRef levels in the FormatModule and the UVar they are mapped to
level_vars: HashMap<usize, UVar>,
// /// Scaffolding for compartmentalized external type inference in the arithmetic extension grammar
// sub_extension: EmbeddedResolver,
}
// SECTION - Construction and instantiation in the meta-context
impl TypeChecker {
/// Constructs a typechecker with initially 0 meta-variables.
pub fn new() -> Self {
Self {
constraints: Vec::new(),
aliases: Vec::new(),
varmaps: VarMapMap::new(),
level_vars: HashMap::new(),
// sub_extension: EmbeddedResolver::new(),
}
}
#[cfg_attr(not(test), allow(dead_code))]
/// Returns the number of individual `UVar`s in the meta-context of `self`.
///
/// May panic in debug builds if, for any reason, the internal state has diverged
/// (i.e. different numbers of aliases and constraints).
pub fn size(&self) -> usize {
if cfg!(debug_assertions) {
self.check_uvar_sanity();
}
self.constraints.len()
}
/// Instantiates a new [`VarMap`] object in the typechecker meta-context and returns an identifier pointing to it.
fn init_varmap(&mut self) -> VMId {
self.varmaps.get_new_id()
}
/// Instantiates a new UVar and immediately equates it with a specified UType
///
/// Useful primarily for preserving traversal-order requirements for down-the-line association with
/// otherwise untyped Format-tree nodes
///
/// This should never return `Err(_)` unless something catastrophic has happened, or it was called
/// with an improper `UType` (e.g. one that references an out-of-range UVar at the time it was constructed)
fn init_var_simple(&mut self, typ: UType) -> TCResult<(UVar, Rc<UType>)> {
let newvar = self.get_new_uvar();
let rc = Rc::new(typ);
let constr = Constraint::Equiv(rc.clone());
self.unify_var_constraint(newvar, constr)?;
Ok((newvar, rc))
}
/// Instantiates a new UVar with no known constraints or aliases, returning it by-value
fn get_new_uvar(&mut self) -> UVar {
let ret = UVar(self.constraints.len());
self.constraints.push(Constraints::new());
self.aliases.push(Alias::new());
ret
}
/// Same as [`get_new_uvar`], but additionally informs the initial constraints to indicate that the type
/// must be numeric
fn get_new_uvar_numtree(&mut self) -> UVar {
let var = self.get_new_uvar();
let constr = Constraint::NumTree(IntSet::ZAny);
self.unify_var_constraint(var, constr).unwrap();
var
}
fn infer_var_scope_pattern(
&mut self,
pat: &Pattern,
scope: &mut UMultiScope<'_>,
) -> TCResult<UVar> {
match pat {
Pattern::Binding(name) => {
let var = self.get_new_uvar();
scope.push(name.clone(), var);
Ok(var)
}
Pattern::Wildcard => {
let var = self.get_new_uvar();
Ok(var)
}
Pattern::Bool(_) => {
let var = self.init_var_simple(UType::Base(BaseType::Bool))?.0;
Ok(var)
}
Pattern::U8(_) => {
let var = self.init_var_simple(UType::Base(BaseType::U8))?.0;
Ok(var)
}
Pattern::U16(_) => {
let var = self.init_var_simple(UType::Base(BaseType::U16))?.0;
Ok(var)
}
Pattern::U32(_) => {
let var = self.init_var_simple(UType::Base(BaseType::U32))?.0;
Ok(var)
}
Pattern::U64(_) => {
let var = self.init_var_simple(UType::Base(BaseType::U64))?.0;
Ok(var)
}
Pattern::Int(bounds) => {
let var = self.get_new_uvar();
let width = bounds.min_required_width();
self.unify_var_baseset(var, BaseSet::U(UintSet::at_least(width)))?;
Ok(var)
}
Pattern::ZConst(n) => {
let var = self.get_new_uvar();
let c = inference::Constraint::Encompasses(ZBounds::singleton(n.clone()));
let mut iset = PrimIntSet::ANY;
for p in crate::numeric::elaborator::PRIM_INTS {
if c.is_satisfied_by(IntType::Prim(p)) == Some(false) {
iset.remove(p);
}
}
self.unify_var_intset(var, IntSet::Z(iset))?;
Ok(var)
}
Pattern::ZRange(bounds) => {
let var = self.get_new_uvar();
let c = inference::Constraint::Encompasses(bounds.clone());
let mut iset = PrimIntSet::ANY;
for p in crate::numeric::elaborator::PRIM_INTS {
if c.is_satisfied_by(IntType::Prim(p)) == Some(false) {
iset.remove(p);
}
}
self.unify_var_intset(var, IntSet::Z(iset))?;
Ok(var)
}
Pattern::Char(_) => {
let var = self.init_var_simple(UType::Base(BaseType::Char))?.0;
Ok(var)
}
Pattern::Tuple(pats) => {
let tuple_var = self.get_new_uvar();
let mut elem_vars = Vec::with_capacity(pats.len());
for p in pats.iter() {
let pvar = self.infer_var_scope_pattern(p, scope)?;
elem_vars.push(Rc::new(UType::Var(pvar)));
}
self.unify_var_utype(tuple_var, Rc::new(UType::Tuple(elem_vars)))?;
Ok(tuple_var)
}
Pattern::Variant(vname, inner) => {
let newvar = self.get_new_uvar();
let inner_var = self.infer_var_scope_pattern(inner.as_ref(), scope)?;
self.add_uvar_variant(newvar, vname.clone(), Rc::new(UType::Var(inner_var)))?;
Ok(newvar)
}
Pattern::Seq(elts) => {
let seq_uvar = self.get_new_uvar();
let elem_uvar = self.get_new_uvar();
for elt in elts.iter() {
let elt_uvar = self.infer_var_scope_pattern(elt, scope)?;
self.unify_var_pair(elem_uvar, elt_uvar)?;
}
self.unify_var_utype(
seq_uvar,
Rc::new(UType::seq(Rc::new(UType::Var(elem_uvar)))),
)?;
Ok(seq_uvar)
}
Pattern::Option(opt) => {
let outer_var = self.get_new_uvar();
let inner_var = if let Some(inner) = opt.as_ref() {
self.infer_var_scope_pattern(inner, scope)?
} else {
self.get_new_uvar()
};
self.unify_var_utype(
outer_var,
Rc::new(UType::Option(Rc::new(UType::Var(inner_var)))),
)?;
Ok(outer_var)
}
}
}
fn unify_utype_format_match_case(
&mut self,
head_t: Rc<UType>,
pat: &Pattern,
rhs_var: UVar,
rhs_format: &Format,
ctxt: Ctxt<'_>,
) -> TCResult<()> {
let mut child = UMultiScope::new(ctxt.scope);
let pvar = self.infer_var_scope_pattern(pat, &mut child)?;
let tmp = child.clone();
let new_scope = UScope::Multi(&tmp);
let new_ctxt = ctxt.with_scope(&new_scope);
let local_rhs_var = self.infer_var_format(rhs_format, new_ctxt)?;
let _tmp = (
"unify_utype_format_match_case",
pvar,
format!("{:?}", head_t),
);
try_with!( self.unify_var_utype(pvar, head_t) => _tmp );
self.unify_var_pair(rhs_var, local_rhs_var)?;
Ok(())
}
fn unify_utype_expr_match_case<'a>(
&mut self,
head_t: Rc<UType>,
pat: &Pattern,
rhs_var: UVar,
rhs_expr: &Expr,
scope: &'a UScope<'a>,
) -> TCResult<()> {
let mut child = UMultiScope::new(scope);
let pvar = self.infer_var_scope_pattern(pat, &mut child)?;
let tmp = child.clone();
let new_scope = UScope::Multi(&tmp);
let local_rhs_var = self.infer_var_expr(rhs_expr, &new_scope)?;
let _tmp = ("unify_utype_expr_match_case", pvar, format!("{:?}", head_t));
try_with!(self.unify_var_utype(pvar, head_t) => _tmp);
self.unify_var_pair(rhs_var, local_rhs_var)?;
Ok(())
}
/// Converts a `UType` to Weak Head-Normal Form `VType` by unchaining as many meta-variables as required, after performing
/// a sanity check to eliminate potential infinite types from consideration.
///
/// Will avoid panicking at all costs, even if it requires returning a non-WHNF variable.
///
/// # Panics
///
/// Will only ever panic if `t` is an infinite type.
fn to_whnf_vtype(&self, t: Rc<UType>) -> VType {
assert!(!self.is_infinite_type(t.clone()));
match t.as_ref() {
UType::Var(v) => {
let v0 = self.get_canonical_uvar(*v);
match &self.constraints[v0.0] {
Constraints::Invariant(Constraint::Equiv(ut)) => self.to_whnf_vtype(ut.clone()),
Constraints::Invariant(Constraint::Elem(bs)) => VType::Base(*bs),
Constraints::Invariant(Constraint::Proj(ps)) => self.proj_shape_to_vtype(ps),
Constraints::Invariant(Constraint::NumTree(is)) => VType::Int(*is),
Constraints::Variant(vmid) => VType::IndefiniteUnion(*vmid),
Constraints::Indefinite => VType::Abstract(v0.into()),
}
}
_ => VType::Abstract(t),
}
}
fn unify_var_valuetype_union<'a>(
&mut self,
var: UVar,
branches: impl IntoIterator<Item = (&'a Label, &'a ValueType)> + 'a,
) -> TCResult<()> {
for (lbl, branch_vt) in branches.into_iter() {
let ut = if let Some(ut) = UType::from_valuetype(branch_vt) {
Rc::new(ut)
} else {
let branch_var = self.get_new_uvar();
self.unify_var_valuetype(branch_var, branch_vt)?;
branch_var.into()
};
self.add_uvar_variant(var, lbl.clone(), ut)?;
}
Ok(())
}
fn infer_var_format_level(&mut self, level: usize, ctxt: Ctxt<'_>) -> TCResult<UVar> {
if let Some(ret) = self.level_vars.get(&level) {
Ok(*ret)
} else {
let ret = self.infer_var_format(ctxt.module.get_format(level), ctxt)?;
self.level_vars.insert(level, ret);
Ok(ret)
}
}
fn infer_var_view_format(
&mut self,
view_format: &ViewFormat,
ctxt: Ctxt<'_>,
) -> TCResult<UVar> {
match view_format {
ViewFormat::CaptureBytes(len) => {
let newvar = self.get_new_uvar();
let len_var = self.infer_var_expr(len, ctxt.scope)?;
self.unify_var_baseset(len_var, BaseSet::U(UintSet::ANY))?;
// REVIEW - should we have a special UType for captured View-window reads?
self.unify_var_utype(
newvar,
Rc::new(UType::seq_view(Rc::new(UType::Base(BaseType::U8)))),
)?;
Ok(newvar)
}