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 /// Canonical 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 generic_bounds.into_iter().enumerate().map(move |(idx, (predicate, span))| Obligation {
119 cause: cause(idx, span),
126 /// Determines whether the type `ty` is known to meet `bound` and
127 /// returns true if so. Returns false if `ty` either does not meet
128 /// `bound` or is not known to meet bound (note that this is
129 /// conservative towards *no impl*, which is the opposite of the
130 /// `evaluate` methods).
131 pub fn type_known_to_meet_bound_modulo_regions<'tcx>(
132 infcx: &InferCtxt<'tcx>,
133 param_env: ty::ParamEnv<'tcx>,
138 let trait_ref = ty::Binder::dummy(infcx.tcx.mk_trait_ref(def_id, [ty]));
139 pred_known_to_hold_modulo_regions(infcx, param_env, trait_ref.without_const(), span)
142 #[instrument(level = "debug", skip(infcx, param_env, span, pred), ret)]
143 fn pred_known_to_hold_modulo_regions<'tcx>(
144 infcx: &InferCtxt<'tcx>,
145 param_env: ty::ParamEnv<'tcx>,
146 pred: impl ToPredicate<'tcx> + TypeVisitable<'tcx>,
149 let has_non_region_infer = pred.has_non_region_infer();
150 let obligation = Obligation {
152 // We can use a dummy node-id here because we won't pay any mind
153 // to region obligations that arise (there shouldn't really be any
155 cause: ObligationCause::misc(span, hir::CRATE_HIR_ID),
157 predicate: pred.to_predicate(infcx.tcx),
160 let result = infcx.predicate_must_hold_modulo_regions(&obligation);
163 if result && has_non_region_infer {
164 // Because of inference "guessing", selection can sometimes claim
165 // to succeed while the success requires a guess. To ensure
166 // this function's result remains infallible, we must confirm
167 // that guess. While imperfect, I believe this is sound.
169 // FIXME(@lcnr): this function doesn't seem right.
170 // The handling of regions in this area of the code is terrible,
171 // see issue #29149. We should be able to improve on this with
173 let errors = fully_solve_obligation(infcx, obligation);
175 // Note: we only assume something is `Copy` if we can
176 // *definitively* show that it implements `Copy`. Otherwise,
177 // assume it is move; linear is always ok.
190 #[instrument(level = "debug", skip(tcx, elaborated_env))]
191 fn do_normalize_predicates<'tcx>(
193 cause: ObligationCause<'tcx>,
194 elaborated_env: ty::ParamEnv<'tcx>,
195 predicates: Vec<ty::Predicate<'tcx>>,
196 ) -> Result<Vec<ty::Predicate<'tcx>>, ErrorGuaranteed> {
197 let span = cause.span;
198 // FIXME. We should really... do something with these region
199 // obligations. But this call just continues the older
200 // behavior (i.e., doesn't cause any new bugs), and it would
201 // take some further refactoring to actually solve them. In
202 // particular, we would have to handle implied bounds
203 // properly, and that code is currently largely confined to
204 // regionck (though I made some efforts to extract it
207 // @arielby: In any case, these obligations are checked
208 // by wfcheck anyway, so I'm not sure we have to check
209 // them here too, and we will remove this function when
210 // we move over to lazy normalization *anyway*.
211 let infcx = tcx.infer_ctxt().ignoring_regions().build();
212 let predicates = match fully_normalize(&infcx, cause, elaborated_env, predicates) {
213 Ok(predicates) => predicates,
215 let reported = infcx.err_ctxt().report_fulfillment_errors(&errors, None);
216 return Err(reported);
220 debug!("do_normalize_predictes: normalized predicates = {:?}", predicates);
222 // We can use the `elaborated_env` here; the region code only
223 // cares about declarations like `'a: 'b`.
224 let outlives_env = OutlivesEnvironment::new(elaborated_env);
226 // FIXME: It's very weird that we ignore region obligations but apparently
227 // still need to use `resolve_regions` as we need the resolved regions in
228 // the normalized predicates.
229 let errors = infcx.resolve_regions(&outlives_env);
230 if !errors.is_empty() {
231 tcx.sess.delay_span_bug(
233 format!("failed region resolution while normalizing {elaborated_env:?}: {errors:?}"),
237 match infcx.fully_resolve(predicates) {
238 Ok(predicates) => Ok(predicates),
240 // If we encounter a fixup error, it means that some type
241 // variable wound up unconstrained. I actually don't know
242 // if this can happen, and I certainly don't expect it to
243 // happen often, but if it did happen it probably
244 // represents a legitimate failure due to some kind of
245 // unconstrained variable.
247 // @lcnr: Let's still ICE here for now. I want a test case
251 "inference variables in normalized parameter environment: {}",
258 // FIXME: this is gonna need to be removed ...
259 /// Normalizes the parameter environment, reporting errors if they occur.
260 #[instrument(level = "debug", skip(tcx))]
261 pub fn normalize_param_env_or_error<'tcx>(
263 unnormalized_env: ty::ParamEnv<'tcx>,
264 cause: ObligationCause<'tcx>,
265 ) -> ty::ParamEnv<'tcx> {
266 // I'm not wild about reporting errors here; I'd prefer to
267 // have the errors get reported at a defined place (e.g.,
268 // during typeck). Instead I have all parameter
269 // environments, in effect, going through this function
270 // and hence potentially reporting errors. This ensures of
271 // course that we never forget to normalize (the
272 // alternative seemed like it would involve a lot of
273 // manual invocations of this fn -- and then we'd have to
274 // deal with the errors at each of those sites).
276 // In any case, in practice, typeck constructs all the
277 // parameter environments once for every fn as it goes,
278 // and errors will get reported then; so outside of type inference we
279 // can be sure that no errors should occur.
280 let mut predicates: Vec<_> =
281 util::elaborate_predicates(tcx, unnormalized_env.caller_bounds().into_iter())
282 .map(|obligation| obligation.predicate)
285 debug!("normalize_param_env_or_error: elaborated-predicates={:?}", predicates);
287 let elaborated_env = ty::ParamEnv::new(
288 tcx.intern_predicates(&predicates),
289 unnormalized_env.reveal(),
290 unnormalized_env.constness(),
293 // HACK: we are trying to normalize the param-env inside *itself*. The problem is that
294 // normalization expects its param-env to be already normalized, which means we have
297 // The way we handle this is by normalizing the param-env inside an unnormalized version
298 // of the param-env, which means that if the param-env contains unnormalized projections,
299 // we'll have some normalization failures. This is unfortunate.
301 // Lazy normalization would basically handle this by treating just the
302 // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
304 // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
305 // types, so to make the situation less bad, we normalize all the predicates *but*
306 // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
307 // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
309 // This works fairly well because trait matching does not actually care about param-env
310 // TypeOutlives predicates - these are normally used by regionck.
311 let outlives_predicates: Vec<_> = predicates
312 .drain_filter(|predicate| {
314 predicate.kind().skip_binder(),
315 ty::PredicateKind::Clause(ty::Clause::TypeOutlives(..))
321 "normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
322 predicates, outlives_predicates
324 let Ok(non_outlives_predicates) = do_normalize_predicates(
330 // An unnormalized env is better than nothing.
331 debug!("normalize_param_env_or_error: errored resolving non-outlives predicates");
332 return elaborated_env;
335 debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates);
337 // Not sure whether it is better to include the unnormalized TypeOutlives predicates
338 // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
339 // predicates here anyway. Keeping them here anyway because it seems safer.
340 let outlives_env: Vec<_> =
341 non_outlives_predicates.iter().chain(&outlives_predicates).cloned().collect();
342 let outlives_env = ty::ParamEnv::new(
343 tcx.intern_predicates(&outlives_env),
344 unnormalized_env.reveal(),
345 unnormalized_env.constness(),
347 let Ok(outlives_predicates) = do_normalize_predicates(
353 // An unnormalized env is better than nothing.
354 debug!("normalize_param_env_or_error: errored resolving outlives predicates");
355 return elaborated_env;
357 debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates);
359 let mut predicates = non_outlives_predicates;
360 predicates.extend(outlives_predicates);
361 debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
363 tcx.intern_predicates(&predicates),
364 unnormalized_env.reveal(),
365 unnormalized_env.constness(),
369 /// Normalize a type and process all resulting obligations, returning any errors
370 #[instrument(skip_all)]
371 pub fn fully_normalize<'tcx, T>(
372 infcx: &InferCtxt<'tcx>,
373 cause: ObligationCause<'tcx>,
374 param_env: ty::ParamEnv<'tcx>,
376 ) -> Result<T, Vec<FulfillmentError<'tcx>>>
378 T: TypeFoldable<'tcx>,
380 let ocx = ObligationCtxt::new(infcx);
382 let normalized_value = ocx.normalize(&cause, param_env, value);
383 debug!(?normalized_value);
384 debug!("select_all_or_error start");
385 let errors = ocx.select_all_or_error();
386 if !errors.is_empty() {
389 debug!("select_all_or_error complete");
390 let resolved_value = infcx.resolve_vars_if_possible(normalized_value);
391 debug!(?resolved_value);
395 /// Process an obligation (and any nested obligations that come from it) to
396 /// completion, returning any errors
397 pub fn fully_solve_obligation<'tcx>(
398 infcx: &InferCtxt<'tcx>,
399 obligation: PredicateObligation<'tcx>,
400 ) -> Vec<FulfillmentError<'tcx>> {
401 fully_solve_obligations(infcx, [obligation])
404 /// Process a set of obligations (and any nested obligations that come from them)
406 pub fn fully_solve_obligations<'tcx>(
407 infcx: &InferCtxt<'tcx>,
408 obligations: impl IntoIterator<Item = PredicateObligation<'tcx>>,
409 ) -> Vec<FulfillmentError<'tcx>> {
410 let ocx = ObligationCtxt::new(infcx);
411 ocx.register_obligations(obligations);
412 ocx.select_all_or_error()
415 /// Process a bound (and any nested obligations that come from it) to completion.
416 /// This is a convenience function for traits that have no generic arguments, such
417 /// as auto traits, and builtin traits like Copy or Sized.
418 pub fn fully_solve_bound<'tcx>(
419 infcx: &InferCtxt<'tcx>,
420 cause: ObligationCause<'tcx>,
421 param_env: ty::ParamEnv<'tcx>,
424 ) -> Vec<FulfillmentError<'tcx>> {
426 let trait_ref = tcx.mk_trait_ref(bound, [ty]);
427 let obligation = Obligation::new(tcx, cause, param_env, ty::Binder::dummy(trait_ref));
429 fully_solve_obligation(infcx, obligation)
432 /// Normalizes the predicates and checks whether they hold in an empty environment. If this
433 /// returns true, then either normalize encountered an error or one of the predicates did not
434 /// hold. Used when creating vtables to check for unsatisfiable methods.
435 pub fn impossible_predicates<'tcx>(
437 predicates: Vec<ty::Predicate<'tcx>>,
439 debug!("impossible_predicates(predicates={:?})", predicates);
441 let infcx = tcx.infer_ctxt().build();
442 let param_env = ty::ParamEnv::reveal_all();
443 let ocx = ObligationCtxt::new(&infcx);
444 let predicates = ocx.normalize(&ObligationCause::dummy(), param_env, predicates);
445 for predicate in predicates {
446 let obligation = Obligation::new(tcx, ObligationCause::dummy(), param_env, predicate);
447 ocx.register_obligation(obligation);
449 let errors = ocx.select_all_or_error();
451 let result = !errors.is_empty();
452 debug!("impossible_predicates = {:?}", result);
456 fn subst_and_check_impossible_predicates<'tcx>(
458 key: (DefId, SubstsRef<'tcx>),
460 debug!("subst_and_check_impossible_predicates(key={:?})", key);
462 let mut predicates = tcx.predicates_of(key.0).instantiate(tcx, key.1).predicates;
464 // Specifically check trait fulfillment to avoid an error when trying to resolve
466 if let Some(trait_def_id) = tcx.trait_of_item(key.0) {
467 let trait_ref = ty::TraitRef::from_method(tcx, trait_def_id, key.1);
468 predicates.push(ty::Binder::dummy(trait_ref).to_predicate(tcx));
471 predicates.retain(|predicate| !predicate.needs_subst());
472 let result = impossible_predicates(tcx, predicates);
474 debug!("subst_and_check_impossible_predicates(key={:?}) = {:?}", key, result);
478 /// Checks whether a trait's method is impossible to call on a given impl.
480 /// This only considers predicates that reference the impl's generics, and not
481 /// those that reference the method's generics.
482 fn is_impossible_method(tcx: TyCtxt<'_>, (impl_def_id, trait_item_def_id): (DefId, DefId)) -> bool {
483 struct ReferencesOnlyParentGenerics<'tcx> {
485 generics: &'tcx ty::Generics,
486 trait_item_def_id: DefId,
488 impl<'tcx> ty::TypeVisitor<'tcx> for ReferencesOnlyParentGenerics<'tcx> {
490 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
491 // If this is a parameter from the trait item's own generics, then bail
492 if let ty::Param(param) = t.kind()
493 && let param_def_id = self.generics.type_param(param, self.tcx).def_id
494 && self.tcx.parent(param_def_id) == self.trait_item_def_id
496 return ControlFlow::BREAK;
498 t.super_visit_with(self)
500 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
501 if let ty::ReEarlyBound(param) = r.kind()
502 && let param_def_id = self.generics.region_param(¶m, self.tcx).def_id
503 && self.tcx.parent(param_def_id) == self.trait_item_def_id
505 return ControlFlow::BREAK;
507 r.super_visit_with(self)
509 fn visit_const(&mut self, ct: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
510 if let ty::ConstKind::Param(param) = ct.kind()
511 && let param_def_id = self.generics.const_param(¶m, self.tcx).def_id
512 && self.tcx.parent(param_def_id) == self.trait_item_def_id
514 return ControlFlow::BREAK;
516 ct.super_visit_with(self)
520 let generics = tcx.generics_of(trait_item_def_id);
521 let predicates = tcx.predicates_of(trait_item_def_id);
522 let impl_trait_ref = tcx
523 .impl_trait_ref(impl_def_id)
524 .expect("expected impl to correspond to trait")
526 let param_env = tcx.param_env(impl_def_id);
528 let mut visitor = ReferencesOnlyParentGenerics { tcx, generics, trait_item_def_id };
529 let predicates_for_trait = predicates.predicates.iter().filter_map(|(pred, span)| {
530 if pred.visit_with(&mut visitor).is_continue() {
531 Some(Obligation::new(
533 ObligationCause::dummy_with_span(*span),
535 ty::EarlyBinder(*pred).subst(tcx, impl_trait_ref.substs),
542 let infcx = tcx.infer_ctxt().ignoring_regions().build();
543 for obligation in predicates_for_trait {
544 // Ignore overflow error, to be conservative.
545 if let Ok(result) = infcx.evaluate_obligation(&obligation)
546 && !result.may_apply()
554 pub fn provide(providers: &mut ty::query::Providers) {
555 object_safety::provide(providers);
556 vtable::provide(providers);
557 *providers = ty::query::Providers {
558 specialization_graph_of: specialize::specialization_graph_provider,
559 specializes: specialize::specializes,
560 subst_and_check_impossible_predicates,
561 is_impossible_method,