1 //! Trait Resolution. See the [rustc dev guide] for more information on how this works.
3 //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html
8 pub mod const_evaluatable;
10 pub mod error_reporting;
14 pub mod outlives_bounds;
24 use crate::infer::outlives::env::OutlivesEnvironment;
25 use crate::infer::{InferCtxt, TyCtxtInferExt};
26 use crate::traits::error_reporting::TypeErrCtxtExt as _;
27 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
28 use rustc_errors::ErrorGuaranteed;
29 use rustc_middle::ty::fold::TypeFoldable;
30 use rustc_middle::ty::visit::TypeVisitable;
31 use rustc_middle::ty::{self, DefIdTree, ToPredicate, Ty, TyCtxt, TypeSuperVisitable};
32 use rustc_middle::ty::{InternalSubsts, SubstsRef};
33 use rustc_span::def_id::{DefId, CRATE_DEF_ID};
37 use std::ops::ControlFlow;
39 pub use self::FulfillmentErrorCode::*;
40 pub use self::ImplSource::*;
41 pub use self::ObligationCauseCode::*;
42 pub use self::SelectionError::*;
44 pub use self::coherence::{add_placeholder_note, orphan_check, overlapping_impls};
45 pub use self::coherence::{OrphanCheckErr, OverlapResult};
46 pub use self::engine::{ObligationCtxt, TraitEngineExt};
47 pub use self::fulfill::{FulfillmentContext, PendingPredicateObligation};
48 pub use self::object_safety::astconv_object_safety_violations;
49 pub use self::object_safety::is_vtable_safe_method;
50 pub use self::object_safety::MethodViolationCode;
51 pub use self::object_safety::ObjectSafetyViolation;
52 pub use self::project::{normalize_projection_type, NormalizeExt};
53 pub use self::select::{EvaluationCache, SelectionCache, SelectionContext};
54 pub use self::select::{EvaluationResult, IntercrateAmbiguityCause, OverflowError};
55 pub use self::specialize::specialization_graph::FutureCompatOverlapError;
56 pub use self::specialize::specialization_graph::FutureCompatOverlapErrorKind;
57 pub use self::specialize::{specialization_graph, translate_substs, OverlapError};
58 pub use self::structural_match::{
59 search_for_adt_const_param_violation, search_for_structural_match_violation,
62 elaborate_obligations, elaborate_predicates, elaborate_predicates_with_span,
63 elaborate_trait_ref, elaborate_trait_refs,
65 pub use self::util::{expand_trait_aliases, TraitAliasExpander};
67 get_vtable_index_of_object_method, impl_item_is_final, predicate_for_trait_def, upcast_choices,
70 supertrait_def_ids, supertraits, transitive_bounds, transitive_bounds_that_define_assoc_type,
71 SupertraitDefIds, Supertraits,
74 pub use self::chalk_fulfill::FulfillmentContext as ChalkFulfillmentContext;
76 pub use rustc_infer::traits::*;
78 /// Whether to skip the leak check, as part of a future compatibility warning step.
80 /// The "default" for skip-leak-check corresponds to the current
81 /// behavior (do not skip the leak check) -- not the behavior we are
82 /// transitioning into.
83 #[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
84 pub enum SkipLeakCheck {
91 fn is_yes(self) -> bool {
92 self == SkipLeakCheck::Yes
96 /// The mode that trait queries run in.
97 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
98 pub enum TraitQueryMode {
99 /// Standard/un-canonicalized queries get accurate
100 /// spans etc. passed in and hence can do reasonable
101 /// error reporting on their own.
103 /// Canonical queries get dummy spans and hence
104 /// must generally propagate errors to
105 /// pre-canonicalization callsites.
109 /// Creates predicate obligations from the generic bounds.
110 #[instrument(level = "debug", skip(cause, param_env))]
111 pub fn predicates_for_generics<'tcx>(
112 cause: impl Fn(usize, Span) -> ObligationCause<'tcx>,
113 param_env: ty::ParamEnv<'tcx>,
114 generic_bounds: ty::InstantiatedPredicates<'tcx>,
115 ) -> impl Iterator<Item = PredicateObligation<'tcx>> {
116 generic_bounds.into_iter().enumerate().map(move |(idx, (predicate, span))| Obligation {
117 cause: cause(idx, span),
124 /// Determines whether the type `ty` is known to meet `bound` and
125 /// returns true if so. Returns false if `ty` either does not meet
126 /// `bound` or is not known to meet bound (note that this is
127 /// conservative towards *no impl*, which is the opposite of the
128 /// `evaluate` methods).
129 pub fn type_known_to_meet_bound_modulo_regions<'tcx>(
130 infcx: &InferCtxt<'tcx>,
131 param_env: ty::ParamEnv<'tcx>,
136 let trait_ref = ty::Binder::dummy(infcx.tcx.mk_trait_ref(def_id, [ty]));
137 pred_known_to_hold_modulo_regions(infcx, param_env, trait_ref.without_const(), span)
140 #[instrument(level = "debug", skip(infcx, param_env, span, pred), ret)]
141 fn pred_known_to_hold_modulo_regions<'tcx>(
142 infcx: &InferCtxt<'tcx>,
143 param_env: ty::ParamEnv<'tcx>,
144 pred: impl ToPredicate<'tcx> + TypeVisitable<'tcx>,
147 let has_non_region_infer = pred.has_non_region_infer();
148 let obligation = Obligation {
150 // We can use a dummy node-id here because we won't pay any mind
151 // to region obligations that arise (there shouldn't really be any
153 cause: ObligationCause::misc(span, CRATE_DEF_ID),
155 predicate: pred.to_predicate(infcx.tcx),
158 let result = infcx.predicate_must_hold_modulo_regions(&obligation);
161 if result && has_non_region_infer {
162 // Because of inference "guessing", selection can sometimes claim
163 // to succeed while the success requires a guess. To ensure
164 // this function's result remains infallible, we must confirm
165 // that guess. While imperfect, I believe this is sound.
167 // FIXME(@lcnr): this function doesn't seem right.
169 // The handling of regions in this area of the code is terrible,
170 // see issue #29149. We should be able to improve on this with
172 let errors = fully_solve_obligation(infcx, obligation);
186 #[instrument(level = "debug", skip(tcx, elaborated_env))]
187 fn do_normalize_predicates<'tcx>(
189 cause: ObligationCause<'tcx>,
190 elaborated_env: ty::ParamEnv<'tcx>,
191 predicates: Vec<ty::Predicate<'tcx>>,
192 ) -> Result<Vec<ty::Predicate<'tcx>>, ErrorGuaranteed> {
193 let span = cause.span;
194 // FIXME. We should really... do something with these region
195 // obligations. But this call just continues the older
196 // behavior (i.e., doesn't cause any new bugs), and it would
197 // take some further refactoring to actually solve them. In
198 // particular, we would have to handle implied bounds
199 // properly, and that code is currently largely confined to
200 // regionck (though I made some efforts to extract it
203 // @arielby: In any case, these obligations are checked
204 // by wfcheck anyway, so I'm not sure we have to check
205 // them here too, and we will remove this function when
206 // we move over to lazy normalization *anyway*.
207 let infcx = tcx.infer_ctxt().ignoring_regions().build();
208 let predicates = match fully_normalize(&infcx, cause, elaborated_env, predicates) {
209 Ok(predicates) => predicates,
211 let reported = infcx.err_ctxt().report_fulfillment_errors(&errors, None);
212 return Err(reported);
216 debug!("do_normalize_predictes: normalized predicates = {:?}", predicates);
218 // We can use the `elaborated_env` here; the region code only
219 // cares about declarations like `'a: 'b`.
220 let outlives_env = OutlivesEnvironment::new(elaborated_env);
222 // FIXME: It's very weird that we ignore region obligations but apparently
223 // still need to use `resolve_regions` as we need the resolved regions in
224 // the normalized predicates.
225 let errors = infcx.resolve_regions(&outlives_env);
226 if !errors.is_empty() {
227 tcx.sess.delay_span_bug(
229 format!("failed region resolution while normalizing {elaborated_env:?}: {errors:?}"),
233 match infcx.fully_resolve(predicates) {
234 Ok(predicates) => Ok(predicates),
236 // If we encounter a fixup error, it means that some type
237 // variable wound up unconstrained. I actually don't know
238 // if this can happen, and I certainly don't expect it to
239 // happen often, but if it did happen it probably
240 // represents a legitimate failure due to some kind of
241 // unconstrained variable.
243 // @lcnr: Let's still ICE here for now. I want a test case
247 "inference variables in normalized parameter environment: {}",
254 // FIXME: this is gonna need to be removed ...
255 /// Normalizes the parameter environment, reporting errors if they occur.
256 #[instrument(level = "debug", skip(tcx))]
257 pub fn normalize_param_env_or_error<'tcx>(
259 unnormalized_env: ty::ParamEnv<'tcx>,
260 cause: ObligationCause<'tcx>,
261 ) -> ty::ParamEnv<'tcx> {
262 // I'm not wild about reporting errors here; I'd prefer to
263 // have the errors get reported at a defined place (e.g.,
264 // during typeck). Instead I have all parameter
265 // environments, in effect, going through this function
266 // and hence potentially reporting errors. This ensures of
267 // course that we never forget to normalize (the
268 // alternative seemed like it would involve a lot of
269 // manual invocations of this fn -- and then we'd have to
270 // deal with the errors at each of those sites).
272 // In any case, in practice, typeck constructs all the
273 // parameter environments once for every fn as it goes,
274 // and errors will get reported then; so outside of type inference we
275 // can be sure that no errors should occur.
276 let mut predicates: Vec<_> =
277 util::elaborate_predicates(tcx, unnormalized_env.caller_bounds().into_iter())
278 .map(|obligation| obligation.predicate)
281 debug!("normalize_param_env_or_error: elaborated-predicates={:?}", predicates);
283 let elaborated_env = ty::ParamEnv::new(
284 tcx.intern_predicates(&predicates),
285 unnormalized_env.reveal(),
286 unnormalized_env.constness(),
289 // HACK: we are trying to normalize the param-env inside *itself*. The problem is that
290 // normalization expects its param-env to be already normalized, which means we have
293 // The way we handle this is by normalizing the param-env inside an unnormalized version
294 // of the param-env, which means that if the param-env contains unnormalized projections,
295 // we'll have some normalization failures. This is unfortunate.
297 // Lazy normalization would basically handle this by treating just the
298 // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
300 // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
301 // types, so to make the situation less bad, we normalize all the predicates *but*
302 // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
303 // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
305 // This works fairly well because trait matching does not actually care about param-env
306 // TypeOutlives predicates - these are normally used by regionck.
307 let outlives_predicates: Vec<_> = predicates
308 .drain_filter(|predicate| {
310 predicate.kind().skip_binder(),
311 ty::PredicateKind::Clause(ty::Clause::TypeOutlives(..))
317 "normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
318 predicates, outlives_predicates
320 let Ok(non_outlives_predicates) = do_normalize_predicates(
326 // An unnormalized env is better than nothing.
327 debug!("normalize_param_env_or_error: errored resolving non-outlives predicates");
328 return elaborated_env;
331 debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates);
333 // Not sure whether it is better to include the unnormalized TypeOutlives predicates
334 // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
335 // predicates here anyway. Keeping them here anyway because it seems safer.
336 let outlives_env: Vec<_> =
337 non_outlives_predicates.iter().chain(&outlives_predicates).cloned().collect();
338 let outlives_env = ty::ParamEnv::new(
339 tcx.intern_predicates(&outlives_env),
340 unnormalized_env.reveal(),
341 unnormalized_env.constness(),
343 let Ok(outlives_predicates) = do_normalize_predicates(
349 // An unnormalized env is better than nothing.
350 debug!("normalize_param_env_or_error: errored resolving outlives predicates");
351 return elaborated_env;
353 debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates);
355 let mut predicates = non_outlives_predicates;
356 predicates.extend(outlives_predicates);
357 debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
359 tcx.intern_predicates(&predicates),
360 unnormalized_env.reveal(),
361 unnormalized_env.constness(),
365 /// Normalize a type and process all resulting obligations, returning any errors
366 #[instrument(skip_all)]
367 pub fn fully_normalize<'tcx, T>(
368 infcx: &InferCtxt<'tcx>,
369 cause: ObligationCause<'tcx>,
370 param_env: ty::ParamEnv<'tcx>,
372 ) -> Result<T, Vec<FulfillmentError<'tcx>>>
374 T: TypeFoldable<'tcx>,
376 let ocx = ObligationCtxt::new(infcx);
378 let normalized_value = ocx.normalize(&cause, param_env, value);
379 debug!(?normalized_value);
380 debug!("select_all_or_error start");
381 let errors = ocx.select_all_or_error();
382 if !errors.is_empty() {
385 debug!("select_all_or_error complete");
386 let resolved_value = infcx.resolve_vars_if_possible(normalized_value);
387 debug!(?resolved_value);
391 /// Process an obligation (and any nested obligations that come from it) to
392 /// completion, returning any errors
393 pub fn fully_solve_obligation<'tcx>(
394 infcx: &InferCtxt<'tcx>,
395 obligation: PredicateObligation<'tcx>,
396 ) -> Vec<FulfillmentError<'tcx>> {
397 fully_solve_obligations(infcx, [obligation])
400 /// Process a set of obligations (and any nested obligations that come from them)
402 pub fn fully_solve_obligations<'tcx>(
403 infcx: &InferCtxt<'tcx>,
404 obligations: impl IntoIterator<Item = PredicateObligation<'tcx>>,
405 ) -> Vec<FulfillmentError<'tcx>> {
406 let ocx = ObligationCtxt::new(infcx);
407 ocx.register_obligations(obligations);
408 ocx.select_all_or_error()
411 /// Process a bound (and any nested obligations that come from it) to completion.
412 /// This is a convenience function for traits that have no generic arguments, such
413 /// as auto traits, and builtin traits like Copy or Sized.
414 pub fn fully_solve_bound<'tcx>(
415 infcx: &InferCtxt<'tcx>,
416 cause: ObligationCause<'tcx>,
417 param_env: ty::ParamEnv<'tcx>,
420 ) -> Vec<FulfillmentError<'tcx>> {
422 let trait_ref = tcx.mk_trait_ref(bound, [ty]);
423 let obligation = Obligation::new(tcx, cause, param_env, ty::Binder::dummy(trait_ref));
425 fully_solve_obligation(infcx, obligation)
428 /// Normalizes the predicates and checks whether they hold in an empty environment. If this
429 /// returns true, then either normalize encountered an error or one of the predicates did not
430 /// hold. Used when creating vtables to check for unsatisfiable methods.
431 pub fn impossible_predicates<'tcx>(
433 predicates: Vec<ty::Predicate<'tcx>>,
435 debug!("impossible_predicates(predicates={:?})", predicates);
437 let infcx = tcx.infer_ctxt().build();
438 let param_env = ty::ParamEnv::reveal_all();
439 let ocx = ObligationCtxt::new(&infcx);
440 let predicates = ocx.normalize(&ObligationCause::dummy(), param_env, predicates);
441 for predicate in predicates {
442 let obligation = Obligation::new(tcx, ObligationCause::dummy(), param_env, predicate);
443 ocx.register_obligation(obligation);
445 let errors = ocx.select_all_or_error();
447 let result = !errors.is_empty();
448 debug!("impossible_predicates = {:?}", result);
452 fn subst_and_check_impossible_predicates<'tcx>(
454 key: (DefId, SubstsRef<'tcx>),
456 debug!("subst_and_check_impossible_predicates(key={:?})", key);
458 let mut predicates = tcx.predicates_of(key.0).instantiate(tcx, key.1).predicates;
460 // Specifically check trait fulfillment to avoid an error when trying to resolve
462 if let Some(trait_def_id) = tcx.trait_of_item(key.0) {
463 let trait_ref = ty::TraitRef::from_method(tcx, trait_def_id, key.1);
464 predicates.push(ty::Binder::dummy(trait_ref).to_predicate(tcx));
467 predicates.retain(|predicate| !predicate.needs_subst());
468 let result = impossible_predicates(tcx, predicates);
470 debug!("subst_and_check_impossible_predicates(key={:?}) = {:?}", key, result);
474 /// Checks whether a trait's method is impossible to call on a given impl.
476 /// This only considers predicates that reference the impl's generics, and not
477 /// those that reference the method's generics.
478 fn is_impossible_method(tcx: TyCtxt<'_>, (impl_def_id, trait_item_def_id): (DefId, DefId)) -> bool {
479 struct ReferencesOnlyParentGenerics<'tcx> {
481 generics: &'tcx ty::Generics,
482 trait_item_def_id: DefId,
484 impl<'tcx> ty::TypeVisitor<'tcx> for ReferencesOnlyParentGenerics<'tcx> {
486 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
487 // If this is a parameter from the trait item's own generics, then bail
488 if let ty::Param(param) = t.kind()
489 && let param_def_id = self.generics.type_param(param, self.tcx).def_id
490 && self.tcx.parent(param_def_id) == self.trait_item_def_id
492 return ControlFlow::Break(());
494 t.super_visit_with(self)
496 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
497 if let ty::ReEarlyBound(param) = r.kind()
498 && let param_def_id = self.generics.region_param(¶m, self.tcx).def_id
499 && self.tcx.parent(param_def_id) == self.trait_item_def_id
501 return ControlFlow::Break(());
503 r.super_visit_with(self)
505 fn visit_const(&mut self, ct: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
506 if let ty::ConstKind::Param(param) = ct.kind()
507 && let param_def_id = self.generics.const_param(¶m, self.tcx).def_id
508 && self.tcx.parent(param_def_id) == self.trait_item_def_id
510 return ControlFlow::Break(());
512 ct.super_visit_with(self)
516 let generics = tcx.generics_of(trait_item_def_id);
517 let predicates = tcx.predicates_of(trait_item_def_id);
518 let impl_trait_ref = tcx
519 .impl_trait_ref(impl_def_id)
520 .expect("expected impl to correspond to trait")
522 let param_env = tcx.param_env(impl_def_id);
524 let mut visitor = ReferencesOnlyParentGenerics { tcx, generics, trait_item_def_id };
525 let predicates_for_trait = predicates.predicates.iter().filter_map(|(pred, span)| {
526 if pred.visit_with(&mut visitor).is_continue() {
527 Some(Obligation::new(
529 ObligationCause::dummy_with_span(*span),
531 ty::EarlyBinder(*pred).subst(tcx, impl_trait_ref.substs),
538 let infcx = tcx.infer_ctxt().ignoring_regions().build();
539 for obligation in predicates_for_trait {
540 // Ignore overflow error, to be conservative.
541 if let Ok(result) = infcx.evaluate_obligation(&obligation)
542 && !result.may_apply()
550 pub fn provide(providers: &mut ty::query::Providers) {
551 object_safety::provide(providers);
552 vtable::provide(providers);
553 *providers = ty::query::Providers {
554 specialization_graph_of: specialize::specialization_graph_provider,
555 specializes: specialize::specializes,
556 subst_and_check_impossible_predicates,
557 is_impossible_method,