Auto merge of #67953 - cjgillot:split_infer, r=Zoxc

Split librustc::{traits,infer} to a separate crate rustc_infer

This is still very much work in progress.
Three functions are between dimensions (at the end of `rustc::traits`), waiting for some dependency breaking scheme.
Please tell me if the approach seems sound, and how you would like to split this PR up.

The formatting is deliberately off, to ease rebasing.

cc #65031
This commit is contained in:
bors 2020-02-16 22:24:54 +00:00
commit a643ee8d69
177 changed files with 8571 additions and 8392 deletions

View File

@ -3111,8 +3111,6 @@ dependencies = [
"bitflags",
"byteorder",
"chalk-engine",
"fmt_macros",
"graphviz",
"jobserver",
"log",
"measureme",
@ -3776,6 +3774,28 @@ dependencies = [
"smallvec 1.0.0",
]
[[package]]
name = "rustc_infer"
version = "0.0.0"
dependencies = [
"fmt_macros",
"graphviz",
"log",
"rustc",
"rustc_attr",
"rustc_data_structures",
"rustc_error_codes",
"rustc_errors",
"rustc_hir",
"rustc_index",
"rustc_macros",
"rustc_session",
"rustc_span",
"rustc_target",
"smallvec 1.0.0",
"syntax",
]
[[package]]
name = "rustc_interface"
version = "0.0.0"
@ -3796,6 +3816,7 @@ dependencies = [
"rustc_expand",
"rustc_hir",
"rustc_incremental",
"rustc_infer",
"rustc_lint",
"rustc_metadata",
"rustc_mir",
@ -3838,6 +3859,7 @@ dependencies = [
"rustc_feature",
"rustc_hir",
"rustc_index",
"rustc_infer",
"rustc_session",
"rustc_span",
"rustc_target",
@ -3907,6 +3929,7 @@ dependencies = [
"rustc_errors",
"rustc_hir",
"rustc_index",
"rustc_infer",
"rustc_lexer",
"rustc_macros",
"rustc_span",
@ -3929,6 +3952,7 @@ dependencies = [
"rustc_errors",
"rustc_hir",
"rustc_index",
"rustc_infer",
"rustc_macros",
"rustc_session",
"rustc_span",
@ -3969,6 +3993,7 @@ dependencies = [
"rustc_feature",
"rustc_hir",
"rustc_index",
"rustc_infer",
"rustc_session",
"rustc_span",
"rustc_target",
@ -4019,6 +4044,7 @@ dependencies = [
"rustc_expand",
"rustc_feature",
"rustc_hir",
"rustc_infer",
"rustc_metadata",
"rustc_session",
"rustc_span",
@ -4108,6 +4134,7 @@ dependencies = [
"rustc",
"rustc_data_structures",
"rustc_hir",
"rustc_infer",
"rustc_macros",
"rustc_span",
"rustc_target",
@ -4123,6 +4150,7 @@ dependencies = [
"rustc",
"rustc_data_structures",
"rustc_hir",
"rustc_infer",
"rustc_span",
"rustc_target",
]
@ -4139,6 +4167,7 @@ dependencies = [
"rustc_errors",
"rustc_hir",
"rustc_index",
"rustc_infer",
"rustc_span",
"rustc_target",
"smallvec 1.0.0",

View File

@ -12,8 +12,6 @@ doctest = false
[dependencies]
arena = { path = "../libarena" }
bitflags = "1.2.1"
fmt_macros = { path = "../libfmt_macros" }
graphviz = { path = "../libgraphviz" }
jobserver = "0.1"
scoped-tls = "1.0"
log = { version = "0.4", features = ["release_max_level_info", "std"] }

View File

@ -51,19 +51,19 @@ macro_rules! arena_types {
[] dropck_outlives:
rustc::infer::canonical::Canonical<'tcx,
rustc::infer::canonical::QueryResponse<'tcx,
rustc::traits::query::dropck_outlives::DropckOutlivesResult<'tcx>
rustc::traits::query::DropckOutlivesResult<'tcx>
>
>,
[] normalize_projection_ty:
rustc::infer::canonical::Canonical<'tcx,
rustc::infer::canonical::QueryResponse<'tcx,
rustc::traits::query::normalize::NormalizationResult<'tcx>
rustc::traits::query::NormalizationResult<'tcx>
>
>,
[] implied_outlives_bounds:
rustc::infer::canonical::Canonical<'tcx,
rustc::infer::canonical::QueryResponse<'tcx,
Vec<rustc::traits::query::outlives_bounds::OutlivesBound<'tcx>>
Vec<rustc::traits::query::OutlivesBound<'tcx>>
>
>,
[] type_op_subtype:

View File

@ -21,7 +21,7 @@
//!
//! [c]: https://rust-lang.github.io/rustc-guide/traits/canonicalization.html
use crate::infer::region_constraints::MemberConstraint;
use crate::infer::MemberConstraint;
use crate::ty::subst::GenericArg;
use crate::ty::{self, BoundVar, List, Region, TyCtxt};
use rustc_index::vec::IndexVec;

File diff suppressed because it is too large Load Diff

View File

@ -1,31 +0,0 @@
pub mod canonical;
use crate::ty::Region;
use crate::ty::Ty;
use rustc_data_structures::sync::Lrc;
use rustc_hir::def_id::DefId;
use rustc_span::Span;
/// Requires that `region` must be equal to one of the regions in `choice_regions`.
/// We often denote this using the syntax:
///
/// ```
/// R0 member of [O1..On]
/// ```
#[derive(Debug, Clone, HashStable, TypeFoldable, Lift)]
pub struct MemberConstraint<'tcx> {
/// The `DefId` of the opaque type causing this constraint: used for error reporting.
pub opaque_type_def_id: DefId,
/// The span where the hidden type was instantiated.
pub definition_span: Span,
/// The hidden type in which `member_region` appears: used for error reporting.
pub hidden_ty: Ty<'tcx>,
/// The region `R0`.
pub member_region: Region<'tcx>,
/// The options `O1..On`.
pub choice_regions: Lrc<Vec<Region<'tcx>>>,
}

View File

@ -13,10 +13,6 @@
//! defined in the `ty` module. This includes the **type context**
//! (or `tcx`), which is the central context during most of
//! compilation, containing the interners and other things.
//! - **Traits.** Trait resolution is implemented in the `traits` module.
//! - **Type inference.** The type inference code can be found in the `infer` module;
//! this code handles low-level equality and subtyping operations. The
//! type check pass in the compiler is found in the `librustc_typeck` crate.
//!
//! For more information about how rustc works, see the [rustc guide].
//!

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,71 +1,712 @@
use crate::traits;
use crate::traits::project::Normalized;
use crate::ty;
use crate::ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
use crate::ty::{self, Lift, Ty, TyCtxt};
use rustc_span::symbol::Symbol;
use smallvec::SmallVec;
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::rc::Rc;
// Structural impls for the structs in `traits`.
impl<'tcx, T: fmt::Debug> fmt::Debug for Normalized<'tcx, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Normalized({:?}, {:?})", self.value, self.obligations)
}
}
impl<'tcx, O: fmt::Debug> fmt::Debug for traits::Obligation<'tcx, O> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if ty::tls::with(|tcx| tcx.sess.verbose()) {
write!(
f,
"Obligation(predicate={:?}, cause={:?}, param_env={:?}, depth={})",
self.predicate, self.cause, self.param_env, self.recursion_depth
)
} else {
write!(f, "Obligation(predicate={:?}, depth={})", self.predicate, self.recursion_depth)
}
}
}
impl<'tcx> fmt::Debug for traits::FulfillmentError<'tcx> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "FulfillmentError({:?},{:?})", self.obligation, self.code)
}
}
impl<'tcx> fmt::Debug for traits::FulfillmentErrorCode<'tcx> {
impl<'tcx, N: fmt::Debug> fmt::Debug for traits::Vtable<'tcx, N> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
super::CodeSelectionError(ref e) => write!(f, "{:?}", e),
super::CodeProjectionError(ref e) => write!(f, "{:?}", e),
super::CodeSubtypeError(ref a, ref b) => {
write!(f, "CodeSubtypeError({:?}, {:?})", a, b)
}
super::CodeAmbiguity => write!(f, "Ambiguity"),
super::VtableImpl(ref v) => write!(f, "{:?}", v),
super::VtableAutoImpl(ref t) => write!(f, "{:?}", t),
super::VtableClosure(ref d) => write!(f, "{:?}", d),
super::VtableGenerator(ref d) => write!(f, "{:?}", d),
super::VtableFnPointer(ref d) => write!(f, "VtableFnPointer({:?})", d),
super::VtableObject(ref d) => write!(f, "{:?}", d),
super::VtableParam(ref n) => write!(f, "VtableParam({:?})", n),
super::VtableBuiltin(ref d) => write!(f, "{:?}", d),
super::VtableTraitAlias(ref d) => write!(f, "{:?}", d),
}
}
}
impl<'tcx> fmt::Debug for traits::MismatchedProjectionTypes<'tcx> {
impl<'tcx, N: fmt::Debug> fmt::Debug for traits::VtableImplData<'tcx, N> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "MismatchedProjectionTypes({:?})", self.err)
write!(
f,
"VtableImplData(impl_def_id={:?}, substs={:?}, nested={:?})",
self.impl_def_id, self.substs, self.nested
)
}
}
impl<'tcx, N: fmt::Debug> fmt::Debug for traits::VtableGeneratorData<'tcx, N> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"VtableGeneratorData(generator_def_id={:?}, substs={:?}, nested={:?})",
self.generator_def_id, self.substs, self.nested
)
}
}
impl<'tcx, N: fmt::Debug> fmt::Debug for traits::VtableClosureData<'tcx, N> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"VtableClosureData(closure_def_id={:?}, substs={:?}, nested={:?})",
self.closure_def_id, self.substs, self.nested
)
}
}
impl<N: fmt::Debug> fmt::Debug for traits::VtableBuiltinData<N> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "VtableBuiltinData(nested={:?})", self.nested)
}
}
impl<N: fmt::Debug> fmt::Debug for traits::VtableAutoImplData<N> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"VtableAutoImplData(trait_def_id={:?}, nested={:?})",
self.trait_def_id, self.nested
)
}
}
impl<'tcx, N: fmt::Debug> fmt::Debug for traits::VtableObjectData<'tcx, N> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"VtableObjectData(upcast={:?}, vtable_base={}, nested={:?})",
self.upcast_trait_ref, self.vtable_base, self.nested
)
}
}
impl<'tcx, N: fmt::Debug> fmt::Debug for traits::VtableFnPointerData<'tcx, N> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "VtableFnPointerData(fn_ty={:?}, nested={:?})", self.fn_ty, self.nested)
}
}
impl<'tcx, N: fmt::Debug> fmt::Debug for traits::VtableTraitAliasData<'tcx, N> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"VtableTraitAlias(alias_def_id={:?}, substs={:?}, nested={:?})",
self.alias_def_id, self.substs, self.nested
)
}
}
impl<'tcx> fmt::Display for traits::WhereClause<'tcx> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
use crate::traits::WhereClause::*;
// Bypass `ty::print` because it does not print out anonymous regions.
// FIXME(eddyb) implement a custom `PrettyPrinter`, or move this to `ty::print`.
fn write_region_name<'tcx>(
r: ty::Region<'tcx>,
fmt: &mut fmt::Formatter<'_>,
) -> fmt::Result {
match r {
ty::ReLateBound(index, br) => match br {
ty::BoundRegion::BrNamed(_, name) => write!(fmt, "{}", name),
ty::BoundRegion::BrAnon(var) => {
if *index == ty::INNERMOST {
write!(fmt, "'^{}", var)
} else {
write!(fmt, "'^{}_{}", index.index(), var)
}
}
_ => write!(fmt, "'_"),
},
_ => write!(fmt, "{}", r),
}
}
match self {
Implemented(trait_ref) => write!(fmt, "Implemented({})", trait_ref),
ProjectionEq(projection) => write!(fmt, "ProjectionEq({})", projection),
RegionOutlives(predicate) => {
write!(fmt, "RegionOutlives({}: ", predicate.0)?;
write_region_name(predicate.1, fmt)?;
write!(fmt, ")")
}
TypeOutlives(predicate) => {
write!(fmt, "TypeOutlives({}: ", predicate.0)?;
write_region_name(predicate.1, fmt)?;
write!(fmt, ")")
}
}
}
}
impl<'tcx> fmt::Display for traits::WellFormed<'tcx> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
use crate::traits::WellFormed::*;
match self {
Trait(trait_ref) => write!(fmt, "WellFormed({})", trait_ref),
Ty(ty) => write!(fmt, "WellFormed({})", ty),
}
}
}
impl<'tcx> fmt::Display for traits::FromEnv<'tcx> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
use crate::traits::FromEnv::*;
match self {
Trait(trait_ref) => write!(fmt, "FromEnv({})", trait_ref),
Ty(ty) => write!(fmt, "FromEnv({})", ty),
}
}
}
impl<'tcx> fmt::Display for traits::DomainGoal<'tcx> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
use crate::traits::DomainGoal::*;
match self {
Holds(wc) => write!(fmt, "{}", wc),
WellFormed(wf) => write!(fmt, "{}", wf),
FromEnv(from_env) => write!(fmt, "{}", from_env),
Normalize(projection) => {
write!(fmt, "Normalize({} -> {})", projection.projection_ty, projection.ty)
}
}
}
}
impl fmt::Display for traits::QuantifierKind {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
use crate::traits::QuantifierKind::*;
match self {
Universal => write!(fmt, "forall"),
Existential => write!(fmt, "exists"),
}
}
}
/// Collect names for regions / types bound by a quantified goal / clause.
/// This collector does not try to do anything clever like in `ty::print`, it's just used
/// for debug output in tests anyway.
struct BoundNamesCollector {
// Just sort by name because `BoundRegion::BrNamed` does not have a `BoundVar` index anyway.
regions: BTreeSet<Symbol>,
// Sort by `BoundVar` index, so usually this should be equivalent to the order given
// by the list of type parameters.
types: BTreeMap<u32, Symbol>,
binder_index: ty::DebruijnIndex,
}
impl BoundNamesCollector {
fn new() -> Self {
BoundNamesCollector {
regions: BTreeSet::new(),
types: BTreeMap::new(),
binder_index: ty::INNERMOST,
}
}
fn is_empty(&self) -> bool {
self.regions.is_empty() && self.types.is_empty()
}
fn write_names(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut start = true;
for r in &self.regions {
if !start {
write!(fmt, ", ")?;
}
start = false;
write!(fmt, "{}", r)?;
}
for (_, t) in &self.types {
if !start {
write!(fmt, ", ")?;
}
start = false;
write!(fmt, "{}", t)?;
}
Ok(())
}
}
impl<'tcx> TypeVisitor<'tcx> for BoundNamesCollector {
fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &ty::Binder<T>) -> bool {
self.binder_index.shift_in(1);
let result = t.super_visit_with(self);
self.binder_index.shift_out(1);
result
}
fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
match t.kind {
ty::Bound(debruijn, bound_ty) if debruijn == self.binder_index => {
self.types.insert(
bound_ty.var.as_u32(),
match bound_ty.kind {
ty::BoundTyKind::Param(name) => name,
ty::BoundTyKind::Anon => {
Symbol::intern(&format!("^{}", bound_ty.var.as_u32()))
}
},
);
}
_ => (),
};
t.super_visit_with(self)
}
fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
match r {
ty::ReLateBound(index, br) if *index == self.binder_index => match br {
ty::BoundRegion::BrNamed(_, name) => {
self.regions.insert(*name);
}
ty::BoundRegion::BrAnon(var) => {
self.regions.insert(Symbol::intern(&format!("'^{}", var)));
}
_ => (),
},
_ => (),
};
r.super_visit_with(self)
}
}
impl<'tcx> fmt::Display for traits::Goal<'tcx> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
use crate::traits::GoalKind::*;
match self {
Implies(hypotheses, goal) => {
write!(fmt, "if (")?;
for (index, hyp) in hypotheses.iter().enumerate() {
if index > 0 {
write!(fmt, ", ")?;
}
write!(fmt, "{}", hyp)?;
}
write!(fmt, ") {{ {} }}", goal)
}
And(goal1, goal2) => write!(fmt, "({} && {})", goal1, goal2),
Not(goal) => write!(fmt, "not {{ {} }}", goal),
DomainGoal(goal) => write!(fmt, "{}", goal),
Quantified(qkind, goal) => {
let mut collector = BoundNamesCollector::new();
goal.skip_binder().visit_with(&mut collector);
if !collector.is_empty() {
write!(fmt, "{}<", qkind)?;
collector.write_names(fmt)?;
write!(fmt, "> {{ ")?;
}
write!(fmt, "{}", goal.skip_binder())?;
if !collector.is_empty() {
write!(fmt, " }}")?;
}
Ok(())
}
Subtype(a, b) => write!(fmt, "{} <: {}", a, b),
CannotProve => write!(fmt, "CannotProve"),
}
}
}
impl<'tcx> fmt::Display for traits::ProgramClause<'tcx> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
let traits::ProgramClause { goal, hypotheses, .. } = self;
write!(fmt, "{}", goal)?;
if !hypotheses.is_empty() {
write!(fmt, " :- ")?;
for (index, condition) in hypotheses.iter().enumerate() {
if index > 0 {
write!(fmt, ", ")?;
}
write!(fmt, "{}", condition)?;
}
}
write!(fmt, ".")
}
}
impl<'tcx> fmt::Display for traits::Clause<'tcx> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
use crate::traits::Clause::*;
match self {
Implies(clause) => write!(fmt, "{}", clause),
ForAll(clause) => {
let mut collector = BoundNamesCollector::new();
clause.skip_binder().visit_with(&mut collector);
if !collector.is_empty() {
write!(fmt, "forall<")?;
collector.write_names(fmt)?;
write!(fmt, "> {{ ")?;
}
write!(fmt, "{}", clause.skip_binder())?;
if !collector.is_empty() {
write!(fmt, " }}")?;
}
Ok(())
}
}
}
}
///////////////////////////////////////////////////////////////////////////
// Lift implementations
impl<'a, 'tcx> Lift<'tcx> for traits::SelectionError<'a> {
type Lifted = traits::SelectionError<'tcx>;
fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
match *self {
super::Unimplemented => Some(super::Unimplemented),
super::OutputTypeParameterMismatch(a, b, ref err) => {
tcx.lift(&(a, b)).and_then(|(a, b)| {
tcx.lift(err).map(|err| super::OutputTypeParameterMismatch(a, b, err))
})
}
super::TraitNotObjectSafe(def_id) => Some(super::TraitNotObjectSafe(def_id)),
super::ConstEvalFailure(err) => Some(super::ConstEvalFailure(err)),
super::Overflow => Some(super::Overflow),
}
}
}
impl<'a, 'tcx> Lift<'tcx> for traits::ObligationCauseCode<'a> {
type Lifted = traits::ObligationCauseCode<'tcx>;
fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
match *self {
super::ReturnNoExpression => Some(super::ReturnNoExpression),
super::MiscObligation => Some(super::MiscObligation),
super::SliceOrArrayElem => Some(super::SliceOrArrayElem),
super::TupleElem => Some(super::TupleElem),
super::ProjectionWf(proj) => tcx.lift(&proj).map(super::ProjectionWf),
super::ItemObligation(def_id) => Some(super::ItemObligation(def_id)),
super::BindingObligation(def_id, span) => Some(super::BindingObligation(def_id, span)),
super::ReferenceOutlivesReferent(ty) => {
tcx.lift(&ty).map(super::ReferenceOutlivesReferent)
}
super::ObjectTypeBound(ty, r) => tcx
.lift(&ty)
.and_then(|ty| tcx.lift(&r).and_then(|r| Some(super::ObjectTypeBound(ty, r)))),
super::ObjectCastObligation(ty) => tcx.lift(&ty).map(super::ObjectCastObligation),
super::Coercion { source, target } => {
Some(super::Coercion { source: tcx.lift(&source)?, target: tcx.lift(&target)? })
}
super::AssignmentLhsSized => Some(super::AssignmentLhsSized),
super::TupleInitializerSized => Some(super::TupleInitializerSized),
super::StructInitializerSized => Some(super::StructInitializerSized),
super::VariableType(id) => Some(super::VariableType(id)),
super::ReturnValue(id) => Some(super::ReturnValue(id)),
super::ReturnType => Some(super::ReturnType),
super::SizedArgumentType => Some(super::SizedArgumentType),
super::SizedReturnType => Some(super::SizedReturnType),
super::SizedYieldType => Some(super::SizedYieldType),
super::RepeatVec(suggest_flag) => Some(super::RepeatVec(suggest_flag)),
super::FieldSized { adt_kind, last } => Some(super::FieldSized { adt_kind, last }),
super::ConstSized => Some(super::ConstSized),
super::ConstPatternStructural => Some(super::ConstPatternStructural),
super::SharedStatic => Some(super::SharedStatic),
super::BuiltinDerivedObligation(ref cause) => {
tcx.lift(cause).map(super::BuiltinDerivedObligation)
}
super::ImplDerivedObligation(ref cause) => {
tcx.lift(cause).map(super::ImplDerivedObligation)
}
super::CompareImplMethodObligation {
item_name,
impl_item_def_id,
trait_item_def_id,
} => Some(super::CompareImplMethodObligation {
item_name,
impl_item_def_id,
trait_item_def_id,
}),
super::CompareImplTypeObligation { item_name, impl_item_def_id, trait_item_def_id } => {
Some(super::CompareImplTypeObligation {
item_name,
impl_item_def_id,
trait_item_def_id,
})
}
super::ExprAssignable => Some(super::ExprAssignable),
super::MatchExpressionArm(box super::MatchExpressionArmCause {
arm_span,
source,
ref prior_arms,
last_ty,
scrut_hir_id,
}) => tcx.lift(&last_ty).map(|last_ty| {
super::MatchExpressionArm(box super::MatchExpressionArmCause {
arm_span,
source,
prior_arms: prior_arms.clone(),
last_ty,
scrut_hir_id,
})
}),
super::Pattern { span, root_ty, origin_expr } => {
tcx.lift(&root_ty).map(|root_ty| super::Pattern { span, root_ty, origin_expr })
}
super::IfExpression(box super::IfExpressionCause { then, outer, semicolon }) => {
Some(super::IfExpression(box super::IfExpressionCause { then, outer, semicolon }))
}
super::IfExpressionWithNoElse => Some(super::IfExpressionWithNoElse),
super::MainFunctionType => Some(super::MainFunctionType),
super::StartFunctionType => Some(super::StartFunctionType),
super::IntrinsicType => Some(super::IntrinsicType),
super::MethodReceiver => Some(super::MethodReceiver),
super::BlockTailExpression(id) => Some(super::BlockTailExpression(id)),
super::TrivialBound => Some(super::TrivialBound),
super::AssocTypeBound(ref data) => Some(super::AssocTypeBound(data.clone())),
}
}
}
impl<'a, 'tcx> Lift<'tcx> for traits::DerivedObligationCause<'a> {
type Lifted = traits::DerivedObligationCause<'tcx>;
fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
tcx.lift(&self.parent_trait_ref).and_then(|trait_ref| {
tcx.lift(&*self.parent_code).map(|code| traits::DerivedObligationCause {
parent_trait_ref: trait_ref,
parent_code: Rc::new(code),
})
})
}
}
impl<'a, 'tcx> Lift<'tcx> for traits::ObligationCause<'a> {
type Lifted = traits::ObligationCause<'tcx>;
fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
tcx.lift(&self.code).map(|code| traits::ObligationCause {
span: self.span,
body_id: self.body_id,
code,
})
}
}
// For codegen only.
impl<'a, 'tcx> Lift<'tcx> for traits::Vtable<'a, ()> {
type Lifted = traits::Vtable<'tcx, ()>;
fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
match self.clone() {
traits::VtableImpl(traits::VtableImplData { impl_def_id, substs, nested }) => {
tcx.lift(&substs).map(|substs| {
traits::VtableImpl(traits::VtableImplData { impl_def_id, substs, nested })
})
}
traits::VtableAutoImpl(t) => Some(traits::VtableAutoImpl(t)),
traits::VtableGenerator(traits::VtableGeneratorData {
generator_def_id,
substs,
nested,
}) => tcx.lift(&substs).map(|substs| {
traits::VtableGenerator(traits::VtableGeneratorData {
generator_def_id: generator_def_id,
substs: substs,
nested: nested,
})
}),
traits::VtableClosure(traits::VtableClosureData { closure_def_id, substs, nested }) => {
tcx.lift(&substs).map(|substs| {
traits::VtableClosure(traits::VtableClosureData {
closure_def_id,
substs,
nested,
})
})
}
traits::VtableFnPointer(traits::VtableFnPointerData { fn_ty, nested }) => {
tcx.lift(&fn_ty).map(|fn_ty| {
traits::VtableFnPointer(traits::VtableFnPointerData { fn_ty, nested })
})
}
traits::VtableParam(n) => Some(traits::VtableParam(n)),
traits::VtableBuiltin(n) => Some(traits::VtableBuiltin(n)),
traits::VtableObject(traits::VtableObjectData {
upcast_trait_ref,
vtable_base,
nested,
}) => tcx.lift(&upcast_trait_ref).map(|trait_ref| {
traits::VtableObject(traits::VtableObjectData {
upcast_trait_ref: trait_ref,
vtable_base,
nested,
})
}),
traits::VtableTraitAlias(traits::VtableTraitAliasData {
alias_def_id,
substs,
nested,
}) => tcx.lift(&substs).map(|substs| {
traits::VtableTraitAlias(traits::VtableTraitAliasData {
alias_def_id,
substs,
nested,
})
}),
}
}
}
impl<'a, 'tcx> Lift<'tcx> for traits::Environment<'a> {
type Lifted = traits::Environment<'tcx>;
fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
tcx.lift(&self.clauses).map(|clauses| traits::Environment { clauses })
}
}
impl<'a, 'tcx, G: Lift<'tcx>> Lift<'tcx> for traits::InEnvironment<'a, G> {
type Lifted = traits::InEnvironment<'tcx, G::Lifted>;
fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
tcx.lift(&self.environment).and_then(|environment| {
tcx.lift(&self.goal).map(|goal| traits::InEnvironment { environment, goal })
})
}
}
impl<'tcx, C> Lift<'tcx> for chalk_engine::ExClause<C>
where
C: chalk_engine::context::Context + Clone,
C: traits::ChalkContextLift<'tcx>,
{
type Lifted = C::LiftedExClause;
fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
<C as traits::ChalkContextLift>::lift_ex_clause_to_tcx(self, tcx)
}
}
impl<'tcx, C> Lift<'tcx> for chalk_engine::DelayedLiteral<C>
where
C: chalk_engine::context::Context + Clone,
C: traits::ChalkContextLift<'tcx>,
{
type Lifted = C::LiftedDelayedLiteral;
fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
<C as traits::ChalkContextLift>::lift_delayed_literal_to_tcx(self, tcx)
}
}
impl<'tcx, C> Lift<'tcx> for chalk_engine::Literal<C>
where
C: chalk_engine::context::Context + Clone,
C: traits::ChalkContextLift<'tcx>,
{
type Lifted = C::LiftedLiteral;
fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
<C as traits::ChalkContextLift>::lift_literal_to_tcx(self, tcx)
}
}
///////////////////////////////////////////////////////////////////////////
// TypeFoldable implementations.
impl<'tcx, O: TypeFoldable<'tcx>> TypeFoldable<'tcx> for traits::Obligation<'tcx, O> {
CloneTypeFoldableAndLiftImpls! {
traits::QuantifierKind,
}
impl<'tcx> TypeFoldable<'tcx> for &'tcx ty::List<traits::Goal<'tcx>> {
fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
traits::Obligation {
cause: self.cause.clone(),
recursion_depth: self.recursion_depth,
predicate: self.predicate.fold_with(folder),
param_env: self.param_env.fold_with(folder),
}
let v = self.iter().map(|t| t.fold_with(folder)).collect::<SmallVec<[_; 8]>>();
folder.tcx().intern_goals(&v)
}
fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
self.predicate.visit_with(visitor)
self.iter().any(|t| t.visit_with(visitor))
}
}
impl<'tcx> TypeFoldable<'tcx> for traits::Goal<'tcx> {
fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
let v = (**self).fold_with(folder);
folder.tcx().mk_goal(v)
}
fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
(**self).visit_with(visitor)
}
}
CloneTypeFoldableAndLiftImpls! {
traits::ProgramClauseCategory,
}
impl<'tcx> TypeFoldable<'tcx> for traits::Clauses<'tcx> {
fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
let v = self.iter().map(|t| t.fold_with(folder)).collect::<SmallVec<[_; 8]>>();
folder.tcx().intern_clauses(&v)
}
fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
self.iter().any(|t| t.visit_with(visitor))
}
}
impl<'tcx, C> TypeFoldable<'tcx> for chalk_engine::ExClause<C>
where
C: traits::ExClauseFold<'tcx>,
C::Substitution: Clone,
C::RegionConstraint: Clone,
{
fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
<C as traits::ExClauseFold>::fold_ex_clause_with(self, folder)
}
fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
<C as traits::ExClauseFold>::visit_ex_clause_with(self, visitor)
}
}
EnumTypeFoldableImpl! {
impl<'tcx, C> TypeFoldable<'tcx> for chalk_engine::DelayedLiteral<C> {
(chalk_engine::DelayedLiteral::CannotProve)(a),
(chalk_engine::DelayedLiteral::Negative)(a),
(chalk_engine::DelayedLiteral::Positive)(a, b),
} where
C: chalk_engine::context::Context<CanonicalConstrainedSubst: TypeFoldable<'tcx>> + Clone,
}
EnumTypeFoldableImpl! {
impl<'tcx, C> TypeFoldable<'tcx> for chalk_engine::Literal<C> {
(chalk_engine::Literal::Negative)(a),
(chalk_engine::Literal::Positive)(a),
} where
C: chalk_engine::context::Context<GoalInEnvironment: Clone + TypeFoldable<'tcx>> + Clone,
}
CloneTypeFoldableAndLiftImpls! {
chalk_engine::TableIndex,
}

View File

@ -1,736 +0,0 @@
//! Trait Resolution. See the [rustc guide] for more information on how this works.
//!
//! [rustc guide]: https://rust-lang.github.io/rustc-guide/traits/resolution.html
pub mod query;
pub mod select;
pub mod specialization_graph;
mod structural_impls;
use crate::mir::interpret::ErrorHandled;
use crate::ty::fold::{TypeFolder, TypeVisitor};
use crate::ty::subst::SubstsRef;
use crate::ty::{self, AdtKind, List, Ty, TyCtxt};
use rustc_hir as hir;
use rustc_hir::def_id::DefId;
use rustc_span::{Span, DUMMY_SP};
use syntax::ast;
use std::fmt::Debug;
use std::rc::Rc;
pub use self::select::{EvaluationCache, EvaluationResult, OverflowError, SelectionCache};
pub use self::ObligationCauseCode::*;
pub use self::SelectionError::*;
pub use self::Vtable::*;
/// Depending on the stage of compilation, we want projection to be
/// more or less conservative.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, HashStable)]
pub enum Reveal {
/// At type-checking time, we refuse to project any associated
/// type that is marked `default`. Non-`default` ("final") types
/// are always projected. This is necessary in general for
/// soundness of specialization. However, we *could* allow
/// projections in fully-monomorphic cases. We choose not to,
/// because we prefer for `default type` to force the type
/// definition to be treated abstractly by any consumers of the
/// impl. Concretely, that means that the following example will
/// fail to compile:
///
/// ```
/// trait Assoc {
/// type Output;
/// }
///
/// impl<T> Assoc for T {
/// default type Output = bool;
/// }
///
/// fn main() {
/// let <() as Assoc>::Output = true;
/// }
/// ```
UserFacing,
/// At codegen time, all monomorphic projections will succeed.
/// Also, `impl Trait` is normalized to the concrete type,
/// which has to be already collected by type-checking.
///
/// NOTE: as `impl Trait`'s concrete type should *never*
/// be observable directly by the user, `Reveal::All`
/// should not be used by checks which may expose
/// type equality or type contents to the user.
/// There are some exceptions, e.g., around OIBITS and
/// transmute-checking, which expose some details, but
/// not the whole concrete type of the `impl Trait`.
All,
}
/// The reason why we incurred this obligation; used for error reporting.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct ObligationCause<'tcx> {
pub span: Span,
/// The ID of the fn body that triggered this obligation. This is
/// used for region obligations to determine the precise
/// environment in which the region obligation should be evaluated
/// (in particular, closures can add new assumptions). See the
/// field `region_obligations` of the `FulfillmentContext` for more
/// information.
pub body_id: hir::HirId,
pub code: ObligationCauseCode<'tcx>,
}
impl<'tcx> ObligationCause<'tcx> {
#[inline]
pub fn new(
span: Span,
body_id: hir::HirId,
code: ObligationCauseCode<'tcx>,
) -> ObligationCause<'tcx> {
ObligationCause { span, body_id, code }
}
pub fn misc(span: Span, body_id: hir::HirId) -> ObligationCause<'tcx> {
ObligationCause { span, body_id, code: MiscObligation }
}
pub fn dummy() -> ObligationCause<'tcx> {
ObligationCause { span: DUMMY_SP, body_id: hir::CRATE_HIR_ID, code: MiscObligation }
}
pub fn span(&self, tcx: TyCtxt<'tcx>) -> Span {
match self.code {
ObligationCauseCode::CompareImplMethodObligation { .. }
| ObligationCauseCode::MainFunctionType
| ObligationCauseCode::StartFunctionType => tcx.sess.source_map().def_span(self.span),
ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
arm_span,
..
}) => arm_span,
_ => self.span,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum ObligationCauseCode<'tcx> {
/// Not well classified or should be obvious from the span.
MiscObligation,
/// A slice or array is WF only if `T: Sized`.
SliceOrArrayElem,
/// A tuple is WF only if its middle elements are `Sized`.
TupleElem,
/// This is the trait reference from the given projection.
ProjectionWf(ty::ProjectionTy<'tcx>),
/// In an impl of trait `X` for type `Y`, type `Y` must
/// also implement all supertraits of `X`.
ItemObligation(DefId),
/// Like `ItemObligation`, but with extra detail on the source of the obligation.
BindingObligation(DefId, Span),
/// A type like `&'a T` is WF only if `T: 'a`.
ReferenceOutlivesReferent(Ty<'tcx>),
/// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
ObjectTypeBound(Ty<'tcx>, ty::Region<'tcx>),
/// Obligation incurred due to an object cast.
ObjectCastObligation(/* Object type */ Ty<'tcx>),
/// Obligation incurred due to a coercion.
Coercion {
source: Ty<'tcx>,
target: Ty<'tcx>,
},
/// Various cases where expressions must be `Sized` / `Copy` / etc.
/// `L = X` implies that `L` is `Sized`.
AssignmentLhsSized,
/// `(x1, .., xn)` must be `Sized`.
TupleInitializerSized,
/// `S { ... }` must be `Sized`.
StructInitializerSized,
/// Type of each variable must be `Sized`.
VariableType(hir::HirId),
/// Argument type must be `Sized`.
SizedArgumentType,
/// Return type must be `Sized`.
SizedReturnType,
/// Yield type must be `Sized`.
SizedYieldType,
/// `[T, ..n]` implies that `T` must be `Copy`.
/// If `true`, suggest `const_in_array_repeat_expressions` feature flag.
RepeatVec(bool),
/// Types of fields (other than the last, except for packed structs) in a struct must be sized.
FieldSized {
adt_kind: AdtKind,
last: bool,
},
/// Constant expressions must be sized.
ConstSized,
/// `static` items must have `Sync` type.
SharedStatic,
BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
ImplDerivedObligation(DerivedObligationCause<'tcx>),
/// Error derived when matching traits/impls; see ObligationCause for more details
CompareImplMethodObligation {
item_name: ast::Name,
impl_item_def_id: DefId,
trait_item_def_id: DefId,
},
/// Error derived when matching traits/impls; see ObligationCause for more details
CompareImplTypeObligation {
item_name: ast::Name,
impl_item_def_id: DefId,
trait_item_def_id: DefId,
},
/// Checking that this expression can be assigned where it needs to be
// FIXME(eddyb) #11161 is the original Expr required?
ExprAssignable,
/// Computing common supertype in the arms of a match expression
MatchExpressionArm(Box<MatchExpressionArmCause<'tcx>>),
/// Type error arising from type checking a pattern against an expected type.
Pattern {
/// The span of the scrutinee or type expression which caused the `root_ty` type.
span: Option<Span>,
/// The root expected type induced by a scrutinee or type expression.
root_ty: Ty<'tcx>,
/// Whether the `Span` came from an expression or a type expression.
origin_expr: bool,
},
/// Constants in patterns must have `Structural` type.
ConstPatternStructural,
/// Computing common supertype in an if expression
IfExpression(Box<IfExpressionCause>),
/// Computing common supertype of an if expression with no else counter-part
IfExpressionWithNoElse,
/// `main` has wrong type
MainFunctionType,
/// `start` has wrong type
StartFunctionType,
/// Intrinsic has wrong type
IntrinsicType,
/// Method receiver
MethodReceiver,
/// `return` with no expression
ReturnNoExpression,
/// `return` with an expression
ReturnValue(hir::HirId),
/// Return type of this function
ReturnType,
/// Block implicit return
BlockTailExpression(hir::HirId),
/// #[feature(trivial_bounds)] is not enabled
TrivialBound,
AssocTypeBound(Box<AssocTypeBoundData>),
}
impl ObligationCauseCode<'_> {
// Return the base obligation, ignoring derived obligations.
pub fn peel_derives(&self) -> &Self {
let mut base_cause = self;
while let BuiltinDerivedObligation(cause) | ImplDerivedObligation(cause) = base_cause {
base_cause = &cause.parent_code;
}
base_cause
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct AssocTypeBoundData {
pub impl_span: Option<Span>,
pub original: Span,
pub bounds: Vec<Span>,
}
// `ObligationCauseCode` is used a lot. Make sure it doesn't unintentionally get bigger.
#[cfg(target_arch = "x86_64")]
static_assert_size!(ObligationCauseCode<'_>, 32);
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct MatchExpressionArmCause<'tcx> {
pub arm_span: Span,
pub source: hir::MatchSource,
pub prior_arms: Vec<Span>,
pub last_ty: Ty<'tcx>,
pub scrut_hir_id: hir::HirId,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct IfExpressionCause {
pub then: Span,
pub outer: Option<Span>,
pub semicolon: Option<Span>,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct DerivedObligationCause<'tcx> {
/// The trait reference of the parent obligation that led to the
/// current obligation. Note that only trait obligations lead to
/// derived obligations, so we just store the trait reference here
/// directly.
pub parent_trait_ref: ty::PolyTraitRef<'tcx>,
/// The parent trait had this cause.
pub parent_code: Rc<ObligationCauseCode<'tcx>>,
}
/// The following types:
/// * `WhereClause`,
/// * `WellFormed`,
/// * `FromEnv`,
/// * `DomainGoal`,
/// * `Goal`,
/// * `Clause`,
/// * `Environment`,
/// * `InEnvironment`,
/// are used for representing the trait system in the form of
/// logic programming clauses. They are part of the interface
/// for the chalk SLG solver.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
pub enum WhereClause<'tcx> {
Implemented(ty::TraitPredicate<'tcx>),
ProjectionEq(ty::ProjectionPredicate<'tcx>),
RegionOutlives(ty::RegionOutlivesPredicate<'tcx>),
TypeOutlives(ty::TypeOutlivesPredicate<'tcx>),
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
pub enum WellFormed<'tcx> {
Trait(ty::TraitPredicate<'tcx>),
Ty(Ty<'tcx>),
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
pub enum FromEnv<'tcx> {
Trait(ty::TraitPredicate<'tcx>),
Ty(Ty<'tcx>),
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
pub enum DomainGoal<'tcx> {
Holds(WhereClause<'tcx>),
WellFormed(WellFormed<'tcx>),
FromEnv(FromEnv<'tcx>),
Normalize(ty::ProjectionPredicate<'tcx>),
}
pub type PolyDomainGoal<'tcx> = ty::Binder<DomainGoal<'tcx>>;
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
pub enum QuantifierKind {
Universal,
Existential,
}
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
pub enum GoalKind<'tcx> {
Implies(Clauses<'tcx>, Goal<'tcx>),
And(Goal<'tcx>, Goal<'tcx>),
Not(Goal<'tcx>),
DomainGoal(DomainGoal<'tcx>),
Quantified(QuantifierKind, ty::Binder<Goal<'tcx>>),
Subtype(Ty<'tcx>, Ty<'tcx>),
CannotProve,
}
pub type Goal<'tcx> = &'tcx GoalKind<'tcx>;
pub type Goals<'tcx> = &'tcx List<Goal<'tcx>>;
impl<'tcx> DomainGoal<'tcx> {
pub fn into_goal(self) -> GoalKind<'tcx> {
GoalKind::DomainGoal(self)
}
pub fn into_program_clause(self) -> ProgramClause<'tcx> {
ProgramClause {
goal: self,
hypotheses: ty::List::empty(),
category: ProgramClauseCategory::Other,
}
}
}
impl<'tcx> GoalKind<'tcx> {
pub fn from_poly_domain_goal(
domain_goal: PolyDomainGoal<'tcx>,
tcx: TyCtxt<'tcx>,
) -> GoalKind<'tcx> {
match domain_goal.no_bound_vars() {
Some(p) => p.into_goal(),
None => GoalKind::Quantified(
QuantifierKind::Universal,
domain_goal.map_bound(|p| tcx.mk_goal(p.into_goal())),
),
}
}
}
/// This matches the definition from Page 7 of "A Proof Procedure for the Logic of Hereditary
/// Harrop Formulas".
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
pub enum Clause<'tcx> {
Implies(ProgramClause<'tcx>),
ForAll(ty::Binder<ProgramClause<'tcx>>),
}
impl Clause<'tcx> {
pub fn category(self) -> ProgramClauseCategory {
match self {
Clause::Implies(clause) => clause.category,
Clause::ForAll(clause) => clause.skip_binder().category,
}
}
}
/// Multiple clauses.
pub type Clauses<'tcx> = &'tcx List<Clause<'tcx>>;
/// A "program clause" has the form `D :- G1, ..., Gn`. It is saying
/// that the domain goal `D` is true if `G1...Gn` are provable. This
/// is equivalent to the implication `G1..Gn => D`; we usually write
/// it with the reverse implication operator `:-` to emphasize the way
/// that programs are actually solved (via backchaining, which starts
/// with the goal to solve and proceeds from there).
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
pub struct ProgramClause<'tcx> {
/// This goal will be considered true ...
pub goal: DomainGoal<'tcx>,
/// ... if we can prove these hypotheses (there may be no hypotheses at all):
pub hypotheses: Goals<'tcx>,
/// Useful for filtering clauses.
pub category: ProgramClauseCategory,
}
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
pub enum ProgramClauseCategory {
ImpliedBound,
WellFormed,
Other,
}
/// A set of clauses that we assume to be true.
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
pub struct Environment<'tcx> {
pub clauses: Clauses<'tcx>,
}
impl Environment<'tcx> {
pub fn with<G>(self, goal: G) -> InEnvironment<'tcx, G> {
InEnvironment { environment: self, goal }
}
}
/// Something (usually a goal), along with an environment.
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
pub struct InEnvironment<'tcx, G> {
pub environment: Environment<'tcx>,
pub goal: G,
}
#[derive(Clone, Debug, TypeFoldable)]
pub enum SelectionError<'tcx> {
Unimplemented,
OutputTypeParameterMismatch(
ty::PolyTraitRef<'tcx>,
ty::PolyTraitRef<'tcx>,
ty::error::TypeError<'tcx>,
),
TraitNotObjectSafe(DefId),
ConstEvalFailure(ErrorHandled),
Overflow,
}
/// When performing resolution, it is typically the case that there
/// can be one of three outcomes:
///
/// - `Ok(Some(r))`: success occurred with result `r`
/// - `Ok(None)`: could not definitely determine anything, usually due
/// to inconclusive type inference.
/// - `Err(e)`: error `e` occurred
pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
/// Given the successful resolution of an obligation, the `Vtable`
/// indicates where the vtable comes from. Note that while we call this
/// a "vtable", it does not necessarily indicate dynamic dispatch at
/// runtime. `Vtable` instances just tell the compiler where to find
/// methods, but in generic code those methods are typically statically
/// dispatched -- only when an object is constructed is a `Vtable`
/// instance reified into an actual vtable.
///
/// For example, the vtable may be tied to a specific impl (case A),
/// or it may be relative to some bound that is in scope (case B).
///
/// ```
/// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
/// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
/// impl Clone for int { ... } // Impl_3
///
/// fn foo<T:Clone>(concrete: Option<Box<int>>,
/// param: T,
/// mixed: Option<T>) {
///
/// // Case A: Vtable points at a specific impl. Only possible when
/// // type is concretely known. If the impl itself has bounded
/// // type parameters, Vtable will carry resolutions for those as well:
/// concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
///
/// // Case B: Vtable must be provided by caller. This applies when
/// // type is a type parameter.
/// param.clone(); // VtableParam
///
/// // Case C: A mix of cases A and B.
/// mixed.clone(); // Vtable(Impl_1, [VtableParam])
/// }
/// ```
///
/// ### The type parameter `N`
///
/// See explanation on `VtableImplData`.
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
pub enum Vtable<'tcx, N> {
/// Vtable identifying a particular impl.
VtableImpl(VtableImplData<'tcx, N>),
/// Vtable for auto trait implementations.
/// This carries the information and nested obligations with regards
/// to an auto implementation for a trait `Trait`. The nested obligations
/// ensure the trait implementation holds for all the constituent types.
VtableAutoImpl(VtableAutoImplData<N>),
/// Successful resolution to an obligation provided by the caller
/// for some type parameter. The `Vec<N>` represents the
/// obligations incurred from normalizing the where-clause (if
/// any).
VtableParam(Vec<N>),
/// Virtual calls through an object.
VtableObject(VtableObjectData<'tcx, N>),
/// Successful resolution for a builtin trait.
VtableBuiltin(VtableBuiltinData<N>),
/// Vtable automatically generated for a closure. The `DefId` is the ID
/// of the closure expression. This is a `VtableImpl` in spirit, but the
/// impl is generated by the compiler and does not appear in the source.
VtableClosure(VtableClosureData<'tcx, N>),
/// Same as above, but for a function pointer type with the given signature.
VtableFnPointer(VtableFnPointerData<'tcx, N>),
/// Vtable automatically generated for a generator.
VtableGenerator(VtableGeneratorData<'tcx, N>),
/// Vtable for a trait alias.
VtableTraitAlias(VtableTraitAliasData<'tcx, N>),
}
impl<'tcx, N> Vtable<'tcx, N> {
pub fn nested_obligations(self) -> Vec<N> {
match self {
VtableImpl(i) => i.nested,
VtableParam(n) => n,
VtableBuiltin(i) => i.nested,
VtableAutoImpl(d) => d.nested,
VtableClosure(c) => c.nested,
VtableGenerator(c) => c.nested,
VtableObject(d) => d.nested,
VtableFnPointer(d) => d.nested,
VtableTraitAlias(d) => d.nested,
}
}
pub fn map<M, F>(self, f: F) -> Vtable<'tcx, M>
where
F: FnMut(N) -> M,
{
match self {
VtableImpl(i) => VtableImpl(VtableImplData {
impl_def_id: i.impl_def_id,
substs: i.substs,
nested: i.nested.into_iter().map(f).collect(),
}),
VtableParam(n) => VtableParam(n.into_iter().map(f).collect()),
VtableBuiltin(i) => {
VtableBuiltin(VtableBuiltinData { nested: i.nested.into_iter().map(f).collect() })
}
VtableObject(o) => VtableObject(VtableObjectData {
upcast_trait_ref: o.upcast_trait_ref,
vtable_base: o.vtable_base,
nested: o.nested.into_iter().map(f).collect(),
}),
VtableAutoImpl(d) => VtableAutoImpl(VtableAutoImplData {
trait_def_id: d.trait_def_id,
nested: d.nested.into_iter().map(f).collect(),
}),
VtableClosure(c) => VtableClosure(VtableClosureData {
closure_def_id: c.closure_def_id,
substs: c.substs,
nested: c.nested.into_iter().map(f).collect(),
}),
VtableGenerator(c) => VtableGenerator(VtableGeneratorData {
generator_def_id: c.generator_def_id,
substs: c.substs,
nested: c.nested.into_iter().map(f).collect(),
}),
VtableFnPointer(p) => VtableFnPointer(VtableFnPointerData {
fn_ty: p.fn_ty,
nested: p.nested.into_iter().map(f).collect(),
}),
VtableTraitAlias(d) => VtableTraitAlias(VtableTraitAliasData {
alias_def_id: d.alias_def_id,
substs: d.substs,
nested: d.nested.into_iter().map(f).collect(),
}),
}
}
}
/// Identifies a particular impl in the source, along with a set of
/// substitutions from the impl's type/lifetime parameters. The
/// `nested` vector corresponds to the nested obligations attached to
/// the impl's type parameters.
///
/// The type parameter `N` indicates the type used for "nested
/// obligations" that are required by the impl. During type-check, this
/// is `Obligation`, as one might expect. During codegen, however, this
/// is `()`, because codegen only requires a shallow resolution of an
/// impl, and nested obligations are satisfied later.
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
pub struct VtableImplData<'tcx, N> {
pub impl_def_id: DefId,
pub substs: SubstsRef<'tcx>,
pub nested: Vec<N>,
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
pub struct VtableGeneratorData<'tcx, N> {
pub generator_def_id: DefId,
pub substs: SubstsRef<'tcx>,
/// Nested obligations. This can be non-empty if the generator
/// signature contains associated types.
pub nested: Vec<N>,
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
pub struct VtableClosureData<'tcx, N> {
pub closure_def_id: DefId,
pub substs: SubstsRef<'tcx>,
/// Nested obligations. This can be non-empty if the closure
/// signature contains associated types.
pub nested: Vec<N>,
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
pub struct VtableAutoImplData<N> {
pub trait_def_id: DefId,
pub nested: Vec<N>,
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
pub struct VtableBuiltinData<N> {
pub nested: Vec<N>,
}
/// A vtable for some object-safe trait `Foo` automatically derived
/// for the object type `Foo`.
#[derive(PartialEq, Eq, Clone, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
pub struct VtableObjectData<'tcx, N> {
/// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
/// The vtable is formed by concatenating together the method lists of
/// the base object trait and all supertraits; this is the start of
/// `upcast_trait_ref`'s methods in that vtable.
pub vtable_base: usize,
pub nested: Vec<N>,
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
pub struct VtableFnPointerData<'tcx, N> {
pub fn_ty: Ty<'tcx>,
pub nested: Vec<N>,
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
pub struct VtableTraitAliasData<'tcx, N> {
pub alias_def_id: DefId,
pub substs: SubstsRef<'tcx>,
pub nested: Vec<N>,
}
pub trait ExClauseFold<'tcx>
where
Self: chalk_engine::context::Context + Clone,
{
fn fold_ex_clause_with<F: TypeFolder<'tcx>>(
ex_clause: &chalk_engine::ExClause<Self>,
folder: &mut F,
) -> chalk_engine::ExClause<Self>;
fn visit_ex_clause_with<V: TypeVisitor<'tcx>>(
ex_clause: &chalk_engine::ExClause<Self>,
visitor: &mut V,
) -> bool;
}
pub trait ChalkContextLift<'tcx>
where
Self: chalk_engine::context::Context + Clone,
{
type LiftedExClause: Debug + 'tcx;
type LiftedDelayedLiteral: Debug + 'tcx;
type LiftedLiteral: Debug + 'tcx;
fn lift_ex_clause_to_tcx(
ex_clause: &chalk_engine::ExClause<Self>,
tcx: TyCtxt<'tcx>,
) -> Option<Self::LiftedExClause>;
fn lift_delayed_literal_to_tcx(
ex_clause: &chalk_engine::DelayedLiteral<Self>,
tcx: TyCtxt<'tcx>,
) -> Option<Self::LiftedDelayedLiteral>;
fn lift_literal_to_tcx(
ex_clause: &chalk_engine::Literal<Self>,
tcx: TyCtxt<'tcx>,
) -> Option<Self::LiftedLiteral>;
}

View File

@ -1,290 +0,0 @@
//! Candidate selection. See the [rustc guide] for more information on how this works.
//!
//! [rustc guide]: https://rust-lang.github.io/rustc-guide/traits/resolution.html#selection
use self::EvaluationResult::*;
use super::{SelectionError, SelectionResult};
use crate::dep_graph::DepNodeIndex;
use crate::ty::{self, TyCtxt};
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::sync::Lock;
use rustc_hir::def_id::DefId;
#[derive(Clone, Default)]
pub struct SelectionCache<'tcx> {
pub hashmap: Lock<
FxHashMap<
ty::ParamEnvAnd<'tcx, ty::TraitRef<'tcx>>,
WithDepNode<SelectionResult<'tcx, SelectionCandidate<'tcx>>>,
>,
>,
}
impl<'tcx> SelectionCache<'tcx> {
/// Actually frees the underlying memory in contrast to what stdlib containers do on `clear`
pub fn clear(&self) {
*self.hashmap.borrow_mut() = Default::default();
}
}
/// The selection process begins by considering all impls, where
/// clauses, and so forth that might resolve an obligation. Sometimes
/// we'll be able to say definitively that (e.g.) an impl does not
/// apply to the obligation: perhaps it is defined for `usize` but the
/// obligation is for `int`. In that case, we drop the impl out of the
/// list. But the other cases are considered *candidates*.
///
/// For selection to succeed, there must be exactly one matching
/// candidate. If the obligation is fully known, this is guaranteed
/// by coherence. However, if the obligation contains type parameters
/// or variables, there may be multiple such impls.
///
/// It is not a real problem if multiple matching impls exist because
/// of type variables - it just means the obligation isn't sufficiently
/// elaborated. In that case we report an ambiguity, and the caller can
/// try again after more type information has been gathered or report a
/// "type annotations needed" error.
///
/// However, with type parameters, this can be a real problem - type
/// parameters don't unify with regular types, but they *can* unify
/// with variables from blanket impls, and (unless we know its bounds
/// will always be satisfied) picking the blanket impl will be wrong
/// for at least *some* substitutions. To make this concrete, if we have
///
/// trait AsDebug { type Out : fmt::Debug; fn debug(self) -> Self::Out; }
/// impl<T: fmt::Debug> AsDebug for T {
/// type Out = T;
/// fn debug(self) -> fmt::Debug { self }
/// }
/// fn foo<T: AsDebug>(t: T) { println!("{:?}", <T as AsDebug>::debug(t)); }
///
/// we can't just use the impl to resolve the `<T as AsDebug>` obligation
/// -- a type from another crate (that doesn't implement `fmt::Debug`) could
/// implement `AsDebug`.
///
/// Because where-clauses match the type exactly, multiple clauses can
/// only match if there are unresolved variables, and we can mostly just
/// report this ambiguity in that case. This is still a problem - we can't
/// *do anything* with ambiguities that involve only regions. This is issue
/// #21974.
///
/// If a single where-clause matches and there are no inference
/// variables left, then it definitely matches and we can just select
/// it.
///
/// In fact, we even select the where-clause when the obligation contains
/// inference variables. The can lead to inference making "leaps of logic",
/// for example in this situation:
///
/// pub trait Foo<T> { fn foo(&self) -> T; }
/// impl<T> Foo<()> for T { fn foo(&self) { } }
/// impl Foo<bool> for bool { fn foo(&self) -> bool { *self } }
///
/// pub fn foo<T>(t: T) where T: Foo<bool> {
/// println!("{:?}", <T as Foo<_>>::foo(&t));
/// }
/// fn main() { foo(false); }
///
/// Here the obligation `<T as Foo<$0>>` can be matched by both the blanket
/// impl and the where-clause. We select the where-clause and unify `$0=bool`,
/// so the program prints "false". However, if the where-clause is omitted,
/// the blanket impl is selected, we unify `$0=()`, and the program prints
/// "()".
///
/// Exactly the same issues apply to projection and object candidates, except
/// that we can have both a projection candidate and a where-clause candidate
/// for the same obligation. In that case either would do (except that
/// different "leaps of logic" would occur if inference variables are
/// present), and we just pick the where-clause. This is, for example,
/// required for associated types to work in default impls, as the bounds
/// are visible both as projection bounds and as where-clauses from the
/// parameter environment.
#[derive(PartialEq, Eq, Debug, Clone, TypeFoldable)]
pub enum SelectionCandidate<'tcx> {
BuiltinCandidate {
/// `false` if there are no *further* obligations.
has_nested: bool,
},
ParamCandidate(ty::PolyTraitRef<'tcx>),
ImplCandidate(DefId),
AutoImplCandidate(DefId),
/// This is a trait matching with a projected type as `Self`, and
/// we found an applicable bound in the trait definition.
ProjectionCandidate,
/// Implementation of a `Fn`-family trait by one of the anonymous types
/// generated for a `||` expression.
ClosureCandidate,
/// Implementation of a `Generator` trait by one of the anonymous types
/// generated for a generator.
GeneratorCandidate,
/// Implementation of a `Fn`-family trait by one of the anonymous
/// types generated for a fn pointer type (e.g., `fn(int) -> int`)
FnPointerCandidate,
TraitAliasCandidate(DefId),
ObjectCandidate,
BuiltinObjectCandidate,
BuiltinUnsizeCandidate,
}
/// The result of trait evaluation. The order is important
/// here as the evaluation of a list is the maximum of the
/// evaluations.
///
/// The evaluation results are ordered:
/// - `EvaluatedToOk` implies `EvaluatedToOkModuloRegions`
/// implies `EvaluatedToAmbig` implies `EvaluatedToUnknown`
/// - `EvaluatedToErr` implies `EvaluatedToRecur`
/// - the "union" of evaluation results is equal to their maximum -
/// all the "potential success" candidates can potentially succeed,
/// so they are noops when unioned with a definite error, and within
/// the categories it's easy to see that the unions are correct.
#[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq, HashStable)]
pub enum EvaluationResult {
/// Evaluation successful.
EvaluatedToOk,
/// Evaluation successful, but there were unevaluated region obligations.
EvaluatedToOkModuloRegions,
/// Evaluation is known to be ambiguous -- it *might* hold for some
/// assignment of inference variables, but it might not.
///
/// While this has the same meaning as `EvaluatedToUnknown` -- we can't
/// know whether this obligation holds or not -- it is the result we
/// would get with an empty stack, and therefore is cacheable.
EvaluatedToAmbig,
/// Evaluation failed because of recursion involving inference
/// variables. We are somewhat imprecise there, so we don't actually
/// know the real result.
///
/// This can't be trivially cached for the same reason as `EvaluatedToRecur`.
EvaluatedToUnknown,
/// Evaluation failed because we encountered an obligation we are already
/// trying to prove on this branch.
///
/// We know this branch can't be a part of a minimal proof-tree for
/// the "root" of our cycle, because then we could cut out the recursion
/// and maintain a valid proof tree. However, this does not mean
/// that all the obligations on this branch do not hold -- it's possible
/// that we entered this branch "speculatively", and that there
/// might be some other way to prove this obligation that does not
/// go through this cycle -- so we can't cache this as a failure.
///
/// For example, suppose we have this:
///
/// ```rust,ignore (pseudo-Rust)
/// pub trait Trait { fn xyz(); }
/// // This impl is "useless", but we can still have
/// // an `impl Trait for SomeUnsizedType` somewhere.
/// impl<T: Trait + Sized> Trait for T { fn xyz() {} }
///
/// pub fn foo<T: Trait + ?Sized>() {
/// <T as Trait>::xyz();
/// }
/// ```
///
/// When checking `foo`, we have to prove `T: Trait`. This basically
/// translates into this:
///
/// ```plain,ignore
/// (T: Trait + Sized →_\impl T: Trait), T: Trait ⊢ T: Trait
/// ```
///
/// When we try to prove it, we first go the first option, which
/// recurses. This shows us that the impl is "useless" -- it won't
/// tell us that `T: Trait` unless it already implemented `Trait`
/// by some other means. However, that does not prevent `T: Trait`
/// does not hold, because of the bound (which can indeed be satisfied
/// by `SomeUnsizedType` from another crate).
//
// FIXME: when an `EvaluatedToRecur` goes past its parent root, we
// ought to convert it to an `EvaluatedToErr`, because we know
// there definitely isn't a proof tree for that obligation. Not
// doing so is still sound -- there isn't any proof tree, so the
// branch still can't be a part of a minimal one -- but does not re-enable caching.
EvaluatedToRecur,
/// Evaluation failed.
EvaluatedToErr,
}
impl EvaluationResult {
/// Returns `true` if this evaluation result is known to apply, even
/// considering outlives constraints.
pub fn must_apply_considering_regions(self) -> bool {
self == EvaluatedToOk
}
/// Returns `true` if this evaluation result is known to apply, ignoring
/// outlives constraints.
pub fn must_apply_modulo_regions(self) -> bool {
self <= EvaluatedToOkModuloRegions
}
pub fn may_apply(self) -> bool {
match self {
EvaluatedToOk | EvaluatedToOkModuloRegions | EvaluatedToAmbig | EvaluatedToUnknown => {
true
}
EvaluatedToErr | EvaluatedToRecur => false,
}
}
pub fn is_stack_dependent(self) -> bool {
match self {
EvaluatedToUnknown | EvaluatedToRecur => true,
EvaluatedToOk | EvaluatedToOkModuloRegions | EvaluatedToAmbig | EvaluatedToErr => false,
}
}
}
/// Indicates that trait evaluation caused overflow.
#[derive(Copy, Clone, Debug, PartialEq, Eq, HashStable)]
pub struct OverflowError;
impl<'tcx> From<OverflowError> for SelectionError<'tcx> {
fn from(OverflowError: OverflowError) -> SelectionError<'tcx> {
SelectionError::Overflow
}
}
#[derive(Clone, Default)]
pub struct EvaluationCache<'tcx> {
pub hashmap: Lock<
FxHashMap<ty::ParamEnvAnd<'tcx, ty::PolyTraitRef<'tcx>>, WithDepNode<EvaluationResult>>,
>,
}
impl<'tcx> EvaluationCache<'tcx> {
/// Actually frees the underlying memory in contrast to what stdlib containers do on `clear`
pub fn clear(&self) {
*self.hashmap.borrow_mut() = Default::default();
}
}
#[derive(Clone, Eq, PartialEq)]
pub struct WithDepNode<T> {
dep_node: DepNodeIndex,
cached_value: T,
}
impl<T: Clone> WithDepNode<T> {
pub fn new(dep_node: DepNodeIndex, cached_value: T) -> Self {
WithDepNode { dep_node, cached_value }
}
pub fn get(&self, tcx: TyCtxt<'_>) -> T {
tcx.dep_graph.read_index(self.dep_node);
self.cached_value.clone()
}
}

View File

@ -1,712 +0,0 @@
use crate::traits;
use crate::ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
use crate::ty::{self, Lift, Ty, TyCtxt};
use rustc_span::symbol::Symbol;
use smallvec::SmallVec;
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::rc::Rc;
// Structural impls for the structs in `traits`.
impl<'tcx, N: fmt::Debug> fmt::Debug for traits::Vtable<'tcx, N> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
super::VtableImpl(ref v) => write!(f, "{:?}", v),
super::VtableAutoImpl(ref t) => write!(f, "{:?}", t),
super::VtableClosure(ref d) => write!(f, "{:?}", d),
super::VtableGenerator(ref d) => write!(f, "{:?}", d),
super::VtableFnPointer(ref d) => write!(f, "VtableFnPointer({:?})", d),
super::VtableObject(ref d) => write!(f, "{:?}", d),
super::VtableParam(ref n) => write!(f, "VtableParam({:?})", n),
super::VtableBuiltin(ref d) => write!(f, "{:?}", d),
super::VtableTraitAlias(ref d) => write!(f, "{:?}", d),
}
}
}
impl<'tcx, N: fmt::Debug> fmt::Debug for traits::VtableImplData<'tcx, N> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"VtableImplData(impl_def_id={:?}, substs={:?}, nested={:?})",
self.impl_def_id, self.substs, self.nested
)
}
}
impl<'tcx, N: fmt::Debug> fmt::Debug for traits::VtableGeneratorData<'tcx, N> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"VtableGeneratorData(generator_def_id={:?}, substs={:?}, nested={:?})",
self.generator_def_id, self.substs, self.nested
)
}
}
impl<'tcx, N: fmt::Debug> fmt::Debug for traits::VtableClosureData<'tcx, N> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"VtableClosureData(closure_def_id={:?}, substs={:?}, nested={:?})",
self.closure_def_id, self.substs, self.nested
)
}
}
impl<N: fmt::Debug> fmt::Debug for traits::VtableBuiltinData<N> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "VtableBuiltinData(nested={:?})", self.nested)
}
}
impl<N: fmt::Debug> fmt::Debug for traits::VtableAutoImplData<N> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"VtableAutoImplData(trait_def_id={:?}, nested={:?})",
self.trait_def_id, self.nested
)
}
}
impl<'tcx, N: fmt::Debug> fmt::Debug for traits::VtableObjectData<'tcx, N> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"VtableObjectData(upcast={:?}, vtable_base={}, nested={:?})",
self.upcast_trait_ref, self.vtable_base, self.nested
)
}
}
impl<'tcx, N: fmt::Debug> fmt::Debug for traits::VtableFnPointerData<'tcx, N> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "VtableFnPointerData(fn_ty={:?}, nested={:?})", self.fn_ty, self.nested)
}
}
impl<'tcx, N: fmt::Debug> fmt::Debug for traits::VtableTraitAliasData<'tcx, N> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"VtableTraitAlias(alias_def_id={:?}, substs={:?}, nested={:?})",
self.alias_def_id, self.substs, self.nested
)
}
}
impl<'tcx> fmt::Display for traits::WhereClause<'tcx> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
use crate::traits::WhereClause::*;
// Bypass `ty::print` because it does not print out anonymous regions.
// FIXME(eddyb) implement a custom `PrettyPrinter`, or move this to `ty::print`.
fn write_region_name<'tcx>(
r: ty::Region<'tcx>,
fmt: &mut fmt::Formatter<'_>,
) -> fmt::Result {
match r {
ty::ReLateBound(index, br) => match br {
ty::BoundRegion::BrNamed(_, name) => write!(fmt, "{}", name),
ty::BoundRegion::BrAnon(var) => {
if *index == ty::INNERMOST {
write!(fmt, "'^{}", var)
} else {
write!(fmt, "'^{}_{}", index.index(), var)
}
}
_ => write!(fmt, "'_"),
},
_ => write!(fmt, "{}", r),
}
}
match self {
Implemented(trait_ref) => write!(fmt, "Implemented({})", trait_ref),
ProjectionEq(projection) => write!(fmt, "ProjectionEq({})", projection),
RegionOutlives(predicate) => {
write!(fmt, "RegionOutlives({}: ", predicate.0)?;
write_region_name(predicate.1, fmt)?;
write!(fmt, ")")
}
TypeOutlives(predicate) => {
write!(fmt, "TypeOutlives({}: ", predicate.0)?;
write_region_name(predicate.1, fmt)?;
write!(fmt, ")")
}
}
}
}
impl<'tcx> fmt::Display for traits::WellFormed<'tcx> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
use crate::traits::WellFormed::*;
match self {
Trait(trait_ref) => write!(fmt, "WellFormed({})", trait_ref),
Ty(ty) => write!(fmt, "WellFormed({})", ty),
}
}
}
impl<'tcx> fmt::Display for traits::FromEnv<'tcx> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
use crate::traits::FromEnv::*;
match self {
Trait(trait_ref) => write!(fmt, "FromEnv({})", trait_ref),
Ty(ty) => write!(fmt, "FromEnv({})", ty),
}
}
}
impl<'tcx> fmt::Display for traits::DomainGoal<'tcx> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
use crate::traits::DomainGoal::*;
match self {
Holds(wc) => write!(fmt, "{}", wc),
WellFormed(wf) => write!(fmt, "{}", wf),
FromEnv(from_env) => write!(fmt, "{}", from_env),
Normalize(projection) => {
write!(fmt, "Normalize({} -> {})", projection.projection_ty, projection.ty)
}
}
}
}
impl fmt::Display for traits::QuantifierKind {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
use crate::traits::QuantifierKind::*;
match self {
Universal => write!(fmt, "forall"),
Existential => write!(fmt, "exists"),
}
}
}
/// Collect names for regions / types bound by a quantified goal / clause.
/// This collector does not try to do anything clever like in `ty::print`, it's just used
/// for debug output in tests anyway.
struct BoundNamesCollector {
// Just sort by name because `BoundRegion::BrNamed` does not have a `BoundVar` index anyway.
regions: BTreeSet<Symbol>,
// Sort by `BoundVar` index, so usually this should be equivalent to the order given
// by the list of type parameters.
types: BTreeMap<u32, Symbol>,
binder_index: ty::DebruijnIndex,
}
impl BoundNamesCollector {
fn new() -> Self {
BoundNamesCollector {
regions: BTreeSet::new(),
types: BTreeMap::new(),
binder_index: ty::INNERMOST,
}
}
fn is_empty(&self) -> bool {
self.regions.is_empty() && self.types.is_empty()
}
fn write_names(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut start = true;
for r in &self.regions {
if !start {
write!(fmt, ", ")?;
}
start = false;
write!(fmt, "{}", r)?;
}
for (_, t) in &self.types {
if !start {
write!(fmt, ", ")?;
}
start = false;
write!(fmt, "{}", t)?;
}
Ok(())
}
}
impl<'tcx> TypeVisitor<'tcx> for BoundNamesCollector {
fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &ty::Binder<T>) -> bool {
self.binder_index.shift_in(1);
let result = t.super_visit_with(self);
self.binder_index.shift_out(1);
result
}
fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
match t.kind {
ty::Bound(debruijn, bound_ty) if debruijn == self.binder_index => {
self.types.insert(
bound_ty.var.as_u32(),
match bound_ty.kind {
ty::BoundTyKind::Param(name) => name,
ty::BoundTyKind::Anon => {
Symbol::intern(&format!("^{}", bound_ty.var.as_u32()))
}
},
);
}
_ => (),
};
t.super_visit_with(self)
}
fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
match r {
ty::ReLateBound(index, br) if *index == self.binder_index => match br {
ty::BoundRegion::BrNamed(_, name) => {
self.regions.insert(*name);
}
ty::BoundRegion::BrAnon(var) => {
self.regions.insert(Symbol::intern(&format!("'^{}", var)));
}
_ => (),
},
_ => (),
};
r.super_visit_with(self)
}
}
impl<'tcx> fmt::Display for traits::Goal<'tcx> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
use crate::traits::GoalKind::*;
match self {
Implies(hypotheses, goal) => {
write!(fmt, "if (")?;
for (index, hyp) in hypotheses.iter().enumerate() {
if index > 0 {
write!(fmt, ", ")?;
}
write!(fmt, "{}", hyp)?;
}
write!(fmt, ") {{ {} }}", goal)
}
And(goal1, goal2) => write!(fmt, "({} && {})", goal1, goal2),
Not(goal) => write!(fmt, "not {{ {} }}", goal),
DomainGoal(goal) => write!(fmt, "{}", goal),
Quantified(qkind, goal) => {
let mut collector = BoundNamesCollector::new();
goal.skip_binder().visit_with(&mut collector);
if !collector.is_empty() {
write!(fmt, "{}<", qkind)?;
collector.write_names(fmt)?;
write!(fmt, "> {{ ")?;
}
write!(fmt, "{}", goal.skip_binder())?;
if !collector.is_empty() {
write!(fmt, " }}")?;
}
Ok(())
}
Subtype(a, b) => write!(fmt, "{} <: {}", a, b),
CannotProve => write!(fmt, "CannotProve"),
}
}
}
impl<'tcx> fmt::Display for traits::ProgramClause<'tcx> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
let traits::ProgramClause { goal, hypotheses, .. } = self;
write!(fmt, "{}", goal)?;
if !hypotheses.is_empty() {
write!(fmt, " :- ")?;
for (index, condition) in hypotheses.iter().enumerate() {
if index > 0 {
write!(fmt, ", ")?;
}
write!(fmt, "{}", condition)?;
}
}
write!(fmt, ".")
}
}
impl<'tcx> fmt::Display for traits::Clause<'tcx> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
use crate::traits::Clause::*;
match self {
Implies(clause) => write!(fmt, "{}", clause),
ForAll(clause) => {
let mut collector = BoundNamesCollector::new();
clause.skip_binder().visit_with(&mut collector);
if !collector.is_empty() {
write!(fmt, "forall<")?;
collector.write_names(fmt)?;
write!(fmt, "> {{ ")?;
}
write!(fmt, "{}", clause.skip_binder())?;
if !collector.is_empty() {
write!(fmt, " }}")?;
}
Ok(())
}
}
}
}
///////////////////////////////////////////////////////////////////////////
// Lift implementations
impl<'a, 'tcx> Lift<'tcx> for traits::SelectionError<'a> {
type Lifted = traits::SelectionError<'tcx>;
fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
match *self {
super::Unimplemented => Some(super::Unimplemented),
super::OutputTypeParameterMismatch(a, b, ref err) => {
tcx.lift(&(a, b)).and_then(|(a, b)| {
tcx.lift(err).map(|err| super::OutputTypeParameterMismatch(a, b, err))
})
}
super::TraitNotObjectSafe(def_id) => Some(super::TraitNotObjectSafe(def_id)),
super::ConstEvalFailure(err) => Some(super::ConstEvalFailure(err)),
super::Overflow => Some(super::Overflow),
}
}
}
impl<'a, 'tcx> Lift<'tcx> for traits::ObligationCauseCode<'a> {
type Lifted = traits::ObligationCauseCode<'tcx>;
fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
match *self {
super::ReturnNoExpression => Some(super::ReturnNoExpression),
super::MiscObligation => Some(super::MiscObligation),
super::SliceOrArrayElem => Some(super::SliceOrArrayElem),
super::TupleElem => Some(super::TupleElem),
super::ProjectionWf(proj) => tcx.lift(&proj).map(super::ProjectionWf),
super::ItemObligation(def_id) => Some(super::ItemObligation(def_id)),
super::BindingObligation(def_id, span) => Some(super::BindingObligation(def_id, span)),
super::ReferenceOutlivesReferent(ty) => {
tcx.lift(&ty).map(super::ReferenceOutlivesReferent)
}
super::ObjectTypeBound(ty, r) => tcx
.lift(&ty)
.and_then(|ty| tcx.lift(&r).and_then(|r| Some(super::ObjectTypeBound(ty, r)))),
super::ObjectCastObligation(ty) => tcx.lift(&ty).map(super::ObjectCastObligation),
super::Coercion { source, target } => {
Some(super::Coercion { source: tcx.lift(&source)?, target: tcx.lift(&target)? })
}
super::AssignmentLhsSized => Some(super::AssignmentLhsSized),
super::TupleInitializerSized => Some(super::TupleInitializerSized),
super::StructInitializerSized => Some(super::StructInitializerSized),
super::VariableType(id) => Some(super::VariableType(id)),
super::ReturnValue(id) => Some(super::ReturnValue(id)),
super::ReturnType => Some(super::ReturnType),
super::SizedArgumentType => Some(super::SizedArgumentType),
super::SizedReturnType => Some(super::SizedReturnType),
super::SizedYieldType => Some(super::SizedYieldType),
super::RepeatVec(suggest_flag) => Some(super::RepeatVec(suggest_flag)),
super::FieldSized { adt_kind, last } => Some(super::FieldSized { adt_kind, last }),
super::ConstSized => Some(super::ConstSized),
super::ConstPatternStructural => Some(super::ConstPatternStructural),
super::SharedStatic => Some(super::SharedStatic),
super::BuiltinDerivedObligation(ref cause) => {
tcx.lift(cause).map(super::BuiltinDerivedObligation)
}
super::ImplDerivedObligation(ref cause) => {
tcx.lift(cause).map(super::ImplDerivedObligation)
}
super::CompareImplMethodObligation {
item_name,
impl_item_def_id,
trait_item_def_id,
} => Some(super::CompareImplMethodObligation {
item_name,
impl_item_def_id,
trait_item_def_id,
}),
super::CompareImplTypeObligation { item_name, impl_item_def_id, trait_item_def_id } => {
Some(super::CompareImplTypeObligation {
item_name,
impl_item_def_id,
trait_item_def_id,
})
}
super::ExprAssignable => Some(super::ExprAssignable),
super::MatchExpressionArm(box super::MatchExpressionArmCause {
arm_span,
source,
ref prior_arms,
last_ty,
scrut_hir_id,
}) => tcx.lift(&last_ty).map(|last_ty| {
super::MatchExpressionArm(box super::MatchExpressionArmCause {
arm_span,
source,
prior_arms: prior_arms.clone(),
last_ty,
scrut_hir_id,
})
}),
super::Pattern { span, root_ty, origin_expr } => {
tcx.lift(&root_ty).map(|root_ty| super::Pattern { span, root_ty, origin_expr })
}
super::IfExpression(box super::IfExpressionCause { then, outer, semicolon }) => {
Some(super::IfExpression(box super::IfExpressionCause { then, outer, semicolon }))
}
super::IfExpressionWithNoElse => Some(super::IfExpressionWithNoElse),
super::MainFunctionType => Some(super::MainFunctionType),
super::StartFunctionType => Some(super::StartFunctionType),
super::IntrinsicType => Some(super::IntrinsicType),
super::MethodReceiver => Some(super::MethodReceiver),
super::BlockTailExpression(id) => Some(super::BlockTailExpression(id)),
super::TrivialBound => Some(super::TrivialBound),
super::AssocTypeBound(ref data) => Some(super::AssocTypeBound(data.clone())),
}
}
}
impl<'a, 'tcx> Lift<'tcx> for traits::DerivedObligationCause<'a> {
type Lifted = traits::DerivedObligationCause<'tcx>;
fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
tcx.lift(&self.parent_trait_ref).and_then(|trait_ref| {
tcx.lift(&*self.parent_code).map(|code| traits::DerivedObligationCause {
parent_trait_ref: trait_ref,
parent_code: Rc::new(code),
})
})
}
}
impl<'a, 'tcx> Lift<'tcx> for traits::ObligationCause<'a> {
type Lifted = traits::ObligationCause<'tcx>;
fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
tcx.lift(&self.code).map(|code| traits::ObligationCause {
span: self.span,
body_id: self.body_id,
code,
})
}
}
// For codegen only.
impl<'a, 'tcx> Lift<'tcx> for traits::Vtable<'a, ()> {
type Lifted = traits::Vtable<'tcx, ()>;
fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
match self.clone() {
traits::VtableImpl(traits::VtableImplData { impl_def_id, substs, nested }) => {
tcx.lift(&substs).map(|substs| {
traits::VtableImpl(traits::VtableImplData { impl_def_id, substs, nested })
})
}
traits::VtableAutoImpl(t) => Some(traits::VtableAutoImpl(t)),
traits::VtableGenerator(traits::VtableGeneratorData {
generator_def_id,
substs,
nested,
}) => tcx.lift(&substs).map(|substs| {
traits::VtableGenerator(traits::VtableGeneratorData {
generator_def_id: generator_def_id,
substs: substs,
nested: nested,
})
}),
traits::VtableClosure(traits::VtableClosureData { closure_def_id, substs, nested }) => {
tcx.lift(&substs).map(|substs| {
traits::VtableClosure(traits::VtableClosureData {
closure_def_id,
substs,
nested,
})
})
}
traits::VtableFnPointer(traits::VtableFnPointerData { fn_ty, nested }) => {
tcx.lift(&fn_ty).map(|fn_ty| {
traits::VtableFnPointer(traits::VtableFnPointerData { fn_ty, nested })
})
}
traits::VtableParam(n) => Some(traits::VtableParam(n)),
traits::VtableBuiltin(n) => Some(traits::VtableBuiltin(n)),
traits::VtableObject(traits::VtableObjectData {
upcast_trait_ref,
vtable_base,
nested,
}) => tcx.lift(&upcast_trait_ref).map(|trait_ref| {
traits::VtableObject(traits::VtableObjectData {
upcast_trait_ref: trait_ref,
vtable_base,
nested,
})
}),
traits::VtableTraitAlias(traits::VtableTraitAliasData {
alias_def_id,
substs,
nested,
}) => tcx.lift(&substs).map(|substs| {
traits::VtableTraitAlias(traits::VtableTraitAliasData {
alias_def_id,
substs,
nested,
})
}),
}
}
}
impl<'a, 'tcx> Lift<'tcx> for traits::Environment<'a> {
type Lifted = traits::Environment<'tcx>;
fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
tcx.lift(&self.clauses).map(|clauses| traits::Environment { clauses })
}
}
impl<'a, 'tcx, G: Lift<'tcx>> Lift<'tcx> for traits::InEnvironment<'a, G> {
type Lifted = traits::InEnvironment<'tcx, G::Lifted>;
fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
tcx.lift(&self.environment).and_then(|environment| {
tcx.lift(&self.goal).map(|goal| traits::InEnvironment { environment, goal })
})
}
}
impl<'tcx, C> Lift<'tcx> for chalk_engine::ExClause<C>
where
C: chalk_engine::context::Context + Clone,
C: traits::ChalkContextLift<'tcx>,
{
type Lifted = C::LiftedExClause;
fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
<C as traits::ChalkContextLift>::lift_ex_clause_to_tcx(self, tcx)
}
}
impl<'tcx, C> Lift<'tcx> for chalk_engine::DelayedLiteral<C>
where
C: chalk_engine::context::Context + Clone,
C: traits::ChalkContextLift<'tcx>,
{
type Lifted = C::LiftedDelayedLiteral;
fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
<C as traits::ChalkContextLift>::lift_delayed_literal_to_tcx(self, tcx)
}
}
impl<'tcx, C> Lift<'tcx> for chalk_engine::Literal<C>
where
C: chalk_engine::context::Context + Clone,
C: traits::ChalkContextLift<'tcx>,
{
type Lifted = C::LiftedLiteral;
fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> {
<C as traits::ChalkContextLift>::lift_literal_to_tcx(self, tcx)
}
}
///////////////////////////////////////////////////////////////////////////
// TypeFoldable implementations.
CloneTypeFoldableAndLiftImpls! {
traits::QuantifierKind,
}
impl<'tcx> TypeFoldable<'tcx> for &'tcx ty::List<traits::Goal<'tcx>> {
fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
let v = self.iter().map(|t| t.fold_with(folder)).collect::<SmallVec<[_; 8]>>();
folder.tcx().intern_goals(&v)
}
fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
self.iter().any(|t| t.visit_with(visitor))
}
}
impl<'tcx> TypeFoldable<'tcx> for traits::Goal<'tcx> {
fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
let v = (**self).fold_with(folder);
folder.tcx().mk_goal(v)
}
fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
(**self).visit_with(visitor)
}
}
CloneTypeFoldableAndLiftImpls! {
traits::ProgramClauseCategory,
}
impl<'tcx> TypeFoldable<'tcx> for traits::Clauses<'tcx> {
fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
let v = self.iter().map(|t| t.fold_with(folder)).collect::<SmallVec<[_; 8]>>();
folder.tcx().intern_clauses(&v)
}
fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
self.iter().any(|t| t.visit_with(visitor))
}
}
impl<'tcx, C> TypeFoldable<'tcx> for chalk_engine::ExClause<C>
where
C: traits::ExClauseFold<'tcx>,
C::Substitution: Clone,
C::RegionConstraint: Clone,
{
fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
<C as traits::ExClauseFold>::fold_ex_clause_with(self, folder)
}
fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
<C as traits::ExClauseFold>::visit_ex_clause_with(self, visitor)
}
}
EnumTypeFoldableImpl! {
impl<'tcx, C> TypeFoldable<'tcx> for chalk_engine::DelayedLiteral<C> {
(chalk_engine::DelayedLiteral::CannotProve)(a),
(chalk_engine::DelayedLiteral::Negative)(a),
(chalk_engine::DelayedLiteral::Positive)(a, b),
} where
C: chalk_engine::context::Context<CanonicalConstrainedSubst: TypeFoldable<'tcx>> + Clone,
}
EnumTypeFoldableImpl! {
impl<'tcx, C> TypeFoldable<'tcx> for chalk_engine::Literal<C> {
(chalk_engine::Literal::Negative)(a),
(chalk_engine::Literal::Positive)(a),
} where
C: chalk_engine::context::Context<GoalInEnvironment: Clone + TypeFoldable<'tcx>> + Clone,
}
CloneTypeFoldableAndLiftImpls! {
chalk_engine::TableIndex,
}

View File

@ -19,15 +19,15 @@ use crate::mir::interpret::{LitToConstError, LitToConstInput};
use crate::mir::mono::CodegenUnit;
use crate::session::config::{EntryFnType, OptLevel, OutputFilenames, SymbolManglingVersion};
use crate::session::CrateDisambiguator;
use crate::traits::query::dropck_outlives::{DropckOutlivesResult, DtorckConstraint};
use crate::traits::query::method_autoderef::MethodAutoderefStepsResult;
use crate::traits::query::normalize::NormalizationResult;
use crate::traits::query::outlives_bounds::OutlivesBound;
use crate::traits::query::{
CanonicalPredicateGoal, CanonicalProjectionGoal, CanonicalTyGoal,
CanonicalTypeOpAscribeUserTypeGoal, CanonicalTypeOpEqGoal, CanonicalTypeOpNormalizeGoal,
CanonicalTypeOpProvePredicateGoal, CanonicalTypeOpSubtypeGoal, NoSolution,
};
use crate::traits::query::{
DropckOutlivesResult, DtorckConstraint, MethodAutoderefStepsResult, NormalizationResult,
OutlivesBound,
};
use crate::traits::specialization_graph;
use crate::traits::Clauses;
use crate::traits::{self, Vtable};

View File

@ -0,0 +1,28 @@
[package]
authors = ["The Rust Project Developers"]
name = "rustc_infer"
version = "0.0.0"
edition = "2018"
[lib]
name = "rustc_infer"
path = "lib.rs"
doctest = false
[dependencies]
fmt_macros = { path = "../libfmt_macros" }
graphviz = { path = "../libgraphviz" }
log = { version = "0.4", features = ["release_max_level_info", "std"] }
rustc_attr = { path = "../librustc_attr" }
rustc = { path = "../librustc" }
rustc_data_structures = { path = "../librustc_data_structures" }
rustc_errors = { path = "../librustc_errors" }
rustc_error_codes = { path = "../librustc_error_codes" }
rustc_hir = { path = "../librustc_hir" }
rustc_index = { path = "../librustc_index" }
rustc_macros = { path = "../librustc_macros" }
rustc_session = { path = "../librustc_session" }
rustc_span = { path = "../librustc_span" }
rustc_target = { path = "../librustc_target" }
smallvec = { version = "1.0", features = ["union", "may_dangle"] }
syntax = { path = "../libsyntax" }

View File

@ -27,8 +27,8 @@
use super::*;
use crate::ty::relate::{Relate, TypeRelation};
use crate::ty::Const;
use rustc::ty::relate::{Relate, TypeRelation};
use rustc::ty::Const;
pub struct At<'a, 'tcx> {
pub infcx: &'a InferCtxt<'a, 'tcx>,

View File

@ -10,10 +10,10 @@ use crate::infer::canonical::{
OriginalQueryValues,
};
use crate::infer::InferCtxt;
use crate::ty::flags::FlagComputation;
use crate::ty::fold::{TypeFoldable, TypeFolder};
use crate::ty::subst::GenericArg;
use crate::ty::{self, BoundVar, InferConst, List, Ty, TyCtxt, TypeFlags};
use rustc::ty::flags::FlagComputation;
use rustc::ty::fold::{TypeFoldable, TypeFolder};
use rustc::ty::subst::GenericArg;
use rustc::ty::{self, BoundVar, InferConst, List, Ty, TyCtxt, TypeFlags};
use std::sync::atomic::Ordering;
use rustc_data_structures::fx::FxHashMap;

View File

@ -29,12 +29,11 @@ use rustc::ty::{self, BoundVar, List};
use rustc_index::vec::IndexVec;
use rustc_span::source_map::Span;
pub use rustc::infer::types::canonical::*;
pub use rustc::infer::canonical::*;
use substitute::CanonicalExt;
mod canonicalizer;
pub mod query_response;
mod substitute;
impl<'cx, 'tcx> InferCtxt<'cx, 'tcx> {

View File

@ -7,8 +7,7 @@
//!
//! [c]: https://rust-lang.github.io/rustc-guide/traits/canonicalization.html
use crate::arena::ArenaAllocatable;
use crate::infer::canonical::substitute::substitute_value;
use crate::infer::canonical::substitute::{substitute_value, CanonicalExt};
use crate::infer::canonical::{
Canonical, CanonicalVarValues, CanonicalizedQueryResponse, Certainty, OriginalQueryValues,
QueryOutlivesConstraint, QueryRegionConstraints, QueryResponse,
@ -19,9 +18,10 @@ use crate::infer::{InferCtxt, InferOk, InferResult};
use crate::traits::query::{Fallible, NoSolution};
use crate::traits::TraitEngine;
use crate::traits::{Obligation, ObligationCause, PredicateObligation};
use crate::ty::fold::TypeFoldable;
use crate::ty::subst::{GenericArg, GenericArgKind};
use crate::ty::{self, BoundVar, Ty, TyCtxt};
use rustc::arena::ArenaAllocatable;
use rustc::ty::fold::TypeFoldable;
use rustc::ty::subst::{GenericArg, GenericArgKind};
use rustc::ty::{self, BoundVar, Ty, TyCtxt};
use rustc_data_structures::captures::Captures;
use rustc_index::vec::Idx;
use rustc_index::vec::IndexVec;

View File

@ -7,19 +7,16 @@
//! [c]: https://rust-lang.github.io/rustc-guide/traits/canonicalization.html
use crate::infer::canonical::{Canonical, CanonicalVarValues};
use crate::ty::fold::TypeFoldable;
use crate::ty::subst::GenericArgKind;
use crate::ty::{self, TyCtxt};
use rustc::ty::fold::TypeFoldable;
use rustc::ty::subst::GenericArgKind;
use rustc::ty::{self, TyCtxt};
impl<'tcx, V> Canonical<'tcx, V> {
pub(super) trait CanonicalExt<'tcx, V> {
/// Instantiate the wrapped value, replacing each canonical value
/// with the value given in `var_values`.
pub fn substitute(&self, tcx: TyCtxt<'tcx>, var_values: &CanonicalVarValues<'tcx>) -> V
fn substitute(&self, tcx: TyCtxt<'tcx>, var_values: &CanonicalVarValues<'tcx>) -> V
where
V: TypeFoldable<'tcx>,
{
self.substitute_projected(tcx, var_values, |value| value)
}
V: TypeFoldable<'tcx>;
/// Allows one to apply a substitute to some subset of
/// `self.value`. Invoke `projection_fn` with `self.value` to get
@ -27,7 +24,25 @@ impl<'tcx, V> Canonical<'tcx, V> {
/// variables bound in `self` (usually this extracts from subset
/// of `self`). Apply the substitution `var_values` to this value
/// V, replacing each of the canonical variables.
pub fn substitute_projected<T>(
fn substitute_projected<T>(
&self,
tcx: TyCtxt<'tcx>,
var_values: &CanonicalVarValues<'tcx>,
projection_fn: impl FnOnce(&V) -> &T,
) -> T
where
T: TypeFoldable<'tcx>;
}
impl<'tcx, V> CanonicalExt<'tcx, V> for Canonical<'tcx, V> {
fn substitute(&self, tcx: TyCtxt<'tcx>, var_values: &CanonicalVarValues<'tcx>) -> V
where
V: TypeFoldable<'tcx>,
{
self.substitute_projected(tcx, var_values, |value| value)
}
fn substitute_projected<T>(
&self,
tcx: TyCtxt<'tcx>,
var_values: &CanonicalVarValues<'tcx>,

View File

@ -33,12 +33,12 @@ use super::unify_key::{ConstVariableOrigin, ConstVariableOriginKind};
use super::{InferCtxt, MiscVariable, TypeTrace};
use crate::traits::{Obligation, PredicateObligations};
use crate::ty::error::TypeError;
use crate::ty::relate::{self, Relate, RelateResult, TypeRelation};
use crate::ty::subst::SubstsRef;
use crate::ty::{self, InferConst, Ty, TyCtxt};
use crate::ty::{IntType, UintType};
use rustc::ty::error::TypeError;
use rustc::ty::relate::{self, Relate, RelateResult, TypeRelation};
use rustc::ty::subst::SubstsRef;
use rustc::ty::{self, InferConst, Ty, TyCtxt};
use rustc::ty::{IntType, UintType};
use rustc_hir::def_id::DefId;
use rustc_span::{Span, DUMMY_SP};
use syntax::ast;

View File

@ -1,10 +1,10 @@
use super::combine::{CombineFields, RelationDir};
use super::Subtype;
use crate::ty::relate::{self, Relate, RelateResult, TypeRelation};
use crate::ty::subst::SubstsRef;
use crate::ty::TyVar;
use crate::ty::{self, Ty, TyCtxt};
use rustc::ty::relate::{self, Relate, RelateResult, TypeRelation};
use rustc::ty::subst::SubstsRef;
use rustc::ty::TyVar;
use rustc::ty::{self, Ty, TyCtxt};
use rustc_hir::def_id::DefId;

View File

@ -49,17 +49,18 @@ use super::lexical_region_resolve::RegionResolutionError;
use super::region_constraints::GenericKind;
use super::{InferCtxt, RegionVariableOrigin, SubregionOrigin, TypeTrace, ValuePairs};
use crate::hir::map;
use crate::infer::opaque_types;
use crate::infer::{self, SuppressRegionErrors};
use crate::middle::region;
use crate::traits::error_reporting::report_object_safety_error;
use crate::traits::object_safety_violations;
use crate::traits::{
IfExpressionCause, MatchExpressionArmCause, ObligationCause, ObligationCauseCode,
};
use crate::ty::error::TypeError;
use crate::ty::{
use rustc::hir::map;
use rustc::middle::region;
use rustc::ty::error::TypeError;
use rustc::ty::{
self,
subst::{Subst, SubstsRef},
Region, Ty, TyCtxt, TypeFoldable,
@ -2005,7 +2006,12 @@ enum FailureCode {
Error0644(&'static str),
}
impl<'tcx> ObligationCause<'tcx> {
trait ObligationCauseExt<'tcx> {
fn as_failure_code(&self, terr: &TypeError<'tcx>) -> FailureCode;
fn as_requirement_str(&self) -> &'static str;
}
impl<'tcx> ObligationCauseExt<'tcx> for ObligationCause<'tcx> {
fn as_failure_code(&self, terr: &TypeError<'tcx>) -> FailureCode {
use self::FailureCode::*;
use crate::traits::ObligationCauseCode::*;

View File

@ -1,8 +1,8 @@
use crate::hir::map::Map;
use crate::infer::type_variable::TypeVariableOriginKind;
use crate::infer::InferCtxt;
use crate::ty::print::Print;
use crate::ty::{self, DefIdTree, Infer, Ty, TyVar};
use rustc::hir::map::Map;
use rustc::ty::print::Print;
use rustc::ty::{self, DefIdTree, Infer, Ty, TyVar};
use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder};
use rustc_hir as hir;
use rustc_hir::def::{DefKind, Namespace};

View File

@ -3,7 +3,7 @@
use crate::infer::error_reporting::nice_region_error::util::AnonymousParamInfo;
use crate::infer::error_reporting::nice_region_error::NiceRegionError;
use crate::util::common::ErrorReported;
use rustc::util::common::ErrorReported;
use rustc_errors::struct_span_err;

View File

@ -1,7 +1,7 @@
use crate::hir::map::Map;
use crate::infer::error_reporting::nice_region_error::NiceRegionError;
use crate::middle::resolve_lifetime as rl;
use crate::ty::{self, Region, TyCtxt};
use rustc::hir::map::Map;
use rustc::middle::resolve_lifetime as rl;
use rustc::ty::{self, Region, TyCtxt};
use rustc_hir as hir;
use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
use rustc_hir::Node;

View File

@ -1,8 +1,8 @@
use crate::infer::lexical_region_resolve::RegionResolutionError;
use crate::infer::lexical_region_resolve::RegionResolutionError::*;
use crate::infer::InferCtxt;
use crate::ty::{self, TyCtxt};
use crate::util::common::ErrorReported;
use rustc::ty::{self, TyCtxt};
use rustc::util::common::ErrorReported;
use rustc_errors::DiagnosticBuilder;
use rustc_span::source_map::Span;

View File

@ -1,7 +1,7 @@
//! Error Reporting for Anonymous Region Lifetime Errors
//! where one region is named and the other is anonymous.
use crate::infer::error_reporting::nice_region_error::NiceRegionError;
use crate::ty;
use rustc::ty;
use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder};
use rustc_hir::{FunctionRetTy, TyKind};

View File

@ -4,8 +4,8 @@
use crate::infer::error_reporting::nice_region_error::NiceRegionError;
use crate::infer::lexical_region_resolve::RegionResolutionError::SubSupConflict;
use crate::infer::SubregionOrigin;
use crate::ty::RegionKind;
use crate::util::common::ErrorReported;
use rustc::ty::RegionKind;
use rustc::util::common::ErrorReported;
use rustc_hir::{Expr, ExprKind::Closure, Node};
impl<'a, 'tcx> NiceRegionError<'a, 'tcx> {

View File

@ -3,10 +3,10 @@ use crate::infer::lexical_region_resolve::RegionResolutionError;
use crate::infer::ValuePairs;
use crate::infer::{SubregionOrigin, TypeTrace};
use crate::traits::{ObligationCause, ObligationCauseCode};
use crate::ty::error::ExpectedFound;
use crate::ty::print::{FmtPrinter, Print, RegionHighlightMode};
use crate::ty::subst::SubstsRef;
use crate::ty::{self, TyCtxt};
use rustc::ty::error::ExpectedFound;
use rustc::ty::print::{FmtPrinter, Print, RegionHighlightMode};
use rustc::ty::subst::SubstsRef;
use rustc::ty::{self, TyCtxt};
use rustc_errors::DiagnosticBuilder;
use rustc_hir::def::Namespace;
use rustc_hir::def_id::DefId;

View File

@ -3,8 +3,8 @@
use crate::infer::error_reporting::msg_span_from_free_region;
use crate::infer::error_reporting::nice_region_error::NiceRegionError;
use crate::infer::lexical_region_resolve::RegionResolutionError;
use crate::ty::{BoundRegion, FreeRegion, RegionKind};
use crate::util::common::ErrorReported;
use rustc::ty::{BoundRegion, FreeRegion, RegionKind};
use rustc::util::common::ErrorReported;
use rustc_errors::Applicability;
impl<'a, 'tcx> NiceRegionError<'a, 'tcx> {

View File

@ -4,8 +4,8 @@ use crate::infer::error_reporting::nice_region_error::NiceRegionError;
use crate::infer::lexical_region_resolve::RegionResolutionError;
use crate::infer::{Subtype, ValuePairs};
use crate::traits::ObligationCauseCode::CompareImplMethodObligation;
use crate::ty::Ty;
use crate::util::common::ErrorReported;
use rustc::ty::Ty;
use rustc::util::common::ErrorReported;
use rustc_span::Span;
impl<'a, 'tcx> NiceRegionError<'a, 'tcx> {

View File

@ -2,7 +2,7 @@
//! anonymous regions.
use crate::infer::error_reporting::nice_region_error::NiceRegionError;
use crate::ty::{self, DefIdTree, Region, Ty};
use rustc::ty::{self, DefIdTree, Region, Ty};
use rustc_hir as hir;
use rustc_hir::def_id::DefId;
use rustc_span::Span;

View File

@ -1,8 +1,8 @@
use crate::infer::error_reporting::note_and_explain_region;
use crate::infer::error_reporting::{note_and_explain_region, ObligationCauseExt};
use crate::infer::{self, InferCtxt, SubregionOrigin};
use crate::middle::region;
use crate::ty::error::TypeError;
use crate::ty::{self, Region};
use rustc::middle::region;
use rustc::ty::error::TypeError;
use rustc::ty::{self, Region};
use rustc_errors::{struct_span_err, DiagnosticBuilder};
impl<'a, 'tcx> InferCtxt<'a, 'tcx> {

View File

@ -31,8 +31,8 @@
//! variable only once, and it does so as soon as it can, so it is reasonable to ask what the type
//! inferencer knows "so far".
use crate::ty::fold::TypeFolder;
use crate::ty::{self, Ty, TyCtxt, TypeFoldable};
use rustc::ty::fold::TypeFolder;
use rustc::ty::{self, Ty, TyCtxt, TypeFoldable};
use rustc_data_structures::fx::FxHashMap;

View File

@ -1,5 +1,5 @@
use crate::ty::fold::{TypeFoldable, TypeFolder};
use crate::ty::{self, ConstVid, FloatVid, IntVid, RegionVid, Ty, TyCtxt, TyVid};
use rustc::ty::fold::{TypeFoldable, TypeFolder};
use rustc::ty::{self, ConstVid, FloatVid, IntVid, RegionVid, Ty, TyCtxt, TyVid};
use super::type_variable::TypeVariableOrigin;
use super::InferCtxt;

View File

@ -4,8 +4,8 @@ use super::InferCtxt;
use super::Subtype;
use crate::traits::ObligationCause;
use crate::ty::relate::{Relate, RelateResult, TypeRelation};
use crate::ty::{self, Ty, TyCtxt};
use rustc::ty::relate::{Relate, RelateResult, TypeRelation};
use rustc::ty::{self, Ty, TyCtxt};
/// "Greatest lower bound" (common subtype)
pub struct Glb<'combine, 'infcx, 'tcx> {

View File

@ -5,8 +5,8 @@ use super::combine::CombineFields;
use super::{HigherRankedType, InferCtxt, PlaceholderMap};
use crate::infer::CombinedSnapshot;
use crate::ty::relate::{Relate, RelateResult, TypeRelation};
use crate::ty::{self, Binder, TypeFoldable};
use rustc::ty::relate::{Relate, RelateResult, TypeRelation};
use rustc::ty::{self, Binder, TypeFoldable};
impl<'a, 'tcx> CombineFields<'a, 'tcx> {
pub fn higher_ranked_sub<T>(

View File

@ -23,9 +23,9 @@ use super::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
use super::InferCtxt;
use crate::traits::ObligationCause;
use crate::ty::relate::{RelateResult, TypeRelation};
use crate::ty::TyVar;
use crate::ty::{self, Ty};
use rustc::ty::relate::{RelateResult, TypeRelation};
use rustc::ty::TyVar;
use rustc::ty::{self, Ty};
pub trait LatticeDir<'f, 'tcx>: TypeRelation<'tcx> {
fn infcx(&self) -> &'f InferCtxt<'f, 'tcx>;

View File

@ -11,9 +11,9 @@ use graphviz as dot;
use super::Constraint;
use crate::infer::region_constraints::RegionConstraintData;
use crate::infer::SubregionOrigin;
use crate::middle::free_region::RegionRelations;
use crate::middle::region;
use crate::ty;
use rustc::middle::free_region::RegionRelations;
use rustc::middle::region;
use rustc::ty;
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_hir::def_id::DefIndex;

View File

@ -8,12 +8,12 @@ use crate::infer::region_constraints::VarInfos;
use crate::infer::region_constraints::VerifyBound;
use crate::infer::RegionVariableOrigin;
use crate::infer::SubregionOrigin;
use crate::middle::free_region::RegionRelations;
use crate::ty::fold::TypeFoldable;
use crate::ty::{self, Ty, TyCtxt};
use crate::ty::{ReEarlyBound, ReEmpty, ReErased, ReFree, ReStatic};
use crate::ty::{ReLateBound, RePlaceholder, ReScope, ReVar};
use crate::ty::{Region, RegionVid};
use rustc::middle::free_region::RegionRelations;
use rustc::ty::fold::TypeFoldable;
use rustc::ty::{self, Ty, TyCtxt};
use rustc::ty::{ReEarlyBound, ReEmpty, ReErased, ReFree, ReStatic};
use rustc::ty::{ReLateBound, RePlaceholder, ReScope, ReVar};
use rustc::ty::{Region, RegionVid};
use rustc_data_structures::fx::FxHashSet;
use rustc_data_structures::graph::implementation::{
Direction, Graph, NodeIndex, INCOMING, OUTGOING,

View File

@ -4,8 +4,8 @@ use super::InferCtxt;
use super::Subtype;
use crate::traits::ObligationCause;
use crate::ty::relate::{Relate, RelateResult, TypeRelation};
use crate::ty::{self, Ty, TyCtxt};
use rustc::ty::relate::{Relate, RelateResult, TypeRelation};
use rustc::ty::{self, Ty, TyCtxt};
/// "Least upper bound" (common supertype)
pub struct Lub<'combine, 'infcx, 'tcx> {

File diff suppressed because it is too large Load Diff

View File

@ -24,11 +24,11 @@
use crate::infer::InferCtxt;
use crate::infer::{ConstVarValue, ConstVariableValue};
use crate::traits::DomainGoal;
use crate::ty::error::TypeError;
use crate::ty::fold::{TypeFoldable, TypeVisitor};
use crate::ty::relate::{self, Relate, RelateResult, TypeRelation};
use crate::ty::subst::GenericArg;
use crate::ty::{self, InferConst, Ty, TyCtxt};
use rustc::ty::error::TypeError;
use rustc::ty::fold::{TypeFoldable, TypeVisitor};
use rustc::ty::relate::{self, Relate, RelateResult, TypeRelation};
use rustc::ty::subst::GenericArg;
use rustc::ty::{self, InferConst, Ty, TyCtxt};
use rustc_data_structures::fx::FxHashMap;
use std::fmt::Debug;

View File

@ -1,12 +1,12 @@
use crate::infer::error_reporting::{note_and_explain_free_region, note_and_explain_region};
use crate::infer::{self, InferCtxt, InferOk, TypeVariableOrigin, TypeVariableOriginKind};
use crate::middle::region;
use crate::traits::{self, PredicateObligation};
use crate::ty::fold::{BottomUpFolder, TypeFoldable, TypeFolder, TypeVisitor};
use crate::ty::free_region_map::FreeRegionRelations;
use crate::ty::subst::{GenericArg, GenericArgKind, InternalSubsts, SubstsRef};
use crate::ty::{self, GenericParamDefKind, Ty, TyCtxt};
use rustc::middle::region;
use rustc::session::config::nightly_options;
use rustc::ty::fold::{BottomUpFolder, TypeFoldable, TypeFolder, TypeVisitor};
use rustc::ty::free_region_map::FreeRegionRelations;
use rustc::ty::subst::{GenericArg, GenericArgKind, InternalSubsts, SubstsRef};
use rustc::ty::{self, GenericParamDefKind, Ty, TyCtxt};
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::sync::Lrc;
use rustc_errors::{struct_span_err, DiagnosticBuilder};

View File

@ -1,7 +1,7 @@
use crate::infer::{GenericKind, InferCtxt};
use crate::traits::query::outlives_bounds::{self, OutlivesBound};
use crate::ty::free_region_map::FreeRegionMap;
use crate::ty::{self, Ty};
use rustc::ty::free_region_map::FreeRegionMap;
use rustc::ty::{self, Ty};
use rustc_data_structures::fx::FxHashMap;
use rustc_hir as hir;
use rustc_span::Span;

View File

@ -63,11 +63,13 @@ use crate::infer::outlives::env::RegionBoundPairs;
use crate::infer::outlives::verify::VerifyBoundCx;
use crate::infer::{self, GenericKind, InferCtxt, RegionObligation, SubregionOrigin, VerifyBound};
use crate::traits::ObligationCause;
use crate::ty::outlives::Component;
use crate::ty::subst::GenericArgKind;
use crate::ty::{self, Region, Ty, TyCtxt, TypeFoldable};
use rustc::ty::outlives::Component;
use rustc::ty::subst::GenericArgKind;
use rustc::ty::{self, Region, Ty, TyCtxt, TypeFoldable};
use rustc_data_structures::fx::FxHashMap;
use rustc_hir as hir;
use smallvec::smallvec;
impl<'cx, 'tcx> InferCtxt<'cx, 'tcx> {
/// Registers that the given region obligation must be resolved

View File

@ -1,11 +1,13 @@
use crate::infer::outlives::env::RegionBoundPairs;
use crate::infer::{GenericKind, VerifyBound};
use crate::traits;
use crate::ty::subst::{InternalSubsts, Subst};
use crate::ty::{self, Ty, TyCtxt};
use rustc::ty::subst::{InternalSubsts, Subst};
use rustc::ty::{self, Ty, TyCtxt};
use rustc_data_structures::captures::Captures;
use rustc_hir::def_id::DefId;
use smallvec::smallvec;
/// The `TypeOutlives` struct has the job of "lowering" a `T: 'a`
/// obligation into a series of `'a: 'b` constraints and "verifys", as
/// described on the module comment. The final constraints are emitted

View File

@ -1,7 +1,7 @@
use super::*;
use crate::infer::{CombinedSnapshot, PlaceholderMap};
use crate::ty::error::TypeError;
use crate::ty::relate::RelateResult;
use rustc::ty::error::TypeError;
use rustc::ty::relate::RelateResult;
impl<'tcx> RegionConstraintCollector<'tcx> {
/// Searches region constraints created since `snapshot` that

View File

@ -6,10 +6,10 @@ use self::UndoLog::*;
use super::unify_key;
use super::{MiscVariable, RegionVariableOrigin, SubregionOrigin};
use crate::ty::ReStatic;
use crate::ty::{self, Ty, TyCtxt};
use crate::ty::{ReLateBound, ReVar};
use crate::ty::{Region, RegionVid};
use rustc::ty::ReStatic;
use rustc::ty::{self, Ty, TyCtxt};
use rustc::ty::{ReLateBound, ReVar};
use rustc::ty::{Region, RegionVid};
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_data_structures::sync::Lrc;
use rustc_data_structures::unify as ut;
@ -23,7 +23,7 @@ use std::{cmp, fmt, mem};
mod leak_check;
pub use rustc::infer::types::MemberConstraint;
pub use rustc::infer::MemberConstraint;
#[derive(Default)]
pub struct RegionConstraintCollector<'tcx> {

View File

@ -1,7 +1,7 @@
use super::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
use super::{FixupError, FixupResult, InferCtxt, Span};
use crate::ty::fold::{TypeFolder, TypeVisitor};
use crate::ty::{self, Const, InferConst, Ty, TyCtxt, TypeFoldable};
use rustc::ty::fold::{TypeFolder, TypeVisitor};
use rustc::ty::{self, Const, InferConst, Ty, TyCtxt, TypeFoldable};
///////////////////////////////////////////////////////////////////////////
// OPPORTUNISTIC VAR RESOLVER

View File

@ -2,10 +2,10 @@ use super::combine::{CombineFields, RelationDir};
use super::SubregionOrigin;
use crate::traits::Obligation;
use crate::ty::fold::TypeFoldable;
use crate::ty::relate::{Cause, Relate, RelateResult, TypeRelation};
use crate::ty::TyVar;
use crate::ty::{self, Ty, TyCtxt};
use rustc::ty::fold::TypeFoldable;
use rustc::ty::relate::{Cause, Relate, RelateResult, TypeRelation};
use rustc::ty::TyVar;
use rustc::ty::{self, Ty, TyCtxt};
use std::mem;
/// Ensures `a` is made a subtype of `b`. Returns `a` on success.

View File

@ -1,4 +1,4 @@
use crate::ty::{self, Ty, TyVid};
use rustc::ty::{self, Ty, TyVid};
use rustc_hir::def_id::DefId;
use rustc_span::symbol::Symbol;
use rustc_span::Span;

38
src/librustc_infer/lib.rs Normal file
View File

@ -0,0 +1,38 @@
//! This crates defines the trait resolution method and the type inference engine.
//!
//! - **Traits.** Trait resolution is implemented in the `traits` module.
//! - **Type inference.** The type inference code can be found in the `infer` module;
//! this code handles low-level equality and subtyping operations. The
//! type check pass in the compiler is found in the `librustc_typeck` crate.
//!
//! For more information about how rustc works, see the [rustc guide].
//!
//! [rustc guide]: https://rust-lang.github.io/rustc-guide/
//!
//! # Note
//!
//! This API is completely unstable and subject to change.
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
#![feature(bool_to_option)]
#![feature(box_patterns)]
#![feature(box_syntax)]
#![feature(drain_filter)]
#![feature(never_type)]
#![feature(range_is_empty)]
#![feature(in_band_lifetimes)]
#![feature(crate_visibility_modifier)]
#![recursion_limit = "512"]
#[macro_use]
extern crate rustc_macros;
#[cfg(target_arch = "x86_64")]
#[macro_use]
extern crate rustc_data_structures;
#[macro_use]
extern crate log;
#[macro_use]
extern crate rustc;
pub mod infer;
pub mod traits;

View File

@ -5,8 +5,8 @@ use super::*;
use crate::infer::region_constraints::{Constraint, RegionConstraintData};
use crate::infer::InferCtxt;
use crate::ty::fold::TypeFolder;
use crate::ty::{Region, RegionVid};
use rustc::ty::fold::TypeFolder;
use rustc::ty::{Region, RegionVid};
use rustc_data_structures::fx::{FxHashMap, FxHashSet};

View File

@ -1,14 +1,14 @@
use crate::infer::canonical::{Canonical, OriginalQueryValues};
use crate::infer::canonical::OriginalQueryValues;
use crate::infer::InferCtxt;
use crate::traits::query::NoSolution;
use crate::traits::{
Environment, FulfillmentError, FulfillmentErrorCode, InEnvironment, ObligationCause,
PredicateObligation, SelectionError, TraitEngine,
};
use crate::ty::{self, Ty};
use rustc::ty::{self, Ty};
use rustc_data_structures::fx::FxHashSet;
pub type CanonicalGoal<'tcx> = Canonical<'tcx, InEnvironment<'tcx, ty::Predicate<'tcx>>>;
pub use rustc::traits::ChalkCanonicalGoal as CanonicalGoal;
pub struct FulfillmentContext<'tcx> {
obligations: FxHashSet<InEnvironment<'tcx, PredicateObligation<'tcx>>>,

View File

@ -3,12 +3,12 @@
// seems likely that they should eventually be merged into more
// general routines.
use crate::infer::InferCtxt;
use crate::infer::{InferCtxt, TyCtxtInferExt};
use crate::traits::{
FulfillmentContext, Obligation, ObligationCause, SelectionContext, TraitEngine, Vtable,
};
use crate::ty::fold::TypeFoldable;
use crate::ty::{self, TyCtxt};
use rustc::ty::fold::TypeFoldable;
use rustc::ty::{self, TyCtxt};
/// Attempts to resolve an obligation to a vtable. The result is
/// a shallow vtable resolution, meaning that we do not

View File

@ -4,13 +4,13 @@
//! [trait-resolution]: https://rust-lang.github.io/rustc-guide/traits/resolution.html
//! [trait-specialization]: https://rust-lang.github.io/rustc-guide/traits/specialization.html
use crate::infer::{CombinedSnapshot, InferOk};
use crate::infer::{CombinedSnapshot, InferOk, TyCtxtInferExt};
use crate::traits::select::IntercrateAmbiguityCause;
use crate::traits::SkipLeakCheck;
use crate::traits::{self, Normalized, Obligation, ObligationCause, SelectionContext};
use crate::ty::fold::TypeFoldable;
use crate::ty::subst::Subst;
use crate::ty::{self, Ty, TyCtxt};
use rustc::ty::fold::TypeFoldable;
use rustc::ty::subst::Subst;
use rustc::ty::{self, Ty, TyCtxt};
use rustc_hir::def_id::{DefId, LOCAL_CRATE};
use rustc_span::symbol::sym;
use rustc_span::DUMMY_SP;

View File

@ -1,6 +1,6 @@
use crate::infer::InferCtxt;
use crate::traits::Obligation;
use crate::ty::{self, ToPredicate, Ty, TyCtxt, WithConstness};
use rustc::ty::{self, ToPredicate, Ty, TyCtxt, WithConstness};
use rustc_hir::def_id::DefId;
use super::{ChalkFulfillmentContext, FulfillmentContext, FulfillmentError};

View File

@ -11,18 +11,17 @@ use super::{
use crate::infer::error_reporting::{TyCategory, TypeAnnotationNeeded as ErrorCode};
use crate::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
use crate::infer::{self, InferCtxt};
use crate::mir::interpret::ErrorHandled;
use crate::session::DiagnosticMessageId;
use crate::infer::{self, InferCtxt, TyCtxtInferExt};
use crate::traits::object_safety_violations;
use crate::ty::error::ExpectedFound;
use crate::ty::fast_reject;
use crate::ty::fold::TypeFolder;
use crate::ty::SubtypePredicate;
use crate::ty::{
use rustc::mir::interpret::ErrorHandled;
use rustc::session::DiagnosticMessageId;
use rustc::ty::error::ExpectedFound;
use rustc::ty::fast_reject;
use rustc::ty::fold::TypeFolder;
use rustc::ty::SubtypePredicate;
use rustc::ty::{
self, AdtKind, ToPolyTraitRef, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness,
};
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder};
use rustc_hir as hir;

View File

@ -2,8 +2,8 @@ use super::{
ObligationCauseCode, OnUnimplementedDirective, OnUnimplementedNote, PredicateObligation,
};
use crate::infer::InferCtxt;
use crate::ty::subst::Subst;
use crate::ty::{self, GenericParamDefKind};
use rustc::ty::subst::Subst;
use rustc::ty::{self, GenericParamDefKind};
use rustc_hir as hir;
use rustc_hir::def_id::DefId;
use rustc_span::symbol::sym;

View File

@ -6,8 +6,9 @@ use super::{
use crate::infer::InferCtxt;
use crate::traits::error_reporting::suggest_constraining_type_param;
use crate::traits::object_safety::object_safety_violations;
use crate::ty::TypeckTables;
use crate::ty::{self, AdtKind, DefIdTree, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness};
use rustc::ty::TypeckTables;
use rustc::ty::{self, AdtKind, DefIdTree, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness};
use rustc_errors::{
error_code, pluralize, struct_span_err, Applicability, DiagnosticBuilder, Style,
};

View File

@ -1,6 +1,6 @@
use crate::infer::{InferCtxt, ShallowResolver};
use crate::ty::error::ExpectedFound;
use crate::ty::{self, ToPolyTraitRef, Ty, TypeFoldable};
use rustc::ty::error::ExpectedFound;
use rustc::ty::{self, ToPolyTraitRef, Ty, TypeFoldable};
use rustc_data_structures::obligation_forest::ProcessResult;
use rustc_data_structures::obligation_forest::{DoCompleted, Error, ForestObligation};
use rustc_data_structures::obligation_forest::{ObligationForest, ObligationProcessor};

View File

@ -1,8 +1,9 @@
//! Miscellaneous type-system utilities that are too small to deserve their own modules.
use crate::infer::TyCtxtInferExt;
use crate::traits::{self, ObligationCause};
use crate::ty::{self, Ty, TyCtxt, TypeFoldable};
use rustc::ty::{self, Ty, TyCtxt, TypeFoldable};
use rustc_hir as hir;
#[derive(Clone)]

View File

@ -0,0 +1,648 @@
//! Trait Resolution. See the [rustc guide] for more information on how this works.
//!
//! [rustc guide]: https://rust-lang.github.io/rustc-guide/traits/resolution.html
#[allow(dead_code)]
pub mod auto_trait;
mod chalk_fulfill;
pub mod codegen;
mod coherence;
mod engine;
pub mod error_reporting;
mod fulfill;
pub mod misc;
mod object_safety;
mod on_unimplemented;
mod project;
pub mod query;
mod select;
mod specialize;
mod structural_impls;
mod structural_match;
mod util;
pub mod wf;
use crate::infer::outlives::env::OutlivesEnvironment;
use crate::infer::{InferCtxt, SuppressRegionErrors, TyCtxtInferExt};
use rustc::middle::region;
use rustc::ty::error::{ExpectedFound, TypeError};
use rustc::ty::fold::TypeFoldable;
use rustc::ty::subst::{InternalSubsts, SubstsRef};
use rustc::ty::{self, GenericParamDefKind, ToPredicate, Ty, TyCtxt, WithConstness};
use rustc::util::common::ErrorReported;
use rustc_hir as hir;
use rustc_hir::def_id::DefId;
use rustc_span::{Span, DUMMY_SP};
use std::fmt::Debug;
pub use self::FulfillmentErrorCode::*;
pub use self::ObligationCauseCode::*;
pub use self::SelectionError::*;
pub use self::Vtable::*;
pub use self::coherence::{add_placeholder_note, orphan_check, overlapping_impls};
pub use self::coherence::{OrphanCheckErr, OverlapResult};
pub use self::engine::{TraitEngine, TraitEngineExt};
pub use self::fulfill::{FulfillmentContext, PendingPredicateObligation};
pub use self::object_safety::astconv_object_safety_violations;
pub use self::object_safety::is_vtable_safe_method;
pub use self::object_safety::object_safety_violations;
pub use self::object_safety::MethodViolationCode;
pub use self::object_safety::ObjectSafetyViolation;
pub use self::on_unimplemented::{OnUnimplementedDirective, OnUnimplementedNote};
pub use self::project::MismatchedProjectionTypes;
pub use self::project::{
normalize, normalize_projection_type, normalize_to, poly_project_and_unify_type,
};
pub use self::project::{Normalized, ProjectionCache, ProjectionCacheSnapshot, Reveal};
pub use self::select::{EvaluationCache, SelectionCache, SelectionContext};
pub use self::select::{EvaluationResult, IntercrateAmbiguityCause, OverflowError};
pub use self::specialize::find_associated_item;
pub use self::specialize::specialization_graph::FutureCompatOverlapError;
pub use self::specialize::specialization_graph::FutureCompatOverlapErrorKind;
pub use self::specialize::{specialization_graph, translate_substs, OverlapError};
pub use self::structural_match::search_for_structural_match_violation;
pub use self::structural_match::type_marked_structural;
pub use self::structural_match::NonStructuralMatchTy;
pub use self::util::{elaborate_predicates, elaborate_trait_ref, elaborate_trait_refs};
pub use self::util::{expand_trait_aliases, TraitAliasExpander};
pub use self::util::{
get_vtable_index_of_object_method, impl_is_default, impl_item_is_final,
predicate_for_trait_def, upcast_choices,
};
pub use self::util::{
supertrait_def_ids, supertraits, transitive_bounds, SupertraitDefIds, Supertraits,
};
pub use self::chalk_fulfill::{
CanonicalGoal as ChalkCanonicalGoal, FulfillmentContext as ChalkFulfillmentContext,
};
pub use rustc::traits::*;
/// Whether to skip the leak check, as part of a future compatibility warning step.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum SkipLeakCheck {
Yes,
No,
}
impl SkipLeakCheck {
fn is_yes(self) -> bool {
self == SkipLeakCheck::Yes
}
}
/// The "default" for skip-leak-check corresponds to the current
/// behavior (do not skip the leak check) -- not the behavior we are
/// transitioning into.
impl Default for SkipLeakCheck {
fn default() -> Self {
SkipLeakCheck::No
}
}
/// The mode that trait queries run in.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum TraitQueryMode {
// Standard/un-canonicalized queries get accurate
// spans etc. passed in and hence can do reasonable
// error reporting on their own.
Standard,
// Canonicalized queries get dummy spans and hence
// must generally propagate errors to
// pre-canonicalization callsites.
Canonical,
}
/// An `Obligation` represents some trait reference (e.g., `int: Eq`) for
/// which the vtable must be found. The process of finding a vtable is
/// called "resolving" the `Obligation`. This process consists of
/// either identifying an `impl` (e.g., `impl Eq for int`) that
/// provides the required vtable, or else finding a bound that is in
/// scope. The eventual result is usually a `Selection` (defined below).
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct Obligation<'tcx, T> {
/// The reason we have to prove this thing.
pub cause: ObligationCause<'tcx>,
/// The environment in which we should prove this thing.
pub param_env: ty::ParamEnv<'tcx>,
/// The thing we are trying to prove.
pub predicate: T,
/// If we started proving this as a result of trying to prove
/// something else, track the total depth to ensure termination.
/// If this goes over a certain threshold, we abort compilation --
/// in such cases, we can not say whether or not the predicate
/// holds for certain. Stupid halting problem; such a drag.
pub recursion_depth: usize,
}
pub type PredicateObligation<'tcx> = Obligation<'tcx, ty::Predicate<'tcx>>;
pub type TraitObligation<'tcx> = Obligation<'tcx, ty::PolyTraitPredicate<'tcx>>;
// `PredicateObligation` is used a lot. Make sure it doesn't unintentionally get bigger.
#[cfg(target_arch = "x86_64")]
static_assert_size!(PredicateObligation<'_>, 112);
pub type Obligations<'tcx, O> = Vec<Obligation<'tcx, O>>;
pub type PredicateObligations<'tcx> = Vec<PredicateObligation<'tcx>>;
pub type TraitObligations<'tcx> = Vec<TraitObligation<'tcx>>;
pub type Selection<'tcx> = Vtable<'tcx, PredicateObligation<'tcx>>;
pub struct FulfillmentError<'tcx> {
pub obligation: PredicateObligation<'tcx>,
pub code: FulfillmentErrorCode<'tcx>,
/// Diagnostics only: we opportunistically change the `code.span` when we encounter an
/// obligation error caused by a call argument. When this is the case, we also signal that in
/// this field to ensure accuracy of suggestions.
pub points_at_arg_span: bool,
}
#[derive(Clone)]
pub enum FulfillmentErrorCode<'tcx> {
CodeSelectionError(SelectionError<'tcx>),
CodeProjectionError(MismatchedProjectionTypes<'tcx>),
CodeSubtypeError(ExpectedFound<Ty<'tcx>>, TypeError<'tcx>), // always comes from a SubtypePredicate
CodeAmbiguity,
}
/// Creates predicate obligations from the generic bounds.
pub fn predicates_for_generics<'tcx>(
cause: ObligationCause<'tcx>,
param_env: ty::ParamEnv<'tcx>,
generic_bounds: &ty::InstantiatedPredicates<'tcx>,
) -> PredicateObligations<'tcx> {
util::predicates_for_generics(cause, 0, param_env, generic_bounds)
}
/// Determines whether the type `ty` is known to meet `bound` and
/// returns true if so. Returns false if `ty` either does not meet
/// `bound` or is not known to meet bound (note that this is
/// conservative towards *no impl*, which is the opposite of the
/// `evaluate` methods).
pub fn type_known_to_meet_bound_modulo_regions<'a, 'tcx>(
infcx: &InferCtxt<'a, 'tcx>,
param_env: ty::ParamEnv<'tcx>,
ty: Ty<'tcx>,
def_id: DefId,
span: Span,
) -> bool {
debug!(
"type_known_to_meet_bound_modulo_regions(ty={:?}, bound={:?})",
ty,
infcx.tcx.def_path_str(def_id)
);
let trait_ref = ty::TraitRef { def_id, substs: infcx.tcx.mk_substs_trait(ty, &[]) };
let obligation = Obligation {
param_env,
cause: ObligationCause::misc(span, hir::DUMMY_HIR_ID),
recursion_depth: 0,
predicate: trait_ref.without_const().to_predicate(),
};
let result = infcx.predicate_must_hold_modulo_regions(&obligation);
debug!(
"type_known_to_meet_ty={:?} bound={} => {:?}",
ty,
infcx.tcx.def_path_str(def_id),
result
);
if result && (ty.has_infer_types() || ty.has_closure_types()) {
// Because of inference "guessing", selection can sometimes claim
// to succeed while the success requires a guess. To ensure
// this function's result remains infallible, we must confirm
// that guess. While imperfect, I believe this is sound.
// The handling of regions in this area of the code is terrible,
// see issue #29149. We should be able to improve on this with
// NLL.
let mut fulfill_cx = FulfillmentContext::new_ignoring_regions();
// We can use a dummy node-id here because we won't pay any mind
// to region obligations that arise (there shouldn't really be any
// anyhow).
let cause = ObligationCause::misc(span, hir::DUMMY_HIR_ID);
fulfill_cx.register_bound(infcx, param_env, ty, def_id, cause);
// Note: we only assume something is `Copy` if we can
// *definitively* show that it implements `Copy`. Otherwise,
// assume it is move; linear is always ok.
match fulfill_cx.select_all_or_error(infcx) {
Ok(()) => {
debug!(
"type_known_to_meet_bound_modulo_regions: ty={:?} bound={} success",
ty,
infcx.tcx.def_path_str(def_id)
);
true
}
Err(e) => {
debug!(
"type_known_to_meet_bound_modulo_regions: ty={:?} bound={} errors={:?}",
ty,
infcx.tcx.def_path_str(def_id),
e
);
false
}
}
} else {
result
}
}
fn do_normalize_predicates<'tcx>(
tcx: TyCtxt<'tcx>,
region_context: DefId,
cause: ObligationCause<'tcx>,
elaborated_env: ty::ParamEnv<'tcx>,
predicates: Vec<ty::Predicate<'tcx>>,
) -> Result<Vec<ty::Predicate<'tcx>>, ErrorReported> {
debug!(
"do_normalize_predicates(predicates={:?}, region_context={:?}, cause={:?})",
predicates, region_context, cause,
);
let span = cause.span;
tcx.infer_ctxt().enter(|infcx| {
// FIXME. We should really... do something with these region
// obligations. But this call just continues the older
// behavior (i.e., doesn't cause any new bugs), and it would
// take some further refactoring to actually solve them. In
// particular, we would have to handle implied bounds
// properly, and that code is currently largely confined to
// regionck (though I made some efforts to extract it
// out). -nmatsakis
//
// @arielby: In any case, these obligations are checked
// by wfcheck anyway, so I'm not sure we have to check
// them here too, and we will remove this function when
// we move over to lazy normalization *anyway*.
let fulfill_cx = FulfillmentContext::new_ignoring_regions();
let predicates =
match fully_normalize(&infcx, fulfill_cx, cause, elaborated_env, &predicates) {
Ok(predicates) => predicates,
Err(errors) => {
infcx.report_fulfillment_errors(&errors, None, false);
return Err(ErrorReported);
}
};
debug!("do_normalize_predictes: normalized predicates = {:?}", predicates);
let region_scope_tree = region::ScopeTree::default();
// We can use the `elaborated_env` here; the region code only
// cares about declarations like `'a: 'b`.
let outlives_env = OutlivesEnvironment::new(elaborated_env);
infcx.resolve_regions_and_report_errors(
region_context,
&region_scope_tree,
&outlives_env,
SuppressRegionErrors::default(),
);
let predicates = match infcx.fully_resolve(&predicates) {
Ok(predicates) => predicates,
Err(fixup_err) => {
// If we encounter a fixup error, it means that some type
// variable wound up unconstrained. I actually don't know
// if this can happen, and I certainly don't expect it to
// happen often, but if it did happen it probably
// represents a legitimate failure due to some kind of
// unconstrained variable, and it seems better not to ICE,
// all things considered.
tcx.sess.span_err(span, &fixup_err.to_string());
return Err(ErrorReported);
}
};
if predicates.has_local_value() {
// FIXME: shouldn't we, you know, actually report an error here? or an ICE?
Err(ErrorReported)
} else {
Ok(predicates)
}
})
}
// FIXME: this is gonna need to be removed ...
/// Normalizes the parameter environment, reporting errors if they occur.
pub fn normalize_param_env_or_error<'tcx>(
tcx: TyCtxt<'tcx>,
region_context: DefId,
unnormalized_env: ty::ParamEnv<'tcx>,
cause: ObligationCause<'tcx>,
) -> ty::ParamEnv<'tcx> {
// I'm not wild about reporting errors here; I'd prefer to
// have the errors get reported at a defined place (e.g.,
// during typeck). Instead I have all parameter
// environments, in effect, going through this function
// and hence potentially reporting errors. This ensures of
// course that we never forget to normalize (the
// alternative seemed like it would involve a lot of
// manual invocations of this fn -- and then we'd have to
// deal with the errors at each of those sites).
//
// In any case, in practice, typeck constructs all the
// parameter environments once for every fn as it goes,
// and errors will get reported then; so after typeck we
// can be sure that no errors should occur.
debug!(
"normalize_param_env_or_error(region_context={:?}, unnormalized_env={:?}, cause={:?})",
region_context, unnormalized_env, cause
);
let mut predicates: Vec<_> =
util::elaborate_predicates(tcx, unnormalized_env.caller_bounds.to_vec()).collect();
debug!("normalize_param_env_or_error: elaborated-predicates={:?}", predicates);
let elaborated_env = ty::ParamEnv::new(
tcx.intern_predicates(&predicates),
unnormalized_env.reveal,
unnormalized_env.def_id,
);
// HACK: we are trying to normalize the param-env inside *itself*. The problem is that
// normalization expects its param-env to be already normalized, which means we have
// a circularity.
//
// The way we handle this is by normalizing the param-env inside an unnormalized version
// of the param-env, which means that if the param-env contains unnormalized projections,
// we'll have some normalization failures. This is unfortunate.
//
// Lazy normalization would basically handle this by treating just the
// normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
//
// Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
// types, so to make the situation less bad, we normalize all the predicates *but*
// the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
// then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
//
// This works fairly well because trait matching does not actually care about param-env
// TypeOutlives predicates - these are normally used by regionck.
let outlives_predicates: Vec<_> = predicates
.drain_filter(|predicate| match predicate {
ty::Predicate::TypeOutlives(..) => true,
_ => false,
})
.collect();
debug!(
"normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
predicates, outlives_predicates
);
let non_outlives_predicates = match do_normalize_predicates(
tcx,
region_context,
cause.clone(),
elaborated_env,
predicates,
) {
Ok(predicates) => predicates,
// An unnormalized env is better than nothing.
Err(ErrorReported) => {
debug!("normalize_param_env_or_error: errored resolving non-outlives predicates");
return elaborated_env;
}
};
debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates);
// Not sure whether it is better to include the unnormalized TypeOutlives predicates
// here. I believe they should not matter, because we are ignoring TypeOutlives param-env
// predicates here anyway. Keeping them here anyway because it seems safer.
let outlives_env: Vec<_> =
non_outlives_predicates.iter().chain(&outlives_predicates).cloned().collect();
let outlives_env =
ty::ParamEnv::new(tcx.intern_predicates(&outlives_env), unnormalized_env.reveal, None);
let outlives_predicates = match do_normalize_predicates(
tcx,
region_context,
cause,
outlives_env,
outlives_predicates,
) {
Ok(predicates) => predicates,
// An unnormalized env is better than nothing.
Err(ErrorReported) => {
debug!("normalize_param_env_or_error: errored resolving outlives predicates");
return elaborated_env;
}
};
debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates);
let mut predicates = non_outlives_predicates;
predicates.extend(outlives_predicates);
debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
ty::ParamEnv::new(
tcx.intern_predicates(&predicates),
unnormalized_env.reveal,
unnormalized_env.def_id,
)
}
pub fn fully_normalize<'a, 'tcx, T>(
infcx: &InferCtxt<'a, 'tcx>,
mut fulfill_cx: FulfillmentContext<'tcx>,
cause: ObligationCause<'tcx>,
param_env: ty::ParamEnv<'tcx>,
value: &T,
) -> Result<T, Vec<FulfillmentError<'tcx>>>
where
T: TypeFoldable<'tcx>,
{
debug!("fully_normalize_with_fulfillcx(value={:?})", value);
let selcx = &mut SelectionContext::new(infcx);
let Normalized { value: normalized_value, obligations } =
project::normalize(selcx, param_env, cause, value);
debug!(
"fully_normalize: normalized_value={:?} obligations={:?}",
normalized_value, obligations
);
for obligation in obligations {
fulfill_cx.register_predicate_obligation(selcx.infcx(), obligation);
}
debug!("fully_normalize: select_all_or_error start");
fulfill_cx.select_all_or_error(infcx)?;
debug!("fully_normalize: select_all_or_error complete");
let resolved_value = infcx.resolve_vars_if_possible(&normalized_value);
debug!("fully_normalize: resolved_value={:?}", resolved_value);
Ok(resolved_value)
}
/// Normalizes the predicates and checks whether they hold in an empty
/// environment. If this returns false, then either normalize
/// encountered an error or one of the predicates did not hold. Used
/// when creating vtables to check for unsatisfiable methods.
pub fn normalize_and_test_predicates<'tcx>(
tcx: TyCtxt<'tcx>,
predicates: Vec<ty::Predicate<'tcx>>,
) -> bool {
debug!("normalize_and_test_predicates(predicates={:?})", predicates);
let result = tcx.infer_ctxt().enter(|infcx| {
let param_env = ty::ParamEnv::reveal_all();
let mut selcx = SelectionContext::new(&infcx);
let mut fulfill_cx = FulfillmentContext::new();
let cause = ObligationCause::dummy();
let Normalized { value: predicates, obligations } =
normalize(&mut selcx, param_env, cause.clone(), &predicates);
for obligation in obligations {
fulfill_cx.register_predicate_obligation(&infcx, obligation);
}
for predicate in predicates {
let obligation = Obligation::new(cause.clone(), param_env, predicate);
fulfill_cx.register_predicate_obligation(&infcx, obligation);
}
fulfill_cx.select_all_or_error(&infcx).is_ok()
});
debug!("normalize_and_test_predicates(predicates={:?}) = {:?}", predicates, result);
result
}
fn substitute_normalize_and_test_predicates<'tcx>(
tcx: TyCtxt<'tcx>,
key: (DefId, SubstsRef<'tcx>),
) -> bool {
debug!("substitute_normalize_and_test_predicates(key={:?})", key);
let predicates = tcx.predicates_of(key.0).instantiate(tcx, key.1).predicates;
let result = normalize_and_test_predicates(tcx, predicates);
debug!("substitute_normalize_and_test_predicates(key={:?}) = {:?}", key, result);
result
}
/// Given a trait `trait_ref`, iterates the vtable entries
/// that come from `trait_ref`, including its supertraits.
#[inline] // FIXME(#35870): avoid closures being unexported due to `impl Trait`.
fn vtable_methods<'tcx>(
tcx: TyCtxt<'tcx>,
trait_ref: ty::PolyTraitRef<'tcx>,
) -> &'tcx [Option<(DefId, SubstsRef<'tcx>)>] {
debug!("vtable_methods({:?})", trait_ref);
tcx.arena.alloc_from_iter(supertraits(tcx, trait_ref).flat_map(move |trait_ref| {
let trait_methods = tcx
.associated_items(trait_ref.def_id())
.iter()
.filter(|item| item.kind == ty::AssocKind::Method);
// Now list each method's DefId and InternalSubsts (for within its trait).
// If the method can never be called from this object, produce None.
trait_methods.map(move |trait_method| {
debug!("vtable_methods: trait_method={:?}", trait_method);
let def_id = trait_method.def_id;
// Some methods cannot be called on an object; skip those.
if !is_vtable_safe_method(tcx, trait_ref.def_id(), &trait_method) {
debug!("vtable_methods: not vtable safe");
return None;
}
// The method may have some early-bound lifetimes; add regions for those.
let substs = trait_ref.map_bound(|trait_ref| {
InternalSubsts::for_item(tcx, def_id, |param, _| match param.kind {
GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(),
GenericParamDefKind::Type { .. } | GenericParamDefKind::Const => {
trait_ref.substs[param.index as usize]
}
})
});
// The trait type may have higher-ranked lifetimes in it;
// erase them if they appear, so that we get the type
// at some particular call site.
let substs =
tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &substs);
// It's possible that the method relies on where-clauses that
// do not hold for this particular set of type parameters.
// Note that this method could then never be called, so we
// do not want to try and codegen it, in that case (see #23435).
let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs);
if !normalize_and_test_predicates(tcx, predicates.predicates) {
debug!("vtable_methods: predicates do not hold");
return None;
}
Some((def_id, substs))
})
}))
}
impl<'tcx, O> Obligation<'tcx, O> {
pub fn new(
cause: ObligationCause<'tcx>,
param_env: ty::ParamEnv<'tcx>,
predicate: O,
) -> Obligation<'tcx, O> {
Obligation { cause, param_env, recursion_depth: 0, predicate }
}
fn with_depth(
cause: ObligationCause<'tcx>,
recursion_depth: usize,
param_env: ty::ParamEnv<'tcx>,
predicate: O,
) -> Obligation<'tcx, O> {
Obligation { cause, param_env, recursion_depth, predicate }
}
pub fn misc(
span: Span,
body_id: hir::HirId,
param_env: ty::ParamEnv<'tcx>,
trait_ref: O,
) -> Obligation<'tcx, O> {
Obligation::new(ObligationCause::misc(span, body_id), param_env, trait_ref)
}
pub fn with<P>(&self, value: P) -> Obligation<'tcx, P> {
Obligation {
cause: self.cause.clone(),
param_env: self.param_env,
recursion_depth: self.recursion_depth,
predicate: value,
}
}
}
impl<'tcx> FulfillmentError<'tcx> {
fn new(
obligation: PredicateObligation<'tcx>,
code: FulfillmentErrorCode<'tcx>,
) -> FulfillmentError<'tcx> {
FulfillmentError { obligation: obligation, code: code, points_at_arg_span: false }
}
}
impl<'tcx> TraitObligation<'tcx> {
fn self_ty(&self) -> ty::Binder<Ty<'tcx>> {
self.predicate.map_bound(|p| p.self_ty())
}
}
pub fn provide(providers: &mut ty::query::Providers<'_>) {
*providers = ty::query::Providers {
is_object_safe: object_safety::is_object_safe_provider,
specialization_graph_of: specialize::specialization_graph_provider,
specializes: specialize::specializes,
codegen_fulfill_obligation: codegen::codegen_fulfill_obligation,
vtable_methods,
substitute_normalize_and_test_predicates,
..*providers
};
}

View File

@ -10,9 +10,10 @@
use super::elaborate_predicates;
use crate::infer::TyCtxtInferExt;
use crate::traits::{self, Obligation, ObligationCause};
use crate::ty::subst::{InternalSubsts, Subst};
use crate::ty::{self, Predicate, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness};
use rustc::ty::subst::{InternalSubsts, Subst};
use rustc::ty::{self, Predicate, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness};
use rustc_errors::Applicability;
use rustc_hir as hir;
use rustc_hir::def_id::DefId;
@ -552,7 +553,7 @@ fn virtual_call_violation_for_method<'tcx>(
} else {
// Do sanity check to make sure the receiver actually has the layout of a pointer.
use crate::ty::layout::Abi;
use rustc::ty::layout::Abi;
let param_env = tcx.param_env(method.def_id);

View File

@ -1,7 +1,7 @@
use fmt_macros::{Parser, Piece, Position};
use crate::ty::{self, GenericParamDefKind, TyCtxt};
use crate::util::common::ErrorReported;
use rustc::ty::{self, GenericParamDefKind, TyCtxt};
use rustc::util::common::ErrorReported;
use rustc_attr as attr;
use rustc_data_structures::fx::FxHashMap;

View File

@ -14,9 +14,9 @@ use super::{VtableClosureData, VtableFnPointerData, VtableGeneratorData, VtableI
use crate::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
use crate::infer::{InferCtxt, InferOk, LateBoundRegionConversionTime};
use crate::ty::fold::{TypeFoldable, TypeFolder};
use crate::ty::subst::{InternalSubsts, Subst};
use crate::ty::{self, ToPolyTraitRef, ToPredicate, Ty, TyCtxt, WithConstness};
use rustc::ty::fold::{TypeFoldable, TypeFolder};
use rustc::ty::subst::{InternalSubsts, Subst};
use rustc::ty::{self, ToPolyTraitRef, ToPredicate, Ty, TyCtxt, WithConstness};
use rustc_data_structures::snapshot_map::{Snapshot, SnapshotMap};
use rustc_hir::def_id::DefId;
use rustc_span::symbol::sym;

View File

@ -12,4 +12,4 @@ pub mod normalize;
pub mod outlives_bounds;
pub mod type_op;
pub use rustc::traits::types::query::*;
pub use rustc::traits::query::*;

View File

@ -7,9 +7,9 @@ use crate::infer::canonical::OriginalQueryValues;
use crate::infer::{InferCtxt, InferOk};
use crate::traits::project::Normalized;
use crate::traits::{Obligation, ObligationCause, PredicateObligation, Reveal};
use crate::ty::fold::{TypeFoldable, TypeFolder};
use crate::ty::subst::Subst;
use crate::ty::{self, Ty, TyCtxt};
use rustc::ty::fold::{TypeFoldable, TypeFolder};
use rustc::ty::subst::Subst;
use rustc::ty::{self, Ty, TyCtxt};
use super::NoSolution;

View File

@ -2,7 +2,7 @@ use crate::infer::canonical::OriginalQueryValues;
use crate::infer::InferCtxt;
use crate::traits::query::NoSolution;
use crate::traits::{FulfillmentContext, ObligationCause, TraitEngine, TraitEngineExt};
use crate::ty::{self, Ty};
use rustc::ty::{self, Ty};
use rustc_hir as hir;
use rustc_span::source_map::Span;

View File

@ -1,6 +1,6 @@
use crate::infer::canonical::{Canonicalized, CanonicalizedQueryResponse};
use crate::traits::query::Fallible;
use crate::ty::{ParamEnvAnd, TyCtxt};
use rustc::ty::{ParamEnvAnd, TyCtxt};
pub use rustc::traits::query::type_op::Eq;

View File

@ -1,7 +1,7 @@
use crate::infer::canonical::{Canonicalized, CanonicalizedQueryResponse};
use crate::traits::query::outlives_bounds::OutlivesBound;
use crate::traits::query::Fallible;
use crate::ty::{ParamEnvAnd, Ty, TyCtxt};
use rustc::ty::{ParamEnvAnd, Ty, TyCtxt};
#[derive(Clone, Debug, HashStable, TypeFoldable, Lift)]
pub struct ImpliedOutlivesBounds<'tcx> {

View File

@ -4,8 +4,8 @@ use crate::infer::canonical::{
use crate::infer::{InferCtxt, InferOk};
use crate::traits::query::Fallible;
use crate::traits::ObligationCause;
use crate::ty::fold::TypeFoldable;
use crate::ty::{ParamEnvAnd, TyCtxt};
use rustc::ty::fold::TypeFoldable;
use rustc::ty::{ParamEnvAnd, TyCtxt};
use std::fmt;
use std::rc::Rc;
@ -19,7 +19,7 @@ pub mod prove_predicate;
use self::prove_predicate::ProvePredicate;
pub mod subtype;
pub use crate::traits::types::query::type_op::*;
pub use rustc::traits::query::type_op::*;
/// "Type ops" are used in NLL to perform some particular action and
/// extract out the resulting region constraints (or an error if it

View File

@ -1,7 +1,7 @@
use crate::infer::canonical::{Canonicalized, CanonicalizedQueryResponse};
use crate::traits::query::Fallible;
use crate::ty::fold::TypeFoldable;
use crate::ty::{self, Lift, ParamEnvAnd, Ty, TyCtxt};
use rustc::ty::fold::TypeFoldable;
use rustc::ty::{self, Lift, ParamEnvAnd, Ty, TyCtxt};
use std::fmt;
pub use rustc::traits::query::type_op::Normalize;

View File

@ -1,7 +1,7 @@
use crate::infer::canonical::{Canonicalized, CanonicalizedQueryResponse};
use crate::traits::query::dropck_outlives::{trivial_dropck_outlives, DropckOutlivesResult};
use crate::traits::query::Fallible;
use crate::ty::{ParamEnvAnd, Ty, TyCtxt};
use rustc::ty::{ParamEnvAnd, Ty, TyCtxt};
#[derive(Copy, Clone, Debug, HashStable, TypeFoldable, Lift)]
pub struct DropckOutlives<'tcx> {

View File

@ -1,6 +1,6 @@
use crate::infer::canonical::{Canonicalized, CanonicalizedQueryResponse};
use crate::traits::query::Fallible;
use crate::ty::{ParamEnvAnd, Predicate, TyCtxt};
use rustc::ty::{ParamEnvAnd, Predicate, TyCtxt};
pub use rustc::traits::query::type_op::ProvePredicate;

View File

@ -1,6 +1,6 @@
use crate::infer::canonical::{Canonicalized, CanonicalizedQueryResponse};
use crate::traits::query::Fallible;
use crate::ty::{ParamEnvAnd, TyCtxt};
use rustc::ty::{ParamEnvAnd, TyCtxt};
pub use rustc::traits::query::type_op::Subtype;

File diff suppressed because it is too large Load Diff

View File

@ -10,13 +10,14 @@
//! [rustc guide]: https://rust-lang.github.io/rustc-guide/traits/specialization.html
pub mod specialization_graph;
use specialization_graph::GraphExt;
use crate::infer::{InferCtxt, InferOk};
use crate::infer::{InferCtxt, InferOk, TyCtxtInferExt};
use crate::traits::select::IntercrateAmbiguityCause;
use crate::traits::{self, coherence, FutureCompatOverlapErrorKind, ObligationCause, TraitEngine};
use crate::ty::subst::{InternalSubsts, Subst, SubstsRef};
use crate::ty::{self, TyCtxt, TypeFoldable};
use rustc::lint::LintDiagnosticBuilder;
use rustc::ty::subst::{InternalSubsts, Subst, SubstsRef};
use rustc::ty::{self, TyCtxt, TypeFoldable};
use rustc_data_structures::fx::FxHashSet;
use rustc_errors::struct_span_err;
use rustc_hir::def_id::DefId;

View File

@ -5,7 +5,7 @@ use rustc::ty::fast_reject::{self, SimplifiedType};
use rustc::ty::{self, TyCtxt, TypeFoldable};
use rustc_hir::def_id::DefId;
pub use rustc::traits::types::specialization_graph::*;
pub use rustc::traits::specialization_graph::*;
#[derive(Copy, Clone, Debug)]
pub enum FutureCompatOverlapErrorKind {
@ -31,7 +31,19 @@ enum Inserted {
ShouldRecurseOn(DefId),
}
impl<'tcx> Children {
trait ChildrenExt {
fn insert_blindly(&mut self, tcx: TyCtxt<'tcx>, impl_def_id: DefId);
fn remove_existing(&mut self, tcx: TyCtxt<'tcx>, impl_def_id: DefId);
fn insert(
&mut self,
tcx: TyCtxt<'tcx>,
impl_def_id: DefId,
simplified_self: Option<SimplifiedType>,
) -> Result<Inserted, OverlapError>;
}
impl ChildrenExt for Children {
/// Insert an impl into this set of children without comparing to any existing impls.
fn insert_blindly(&mut self, tcx: TyCtxt<'tcx>, impl_def_id: DefId) {
let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap();
@ -76,8 +88,8 @@ impl<'tcx> Children {
debug!("insert(impl_def_id={:?}, simplified_self={:?})", impl_def_id, simplified_self,);
let possible_siblings = match simplified_self {
Some(st) => PotentialSiblings::Filtered(self.filtered(st)),
None => PotentialSiblings::Unfiltered(self.iter()),
Some(st) => PotentialSiblings::Filtered(filtered_children(self, st)),
None => PotentialSiblings::Unfiltered(iter_children(self)),
};
for possible_sibling in possible_siblings {
@ -199,16 +211,19 @@ impl<'tcx> Children {
self.insert_blindly(tcx, impl_def_id);
Ok(Inserted::BecameNewSibling(last_lint))
}
}
fn iter(&mut self) -> impl Iterator<Item = DefId> + '_ {
let nonblanket = self.nonblanket_impls.iter_mut().flat_map(|(_, v)| v.iter());
self.blanket_impls.iter().chain(nonblanket).cloned()
}
fn iter_children(children: &mut Children) -> impl Iterator<Item = DefId> + '_ {
let nonblanket = children.nonblanket_impls.iter_mut().flat_map(|(_, v)| v.iter());
children.blanket_impls.iter().chain(nonblanket).cloned()
}
fn filtered(&mut self, st: SimplifiedType) -> impl Iterator<Item = DefId> + '_ {
let nonblanket = self.nonblanket_impls.entry(st).or_default().iter();
self.blanket_impls.iter().chain(nonblanket).cloned()
}
fn filtered_children(
children: &mut Children,
st: SimplifiedType,
) -> impl Iterator<Item = DefId> + '_ {
let nonblanket = children.nonblanket_impls.entry(st).or_default().iter();
children.blanket_impls.iter().chain(nonblanket).cloned()
}
// A custom iterator used by Children::insert
@ -236,11 +251,25 @@ where
}
}
impl<'tcx> Graph {
pub trait GraphExt {
/// Insert a local impl into the specialization graph. If an existing impl
/// conflicts with it (has overlap, but neither specializes the other),
/// information about the area of overlap is returned in the `Err`.
pub fn insert(
fn insert(
&mut self,
tcx: TyCtxt<'tcx>,
impl_def_id: DefId,
) -> Result<Option<FutureCompatOverlapError>, OverlapError>;
/// Insert cached metadata mapping from a child impl back to its parent.
fn record_impl_from_cstore(&mut self, tcx: TyCtxt<'tcx>, parent: DefId, child: DefId);
}
impl GraphExt for Graph {
/// Insert a local impl into the specialization graph. If an existing impl
/// conflicts with it (has overlap, but neither specializes the other),
/// information about the area of overlap is returned in the `Err`.
fn insert(
&mut self,
tcx: TyCtxt<'tcx>,
impl_def_id: DefId,
@ -337,7 +366,7 @@ impl<'tcx> Graph {
}
/// Insert cached metadata mapping from a child impl back to its parent.
pub fn record_impl_from_cstore(&mut self, tcx: TyCtxt<'tcx>, parent: DefId, child: DefId) {
fn record_impl_from_cstore(&mut self, tcx: TyCtxt<'tcx>, parent: DefId, child: DefId) {
if self.parent.insert(child, parent).is_some() {
bug!(
"When recording an impl from the crate store, information about its parent \

View File

@ -0,0 +1,71 @@
use crate::traits;
use crate::traits::project::Normalized;
use rustc::ty;
use rustc::ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
use std::fmt;
// Structural impls for the structs in `traits`.
impl<'tcx, T: fmt::Debug> fmt::Debug for Normalized<'tcx, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Normalized({:?}, {:?})", self.value, self.obligations)
}
}
impl<'tcx, O: fmt::Debug> fmt::Debug for traits::Obligation<'tcx, O> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if ty::tls::with(|tcx| tcx.sess.verbose()) {
write!(
f,
"Obligation(predicate={:?}, cause={:?}, param_env={:?}, depth={})",
self.predicate, self.cause, self.param_env, self.recursion_depth
)
} else {
write!(f, "Obligation(predicate={:?}, depth={})", self.predicate, self.recursion_depth)
}
}
}
impl<'tcx> fmt::Debug for traits::FulfillmentError<'tcx> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "FulfillmentError({:?},{:?})", self.obligation, self.code)
}
}
impl<'tcx> fmt::Debug for traits::FulfillmentErrorCode<'tcx> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
super::CodeSelectionError(ref e) => write!(f, "{:?}", e),
super::CodeProjectionError(ref e) => write!(f, "{:?}", e),
super::CodeSubtypeError(ref a, ref b) => {
write!(f, "CodeSubtypeError({:?}, {:?})", a, b)
}
super::CodeAmbiguity => write!(f, "Ambiguity"),
}
}
}
impl<'tcx> fmt::Debug for traits::MismatchedProjectionTypes<'tcx> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "MismatchedProjectionTypes({:?})", self.err)
}
}
///////////////////////////////////////////////////////////////////////////
// TypeFoldable implementations.
impl<'tcx, O: TypeFoldable<'tcx>> TypeFoldable<'tcx> for traits::Obligation<'tcx, O> {
fn super_fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> Self {
traits::Obligation {
cause: self.cause.clone(),
recursion_depth: self.recursion_depth,
predicate: self.predicate.fold_with(folder),
param_env: self.param_env.fold_with(folder),
}
}
fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> bool {
self.predicate.visit_with(visitor)
}
}

View File

@ -1,9 +1,8 @@
use crate::ty::fold::{TypeFoldable, TypeVisitor};
use crate::ty::{self, AdtDef, Ty, TyCtxt};
use crate::infer::{InferCtxt, TyCtxtInferExt};
use crate::traits::ObligationCause;
use crate::traits::{self, ConstPatternStructural, TraitEngine};
use rustc::infer::InferCtxt;
use rustc::traits::ObligationCause;
use rustc::traits::{self, ConstPatternStructural, TraitEngine};
use rustc::ty::{self, AdtDef, Ty, TyCtxt, TypeFoldable, TypeVisitor};
use rustc_data_structures::fx::FxHashSet;
use rustc_hir as hir;
use rustc_span::Span;

View File

@ -1,10 +1,11 @@
use rustc_errors::DiagnosticBuilder;
use rustc_span::Span;
use smallvec::smallvec;
use smallvec::SmallVec;
use crate::ty::outlives::Component;
use crate::ty::subst::{GenericArg, Subst, SubstsRef};
use crate::ty::{self, ToPolyTraitRef, ToPredicate, Ty, TyCtxt, WithConstness};
use rustc::ty::outlives::Component;
use rustc::ty::subst::{GenericArg, Subst, SubstsRef};
use rustc::ty::{self, ToPolyTraitRef, ToPredicate, Ty, TyCtxt, WithConstness};
use rustc_data_structures::fx::FxHashSet;
use rustc_hir as hir;
use rustc_hir::def_id::DefId;

View File

@ -1,9 +1,9 @@
use crate::infer::opaque_types::required_region_bounds;
use crate::infer::InferCtxt;
use crate::middle::lang_items;
use crate::traits::{self, AssocTypeBoundData};
use crate::ty::subst::SubstsRef;
use crate::ty::{self, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness};
use rustc::middle::lang_items;
use rustc::ty::subst::SubstsRef;
use rustc::ty::{self, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness};
use rustc_hir as hir;
use rustc_hir::def_id::DefId;
use rustc_span::symbol::{kw, Ident};

View File

@ -31,6 +31,7 @@ rustc_codegen_ssa = { path = "../librustc_codegen_ssa" }
rustc_codegen_utils = { path = "../librustc_codegen_utils" }
rustc_codegen_llvm = { path = "../librustc_codegen_llvm", optional = true }
rustc_hir = { path = "../librustc_hir" }
rustc_infer = { path = "../librustc_infer" }
rustc_metadata = { path = "../librustc_metadata" }
rustc_mir = { path = "../librustc_mir" }
rustc_mir_build = { path = "../librustc_mir_build" }

View File

@ -13,7 +13,6 @@ use rustc::session::config::{self, CrateType, Input, OutputFilenames, OutputType
use rustc::session::config::{PpMode, PpSourceMode};
use rustc::session::search_paths::PathKind;
use rustc::session::Session;
use rustc::traits;
use rustc::ty::steal::Steal;
use rustc::ty::{self, GlobalCtxt, ResolverOutputs, TyCtxt};
use rustc::util::common::ErrorReported;
@ -26,6 +25,7 @@ use rustc_errors::PResult;
use rustc_expand::base::ExtCtxt;
use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
use rustc_hir::Crate;
use rustc_infer::traits;
use rustc_lint::LintStore;
use rustc_mir as mir;
use rustc_mir_build as mir_build;

View File

@ -23,3 +23,4 @@ rustc_data_structures = { path = "../librustc_data_structures" }
rustc_feature = { path = "../librustc_feature" }
rustc_index = { path = "../librustc_index" }
rustc_session = { path = "../librustc_session" }
rustc_infer = { path = "../librustc_infer" }

View File

@ -24,7 +24,6 @@
use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
use rustc::hir::map::Map;
use rustc::lint::LintDiagnosticBuilder;
use rustc::traits::misc::can_type_implement_copy;
use rustc::ty::{self, layout::VariantIdx, Ty, TyCtxt};
use rustc_ast_pretty::pprust::{self, expr_to_string};
use rustc_data_structures::fx::FxHashSet;
@ -36,6 +35,7 @@ use rustc_hir::def::{DefKind, Res};
use rustc_hir::def_id::DefId;
use rustc_hir::{GenericParamKind, PatKind};
use rustc_hir::{HirIdSet, Node};
use rustc_infer::traits::misc::can_type_implement_copy;
use rustc_session::lint::FutureIncompatibleInfo;
use rustc_span::edition::Edition;
use rustc_span::source_map::Spanned;

Some files were not shown because too many files have changed in this diff Show More