pub use self::freshen::TypeFreshener;
pub use self::LateBoundRegionConversionTime::*;
pub use self::RegionVariableOrigin::*;
pub use self::SubregionOrigin::*;
pub use self::ValuePairs::*;
pub(crate) use self::undo_log::{InferCtxtUndoLogs, Snapshot, UndoLog};
use crate::traits::{self, ObligationCause, PredicateObligations, TraitEngine};
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_data_structures::sync::Lrc;
use rustc_data_structures::undo_log::Rollback;
use rustc_data_structures::unify as ut;
use rustc_errors::DiagnosticBuilder;
use rustc_hir as hir;
use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_middle::infer::canonical::{Canonical, CanonicalVarValues};
use rustc_middle::infer::unify_key::{ConstVarValue, ConstVariableValue};
use rustc_middle::infer::unify_key::{ConstVariableOrigin, ConstVariableOriginKind, ToType};
use rustc_middle::mir;
use rustc_middle::mir::interpret::EvalToConstValueResult;
use rustc_middle::traits::select;
use rustc_middle::ty::error::{ExpectedFound, TypeError, UnconstrainedNumeric};
use rustc_middle::ty::fold::{TypeFoldable, TypeFolder};
use rustc_middle::ty::relate::RelateResult;
use rustc_middle::ty::subst::{GenericArg, GenericArgKind, InternalSubsts, SubstsRef};
pub use rustc_middle::ty::IntVarValue;
use rustc_middle::ty::{self, GenericParamDefKind, InferConst, Ty, TyCtxt};
use rustc_middle::ty::{ConstVid, FloatVid, IntVid, TyVid};
use rustc_session::config::BorrowckMode;
use rustc_span::symbol::Symbol;
use rustc_span::Span;
use std::cell::{Cell, Ref, RefCell};
use std::collections::BTreeMap;
use std::fmt;
use self::combine::CombineFields;
use self::free_regions::RegionRelations;
use self::lexical_region_resolve::LexicalRegionResolutions;
use self::outlives::env::OutlivesEnvironment;
use self::region_constraints::{GenericKind, RegionConstraintData, VarInfos, VerifyBound};
use self::region_constraints::{
RegionConstraintCollector, RegionConstraintStorage, RegionSnapshot,
};
use self::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
pub mod at;
pub mod canonical;
mod combine;
mod equate;
pub mod error_reporting;
pub mod free_regions;
mod freshen;
mod fudge;
mod glb;
mod higher_ranked;
pub mod lattice;
mod lexical_region_resolve;
mod lub;
pub mod nll_relate;
pub mod outlives;
pub mod region_constraints;
pub mod resolve;
mod sub;
pub mod type_variable;
mod undo_log;
use crate::infer::canonical::OriginalQueryValues;
pub use rustc_middle::infer::unify_key;
#[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 type Bound<T> = Option<T>;
pub type UnitResult<'tcx> = RelateResult<'tcx, ()>;
pub type FixupResult<'tcx, T> = Result<T, FixupError<'tcx>>;
pub(crate) type UnificationTable<'a, 'tcx, T> = ut::UnificationTable<
ut::InPlace<T, &'a mut ut::UnificationStorage<T>, &'a mut InferCtxtUndoLogs<'tcx>>,
>;
#[derive(Copy, Clone, Debug)]
pub enum RegionckMode {
Solve,
Erase {
suppress_errors: bool,
},
}
impl Default for RegionckMode {
fn default() -> Self {
RegionckMode::Solve
}
}
impl RegionckMode {
pub fn for_item_body(tcx: TyCtxt<'_>) -> Self {
match tcx.borrowck_mode() {
BorrowckMode::Migrate => RegionckMode::Erase { suppress_errors: false },
BorrowckMode::Mir => RegionckMode::Erase { suppress_errors: true },
}
}
}
pub struct InferCtxtInner<'tcx> {
pub projection_cache: traits::ProjectionCacheStorage<'tcx>,
type_variable_storage: type_variable::TypeVariableStorage<'tcx>,
const_unification_storage: ut::UnificationTableStorage<ty::ConstVid<'tcx>>,
int_unification_storage: ut::UnificationTableStorage<ty::IntVid>,
float_unification_storage: ut::UnificationTableStorage<ty::FloatVid>,
region_constraint_storage: Option<RegionConstraintStorage<'tcx>>,
region_obligations: Vec<(hir::HirId, RegionObligation<'tcx>)>,
undo_log: InferCtxtUndoLogs<'tcx>,
}
impl<'tcx> InferCtxtInner<'tcx> {
fn new() -> InferCtxtInner<'tcx> {
InferCtxtInner {
projection_cache: Default::default(),
type_variable_storage: type_variable::TypeVariableStorage::new(),
undo_log: InferCtxtUndoLogs::default(),
const_unification_storage: ut::UnificationTableStorage::new(),
int_unification_storage: ut::UnificationTableStorage::new(),
float_unification_storage: ut::UnificationTableStorage::new(),
region_constraint_storage: Some(RegionConstraintStorage::new()),
region_obligations: vec![],
}
}
#[inline]
pub fn region_obligations(&self) -> &[(hir::HirId, 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 type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> {
self.type_variable_storage.with_log(&mut self.undo_log)
}
#[inline]
fn int_unification_table(
&mut self,
) -> ut::UnificationTable<
ut::InPlace<
ty::IntVid,
&mut ut::UnificationStorage<ty::IntVid>,
&mut InferCtxtUndoLogs<'tcx>,
>,
> {
self.int_unification_storage.with_log(&mut self.undo_log)
}
#[inline]
fn float_unification_table(
&mut self,
) -> ut::UnificationTable<
ut::InPlace<
ty::FloatVid,
&mut ut::UnificationStorage<ty::FloatVid>,
&mut InferCtxtUndoLogs<'tcx>,
>,
> {
self.float_unification_storage.with_log(&mut self.undo_log)
}
#[inline]
fn const_unification_table(
&mut self,
) -> ut::UnificationTable<
ut::InPlace<
ty::ConstVid<'tcx>,
&mut ut::UnificationStorage<ty::ConstVid<'tcx>>,
&mut InferCtxtUndoLogs<'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)
}
}
pub struct InferCtxt<'a, 'tcx> {
pub tcx: TyCtxt<'tcx>,
pub in_progress_typeck_results: Option<&'a RefCell<ty::TypeckResults<'tcx>>>,
pub inner: RefCell<InferCtxtInner<'tcx>>,
skip_leak_check: Cell<bool>,
lexical_region_resolutions: RefCell<Option<LexicalRegionResolutions<'tcx>>>,
pub selection_cache: select::SelectionCache<'tcx>,
pub evaluation_cache: select::EvaluationCache<'tcx>,
pub reported_trait_errors: RefCell<FxHashMap<Span, Vec<ty::Predicate<'tcx>>>>,
pub reported_closure_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
tainted_by_errors_flag: Cell<bool>,
err_count_on_creation: usize,
in_snapshot: Cell<bool>,
universe: Cell<ty::UniverseIndex>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable)]
pub enum ValuePairs<'tcx> {
Types(ExpectedFound<Ty<'tcx>>),
Regions(ExpectedFound<ty::Region<'tcx>>),
Consts(ExpectedFound<&'tcx ty::Const<'tcx>>),
TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
}
#[derive(Clone, Debug)]
pub struct TypeTrace<'tcx> {
cause: ObligationCause<'tcx>,
values: ValuePairs<'tcx>,
}
#[derive(Clone, Debug)]
pub enum SubregionOrigin<'tcx> {
Subtype(Box<TypeTrace<'tcx>>),
RelateObjectBound(Span),
RelateParamBound(Span, Ty<'tcx>),
RelateRegionParamBound(Span),
Reborrow(Span),
ReborrowUpvar(Span, ty::UpvarId),
DataBorrowed(Ty<'tcx>, Span),
ReferenceOutlivesReferent(Ty<'tcx>, Span),
CallReturn(Span),
CompareImplMethodObligation {
span: Span,
item_name: Symbol,
impl_item_def_id: DefId,
trait_item_def_id: DefId,
},
}
#[cfg(target_arch = "x86_64")]
static_assert_size!(SubregionOrigin<'_>, 32);
#[derive(Clone, Copy, Debug)]
pub enum LateBoundRegionConversionTime {
FnCall,
HigherRankedType,
AssocTypeProjection(DefId),
}
#[derive(Copy, Clone, Debug)]
pub enum RegionVariableOrigin {
MiscVariable(Span),
PatternRegion(Span),
AddrOfRegion(Span),
Autoref(Span, ty::AssocItem),
Coercion(Span),
EarlyBoundRegion(Span, Symbol),
LateBoundRegion(Span, ty::BoundRegion, LateBoundRegionConversionTime),
UpvarRegion(ty::UpvarId, Span),
BoundRegionInCoherence(Symbol),
NLL(NLLRegionVariableOrigin),
}
#[derive(Copy, Clone, Debug)]
pub enum NLLRegionVariableOrigin {
FreeRegion,
Placeholder(ty::PlaceholderRegion),
RootEmptyRegion,
Existential {
from_forall: bool,
},
}
#[derive(Copy, Clone, Debug)]
pub enum FixupError<'tcx> {
UnresolvedIntTy(IntVid),
UnresolvedFloatTy(FloatVid),
UnresolvedTy(TyVid),
UnresolvedConst(ConstVid<'tcx>),
}
#[derive(Clone)]
pub struct RegionObligation<'tcx> {
pub sub_region: ty::Region<'tcx>,
pub sup_type: Ty<'tcx>,
pub origin: SubregionOrigin<'tcx>,
}
impl<'tcx> fmt::Display for FixupError<'tcx> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use self::FixupError::*;
match *self {
UnresolvedIntTy(_) => write!(
f,
"cannot determine the type of this integer; \
add a suffix to specify the type explicitly"
),
UnresolvedFloatTy(_) => write!(
f,
"cannot determine the type of this number; \
add a suffix to specify the type explicitly"
),
UnresolvedTy(_) => write!(f, "unconstrained type"),
UnresolvedConst(_) => write!(f, "unconstrained const value"),
}
}
}
pub struct InferCtxtBuilder<'tcx> {
tcx: TyCtxt<'tcx>,
fresh_typeck_results: Option<RefCell<ty::TypeckResults<'tcx>>>,
}
pub trait TyCtxtInferExt<'tcx> {
fn infer_ctxt(self) -> InferCtxtBuilder<'tcx>;
}
impl TyCtxtInferExt<'tcx> for TyCtxt<'tcx> {
fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> {
InferCtxtBuilder { tcx: self, fresh_typeck_results: None }
}
}
impl<'tcx> InferCtxtBuilder<'tcx> {
pub fn with_fresh_in_progress_typeck_results(mut self, table_owner: LocalDefId) -> Self {
self.fresh_typeck_results = Some(RefCell::new(ty::TypeckResults::new(table_owner)));
self
}
pub fn enter_with_canonical<T, R>(
&mut self,
span: Span,
canonical: &Canonical<'tcx, T>,
f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>, T, CanonicalVarValues<'tcx>) -> R,
) -> R
where
T: TypeFoldable<'tcx>,
{
self.enter(|infcx| {
let (value, subst) =
infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical);
f(infcx, value, subst)
})
}
pub fn enter<R>(&mut self, f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>) -> R) -> R {
let InferCtxtBuilder { tcx, ref fresh_typeck_results } = *self;
let in_progress_typeck_results = fresh_typeck_results.as_ref();
f(InferCtxt {
tcx,
in_progress_typeck_results,
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_closure_mismatch: Default::default(),
tainted_by_errors_flag: Cell::new(false),
err_count_on_creation: tcx.sess.err_count(),
in_snapshot: Cell::new(false),
skip_leak_check: Cell::new(false),
universe: Cell::new(ty::UniverseIndex::ROOT),
})
}
}
impl<'tcx, T> InferOk<'tcx, T> {
pub fn unit(self) -> InferOk<'tcx, ()> {
InferOk { value: (), obligations: self.obligations }
}
pub fn into_value_registering_obligations(
self,
infcx: &InferCtxt<'_, 'tcx>,
fulfill_cx: &mut dyn TraitEngine<'tcx>,
) -> T {
let InferOk { value, obligations } = self;
for obligation in obligations {
fulfill_cx.register_predicate_obligation(infcx, obligation);
}
value
}
}
impl<'tcx> InferOk<'tcx, ()> {
pub fn into_obligations(self) -> PredicateObligations<'tcx> {
self.obligations
}
}
#[must_use = "once you start a snapshot, you should always consume it"]
pub struct CombinedSnapshot<'a, 'tcx> {
undo_snapshot: Snapshot<'tcx>,
region_constraints_snapshot: RegionSnapshot,
universe: ty::UniverseIndex,
was_in_snapshot: bool,
_in_progress_typeck_results: Option<Ref<'a, ty::TypeckResults<'tcx>>>,
}
impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
pub fn is_in_snapshot(&self) -> bool {
self.in_snapshot.get()
}
pub fn freshen<T: TypeFoldable<'tcx>>(&self, t: T) -> T {
t.fold_with(&mut self.freshener())
}
pub fn type_var_diverges(&'a self, ty: Ty<'_>) -> bool {
match *ty.kind() {
ty::Infer(ty::TyVar(vid)) => self.inner.borrow_mut().type_variables().var_diverges(vid),
_ => false,
}
}
pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> {
freshen::TypeFreshener::new(self)
}
pub fn type_is_unconstrained_numeric(&'a self, ty: Ty<'_>) -> UnconstrainedNumeric {
use rustc_middle::ty::error::UnconstrainedNumeric::Neither;
use rustc_middle::ty::error::UnconstrainedNumeric::{UnconstrainedFloat, UnconstrainedInt};
match *ty.kind() {
ty::Infer(ty::IntVar(vid)) => {
if self.inner.borrow_mut().int_unification_table().probe_value(vid).is_some() {
Neither
} else {
UnconstrainedInt
}
}
ty::Infer(ty::FloatVar(vid)) => {
if self.inner.borrow_mut().float_unification_table().probe_value(vid).is_some() {
Neither
} else {
UnconstrainedFloat
}
}
_ => Neither,
}
}
pub fn unsolved_variables(&self) -> Vec<Ty<'tcx>> {
let mut inner = self.inner.borrow_mut();
let mut vars: Vec<Ty<'_>> = inner
.type_variables()
.unsolved_variables()
.into_iter()
.map(|t| self.tcx.mk_ty_var(t))
.collect();
vars.extend(
(0..inner.int_unification_table().len())
.map(|i| ty::IntVid { index: i as u32 })
.filter(|&vid| inner.int_unification_table().probe_value(vid).is_none())
.map(|v| self.tcx.mk_int_var(v)),
);
vars.extend(
(0..inner.float_unification_table().len())
.map(|i| ty::FloatVid { index: i as u32 })
.filter(|&vid| inner.float_unification_table().probe_value(vid).is_none())
.map(|v| self.tcx.mk_float_var(v)),
);
vars
}
fn combine_fields(
&'a self,
trace: TypeTrace<'tcx>,
param_env: ty::ParamEnv<'tcx>,
) -> CombineFields<'a, 'tcx> {
CombineFields {
infcx: self,
trace,
cause: None,
param_env,
obligations: PredicateObligations::new(),
}
}
pub fn save_and_restore_in_snapshot_flag<F, R>(&self, func: F) -> R
where
F: FnOnce(&Self) -> R,
{
let flag = self.in_snapshot.replace(false);
let result = func(self);
self.in_snapshot.set(flag);
result
}
fn start_snapshot(&self) -> CombinedSnapshot<'a, 'tcx> {
debug!("start_snapshot()");
let in_snapshot = self.in_snapshot.replace(true);
let mut inner = self.inner.borrow_mut();
CombinedSnapshot {
undo_snapshot: inner.undo_log.start_snapshot(),
region_constraints_snapshot: inner.unwrap_region_constraints().start_snapshot(),
universe: self.universe(),
was_in_snapshot: in_snapshot,
_in_progress_typeck_results: self
.in_progress_typeck_results
.map(|typeck_results| typeck_results.borrow()),
}
}
fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'a, 'tcx>) {
debug!("rollback_to(cause={})", cause);
let CombinedSnapshot {
undo_snapshot,
region_constraints_snapshot,
universe,
was_in_snapshot,
_in_progress_typeck_results,
} = snapshot;
self.in_snapshot.set(was_in_snapshot);
self.universe.set(universe);
let mut inner = self.inner.borrow_mut();
inner.rollback_to(undo_snapshot);
inner.unwrap_region_constraints().rollback_to(region_constraints_snapshot);
}
fn commit_from(&self, snapshot: CombinedSnapshot<'a, 'tcx>) {
debug!("commit_from()");
let CombinedSnapshot {
undo_snapshot,
region_constraints_snapshot: _,
universe: _,
was_in_snapshot,
_in_progress_typeck_results,
} = snapshot;
self.in_snapshot.set(was_in_snapshot);
self.inner.borrow_mut().commit(undo_snapshot);
}
pub fn commit_unconditionally<R, F>(&self, f: F) -> R
where
F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
{
debug!("commit_unconditionally()");
let snapshot = self.start_snapshot();
let r = f(&snapshot);
self.commit_from(snapshot);
r
}
pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E>
where
F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> Result<T, E>,
{
debug!("commit_if_ok()");
let snapshot = self.start_snapshot();
let r = f(&snapshot);
debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok());
match r {
Ok(_) => {
self.commit_from(snapshot);
}
Err(_) => {
self.rollback_to("commit_if_ok -- error", snapshot);
}
}
r
}
pub fn probe<R, F>(&self, f: F) -> R
where
F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
{
debug!("probe()");
let snapshot = self.start_snapshot();
let r = f(&snapshot);
self.rollback_to("probe", snapshot);
r
}
pub fn probe_maybe_skip_leak_check<R, F>(&self, should_skip: bool, f: F) -> R
where
F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R,
{
debug!("probe()");
let snapshot = self.start_snapshot();
let was_skip_leak_check = self.skip_leak_check.get();
if should_skip {
self.skip_leak_check.set(true);
}
let r = f(&snapshot);
self.rollback_to("probe", snapshot);
self.skip_leak_check.set(was_skip_leak_check);
r
}
pub fn region_constraints_added_in_snapshot(
&self,
snapshot: &CombinedSnapshot<'a, 'tcx>,
) -> Option<bool> {
self.inner
.borrow_mut()
.unwrap_region_constraints()
.region_constraints_added_in_snapshot(&snapshot.undo_snapshot)
}
pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) {
self.inner.borrow_mut().unwrap_region_constraints().add_given(sub, sup);
}
pub fn can_sub<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
where
T: at::ToTrace<'tcx>,
{
let origin = &ObligationCause::dummy();
self.probe(|_| {
self.at(origin, param_env).sub(a, b).map(|InferOk { obligations: _, .. }| {
})
})
}
pub fn can_eq<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx>
where
T: at::ToTrace<'tcx>,
{
let origin = &ObligationCause::dummy();
self.probe(|_| {
self.at(origin, param_env).eq(a, b).map(|InferOk { obligations: _, .. }| {
})
})
}
pub fn sub_regions(
&self,
origin: SubregionOrigin<'tcx>,
a: ty::Region<'tcx>,
b: ty::Region<'tcx>,
) {
debug!("sub_regions({:?} <: {:?})", a, b);
self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b);
}
pub fn member_constraint(
&self,
opaque_type_def_id: DefId,
definition_span: Span,
hidden_ty: Ty<'tcx>,
region: ty::Region<'tcx>,
in_regions: &Lrc<Vec<ty::Region<'tcx>>>,
) {
debug!("member_constraint({:?} <: {:?})", region, in_regions);
self.inner.borrow_mut().unwrap_region_constraints().member_constraint(
opaque_type_def_id,
definition_span,
hidden_ty,
region,
in_regions,
);
}
pub fn subtype_predicate(
&self,
cause: &ObligationCause<'tcx>,
param_env: ty::ParamEnv<'tcx>,
predicate: ty::PolySubtypePredicate<'tcx>,
) -> Option<InferResult<'tcx, ()>> {
let two_unbound_type_vars = {
let a = self.shallow_resolve(predicate.skip_binder().a);
let b = self.shallow_resolve(predicate.skip_binder().b);
a.is_ty_var() && b.is_ty_var()
};
if two_unbound_type_vars {
return None;
}
Some(self.commit_if_ok(|_snapshot| {
let ty::SubtypePredicate { a_is_expected, a, b } =
self.replace_bound_vars_with_placeholders(predicate);
let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?;
Ok(ok.unit())
}))
}
pub fn region_outlives_predicate(
&self,
cause: &traits::ObligationCause<'tcx>,
predicate: ty::PolyRegionOutlivesPredicate<'tcx>,
) -> UnitResult<'tcx> {
self.commit_if_ok(|_snapshot| {
let ty::OutlivesPredicate(r_a, r_b) =
self.replace_bound_vars_with_placeholders(predicate);
let origin = SubregionOrigin::from_obligation_cause(cause, || {
RelateRegionParamBound(cause.span)
});
self.sub_regions(origin, r_b, r_a);
Ok(())
})
}
pub fn next_ty_var_id(&self, diverging: bool, origin: TypeVariableOrigin) -> TyVid {
self.inner.borrow_mut().type_variables().new_var(self.universe(), diverging, origin)
}
pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
self.tcx.mk_ty_var(self.next_ty_var_id(false, origin))
}
pub fn next_ty_var_in_universe(
&self,
origin: TypeVariableOrigin,
universe: ty::UniverseIndex,
) -> Ty<'tcx> {
let vid = self.inner.borrow_mut().type_variables().new_var(universe, false, origin);
self.tcx.mk_ty_var(vid)
}
pub fn next_diverging_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> {
self.tcx.mk_ty_var(self.next_ty_var_id(true, origin))
}
pub fn next_const_var(
&self,
ty: Ty<'tcx>,
origin: ConstVariableOrigin,
) -> &'tcx ty::Const<'tcx> {
self.tcx.mk_const_var(self.next_const_var_id(origin), ty)
}
pub fn next_const_var_in_universe(
&self,
ty: Ty<'tcx>,
origin: ConstVariableOrigin,
universe: ty::UniverseIndex,
) -> &'tcx ty::Const<'tcx> {
let vid = self
.inner
.borrow_mut()
.const_unification_table()
.new_key(ConstVarValue { origin, val: ConstVariableValue::Unknown { universe } });
self.tcx.mk_const_var(vid, ty)
}
pub fn next_const_var_id(&self, origin: ConstVariableOrigin) -> ConstVid<'tcx> {
self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
origin,
val: ConstVariableValue::Unknown { universe: self.universe() },
})
}
fn next_int_var_id(&self) -> IntVid {
self.inner.borrow_mut().int_unification_table().new_key(None)
}
pub fn next_int_var(&self) -> Ty<'tcx> {
self.tcx.mk_int_var(self.next_int_var_id())
}
fn next_float_var_id(&self) -> FloatVid {
self.inner.borrow_mut().float_unification_table().new_key(None)
}
pub fn next_float_var(&self) -> Ty<'tcx> {
self.tcx.mk_float_var(self.next_float_var_id())
}
pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> {
self.next_region_var_in_universe(origin, self.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);
self.tcx.mk_region(ty::ReVar(region_var))
}
fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex {
self.inner.borrow_mut().unwrap_region_constraints().universe(r)
}
pub fn num_region_vars(&self) -> usize {
self.inner.borrow_mut().unwrap_region_constraints().num_region_vars()
}
pub fn next_nll_region_var(&self, origin: NLLRegionVariableOrigin) -> ty::Region<'tcx> {
self.next_region_var(RegionVariableOrigin::NLL(origin))
}
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 => {
self.next_region_var(EarlyBoundRegion(span, param.name)).into()
}
GenericParamDefKind::Type { .. } => {
let ty_var_id = self.inner.borrow_mut().type_variables().new_var(
self.universe(),
false,
TypeVariableOrigin {
kind: TypeVariableOriginKind::TypeParameterDefinition(
param.name,
Some(param.def_id),
),
span,
},
);
self.tcx.mk_ty_var(ty_var_id).into()
}
GenericParamDefKind::Const { .. } => {
let origin = ConstVariableOrigin {
kind: ConstVariableOriginKind::ConstParameterDefinition(
param.name,
param.def_id,
),
span,
};
let const_var_id =
self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue {
origin,
val: ConstVariableValue::Unknown { universe: self.universe() },
});
self.tcx.mk_const_var(const_var_id, self.tcx.type_of(param.def_id)).into()
}
}
}
pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> {
InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param))
}
pub fn is_tainted_by_errors(&self) -> bool {
debug!(
"is_tainted_by_errors(err_count={}, err_count_on_creation={}, \
tainted_by_errors_flag={})",
self.tcx.sess.err_count(),
self.err_count_on_creation,
self.tainted_by_errors_flag.get()
);
if self.tcx.sess.err_count() > self.err_count_on_creation {
return true;
}
self.tainted_by_errors_flag.get()
}
pub fn set_tainted_by_errors(&self) {
debug!("set_tainted_by_errors()");
self.tainted_by_errors_flag.set(true)
}
pub fn resolve_regions_and_report_errors(
&self,
region_context: DefId,
outlives_env: &OutlivesEnvironment<'tcx>,
mode: RegionckMode,
) {
let (var_infos, data) = {
let mut inner = self.inner.borrow_mut();
let inner = &mut *inner;
assert!(
self.is_tainted_by_errors() || inner.region_obligations.is_empty(),
"region_obligations not empty: {:#?}",
inner.region_obligations
);
inner
.region_constraint_storage
.take()
.expect("regions already resolved")
.with_log(&mut inner.undo_log)
.into_infos_and_data()
};
let region_rels =
&RegionRelations::new(self.tcx, region_context, outlives_env.free_region_map());
let (lexical_region_resolutions, errors) =
lexical_region_resolve::resolve(region_rels, var_infos, data, mode);
let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions));
assert!(old_value.is_none());
if !self.is_tainted_by_errors() {
self.report_region_errors(&errors);
}
}
pub fn take_and_reset_region_constraints(&self) -> RegionConstraintData<'tcx> {
assert!(
self.inner.borrow().region_obligations.is_empty(),
"region_obligations not empty: {:#?}",
self.inner.borrow().region_obligations
);
self.inner.borrow_mut().unwrap_region_constraints().take_and_reset_data()
}
pub fn with_region_constraints<R>(
&self,
op: impl FnOnce(&RegionConstraintData<'tcx>) -> R,
) -> R {
let mut inner = self.inner.borrow_mut();
op(inner.unwrap_region_constraints().data())
}
pub fn take_region_var_origins(&self) -> VarInfos {
let mut inner = self.inner.borrow_mut();
let (var_infos, data) = inner
.region_constraint_storage
.take()
.expect("regions already resolved")
.with_log(&mut inner.undo_log)
.into_infos_and_data();
assert!(data.is_empty());
var_infos
}
pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
self.resolve_vars_if_possible(t).to_string()
}
pub fn tys_to_string(&self, ts: &[Ty<'tcx>]) -> String {
let tstrs: Vec<String> = ts.iter().map(|t| self.ty_to_string(*t)).collect();
format!("({})", tstrs.join(", "))
}
pub fn trait_ref_to_string(&self, t: ty::TraitRef<'tcx>) -> String {
self.resolve_vars_if_possible(t).print_only_trait_path().to_string()
}
pub fn probe_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, ty::UniverseIndex> {
use self::type_variable::TypeVariableValue;
match self.inner.borrow_mut().type_variables().probe(vid) {
TypeVariableValue::Known { value } => Ok(value),
TypeVariableValue::Unknown { universe } => Err(universe),
}
}
pub fn shallow_resolve<T>(&self, value: T) -> T
where
T: TypeFoldable<'tcx>,
{
value.fold_with(&mut ShallowResolver { infcx: self })
}
pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid {
self.inner.borrow_mut().type_variables().root_var(var)
}
pub fn resolve_vars_if_possible<T>(&self, value: T) -> T
where
T: TypeFoldable<'tcx>,
{
if !value.needs_infer() {
return value.clone();
}
let mut r = resolve::OpportunisticVarResolver::new(self);
value.fold_with(&mut r)
}
pub fn unresolved_type_vars<T>(&self, value: &T) -> Option<(Ty<'tcx>, Option<Span>)>
where
T: TypeFoldable<'tcx>,
{
value.visit_with(&mut resolve::UnresolvedTypeFinder::new(self)).break_value()
}
pub fn probe_const_var(
&self,
vid: ty::ConstVid<'tcx>,
) -> Result<&'tcx ty::Const<'tcx>, ty::UniverseIndex> {
match self.inner.borrow_mut().const_unification_table().probe_value(vid).val {
ConstVariableValue::Known { value } => Ok(value),
ConstVariableValue::Unknown { universe } => Err(universe),
}
}
pub fn fully_resolve<T: TypeFoldable<'tcx>>(&self, value: T) -> FixupResult<'tcx, T> {
resolve::fully_resolve(self, value)
}
pub fn type_error_struct_with_diag<M>(
&self,
sp: Span,
mk_diag: M,
actual_ty: Ty<'tcx>,
) -> DiagnosticBuilder<'tcx>
where
M: FnOnce(String) -> DiagnosticBuilder<'tcx>,
{
let actual_ty = self.resolve_vars_if_possible(actual_ty);
debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
if actual_ty.references_error() {
return self.tcx.sess.diagnostic().struct_dummy();
}
mk_diag(self.ty_to_string(actual_ty))
}
pub fn report_mismatched_types(
&self,
cause: &ObligationCause<'tcx>,
expected: Ty<'tcx>,
actual: Ty<'tcx>,
err: TypeError<'tcx>,
) -> DiagnosticBuilder<'tcx> {
let trace = TypeTrace::types(cause, true, expected, actual);
self.report_and_explain_type_error(trace, &err)
}
pub fn report_mismatched_consts(
&self,
cause: &ObligationCause<'tcx>,
expected: &'tcx ty::Const<'tcx>,
actual: &'tcx ty::Const<'tcx>,
err: TypeError<'tcx>,
) -> DiagnosticBuilder<'tcx> {
let trace = TypeTrace::consts(cause, true, expected, actual);
self.report_and_explain_type_error(trace, &err)
}
pub fn replace_bound_vars_with_fresh_vars<T>(
&self,
span: Span,
lbrct: LateBoundRegionConversionTime,
value: ty::Binder<T>,
) -> (T, BTreeMap<ty::BoundRegion, ty::Region<'tcx>>)
where
T: TypeFoldable<'tcx>,
{
let fld_r = |br| self.next_region_var(LateBoundRegion(span, br, lbrct));
let fld_t = |_| {
self.next_ty_var(TypeVariableOrigin {
kind: TypeVariableOriginKind::MiscVariable,
span,
})
};
let fld_c = |_, ty| {
self.next_const_var(
ty,
ConstVariableOrigin { kind: ConstVariableOriginKind::MiscVariable, span },
)
};
self.tcx.replace_bound_vars(value, fld_r, fld_t, fld_c)
}
pub fn verify_generic_bound(
&self,
origin: SubregionOrigin<'tcx>,
kind: GenericKind<'tcx>,
a: ty::Region<'tcx>,
bound: VerifyBound<'tcx>,
) {
debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound);
self.inner
.borrow_mut()
.unwrap_region_constraints()
.verify_generic_bound(origin, kind, a, bound);
}
pub fn closure_kind(&self, closure_substs: SubstsRef<'tcx>) -> Option<ty::ClosureKind> {
let closure_kind_ty = closure_substs.as_closure().kind_ty();
let closure_kind_ty = self.shallow_resolve(closure_kind_ty);
closure_kind_ty.to_opt_closure_kind()
}
pub fn clear_caches(&self) {
self.selection_cache.clear();
self.evaluation_cache.clear();
self.inner.borrow_mut().projection_cache().clear();
}
fn universe(&self) -> ty::UniverseIndex {
self.universe.get()
}
pub fn create_next_universe(&self) -> ty::UniverseIndex {
let u = self.universe.get().next_universe();
self.universe.set(u);
u
}
pub fn const_eval_resolve(
&self,
param_env: ty::ParamEnv<'tcx>,
def: ty::WithOptConstParam<DefId>,
substs: SubstsRef<'tcx>,
promoted: Option<mir::Promoted>,
span: Option<Span>,
) -> EvalToConstValueResult<'tcx> {
let mut original_values = OriginalQueryValues::default();
let canonical = self.canonicalize_query((param_env, substs), &mut original_values);
let (param_env, substs) = canonical.value;
self.tcx.const_eval_resolve(param_env, def, substs, promoted, span)
}
fn shallow_resolve_ty(&self, typ: Ty<'tcx>) -> Ty<'tcx> {
match *typ.kind() {
ty::Infer(ty::TyVar(v)) => {
let known = self.inner.borrow_mut().type_variables().probe(v).known();
known.map(|t| self.shallow_resolve_ty(t)).unwrap_or(typ)
}
ty::Infer(ty::IntVar(v)) => self
.inner
.borrow_mut()
.int_unification_table()
.probe_value(v)
.map(|v| v.to_type(self.tcx))
.unwrap_or(typ),
ty::Infer(ty::FloatVar(v)) => self
.inner
.borrow_mut()
.float_unification_table()
.probe_value(v)
.map(|v| v.to_type(self.tcx))
.unwrap_or(typ),
_ => typ,
}
}
#[inline(always)]
pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar<'tcx>) -> bool {
match infer_var {
TyOrConstInferVar::Ty(v) => {
use self::type_variable::TypeVariableValue;
match self.inner.borrow_mut().type_variables().inlined_probe(v) {
TypeVariableValue::Unknown { .. } => false,
TypeVariableValue::Known { .. } => true,
}
}
TyOrConstInferVar::TyInt(v) => {
self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_some()
}
TyOrConstInferVar::TyFloat(v) => {
self.inner.borrow_mut().float_unification_table().probe_value(v).is_some()
}
TyOrConstInferVar::Const(v) => {
match self.inner.borrow_mut().const_unification_table().probe_value(v).val {
ConstVariableValue::Unknown { .. } => false,
ConstVariableValue::Known { .. } => true,
}
}
}
}
}
#[derive(Copy, Clone, Debug)]
pub enum TyOrConstInferVar<'tcx> {
Ty(TyVid),
TyInt(IntVid),
TyFloat(FloatVid),
Const(ConstVid<'tcx>),
}
impl TyOrConstInferVar<'tcx> {
pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option<Self> {
match arg.unpack() {
GenericArgKind::Type(ty) => Self::maybe_from_ty(ty),
GenericArgKind::Const(ct) => Self::maybe_from_const(ct),
GenericArgKind::Lifetime(_) => None,
}
}
pub fn maybe_from_ty(ty: Ty<'tcx>) -> Option<Self> {
match *ty.kind() {
ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)),
ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)),
ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)),
_ => None,
}
}
pub fn maybe_from_const(ct: &'tcx ty::Const<'tcx>) -> Option<Self> {
match ct.val {
ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)),
_ => None,
}
}
}
struct ShallowResolver<'a, 'tcx> {
infcx: &'a InferCtxt<'a, 'tcx>,
}
impl<'a, 'tcx> TypeFolder<'tcx> for ShallowResolver<'a, 'tcx> {
fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
self.infcx.tcx
}
fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
self.infcx.shallow_resolve_ty(ty)
}
fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
if let ty::Const { val: ty::ConstKind::Infer(InferConst::Var(vid)), .. } = ct {
self.infcx
.inner
.borrow_mut()
.const_unification_table()
.probe_value(*vid)
.val
.known()
.unwrap_or(ct)
} else {
ct
}
}
}
impl<'tcx> TypeTrace<'tcx> {
pub fn span(&self) -> Span {
self.cause.span
}
pub fn types(
cause: &ObligationCause<'tcx>,
a_is_expected: bool,
a: Ty<'tcx>,
b: Ty<'tcx>,
) -> TypeTrace<'tcx> {
TypeTrace { cause: cause.clone(), values: Types(ExpectedFound::new(a_is_expected, a, b)) }
}
pub fn consts(
cause: &ObligationCause<'tcx>,
a_is_expected: bool,
a: &'tcx ty::Const<'tcx>,
b: &'tcx ty::Const<'tcx>,
) -> TypeTrace<'tcx> {
TypeTrace { cause: cause.clone(), values: Consts(ExpectedFound::new(a_is_expected, a, b)) }
}
pub fn dummy(tcx: TyCtxt<'tcx>) -> TypeTrace<'tcx> {
let err = tcx.ty_error();
TypeTrace {
cause: ObligationCause::dummy(),
values: Types(ExpectedFound { expected: err, found: err }),
}
}
}
impl<'tcx> SubregionOrigin<'tcx> {
pub fn span(&self) -> Span {
match *self {
Subtype(ref a) => a.span(),
RelateObjectBound(a) => a,
RelateParamBound(a, _) => a,
RelateRegionParamBound(a) => a,
Reborrow(a) => a,
ReborrowUpvar(a, _) => a,
DataBorrowed(_, a) => a,
ReferenceOutlivesReferent(_, a) => a,
CallReturn(a) => a,
CompareImplMethodObligation { span, .. } => span,
}
}
pub fn from_obligation_cause<F>(cause: &traits::ObligationCause<'tcx>, default: F) -> Self
where
F: FnOnce() -> Self,
{
match cause.code {
traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => {
SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span)
}
traits::ObligationCauseCode::CompareImplMethodObligation {
item_name,
impl_item_def_id,
trait_item_def_id,
} => SubregionOrigin::CompareImplMethodObligation {
span: cause.span,
item_name,
impl_item_def_id,
trait_item_def_id,
},
_ => default(),
}
}
}
impl RegionVariableOrigin {
pub fn span(&self) -> Span {
match *self {
MiscVariable(a)
| PatternRegion(a)
| AddrOfRegion(a)
| Autoref(a, _)
| Coercion(a)
| EarlyBoundRegion(a, ..)
| LateBoundRegion(a, ..)
| UpvarRegion(_, a) => a,
BoundRegionInCoherence(_) => rustc_span::DUMMY_SP,
NLL(..) => bug!("NLL variable used with `span`"),
}
}
}
impl<'tcx> fmt::Debug for RegionObligation<'tcx> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"RegionObligation(sub_region={:?}, sup_type={:?})",
self.sub_region, self.sup_type
)
}
}