Auto merge of #131226 - nnethercote:rustc_infer-cleanups, r=lcnr

`rustc_infer` cleanups

Various small improvements I found while reading over this code.

r? `@lcnr`
This commit is contained in:
bors 2024-10-07 03:22:04 +00:00
commit 8841a3dadd
17 changed files with 97 additions and 202 deletions

View File

@ -925,18 +925,6 @@ impl<'a> DiagCtxtHandle<'a> {
self.inner.borrow_mut().emit_stashed_diagnostics() self.inner.borrow_mut().emit_stashed_diagnostics()
} }
/// This excludes lint errors, and delayed bugs.
#[inline]
pub fn err_count_excluding_lint_errs(&self) -> usize {
let inner = self.inner.borrow();
inner.err_guars.len()
+ inner
.stashed_diagnostics
.values()
.filter(|(diag, guar)| guar.is_some() && diag.is_lint.is_none())
.count()
}
/// This excludes delayed bugs. /// This excludes delayed bugs.
#[inline] #[inline]
pub fn err_count(&self) -> usize { pub fn err_count(&self) -> usize {

View File

@ -82,7 +82,6 @@ impl<'tcx> InferCtxt<'tcx> {
reported_trait_errors: self.reported_trait_errors.clone(), reported_trait_errors: self.reported_trait_errors.clone(),
reported_signature_mismatch: self.reported_signature_mismatch.clone(), reported_signature_mismatch: self.reported_signature_mismatch.clone(),
tainted_by_errors: self.tainted_by_errors.clone(), tainted_by_errors: self.tainted_by_errors.clone(),
err_count_on_creation: self.err_count_on_creation,
universe: self.universe.clone(), universe: self.universe.clone(),
intercrate, intercrate,
next_trait_solver: self.next_trait_solver, next_trait_solver: self.next_trait_solver,
@ -382,21 +381,7 @@ impl<'tcx> ToTrace<'tcx> for ty::GenericArg<'tcx> {
(GenericArgKind::Const(a), GenericArgKind::Const(b)) => { (GenericArgKind::Const(a), GenericArgKind::Const(b)) => {
ValuePairs::Terms(ExpectedFound::new(true, a.into(), b.into())) ValuePairs::Terms(ExpectedFound::new(true, a.into(), b.into()))
} }
_ => bug!("relating different kinds: {a:?} {b:?}"),
(
GenericArgKind::Lifetime(_),
GenericArgKind::Type(_) | GenericArgKind::Const(_),
)
| (
GenericArgKind::Type(_),
GenericArgKind::Lifetime(_) | GenericArgKind::Const(_),
)
| (
GenericArgKind::Const(_),
GenericArgKind::Lifetime(_) | GenericArgKind::Type(_),
) => {
bug!("relating different kinds: {a:?} {b:?}")
}
}, },
} }
} }

View File

@ -14,7 +14,8 @@ use region_constraints::{
GenericKind, RegionConstraintCollector, RegionConstraintStorage, VarInfos, VerifyBound, GenericKind, RegionConstraintCollector, RegionConstraintStorage, VarInfos, VerifyBound,
}; };
pub use relate::StructurallyRelateAliases; pub use relate::StructurallyRelateAliases;
pub use relate::combine::{CombineFields, PredicateEmittingRelation}; use relate::combine::CombineFields;
pub use relate::combine::PredicateEmittingRelation;
use rustc_data_structures::captures::Captures; use rustc_data_structures::captures::Captures;
use rustc_data_structures::fx::{FxHashSet, FxIndexMap}; use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
use rustc_data_structures::sync::Lrc; use rustc_data_structures::sync::Lrc;
@ -50,23 +51,22 @@ use snapshot::undo_log::InferCtxtUndoLogs;
use tracing::{debug, instrument}; use tracing::{debug, instrument};
use type_variable::TypeVariableOrigin; use type_variable::TypeVariableOrigin;
use crate::infer::relate::RelateResult;
use crate::traits::{self, ObligationCause, ObligationInspector, PredicateObligation, TraitEngine}; use crate::traits::{self, ObligationCause, ObligationInspector, PredicateObligation, TraitEngine};
pub mod at; pub mod at;
pub mod canonical; pub mod canonical;
mod context; mod context;
pub mod free_regions; mod free_regions;
mod freshen; mod freshen;
mod lexical_region_resolve; mod lexical_region_resolve;
pub mod opaque_types; mod opaque_types;
pub mod outlives; pub mod outlives;
mod projection; mod projection;
pub mod region_constraints; pub mod region_constraints;
pub mod relate; pub mod relate;
pub mod resolve; pub mod resolve;
pub(crate) mod snapshot; pub(crate) mod snapshot;
pub mod type_variable; mod type_variable;
#[must_use] #[must_use]
#[derive(Debug)] #[derive(Debug)]
@ -76,8 +76,7 @@ pub struct InferOk<'tcx, T> {
} }
pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>; pub type InferResult<'tcx, T> = Result<InferOk<'tcx, T>, TypeError<'tcx>>;
pub type UnitResult<'tcx> = RelateResult<'tcx, ()>; // "unify result" pub(crate) type FixupResult<T> = Result<T, FixupError>; // "fixup result"
pub type FixupResult<T> = Result<T, FixupError>; // "fixup result"
pub(crate) type UnificationTable<'a, 'tcx, T> = ut::UnificationTable< pub(crate) type UnificationTable<'a, 'tcx, T> = ut::UnificationTable<
ut::InPlace<T, &'a mut ut::UnificationStorage<T>, &'a mut InferCtxtUndoLogs<'tcx>>, ut::InPlace<T, &'a mut ut::UnificationStorage<T>, &'a mut InferCtxtUndoLogs<'tcx>>,
@ -202,7 +201,7 @@ impl<'tcx> InferCtxtInner<'tcx> {
} }
#[inline] #[inline]
pub fn opaque_types(&mut self) -> opaque_types::OpaqueTypeTable<'_, 'tcx> { fn opaque_types(&mut self) -> opaque_types::OpaqueTypeTable<'_, 'tcx> {
self.opaque_type_storage.with_log(&mut self.undo_log) self.opaque_type_storage.with_log(&mut self.undo_log)
} }
@ -280,27 +279,14 @@ pub struct InferCtxt<'tcx> {
pub reported_signature_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>, pub reported_signature_mismatch: RefCell<FxHashSet<(Span, Option<Span>)>>,
/// When an error occurs, we want to avoid reporting "derived" /// When an error occurs, we want to avoid reporting "derived"
/// errors that are due to this original failure. Normally, we /// errors that are due to this original failure. We have this
/// handle this with the `err_count_on_creation` count, which /// flag that one can set whenever one creates a type-error that
/// basically just tracks how many errors were reported when we /// is due to an error in a prior pass.
/// started type-checking a fn and checks to see if any new errors
/// have been reported since then. Not great, but it works.
///
/// However, when errors originated in other passes -- notably
/// resolve -- this heuristic breaks down. Therefore, we have this
/// auxiliary 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()` /// Don't read this flag directly, call `is_tainted_by_errors()`
/// and `set_tainted_by_errors()`. /// and `set_tainted_by_errors()`.
tainted_by_errors: Cell<Option<ErrorGuaranteed>>, tainted_by_errors: Cell<Option<ErrorGuaranteed>>,
/// Track how many errors were reported when this infcx is created.
/// If the number of errors increases, that's also a sign (like
/// `tainted_by_errors`) to avoid reporting certain kinds of errors.
// FIXME(matthewjasper) Merge into `tainted_by_errors`
err_count_on_creation: usize,
/// What is the innermost universe we have created? Starts out as /// What is the innermost universe we have created? Starts out as
/// `UniverseIndex::root()` but grows from there as we enter /// `UniverseIndex::root()` but grows from there as we enter
/// universal quantifiers. /// universal quantifiers.
@ -509,14 +495,31 @@ pub enum NllRegionVariableOrigin {
}, },
} }
// FIXME(eddyb) investigate overlap between this and `TyOrConstInferVar`.
#[derive(Copy, Clone, Debug)] #[derive(Copy, Clone, Debug)]
pub enum FixupError { pub struct FixupError {
UnresolvedIntTy(IntVid), unresolved: TyOrConstInferVar,
UnresolvedFloatTy(FloatVid), }
UnresolvedTy(TyVid),
UnresolvedConst(ConstVid), impl fmt::Display for FixupError {
UnresolvedEffect(EffectVid), 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"),
Effect(_) => write!(f, "unconstrained effect value"),
}
}
} }
/// See the `region_obligations` field for more information. /// See the `region_obligations` field for more information.
@ -527,28 +530,6 @@ pub struct RegionObligation<'tcx> {
pub origin: SubregionOrigin<'tcx>, pub origin: SubregionOrigin<'tcx>,
} }
impl fmt::Display for FixupError {
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"),
UnresolvedEffect(_) => write!(f, "unconstrained effect value"),
}
}
}
/// Used to configure inference contexts before their creation. /// Used to configure inference contexts before their creation.
pub struct InferCtxtBuilder<'tcx> { pub struct InferCtxtBuilder<'tcx> {
tcx: TyCtxt<'tcx>, tcx: TyCtxt<'tcx>,
@ -588,14 +569,6 @@ impl<'tcx> InferCtxtBuilder<'tcx> {
self self
} }
pub fn with_defining_opaque_types(
mut self,
defining_opaque_types: &'tcx ty::List<LocalDefId>,
) -> Self {
self.defining_opaque_types = defining_opaque_types;
self
}
pub fn with_next_trait_solver(mut self, next_trait_solver: bool) -> Self { pub fn with_next_trait_solver(mut self, next_trait_solver: bool) -> Self {
self.next_trait_solver = next_trait_solver; self.next_trait_solver = next_trait_solver;
self self
@ -624,14 +597,15 @@ impl<'tcx> InferCtxtBuilder<'tcx> {
/// the bound values in `C` to their instantiated values in `V` /// the bound values in `C` to their instantiated values in `V`
/// (in other words, `S(C) = V`). /// (in other words, `S(C) = V`).
pub fn build_with_canonical<T>( pub fn build_with_canonical<T>(
self, mut self,
span: Span, span: Span,
canonical: &Canonical<'tcx, T>, canonical: &Canonical<'tcx, T>,
) -> (InferCtxt<'tcx>, T, CanonicalVarValues<'tcx>) ) -> (InferCtxt<'tcx>, T, CanonicalVarValues<'tcx>)
where where
T: TypeFoldable<TyCtxt<'tcx>>, T: TypeFoldable<TyCtxt<'tcx>>,
{ {
let infcx = self.with_defining_opaque_types(canonical.defining_opaque_types).build(); self.defining_opaque_types = canonical.defining_opaque_types;
let infcx = self.build();
let (value, args) = infcx.instantiate_canonical(span, canonical); let (value, args) = infcx.instantiate_canonical(span, canonical);
(infcx, value, args) (infcx, value, args)
} }
@ -657,7 +631,6 @@ impl<'tcx> InferCtxtBuilder<'tcx> {
reported_trait_errors: Default::default(), reported_trait_errors: Default::default(),
reported_signature_mismatch: Default::default(), reported_signature_mismatch: Default::default(),
tainted_by_errors: Cell::new(None), tainted_by_errors: Cell::new(None),
err_count_on_creation: tcx.dcx().err_count_excluding_lint_errs(),
universe: Cell::new(ty::UniverseIndex::ROOT), universe: Cell::new(ty::UniverseIndex::ROOT),
intercrate, intercrate,
next_trait_solver, next_trait_solver,
@ -919,28 +892,16 @@ impl<'tcx> InferCtxt<'tcx> {
ty::Const::new_var(self.tcx, vid) ty::Const::new_var(self.tcx, vid)
} }
pub fn next_const_var_id(&self, origin: ConstVariableOrigin) -> ConstVid {
self.inner
.borrow_mut()
.const_unification_table()
.new_key(ConstVariableValue::Unknown { origin, universe: self.universe() })
.vid
}
fn next_int_var_id(&self) -> IntVid {
self.inner.borrow_mut().int_unification_table().new_key(ty::IntVarValue::Unknown)
}
pub fn next_int_var(&self) -> Ty<'tcx> { pub fn next_int_var(&self) -> Ty<'tcx> {
Ty::new_int_var(self.tcx, self.next_int_var_id()) 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)
fn next_float_var_id(&self) -> FloatVid {
self.inner.borrow_mut().float_unification_table().new_key(ty::FloatVarValue::Unknown)
} }
pub fn next_float_var(&self) -> Ty<'tcx> { pub fn next_float_var(&self) -> Ty<'tcx> {
Ty::new_float_var(self.tcx, self.next_float_var_id()) 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. /// Creates a fresh region variable with the next available index.
@ -1353,7 +1314,7 @@ impl<'tcx> InferCtxt<'tcx> {
} }
/// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method. /// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method.
pub fn verify_generic_bound( pub(crate) fn verify_generic_bound(
&self, &self,
origin: SubregionOrigin<'tcx>, origin: SubregionOrigin<'tcx>,
kind: GenericKind<'tcx>, kind: GenericKind<'tcx>,

View File

@ -13,16 +13,15 @@ use rustc_middle::ty::{
use rustc_span::Span; use rustc_span::Span;
use tracing::{debug, instrument}; use tracing::{debug, instrument};
use super::DefineOpaqueTypes;
use crate::errors::OpaqueHiddenTypeDiag; use crate::errors::OpaqueHiddenTypeDiag;
use crate::infer::{InferCtxt, InferOk}; use crate::infer::{InferCtxt, InferOk};
use crate::traits::{self, Obligation}; use crate::traits::{self, Obligation};
mod table; mod table;
pub type OpaqueTypeMap<'tcx> = FxIndexMap<OpaqueTypeKey<'tcx>, OpaqueTypeDecl<'tcx>>; pub(crate) type OpaqueTypeMap<'tcx> = FxIndexMap<OpaqueTypeKey<'tcx>, OpaqueTypeDecl<'tcx>>;
pub use table::{OpaqueTypeStorage, OpaqueTypeTable}; pub(crate) use table::{OpaqueTypeStorage, OpaqueTypeTable};
use super::DefineOpaqueTypes;
/// Information about the opaque types whose values we /// Information about the opaque types whose values we
/// are inferring in this function (these are the `impl Trait` that /// are inferring in this function (these are the `impl Trait` that
@ -377,9 +376,9 @@ impl<'tcx> InferCtxt<'tcx> {
/// ///
/// We ignore any type parameters because impl trait values are assumed to /// We ignore any type parameters because impl trait values are assumed to
/// capture all the in-scope type parameters. /// capture all the in-scope type parameters.
pub struct ConstrainOpaqueTypeRegionVisitor<'tcx, OP: FnMut(ty::Region<'tcx>)> { struct ConstrainOpaqueTypeRegionVisitor<'tcx, OP: FnMut(ty::Region<'tcx>)> {
pub tcx: TyCtxt<'tcx>, tcx: TyCtxt<'tcx>,
pub op: OP, op: OP,
} }
impl<'tcx, OP> TypeVisitor<TyCtxt<'tcx>> for ConstrainOpaqueTypeRegionVisitor<'tcx, OP> impl<'tcx, OP> TypeVisitor<TyCtxt<'tcx>> for ConstrainOpaqueTypeRegionVisitor<'tcx, OP>
@ -455,20 +454,6 @@ where
} }
} }
pub enum UseKind {
DefiningUse,
OpaqueUse,
}
impl UseKind {
pub fn is_defining(self) -> bool {
match self {
UseKind::DefiningUse => true,
UseKind::OpaqueUse => false,
}
}
}
impl<'tcx> InferCtxt<'tcx> { impl<'tcx> InferCtxt<'tcx> {
#[instrument(skip(self), level = "debug")] #[instrument(skip(self), level = "debug")]
fn register_hidden_type( fn register_hidden_type(

View File

@ -7,7 +7,7 @@ use super::{OpaqueTypeDecl, OpaqueTypeMap};
use crate::infer::snapshot::undo_log::{InferCtxtUndoLogs, UndoLog}; use crate::infer::snapshot::undo_log::{InferCtxtUndoLogs, UndoLog};
#[derive(Default, Debug, Clone)] #[derive(Default, Debug, Clone)]
pub struct OpaqueTypeStorage<'tcx> { pub(crate) struct OpaqueTypeStorage<'tcx> {
/// Opaque types found in explicit return types and their /// Opaque types found in explicit return types and their
/// associated fresh inference variable. Writeback resolves these /// associated fresh inference variable. Writeback resolves these
/// variables to get the concrete type, which can be used to /// variables to get the concrete type, which can be used to
@ -46,7 +46,7 @@ impl<'tcx> Drop for OpaqueTypeStorage<'tcx> {
} }
} }
pub struct OpaqueTypeTable<'a, 'tcx> { pub(crate) struct OpaqueTypeTable<'a, 'tcx> {
storage: &'a mut OpaqueTypeStorage<'tcx>, storage: &'a mut OpaqueTypeStorage<'tcx>,
undo_log: &'a mut InferCtxtUndoLogs<'tcx>, undo_log: &'a mut InferCtxtUndoLogs<'tcx>,

View File

@ -14,7 +14,7 @@ pub mod env;
pub mod for_liveness; pub mod for_liveness;
pub mod obligations; pub mod obligations;
pub mod test_type_match; pub mod test_type_match;
pub mod verify; pub(crate) mod verify;
#[instrument(level = "debug", skip(param_env), ret)] #[instrument(level = "debug", skip(param_env), ret)]
pub fn explicit_outlives_bounds<'tcx>( pub fn explicit_outlives_bounds<'tcx>(

View File

@ -15,7 +15,7 @@ use crate::infer::{GenericKind, VerifyBound};
/// via a "delegate" of type `D` -- this is usually the `infcx`, which /// via a "delegate" of type `D` -- this is usually the `infcx`, which
/// accrues them into the `region_obligations` code, but for NLL we /// accrues them into the `region_obligations` code, but for NLL we
/// use something else. /// use something else.
pub struct VerifyBoundCx<'cx, 'tcx> { pub(crate) struct VerifyBoundCx<'cx, 'tcx> {
tcx: TyCtxt<'tcx>, tcx: TyCtxt<'tcx>,
region_bound_pairs: &'cx RegionBoundPairs<'tcx>, region_bound_pairs: &'cx RegionBoundPairs<'tcx>,
/// During borrowck, if there are no outlives bounds on a generic /// During borrowck, if there are no outlives bounds on a generic
@ -28,7 +28,7 @@ pub struct VerifyBoundCx<'cx, 'tcx> {
} }
impl<'cx, 'tcx> VerifyBoundCx<'cx, 'tcx> { impl<'cx, 'tcx> VerifyBoundCx<'cx, 'tcx> {
pub fn new( pub(crate) fn new(
tcx: TyCtxt<'tcx>, tcx: TyCtxt<'tcx>,
region_bound_pairs: &'cx RegionBoundPairs<'tcx>, region_bound_pairs: &'cx RegionBoundPairs<'tcx>,
implicit_region_bound: Option<ty::Region<'tcx>>, implicit_region_bound: Option<ty::Region<'tcx>>,
@ -38,7 +38,7 @@ impl<'cx, 'tcx> VerifyBoundCx<'cx, 'tcx> {
} }
#[instrument(level = "debug", skip(self))] #[instrument(level = "debug", skip(self))]
pub fn param_or_placeholder_bound(&self, ty: Ty<'tcx>) -> VerifyBound<'tcx> { pub(crate) fn param_or_placeholder_bound(&self, ty: Ty<'tcx>) -> VerifyBound<'tcx> {
// Start with anything like `T: 'a` we can scrape from the // Start with anything like `T: 'a` we can scrape from the
// environment. If the environment contains something like // environment. If the environment contains something like
// `for<'a> T: 'a`, then we know that `T` outlives everything. // `for<'a> T: 'a`, then we know that `T` outlives everything.
@ -92,7 +92,7 @@ impl<'cx, 'tcx> VerifyBoundCx<'cx, 'tcx> {
/// the clause from the environment only applies if `'0 = 'a`, /// the clause from the environment only applies if `'0 = 'a`,
/// which we don't know yet. But we would still include `'b` in /// which we don't know yet. But we would still include `'b` in
/// this list. /// this list.
pub fn approx_declared_bounds_from_env( pub(crate) fn approx_declared_bounds_from_env(
&self, &self,
alias_ty: ty::AliasTy<'tcx>, alias_ty: ty::AliasTy<'tcx>,
) -> Vec<ty::PolyTypeOutlivesPredicate<'tcx>> { ) -> Vec<ty::PolyTypeOutlivesPredicate<'tcx>> {
@ -101,7 +101,7 @@ impl<'cx, 'tcx> VerifyBoundCx<'cx, 'tcx> {
} }
#[instrument(level = "debug", skip(self))] #[instrument(level = "debug", skip(self))]
pub fn alias_bound(&self, alias_ty: ty::AliasTy<'tcx>) -> VerifyBound<'tcx> { pub(crate) fn alias_bound(&self, alias_ty: ty::AliasTy<'tcx>) -> VerifyBound<'tcx> {
let alias_ty_as_ty = alias_ty.to_ty(self.tcx); let alias_ty_as_ty = alias_ty.to_ty(self.tcx);
// Search the env for where clauses like `P: 'a`. // Search the env for where clauses like `P: 'a`.
@ -285,7 +285,7 @@ impl<'cx, 'tcx> VerifyBoundCx<'cx, 'tcx> {
/// ///
/// This is for simplicity, and because we are not really smart /// This is for simplicity, and because we are not really smart
/// enough to cope with such bounds anywhere. /// enough to cope with such bounds anywhere.
pub fn declared_bounds_from_definition( pub(crate) fn declared_bounds_from_definition(
&self, &self,
alias_ty: ty::AliasTy<'tcx>, alias_ty: ty::AliasTy<'tcx>,
) -> impl Iterator<Item = ty::Region<'tcx>> { ) -> impl Iterator<Item = ty::Region<'tcx>> {

View File

@ -304,7 +304,7 @@ pub struct RegionVariableInfo {
pub universe: ty::UniverseIndex, pub universe: ty::UniverseIndex,
} }
pub struct RegionSnapshot { pub(crate) struct RegionSnapshot {
any_unifications: bool, any_unifications: bool,
} }

View File

@ -33,7 +33,7 @@ use crate::infer::{DefineOpaqueTypes, InferCtxt, TypeTrace, relate};
use crate::traits::{Obligation, PredicateObligation}; use crate::traits::{Obligation, PredicateObligation};
#[derive(Clone)] #[derive(Clone)]
pub struct CombineFields<'infcx, 'tcx> { pub(crate) struct CombineFields<'infcx, 'tcx> {
pub infcx: &'infcx InferCtxt<'tcx>, pub infcx: &'infcx InferCtxt<'tcx>,
// Immutable fields // Immutable fields
pub trace: TypeTrace<'tcx>, pub trace: TypeTrace<'tcx>,
@ -47,7 +47,7 @@ pub struct CombineFields<'infcx, 'tcx> {
} }
impl<'infcx, 'tcx> CombineFields<'infcx, 'tcx> { impl<'infcx, 'tcx> CombineFields<'infcx, 'tcx> {
pub fn new( pub(crate) fn new(
infcx: &'infcx InferCtxt<'tcx>, infcx: &'infcx InferCtxt<'tcx>,
trace: TypeTrace<'tcx>, trace: TypeTrace<'tcx>,
param_env: ty::ParamEnv<'tcx>, param_env: ty::ParamEnv<'tcx>,
@ -283,22 +283,22 @@ impl<'tcx> InferCtxt<'tcx> {
} }
impl<'infcx, 'tcx> CombineFields<'infcx, 'tcx> { impl<'infcx, 'tcx> CombineFields<'infcx, 'tcx> {
pub fn tcx(&self) -> TyCtxt<'tcx> { pub(crate) fn tcx(&self) -> TyCtxt<'tcx> {
self.infcx.tcx self.infcx.tcx
} }
pub fn equate<'a>( pub(crate) fn equate<'a>(
&'a mut self, &'a mut self,
structurally_relate_aliases: StructurallyRelateAliases, structurally_relate_aliases: StructurallyRelateAliases,
) -> TypeRelating<'a, 'infcx, 'tcx> { ) -> TypeRelating<'a, 'infcx, 'tcx> {
TypeRelating::new(self, structurally_relate_aliases, ty::Invariant) TypeRelating::new(self, structurally_relate_aliases, ty::Invariant)
} }
pub fn sub<'a>(&'a mut self) -> TypeRelating<'a, 'infcx, 'tcx> { pub(crate) fn sub<'a>(&'a mut self) -> TypeRelating<'a, 'infcx, 'tcx> {
TypeRelating::new(self, StructurallyRelateAliases::No, ty::Covariant) TypeRelating::new(self, StructurallyRelateAliases::No, ty::Covariant)
} }
pub fn sup<'a>(&'a mut self) -> TypeRelating<'a, 'infcx, 'tcx> { pub(crate) fn sup<'a>(&'a mut self) -> TypeRelating<'a, 'infcx, 'tcx> {
TypeRelating::new(self, StructurallyRelateAliases::No, ty::Contravariant) TypeRelating::new(self, StructurallyRelateAliases::No, ty::Contravariant)
} }
@ -310,14 +310,14 @@ impl<'infcx, 'tcx> CombineFields<'infcx, 'tcx> {
LatticeOp::new(self, LatticeOpKind::Glb) LatticeOp::new(self, LatticeOpKind::Glb)
} }
pub fn register_obligations( pub(crate) fn register_obligations(
&mut self, &mut self,
obligations: impl IntoIterator<Item = Goal<'tcx, ty::Predicate<'tcx>>>, obligations: impl IntoIterator<Item = Goal<'tcx, ty::Predicate<'tcx>>>,
) { ) {
self.goals.extend(obligations); self.goals.extend(obligations);
} }
pub fn register_predicates( pub(crate) fn register_predicates(
&mut self, &mut self,
obligations: impl IntoIterator<Item: Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>>>, obligations: impl IntoIterator<Item: Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>>>,
) { ) {

View File

@ -5,7 +5,7 @@
pub use rustc_middle::ty::relate::RelateResult; pub use rustc_middle::ty::relate::RelateResult;
pub use rustc_next_trait_solver::relate::*; pub use rustc_next_trait_solver::relate::*;
pub use self::combine::{CombineFields, PredicateEmittingRelation}; pub use self::combine::PredicateEmittingRelation;
#[allow(hidden_glob_reexports)] #[allow(hidden_glob_reexports)]
pub(super) mod combine; pub(super) mod combine;

View File

@ -13,7 +13,7 @@ use crate::infer::relate::{PredicateEmittingRelation, StructurallyRelateAliases}
use crate::infer::{DefineOpaqueTypes, InferCtxt, SubregionOrigin}; use crate::infer::{DefineOpaqueTypes, InferCtxt, SubregionOrigin};
/// Enforce that `a` is equal to or a subtype of `b`. /// Enforce that `a` is equal to or a subtype of `b`.
pub struct TypeRelating<'combine, 'a, 'tcx> { pub(crate) struct TypeRelating<'combine, 'a, 'tcx> {
// Immutable except for the `InferCtxt` and the // Immutable except for the `InferCtxt` and the
// resulting nested `goals`. // resulting nested `goals`.
fields: &'combine mut CombineFields<'a, 'tcx>, fields: &'combine mut CombineFields<'a, 'tcx>,
@ -49,7 +49,7 @@ pub struct TypeRelating<'combine, 'a, 'tcx> {
} }
impl<'combine, 'infcx, 'tcx> TypeRelating<'combine, 'infcx, 'tcx> { impl<'combine, 'infcx, 'tcx> TypeRelating<'combine, 'infcx, 'tcx> {
pub fn new( pub(crate) fn new(
f: &'combine mut CombineFields<'infcx, 'tcx>, f: &'combine mut CombineFields<'infcx, 'tcx>,
structurally_relate_aliases: StructurallyRelateAliases, structurally_relate_aliases: StructurallyRelateAliases,
ambient_variance: ty::Variance, ambient_variance: ty::Variance,

View File

@ -121,8 +121,6 @@ where
value.try_fold_with(&mut FullTypeResolver { infcx }) value.try_fold_with(&mut FullTypeResolver { infcx })
} }
// N.B. This type is not public because the protocol around checking the
// `err` field is not enforceable otherwise.
struct FullTypeResolver<'a, 'tcx> { struct FullTypeResolver<'a, 'tcx> {
infcx: &'a InferCtxt<'tcx>, infcx: &'a InferCtxt<'tcx>,
} }
@ -138,11 +136,13 @@ impl<'a, 'tcx> FallibleTypeFolder<TyCtxt<'tcx>> for FullTypeResolver<'a, 'tcx> {
if !t.has_infer() { if !t.has_infer() {
Ok(t) // micro-optimize -- if there is nothing in this type that this fold affects... Ok(t) // micro-optimize -- if there is nothing in this type that this fold affects...
} else { } else {
use super::TyOrConstInferVar::*;
let t = self.infcx.shallow_resolve(t); let t = self.infcx.shallow_resolve(t);
match *t.kind() { match *t.kind() {
ty::Infer(ty::TyVar(vid)) => Err(FixupError::UnresolvedTy(vid)), ty::Infer(ty::TyVar(vid)) => Err(FixupError { unresolved: Ty(vid) }),
ty::Infer(ty::IntVar(vid)) => Err(FixupError::UnresolvedIntTy(vid)), ty::Infer(ty::IntVar(vid)) => Err(FixupError { unresolved: TyInt(vid) }),
ty::Infer(ty::FloatVar(vid)) => Err(FixupError::UnresolvedFloatTy(vid)), ty::Infer(ty::FloatVar(vid)) => Err(FixupError { unresolved: TyFloat(vid) }),
ty::Infer(_) => { ty::Infer(_) => {
bug!("Unexpected type in full type resolver: {:?}", t); bug!("Unexpected type in full type resolver: {:?}", t);
} }
@ -171,13 +171,13 @@ impl<'a, 'tcx> FallibleTypeFolder<TyCtxt<'tcx>> for FullTypeResolver<'a, 'tcx> {
let c = self.infcx.shallow_resolve_const(c); let c = self.infcx.shallow_resolve_const(c);
match c.kind() { match c.kind() {
ty::ConstKind::Infer(InferConst::Var(vid)) => { ty::ConstKind::Infer(InferConst::Var(vid)) => {
return Err(FixupError::UnresolvedConst(vid)); return Err(FixupError { unresolved: super::TyOrConstInferVar::Const(vid) });
} }
ty::ConstKind::Infer(InferConst::Fresh(_)) => { ty::ConstKind::Infer(InferConst::Fresh(_)) => {
bug!("Unexpected const in full const resolver: {:?}", c); bug!("Unexpected const in full const resolver: {:?}", c);
} }
ty::ConstKind::Infer(InferConst::EffectVar(evid)) => { ty::ConstKind::Infer(InferConst::EffectVar(evid)) => {
return Err(FixupError::UnresolvedEffect(evid)); return Err(FixupError { unresolved: super::TyOrConstInferVar::Effect(evid) });
} }
_ => {} _ => {}
} }

View File

@ -5,7 +5,7 @@ use tracing::{debug, instrument};
use super::InferCtxt; use super::InferCtxt;
use super::region_constraints::RegionSnapshot; use super::region_constraints::RegionSnapshot;
mod fudge; pub(crate) mod fudge;
pub(crate) mod undo_log; pub(crate) mod undo_log;
use undo_log::{Snapshot, UndoLog}; use undo_log::{Snapshot, UndoLog};

View File

@ -20,7 +20,7 @@ impl<'tcx> Rollback<sv::UndoLog<ut::Delegate<TyVidEqKey<'tcx>>>> for TypeVariabl
} }
#[derive(Clone)] #[derive(Clone)]
pub struct TypeVariableStorage<'tcx> { pub(crate) struct TypeVariableStorage<'tcx> {
/// The origins of each type variable. /// The origins of each type variable.
values: IndexVec<TyVid, TypeVariableData>, values: IndexVec<TyVid, TypeVariableData>,
/// Two variables are unified in `eq_relations` when we have a /// Two variables are unified in `eq_relations` when we have a
@ -29,7 +29,7 @@ pub struct TypeVariableStorage<'tcx> {
eq_relations: ut::UnificationTableStorage<TyVidEqKey<'tcx>>, eq_relations: ut::UnificationTableStorage<TyVidEqKey<'tcx>>,
} }
pub struct TypeVariableTable<'a, 'tcx> { pub(crate) struct TypeVariableTable<'a, 'tcx> {
storage: &'a mut TypeVariableStorage<'tcx>, storage: &'a mut TypeVariableStorage<'tcx>,
undo_log: &'a mut InferCtxtUndoLogs<'tcx>, undo_log: &'a mut InferCtxtUndoLogs<'tcx>,
@ -50,7 +50,7 @@ pub(crate) struct TypeVariableData {
} }
#[derive(Copy, Clone, Debug)] #[derive(Copy, Clone, Debug)]
pub enum TypeVariableValue<'tcx> { pub(crate) enum TypeVariableValue<'tcx> {
Known { value: Ty<'tcx> }, Known { value: Ty<'tcx> },
Unknown { universe: ty::UniverseIndex }, Unknown { universe: ty::UniverseIndex },
} }
@ -58,14 +58,14 @@ pub enum TypeVariableValue<'tcx> {
impl<'tcx> TypeVariableValue<'tcx> { impl<'tcx> TypeVariableValue<'tcx> {
/// If this value is known, returns the type it is known to be. /// If this value is known, returns the type it is known to be.
/// Otherwise, `None`. /// Otherwise, `None`.
pub fn known(&self) -> Option<Ty<'tcx>> { pub(crate) fn known(&self) -> Option<Ty<'tcx>> {
match *self { match *self {
TypeVariableValue::Unknown { .. } => None, TypeVariableValue::Unknown { .. } => None,
TypeVariableValue::Known { value } => Some(value), TypeVariableValue::Known { value } => Some(value),
} }
} }
pub fn is_unknown(&self) -> bool { pub(crate) fn is_unknown(&self) -> bool {
match *self { match *self {
TypeVariableValue::Unknown { .. } => true, TypeVariableValue::Unknown { .. } => true,
TypeVariableValue::Known { .. } => false, TypeVariableValue::Known { .. } => false,
@ -74,7 +74,7 @@ impl<'tcx> TypeVariableValue<'tcx> {
} }
impl<'tcx> TypeVariableStorage<'tcx> { impl<'tcx> TypeVariableStorage<'tcx> {
pub fn new() -> TypeVariableStorage<'tcx> { pub(crate) fn new() -> TypeVariableStorage<'tcx> {
TypeVariableStorage { TypeVariableStorage {
values: Default::default(), values: Default::default(),
eq_relations: ut::UnificationTableStorage::new(), eq_relations: ut::UnificationTableStorage::new(),
@ -105,14 +105,14 @@ impl<'tcx> TypeVariableTable<'_, 'tcx> {
/// ///
/// Note that this function does not return care whether /// Note that this function does not return care whether
/// `vid` has been unified with something else or not. /// `vid` has been unified with something else or not.
pub fn var_origin(&self, vid: ty::TyVid) -> TypeVariableOrigin { pub(crate) fn var_origin(&self, vid: ty::TyVid) -> TypeVariableOrigin {
self.storage.values[vid].origin self.storage.values[vid].origin
} }
/// Records that `a == b`, depending on `dir`. /// Records that `a == b`, depending on `dir`.
/// ///
/// Precondition: neither `a` nor `b` are known. /// Precondition: neither `a` nor `b` are known.
pub fn equate(&mut self, a: ty::TyVid, b: ty::TyVid) { pub(crate) fn equate(&mut self, a: ty::TyVid, b: ty::TyVid) {
debug_assert!(self.probe(a).is_unknown()); debug_assert!(self.probe(a).is_unknown());
debug_assert!(self.probe(b).is_unknown()); debug_assert!(self.probe(b).is_unknown());
self.eq_relations().union(a, b); self.eq_relations().union(a, b);
@ -121,7 +121,7 @@ impl<'tcx> TypeVariableTable<'_, 'tcx> {
/// Instantiates `vid` with the type `ty`. /// Instantiates `vid` with the type `ty`.
/// ///
/// Precondition: `vid` must not have been previously instantiated. /// Precondition: `vid` must not have been previously instantiated.
pub fn instantiate(&mut self, vid: ty::TyVid, ty: Ty<'tcx>) { pub(crate) fn instantiate(&mut self, vid: ty::TyVid, ty: Ty<'tcx>) {
let vid = self.root_var(vid); let vid = self.root_var(vid);
debug_assert!(!ty.is_ty_var(), "instantiating ty var with var: {vid:?} {ty:?}"); debug_assert!(!ty.is_ty_var(), "instantiating ty var with var: {vid:?} {ty:?}");
debug_assert!(self.probe(vid).is_unknown()); debug_assert!(self.probe(vid).is_unknown());
@ -143,7 +143,7 @@ impl<'tcx> TypeVariableTable<'_, 'tcx> {
/// - `origin`: indicates *why* the type variable was created. /// - `origin`: indicates *why* the type variable was created.
/// The code in this module doesn't care, but it can be useful /// The code in this module doesn't care, but it can be useful
/// for improving error messages. /// for improving error messages.
pub fn new_var( pub(crate) fn new_var(
&mut self, &mut self,
universe: ty::UniverseIndex, universe: ty::UniverseIndex,
origin: TypeVariableOrigin, origin: TypeVariableOrigin,
@ -158,7 +158,7 @@ impl<'tcx> TypeVariableTable<'_, 'tcx> {
} }
/// Returns the number of type variables created thus far. /// Returns the number of type variables created thus far.
pub fn num_vars(&self) -> usize { pub(crate) fn num_vars(&self) -> usize {
self.storage.values.len() self.storage.values.len()
} }
@ -167,42 +167,29 @@ impl<'tcx> TypeVariableTable<'_, 'tcx> {
/// will yield the same root variable (per the union-find /// will yield the same root variable (per the union-find
/// algorithm), so `root_var(a) == root_var(b)` implies that `a == /// algorithm), so `root_var(a) == root_var(b)` implies that `a ==
/// b` (transitively). /// b` (transitively).
pub fn root_var(&mut self, vid: ty::TyVid) -> ty::TyVid { pub(crate) fn root_var(&mut self, vid: ty::TyVid) -> ty::TyVid {
self.eq_relations().find(vid).vid self.eq_relations().find(vid).vid
} }
/// Retrieves the type to which `vid` has been instantiated, if /// Retrieves the type to which `vid` has been instantiated, if
/// any. /// any.
pub fn probe(&mut self, vid: ty::TyVid) -> TypeVariableValue<'tcx> { pub(crate) fn probe(&mut self, vid: ty::TyVid) -> TypeVariableValue<'tcx> {
self.inlined_probe(vid) self.inlined_probe(vid)
} }
/// An always-inlined variant of `probe`, for very hot call sites. /// An always-inlined variant of `probe`, for very hot call sites.
#[inline(always)] #[inline(always)]
pub fn inlined_probe(&mut self, vid: ty::TyVid) -> TypeVariableValue<'tcx> { pub(crate) fn inlined_probe(&mut self, vid: ty::TyVid) -> TypeVariableValue<'tcx> {
self.eq_relations().inlined_probe_value(vid) self.eq_relations().inlined_probe_value(vid)
} }
/// If `t` is a type-inference variable, and it has been
/// instantiated, then return the with which it was
/// instantiated. Otherwise, returns `t`.
pub fn replace_if_possible(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
match *t.kind() {
ty::Infer(ty::TyVar(v)) => match self.probe(v) {
TypeVariableValue::Unknown { .. } => t,
TypeVariableValue::Known { value } => value,
},
_ => t,
}
}
#[inline] #[inline]
fn eq_relations(&mut self) -> super::UnificationTable<'_, 'tcx, TyVidEqKey<'tcx>> { fn eq_relations(&mut self) -> super::UnificationTable<'_, 'tcx, TyVidEqKey<'tcx>> {
self.storage.eq_relations.with_log(self.undo_log) self.storage.eq_relations.with_log(self.undo_log)
} }
/// Returns a range of the type variables created during the snapshot. /// Returns a range of the type variables created during the snapshot.
pub fn vars_since_snapshot( pub(crate) fn vars_since_snapshot(
&mut self, &mut self,
value_count: usize, value_count: usize,
) -> (Range<TyVid>, Vec<TypeVariableOrigin>) { ) -> (Range<TyVid>, Vec<TypeVariableOrigin>) {
@ -215,7 +202,7 @@ impl<'tcx> TypeVariableTable<'_, 'tcx> {
/// Returns indices of all variables that are not yet /// Returns indices of all variables that are not yet
/// instantiated. /// instantiated.
pub fn unresolved_variables(&mut self) -> Vec<ty::TyVid> { pub(crate) fn unresolved_variables(&mut self) -> Vec<ty::TyVid> {
(0..self.num_vars()) (0..self.num_vars())
.filter_map(|i| { .filter_map(|i| {
let vid = ty::TyVid::from_usize(i); let vid = ty::TyVid::from_usize(i);

View File

@ -19,10 +19,7 @@
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")] #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
#![doc(rust_logo)] #![doc(rust_logo)]
#![feature(assert_matches)] #![feature(assert_matches)]
#![feature(box_patterns)]
#![feature(extend_one)] #![feature(extend_one)]
#![feature(if_let_guard)]
#![feature(iter_intersperse)]
#![feature(iterator_try_collect)] #![feature(iterator_try_collect)]
#![feature(let_chains)] #![feature(let_chains)]
#![feature(rustdoc_internals)] #![feature(rustdoc_internals)]

View File

@ -212,15 +212,7 @@ impl<'tcx> Relate<TyCtxt<'tcx>> for ty::GenericArg<'tcx> {
(ty::GenericArgKind::Const(a_ct), ty::GenericArgKind::Const(b_ct)) => { (ty::GenericArgKind::Const(a_ct), ty::GenericArgKind::Const(b_ct)) => {
Ok(relation.relate(a_ct, b_ct)?.into()) Ok(relation.relate(a_ct, b_ct)?.into())
} }
(ty::GenericArgKind::Lifetime(unpacked), x) => { _ => bug!("impossible case reached: can't relate: {a:?} with {b:?}"),
bug!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
}
(ty::GenericArgKind::Type(unpacked), x) => {
bug!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
}
(ty::GenericArgKind::Const(unpacked), x) => {
bug!("impossible case reached: can't relate: {:?} with {:?}", unpacked, x)
}
} }
} }
} }