1 //! Trait Resolution. See the [rustc guide] for more information on how this works.
3 //! [rustc guide]: https://rust-lang.github.io/rustc-dev-guide/traits/resolution.html
10 pub mod error_reporting;
24 use crate::infer::outlives::env::OutlivesEnvironment;
25 use crate::infer::{InferCtxt, SuppressRegionErrors, TyCtxtInferExt};
26 use rustc::middle::region;
27 use rustc::ty::error::{ExpectedFound, TypeError};
28 use rustc::ty::fold::TypeFoldable;
29 use rustc::ty::subst::{InternalSubsts, SubstsRef};
30 use rustc::ty::{self, GenericParamDefKind, ToPredicate, Ty, TyCtxt, WithConstness};
31 use rustc::util::common::ErrorReported;
33 use rustc_hir::def_id::DefId;
34 use rustc_span::{Span, DUMMY_SP};
38 pub use self::FulfillmentErrorCode::*;
39 pub use self::ObligationCauseCode::*;
40 pub use self::SelectionError::*;
41 pub use self::Vtable::*;
43 pub use self::coherence::{add_placeholder_note, orphan_check, overlapping_impls};
44 pub use self::coherence::{OrphanCheckErr, OverlapResult};
45 pub use self::engine::{TraitEngine, TraitEngineExt};
46 pub use self::fulfill::{FulfillmentContext, PendingPredicateObligation};
47 pub use self::object_safety::astconv_object_safety_violations;
48 pub use self::object_safety::is_vtable_safe_method;
49 pub use self::object_safety::MethodViolationCode;
50 pub use self::object_safety::ObjectSafetyViolation;
51 pub use self::on_unimplemented::{OnUnimplementedDirective, OnUnimplementedNote};
52 pub use self::project::MismatchedProjectionTypes;
53 pub use self::project::{
54 normalize, normalize_projection_type, normalize_to, poly_project_and_unify_type,
56 pub use self::project::{Normalized, ProjectionCache, ProjectionCacheSnapshot, Reveal};
57 pub use self::select::{EvaluationCache, SelectionCache, SelectionContext};
58 pub use self::select::{EvaluationResult, IntercrateAmbiguityCause, OverflowError};
59 pub use self::specialize::find_associated_item;
60 pub use self::specialize::specialization_graph::FutureCompatOverlapError;
61 pub use self::specialize::specialization_graph::FutureCompatOverlapErrorKind;
62 pub use self::specialize::{specialization_graph, translate_substs, OverlapError};
63 pub use self::structural_match::search_for_structural_match_violation;
64 pub use self::structural_match::type_marked_structural;
65 pub use self::structural_match::NonStructuralMatchTy;
66 pub use self::util::{elaborate_predicates, elaborate_trait_ref, elaborate_trait_refs};
67 pub use self::util::{expand_trait_aliases, TraitAliasExpander};
69 get_vtable_index_of_object_method, impl_is_default, impl_item_is_final,
70 predicate_for_trait_def, upcast_choices,
73 supertrait_def_ids, supertraits, transitive_bounds, SupertraitDefIds, Supertraits,
76 pub use rustc::traits::*;
78 /// Whether to skip the leak check, as part of a future compatibility warning step.
79 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
80 pub enum SkipLeakCheck {
86 fn is_yes(self) -> bool {
87 self == SkipLeakCheck::Yes
91 /// The "default" for skip-leak-check corresponds to the current
92 /// behavior (do not skip the leak check) -- not the behavior we are
93 /// transitioning into.
94 impl Default for SkipLeakCheck {
95 fn default() -> Self {
100 /// The mode that trait queries run in.
101 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
102 pub enum TraitQueryMode {
103 // Standard/un-canonicalized queries get accurate
104 // spans etc. passed in and hence can do reasonable
105 // error reporting on their own.
107 // Canonicalized queries get dummy spans and hence
108 // must generally propagate errors to
109 // pre-canonicalization callsites.
113 /// An `Obligation` represents some trait reference (e.g., `int: Eq`) for
114 /// which the vtable must be found. The process of finding a vtable is
115 /// called "resolving" the `Obligation`. This process consists of
116 /// either identifying an `impl` (e.g., `impl Eq for int`) that
117 /// provides the required vtable, or else finding a bound that is in
118 /// scope. The eventual result is usually a `Selection` (defined below).
119 #[derive(Clone, PartialEq, Eq, Hash)]
120 pub struct Obligation<'tcx, T> {
121 /// The reason we have to prove this thing.
122 pub cause: ObligationCause<'tcx>,
124 /// The environment in which we should prove this thing.
125 pub param_env: ty::ParamEnv<'tcx>,
127 /// The thing we are trying to prove.
130 /// If we started proving this as a result of trying to prove
131 /// something else, track the total depth to ensure termination.
132 /// If this goes over a certain threshold, we abort compilation --
133 /// in such cases, we can not say whether or not the predicate
134 /// holds for certain. Stupid halting problem; such a drag.
135 pub recursion_depth: usize,
138 pub type PredicateObligation<'tcx> = Obligation<'tcx, ty::Predicate<'tcx>>;
139 pub type TraitObligation<'tcx> = Obligation<'tcx, ty::PolyTraitPredicate<'tcx>>;
141 // `PredicateObligation` is used a lot. Make sure it doesn't unintentionally get bigger.
142 #[cfg(target_arch = "x86_64")]
143 static_assert_size!(PredicateObligation<'_>, 112);
145 pub type Obligations<'tcx, O> = Vec<Obligation<'tcx, O>>;
146 pub type PredicateObligations<'tcx> = Vec<PredicateObligation<'tcx>>;
147 pub type TraitObligations<'tcx> = Vec<TraitObligation<'tcx>>;
149 pub type Selection<'tcx> = Vtable<'tcx, PredicateObligation<'tcx>>;
151 pub struct FulfillmentError<'tcx> {
152 pub obligation: PredicateObligation<'tcx>,
153 pub code: FulfillmentErrorCode<'tcx>,
154 /// Diagnostics only: we opportunistically change the `code.span` when we encounter an
155 /// obligation error caused by a call argument. When this is the case, we also signal that in
156 /// this field to ensure accuracy of suggestions.
157 pub points_at_arg_span: bool,
161 pub enum FulfillmentErrorCode<'tcx> {
162 CodeSelectionError(SelectionError<'tcx>),
163 CodeProjectionError(MismatchedProjectionTypes<'tcx>),
164 CodeSubtypeError(ExpectedFound<Ty<'tcx>>, TypeError<'tcx>), // always comes from a SubtypePredicate
168 /// Creates predicate obligations from the generic bounds.
169 pub fn predicates_for_generics<'tcx>(
170 cause: ObligationCause<'tcx>,
171 param_env: ty::ParamEnv<'tcx>,
172 generic_bounds: &ty::InstantiatedPredicates<'tcx>,
173 ) -> PredicateObligations<'tcx> {
174 util::predicates_for_generics(cause, 0, param_env, generic_bounds)
177 /// Determines whether the type `ty` is known to meet `bound` and
178 /// returns true if so. Returns false if `ty` either does not meet
179 /// `bound` or is not known to meet bound (note that this is
180 /// conservative towards *no impl*, which is the opposite of the
181 /// `evaluate` methods).
182 pub fn type_known_to_meet_bound_modulo_regions<'a, 'tcx>(
183 infcx: &InferCtxt<'a, 'tcx>,
184 param_env: ty::ParamEnv<'tcx>,
190 "type_known_to_meet_bound_modulo_regions(ty={:?}, bound={:?})",
192 infcx.tcx.def_path_str(def_id)
195 let trait_ref = ty::TraitRef { def_id, substs: infcx.tcx.mk_substs_trait(ty, &[]) };
196 let obligation = Obligation {
198 cause: ObligationCause::misc(span, hir::DUMMY_HIR_ID),
200 predicate: trait_ref.without_const().to_predicate(),
203 let result = infcx.predicate_must_hold_modulo_regions(&obligation);
205 "type_known_to_meet_ty={:?} bound={} => {:?}",
207 infcx.tcx.def_path_str(def_id),
211 if result && ty.has_infer_types_or_consts() {
212 // Because of inference "guessing", selection can sometimes claim
213 // to succeed while the success requires a guess. To ensure
214 // this function's result remains infallible, we must confirm
215 // that guess. While imperfect, I believe this is sound.
217 // The handling of regions in this area of the code is terrible,
218 // see issue #29149. We should be able to improve on this with
220 let mut fulfill_cx = FulfillmentContext::new_ignoring_regions();
222 // We can use a dummy node-id here because we won't pay any mind
223 // to region obligations that arise (there shouldn't really be any
225 let cause = ObligationCause::misc(span, hir::DUMMY_HIR_ID);
227 fulfill_cx.register_bound(infcx, param_env, ty, def_id, cause);
229 // Note: we only assume something is `Copy` if we can
230 // *definitively* show that it implements `Copy`. Otherwise,
231 // assume it is move; linear is always ok.
232 match fulfill_cx.select_all_or_error(infcx) {
235 "type_known_to_meet_bound_modulo_regions: ty={:?} bound={} success",
237 infcx.tcx.def_path_str(def_id)
243 "type_known_to_meet_bound_modulo_regions: ty={:?} bound={} errors={:?}",
245 infcx.tcx.def_path_str(def_id),
256 fn do_normalize_predicates<'tcx>(
258 region_context: DefId,
259 cause: ObligationCause<'tcx>,
260 elaborated_env: ty::ParamEnv<'tcx>,
261 predicates: Vec<ty::Predicate<'tcx>>,
262 ) -> Result<Vec<ty::Predicate<'tcx>>, ErrorReported> {
264 "do_normalize_predicates(predicates={:?}, region_context={:?}, cause={:?})",
265 predicates, region_context, cause,
267 let span = cause.span;
268 tcx.infer_ctxt().enter(|infcx| {
269 // FIXME. We should really... do something with these region
270 // obligations. But this call just continues the older
271 // behavior (i.e., doesn't cause any new bugs), and it would
272 // take some further refactoring to actually solve them. In
273 // particular, we would have to handle implied bounds
274 // properly, and that code is currently largely confined to
275 // regionck (though I made some efforts to extract it
278 // @arielby: In any case, these obligations are checked
279 // by wfcheck anyway, so I'm not sure we have to check
280 // them here too, and we will remove this function when
281 // we move over to lazy normalization *anyway*.
282 let fulfill_cx = FulfillmentContext::new_ignoring_regions();
284 match fully_normalize(&infcx, fulfill_cx, cause, elaborated_env, &predicates) {
285 Ok(predicates) => predicates,
287 infcx.report_fulfillment_errors(&errors, None, false);
288 return Err(ErrorReported);
292 debug!("do_normalize_predictes: normalized predicates = {:?}", predicates);
294 let region_scope_tree = region::ScopeTree::default();
296 // We can use the `elaborated_env` here; the region code only
297 // cares about declarations like `'a: 'b`.
298 let outlives_env = OutlivesEnvironment::new(elaborated_env);
300 infcx.resolve_regions_and_report_errors(
304 SuppressRegionErrors::default(),
307 let predicates = match infcx.fully_resolve(&predicates) {
308 Ok(predicates) => predicates,
310 // If we encounter a fixup error, it means that some type
311 // variable wound up unconstrained. I actually don't know
312 // if this can happen, and I certainly don't expect it to
313 // happen often, but if it did happen it probably
314 // represents a legitimate failure due to some kind of
315 // unconstrained variable, and it seems better not to ICE,
316 // all things considered.
317 tcx.sess.span_err(span, &fixup_err.to_string());
318 return Err(ErrorReported);
321 if predicates.has_local_value() {
322 // FIXME: shouldn't we, you know, actually report an error here? or an ICE?
330 // FIXME: this is gonna need to be removed ...
331 /// Normalizes the parameter environment, reporting errors if they occur.
332 pub fn normalize_param_env_or_error<'tcx>(
334 region_context: DefId,
335 unnormalized_env: ty::ParamEnv<'tcx>,
336 cause: ObligationCause<'tcx>,
337 ) -> ty::ParamEnv<'tcx> {
338 // I'm not wild about reporting errors here; I'd prefer to
339 // have the errors get reported at a defined place (e.g.,
340 // during typeck). Instead I have all parameter
341 // environments, in effect, going through this function
342 // and hence potentially reporting errors. This ensures of
343 // course that we never forget to normalize (the
344 // alternative seemed like it would involve a lot of
345 // manual invocations of this fn -- and then we'd have to
346 // deal with the errors at each of those sites).
348 // In any case, in practice, typeck constructs all the
349 // parameter environments once for every fn as it goes,
350 // and errors will get reported then; so after typeck we
351 // can be sure that no errors should occur.
354 "normalize_param_env_or_error(region_context={:?}, unnormalized_env={:?}, cause={:?})",
355 region_context, unnormalized_env, cause
358 let mut predicates: Vec<_> =
359 util::elaborate_predicates(tcx, unnormalized_env.caller_bounds.to_vec()).collect();
361 debug!("normalize_param_env_or_error: elaborated-predicates={:?}", predicates);
363 let elaborated_env = ty::ParamEnv::new(
364 tcx.intern_predicates(&predicates),
365 unnormalized_env.reveal,
366 unnormalized_env.def_id,
369 // HACK: we are trying to normalize the param-env inside *itself*. The problem is that
370 // normalization expects its param-env to be already normalized, which means we have
373 // The way we handle this is by normalizing the param-env inside an unnormalized version
374 // of the param-env, which means that if the param-env contains unnormalized projections,
375 // we'll have some normalization failures. This is unfortunate.
377 // Lazy normalization would basically handle this by treating just the
378 // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
380 // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
381 // types, so to make the situation less bad, we normalize all the predicates *but*
382 // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
383 // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
385 // This works fairly well because trait matching does not actually care about param-env
386 // TypeOutlives predicates - these are normally used by regionck.
387 let outlives_predicates: Vec<_> = predicates
388 .drain_filter(|predicate| match predicate {
389 ty::Predicate::TypeOutlives(..) => true,
395 "normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
396 predicates, outlives_predicates
398 let non_outlives_predicates = match do_normalize_predicates(
405 Ok(predicates) => predicates,
406 // An unnormalized env is better than nothing.
407 Err(ErrorReported) => {
408 debug!("normalize_param_env_or_error: errored resolving non-outlives predicates");
409 return elaborated_env;
413 debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates);
415 // Not sure whether it is better to include the unnormalized TypeOutlives predicates
416 // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
417 // predicates here anyway. Keeping them here anyway because it seems safer.
418 let outlives_env: Vec<_> =
419 non_outlives_predicates.iter().chain(&outlives_predicates).cloned().collect();
421 ty::ParamEnv::new(tcx.intern_predicates(&outlives_env), unnormalized_env.reveal, None);
422 let outlives_predicates = match do_normalize_predicates(
429 Ok(predicates) => predicates,
430 // An unnormalized env is better than nothing.
431 Err(ErrorReported) => {
432 debug!("normalize_param_env_or_error: errored resolving outlives predicates");
433 return elaborated_env;
436 debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates);
438 let mut predicates = non_outlives_predicates;
439 predicates.extend(outlives_predicates);
440 debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
442 tcx.intern_predicates(&predicates),
443 unnormalized_env.reveal,
444 unnormalized_env.def_id,
448 pub fn fully_normalize<'a, 'tcx, T>(
449 infcx: &InferCtxt<'a, 'tcx>,
450 mut fulfill_cx: FulfillmentContext<'tcx>,
451 cause: ObligationCause<'tcx>,
452 param_env: ty::ParamEnv<'tcx>,
454 ) -> Result<T, Vec<FulfillmentError<'tcx>>>
456 T: TypeFoldable<'tcx>,
458 debug!("fully_normalize_with_fulfillcx(value={:?})", value);
459 let selcx = &mut SelectionContext::new(infcx);
460 let Normalized { value: normalized_value, obligations } =
461 project::normalize(selcx, param_env, cause, value);
463 "fully_normalize: normalized_value={:?} obligations={:?}",
464 normalized_value, obligations
466 for obligation in obligations {
467 fulfill_cx.register_predicate_obligation(selcx.infcx(), obligation);
470 debug!("fully_normalize: select_all_or_error start");
471 fulfill_cx.select_all_or_error(infcx)?;
472 debug!("fully_normalize: select_all_or_error complete");
473 let resolved_value = infcx.resolve_vars_if_possible(&normalized_value);
474 debug!("fully_normalize: resolved_value={:?}", resolved_value);
478 /// Normalizes the predicates and checks whether they hold in an empty
479 /// environment. If this returns false, then either normalize
480 /// encountered an error or one of the predicates did not hold. Used
481 /// when creating vtables to check for unsatisfiable methods.
482 pub fn normalize_and_test_predicates<'tcx>(
484 predicates: Vec<ty::Predicate<'tcx>>,
486 debug!("normalize_and_test_predicates(predicates={:?})", predicates);
488 let result = tcx.infer_ctxt().enter(|infcx| {
489 let param_env = ty::ParamEnv::reveal_all();
490 let mut selcx = SelectionContext::new(&infcx);
491 let mut fulfill_cx = FulfillmentContext::new();
492 let cause = ObligationCause::dummy();
493 let Normalized { value: predicates, obligations } =
494 normalize(&mut selcx, param_env, cause.clone(), &predicates);
495 for obligation in obligations {
496 fulfill_cx.register_predicate_obligation(&infcx, obligation);
498 for predicate in predicates {
499 let obligation = Obligation::new(cause.clone(), param_env, predicate);
500 fulfill_cx.register_predicate_obligation(&infcx, obligation);
503 fulfill_cx.select_all_or_error(&infcx).is_ok()
505 debug!("normalize_and_test_predicates(predicates={:?}) = {:?}", predicates, result);
509 fn substitute_normalize_and_test_predicates<'tcx>(
511 key: (DefId, SubstsRef<'tcx>),
513 debug!("substitute_normalize_and_test_predicates(key={:?})", key);
515 let predicates = tcx.predicates_of(key.0).instantiate(tcx, key.1).predicates;
516 let result = normalize_and_test_predicates(tcx, predicates);
518 debug!("substitute_normalize_and_test_predicates(key={:?}) = {:?}", key, result);
522 /// Given a trait `trait_ref`, iterates the vtable entries
523 /// that come from `trait_ref`, including its supertraits.
524 #[inline] // FIXME(#35870): avoid closures being unexported due to `impl Trait`.
525 fn vtable_methods<'tcx>(
527 trait_ref: ty::PolyTraitRef<'tcx>,
528 ) -> &'tcx [Option<(DefId, SubstsRef<'tcx>)>] {
529 debug!("vtable_methods({:?})", trait_ref);
531 tcx.arena.alloc_from_iter(supertraits(tcx, trait_ref).flat_map(move |trait_ref| {
532 let trait_methods = tcx
533 .associated_items(trait_ref.def_id())
534 .in_definition_order()
535 .filter(|item| item.kind == ty::AssocKind::Method);
537 // Now list each method's DefId and InternalSubsts (for within its trait).
538 // If the method can never be called from this object, produce None.
539 trait_methods.map(move |trait_method| {
540 debug!("vtable_methods: trait_method={:?}", trait_method);
541 let def_id = trait_method.def_id;
543 // Some methods cannot be called on an object; skip those.
544 if !is_vtable_safe_method(tcx, trait_ref.def_id(), &trait_method) {
545 debug!("vtable_methods: not vtable safe");
549 // The method may have some early-bound lifetimes; add regions for those.
550 let substs = trait_ref.map_bound(|trait_ref| {
551 InternalSubsts::for_item(tcx, def_id, |param, _| match param.kind {
552 GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(),
553 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const => {
554 trait_ref.substs[param.index as usize]
559 // The trait type may have higher-ranked lifetimes in it;
560 // erase them if they appear, so that we get the type
561 // at some particular call site.
563 tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &substs);
565 // It's possible that the method relies on where-clauses that
566 // do not hold for this particular set of type parameters.
567 // Note that this method could then never be called, so we
568 // do not want to try and codegen it, in that case (see #23435).
569 let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs);
570 if !normalize_and_test_predicates(tcx, predicates.predicates) {
571 debug!("vtable_methods: predicates do not hold");
575 Some((def_id, substs))
580 impl<'tcx, O> Obligation<'tcx, O> {
582 cause: ObligationCause<'tcx>,
583 param_env: ty::ParamEnv<'tcx>,
585 ) -> Obligation<'tcx, O> {
586 Obligation { cause, param_env, recursion_depth: 0, predicate }
590 cause: ObligationCause<'tcx>,
591 recursion_depth: usize,
592 param_env: ty::ParamEnv<'tcx>,
594 ) -> Obligation<'tcx, O> {
595 Obligation { cause, param_env, recursion_depth, predicate }
601 param_env: ty::ParamEnv<'tcx>,
603 ) -> Obligation<'tcx, O> {
604 Obligation::new(ObligationCause::misc(span, body_id), param_env, trait_ref)
607 pub fn with<P>(&self, value: P) -> Obligation<'tcx, P> {
609 cause: self.cause.clone(),
610 param_env: self.param_env,
611 recursion_depth: self.recursion_depth,
617 impl<'tcx> FulfillmentError<'tcx> {
619 obligation: PredicateObligation<'tcx>,
620 code: FulfillmentErrorCode<'tcx>,
621 ) -> FulfillmentError<'tcx> {
622 FulfillmentError { obligation: obligation, code: code, points_at_arg_span: false }
626 impl<'tcx> TraitObligation<'tcx> {
627 fn self_ty(&self) -> ty::Binder<Ty<'tcx>> {
628 self.predicate.map_bound(|p| p.self_ty())
632 pub fn provide(providers: &mut ty::query::Providers<'_>) {
633 object_safety::provide(providers);
634 *providers = ty::query::Providers {
635 specialization_graph_of: specialize::specialization_graph_provider,
636 specializes: specialize::specializes,
637 codegen_fulfill_obligation: codegen::codegen_fulfill_obligation,
639 substitute_normalize_and_test_predicates,