-
Notifications
You must be signed in to change notification settings - Fork 182
/
lib.rs
3077 lines (2704 loc) · 102 KB
/
lib.rs
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
//! Defines the IR for types and logical predicates.
#![deny(rust_2018_idioms)]
#![warn(missing_docs)]
// Allows macros to refer to this crate as `::chalk_ir`
extern crate self as chalk_ir;
use crate::cast::{Cast, CastTo, Caster};
use crate::fold::shift::Shift;
use crate::fold::{Fold, Folder, Subst, SuperFold};
use crate::visit::{SuperVisit, Visit, VisitExt, Visitor};
use chalk_derive::{Fold, HasInterner, SuperVisit, Visit, Zip};
use std::marker::PhantomData;
use std::ops::ControlFlow;
pub use crate::debug::SeparatorTraitRef;
#[macro_use(bitflags)]
extern crate bitflags;
/// Uninhabited (empty) type, used in combination with `PhantomData`.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Void {}
/// Many of our internal operations (e.g., unification) are an attempt
/// to perform some operation which may not complete.
pub type Fallible<T> = Result<T, NoSolution>;
/// A combination of `Fallible` and `Floundered`.
pub enum FallibleOrFloundered<T> {
/// Success
Ok(T),
/// No solution. See `chalk_ir::NoSolution`.
NoSolution,
/// Floundered. See `chalk_ir::Floundered`.
Floundered,
}
/// Indicates that the attempted operation has "no solution" -- i.e.,
/// cannot be performed.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct NoSolution;
/// Indicates that the complete set of program clauses for this goal
/// cannot be enumerated.
pub struct Floundered;
macro_rules! impl_debugs {
($($id:ident), *) => {
$(
impl<I: Interner> std::fmt::Debug for $id<I> {
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
write!(fmt, "{}({:?})", stringify!($id), self.0)
}
}
)*
};
}
#[macro_use]
pub mod zip;
#[macro_use]
pub mod fold;
#[macro_use]
pub mod visit;
pub mod cast;
pub mod interner;
use interner::{HasInterner, Interner};
pub mod could_match;
pub mod debug;
/// Variance
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub enum Variance {
/// a <: b
Covariant,
/// a == b
Invariant,
/// b <: a
Contravariant,
}
impl Variance {
/// `a.xform(b)` combines the variance of a context with the
/// variance of a type with the following meaning. If we are in a
/// context with variance `a`, and we encounter a type argument in
/// a position with variance `b`, then `a.xform(b)` is the new
/// variance with which the argument appears.
///
/// Example 1:
///
/// ```ignore
/// *mut Vec<i32>
/// ```
///
/// Here, the "ambient" variance starts as covariant. `*mut T` is
/// invariant with respect to `T`, so the variance in which the
/// `Vec<i32>` appears is `Covariant.xform(Invariant)`, which
/// yields `Invariant`. Now, the type `Vec<T>` is covariant with
/// respect to its type argument `T`, and hence the variance of
/// the `i32` here is `Invariant.xform(Covariant)`, which results
/// (again) in `Invariant`.
///
/// Example 2:
///
/// ```ignore
/// fn(*const Vec<i32>, *mut Vec<i32)
/// ```
///
/// The ambient variance is covariant. A `fn` type is
/// contravariant with respect to its parameters, so the variance
/// within which both pointer types appear is
/// `Covariant.xform(Contravariant)`, or `Contravariant`. `*const
/// T` is covariant with respect to `T`, so the variance within
/// which the first `Vec<i32>` appears is
/// `Contravariant.xform(Covariant)` or `Contravariant`. The same
/// is true for its `i32` argument. In the `*mut T` case, the
/// variance of `Vec<i32>` is `Contravariant.xform(Invariant)`,
/// and hence the outermost type is `Invariant` with respect to
/// `Vec<i32>` (and its `i32` argument).
///
/// Source: Figure 1 of "Taming the Wildcards:
/// Combining Definition- and Use-Site Variance" published in PLDI'11.
/// (Doc from rustc)
pub fn xform(self, other: Variance) -> Variance {
match (self, other) {
(Variance::Invariant, _) => Variance::Invariant,
(_, Variance::Invariant) => Variance::Invariant,
(_, Variance::Covariant) => self,
(Variance::Covariant, Variance::Contravariant) => Variance::Contravariant,
(Variance::Contravariant, Variance::Contravariant) => Variance::Covariant,
}
}
/// Converts `Covariant` into `Contravariant` and vice-versa. `Invariant`
/// stays the same.
pub fn invert(self) -> Variance {
match self {
Variance::Invariant => Variance::Invariant,
Variance::Covariant => Variance::Contravariant,
Variance::Contravariant => Variance::Covariant,
}
}
}
#[derive(Clone, PartialEq, Eq, Hash, Fold, Visit, HasInterner)]
/// The set of assumptions we've made so far, and the current number of
/// universal (forall) quantifiers we're within.
pub struct Environment<I: Interner> {
/// The clauses in the environment.
pub clauses: ProgramClauses<I>,
}
impl<I: Interner> Copy for Environment<I> where I::InternedProgramClauses: Copy {}
impl<I: Interner> Environment<I> {
/// Creates a new environment.
pub fn new(interner: I) -> Self {
Environment {
clauses: ProgramClauses::empty(interner),
}
}
/// Adds (an iterator of) clauses to the environment.
pub fn add_clauses<II>(&self, interner: I, clauses: II) -> Self
where
II: IntoIterator<Item = ProgramClause<I>>,
{
let mut env = self.clone();
env.clauses =
ProgramClauses::from_iter(interner, env.clauses.iter(interner).cloned().chain(clauses));
env
}
/// True if any of the clauses in the environment have a consequence of `Compatible`.
/// Panics if the conditions or constraints of that clause are not empty.
pub fn has_compatible_clause(&self, interner: I) -> bool {
self.clauses.as_slice(interner).iter().any(|c| {
let ProgramClauseData(implication) = c.data(interner);
match implication.skip_binders().consequence {
DomainGoal::Compatible => {
// We currently don't generate `Compatible` with any conditions or constraints
// If this was needed, for whatever reason, then a third "yes, but must evaluate"
// return value would have to be added.
assert!(implication.skip_binders().conditions.is_empty(interner));
assert!(implication.skip_binders().constraints.is_empty(interner));
true
}
_ => false,
}
})
}
}
/// A goal with an environment to solve it in.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Fold, Visit)]
#[allow(missing_docs)]
pub struct InEnvironment<G: HasInterner> {
pub environment: Environment<G::Interner>,
pub goal: G,
}
impl<G: HasInterner<Interner = I> + Copy, I: Interner> Copy for InEnvironment<G> where
I::InternedProgramClauses: Copy
{
}
impl<G: HasInterner> InEnvironment<G> {
/// Creates a new environment/goal pair.
pub fn new(environment: &Environment<G::Interner>, goal: G) -> Self {
InEnvironment {
environment: environment.clone(),
goal,
}
}
/// Maps the goal without touching the environment.
pub fn map<OP, H>(self, op: OP) -> InEnvironment<H>
where
OP: FnOnce(G) -> H,
H: HasInterner<Interner = G::Interner>,
{
InEnvironment {
environment: self.environment,
goal: op(self.goal),
}
}
}
impl<G: HasInterner> HasInterner for InEnvironment<G> {
type Interner = G::Interner;
}
/// Different signed int types.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[allow(missing_docs)]
pub enum IntTy {
Isize,
I8,
I16,
I32,
I64,
I128,
}
/// Different unsigned int types.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[allow(missing_docs)]
pub enum UintTy {
Usize,
U8,
U16,
U32,
U64,
U128,
}
/// Different kinds of float types.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[allow(missing_docs)]
pub enum FloatTy {
F32,
F64,
}
/// Types of scalar values.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[allow(missing_docs)]
pub enum Scalar {
Bool,
Char,
Int(IntTy),
Uint(UintTy),
Float(FloatTy),
}
/// Whether a function is safe or not.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Safety {
/// Safe
Safe,
/// Unsafe
Unsafe,
}
/// Whether a type is mutable or not.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Mutability {
/// Mutable
Mut,
/// Immutable
Not,
}
/// An universe index is how a universally quantified parameter is
/// represented when it's binder is moved into the environment.
/// An example chain of transformations would be:
/// `forall<T> { Goal(T) }` (syntactical representation)
/// `forall { Goal(?0) }` (used a DeBruijn index)
/// `Goal(!U1)` (the quantifier was moved to the environment and replaced with a universe index)
/// See <https://rustc-dev-guide.rust-lang.org/borrow_check/region_inference.html#placeholders-and-universes> for more.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct UniverseIndex {
/// The counter for the universe index, starts with 0.
pub counter: usize,
}
impl UniverseIndex {
/// Root universe index (0).
pub const ROOT: UniverseIndex = UniverseIndex { counter: 0 };
/// Root universe index (0).
pub fn root() -> UniverseIndex {
Self::ROOT
}
/// Whether one universe can "see" another.
pub fn can_see(self, ui: UniverseIndex) -> bool {
self.counter >= ui.counter
}
/// Increases the index counter.
pub fn next(self) -> UniverseIndex {
UniverseIndex {
counter: self.counter + 1,
}
}
}
/// Maps the universes found in the `u_canonicalize` result (the
/// "canonical" universes) to the universes found in the original
/// value (and vice versa). When used as a folder -- i.e., from
/// outside this module -- converts from "canonical" universes to the
/// original (but see the `UMapToCanonical` folder).
#[derive(Clone, Debug)]
pub struct UniverseMap {
/// A reverse map -- for each universe Ux that appears in
/// `quantified`, the corresponding universe in the original was
/// `universes[x]`.
pub universes: Vec<UniverseIndex>,
}
impl UniverseMap {
/// Creates a new universe map.
pub fn new() -> Self {
UniverseMap {
universes: vec![UniverseIndex::root()],
}
}
/// Number of canonical universes.
pub fn num_canonical_universes(&self) -> usize {
self.universes.len()
}
}
/// The id for an Abstract Data Type (i.e. structs, unions and enums).
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct AdtId<I: Interner>(pub I::InternedAdtId);
/// The id of a trait definition; could be used to load the trait datum by
/// invoking the [`trait_datum`] method.
///
/// [`trait_datum`]: ../chalk_solve/trait.RustIrDatabase.html#tymethod.trait_datum
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct TraitId<I: Interner>(pub I::DefId);
/// The id for an impl.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ImplId<I: Interner>(pub I::DefId);
/// Id for a specific clause.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ClauseId<I: Interner>(pub I::DefId);
/// The id for the associated type member of a trait. The details of the type
/// can be found by invoking the [`associated_ty_data`] method.
///
/// [`associated_ty_data`]: ../chalk_solve/trait.RustIrDatabase.html#tymethod.associated_ty_data
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct AssocTypeId<I: Interner>(pub I::DefId);
/// Id for an opaque type.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct OpaqueTyId<I: Interner>(pub I::DefId);
/// Function definition id.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct FnDefId<I: Interner>(pub I::DefId);
/// Id for Rust closures.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ClosureId<I: Interner>(pub I::DefId);
/// Id for Rust generators.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct GeneratorId<I: Interner>(pub I::DefId);
/// Id for foreign types.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ForeignDefId<I: Interner>(pub I::DefId);
impl_debugs!(ImplId, ClauseId);
/// A Rust type. The actual type data is stored in `TyKind`.
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, HasInterner)]
pub struct Ty<I: Interner> {
interned: I::InternedType,
}
impl<I: Interner> Ty<I> {
/// Creates a type from `TyKind`.
pub fn new(interner: I, data: impl CastTo<TyKind<I>>) -> Self {
let ty_kind = data.cast(interner);
Ty {
interned: I::intern_ty(interner, ty_kind),
}
}
/// Gets the interned type.
pub fn interned(&self) -> &I::InternedType {
&self.interned
}
/// Gets the underlying type data.
pub fn data(&self, interner: I) -> &TyData<I> {
I::ty_data(interner, &self.interned)
}
/// Gets the underlying type kind.
pub fn kind(&self, interner: I) -> &TyKind<I> {
&I::ty_data(interner, &self.interned).kind
}
/// Creates a `FromEnv` constraint using this type.
pub fn from_env(&self) -> FromEnv<I> {
FromEnv::Ty(self.clone())
}
/// Creates a WF-constraint for this type.
pub fn well_formed(&self) -> WellFormed<I> {
WellFormed::Ty(self.clone())
}
/// Creates a domain goal `FromEnv(T)` where `T` is this type.
pub fn into_from_env_goal(self, interner: I) -> DomainGoal<I> {
self.from_env().cast(interner)
}
/// If this is a `TyKind::BoundVar(d)`, returns `Some(d)` else `None`.
pub fn bound_var(&self, interner: I) -> Option<BoundVar> {
if let TyKind::BoundVar(bv) = self.kind(interner) {
Some(*bv)
} else {
None
}
}
/// If this is a `TyKind::InferenceVar(d)`, returns `Some(d)` else `None`.
pub fn inference_var(&self, interner: I) -> Option<InferenceVar> {
if let TyKind::InferenceVar(depth, _) = self.kind(interner) {
Some(*depth)
} else {
None
}
}
/// Returns true if this is a `BoundVar` or an `InferenceVar` of `TyVariableKind::General`.
pub fn is_general_var(&self, interner: I, binders: &CanonicalVarKinds<I>) -> bool {
match self.kind(interner) {
TyKind::BoundVar(bv)
if bv.debruijn == DebruijnIndex::INNERMOST
&& binders.at(interner, bv.index).kind
== VariableKind::Ty(TyVariableKind::General) =>
{
true
}
TyKind::InferenceVar(_, TyVariableKind::General) => true,
_ => false,
}
}
/// Returns true if this is an `Alias`.
pub fn is_alias(&self, interner: I) -> bool {
matches!(self.kind(interner), TyKind::Alias(..))
}
/// Returns true if this is an `IntTy` or `UintTy`.
pub fn is_integer(&self, interner: I) -> bool {
matches!(
self.kind(interner),
TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_))
)
}
/// Returns true if this is a `FloatTy`.
pub fn is_float(&self, interner: I) -> bool {
matches!(self.kind(interner), TyKind::Scalar(Scalar::Float(_)))
}
/// Returns `Some(adt_id)` if this is an ADT, `None` otherwise
pub fn adt_id(&self, interner: I) -> Option<AdtId<I>> {
match self.kind(interner) {
TyKind::Adt(adt_id, _) => Some(*adt_id),
_ => None,
}
}
/// True if this type contains "bound" types/lifetimes, and hence
/// needs to be shifted across binders. This is a very inefficient
/// check, intended only for debug assertions, because I am lazy.
pub fn needs_shift(&self, interner: I) -> bool {
self.has_free_vars(interner)
}
}
/// Contains the data for a Ty
#[derive(Clone, PartialEq, Eq, Hash, HasInterner)]
pub struct TyData<I: Interner> {
/// The kind
pub kind: TyKind<I>,
/// Type flags
pub flags: TypeFlags,
}
bitflags! {
/// Contains flags indicating various properties of a Ty
pub struct TypeFlags : u16 {
/// Does the type contain an InferenceVar
const HAS_TY_INFER = 1;
/// Does the type contain a lifetime with an InferenceVar
const HAS_RE_INFER = 1 << 1;
/// Does the type contain a ConstValue with an InferenceVar
const HAS_CT_INFER = 1 << 2;
/// Does the type contain a Placeholder TyKind
const HAS_TY_PLACEHOLDER = 1 << 3;
/// Does the type contain a lifetime with a Placeholder
const HAS_RE_PLACEHOLDER = 1 << 4;
/// Does the type contain a ConstValue Placeholder
const HAS_CT_PLACEHOLDER = 1 << 5;
/// True when the type has free lifetimes related to a local context
const HAS_FREE_LOCAL_REGIONS = 1 << 6;
/// Does the type contain a projection of an associated type
const HAS_TY_PROJECTION = 1 << 7;
/// Does the type contain an opaque type
const HAS_TY_OPAQUE = 1 << 8;
/// Does the type contain an unevaluated const projection
const HAS_CT_PROJECTION = 1 << 9;
/// Does the type contain an error
const HAS_ERROR = 1 << 10;
/// Does the type contain any free lifetimes
const HAS_FREE_REGIONS = 1 << 11;
/// True when the type contains lifetimes that will be substituted when function is called
const HAS_RE_LATE_BOUND = 1 << 12;
/// True when the type contains an erased lifetime
const HAS_RE_ERASED = 1 << 13;
/// Does the type contain placeholders or inference variables that could be replaced later
const STILL_FURTHER_SPECIALIZABLE = 1 << 14;
/// True when the type contains free names local to a particular context
const HAS_FREE_LOCAL_NAMES = TypeFlags::HAS_TY_INFER.bits
| TypeFlags::HAS_CT_INFER.bits
| TypeFlags::HAS_TY_PLACEHOLDER.bits
| TypeFlags::HAS_CT_PLACEHOLDER.bits
| TypeFlags::HAS_FREE_LOCAL_REGIONS.bits;
/// Does the type contain any form of projection
const HAS_PROJECTION = TypeFlags::HAS_TY_PROJECTION.bits
| TypeFlags::HAS_TY_OPAQUE.bits
| TypeFlags::HAS_CT_PROJECTION.bits;
}
}
/// Type data, which holds the actual type information.
#[derive(Clone, PartialEq, Eq, Hash, HasInterner)]
pub enum TyKind<I: Interner> {
/// Abstract data types, i.e., structs, unions, or enumerations.
/// For example, a type like `Vec<T>`.
Adt(AdtId<I>, Substitution<I>),
/// an associated type like `Iterator::Item`; see `AssociatedType` for details
AssociatedType(AssocTypeId<I>, Substitution<I>),
/// a scalar type like `bool` or `u32`
Scalar(Scalar),
/// a tuple of the given arity
Tuple(usize, Substitution<I>),
/// an array type like `[T; N]`
Array(Ty<I>, Const<I>),
/// a slice type like `[T]`
Slice(Ty<I>),
/// a raw pointer type like `*const T` or `*mut T`
Raw(Mutability, Ty<I>),
/// a reference type like `&T` or `&mut T`
Ref(Mutability, Lifetime<I>, Ty<I>),
/// a placeholder for opaque types like `impl Trait`
OpaqueType(OpaqueTyId<I>, Substitution<I>),
/// a function definition
FnDef(FnDefId<I>, Substitution<I>),
/// the string primitive type
Str,
/// the never type `!`
Never,
/// A closure.
Closure(ClosureId<I>, Substitution<I>),
/// A generator.
Generator(GeneratorId<I>, Substitution<I>),
/// A generator witness.
GeneratorWitness(GeneratorId<I>, Substitution<I>),
/// foreign types
Foreign(ForeignDefId<I>),
/// This can be used to represent an error, e.g. during name resolution of a type.
/// Chalk itself will not produce this, just pass it through when given.
Error,
/// instantiated from a universally quantified type, e.g., from
/// `forall<T> { .. }`. Stands in as a representative of "some
/// unknown type".
Placeholder(PlaceholderIndex),
/// A "dyn" type is a trait object type created via the "dyn Trait" syntax.
/// In the chalk parser, the traits that the object represents is parsed as
/// a QuantifiedInlineBound, and is then changed to a list of where clauses
/// during lowering.
///
/// See the `Opaque` variant for a discussion about the use of
/// binders here.
Dyn(DynTy<I>),
/// An "alias" type represents some form of type alias, such as:
/// - An associated type projection like `<T as Iterator>::Item`
/// - `impl Trait` types
/// - Named type aliases like `type Foo<X> = Vec<X>`
Alias(AliasTy<I>),
/// A function type such as `for<'a> fn(&'a u32)`.
/// Note that "higher-ranked" types (starting with `for<>`) are either
/// function types or dyn types, and do not appear otherwise in Rust
/// surface syntax.
Function(FnPointer<I>),
/// References the binding at the given depth. The index is a [de
/// Bruijn index], so it counts back through the in-scope binders.
BoundVar(BoundVar),
/// Inference variable defined in the current inference context.
InferenceVar(InferenceVar, TyVariableKind),
}
impl<I: Interner> Copy for TyKind<I>
where
I::InternedLifetime: Copy,
I::InternedSubstitution: Copy,
I::InternedVariableKinds: Copy,
I::InternedQuantifiedWhereClauses: Copy,
I::InternedType: Copy,
I::InternedConst: Copy,
{
}
impl<I: Interner> TyKind<I> {
/// Casts the type data to a type.
pub fn intern(self, interner: I) -> Ty<I> {
Ty::new(interner, self)
}
/// Compute type flags for a TyKind
pub fn compute_flags(&self, interner: I) -> TypeFlags {
match self {
TyKind::Adt(_, substitution)
| TyKind::AssociatedType(_, substitution)
| TyKind::Tuple(_, substitution)
| TyKind::Closure(_, substitution)
| TyKind::Generator(_, substitution)
| TyKind::GeneratorWitness(_, substitution)
| TyKind::FnDef(_, substitution)
| TyKind::OpaqueType(_, substitution) => substitution.compute_flags(interner),
TyKind::Scalar(_) | TyKind::Str | TyKind::Never | TyKind::Foreign(_) => {
TypeFlags::empty()
}
TyKind::Error => TypeFlags::HAS_ERROR,
TyKind::Slice(ty) | TyKind::Raw(_, ty) => ty.data(interner).flags,
TyKind::Ref(_, lifetime, ty) => {
lifetime.compute_flags(interner) | ty.data(interner).flags
}
TyKind::Array(ty, const_ty) => {
let flags = ty.data(interner).flags;
let const_data = const_ty.data(interner);
flags
| const_data.ty.data(interner).flags
| match const_data.value {
ConstValue::BoundVar(_) | ConstValue::Concrete(_) => TypeFlags::empty(),
ConstValue::InferenceVar(_) => {
TypeFlags::HAS_CT_INFER | TypeFlags::STILL_FURTHER_SPECIALIZABLE
}
ConstValue::Placeholder(_) => {
TypeFlags::HAS_CT_PLACEHOLDER | TypeFlags::STILL_FURTHER_SPECIALIZABLE
}
}
}
TyKind::Placeholder(_) => TypeFlags::HAS_TY_PLACEHOLDER,
TyKind::Dyn(dyn_ty) => {
let lifetime_flags = dyn_ty.lifetime.compute_flags(interner);
let mut dyn_flags = TypeFlags::empty();
for var_kind in dyn_ty.bounds.skip_binders().iter(interner) {
match &(var_kind.skip_binders()) {
WhereClause::Implemented(trait_ref) => {
dyn_flags |= trait_ref.substitution.compute_flags(interner)
}
WhereClause::AliasEq(alias_eq) => {
dyn_flags |= alias_eq.alias.compute_flags(interner);
dyn_flags |= alias_eq.ty.data(interner).flags;
}
WhereClause::LifetimeOutlives(lifetime_outlives) => {
dyn_flags |= lifetime_outlives.a.compute_flags(interner)
| lifetime_outlives.b.compute_flags(interner);
}
WhereClause::TypeOutlives(type_outlives) => {
dyn_flags |= type_outlives.ty.data(interner).flags;
dyn_flags |= type_outlives.lifetime.compute_flags(interner);
}
}
}
lifetime_flags | dyn_flags
}
TyKind::Alias(alias_ty) => alias_ty.compute_flags(interner),
TyKind::BoundVar(_) => TypeFlags::empty(),
TyKind::InferenceVar(_, _) => TypeFlags::HAS_TY_INFER,
TyKind::Function(fn_pointer) => fn_pointer.substitution.0.compute_flags(interner),
}
}
}
/// Identifies a particular bound variable within a binder.
/// Variables are identified by the combination of a [`DebruijnIndex`],
/// which identifies the *binder*, and an index within that binder.
///
/// Consider this case:
///
/// ```ignore
/// forall<'a, 'b> { forall<'c, 'd> { ... } }
/// ```
///
/// Within the `...` term:
///
/// * the variable `'a` have a debruijn index of 1 and index 0
/// * the variable `'b` have a debruijn index of 1 and index 1
/// * the variable `'c` have a debruijn index of 0 and index 0
/// * the variable `'d` have a debruijn index of 0 and index 1
///
/// The variables `'a` and `'b` both have debruijn index of 1 because,
/// counting out, they are the 2nd binder enclosing `...`. The indices
/// identify the location *within* that binder.
///
/// The variables `'c` and `'d` both have debruijn index of 0 because
/// they appear in the *innermost* binder enclosing the `...`. The
/// indices identify the location *within* that binder.
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct BoundVar {
/// Debruijn index, which identifies the binder.
pub debruijn: DebruijnIndex,
/// Index within the binder.
pub index: usize,
}
impl BoundVar {
/// Creates a new bound variable.
pub fn new(debruijn: DebruijnIndex, index: usize) -> Self {
Self { debruijn, index }
}
/// Casts the bound variable to a type.
pub fn to_ty<I: Interner>(self, interner: I) -> Ty<I> {
TyKind::<I>::BoundVar(self).intern(interner)
}
/// Wrap the bound variable in a lifetime.
pub fn to_lifetime<I: Interner>(self, interner: I) -> Lifetime<I> {
LifetimeData::<I>::BoundVar(self).intern(interner)
}
/// Wraps the bound variable in a constant.
pub fn to_const<I: Interner>(self, interner: I, ty: Ty<I>) -> Const<I> {
ConstData {
ty,
value: ConstValue::<I>::BoundVar(self),
}
.intern(interner)
}
/// True if this variable is bound within the `amount` innermost binders.
pub fn bound_within(self, outer_binder: DebruijnIndex) -> bool {
self.debruijn.within(outer_binder)
}
/// Adjusts the debruijn index (see [`DebruijnIndex::shifted_in`]).
#[must_use]
pub fn shifted_in(self) -> Self {
BoundVar::new(self.debruijn.shifted_in(), self.index)
}
/// Adjusts the debruijn index (see [`DebruijnIndex::shifted_in`]).
#[must_use]
pub fn shifted_in_from(self, outer_binder: DebruijnIndex) -> Self {
BoundVar::new(self.debruijn.shifted_in_from(outer_binder), self.index)
}
/// Adjusts the debruijn index (see [`DebruijnIndex::shifted_in`]).
#[must_use]
pub fn shifted_out(self) -> Option<Self> {
self.debruijn
.shifted_out()
.map(|db| BoundVar::new(db, self.index))
}
/// Adjusts the debruijn index (see [`DebruijnIndex::shifted_in`]).
#[must_use]
pub fn shifted_out_to(self, outer_binder: DebruijnIndex) -> Option<Self> {
self.debruijn
.shifted_out_to(outer_binder)
.map(|db| BoundVar::new(db, self.index))
}
/// Return the index of the bound variable, but only if it is bound
/// at the innermost binder. Otherwise, returns `None`.
pub fn index_if_innermost(self) -> Option<usize> {
self.index_if_bound_at(DebruijnIndex::INNERMOST)
}
/// Return the index of the bound variable, but only if it is bound
/// at the innermost binder. Otherwise, returns `None`.
pub fn index_if_bound_at(self, debruijn: DebruijnIndex) -> Option<usize> {
if self.debruijn == debruijn {
Some(self.index)
} else {
None
}
}
}
/// References the binder at the given depth. The index is a [de
/// Bruijn index], so it counts back through the in-scope binders,
/// with 0 being the innermost binder. This is used in impls and
/// the like. For example, if we had a rule like `for<T> { (T:
/// Clone) :- (T: Copy) }`, then `T` would be represented as a
/// `BoundVar(0)` (as the `for` is the innermost binder).
///
/// [de Bruijn index]: https://en.wikipedia.org/wiki/De_Bruijn_index
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct DebruijnIndex {
depth: u32,
}
impl DebruijnIndex {
/// Innermost index.
pub const INNERMOST: DebruijnIndex = DebruijnIndex { depth: 0 };
/// One level higher than the innermost index.
pub const ONE: DebruijnIndex = DebruijnIndex { depth: 1 };
/// Creates a new de Bruijn index with a given depth.
pub fn new(depth: u32) -> Self {
DebruijnIndex { depth }
}
/// Depth of the De Bruijn index, counting from 0 starting with
/// the innermost binder.
pub fn depth(self) -> u32 {
self.depth
}
/// True if the binder identified by this index is within the
/// binder identified by the index `outer_binder`.
///
/// # Example
///
/// Imagine you have the following binders in scope
///
/// ```ignore
/// forall<a> forall<b> forall<c>
/// ```
///
/// then the Debruijn index for `c` would be `0`, the index for
/// `b` would be 1, and so on. Now consider the following calls:
///
/// * `c.within(a) = true`
/// * `b.within(a) = true`
/// * `a.within(a) = false`
/// * `a.within(c) = false`
pub fn within(self, outer_binder: DebruijnIndex) -> bool {
self < outer_binder
}
/// Returns the resulting index when this value is moved into
/// through one binder.
#[must_use]
pub fn shifted_in(self) -> DebruijnIndex {
self.shifted_in_from(DebruijnIndex::ONE)
}
/// Update this index in place by shifting it "in" through
/// `amount` number of binders.
pub fn shift_in(&mut self) {
*self = self.shifted_in();
}
/// Adds `outer_binder` levels to the `self` index. Intuitively, this
/// shifts the `self` index, which was valid at the outer binder,
/// so that it is valid at the innermost binder.
///
/// Example: Assume that the following binders are in scope:
///
/// ```ignore
/// for<A> for<B> for<C> for<D>
/// ^ outer binder
/// ```
///
/// Assume further that the `outer_binder` argument is 2,
/// which means that it is referring to the `for<B>` binder
/// (since `D` would be the innermost binder).
///
/// This means that `self` is relative to the binder `B` -- so
/// if `self` is 0 (`INNERMOST`), then it refers to `B`,
/// and if `self` is 1, then it refers to `A`.
///
/// We will return as follows:
///
/// * `0.shifted_in_from(2) = 2` -- i.e., `B`, when shifted in to the binding level `D`, has index 2
/// * `1.shifted_in_from(2) = 3` -- i.e., `A`, when shifted in to the binding level `D`, has index 3
/// * `2.shifted_in_from(1) = 3` -- here, we changed the `outer_binder` to refer to `C`.
/// Therefore `2` (relative to `C`) refers to `A`, so the result is still 3 (since `A`, relative to the
/// innermost binder, has index 3).
#[must_use]
pub fn shifted_in_from(self, outer_binder: DebruijnIndex) -> DebruijnIndex {
DebruijnIndex::new(self.depth() + outer_binder.depth())
}
/// Returns the resulting index when this value is moved out from
/// `amount` number of new binders.
#[must_use]
pub fn shifted_out(self) -> Option<DebruijnIndex> {
self.shifted_out_to(DebruijnIndex::ONE)
}
/// Update in place by shifting out from `amount` binders.
pub fn shift_out(&mut self) {
*self = self.shifted_out().unwrap();
}
/// Subtracts `outer_binder` levels from the `self` index. Intuitively, this
/// shifts the `self` index, which was valid at the innermost
/// binder, to one that is valid at the binder `outer_binder`.
///
/// This will return `None` if the `self` index is internal to the
/// outer binder (i.e., if `self < outer_binder`).
///
/// Example: Assume that the following binders are in scope:
///
/// ```ignore
/// for<A> for<B> for<C> for<D>
/// ^ outer binder
/// ```
///
/// Assume further that the `outer_binder` argument is 2,
/// which means that it is referring to the `for<B>` binder
/// (since `D` would be the innermost binder).
///
/// This means that the result is relative to the binder `B` -- so
/// if `self` is 0 (`INNERMOST`), then it refers to `B`,
/// and if `self` is 1, then it refers to `A`.
///
/// We will return as follows:
///
/// * `1.shifted_out_to(2) = None` -- i.e., the binder for `C` can't be named from the binding level `B`
/// * `3.shifted_out_to(2) = Some(1)` -- i.e., `A`, when shifted out to the binding level `B`, has index 1
pub fn shifted_out_to(self, outer_binder: DebruijnIndex) -> Option<DebruijnIndex> {
if self.within(outer_binder) {
None
} else {
Some(DebruijnIndex::new(self.depth() - outer_binder.depth()))
}
}
}