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;
17 pub(crate) mod relationships;
25 use crate::infer::outlives::env::OutlivesEnvironment;
26 use crate::infer::{InferCtxt, TyCtxtInferExt};
27 use crate::traits::error_reporting::TypeErrCtxtExt as _;
28 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
29 use rustc_errors::ErrorGuaranteed;
31 use rustc_hir::def_id::DefId;
32 use rustc_middle::ty::fold::TypeFoldable;
33 use rustc_middle::ty::visit::TypeVisitable;
34 use rustc_middle::ty::{self, DefIdTree, ToPredicate, Ty, TyCtxt, TypeSuperVisitable};
35 use rustc_middle::ty::{InternalSubsts, SubstsRef};
39 use std::ops::ControlFlow;
41 pub use self::FulfillmentErrorCode::*;
42 pub use self::ImplSource::*;
43 pub use self::ObligationCauseCode::*;
44 pub use self::SelectionError::*;
46 pub use self::coherence::{add_placeholder_note, orphan_check, overlapping_impls};
47 pub use self::coherence::{OrphanCheckErr, OverlapResult};
48 pub use self::engine::{ObligationCtxt, TraitEngineExt};
49 pub use self::fulfill::{FulfillmentContext, PendingPredicateObligation};
50 pub use self::object_safety::astconv_object_safety_violations;
51 pub use self::object_safety::is_vtable_safe_method;
52 pub use self::object_safety::MethodViolationCode;
53 pub use self::object_safety::ObjectSafetyViolation;
54 pub use self::project::{normalize_projection_type, NormalizeExt};
55 pub use self::select::{EvaluationCache, SelectionCache, SelectionContext};
56 pub use self::select::{EvaluationResult, IntercrateAmbiguityCause, OverflowError};
57 pub use self::specialize::specialization_graph::FutureCompatOverlapError;
58 pub use self::specialize::specialization_graph::FutureCompatOverlapErrorKind;
59 pub use self::specialize::{specialization_graph, translate_substs, OverlapError};
60 pub use self::structural_match::{
61 search_for_adt_const_param_violation, search_for_structural_match_violation,
64 elaborate_obligations, elaborate_predicates, elaborate_predicates_with_span,
65 elaborate_trait_ref, elaborate_trait_refs,
67 pub use self::util::{expand_trait_aliases, TraitAliasExpander};
69 get_vtable_index_of_object_method, impl_item_is_final, predicate_for_trait_def, upcast_choices,
72 supertrait_def_ids, supertraits, transitive_bounds, transitive_bounds_that_define_assoc_type,
73 SupertraitDefIds, Supertraits,
76 pub use self::chalk_fulfill::FulfillmentContext as ChalkFulfillmentContext;
78 pub use rustc_infer::traits::*;
80 /// Whether to skip the leak check, as part of a future compatibility warning step.
82 /// The "default" for skip-leak-check corresponds to the current
83 /// behavior (do not skip the leak check) -- not the behavior we are
84 /// transitioning into.
85 #[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
86 pub enum SkipLeakCheck {
93 fn is_yes(self) -> bool {
94 self == SkipLeakCheck::Yes
98 /// The mode that trait queries run in.
99 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
100 pub enum TraitQueryMode {
101 /// Standard/un-canonicalized queries get accurate
102 /// spans etc. passed in and hence can do reasonable
103 /// error reporting on their own.
105 /// Canonicalized queries get dummy spans and hence
106 /// must generally propagate errors to
107 /// pre-canonicalization callsites.
111 /// Creates predicate obligations from the generic bounds.
112 #[instrument(level = "debug", skip(cause, param_env))]
113 pub fn predicates_for_generics<'tcx>(
114 cause: impl Fn(usize, Span) -> ObligationCause<'tcx>,
115 param_env: ty::ParamEnv<'tcx>,
116 generic_bounds: ty::InstantiatedPredicates<'tcx>,
117 ) -> impl Iterator<Item = PredicateObligation<'tcx>> {
118 std::iter::zip(generic_bounds.predicates, generic_bounds.spans).enumerate().map(
119 move |(idx, (predicate, span))| Obligation {
120 cause: cause(idx, span),
128 /// Determines whether the type `ty` is known to meet `bound` and
129 /// returns true if so. Returns false if `ty` either does not meet
130 /// `bound` or is not known to meet bound (note that this is
131 /// conservative towards *no impl*, which is the opposite of the
132 /// `evaluate` methods).
133 pub fn type_known_to_meet_bound_modulo_regions<'tcx>(
134 infcx: &InferCtxt<'tcx>,
135 param_env: ty::ParamEnv<'tcx>,
140 let trait_ref = ty::Binder::dummy(infcx.tcx.mk_trait_ref(def_id, [ty]));
141 pred_known_to_hold_modulo_regions(infcx, param_env, trait_ref.without_const(), span)
144 #[instrument(level = "debug", skip(infcx, param_env, span, pred), ret)]
145 fn pred_known_to_hold_modulo_regions<'tcx>(
146 infcx: &InferCtxt<'tcx>,
147 param_env: ty::ParamEnv<'tcx>,
148 pred: impl ToPredicate<'tcx> + TypeVisitable<'tcx>,
151 let has_non_region_infer = pred.has_non_region_infer();
152 let obligation = Obligation {
154 // We can use a dummy node-id here because we won't pay any mind
155 // to region obligations that arise (there shouldn't really be any
157 cause: ObligationCause::misc(span, hir::CRATE_HIR_ID),
159 predicate: pred.to_predicate(infcx.tcx),
162 let result = infcx.predicate_must_hold_modulo_regions(&obligation);
165 if result && has_non_region_infer {
166 // Because of inference "guessing", selection can sometimes claim
167 // to succeed while the success requires a guess. To ensure
168 // this function's result remains infallible, we must confirm
169 // that guess. While imperfect, I believe this is sound.
171 // FIXME(@lcnr): this function doesn't seem right.
172 // The handling of regions in this area of the code is terrible,
173 // see issue #29149. We should be able to improve on this with
175 let errors = fully_solve_obligation(infcx, obligation);
177 // Note: we only assume something is `Copy` if we can
178 // *definitively* show that it implements `Copy`. Otherwise,
179 // assume it is move; linear is always ok.
192 #[instrument(level = "debug", skip(tcx, elaborated_env))]
193 fn do_normalize_predicates<'tcx>(
195 cause: ObligationCause<'tcx>,
196 elaborated_env: ty::ParamEnv<'tcx>,
197 predicates: Vec<ty::Predicate<'tcx>>,
198 ) -> Result<Vec<ty::Predicate<'tcx>>, ErrorGuaranteed> {
199 let span = cause.span;
200 // FIXME. We should really... do something with these region
201 // obligations. But this call just continues the older
202 // behavior (i.e., doesn't cause any new bugs), and it would
203 // take some further refactoring to actually solve them. In
204 // particular, we would have to handle implied bounds
205 // properly, and that code is currently largely confined to
206 // regionck (though I made some efforts to extract it
209 // @arielby: In any case, these obligations are checked
210 // by wfcheck anyway, so I'm not sure we have to check
211 // them here too, and we will remove this function when
212 // we move over to lazy normalization *anyway*.
213 let infcx = tcx.infer_ctxt().ignoring_regions().build();
214 let predicates = match fully_normalize(&infcx, cause, elaborated_env, predicates) {
215 Ok(predicates) => predicates,
217 let reported = infcx.err_ctxt().report_fulfillment_errors(&errors, None);
218 return Err(reported);
222 debug!("do_normalize_predictes: normalized predicates = {:?}", predicates);
224 // We can use the `elaborated_env` here; the region code only
225 // cares about declarations like `'a: 'b`.
226 let outlives_env = OutlivesEnvironment::new(elaborated_env);
228 // FIXME: It's very weird that we ignore region obligations but apparently
229 // still need to use `resolve_regions` as we need the resolved regions in
230 // the normalized predicates.
231 let errors = infcx.resolve_regions(&outlives_env);
232 if !errors.is_empty() {
233 tcx.sess.delay_span_bug(
235 format!("failed region resolution while normalizing {elaborated_env:?}: {errors:?}"),
239 match infcx.fully_resolve(predicates) {
240 Ok(predicates) => Ok(predicates),
242 // If we encounter a fixup error, it means that some type
243 // variable wound up unconstrained. I actually don't know
244 // if this can happen, and I certainly don't expect it to
245 // happen often, but if it did happen it probably
246 // represents a legitimate failure due to some kind of
247 // unconstrained variable.
249 // @lcnr: Let's still ICE here for now. I want a test case
253 "inference variables in normalized parameter environment: {}",
260 // FIXME: this is gonna need to be removed ...
261 /// Normalizes the parameter environment, reporting errors if they occur.
262 #[instrument(level = "debug", skip(tcx))]
263 pub fn normalize_param_env_or_error<'tcx>(
265 unnormalized_env: ty::ParamEnv<'tcx>,
266 cause: ObligationCause<'tcx>,
267 ) -> ty::ParamEnv<'tcx> {
268 // I'm not wild about reporting errors here; I'd prefer to
269 // have the errors get reported at a defined place (e.g.,
270 // during typeck). Instead I have all parameter
271 // environments, in effect, going through this function
272 // and hence potentially reporting errors. This ensures of
273 // course that we never forget to normalize (the
274 // alternative seemed like it would involve a lot of
275 // manual invocations of this fn -- and then we'd have to
276 // deal with the errors at each of those sites).
278 // In any case, in practice, typeck constructs all the
279 // parameter environments once for every fn as it goes,
280 // and errors will get reported then; so outside of type inference we
281 // can be sure that no errors should occur.
282 let mut predicates: Vec<_> =
283 util::elaborate_predicates(tcx, unnormalized_env.caller_bounds().into_iter())
284 .map(|obligation| obligation.predicate)
287 debug!("normalize_param_env_or_error: elaborated-predicates={:?}", predicates);
289 let elaborated_env = ty::ParamEnv::new(
290 tcx.intern_predicates(&predicates),
291 unnormalized_env.reveal(),
292 unnormalized_env.constness(),
295 // HACK: we are trying to normalize the param-env inside *itself*. The problem is that
296 // normalization expects its param-env to be already normalized, which means we have
299 // The way we handle this is by normalizing the param-env inside an unnormalized version
300 // of the param-env, which means that if the param-env contains unnormalized projections,
301 // we'll have some normalization failures. This is unfortunate.
303 // Lazy normalization would basically handle this by treating just the
304 // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
306 // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
307 // types, so to make the situation less bad, we normalize all the predicates *but*
308 // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
309 // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
311 // This works fairly well because trait matching does not actually care about param-env
312 // TypeOutlives predicates - these are normally used by regionck.
313 let outlives_predicates: Vec<_> = predicates
314 .drain_filter(|predicate| {
316 predicate.kind().skip_binder(),
317 ty::PredicateKind::Clause(ty::Clause::TypeOutlives(..))
323 "normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
324 predicates, outlives_predicates
326 let Ok(non_outlives_predicates) = do_normalize_predicates(
332 // An unnormalized env is better than nothing.
333 debug!("normalize_param_env_or_error: errored resolving non-outlives predicates");
334 return elaborated_env;
337 debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates);
339 // Not sure whether it is better to include the unnormalized TypeOutlives predicates
340 // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
341 // predicates here anyway. Keeping them here anyway because it seems safer.
342 let outlives_env: Vec<_> =
343 non_outlives_predicates.iter().chain(&outlives_predicates).cloned().collect();
344 let outlives_env = ty::ParamEnv::new(
345 tcx.intern_predicates(&outlives_env),
346 unnormalized_env.reveal(),
347 unnormalized_env.constness(),
349 let Ok(outlives_predicates) = do_normalize_predicates(
355 // An unnormalized env is better than nothing.
356 debug!("normalize_param_env_or_error: errored resolving outlives predicates");
357 return elaborated_env;
359 debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates);
361 let mut predicates = non_outlives_predicates;
362 predicates.extend(outlives_predicates);
363 debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
365 tcx.intern_predicates(&predicates),
366 unnormalized_env.reveal(),
367 unnormalized_env.constness(),
371 /// Normalize a type and process all resulting obligations, returning any errors
372 #[instrument(skip_all)]
373 pub fn fully_normalize<'tcx, T>(
374 infcx: &InferCtxt<'tcx>,
375 cause: ObligationCause<'tcx>,
376 param_env: ty::ParamEnv<'tcx>,
378 ) -> Result<T, Vec<FulfillmentError<'tcx>>>
380 T: TypeFoldable<'tcx>,
382 let ocx = ObligationCtxt::new(infcx);
384 let normalized_value = ocx.normalize(&cause, param_env, value);
385 debug!(?normalized_value);
386 debug!("select_all_or_error start");
387 let errors = ocx.select_all_or_error();
388 if !errors.is_empty() {
391 debug!("select_all_or_error complete");
392 let resolved_value = infcx.resolve_vars_if_possible(normalized_value);
393 debug!(?resolved_value);
397 /// Process an obligation (and any nested obligations that come from it) to
398 /// completion, returning any errors
399 pub fn fully_solve_obligation<'tcx>(
400 infcx: &InferCtxt<'tcx>,
401 obligation: PredicateObligation<'tcx>,
402 ) -> Vec<FulfillmentError<'tcx>> {
403 fully_solve_obligations(infcx, [obligation])
406 /// Process a set of obligations (and any nested obligations that come from them)
408 pub fn fully_solve_obligations<'tcx>(
409 infcx: &InferCtxt<'tcx>,
410 obligations: impl IntoIterator<Item = PredicateObligation<'tcx>>,
411 ) -> Vec<FulfillmentError<'tcx>> {
412 let ocx = ObligationCtxt::new(infcx);
413 ocx.register_obligations(obligations);
414 ocx.select_all_or_error()
417 /// Process a bound (and any nested obligations that come from it) to completion.
418 /// This is a convenience function for traits that have no generic arguments, such
419 /// as auto traits, and builtin traits like Copy or Sized.
420 pub fn fully_solve_bound<'tcx>(
421 infcx: &InferCtxt<'tcx>,
422 cause: ObligationCause<'tcx>,
423 param_env: ty::ParamEnv<'tcx>,
426 ) -> Vec<FulfillmentError<'tcx>> {
428 let trait_ref = ty::TraitRef { def_id: bound, substs: tcx.mk_substs_trait(ty, []) };
429 let obligation = Obligation {
433 predicate: ty::Binder::dummy(trait_ref).without_const().to_predicate(tcx),
436 fully_solve_obligation(infcx, obligation)
439 /// Normalizes the predicates and checks whether they hold in an empty environment. If this
440 /// returns true, then either normalize encountered an error or one of the predicates did not
441 /// hold. Used when creating vtables to check for unsatisfiable methods.
442 pub fn impossible_predicates<'tcx>(
444 predicates: Vec<ty::Predicate<'tcx>>,
446 debug!("impossible_predicates(predicates={:?})", predicates);
448 let infcx = tcx.infer_ctxt().build();
449 let param_env = ty::ParamEnv::reveal_all();
450 let ocx = ObligationCtxt::new(&infcx);
451 let predicates = ocx.normalize(&ObligationCause::dummy(), param_env, predicates);
452 for predicate in predicates {
453 let obligation = Obligation::new(tcx, ObligationCause::dummy(), param_env, predicate);
454 ocx.register_obligation(obligation);
456 let errors = ocx.select_all_or_error();
458 // Clean up after ourselves
459 let _ = infcx.inner.borrow_mut().opaque_type_storage.take_opaque_types();
461 let result = !errors.is_empty();
462 debug!("impossible_predicates = {:?}", result);
466 fn subst_and_check_impossible_predicates<'tcx>(
468 key: (DefId, SubstsRef<'tcx>),
470 debug!("subst_and_check_impossible_predicates(key={:?})", key);
472 let mut predicates = tcx.predicates_of(key.0).instantiate(tcx, key.1).predicates;
474 // Specifically check trait fulfillment to avoid an error when trying to resolve
476 if let Some(trait_def_id) = tcx.trait_of_item(key.0) {
477 let trait_ref = ty::TraitRef::from_method(tcx, trait_def_id, key.1);
478 predicates.push(ty::Binder::dummy(trait_ref).to_predicate(tcx));
481 predicates.retain(|predicate| !predicate.needs_subst());
482 let result = impossible_predicates(tcx, predicates);
484 debug!("subst_and_check_impossible_predicates(key={:?}) = {:?}", key, result);
488 /// Checks whether a trait's method is impossible to call on a given impl.
490 /// This only considers predicates that reference the impl's generics, and not
491 /// those that reference the method's generics.
492 fn is_impossible_method<'tcx>(
494 (impl_def_id, trait_item_def_id): (DefId, DefId),
496 struct ReferencesOnlyParentGenerics<'tcx> {
498 generics: &'tcx ty::Generics,
499 trait_item_def_id: DefId,
501 impl<'tcx> ty::TypeVisitor<'tcx> for ReferencesOnlyParentGenerics<'tcx> {
503 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
504 // If this is a parameter from the trait item's own generics, then bail
505 if let ty::Param(param) = t.kind()
506 && let param_def_id = self.generics.type_param(param, self.tcx).def_id
507 && self.tcx.parent(param_def_id) == self.trait_item_def_id
509 return ControlFlow::BREAK;
511 t.super_visit_with(self)
513 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
514 if let ty::ReEarlyBound(param) = r.kind()
515 && let param_def_id = self.generics.region_param(¶m, self.tcx).def_id
516 && self.tcx.parent(param_def_id) == self.trait_item_def_id
518 return ControlFlow::BREAK;
520 r.super_visit_with(self)
522 fn visit_const(&mut self, ct: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
523 if let ty::ConstKind::Param(param) = ct.kind()
524 && let param_def_id = self.generics.const_param(¶m, self.tcx).def_id
525 && self.tcx.parent(param_def_id) == self.trait_item_def_id
527 return ControlFlow::BREAK;
529 ct.super_visit_with(self)
533 let generics = tcx.generics_of(trait_item_def_id);
534 let predicates = tcx.predicates_of(trait_item_def_id);
536 tcx.impl_trait_ref(impl_def_id).expect("expected impl to correspond to trait");
537 let param_env = tcx.param_env(impl_def_id);
539 let mut visitor = ReferencesOnlyParentGenerics { tcx, generics, trait_item_def_id };
540 let predicates_for_trait = predicates.predicates.iter().filter_map(|(pred, span)| {
541 if pred.visit_with(&mut visitor).is_continue() {
542 Some(Obligation::new(
544 ObligationCause::dummy_with_span(*span),
546 ty::EarlyBinder(*pred).subst(tcx, impl_trait_ref.substs),
553 let infcx = tcx.infer_ctxt().ignoring_regions().build();
554 for obligation in predicates_for_trait {
555 // Ignore overflow error, to be conservative.
556 if let Ok(result) = infcx.evaluate_obligation(&obligation)
557 && !result.may_apply()
565 pub fn provide(providers: &mut ty::query::Providers) {
566 object_safety::provide(providers);
567 vtable::provide(providers);
568 *providers = ty::query::Providers {
569 specialization_graph_of: specialize::specialization_graph_provider,
570 specializes: specialize::specializes,
571 subst_and_check_impossible_predicates,
572 is_impossible_method,