rust/compiler/rustc_trait_selection/src/infer.rs

223 lines
7.8 KiB
Rust
Raw Normal View History

2021-07-06 09:38:15 +00:00
use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
2020-02-22 10:44:18 +00:00
use crate::traits::query::outlives_bounds::InferCtxtExt as _;
use crate::traits::{self, TraitEngine, TraitEngineExt};
2020-03-29 15:19:48 +00:00
use rustc_hir as hir;
2021-07-06 09:38:15 +00:00
use rustc_hir::def_id::DefId;
use rustc_hir::lang_items::LangItem;
2020-03-29 15:19:48 +00:00
use rustc_infer::infer::outlives::env::OutlivesEnvironment;
use rustc_infer::traits::ObligationCause;
2020-03-29 14:41:09 +00:00
use rustc_middle::arena::ArenaAllocatable;
use rustc_middle::infer::canonical::{Canonical, CanonicalizedQueryResponse, QueryResponse};
use rustc_middle::traits::query::Fallible;
2021-07-06 09:38:15 +00:00
use rustc_middle::ty::subst::SubstsRef;
use rustc_middle::ty::ToPredicate;
use rustc_middle::ty::WithConstness;
2020-03-29 14:41:09 +00:00
use rustc_middle::ty::{self, Ty, TypeFoldable};
2020-02-22 10:44:18 +00:00
use rustc_span::{Span, DUMMY_SP};
use std::fmt::Debug;
pub use rustc_infer::infer::*;
pub trait InferCtxtExt<'tcx> {
fn type_is_copy_modulo_regions(
&self,
param_env: ty::ParamEnv<'tcx>,
ty: Ty<'tcx>,
span: Span,
) -> bool;
fn partially_normalize_associated_types_in<T>(
&self,
Add initial implementation of HIR-based WF checking for diagnostics During well-formed checking, we walk through all types 'nested' in generic arguments. For example, WF-checking `Option<MyStruct<u8>>` will cause us to check `MyStruct<u8>` and `u8`. However, this is done on a `rustc_middle::ty::Ty`, which has no span information. As a result, any errors that occur will have a very general span (e.g. the definintion of an associated item). This becomes a problem when macros are involved. In general, an associated type like `type MyType = Option<MyStruct<u8>>;` may have completely different spans for each nested type in the HIR. Using the span of the entire associated item might end up pointing to a macro invocation, even though a user-provided span is available in one of the nested types. This PR adds a framework for HIR-based well formed checking. This check is only run during error reporting, and is used to obtain a more precise span for an existing error. This is accomplished by individually checking each 'nested' type in the HIR for the type, allowing us to find the most-specific type (and span) that produces a given error. The majority of the changes are to the error-reporting code. However, some of the general trait code is modified to pass through more information. Since this has no soundness implications, I've implemented a minimal version to begin with, which can be extended over time. In particular, this only works for HIR items with a corresponding `DefId` (e.g. it will not work for WF-checking performed within function bodies).
2021-04-04 20:55:39 +00:00
cause: ObligationCause<'tcx>,
2020-02-22 10:44:18 +00:00
param_env: ty::ParamEnv<'tcx>,
2020-10-24 00:21:18 +00:00
value: T,
2020-02-22 10:44:18 +00:00
) -> InferOk<'tcx, T>
where
T: TypeFoldable<'tcx>;
2021-07-06 09:38:15 +00:00
/// Check whether a `ty` implements given trait(trait_def_id).
/// The inputs are:
///
/// - the def-id of the trait
/// - the self type
/// - the *other* type parameters of the trait, excluding the self-type
/// - the parameter environment
fn type_implements_trait(
&self,
trait_def_id: DefId,
ty: Ty<'tcx>,
params: SubstsRef<'tcx>,
param_env: ty::ParamEnv<'tcx>,
) -> traits::EvaluationResult;
}
2020-02-22 10:44:18 +00:00
impl<'cx, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'cx, 'tcx> {
fn type_is_copy_modulo_regions(
&self,
param_env: ty::ParamEnv<'tcx>,
ty: Ty<'tcx>,
span: Span,
) -> bool {
2020-10-24 00:21:18 +00:00
let ty = self.resolve_vars_if_possible(ty);
2020-02-22 10:44:18 +00:00
if !(param_env, ty).needs_infer() {
return ty.is_copy_modulo_regions(self.tcx.at(span), param_env);
2020-02-22 10:44:18 +00:00
}
let copy_def_id = self.tcx.require_lang_item(LangItem::Copy, None);
2020-02-22 10:44:18 +00:00
// This can get called from typeck (by euv), and `moves_by_default`
// rightly refuses to work with inference variables, but
// moves_by_default has a cache, which we want to use in other
// cases.
traits::type_known_to_meet_bound_modulo_regions(self, param_env, ty, copy_def_id, span)
}
/// Normalizes associated types in `value`, potentially returning
/// new obligations that must further be processed.
fn partially_normalize_associated_types_in<T>(
&self,
Add initial implementation of HIR-based WF checking for diagnostics During well-formed checking, we walk through all types 'nested' in generic arguments. For example, WF-checking `Option<MyStruct<u8>>` will cause us to check `MyStruct<u8>` and `u8`. However, this is done on a `rustc_middle::ty::Ty`, which has no span information. As a result, any errors that occur will have a very general span (e.g. the definintion of an associated item). This becomes a problem when macros are involved. In general, an associated type like `type MyType = Option<MyStruct<u8>>;` may have completely different spans for each nested type in the HIR. Using the span of the entire associated item might end up pointing to a macro invocation, even though a user-provided span is available in one of the nested types. This PR adds a framework for HIR-based well formed checking. This check is only run during error reporting, and is used to obtain a more precise span for an existing error. This is accomplished by individually checking each 'nested' type in the HIR for the type, allowing us to find the most-specific type (and span) that produces a given error. The majority of the changes are to the error-reporting code. However, some of the general trait code is modified to pass through more information. Since this has no soundness implications, I've implemented a minimal version to begin with, which can be extended over time. In particular, this only works for HIR items with a corresponding `DefId` (e.g. it will not work for WF-checking performed within function bodies).
2021-04-04 20:55:39 +00:00
cause: ObligationCause<'tcx>,
2020-02-22 10:44:18 +00:00
param_env: ty::ParamEnv<'tcx>,
2020-10-24 00:21:18 +00:00
value: T,
2020-02-22 10:44:18 +00:00
) -> InferOk<'tcx, T>
where
T: TypeFoldable<'tcx>,
{
debug!("partially_normalize_associated_types_in(value={:?})", value);
let mut selcx = traits::SelectionContext::new(self);
let traits::Normalized { value, obligations } =
traits::normalize(&mut selcx, param_env, cause, value);
debug!(
"partially_normalize_associated_types_in: result={:?} predicates={:?}",
value, obligations
);
InferOk { value, obligations }
}
2021-07-06 09:38:15 +00:00
fn type_implements_trait(
&self,
trait_def_id: DefId,
ty: Ty<'tcx>,
params: SubstsRef<'tcx>,
param_env: ty::ParamEnv<'tcx>,
) -> traits::EvaluationResult {
debug!(
"type_implements_trait: trait_def_id={:?}, type={:?}, params={:?}, param_env={:?}",
trait_def_id, ty, params, param_env
);
let trait_ref =
ty::TraitRef { def_id: trait_def_id, substs: self.tcx.mk_substs_trait(ty, params) };
let obligation = traits::Obligation {
cause: traits::ObligationCause::dummy(),
param_env,
recursion_depth: 0,
predicate: trait_ref.without_const().to_predicate(self.tcx),
};
self.evaluate_obligation_no_overflow(&obligation)
}
2020-02-22 10:44:18 +00:00
}
pub trait InferCtxtBuilderExt<'tcx> {
fn enter_canonical_trait_query<K, R>(
&mut self,
canonical_key: &Canonical<'tcx, K>,
operation: impl FnOnce(&InferCtxt<'_, 'tcx>, &mut dyn TraitEngine<'tcx>, K) -> Fallible<R>,
) -> Fallible<CanonicalizedQueryResponse<'tcx, R>>
where
K: TypeFoldable<'tcx>,
R: Debug + TypeFoldable<'tcx>,
Canonical<'tcx, QueryResponse<'tcx, R>>: ArenaAllocatable<'tcx>;
2020-02-22 10:44:18 +00:00
}
impl<'tcx> InferCtxtBuilderExt<'tcx> for InferCtxtBuilder<'tcx> {
/// The "main method" for a canonicalized trait query. Given the
/// canonical key `canonical_key`, this method will create a new
/// inference context, instantiate the key, and run your operation
/// `op`. The operation should yield up a result (of type `R`) as
/// well as a set of trait obligations that must be fully
/// satisfied. These obligations will be processed and the
/// canonical result created.
///
/// Returns `NoSolution` in the event of any error.
///
/// (It might be mildly nicer to implement this on `TyCtxt`, and
/// not `InferCtxtBuilder`, but that is a bit tricky right now.
/// In part because we would need a `for<'tcx>` sort of
/// bound for the closure and in part because it is convenient to
/// have `'tcx` be free on this function so that we can talk about
/// `K: TypeFoldable<'tcx>`.)
fn enter_canonical_trait_query<K, R>(
&mut self,
canonical_key: &Canonical<'tcx, K>,
operation: impl FnOnce(&InferCtxt<'_, 'tcx>, &mut dyn TraitEngine<'tcx>, K) -> Fallible<R>,
) -> Fallible<CanonicalizedQueryResponse<'tcx, R>>
where
K: TypeFoldable<'tcx>,
R: Debug + TypeFoldable<'tcx>,
Canonical<'tcx, QueryResponse<'tcx, R>>: ArenaAllocatable<'tcx>,
2020-02-22 10:44:18 +00:00
{
self.enter_with_canonical(
DUMMY_SP,
canonical_key,
|ref infcx, key, canonical_inference_vars| {
let mut fulfill_cx = <dyn TraitEngine<'_>>::new(infcx.tcx);
2020-02-22 10:44:18 +00:00
let value = operation(infcx, &mut *fulfill_cx, key)?;
infcx.make_canonicalized_query_response(
canonical_inference_vars,
value,
&mut *fulfill_cx,
)
},
)
}
}
pub trait OutlivesEnvironmentExt<'tcx> {
fn add_implied_bounds(
&mut self,
infcx: &InferCtxt<'a, 'tcx>,
fn_sig_tys: &[Ty<'tcx>],
body_id: hir::HirId,
span: Span,
);
}
impl<'tcx> OutlivesEnvironmentExt<'tcx> for OutlivesEnvironment<'tcx> {
/// This method adds "implied bounds" into the outlives environment.
/// Implied bounds are outlives relationships that we can deduce
/// on the basis that certain types must be well-formed -- these are
/// either the types that appear in the function signature or else
/// the input types to an impl. For example, if you have a function
/// like
///
/// ```
/// fn foo<'a, 'b, T>(x: &'a &'b [T]) { }
/// ```
///
/// we can assume in the caller's body that `'b: 'a` and that `T:
/// 'b` (and hence, transitively, that `T: 'a`). This method would
/// add those assumptions into the outlives-environment.
///
2020-12-28 17:15:16 +00:00
/// Tests: `src/test/ui/regions/regions-free-region-ordering-*.rs`
2020-02-22 10:44:18 +00:00
fn add_implied_bounds(
&mut self,
infcx: &InferCtxt<'a, 'tcx>,
fn_sig_tys: &[Ty<'tcx>],
body_id: hir::HirId,
span: Span,
) {
debug!("add_implied_bounds()");
for &ty in fn_sig_tys {
2020-10-24 00:21:18 +00:00
let ty = infcx.resolve_vars_if_possible(ty);
2020-02-22 10:44:18 +00:00
debug!("add_implied_bounds: ty = {}", ty);
let implied_bounds = infcx.implied_outlives_bounds(self.param_env, body_id, ty, span);
self.add_outlives_bounds(Some(infcx), implied_bounds)
}
}
}