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
9 pub mod const_evaluatable;
11 pub mod error_reporting;
15 pub mod outlives_bounds;
18 pub(crate) mod relationships;
26 use crate::infer::outlives::env::OutlivesEnvironment;
27 use crate::infer::{InferCtxt, TyCtxtInferExt};
28 use crate::traits::error_reporting::TypeErrCtxtExt as _;
29 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
30 use rustc_errors::ErrorGuaranteed;
32 use rustc_hir::def_id::DefId;
33 use rustc_middle::ty::fold::TypeFoldable;
34 use rustc_middle::ty::visit::TypeVisitable;
35 use rustc_middle::ty::{self, DefIdTree, ToPredicate, Ty, TyCtxt, TypeSuperVisitable};
36 use rustc_middle::ty::{InternalSubsts, SubstsRef};
40 use std::ops::ControlFlow;
42 pub use self::FulfillmentErrorCode::*;
43 pub use self::ImplSource::*;
44 pub use self::ObligationCauseCode::*;
45 pub use self::SelectionError::*;
47 pub use self::coherence::{add_placeholder_note, orphan_check, overlapping_impls};
48 pub use self::coherence::{OrphanCheckErr, OverlapResult};
49 pub use self::engine::{ObligationCtxt, TraitEngineExt};
50 pub use self::fulfill::{FulfillmentContext, PendingPredicateObligation};
51 pub use self::object_safety::astconv_object_safety_violations;
52 pub use self::object_safety::is_vtable_safe_method;
53 pub use self::object_safety::MethodViolationCode;
54 pub use self::object_safety::ObjectSafetyViolation;
55 pub use self::project::{normalize_projection_type, NormalizeExt};
56 pub use self::select::{EvaluationCache, SelectionCache, SelectionContext};
57 pub use self::select::{EvaluationResult, IntercrateAmbiguityCause, OverflowError};
58 pub use self::specialize::specialization_graph::FutureCompatOverlapError;
59 pub use self::specialize::specialization_graph::FutureCompatOverlapErrorKind;
60 pub use self::specialize::{specialization_graph, translate_substs, OverlapError};
61 pub use self::structural_match::{
62 search_for_adt_const_param_violation, search_for_structural_match_violation,
65 elaborate_obligations, elaborate_predicates, elaborate_predicates_with_span,
66 elaborate_trait_ref, elaborate_trait_refs,
68 pub use self::util::{expand_trait_aliases, TraitAliasExpander};
70 get_vtable_index_of_object_method, impl_item_is_final, predicate_for_trait_def, upcast_choices,
73 supertrait_def_ids, supertraits, transitive_bounds, transitive_bounds_that_define_assoc_type,
74 SupertraitDefIds, Supertraits,
77 pub use self::chalk_fulfill::FulfillmentContext as ChalkFulfillmentContext;
79 pub use rustc_infer::traits::*;
81 /// Whether to skip the leak check, as part of a future compatibility warning step.
83 /// The "default" for skip-leak-check corresponds to the current
84 /// behavior (do not skip the leak check) -- not the behavior we are
85 /// transitioning into.
86 #[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
87 pub enum SkipLeakCheck {
94 fn is_yes(self) -> bool {
95 self == SkipLeakCheck::Yes
99 /// The mode that trait queries run in.
100 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
101 pub enum TraitQueryMode {
102 /// Standard/un-canonicalized queries get accurate
103 /// spans etc. passed in and hence can do reasonable
104 /// error reporting on their own.
106 /// Canonicalized queries get dummy spans and hence
107 /// must generally propagate errors to
108 /// pre-canonicalization callsites.
112 /// Creates predicate obligations from the generic bounds.
113 #[instrument(level = "debug", skip(cause, param_env))]
114 pub fn predicates_for_generics<'tcx>(
115 cause: impl Fn(usize, Span) -> ObligationCause<'tcx>,
116 param_env: ty::ParamEnv<'tcx>,
117 generic_bounds: ty::InstantiatedPredicates<'tcx>,
118 ) -> impl Iterator<Item = PredicateObligation<'tcx>> {
119 std::iter::zip(generic_bounds.predicates, generic_bounds.spans).enumerate().map(
120 move |(idx, (predicate, span))| Obligation {
121 cause: cause(idx, span),
129 /// Determines whether the type `ty` is known to meet `bound` and
130 /// returns true if so. Returns false if `ty` either does not meet
131 /// `bound` or is not known to meet bound (note that this is
132 /// conservative towards *no impl*, which is the opposite of the
133 /// `evaluate` methods).
134 pub fn type_known_to_meet_bound_modulo_regions<'tcx>(
135 infcx: &InferCtxt<'tcx>,
136 param_env: ty::ParamEnv<'tcx>,
141 let trait_ref = ty::Binder::dummy(infcx.tcx.mk_trait_ref(def_id, [ty]));
142 pred_known_to_hold_modulo_regions(infcx, param_env, trait_ref.without_const(), span)
145 #[instrument(level = "debug", skip(infcx, param_env, span, pred), ret)]
146 fn pred_known_to_hold_modulo_regions<'tcx>(
147 infcx: &InferCtxt<'tcx>,
148 param_env: ty::ParamEnv<'tcx>,
149 pred: impl ToPredicate<'tcx> + TypeVisitable<'tcx>,
152 let has_non_region_infer = pred.has_non_region_infer();
153 let obligation = Obligation {
155 // We can use a dummy node-id here because we won't pay any mind
156 // to region obligations that arise (there shouldn't really be any
158 cause: ObligationCause::misc(span, hir::CRATE_HIR_ID),
160 predicate: pred.to_predicate(infcx.tcx),
163 let result = infcx.predicate_must_hold_modulo_regions(&obligation);
166 if result && has_non_region_infer {
167 // Because of inference "guessing", selection can sometimes claim
168 // to succeed while the success requires a guess. To ensure
169 // this function's result remains infallible, we must confirm
170 // that guess. While imperfect, I believe this is sound.
172 // FIXME(@lcnr): this function doesn't seem right.
173 // The handling of regions in this area of the code is terrible,
174 // see issue #29149. We should be able to improve on this with
176 let errors = fully_solve_obligation(infcx, obligation);
178 // Note: we only assume something is `Copy` if we can
179 // *definitively* show that it implements `Copy`. Otherwise,
180 // assume it is move; linear is always ok.
193 #[instrument(level = "debug", skip(tcx, elaborated_env))]
194 fn do_normalize_predicates<'tcx>(
196 cause: ObligationCause<'tcx>,
197 elaborated_env: ty::ParamEnv<'tcx>,
198 predicates: Vec<ty::Predicate<'tcx>>,
199 ) -> Result<Vec<ty::Predicate<'tcx>>, ErrorGuaranteed> {
200 let span = cause.span;
201 // FIXME. We should really... do something with these region
202 // obligations. But this call just continues the older
203 // behavior (i.e., doesn't cause any new bugs), and it would
204 // take some further refactoring to actually solve them. In
205 // particular, we would have to handle implied bounds
206 // properly, and that code is currently largely confined to
207 // regionck (though I made some efforts to extract it
210 // @arielby: In any case, these obligations are checked
211 // by wfcheck anyway, so I'm not sure we have to check
212 // them here too, and we will remove this function when
213 // we move over to lazy normalization *anyway*.
214 let infcx = tcx.infer_ctxt().ignoring_regions().build();
215 let predicates = match fully_normalize(&infcx, cause, elaborated_env, predicates) {
216 Ok(predicates) => predicates,
218 let reported = infcx.err_ctxt().report_fulfillment_errors(&errors, None);
219 return Err(reported);
223 debug!("do_normalize_predictes: normalized predicates = {:?}", predicates);
225 // We can use the `elaborated_env` here; the region code only
226 // cares about declarations like `'a: 'b`.
227 let outlives_env = OutlivesEnvironment::new(elaborated_env);
229 // FIXME: It's very weird that we ignore region obligations but apparently
230 // still need to use `resolve_regions` as we need the resolved regions in
231 // the normalized predicates.
232 let errors = infcx.resolve_regions(&outlives_env);
233 if !errors.is_empty() {
234 tcx.sess.delay_span_bug(
236 format!("failed region resolution while normalizing {elaborated_env:?}: {errors:?}"),
240 match infcx.fully_resolve(predicates) {
241 Ok(predicates) => Ok(predicates),
243 // If we encounter a fixup error, it means that some type
244 // variable wound up unconstrained. I actually don't know
245 // if this can happen, and I certainly don't expect it to
246 // happen often, but if it did happen it probably
247 // represents a legitimate failure due to some kind of
248 // unconstrained variable.
250 // @lcnr: Let's still ICE here for now. I want a test case
254 "inference variables in normalized parameter environment: {}",
261 // FIXME: this is gonna need to be removed ...
262 /// Normalizes the parameter environment, reporting errors if they occur.
263 #[instrument(level = "debug", skip(tcx))]
264 pub fn normalize_param_env_or_error<'tcx>(
266 unnormalized_env: ty::ParamEnv<'tcx>,
267 cause: ObligationCause<'tcx>,
268 ) -> ty::ParamEnv<'tcx> {
269 // I'm not wild about reporting errors here; I'd prefer to
270 // have the errors get reported at a defined place (e.g.,
271 // during typeck). Instead I have all parameter
272 // environments, in effect, going through this function
273 // and hence potentially reporting errors. This ensures of
274 // course that we never forget to normalize (the
275 // alternative seemed like it would involve a lot of
276 // manual invocations of this fn -- and then we'd have to
277 // deal with the errors at each of those sites).
279 // In any case, in practice, typeck constructs all the
280 // parameter environments once for every fn as it goes,
281 // and errors will get reported then; so outside of type inference we
282 // can be sure that no errors should occur.
283 let mut predicates: Vec<_> =
284 util::elaborate_predicates(tcx, unnormalized_env.caller_bounds().into_iter())
285 .map(|obligation| obligation.predicate)
288 debug!("normalize_param_env_or_error: elaborated-predicates={:?}", predicates);
290 let elaborated_env = ty::ParamEnv::new(
291 tcx.intern_predicates(&predicates),
292 unnormalized_env.reveal(),
293 unnormalized_env.constness(),
296 // HACK: we are trying to normalize the param-env inside *itself*. The problem is that
297 // normalization expects its param-env to be already normalized, which means we have
300 // The way we handle this is by normalizing the param-env inside an unnormalized version
301 // of the param-env, which means that if the param-env contains unnormalized projections,
302 // we'll have some normalization failures. This is unfortunate.
304 // Lazy normalization would basically handle this by treating just the
305 // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
307 // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
308 // types, so to make the situation less bad, we normalize all the predicates *but*
309 // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
310 // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
312 // This works fairly well because trait matching does not actually care about param-env
313 // TypeOutlives predicates - these are normally used by regionck.
314 let outlives_predicates: Vec<_> = predicates
315 .drain_filter(|predicate| {
317 predicate.kind().skip_binder(),
318 ty::PredicateKind::Clause(ty::Clause::TypeOutlives(..))
324 "normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
325 predicates, outlives_predicates
327 let Ok(non_outlives_predicates) = do_normalize_predicates(
333 // An unnormalized env is better than nothing.
334 debug!("normalize_param_env_or_error: errored resolving non-outlives predicates");
335 return elaborated_env;
338 debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates);
340 // Not sure whether it is better to include the unnormalized TypeOutlives predicates
341 // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
342 // predicates here anyway. Keeping them here anyway because it seems safer.
343 let outlives_env: Vec<_> =
344 non_outlives_predicates.iter().chain(&outlives_predicates).cloned().collect();
345 let outlives_env = ty::ParamEnv::new(
346 tcx.intern_predicates(&outlives_env),
347 unnormalized_env.reveal(),
348 unnormalized_env.constness(),
350 let Ok(outlives_predicates) = do_normalize_predicates(
356 // An unnormalized env is better than nothing.
357 debug!("normalize_param_env_or_error: errored resolving outlives predicates");
358 return elaborated_env;
360 debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates);
362 let mut predicates = non_outlives_predicates;
363 predicates.extend(outlives_predicates);
364 debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
366 tcx.intern_predicates(&predicates),
367 unnormalized_env.reveal(),
368 unnormalized_env.constness(),
372 /// Normalize a type and process all resulting obligations, returning any errors
373 #[instrument(skip_all)]
374 pub fn fully_normalize<'tcx, T>(
375 infcx: &InferCtxt<'tcx>,
376 cause: ObligationCause<'tcx>,
377 param_env: ty::ParamEnv<'tcx>,
379 ) -> Result<T, Vec<FulfillmentError<'tcx>>>
381 T: TypeFoldable<'tcx>,
383 let ocx = ObligationCtxt::new(infcx);
385 let normalized_value = ocx.normalize(&cause, param_env, value);
386 debug!(?normalized_value);
387 debug!("select_all_or_error start");
388 let errors = ocx.select_all_or_error();
389 if !errors.is_empty() {
392 debug!("select_all_or_error complete");
393 let resolved_value = infcx.resolve_vars_if_possible(normalized_value);
394 debug!(?resolved_value);
398 /// Process an obligation (and any nested obligations that come from it) to
399 /// completion, returning any errors
400 pub fn fully_solve_obligation<'tcx>(
401 infcx: &InferCtxt<'tcx>,
402 obligation: PredicateObligation<'tcx>,
403 ) -> Vec<FulfillmentError<'tcx>> {
404 fully_solve_obligations(infcx, [obligation])
407 /// Process a set of obligations (and any nested obligations that come from them)
409 pub fn fully_solve_obligations<'tcx>(
410 infcx: &InferCtxt<'tcx>,
411 obligations: impl IntoIterator<Item = PredicateObligation<'tcx>>,
412 ) -> Vec<FulfillmentError<'tcx>> {
413 let ocx = ObligationCtxt::new(infcx);
414 ocx.register_obligations(obligations);
415 ocx.select_all_or_error()
418 /// Process a bound (and any nested obligations that come from it) to completion.
419 /// This is a convenience function for traits that have no generic arguments, such
420 /// as auto traits, and builtin traits like Copy or Sized.
421 pub fn fully_solve_bound<'tcx>(
422 infcx: &InferCtxt<'tcx>,
423 cause: ObligationCause<'tcx>,
424 param_env: ty::ParamEnv<'tcx>,
427 ) -> Vec<FulfillmentError<'tcx>> {
429 let trait_ref = ty::TraitRef { def_id: bound, substs: tcx.mk_substs_trait(ty, []) };
430 let obligation = Obligation {
434 predicate: ty::Binder::dummy(trait_ref).without_const().to_predicate(tcx),
437 fully_solve_obligation(infcx, obligation)
440 /// Normalizes the predicates and checks whether they hold in an empty environment. If this
441 /// returns true, then either normalize encountered an error or one of the predicates did not
442 /// hold. Used when creating vtables to check for unsatisfiable methods.
443 pub fn impossible_predicates<'tcx>(
445 predicates: Vec<ty::Predicate<'tcx>>,
447 debug!("impossible_predicates(predicates={:?})", predicates);
449 let infcx = tcx.infer_ctxt().build();
450 let param_env = ty::ParamEnv::reveal_all();
451 let ocx = ObligationCtxt::new(&infcx);
452 let predicates = ocx.normalize(&ObligationCause::dummy(), param_env, predicates);
453 for predicate in predicates {
454 let obligation = Obligation::new(tcx, ObligationCause::dummy(), param_env, predicate);
455 ocx.register_obligation(obligation);
457 let errors = ocx.select_all_or_error();
459 // Clean up after ourselves
460 let _ = infcx.inner.borrow_mut().opaque_type_storage.take_opaque_types();
462 let result = !errors.is_empty();
463 debug!("impossible_predicates = {:?}", result);
467 fn subst_and_check_impossible_predicates<'tcx>(
469 key: (DefId, SubstsRef<'tcx>),
471 debug!("subst_and_check_impossible_predicates(key={:?})", key);
473 let mut predicates = tcx.predicates_of(key.0).instantiate(tcx, key.1).predicates;
475 // Specifically check trait fulfillment to avoid an error when trying to resolve
477 if let Some(trait_def_id) = tcx.trait_of_item(key.0) {
478 let trait_ref = ty::TraitRef::from_method(tcx, trait_def_id, key.1);
479 predicates.push(ty::Binder::dummy(trait_ref).to_predicate(tcx));
482 predicates.retain(|predicate| !predicate.needs_subst());
483 let result = impossible_predicates(tcx, predicates);
485 debug!("subst_and_check_impossible_predicates(key={:?}) = {:?}", key, result);
489 /// Checks whether a trait's method is impossible to call on a given impl.
491 /// This only considers predicates that reference the impl's generics, and not
492 /// those that reference the method's generics.
493 fn is_impossible_method<'tcx>(
495 (impl_def_id, trait_item_def_id): (DefId, DefId),
497 struct ReferencesOnlyParentGenerics<'tcx> {
499 generics: &'tcx ty::Generics,
500 trait_item_def_id: DefId,
502 impl<'tcx> ty::TypeVisitor<'tcx> for ReferencesOnlyParentGenerics<'tcx> {
504 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
505 // If this is a parameter from the trait item's own generics, then bail
506 if let ty::Param(param) = t.kind()
507 && let param_def_id = self.generics.type_param(param, self.tcx).def_id
508 && self.tcx.parent(param_def_id) == self.trait_item_def_id
510 return ControlFlow::BREAK;
512 t.super_visit_with(self)
514 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
515 if let ty::ReEarlyBound(param) = r.kind()
516 && let param_def_id = self.generics.region_param(¶m, self.tcx).def_id
517 && self.tcx.parent(param_def_id) == self.trait_item_def_id
519 return ControlFlow::BREAK;
521 r.super_visit_with(self)
523 fn visit_const(&mut self, ct: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
524 if let ty::ConstKind::Param(param) = ct.kind()
525 && let param_def_id = self.generics.const_param(¶m, self.tcx).def_id
526 && self.tcx.parent(param_def_id) == self.trait_item_def_id
528 return ControlFlow::BREAK;
530 ct.super_visit_with(self)
534 let generics = tcx.generics_of(trait_item_def_id);
535 let predicates = tcx.predicates_of(trait_item_def_id);
537 tcx.impl_trait_ref(impl_def_id).expect("expected impl to correspond to trait");
538 let param_env = tcx.param_env(impl_def_id);
540 let mut visitor = ReferencesOnlyParentGenerics { tcx, generics, trait_item_def_id };
541 let predicates_for_trait = predicates.predicates.iter().filter_map(|(pred, span)| {
542 if pred.visit_with(&mut visitor).is_continue() {
543 Some(Obligation::new(
545 ObligationCause::dummy_with_span(*span),
547 ty::EarlyBinder(*pred).subst(tcx, impl_trait_ref.substs),
554 let infcx = tcx.infer_ctxt().ignoring_regions().build();
555 for obligation in predicates_for_trait {
556 // Ignore overflow error, to be conservative.
557 if let Ok(result) = infcx.evaluate_obligation(&obligation)
558 && !result.may_apply()
566 pub fn provide(providers: &mut ty::query::Providers) {
567 object_safety::provide(providers);
568 vtable::provide(providers);
569 *providers = ty::query::Providers {
570 specialization_graph_of: specialize::specialization_graph_provider,
571 specializes: specialize::specializes,
572 codegen_select_candidate: codegen::codegen_select_candidate,
573 subst_and_check_impossible_predicates,
574 is_impossible_method,