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;
30 use rustc_hir::def_id::DefId;
31 use rustc_middle::ty::fold::TypeFoldable;
32 use rustc_middle::ty::visit::TypeVisitable;
33 use rustc_middle::ty::{self, DefIdTree, ToPredicate, Ty, TyCtxt, TypeSuperVisitable};
34 use rustc_middle::ty::{InternalSubsts, SubstsRef};
38 use std::ops::ControlFlow;
40 pub use self::FulfillmentErrorCode::*;
41 pub use self::ImplSource::*;
42 pub use self::ObligationCauseCode::*;
43 pub use self::SelectionError::*;
45 pub use self::coherence::{add_placeholder_note, orphan_check, overlapping_impls};
46 pub use self::coherence::{OrphanCheckErr, OverlapResult};
47 pub use self::engine::{ObligationCtxt, TraitEngineExt};
48 pub use self::fulfill::{FulfillmentContext, PendingPredicateObligation};
49 pub use self::object_safety::astconv_object_safety_violations;
50 pub use self::object_safety::is_vtable_safe_method;
51 pub use self::object_safety::MethodViolationCode;
52 pub use self::object_safety::ObjectSafetyViolation;
53 pub use self::project::{normalize_projection_type, NormalizeExt};
54 pub use self::select::{EvaluationCache, SelectionCache, SelectionContext};
55 pub use self::select::{EvaluationResult, IntercrateAmbiguityCause, OverflowError};
56 pub use self::specialize::specialization_graph::FutureCompatOverlapError;
57 pub use self::specialize::specialization_graph::FutureCompatOverlapErrorKind;
58 pub use self::specialize::{specialization_graph, translate_substs, OverlapError};
59 pub use self::structural_match::{
60 search_for_adt_const_param_violation, search_for_structural_match_violation,
63 elaborate_obligations, elaborate_predicates, elaborate_predicates_with_span,
64 elaborate_trait_ref, elaborate_trait_refs,
66 pub use self::util::{expand_trait_aliases, TraitAliasExpander};
68 get_vtable_index_of_object_method, impl_item_is_final, predicate_for_trait_def, upcast_choices,
71 supertrait_def_ids, supertraits, transitive_bounds, transitive_bounds_that_define_assoc_type,
72 SupertraitDefIds, Supertraits,
75 pub use self::chalk_fulfill::FulfillmentContext as ChalkFulfillmentContext;
77 pub use rustc_infer::traits::*;
79 /// Whether to skip the leak check, as part of a future compatibility warning step.
81 /// The "default" for skip-leak-check corresponds to the current
82 /// behavior (do not skip the leak check) -- not the behavior we are
83 /// transitioning into.
84 #[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
85 pub enum SkipLeakCheck {
92 fn is_yes(self) -> bool {
93 self == SkipLeakCheck::Yes
97 /// The mode that trait queries run in.
98 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
99 pub enum TraitQueryMode {
100 /// Standard/un-canonicalized queries get accurate
101 /// spans etc. passed in and hence can do reasonable
102 /// error reporting on their own.
104 /// Canonical queries get dummy spans and hence
105 /// must generally propagate errors to
106 /// pre-canonicalization callsites.
110 /// Creates predicate obligations from the generic bounds.
111 #[instrument(level = "debug", skip(cause, param_env))]
112 pub fn predicates_for_generics<'tcx>(
113 cause: impl Fn(usize, Span) -> ObligationCause<'tcx>,
114 param_env: ty::ParamEnv<'tcx>,
115 generic_bounds: ty::InstantiatedPredicates<'tcx>,
116 ) -> impl Iterator<Item = PredicateObligation<'tcx>> {
117 generic_bounds.into_iter().enumerate().map(move |(idx, (predicate, span))| Obligation {
118 cause: cause(idx, span),
125 /// Determines whether the type `ty` is known to meet `bound` and
126 /// returns true if so. Returns false if `ty` either does not meet
127 /// `bound` or is not known to meet bound (note that this is
128 /// conservative towards *no impl*, which is the opposite of the
129 /// `evaluate` methods).
130 pub fn type_known_to_meet_bound_modulo_regions<'tcx>(
131 infcx: &InferCtxt<'tcx>,
132 param_env: ty::ParamEnv<'tcx>,
137 let trait_ref = ty::Binder::dummy(infcx.tcx.mk_trait_ref(def_id, [ty]));
138 pred_known_to_hold_modulo_regions(infcx, param_env, trait_ref.without_const(), span)
141 #[instrument(level = "debug", skip(infcx, param_env, span, pred), ret)]
142 fn pred_known_to_hold_modulo_regions<'tcx>(
143 infcx: &InferCtxt<'tcx>,
144 param_env: ty::ParamEnv<'tcx>,
145 pred: impl ToPredicate<'tcx> + TypeVisitable<'tcx>,
148 let has_non_region_infer = pred.has_non_region_infer();
149 let obligation = Obligation {
151 // We can use a dummy node-id here because we won't pay any mind
152 // to region obligations that arise (there shouldn't really be any
154 cause: ObligationCause::misc(span, hir::CRATE_HIR_ID),
156 predicate: pred.to_predicate(infcx.tcx),
159 let result = infcx.predicate_must_hold_modulo_regions(&obligation);
162 if result && has_non_region_infer {
163 // Because of inference "guessing", selection can sometimes claim
164 // to succeed while the success requires a guess. To ensure
165 // this function's result remains infallible, we must confirm
166 // that guess. While imperfect, I believe this is sound.
168 // 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);
174 // Note: we only assume something is `Copy` if we can
175 // *definitively* show that it implements `Copy`. Otherwise,
176 // assume it is move; linear is always ok.
189 #[instrument(level = "debug", skip(tcx, elaborated_env))]
190 fn do_normalize_predicates<'tcx>(
192 cause: ObligationCause<'tcx>,
193 elaborated_env: ty::ParamEnv<'tcx>,
194 predicates: Vec<ty::Predicate<'tcx>>,
195 ) -> Result<Vec<ty::Predicate<'tcx>>, ErrorGuaranteed> {
196 let span = cause.span;
197 // FIXME. We should really... do something with these region
198 // obligations. But this call just continues the older
199 // behavior (i.e., doesn't cause any new bugs), and it would
200 // take some further refactoring to actually solve them. In
201 // particular, we would have to handle implied bounds
202 // properly, and that code is currently largely confined to
203 // regionck (though I made some efforts to extract it
206 // @arielby: In any case, these obligations are checked
207 // by wfcheck anyway, so I'm not sure we have to check
208 // them here too, and we will remove this function when
209 // we move over to lazy normalization *anyway*.
210 let infcx = tcx.infer_ctxt().ignoring_regions().build();
211 let predicates = match fully_normalize(&infcx, cause, elaborated_env, predicates) {
212 Ok(predicates) => predicates,
214 let reported = infcx.err_ctxt().report_fulfillment_errors(&errors, None);
215 return Err(reported);
219 debug!("do_normalize_predictes: normalized predicates = {:?}", predicates);
221 // We can use the `elaborated_env` here; the region code only
222 // cares about declarations like `'a: 'b`.
223 let outlives_env = OutlivesEnvironment::new(elaborated_env);
225 // FIXME: It's very weird that we ignore region obligations but apparently
226 // still need to use `resolve_regions` as we need the resolved regions in
227 // the normalized predicates.
228 let errors = infcx.resolve_regions(&outlives_env);
229 if !errors.is_empty() {
230 tcx.sess.delay_span_bug(
232 format!("failed region resolution while normalizing {elaborated_env:?}: {errors:?}"),
236 match infcx.fully_resolve(predicates) {
237 Ok(predicates) => Ok(predicates),
239 // If we encounter a fixup error, it means that some type
240 // variable wound up unconstrained. I actually don't know
241 // if this can happen, and I certainly don't expect it to
242 // happen often, but if it did happen it probably
243 // represents a legitimate failure due to some kind of
244 // unconstrained variable.
246 // @lcnr: Let's still ICE here for now. I want a test case
250 "inference variables in normalized parameter environment: {}",
257 // FIXME: this is gonna need to be removed ...
258 /// Normalizes the parameter environment, reporting errors if they occur.
259 #[instrument(level = "debug", skip(tcx))]
260 pub fn normalize_param_env_or_error<'tcx>(
262 unnormalized_env: ty::ParamEnv<'tcx>,
263 cause: ObligationCause<'tcx>,
264 ) -> ty::ParamEnv<'tcx> {
265 // I'm not wild about reporting errors here; I'd prefer to
266 // have the errors get reported at a defined place (e.g.,
267 // during typeck). Instead I have all parameter
268 // environments, in effect, going through this function
269 // and hence potentially reporting errors. This ensures of
270 // course that we never forget to normalize (the
271 // alternative seemed like it would involve a lot of
272 // manual invocations of this fn -- and then we'd have to
273 // deal with the errors at each of those sites).
275 // In any case, in practice, typeck constructs all the
276 // parameter environments once for every fn as it goes,
277 // and errors will get reported then; so outside of type inference we
278 // can be sure that no errors should occur.
279 let mut predicates: Vec<_> =
280 util::elaborate_predicates(tcx, unnormalized_env.caller_bounds().into_iter())
281 .map(|obligation| obligation.predicate)
284 debug!("normalize_param_env_or_error: elaborated-predicates={:?}", predicates);
286 let elaborated_env = ty::ParamEnv::new(
287 tcx.intern_predicates(&predicates),
288 unnormalized_env.reveal(),
289 unnormalized_env.constness(),
292 // HACK: we are trying to normalize the param-env inside *itself*. The problem is that
293 // normalization expects its param-env to be already normalized, which means we have
296 // The way we handle this is by normalizing the param-env inside an unnormalized version
297 // of the param-env, which means that if the param-env contains unnormalized projections,
298 // we'll have some normalization failures. This is unfortunate.
300 // Lazy normalization would basically handle this by treating just the
301 // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
303 // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
304 // types, so to make the situation less bad, we normalize all the predicates *but*
305 // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
306 // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
308 // This works fairly well because trait matching does not actually care about param-env
309 // TypeOutlives predicates - these are normally used by regionck.
310 let outlives_predicates: Vec<_> = predicates
311 .drain_filter(|predicate| {
313 predicate.kind().skip_binder(),
314 ty::PredicateKind::Clause(ty::Clause::TypeOutlives(..))
320 "normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
321 predicates, outlives_predicates
323 let Ok(non_outlives_predicates) = do_normalize_predicates(
329 // An unnormalized env is better than nothing.
330 debug!("normalize_param_env_or_error: errored resolving non-outlives predicates");
331 return elaborated_env;
334 debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates);
336 // Not sure whether it is better to include the unnormalized TypeOutlives predicates
337 // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
338 // predicates here anyway. Keeping them here anyway because it seems safer.
339 let outlives_env: Vec<_> =
340 non_outlives_predicates.iter().chain(&outlives_predicates).cloned().collect();
341 let outlives_env = ty::ParamEnv::new(
342 tcx.intern_predicates(&outlives_env),
343 unnormalized_env.reveal(),
344 unnormalized_env.constness(),
346 let Ok(outlives_predicates) = do_normalize_predicates(
352 // An unnormalized env is better than nothing.
353 debug!("normalize_param_env_or_error: errored resolving outlives predicates");
354 return elaborated_env;
356 debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates);
358 let mut predicates = non_outlives_predicates;
359 predicates.extend(outlives_predicates);
360 debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
362 tcx.intern_predicates(&predicates),
363 unnormalized_env.reveal(),
364 unnormalized_env.constness(),
368 /// Normalize a type and process all resulting obligations, returning any errors
369 #[instrument(skip_all)]
370 pub fn fully_normalize<'tcx, T>(
371 infcx: &InferCtxt<'tcx>,
372 cause: ObligationCause<'tcx>,
373 param_env: ty::ParamEnv<'tcx>,
375 ) -> Result<T, Vec<FulfillmentError<'tcx>>>
377 T: TypeFoldable<'tcx>,
379 let ocx = ObligationCtxt::new(infcx);
381 let normalized_value = ocx.normalize(&cause, param_env, value);
382 debug!(?normalized_value);
383 debug!("select_all_or_error start");
384 let errors = ocx.select_all_or_error();
385 if !errors.is_empty() {
388 debug!("select_all_or_error complete");
389 let resolved_value = infcx.resolve_vars_if_possible(normalized_value);
390 debug!(?resolved_value);
394 /// Process an obligation (and any nested obligations that come from it) to
395 /// completion, returning any errors
396 pub fn fully_solve_obligation<'tcx>(
397 infcx: &InferCtxt<'tcx>,
398 obligation: PredicateObligation<'tcx>,
399 ) -> Vec<FulfillmentError<'tcx>> {
400 fully_solve_obligations(infcx, [obligation])
403 /// Process a set of obligations (and any nested obligations that come from them)
405 pub fn fully_solve_obligations<'tcx>(
406 infcx: &InferCtxt<'tcx>,
407 obligations: impl IntoIterator<Item = PredicateObligation<'tcx>>,
408 ) -> Vec<FulfillmentError<'tcx>> {
409 let ocx = ObligationCtxt::new(infcx);
410 ocx.register_obligations(obligations);
411 ocx.select_all_or_error()
414 /// Process a bound (and any nested obligations that come from it) to completion.
415 /// This is a convenience function for traits that have no generic arguments, such
416 /// as auto traits, and builtin traits like Copy or Sized.
417 pub fn fully_solve_bound<'tcx>(
418 infcx: &InferCtxt<'tcx>,
419 cause: ObligationCause<'tcx>,
420 param_env: ty::ParamEnv<'tcx>,
423 ) -> Vec<FulfillmentError<'tcx>> {
425 let trait_ref = tcx.mk_trait_ref(bound, [ty]);
426 let obligation = Obligation::new(tcx, cause, param_env, ty::Binder::dummy(trait_ref));
428 fully_solve_obligation(infcx, obligation)
431 /// Normalizes the predicates and checks whether they hold in an empty environment. If this
432 /// returns true, then either normalize encountered an error or one of the predicates did not
433 /// hold. Used when creating vtables to check for unsatisfiable methods.
434 pub fn impossible_predicates<'tcx>(
436 predicates: Vec<ty::Predicate<'tcx>>,
438 debug!("impossible_predicates(predicates={:?})", predicates);
440 let infcx = tcx.infer_ctxt().build();
441 let param_env = ty::ParamEnv::reveal_all();
442 let ocx = ObligationCtxt::new(&infcx);
443 let predicates = ocx.normalize(&ObligationCause::dummy(), param_env, predicates);
444 for predicate in predicates {
445 let obligation = Obligation::new(tcx, ObligationCause::dummy(), param_env, predicate);
446 ocx.register_obligation(obligation);
448 let errors = ocx.select_all_or_error();
450 let result = !errors.is_empty();
451 debug!("impossible_predicates = {:?}", result);
455 fn subst_and_check_impossible_predicates<'tcx>(
457 key: (DefId, SubstsRef<'tcx>),
459 debug!("subst_and_check_impossible_predicates(key={:?})", key);
461 let mut predicates = tcx.predicates_of(key.0).instantiate(tcx, key.1).predicates;
463 // Specifically check trait fulfillment to avoid an error when trying to resolve
465 if let Some(trait_def_id) = tcx.trait_of_item(key.0) {
466 let trait_ref = ty::TraitRef::from_method(tcx, trait_def_id, key.1);
467 predicates.push(ty::Binder::dummy(trait_ref).to_predicate(tcx));
470 predicates.retain(|predicate| !predicate.needs_subst());
471 let result = impossible_predicates(tcx, predicates);
473 debug!("subst_and_check_impossible_predicates(key={:?}) = {:?}", key, result);
477 /// Checks whether a trait's method is impossible to call on a given impl.
479 /// This only considers predicates that reference the impl's generics, and not
480 /// those that reference the method's generics.
481 fn is_impossible_method(tcx: TyCtxt<'_>, (impl_def_id, trait_item_def_id): (DefId, DefId)) -> bool {
482 struct ReferencesOnlyParentGenerics<'tcx> {
484 generics: &'tcx ty::Generics,
485 trait_item_def_id: DefId,
487 impl<'tcx> ty::TypeVisitor<'tcx> for ReferencesOnlyParentGenerics<'tcx> {
489 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
490 // If this is a parameter from the trait item's own generics, then bail
491 if let ty::Param(param) = t.kind()
492 && let param_def_id = self.generics.type_param(param, self.tcx).def_id
493 && self.tcx.parent(param_def_id) == self.trait_item_def_id
495 return ControlFlow::Break(());
497 t.super_visit_with(self)
499 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
500 if let ty::ReEarlyBound(param) = r.kind()
501 && let param_def_id = self.generics.region_param(¶m, self.tcx).def_id
502 && self.tcx.parent(param_def_id) == self.trait_item_def_id
504 return ControlFlow::Break(());
506 r.super_visit_with(self)
508 fn visit_const(&mut self, ct: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
509 if let ty::ConstKind::Param(param) = ct.kind()
510 && let param_def_id = self.generics.const_param(¶m, self.tcx).def_id
511 && self.tcx.parent(param_def_id) == self.trait_item_def_id
513 return ControlFlow::Break(());
515 ct.super_visit_with(self)
519 let generics = tcx.generics_of(trait_item_def_id);
520 let predicates = tcx.predicates_of(trait_item_def_id);
521 let impl_trait_ref = tcx
522 .impl_trait_ref(impl_def_id)
523 .expect("expected impl to correspond to trait")
525 let param_env = tcx.param_env(impl_def_id);
527 let mut visitor = ReferencesOnlyParentGenerics { tcx, generics, trait_item_def_id };
528 let predicates_for_trait = predicates.predicates.iter().filter_map(|(pred, span)| {
529 if pred.visit_with(&mut visitor).is_continue() {
530 Some(Obligation::new(
532 ObligationCause::dummy_with_span(*span),
534 ty::EarlyBinder(*pred).subst(tcx, impl_trait_ref.substs),
541 let infcx = tcx.infer_ctxt().ignoring_regions().build();
542 for obligation in predicates_for_trait {
543 // Ignore overflow error, to be conservative.
544 if let Ok(result) = infcx.evaluate_obligation(&obligation)
545 && !result.may_apply()
553 pub fn provide(providers: &mut ty::query::Providers) {
554 object_safety::provide(providers);
555 vtable::provide(providers);
556 *providers = ty::query::Providers {
557 specialization_graph_of: specialize::specialization_graph_provider,
558 specializes: specialize::specializes,
559 subst_and_check_impossible_predicates,
560 is_impossible_method,