-
Notifications
You must be signed in to change notification settings - Fork 12.8k
/
mod.rs
1617 lines (1433 loc) · 61.7 KB
/
mod.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
use std::cell::{Cell, RefCell};
use std::fmt;
pub use BoundRegionConversionTime::*;
pub use RegionVariableOrigin::*;
pub use SubregionOrigin::*;
pub use at::DefineOpaqueTypes;
use free_regions::RegionRelations;
pub use freshen::TypeFreshener;
use lexical_region_resolve::LexicalRegionResolutions;
pub use lexical_region_resolve::RegionResolutionError;
use opaque_types::OpaqueTypeStorage;
use region_constraints::{
GenericKind, RegionConstraintCollector, RegionConstraintStorage, VarInfos, VerifyBound,
};
pub use relate::StructurallyRelateAliases;
pub use relate::combine::PredicateEmittingRelation;
use rustc_data_structures::captures::Captures;
use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
use rustc_data_structures::sync::Lrc;
use rustc_data_structures::undo_log::{Rollback, UndoLogs};
use rustc_data_structures::unify as ut;
use rustc_errors::{DiagCtxtHandle, ErrorGuaranteed};
use rustc_hir as hir;
use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_macros::extension;
pub use rustc_macros::{TypeFoldable, TypeVisitable};
use rustc_middle::bug;
use rustc_middle::infer::canonical::{CanonicalQueryInput, CanonicalVarValues};
use rustc_middle::infer::unify_key::{ConstVariableOrigin, ConstVariableValue, ConstVidKey};
use rustc_middle::mir::ConstraintCategory;
use rustc_middle::traits::select;
pub use rustc_middle::ty::IntVarValue;
use rustc_middle::ty::error::{ExpectedFound, TypeError};
use rustc_middle::ty::fold::{
BoundVarReplacerDelegate, TypeFoldable, TypeFolder, TypeSuperFoldable,
};
use rustc_middle::ty::visit::TypeVisitableExt;
use rustc_middle::ty::{
self, ConstVid, FloatVid, GenericArg, GenericArgKind, GenericArgs, GenericArgsRef,
GenericParamDefKind, InferConst, IntVid, PseudoCanonicalInput, Ty, TyCtxt, TyVid,
TypeVisitable, TypingEnv, TypingMode,
};
use rustc_span::Span;
use rustc_span::symbol::Symbol;
use rustc_type_ir::solve::Reveal;
use snapshot::undo_log::InferCtxtUndoLogs;
use tracing::{debug, instrument};
use type_variable::TypeVariableOrigin;
use crate::infer::region_constraints::UndoLog;
use crate::traits::{
self, ObligationCause, ObligationInspector, PredicateObligations, TraitEngine,
};
pub mod at;
pub mod canonical;
mod context;
mod free_regions;
mod freshen;
mod lexical_region_resolve;
mod opaque_types;
pub mod outlives;
mod projection;
pub mod region_constraints;
pub mod relate;
pub mod resolve;
pub(crate) mod snapshot;
mod type_variable;
/// `InferOk<'tcx, ()>` is used a lot. It may seem like a useless wrapper
/// around `PredicateObligations<'tcx>`, but it has one important property:
/// because `InferOk` is marked with `#[must_use]`, if you have a method
/// `InferCtxt::f` that returns `InferResult<'tcx, ()>` and you call it with
/// `infcx.f()?;` you'll get a warning about the obligations being discarded
/// without use, which is probably unintentional and has been a source of bugs
/// in the past.
#[must_use]
#[derive(Debug)]
pub struct InferOk<'tcx, T> {
pub value: T,
pub obligations: PredicateObligations<'tcx>,
}
pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
pub(crate) type FixupResult<T> = Result<T, FixupError>; // "fixup result"
pub(crate) type UnificationTable<'a, 'tcx, T> = ut::UnificationTable<
ut::InPlace<T, &'a mut ut::UnificationStorage<T>, &'a mut InferCtxtUndoLogs<'tcx>>,
>;
/// This type contains all the things within `InferCtxt` that sit within a
/// `RefCell` and are involved with taking/rolling back snapshots. Snapshot
/// operations are hot enough that we want only one call to `borrow_mut` per
/// call to `start_snapshot` and `rollback_to`.
#[derive(Clone)]
pub struct InferCtxtInner<'tcx> {
undo_log: InferCtxtUndoLogs<'tcx>,
/// Cache for projections.
///
/// This cache is snapshotted along with the infcx.
projection_cache: traits::ProjectionCacheStorage<'tcx>,
/// We instantiate `UnificationTable` with `bounds<Ty>` because the types
/// that might instantiate a general type variable have an order,
/// represented by its upper and lower bounds.
type_variable_storage: type_variable::TypeVariableStorage<'tcx>,
/// Map from const parameter variable to the kind of const it represents.
const_unification_storage: ut::UnificationTableStorage<ConstVidKey<'tcx>>,
/// Map from integral variable to the kind of integer it represents.
int_unification_storage: ut::UnificationTableStorage<ty::IntVid>,
/// Map from floating variable to the kind of float it represents.
float_unification_storage: ut::UnificationTableStorage<ty::FloatVid>,
/// Tracks the set of region variables and the constraints between them.
///
/// This is initially `Some(_)` but when
/// `resolve_regions_and_report_errors` is invoked, this gets set to `None`
/// -- further attempts to perform unification, etc., may fail if new
/// region constraints would've been added.
region_constraint_storage: Option<RegionConstraintStorage<'tcx>>,
/// A set of constraints that regionck must validate.
///
/// Each constraint has the form `T:'a`, meaning "some type `T` must
/// outlive the lifetime 'a". These constraints derive from
/// instantiated type parameters. So if you had a struct defined
/// like the following:
/// ```ignore (illustrative)
/// struct Foo<T: 'static> { ... }
/// ```
/// In some expression `let x = Foo { ... }`, it will
/// instantiate the type parameter `T` with a fresh type `$0`. At
/// the same time, it will record a region obligation of
/// `$0: 'static`. This will get checked later by regionck. (We
/// can't generally check these things right away because we have
/// to wait until types are resolved.)
///
/// These are stored in a map keyed to the id of the innermost
/// enclosing fn body / static initializer expression. This is
/// because the location where the obligation was incurred can be
/// relevant with respect to which sublifetime assumptions are in
/// place. The reason that we store under the fn-id, and not
/// something more fine-grained, is so that it is easier for
/// regionck to be sure that it has found *all* the region
/// obligations (otherwise, it's easy to fail to walk to a
/// particular node-id).
///
/// Before running `resolve_regions_and_report_errors`, the creator
/// of the inference context is expected to invoke
/// [`InferCtxt::process_registered_region_obligations`]
/// for each body-id in this map, which will process the
/// obligations within. This is expected to be done 'late enough'
/// that all type inference variables have been bound and so forth.
region_obligations: Vec<RegionObligation<'tcx>>,
/// Caches for opaque type inference.
opaque_type_storage: OpaqueTypeStorage<'tcx>,
}
impl<'tcx> InferCtxtInner<'tcx> {
fn new() -> InferCtxtInner<'tcx> {
InferCtxtInner {
undo_log: InferCtxtUndoLogs::default(),
projection_cache: Default::default(),
type_variable_storage: Default::default(),
const_unification_storage: Default::default(),
int_unification_storage: Default::default(),
float_unification_storage: Default::default(),
region_constraint_storage: Some(Default::default()),
region_obligations: vec![],
opaque_type_storage: Default::default(),
}
}
#[inline]
pub fn region_obligations(&self) -> &[RegionObligation<'tcx>] {
&self.region_obligations
}
#[inline]
pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> {
self.projection_cache.with_log(&mut self.undo_log)
}
#[inline]
fn try_type_variables_probe_ref(
&self,
vid: ty::TyVid,
) -> Option<&type_variable::TypeVariableValue<'tcx>> {
// Uses a read-only view of the unification table, this way we don't
// need an undo log.
self.type_variable_storage.eq_relations_ref().try_probe_value(vid)
}
#[inline]
fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> {
self.type_variable_storage.with_log(&mut self.undo_log)
}
#[inline]
fn opaque_types(&mut self) -> opaque_types::OpaqueTypeTable<'_, 'tcx> {
self.opaque_type_storage.with_log(&mut self.undo_log)
}
#[inline]
fn int_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ty::IntVid> {
self.int_unification_storage.with_log(&mut self.undo_log)
}
#[inline]
fn float_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ty::FloatVid> {
self.float_unification_storage.with_log(&mut self.undo_log)
}
#[inline]
fn const_unification_table(&mut self) -> UnificationTable<'_, 'tcx, ConstVidKey<'tcx>> {
self.const_unification_storage.with_log(&mut self.undo_log)
}
#[inline]
pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> {
self.region_constraint_storage
.as_mut()
.expect("region constraints already solved")
.with_log(&mut self.undo_log)
}
// Iterates through the opaque type definitions without taking them; this holds the
// `InferCtxtInner` lock, so make sure to not do anything with `InferCtxt` side-effects
// while looping through this.
pub fn iter_opaque_types(
&self,
) -> impl Iterator<Item = (ty::OpaqueTypeKey<'tcx>, ty::OpaqueHiddenType<'tcx>)> + '_ {
self.opaque_type_storage.opaque_types.iter().map(|(&k, v)| (k, v.hidden_type))
}
}
pub struct InferCtxt<'tcx> {
pub tcx: TyCtxt<'tcx>,
/// The mode of this inference context, see the struct documentation
/// for more details.
typing_mode: TypingMode<'tcx>,
/// Whether this inference context should care about region obligations in
/// the root universe. Most notably, this is used during hir typeck as region
/// solving is left to borrowck instead.
pub considering_regions: bool,
/// If set, this flag causes us to skip the 'leak check' during
/// higher-ranked subtyping operations. This flag is a temporary one used
/// to manage the removal of the leak-check: for the time being, we still run the
/// leak-check, but we issue warnings.
skip_leak_check: bool,
pub inner: RefCell<InferCtxtInner<'tcx>>,
/// Once region inference is done, the values for each variable.
lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
/// Caches the results of trait selection. This cache is used
/// for things that have to do with the parameters in scope.
pub selection_cache: select::SelectionCache<'tcx>,
/// Caches the results of trait evaluation.
pub evaluation_cache: select::EvaluationCache<'tcx>,
/// The set of predicates on which errors have been reported, to
/// avoid reporting the same error twice.
pub reported_trait_errors:
RefCell<FxIndexMap<Span, (Vec<ty::Predicate<'tcx>>, ErrorGuaranteed)>>,
pub reported_signature_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
/// When an error occurs, we want to avoid reporting "derived"
/// errors that are due to this original failure. We have this
/// flag that one can set whenever one creates a type-error that
/// is due to an error in a prior pass.
///
/// Don't read this flag directly, call `is_tainted_by_errors()`
/// and `set_tainted_by_errors()`.
tainted_by_errors: Cell<Option<ErrorGuaranteed>>,
/// What is the innermost universe we have created? Starts out as
/// `UniverseIndex::root()` but grows from there as we enter
/// universal quantifiers.
///
/// N.B., at present, we exclude the universal quantifiers on the
/// item we are type-checking, and just consider those names as
/// part of the root universe. So this would only get incremented
/// when we enter into a higher-ranked (`for<..>`) type or trait
/// bound.
universe: Cell<ty::UniverseIndex>,
next_trait_solver: bool,
pub obligation_inspector: Cell<Option<ObligationInspector<'tcx>>>,
}
/// See the `error_reporting` module for more details.
#[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable, TypeVisitable)]
pub enum ValuePairs<'tcx> {
Regions(ExpectedFound<ty::Region<'tcx>>),
Terms(ExpectedFound<ty::Term<'tcx>>),
Aliases(ExpectedFound<ty::AliasTerm<'tcx>>),
TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
PolySigs(ExpectedFound<ty::PolyFnSig<'tcx>>),
ExistentialTraitRef(ExpectedFound<ty::PolyExistentialTraitRef<'tcx>>),
ExistentialProjection(ExpectedFound<ty::PolyExistentialProjection<'tcx>>),
}
impl<'tcx> ValuePairs<'tcx> {
pub fn ty(&self) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
if let ValuePairs::Terms(ExpectedFound { expected, found }) = self
&& let Some(expected) = expected.as_type()
&& let Some(found) = found.as_type()
{
Some((expected, found))
} else {
None
}
}
}
/// The trace designates the path through inference that we took to
/// encounter an error or subtyping constraint.
///
/// See the `error_reporting` module for more details.
#[derive(Clone, Debug)]
pub struct TypeTrace<'tcx> {
pub cause: ObligationCause<'tcx>,
pub values: ValuePairs<'tcx>,
}
/// The origin of a `r1 <= r2` constraint.
///
/// See `error_reporting` module for more details
#[derive(Clone, Debug)]
pub enum SubregionOrigin<'tcx> {
/// Arose from a subtyping relation
Subtype(Box<TypeTrace<'tcx>>),
/// When casting `&'a T` to an `&'b Trait` object,
/// relating `'a` to `'b`.
RelateObjectBound(Span),
/// Some type parameter was instantiated with the given type,
/// and that type must outlive some region.
RelateParamBound(Span, Ty<'tcx>, Option<Span>),
/// The given region parameter was instantiated with a region
/// that must outlive some other region.
RelateRegionParamBound(Span, Option<Ty<'tcx>>),
/// Creating a pointer `b` to contents of another reference.
Reborrow(Span),
/// (&'a &'b T) where a >= b
ReferenceOutlivesReferent(Ty<'tcx>, Span),
/// Comparing the signature and requirements of an impl method against
/// the containing trait.
CompareImplItemObligation {
span: Span,
impl_item_def_id: LocalDefId,
trait_item_def_id: DefId,
},
/// Checking that the bounds of a trait's associated type hold for a given impl.
CheckAssociatedTypeBounds {
parent: Box<SubregionOrigin<'tcx>>,
impl_item_def_id: LocalDefId,
trait_item_def_id: DefId,
},
AscribeUserTypeProvePredicate(Span),
}
// `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
#[cfg(target_pointer_width = "64")]
rustc_data_structures::static_assert_size!(SubregionOrigin<'_>, 32);
impl<'tcx> SubregionOrigin<'tcx> {
pub fn to_constraint_category(&self) -> ConstraintCategory<'tcx> {
match self {
Self::Subtype(type_trace) => type_trace.cause.to_constraint_category(),
Self::AscribeUserTypeProvePredicate(span) => ConstraintCategory::Predicate(*span),
_ => ConstraintCategory::BoringNoLocation,
}
}
}
/// Times when we replace bound regions with existentials:
#[derive(Clone, Copy, Debug)]
pub enum BoundRegionConversionTime {
/// when a fn is called
FnCall,
/// when two higher-ranked types are compared
HigherRankedType,
/// when projecting an associated type
AssocTypeProjection(DefId),
}
/// Reasons to create a region inference variable.
///
/// See `error_reporting` module for more details.
#[derive(Copy, Clone, Debug)]
pub enum RegionVariableOrigin {
/// Region variables created for ill-categorized reasons.
///
/// They mostly indicate places in need of refactoring.
MiscVariable(Span),
/// Regions created by a `&P` or `[...]` pattern.
PatternRegion(Span),
/// Regions created by `&` operator.
BorrowRegion(Span),
/// Regions created as part of an autoref of a method receiver.
Autoref(Span),
/// Regions created as part of an automatic coercion.
Coercion(Span),
/// Region variables created as the values for early-bound regions.
///
/// FIXME(@lcnr): This should also store a `DefId`, similar to
/// `TypeVariableOrigin`.
RegionParameterDefinition(Span, Symbol),
/// Region variables created when instantiating a binder with
/// existential variables, e.g. when calling a function or method.
BoundRegion(Span, ty::BoundRegionKind, BoundRegionConversionTime),
UpvarRegion(ty::UpvarId, Span),
/// This origin is used for the inference variables that we create
/// during NLL region processing.
Nll(NllRegionVariableOrigin),
}
#[derive(Copy, Clone, Debug)]
pub enum NllRegionVariableOrigin {
/// During NLL region processing, we create variables for free
/// regions that we encounter in the function signature and
/// elsewhere. This origin indices we've got one of those.
FreeRegion,
/// "Universal" instantiation of a higher-ranked region (e.g.,
/// from a `for<'a> T` binder). Meant to represent "any region".
Placeholder(ty::PlaceholderRegion),
Existential {
/// If this is true, then this variable was created to represent a lifetime
/// bound in a `for` binder. For example, it might have been created to
/// represent the lifetime `'a` in a type like `for<'a> fn(&'a u32)`.
/// Such variables are created when we are trying to figure out if there
/// is any valid instantiation of `'a` that could fit into some scenario.
///
/// This is used to inform error reporting: in the case that we are trying to
/// determine whether there is any valid instantiation of a `'a` variable that meets
/// some constraint C, we want to blame the "source" of that `for` type,
/// rather than blaming the source of the constraint C.
from_forall: bool,
},
}
#[derive(Copy, Clone, Debug)]
pub struct FixupError {
unresolved: TyOrConstInferVar,
}
impl fmt::Display for FixupError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use TyOrConstInferVar::*;
match self.unresolved {
TyInt(_) => write!(
f,
"cannot determine the type of this integer; \
add a suffix to specify the type explicitly"
),
TyFloat(_) => write!(
f,
"cannot determine the type of this number; \
add a suffix to specify the type explicitly"
),
Ty(_) => write!(f, "unconstrained type"),
Const(_) => write!(f, "unconstrained const value"),
}
}
}
/// See the `region_obligations` field for more information.
#[derive(Clone, Debug)]
pub struct RegionObligation<'tcx> {
pub sub_region: ty::Region<'tcx>,
pub sup_type: Ty<'tcx>,
pub origin: SubregionOrigin<'tcx>,
}
/// Used to configure inference contexts before their creation.
pub struct InferCtxtBuilder<'tcx> {
tcx: TyCtxt<'tcx>,
considering_regions: bool,
skip_leak_check: bool,
/// Whether we should use the new trait solver in the local inference context,
/// which affects things like which solver is used in `predicate_may_hold`.
next_trait_solver: bool,
}
#[extension(pub trait TyCtxtInferExt<'tcx>)]
impl<'tcx> TyCtxt<'tcx> {
fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
InferCtxtBuilder {
tcx: self,
considering_regions: true,
skip_leak_check: false,
next_trait_solver: self.next_trait_solver_globally(),
}
}
}
impl<'tcx> InferCtxtBuilder<'tcx> {
pub fn with_next_trait_solver(mut self, next_trait_solver: bool) -> Self {
self.next_trait_solver = next_trait_solver;
self
}
pub fn ignoring_regions(mut self) -> Self {
self.considering_regions = false;
self
}
pub fn skip_leak_check(mut self, skip_leak_check: bool) -> Self {
self.skip_leak_check = skip_leak_check;
self
}
/// Given a canonical value `C` as a starting point, create an
/// inference context that contains each of the bound values
/// within instantiated as a fresh variable. The `f` closure is
/// invoked with the new infcx, along with the instantiated value
/// `V` and a instantiation `S`. This instantiation `S` maps from
/// the bound values in `C` to their instantiated values in `V`
/// (in other words, `S(C) = V`).
pub fn build_with_canonical<T>(
mut self,
span: Span,
input: &CanonicalQueryInput<'tcx, T>,
) -> (InferCtxt<'tcx>, T, CanonicalVarValues<'tcx>)
where
T: TypeFoldable<TyCtxt<'tcx>>,
{
let infcx = self.build(input.typing_mode);
let (value, args) = infcx.instantiate_canonical(span, &input.canonical);
(infcx, value, args)
}
pub fn build_with_typing_env(
mut self,
TypingEnv { typing_mode, param_env }: TypingEnv<'tcx>,
) -> (InferCtxt<'tcx>, ty::ParamEnv<'tcx>) {
(self.build(typing_mode), param_env)
}
pub fn build(&mut self, typing_mode: TypingMode<'tcx>) -> InferCtxt<'tcx> {
let InferCtxtBuilder { tcx, considering_regions, skip_leak_check, next_trait_solver } =
*self;
InferCtxt {
tcx,
typing_mode,
considering_regions,
skip_leak_check,
inner: RefCell::new(InferCtxtInner::new()),
lexical_region_resolutions: RefCell::new(None),
selection_cache: Default::default(),
evaluation_cache: Default::default(),
reported_trait_errors: Default::default(),
reported_signature_mismatch: Default::default(),
tainted_by_errors: Cell::new(None),
universe: Cell::new(ty::UniverseIndex::ROOT),
next_trait_solver,
obligation_inspector: Cell::new(None),
}
}
}
impl<'tcx, T> InferOk<'tcx, T> {
/// Extracts `value`, registering any obligations into `fulfill_cx`.
pub fn into_value_registering_obligations<E: 'tcx>(
self,
infcx: &InferCtxt<'tcx>,
fulfill_cx: &mut dyn TraitEngine<'tcx, E>,
) -> T {
let InferOk { value, obligations } = self;
fulfill_cx.register_predicate_obligations(infcx, obligations);
value
}
}
impl<'tcx> InferOk<'tcx, ()> {
pub fn into_obligations(self) -> PredicateObligations<'tcx> {
self.obligations
}
}
impl<'tcx> InferCtxt<'tcx> {
pub fn dcx(&self) -> DiagCtxtHandle<'_> {
self.tcx.dcx().taintable_handle(&self.tainted_by_errors)
}
pub fn next_trait_solver(&self) -> bool {
self.next_trait_solver
}
#[inline(always)]
pub fn typing_mode(
&self,
param_env_for_debug_assertion: ty::ParamEnv<'tcx>,
) -> TypingMode<'tcx> {
if cfg!(debug_assertions) {
match (param_env_for_debug_assertion.reveal(), self.typing_mode) {
(Reveal::All, TypingMode::PostAnalysis)
| (Reveal::UserFacing, TypingMode::Coherence | TypingMode::Analysis { .. }) => {}
(r, t) => unreachable!("TypingMode x Reveal mismatch: {r:?} {t:?}"),
}
}
self.typing_mode
}
#[inline(always)]
pub fn typing_mode_unchecked(&self) -> TypingMode<'tcx> {
self.typing_mode
}
pub fn freshen<T: TypeFoldable<TyCtxt<'tcx>>>(&self, t: T) -> T {
t.fold_with(&mut self.freshener())
}
/// Returns the origin of the type variable identified by `vid`.
///
/// No attempt is made to resolve `vid` to its root variable.
pub fn type_var_origin(&self, vid: TyVid) -> TypeVariableOrigin {
self.inner.borrow_mut().type_variables().var_origin(vid)
}
/// Returns the origin of the const variable identified by `vid`
// FIXME: We should store origins separately from the unification table
// so this doesn't need to be optional.
pub fn const_var_origin(&self, vid: ConstVid) -> Option<ConstVariableOrigin> {
match self.inner.borrow_mut().const_unification_table().probe_value(vid) {
ConstVariableValue::Known { .. } => None,
ConstVariableValue::Unknown { origin, .. } => Some(origin),
}
}
pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
freshen::TypeFreshener::new(self)
}
pub fn unresolved_variables(&self) -> Vec<Ty<'tcx>> {
let mut inner = self.inner.borrow_mut();
let mut vars: Vec<Ty<'_>> = inner
.type_variables()
.unresolved_variables()
.into_iter()
.map(|t| Ty::new_var(self.tcx, t))
.collect();
vars.extend(
(0..inner.int_unification_table().len())
.map(|i| ty::IntVid::from_usize(i))
.filter(|&vid| inner.int_unification_table().probe_value(vid).is_unknown())
.map(|v| Ty::new_int_var(self.tcx, v)),
);
vars.extend(
(0..inner.float_unification_table().len())
.map(|i| ty::FloatVid::from_usize(i))
.filter(|&vid| inner.float_unification_table().probe_value(vid).is_unknown())
.map(|v| Ty::new_float_var(self.tcx, v)),
);
vars
}
#[instrument(skip(self), level = "debug")]
pub fn sub_regions(
&self,
origin: SubregionOrigin<'tcx>,
a: ty::Region<'tcx>,
b: ty::Region<'tcx>,
) {
self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b);
}
/// Require that the region `r` be equal to one of the regions in
/// the set `regions`.
#[instrument(skip(self), level = "debug")]
pub fn member_constraint(
&self,
key: ty::OpaqueTypeKey<'tcx>,
definition_span: Span,
hidden_ty: Ty<'tcx>,
region: ty::Region<'tcx>,
in_regions: Lrc<Vec<ty::Region<'tcx>>>,
) {
self.inner.borrow_mut().unwrap_region_constraints().member_constraint(
key,
definition_span,
hidden_ty,
region,
in_regions,
);
}
/// Processes a `Coerce` predicate from the fulfillment context.
/// This is NOT the preferred way to handle coercion, which is to
/// invoke `FnCtxt::coerce` or a similar method (see `coercion.rs`).
///
/// This method here is actually a fallback that winds up being
/// invoked when `FnCtxt::coerce` encounters unresolved type variables
/// and records a coercion predicate. Presently, this method is equivalent
/// to `subtype_predicate` -- that is, "coercing" `a` to `b` winds up
/// actually requiring `a <: b`. This is of course a valid coercion,
/// but it's not as flexible as `FnCtxt::coerce` would be.
///
/// (We may refactor this in the future, but there are a number of
/// practical obstacles. Among other things, `FnCtxt::coerce` presently
/// records adjustments that are required on the HIR in order to perform
/// the coercion, and we don't currently have a way to manage that.)
pub fn coerce_predicate(
&self,
cause: &ObligationCause<'tcx>,
param_env: ty::ParamEnv<'tcx>,
predicate: ty::PolyCoercePredicate<'tcx>,
) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
let subtype_predicate = predicate.map_bound(|p| ty::SubtypePredicate {
a_is_expected: false, // when coercing from `a` to `b`, `b` is expected
a: p.a,
b: p.b,
});
self.subtype_predicate(cause, param_env, subtype_predicate)
}
pub fn subtype_predicate(
&self,
cause: &ObligationCause<'tcx>,
param_env: ty::ParamEnv<'tcx>,
predicate: ty::PolySubtypePredicate<'tcx>,
) -> Result<InferResult<'tcx, ()>, (TyVid, TyVid)> {
// Check for two unresolved inference variables, in which case we can
// make no progress. This is partly a micro-optimization, but it's
// also an opportunity to "sub-unify" the variables. This isn't
// *necessary* to prevent cycles, because they would eventually be sub-unified
// anyhow during generalization, but it helps with diagnostics (we can detect
// earlier that they are sub-unified).
//
// Note that we can just skip the binders here because
// type variables can't (at present, at
// least) capture any of the things bound by this binder.
//
// Note that this sub here is not just for diagnostics - it has semantic
// effects as well.
let r_a = self.shallow_resolve(predicate.skip_binder().a);
let r_b = self.shallow_resolve(predicate.skip_binder().b);
match (r_a.kind(), r_b.kind()) {
(&ty::Infer(ty::TyVar(a_vid)), &ty::Infer(ty::TyVar(b_vid))) => {
return Err((a_vid, b_vid));
}
_ => {}
}
self.enter_forall(predicate, |ty::SubtypePredicate { a_is_expected, a, b }| {
if a_is_expected {
Ok(self.at(cause, param_env).sub(DefineOpaqueTypes::Yes, a, b))
} else {
Ok(self.at(cause, param_env).sup(DefineOpaqueTypes::Yes, b, a))
}
})
}
pub fn region_outlives_predicate(
&self,
cause: &traits::ObligationCause<'tcx>,
predicate: ty::PolyRegionOutlivesPredicate<'tcx>,
) {
self.enter_forall(predicate, |ty::OutlivesPredicate(r_a, r_b)| {
let origin = SubregionOrigin::from_obligation_cause(cause, || {
RelateRegionParamBound(cause.span, None)
});
self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
})
}
/// Number of type variables created so far.
pub fn num_ty_vars(&self) -> usize {
self.inner.borrow_mut().type_variables().num_vars()
}
pub fn next_ty_var(&self, span: Span) -> Ty<'tcx> {
self.next_ty_var_with_origin(TypeVariableOrigin { span, param_def_id: None })
}
pub fn next_ty_var_with_origin(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
let vid = self.inner.borrow_mut().type_variables().new_var(self.universe(), origin);
Ty::new_var(self.tcx, vid)
}
pub fn next_ty_var_id_in_universe(&self, span: Span, universe: ty::UniverseIndex) -> TyVid {
let origin = TypeVariableOrigin { span, param_def_id: None };
self.inner.borrow_mut().type_variables().new_var(universe, origin)
}
pub fn next_ty_var_in_universe(&self, span: Span, universe: ty::UniverseIndex) -> Ty<'tcx> {
let vid = self.next_ty_var_id_in_universe(span, universe);
Ty::new_var(self.tcx, vid)
}
pub fn next_const_var(&self, span: Span) -> ty::Const<'tcx> {
self.next_const_var_with_origin(ConstVariableOrigin { span, param_def_id: None })
}
pub fn next_const_var_with_origin(&self, origin: ConstVariableOrigin) -> ty::Const<'tcx> {
let vid = self
.inner
.borrow_mut()
.const_unification_table()
.new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
.vid;
ty::Const::new_var(self.tcx, vid)
}
pub fn next_const_var_in_universe(
&self,
span: Span,
universe: ty::UniverseIndex,
) -> ty::Const<'tcx> {
let origin = ConstVariableOrigin { span, param_def_id: None };
let vid = self
.inner
.borrow_mut()
.const_unification_table()
.new_key(ConstVariableValue::Unknown { origin, universe })
.vid;
ty::Const::new_var(self.tcx, vid)
}
pub fn next_int_var(&self) -> Ty<'tcx> {
let next_int_var_id =
self.inner.borrow_mut().int_unification_table().new_key(ty::IntVarValue::Unknown);
Ty::new_int_var(self.tcx, next_int_var_id)
}
pub fn next_float_var(&self) -> Ty<'tcx> {
let next_float_var_id =
self.inner.borrow_mut().float_unification_table().new_key(ty::FloatVarValue::Unknown);
Ty::new_float_var(self.tcx, next_float_var_id)
}
/// Creates a fresh region variable with the next available index.
/// The variable will be created in the maximum universe created
/// thus far, allowing it to name any region created thus far.
pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
self.next_region_var_in_universe(origin, self.universe())
}
/// Creates a fresh region variable with the next available index
/// in the given universe; typically, you can use
/// `next_region_var` and just use the maximal universe.
pub fn next_region_var_in_universe(
&self,
origin: RegionVariableOrigin,
universe: ty::UniverseIndex,
) -> ty::Region<'tcx> {
let region_var =
self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin);
ty::Region::new_var(self.tcx, region_var)
}
/// Return the universe that the region `r` was created in. For
/// most regions (e.g., `'static`, named regions from the user,
/// etc) this is the root universe U0. For inference variables or
/// placeholders, however, it will return the universe which they
/// are associated.
pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
self.inner.borrow_mut().unwrap_region_constraints().universe(r)
}
/// Number of region variables created so far.
pub fn num_region_vars(&self) -> usize {
self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
}
/// Just a convenient wrapper of `next_region_var` for using during NLL.
#[instrument(skip(self), level = "debug")]
pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin) -> ty::Region<'tcx> {
self.next_region_var(RegionVariableOrigin::Nll(origin))
}
/// Just a convenient wrapper of `next_region_var` for using during NLL.
#[instrument(skip(self), level = "debug")]
pub fn next_nll_region_var_in_universe(
&self,
origin: NllRegionVariableOrigin,
universe: ty::UniverseIndex,
) -> ty::Region<'tcx> {
self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe)
}
pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> {
match param.kind {
GenericParamDefKind::Lifetime => {
// Create a region inference variable for the given
// region parameter definition.
self.next_region_var(RegionParameterDefinition(span, param.name)).into()
}
GenericParamDefKind::Type { .. } => {
// Create a type inference variable for the given
// type parameter definition. The generic parameters are
// for actual parameters that may be referred to by
// the default of this type parameter, if it exists.
// e.g., `struct Foo<A, B, C = (A, B)>(...);` when
// used in a path such as `Foo::<T, U>::new()` will
// use an inference variable for `C` with `[T, U]`
// as the generic parameters for the default, `(T, U)`.
let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
self.universe(),
TypeVariableOrigin { param_def_id: Some(param.def_id), span },
);
Ty::new_var(self.tcx, ty_var_id).into()
}
GenericParamDefKind::Const { .. } => {
let origin = ConstVariableOrigin { param_def_id: Some(param.def_id), span };
let const_var_id = self
.inner
.borrow_mut()
.const_unification_table()
.new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
.vid;
ty::Const::new_var(self.tcx, const_var_id).into()
}
}
}
/// Given a set of generics defined on a type or impl, returns the generic parameters mapping
/// each type/region parameter to a fresh inference variable.
pub fn fresh_args_for_item(&self, span: Span, def_id: DefId) -> GenericArgsRef<'tcx> {
GenericArgs::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
}
/// Returns `true` if errors have been reported since this infcx was
/// created. This is sometimes used as a heuristic to skip
/// reporting errors that often occur as a result of earlier
/// errors, but where it's hard to be 100% sure (e.g., unresolved
/// inference variables, regionck errors).
#[must_use = "this method does not have any side effects"]
pub fn tainted_by_errors(&self) -> Option<ErrorGuaranteed> {
self.tainted_by_errors.get()
}
/// Set the "tainted by errors" flag to true. We call this when we
/// observe an error from a prior pass.
pub fn set_tainted_by_errors(&self, e: ErrorGuaranteed) {
debug!("set_tainted_by_errors(ErrorGuaranteed)");
self.tainted_by_errors.set(Some(e));
}
pub fn region_var_origin(&self, vid: ty::RegionVid) -> RegionVariableOrigin {
let mut inner = self.inner.borrow_mut();
let inner = &mut *inner;
inner.unwrap_region_constraints().var_origin(vid)
}
/// Clone the list of variable regions. This is used only during NLL processing
/// to put the set of region variables into the NLL region context.
pub fn get_region_var_origins(&self) -> VarInfos {
let inner = self.inner.borrow();
assert!(!UndoLogs::<UndoLog<'_>>::in_snapshot(&inner.undo_log));
let storage = inner.region_constraint_storage.as_ref().expect("regions already resolved");
assert!(storage.data.is_empty());
// We clone instead of taking because borrowck still wants to use the
// inference context after calling this for diagnostics and the new
// trait solver.
storage.var_infos.clone()
}
#[instrument(level = "debug", skip(self), ret)]
pub fn take_opaque_types(&self) -> opaque_types::OpaqueTypeMap<'tcx> {
std::mem::take(&mut self.inner.borrow_mut().opaque_type_storage.opaque_types)
}