1 //! Trait Resolution. See the [rustc guide] for more information on how this works.
3 //! [rustc guide]: https://rust-lang.github.io/rustc-guide/traits/resolution.html
11 pub mod error_reporting;
25 use crate::infer::outlives::env::OutlivesEnvironment;
26 use crate::infer::{InferCtxt, SuppressRegionErrors, TyCtxtInferExt};
27 use rustc::middle::region;
28 use rustc::ty::error::{ExpectedFound, TypeError};
29 use rustc::ty::fold::TypeFoldable;
30 use rustc::ty::subst::{InternalSubsts, SubstsRef};
31 use rustc::ty::{self, GenericParamDefKind, ToPredicate, Ty, TyCtxt, WithConstness};
32 use rustc::util::common::ErrorReported;
34 use rustc_hir::def_id::DefId;
35 use rustc_span::{Span, DUMMY_SP};
39 pub use self::FulfillmentErrorCode::*;
40 pub use self::ObligationCauseCode::*;
41 pub use self::SelectionError::*;
42 pub use self::Vtable::*;
44 pub use self::coherence::{add_placeholder_note, orphan_check, overlapping_impls};
45 pub use self::coherence::{OrphanCheckErr, OverlapResult};
46 pub use self::engine::{TraitEngine, TraitEngineExt};
47 pub use self::fulfill::{FulfillmentContext, PendingPredicateObligation};
48 pub use self::object_safety::astconv_object_safety_violations;
49 pub use self::object_safety::is_vtable_safe_method;
50 pub use self::object_safety::MethodViolationCode;
51 pub use self::object_safety::ObjectSafetyViolation;
52 pub use self::on_unimplemented::{OnUnimplementedDirective, OnUnimplementedNote};
53 pub use self::project::MismatchedProjectionTypes;
54 pub use self::project::{
55 normalize, normalize_projection_type, normalize_to, poly_project_and_unify_type,
57 pub use self::project::{Normalized, ProjectionCache, ProjectionCacheSnapshot, Reveal};
58 pub use self::select::{EvaluationCache, SelectionCache, SelectionContext};
59 pub use self::select::{EvaluationResult, IntercrateAmbiguityCause, OverflowError};
60 pub use self::specialize::find_associated_item;
61 pub use self::specialize::specialization_graph::FutureCompatOverlapError;
62 pub use self::specialize::specialization_graph::FutureCompatOverlapErrorKind;
63 pub use self::specialize::{specialization_graph, translate_substs, OverlapError};
64 pub use self::structural_match::search_for_structural_match_violation;
65 pub use self::structural_match::type_marked_structural;
66 pub use self::structural_match::NonStructuralMatchTy;
67 pub use self::util::{elaborate_predicates, elaborate_trait_ref, elaborate_trait_refs};
68 pub use self::util::{expand_trait_aliases, TraitAliasExpander};
70 get_vtable_index_of_object_method, impl_is_default, impl_item_is_final,
71 predicate_for_trait_def, upcast_choices,
74 supertrait_def_ids, supertraits, transitive_bounds, SupertraitDefIds, Supertraits,
77 pub use self::chalk_fulfill::{
78 CanonicalGoal as ChalkCanonicalGoal, FulfillmentContext as ChalkFulfillmentContext,
81 pub use rustc::traits::*;
83 /// Whether to skip the leak check, as part of a future compatibility warning step.
84 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
85 pub enum SkipLeakCheck {
91 fn is_yes(self) -> bool {
92 self == SkipLeakCheck::Yes
96 /// The "default" for skip-leak-check corresponds to the current
97 /// behavior (do not skip the leak check) -- not the behavior we are
98 /// transitioning into.
99 impl Default for SkipLeakCheck {
100 fn default() -> Self {
105 /// The mode that trait queries run in.
106 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
107 pub enum TraitQueryMode {
108 // Standard/un-canonicalized queries get accurate
109 // spans etc. passed in and hence can do reasonable
110 // error reporting on their own.
112 // Canonicalized queries get dummy spans and hence
113 // must generally propagate errors to
114 // pre-canonicalization callsites.
118 /// An `Obligation` represents some trait reference (e.g., `int: Eq`) for
119 /// which the vtable must be found. The process of finding a vtable is
120 /// called "resolving" the `Obligation`. This process consists of
121 /// either identifying an `impl` (e.g., `impl Eq for int`) that
122 /// provides the required vtable, or else finding a bound that is in
123 /// scope. The eventual result is usually a `Selection` (defined below).
124 #[derive(Clone, PartialEq, Eq, Hash)]
125 pub struct Obligation<'tcx, T> {
126 /// The reason we have to prove this thing.
127 pub cause: ObligationCause<'tcx>,
129 /// The environment in which we should prove this thing.
130 pub param_env: ty::ParamEnv<'tcx>,
132 /// The thing we are trying to prove.
135 /// If we started proving this as a result of trying to prove
136 /// something else, track the total depth to ensure termination.
137 /// If this goes over a certain threshold, we abort compilation --
138 /// in such cases, we can not say whether or not the predicate
139 /// holds for certain. Stupid halting problem; such a drag.
140 pub recursion_depth: usize,
143 pub type PredicateObligation<'tcx> = Obligation<'tcx, ty::Predicate<'tcx>>;
144 pub type TraitObligation<'tcx> = Obligation<'tcx, ty::PolyTraitPredicate<'tcx>>;
146 // `PredicateObligation` is used a lot. Make sure it doesn't unintentionally get bigger.
147 #[cfg(target_arch = "x86_64")]
148 static_assert_size!(PredicateObligation<'_>, 112);
150 pub type Obligations<'tcx, O> = Vec<Obligation<'tcx, O>>;
151 pub type PredicateObligations<'tcx> = Vec<PredicateObligation<'tcx>>;
152 pub type TraitObligations<'tcx> = Vec<TraitObligation<'tcx>>;
154 pub type Selection<'tcx> = Vtable<'tcx, PredicateObligation<'tcx>>;
156 pub struct FulfillmentError<'tcx> {
157 pub obligation: PredicateObligation<'tcx>,
158 pub code: FulfillmentErrorCode<'tcx>,
159 /// Diagnostics only: we opportunistically change the `code.span` when we encounter an
160 /// obligation error caused by a call argument. When this is the case, we also signal that in
161 /// this field to ensure accuracy of suggestions.
162 pub points_at_arg_span: bool,
166 pub enum FulfillmentErrorCode<'tcx> {
167 CodeSelectionError(SelectionError<'tcx>),
168 CodeProjectionError(MismatchedProjectionTypes<'tcx>),
169 CodeSubtypeError(ExpectedFound<Ty<'tcx>>, TypeError<'tcx>), // always comes from a SubtypePredicate
173 /// Creates predicate obligations from the generic bounds.
174 pub fn predicates_for_generics<'tcx>(
175 cause: ObligationCause<'tcx>,
176 param_env: ty::ParamEnv<'tcx>,
177 generic_bounds: &ty::InstantiatedPredicates<'tcx>,
178 ) -> PredicateObligations<'tcx> {
179 util::predicates_for_generics(cause, 0, param_env, generic_bounds)
182 /// Determines whether the type `ty` is known to meet `bound` and
183 /// returns true if so. Returns false if `ty` either does not meet
184 /// `bound` or is not known to meet bound (note that this is
185 /// conservative towards *no impl*, which is the opposite of the
186 /// `evaluate` methods).
187 pub fn type_known_to_meet_bound_modulo_regions<'a, 'tcx>(
188 infcx: &InferCtxt<'a, 'tcx>,
189 param_env: ty::ParamEnv<'tcx>,
195 "type_known_to_meet_bound_modulo_regions(ty={:?}, bound={:?})",
197 infcx.tcx.def_path_str(def_id)
200 let trait_ref = ty::TraitRef { def_id, substs: infcx.tcx.mk_substs_trait(ty, &[]) };
201 let obligation = Obligation {
203 cause: ObligationCause::misc(span, hir::DUMMY_HIR_ID),
205 predicate: trait_ref.without_const().to_predicate(),
208 let result = infcx.predicate_must_hold_modulo_regions(&obligation);
210 "type_known_to_meet_ty={:?} bound={} => {:?}",
212 infcx.tcx.def_path_str(def_id),
216 if result && (ty.has_infer_types() || ty.has_closure_types()) {
217 // Because of inference "guessing", selection can sometimes claim
218 // to succeed while the success requires a guess. To ensure
219 // this function's result remains infallible, we must confirm
220 // that guess. While imperfect, I believe this is sound.
222 // The handling of regions in this area of the code is terrible,
223 // see issue #29149. We should be able to improve on this with
225 let mut fulfill_cx = FulfillmentContext::new_ignoring_regions();
227 // We can use a dummy node-id here because we won't pay any mind
228 // to region obligations that arise (there shouldn't really be any
230 let cause = ObligationCause::misc(span, hir::DUMMY_HIR_ID);
232 fulfill_cx.register_bound(infcx, param_env, ty, def_id, cause);
234 // Note: we only assume something is `Copy` if we can
235 // *definitively* show that it implements `Copy`. Otherwise,
236 // assume it is move; linear is always ok.
237 match fulfill_cx.select_all_or_error(infcx) {
240 "type_known_to_meet_bound_modulo_regions: ty={:?} bound={} success",
242 infcx.tcx.def_path_str(def_id)
248 "type_known_to_meet_bound_modulo_regions: ty={:?} bound={} errors={:?}",
250 infcx.tcx.def_path_str(def_id),
261 fn do_normalize_predicates<'tcx>(
263 region_context: DefId,
264 cause: ObligationCause<'tcx>,
265 elaborated_env: ty::ParamEnv<'tcx>,
266 predicates: Vec<ty::Predicate<'tcx>>,
267 ) -> Result<Vec<ty::Predicate<'tcx>>, ErrorReported> {
269 "do_normalize_predicates(predicates={:?}, region_context={:?}, cause={:?})",
270 predicates, region_context, cause,
272 let span = cause.span;
273 tcx.infer_ctxt().enter(|infcx| {
274 // FIXME. We should really... do something with these region
275 // obligations. But this call just continues the older
276 // behavior (i.e., doesn't cause any new bugs), and it would
277 // take some further refactoring to actually solve them. In
278 // particular, we would have to handle implied bounds
279 // properly, and that code is currently largely confined to
280 // regionck (though I made some efforts to extract it
283 // @arielby: In any case, these obligations are checked
284 // by wfcheck anyway, so I'm not sure we have to check
285 // them here too, and we will remove this function when
286 // we move over to lazy normalization *anyway*.
287 let fulfill_cx = FulfillmentContext::new_ignoring_regions();
289 match fully_normalize(&infcx, fulfill_cx, cause, elaborated_env, &predicates) {
290 Ok(predicates) => predicates,
292 infcx.report_fulfillment_errors(&errors, None, false);
293 return Err(ErrorReported);
297 debug!("do_normalize_predictes: normalized predicates = {:?}", predicates);
299 let region_scope_tree = region::ScopeTree::default();
301 // We can use the `elaborated_env` here; the region code only
302 // cares about declarations like `'a: 'b`.
303 let outlives_env = OutlivesEnvironment::new(elaborated_env);
305 infcx.resolve_regions_and_report_errors(
309 SuppressRegionErrors::default(),
312 let predicates = match infcx.fully_resolve(&predicates) {
313 Ok(predicates) => predicates,
315 // If we encounter a fixup error, it means that some type
316 // variable wound up unconstrained. I actually don't know
317 // if this can happen, and I certainly don't expect it to
318 // happen often, but if it did happen it probably
319 // represents a legitimate failure due to some kind of
320 // unconstrained variable, and it seems better not to ICE,
321 // all things considered.
322 tcx.sess.span_err(span, &fixup_err.to_string());
323 return Err(ErrorReported);
326 if predicates.has_local_value() {
327 // FIXME: shouldn't we, you know, actually report an error here? or an ICE?
335 // FIXME: this is gonna need to be removed ...
336 /// Normalizes the parameter environment, reporting errors if they occur.
337 pub fn normalize_param_env_or_error<'tcx>(
339 region_context: DefId,
340 unnormalized_env: ty::ParamEnv<'tcx>,
341 cause: ObligationCause<'tcx>,
342 ) -> ty::ParamEnv<'tcx> {
343 // I'm not wild about reporting errors here; I'd prefer to
344 // have the errors get reported at a defined place (e.g.,
345 // during typeck). Instead I have all parameter
346 // environments, in effect, going through this function
347 // and hence potentially reporting errors. This ensures of
348 // course that we never forget to normalize (the
349 // alternative seemed like it would involve a lot of
350 // manual invocations of this fn -- and then we'd have to
351 // deal with the errors at each of those sites).
353 // In any case, in practice, typeck constructs all the
354 // parameter environments once for every fn as it goes,
355 // and errors will get reported then; so after typeck we
356 // can be sure that no errors should occur.
359 "normalize_param_env_or_error(region_context={:?}, unnormalized_env={:?}, cause={:?})",
360 region_context, unnormalized_env, cause
363 let mut predicates: Vec<_> =
364 util::elaborate_predicates(tcx, unnormalized_env.caller_bounds.to_vec()).collect();
366 debug!("normalize_param_env_or_error: elaborated-predicates={:?}", predicates);
368 let elaborated_env = ty::ParamEnv::new(
369 tcx.intern_predicates(&predicates),
370 unnormalized_env.reveal,
371 unnormalized_env.def_id,
374 // HACK: we are trying to normalize the param-env inside *itself*. The problem is that
375 // normalization expects its param-env to be already normalized, which means we have
378 // The way we handle this is by normalizing the param-env inside an unnormalized version
379 // of the param-env, which means that if the param-env contains unnormalized projections,
380 // we'll have some normalization failures. This is unfortunate.
382 // Lazy normalization would basically handle this by treating just the
383 // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
385 // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
386 // types, so to make the situation less bad, we normalize all the predicates *but*
387 // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
388 // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
390 // This works fairly well because trait matching does not actually care about param-env
391 // TypeOutlives predicates - these are normally used by regionck.
392 let outlives_predicates: Vec<_> = predicates
393 .drain_filter(|predicate| match predicate {
394 ty::Predicate::TypeOutlives(..) => true,
400 "normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
401 predicates, outlives_predicates
403 let non_outlives_predicates = match do_normalize_predicates(
410 Ok(predicates) => predicates,
411 // An unnormalized env is better than nothing.
412 Err(ErrorReported) => {
413 debug!("normalize_param_env_or_error: errored resolving non-outlives predicates");
414 return elaborated_env;
418 debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates);
420 // Not sure whether it is better to include the unnormalized TypeOutlives predicates
421 // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
422 // predicates here anyway. Keeping them here anyway because it seems safer.
423 let outlives_env: Vec<_> =
424 non_outlives_predicates.iter().chain(&outlives_predicates).cloned().collect();
426 ty::ParamEnv::new(tcx.intern_predicates(&outlives_env), unnormalized_env.reveal, None);
427 let outlives_predicates = match do_normalize_predicates(
434 Ok(predicates) => predicates,
435 // An unnormalized env is better than nothing.
436 Err(ErrorReported) => {
437 debug!("normalize_param_env_or_error: errored resolving outlives predicates");
438 return elaborated_env;
441 debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates);
443 let mut predicates = non_outlives_predicates;
444 predicates.extend(outlives_predicates);
445 debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
447 tcx.intern_predicates(&predicates),
448 unnormalized_env.reveal,
449 unnormalized_env.def_id,
453 pub fn fully_normalize<'a, 'tcx, T>(
454 infcx: &InferCtxt<'a, 'tcx>,
455 mut fulfill_cx: FulfillmentContext<'tcx>,
456 cause: ObligationCause<'tcx>,
457 param_env: ty::ParamEnv<'tcx>,
459 ) -> Result<T, Vec<FulfillmentError<'tcx>>>
461 T: TypeFoldable<'tcx>,
463 debug!("fully_normalize_with_fulfillcx(value={:?})", value);
464 let selcx = &mut SelectionContext::new(infcx);
465 let Normalized { value: normalized_value, obligations } =
466 project::normalize(selcx, param_env, cause, value);
468 "fully_normalize: normalized_value={:?} obligations={:?}",
469 normalized_value, obligations
471 for obligation in obligations {
472 fulfill_cx.register_predicate_obligation(selcx.infcx(), obligation);
475 debug!("fully_normalize: select_all_or_error start");
476 fulfill_cx.select_all_or_error(infcx)?;
477 debug!("fully_normalize: select_all_or_error complete");
478 let resolved_value = infcx.resolve_vars_if_possible(&normalized_value);
479 debug!("fully_normalize: resolved_value={:?}", resolved_value);
483 /// Normalizes the predicates and checks whether they hold in an empty
484 /// environment. If this returns false, then either normalize
485 /// encountered an error or one of the predicates did not hold. Used
486 /// when creating vtables to check for unsatisfiable methods.
487 pub fn normalize_and_test_predicates<'tcx>(
489 predicates: Vec<ty::Predicate<'tcx>>,
491 debug!("normalize_and_test_predicates(predicates={:?})", predicates);
493 let result = tcx.infer_ctxt().enter(|infcx| {
494 let param_env = ty::ParamEnv::reveal_all();
495 let mut selcx = SelectionContext::new(&infcx);
496 let mut fulfill_cx = FulfillmentContext::new();
497 let cause = ObligationCause::dummy();
498 let Normalized { value: predicates, obligations } =
499 normalize(&mut selcx, param_env, cause.clone(), &predicates);
500 for obligation in obligations {
501 fulfill_cx.register_predicate_obligation(&infcx, obligation);
503 for predicate in predicates {
504 let obligation = Obligation::new(cause.clone(), param_env, predicate);
505 fulfill_cx.register_predicate_obligation(&infcx, obligation);
508 fulfill_cx.select_all_or_error(&infcx).is_ok()
510 debug!("normalize_and_test_predicates(predicates={:?}) = {:?}", predicates, result);
514 fn substitute_normalize_and_test_predicates<'tcx>(
516 key: (DefId, SubstsRef<'tcx>),
518 debug!("substitute_normalize_and_test_predicates(key={:?})", key);
520 let predicates = tcx.predicates_of(key.0).instantiate(tcx, key.1).predicates;
521 let result = normalize_and_test_predicates(tcx, predicates);
523 debug!("substitute_normalize_and_test_predicates(key={:?}) = {:?}", key, result);
527 /// Given a trait `trait_ref`, iterates the vtable entries
528 /// that come from `trait_ref`, including its supertraits.
529 #[inline] // FIXME(#35870): avoid closures being unexported due to `impl Trait`.
530 fn vtable_methods<'tcx>(
532 trait_ref: ty::PolyTraitRef<'tcx>,
533 ) -> &'tcx [Option<(DefId, SubstsRef<'tcx>)>] {
534 debug!("vtable_methods({:?})", trait_ref);
536 tcx.arena.alloc_from_iter(supertraits(tcx, trait_ref).flat_map(move |trait_ref| {
537 let trait_methods = tcx
538 .associated_items(trait_ref.def_id())
539 .in_definition_order()
540 .filter(|item| item.kind == ty::AssocKind::Method);
542 // Now list each method's DefId and InternalSubsts (for within its trait).
543 // If the method can never be called from this object, produce None.
544 trait_methods.map(move |trait_method| {
545 debug!("vtable_methods: trait_method={:?}", trait_method);
546 let def_id = trait_method.def_id;
548 // Some methods cannot be called on an object; skip those.
549 if !is_vtable_safe_method(tcx, trait_ref.def_id(), &trait_method) {
550 debug!("vtable_methods: not vtable safe");
554 // The method may have some early-bound lifetimes; add regions for those.
555 let substs = trait_ref.map_bound(|trait_ref| {
556 InternalSubsts::for_item(tcx, def_id, |param, _| match param.kind {
557 GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(),
558 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const => {
559 trait_ref.substs[param.index as usize]
564 // The trait type may have higher-ranked lifetimes in it;
565 // erase them if they appear, so that we get the type
566 // at some particular call site.
568 tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &substs);
570 // It's possible that the method relies on where-clauses that
571 // do not hold for this particular set of type parameters.
572 // Note that this method could then never be called, so we
573 // do not want to try and codegen it, in that case (see #23435).
574 let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs);
575 if !normalize_and_test_predicates(tcx, predicates.predicates) {
576 debug!("vtable_methods: predicates do not hold");
580 Some((def_id, substs))
585 impl<'tcx, O> Obligation<'tcx, O> {
587 cause: ObligationCause<'tcx>,
588 param_env: ty::ParamEnv<'tcx>,
590 ) -> Obligation<'tcx, O> {
591 Obligation { cause, param_env, recursion_depth: 0, predicate }
595 cause: ObligationCause<'tcx>,
596 recursion_depth: usize,
597 param_env: ty::ParamEnv<'tcx>,
599 ) -> Obligation<'tcx, O> {
600 Obligation { cause, param_env, recursion_depth, predicate }
606 param_env: ty::ParamEnv<'tcx>,
608 ) -> Obligation<'tcx, O> {
609 Obligation::new(ObligationCause::misc(span, body_id), param_env, trait_ref)
612 pub fn with<P>(&self, value: P) -> Obligation<'tcx, P> {
614 cause: self.cause.clone(),
615 param_env: self.param_env,
616 recursion_depth: self.recursion_depth,
622 impl<'tcx> FulfillmentError<'tcx> {
624 obligation: PredicateObligation<'tcx>,
625 code: FulfillmentErrorCode<'tcx>,
626 ) -> FulfillmentError<'tcx> {
627 FulfillmentError { obligation: obligation, code: code, points_at_arg_span: false }
631 impl<'tcx> TraitObligation<'tcx> {
632 fn self_ty(&self) -> ty::Binder<Ty<'tcx>> {
633 self.predicate.map_bound(|p| p.self_ty())
637 pub fn provide(providers: &mut ty::query::Providers<'_>) {
638 object_safety::provide(providers);
639 *providers = ty::query::Providers {
640 specialization_graph_of: specialize::specialization_graph_provider,
641 specializes: specialize::specializes,
642 codegen_fulfill_obligation: codegen::codegen_fulfill_obligation,
644 substitute_normalize_and_test_predicates,