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
9 pub mod error_reporting;
24 use crate::hir::def_id::DefId;
25 use crate::infer::{InferCtxt, SuppressRegionErrors};
26 use crate::infer::outlives::env::OutlivesEnvironment;
27 use crate::middle::region;
28 use crate::mir::interpret::ErrorHandled;
29 use rustc_macros::HashStable;
31 use syntax_pos::{Span, DUMMY_SP};
32 use crate::ty::subst::{InternalSubsts, SubstsRef};
33 use crate::ty::{self, AdtKind, List, Ty, TyCtxt, GenericParamDefKind, ToPredicate};
34 use crate::ty::error::{ExpectedFound, TypeError};
35 use crate::ty::fold::{TypeFolder, TypeFoldable, TypeVisitor};
36 use crate::util::common::ErrorReported;
41 pub use self::SelectionError::*;
42 pub use self::FulfillmentErrorCode::*;
43 pub use self::Vtable::*;
44 pub use self::ObligationCauseCode::*;
46 pub use self::coherence::{add_placeholder_note, orphan_check, overlapping_impls};
47 pub use self::coherence::{OrphanCheckErr, OverlapResult};
48 pub use self::fulfill::{FulfillmentContext, PendingPredicateObligation};
49 pub use self::project::MismatchedProjectionTypes;
50 pub use self::project::{normalize, normalize_projection_type, poly_project_and_unify_type};
51 pub use self::project::{ProjectionCache, ProjectionCacheSnapshot, Reveal, Normalized};
52 pub use self::object_safety::ObjectSafetyViolation;
53 pub use self::object_safety::MethodViolationCode;
54 pub use self::on_unimplemented::{OnUnimplementedDirective, OnUnimplementedNote};
55 pub use self::select::{EvaluationCache, SelectionContext, SelectionCache};
56 pub use self::select::{EvaluationResult, IntercrateAmbiguityCause, OverflowError};
57 pub use self::specialize::{OverlapError, specialization_graph, translate_substs};
58 pub use self::specialize::find_associated_item;
59 pub use self::specialize::specialization_graph::FutureCompatOverlapError;
60 pub use self::specialize::specialization_graph::FutureCompatOverlapErrorKind;
61 pub use self::engine::{TraitEngine, TraitEngineExt};
62 pub use self::util::{elaborate_predicates, elaborate_trait_ref, elaborate_trait_refs};
64 supertraits, supertrait_def_ids, transitive_bounds, Supertraits, SupertraitDefIds,
67 expand_trait_aliases, TraitAliasExpander, TraitAliasExpansionInfoDignosticBuilder,
70 pub use self::chalk_fulfill::{
71 CanonicalGoal as ChalkCanonicalGoal,
72 FulfillmentContext as ChalkFulfillmentContext
75 pub use self::ObligationCauseCode::*;
76 pub use self::FulfillmentErrorCode::*;
77 pub use self::SelectionError::*;
78 pub use self::Vtable::*;
80 /// Whether to enable bug compatibility with issue #43355.
81 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
82 pub enum IntercrateMode {
87 /// The mode that trait queries run in.
88 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
89 pub enum TraitQueryMode {
90 // Standard/un-canonicalized queries get accurate
91 // spans etc. passed in and hence can do reasonable
92 // error reporting on their own.
94 // Canonicalized queries get dummy spans and hence
95 // must generally propagate errors to
96 // pre-canonicalization callsites.
100 /// An `Obligation` represents some trait reference (e.g., `int: Eq`) for
101 /// which the vtable must be found. The process of finding a vtable is
102 /// called "resolving" the `Obligation`. This process consists of
103 /// either identifying an `impl` (e.g., `impl Eq for int`) that
104 /// provides the required vtable, or else finding a bound that is in
105 /// scope. The eventual result is usually a `Selection` (defined below).
106 #[derive(Clone, PartialEq, Eq, Hash)]
107 pub struct Obligation<'tcx, T> {
108 /// The reason we have to prove this thing.
109 pub cause: ObligationCause<'tcx>,
111 /// The environment in which we should prove this thing.
112 pub param_env: ty::ParamEnv<'tcx>,
114 /// The thing we are trying to prove.
117 /// If we started proving this as a result of trying to prove
118 /// something else, track the total depth to ensure termination.
119 /// If this goes over a certain threshold, we abort compilation --
120 /// in such cases, we can not say whether or not the predicate
121 /// holds for certain. Stupid halting problem; such a drag.
122 pub recursion_depth: usize,
125 pub type PredicateObligation<'tcx> = Obligation<'tcx, ty::Predicate<'tcx>>;
126 pub type TraitObligation<'tcx> = Obligation<'tcx, ty::PolyTraitPredicate<'tcx>>;
128 /// The reason why we incurred this obligation; used for error reporting.
129 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
130 pub struct ObligationCause<'tcx> {
133 /// The ID of the fn body that triggered this obligation. This is
134 /// used for region obligations to determine the precise
135 /// environment in which the region obligation should be evaluated
136 /// (in particular, closures can add new assumptions). See the
137 /// field `region_obligations` of the `FulfillmentContext` for more
139 pub body_id: hir::HirId,
141 pub code: ObligationCauseCode<'tcx>
144 impl<'tcx> ObligationCause<'tcx> {
145 pub fn span<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Span {
147 ObligationCauseCode::CompareImplMethodObligation { .. } |
148 ObligationCauseCode::MainFunctionType |
149 ObligationCauseCode::StartFunctionType => {
150 tcx.sess.source_map().def_span(self.span)
152 ObligationCauseCode::MatchExpressionArm { arm_span, .. } => arm_span,
158 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
159 pub enum ObligationCauseCode<'tcx> {
160 /// Not well classified or should be obvious from the span.
163 /// A slice or array is WF only if `T: Sized`.
166 /// A tuple is WF only if its middle elements are `Sized`.
169 /// This is the trait reference from the given projection.
170 ProjectionWf(ty::ProjectionTy<'tcx>),
172 /// In an impl of trait `X` for type `Y`, type `Y` must
173 /// also implement all supertraits of `X`.
174 ItemObligation(DefId),
176 /// A type like `&'a T` is WF only if `T: 'a`.
177 ReferenceOutlivesReferent(Ty<'tcx>),
179 /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
180 ObjectTypeBound(Ty<'tcx>, ty::Region<'tcx>),
182 /// Obligation incurred due to an object cast.
183 ObjectCastObligation(/* Object type */ Ty<'tcx>),
185 // Various cases where expressions must be sized/copy/etc:
186 /// L = X implies that L is Sized
188 /// (x1, .., xn) must be Sized
189 TupleInitializerSized,
190 /// S { ... } must be Sized
191 StructInitializerSized,
192 /// Type of each variable must be Sized
193 VariableType(ast::NodeId),
194 /// Argument type must be Sized
196 /// Return type must be Sized
198 /// Yield type must be Sized
200 /// [T,..n] --> T must be Copy
203 /// Types of fields (other than the last, except for packed structs) in a struct must be sized.
204 FieldSized { adt_kind: AdtKind, last: bool },
206 /// Constant expressions must be sized.
209 /// static items must have `Sync` type
212 BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
214 ImplDerivedObligation(DerivedObligationCause<'tcx>),
216 /// error derived when matching traits/impls; see ObligationCause for more details
217 CompareImplMethodObligation {
218 item_name: ast::Name,
219 impl_item_def_id: DefId,
220 trait_item_def_id: DefId,
223 /// Checking that this expression can be assigned where it needs to be
224 // FIXME(eddyb) #11161 is the original Expr required?
227 /// Computing common supertype in the arms of a match expression
230 source: hir::MatchSource,
231 prior_arms: Vec<Span>,
233 discrim_hir_id: hir::HirId,
236 /// Computing common supertype in the pattern guard for the arms of a match expression
237 MatchExpressionArmPattern { span: Span, ty: Ty<'tcx> },
239 /// Computing common supertype in an if expression
243 semicolon: Option<Span>,
246 /// Computing common supertype of an if expression with no else counter-part
247 IfExpressionWithNoElse,
249 /// `main` has wrong type
252 /// `start` has wrong type
255 /// intrinsic has wrong type
261 /// `return` with no expression
264 /// `return` with an expression
265 ReturnType(hir::HirId),
267 /// Block implicit return
268 BlockTailExpression(hir::HirId),
270 /// #[feature(trivial_bounds)] is not enabled
274 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
275 pub struct DerivedObligationCause<'tcx> {
276 /// The trait reference of the parent obligation that led to the
277 /// current obligation. Note that only trait obligations lead to
278 /// derived obligations, so we just store the trait reference here
280 parent_trait_ref: ty::PolyTraitRef<'tcx>,
282 /// The parent trait had this cause.
283 parent_code: Rc<ObligationCauseCode<'tcx>>
286 pub type Obligations<'tcx, O> = Vec<Obligation<'tcx, O>>;
287 pub type PredicateObligations<'tcx> = Vec<PredicateObligation<'tcx>>;
288 pub type TraitObligations<'tcx> = Vec<TraitObligation<'tcx>>;
290 /// The following types:
298 /// * `InEnvironment`,
299 /// are used for representing the trait system in the form of
300 /// logic programming clauses. They are part of the interface
301 /// for the chalk SLG solver.
302 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable)]
303 pub enum WhereClause<'tcx> {
304 Implemented(ty::TraitPredicate<'tcx>),
305 ProjectionEq(ty::ProjectionPredicate<'tcx>),
306 RegionOutlives(ty::RegionOutlivesPredicate<'tcx>),
307 TypeOutlives(ty::TypeOutlivesPredicate<'tcx>),
310 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable)]
311 pub enum WellFormed<'tcx> {
312 Trait(ty::TraitPredicate<'tcx>),
316 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable)]
317 pub enum FromEnv<'tcx> {
318 Trait(ty::TraitPredicate<'tcx>),
322 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable)]
323 pub enum DomainGoal<'tcx> {
324 Holds(WhereClause<'tcx>),
325 WellFormed(WellFormed<'tcx>),
326 FromEnv(FromEnv<'tcx>),
327 Normalize(ty::ProjectionPredicate<'tcx>),
330 pub type PolyDomainGoal<'tcx> = ty::Binder<DomainGoal<'tcx>>;
332 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
333 pub enum QuantifierKind {
338 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
339 pub enum GoalKind<'tcx> {
340 Implies(Clauses<'tcx>, Goal<'tcx>),
341 And(Goal<'tcx>, Goal<'tcx>),
343 DomainGoal(DomainGoal<'tcx>),
344 Quantified(QuantifierKind, ty::Binder<Goal<'tcx>>),
345 Subtype(Ty<'tcx>, Ty<'tcx>),
349 pub type Goal<'tcx> = &'tcx GoalKind<'tcx>;
351 pub type Goals<'tcx> = &'tcx List<Goal<'tcx>>;
353 impl<'tcx> DomainGoal<'tcx> {
354 pub fn into_goal(self) -> GoalKind<'tcx> {
355 GoalKind::DomainGoal(self)
358 pub fn into_program_clause(self) -> ProgramClause<'tcx> {
361 hypotheses: ty::List::empty(),
362 category: ProgramClauseCategory::Other,
367 impl<'tcx> GoalKind<'tcx> {
368 pub fn from_poly_domain_goal<'a, 'gcx>(
369 domain_goal: PolyDomainGoal<'tcx>,
370 tcx: TyCtxt<'a, 'gcx, 'tcx>,
371 ) -> GoalKind<'tcx> {
372 match domain_goal.no_bound_vars() {
373 Some(p) => p.into_goal(),
374 None => GoalKind::Quantified(
375 QuantifierKind::Universal,
376 domain_goal.map_bound(|p| tcx.mk_goal(p.into_goal()))
382 /// This matches the definition from Page 7 of "A Proof Procedure for the Logic of Hereditary
383 /// Harrop Formulas".
384 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
385 pub enum Clause<'tcx> {
386 Implies(ProgramClause<'tcx>),
387 ForAll(ty::Binder<ProgramClause<'tcx>>),
391 pub fn category(self) -> ProgramClauseCategory {
393 Clause::Implies(clause) => clause.category,
394 Clause::ForAll(clause) => clause.skip_binder().category,
399 /// Multiple clauses.
400 pub type Clauses<'tcx> = &'tcx List<Clause<'tcx>>;
402 /// A "program clause" has the form `D :- G1, ..., Gn`. It is saying
403 /// that the domain goal `D` is true if `G1...Gn` are provable. This
404 /// is equivalent to the implication `G1..Gn => D`; we usually write
405 /// it with the reverse implication operator `:-` to emphasize the way
406 /// that programs are actually solved (via backchaining, which starts
407 /// with the goal to solve and proceeds from there).
408 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
409 pub struct ProgramClause<'tcx> {
410 /// This goal will be considered true ...
411 pub goal: DomainGoal<'tcx>,
413 /// ... if we can prove these hypotheses (there may be no hypotheses at all):
414 pub hypotheses: Goals<'tcx>,
416 /// Useful for filtering clauses.
417 pub category: ProgramClauseCategory,
420 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
421 pub enum ProgramClauseCategory {
427 /// A set of clauses that we assume to be true.
428 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
429 pub struct Environment<'tcx> {
430 pub clauses: Clauses<'tcx>,
433 impl Environment<'tcx> {
434 pub fn with<G>(self, goal: G) -> InEnvironment<'tcx, G> {
442 /// Something (usually a goal), along with an environment.
443 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
444 pub struct InEnvironment<'tcx, G> {
445 pub environment: Environment<'tcx>,
449 pub type Selection<'tcx> = Vtable<'tcx, PredicateObligation<'tcx>>;
451 #[derive(Clone,Debug)]
452 pub enum SelectionError<'tcx> {
454 OutputTypeParameterMismatch(ty::PolyTraitRef<'tcx>,
455 ty::PolyTraitRef<'tcx>,
456 ty::error::TypeError<'tcx>),
457 TraitNotObjectSafe(DefId),
458 ConstEvalFailure(ErrorHandled),
462 pub struct FulfillmentError<'tcx> {
463 pub obligation: PredicateObligation<'tcx>,
464 pub code: FulfillmentErrorCode<'tcx>
468 pub enum FulfillmentErrorCode<'tcx> {
469 CodeSelectionError(SelectionError<'tcx>),
470 CodeProjectionError(MismatchedProjectionTypes<'tcx>),
471 CodeSubtypeError(ExpectedFound<Ty<'tcx>>,
472 TypeError<'tcx>), // always comes from a SubtypePredicate
476 /// When performing resolution, it is typically the case that there
477 /// can be one of three outcomes:
479 /// - `Ok(Some(r))`: success occurred with result `r`
480 /// - `Ok(None)`: could not definitely determine anything, usually due
481 /// to inconclusive type inference.
482 /// - `Err(e)`: error `e` occurred
483 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
485 /// Given the successful resolution of an obligation, the `Vtable`
486 /// indicates where the vtable comes from. Note that while we call this
487 /// a "vtable", it does not necessarily indicate dynamic dispatch at
488 /// runtime. `Vtable` instances just tell the compiler where to find
489 /// methods, but in generic code those methods are typically statically
490 /// dispatched -- only when an object is constructed is a `Vtable`
491 /// instance reified into an actual vtable.
493 /// For example, the vtable may be tied to a specific impl (case A),
494 /// or it may be relative to some bound that is in scope (case B).
497 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
498 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
499 /// impl Clone for int { ... } // Impl_3
501 /// fn foo<T:Clone>(concrete: Option<Box<int>>,
503 /// mixed: Option<T>) {
505 /// // Case A: Vtable points at a specific impl. Only possible when
506 /// // type is concretely known. If the impl itself has bounded
507 /// // type parameters, Vtable will carry resolutions for those as well:
508 /// concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
510 /// // Case B: Vtable must be provided by caller. This applies when
511 /// // type is a type parameter.
512 /// param.clone(); // VtableParam
514 /// // Case C: A mix of cases A and B.
515 /// mixed.clone(); // Vtable(Impl_1, [VtableParam])
519 /// ### The type parameter `N`
521 /// See explanation on `VtableImplData`.
522 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
523 pub enum Vtable<'tcx, N> {
524 /// Vtable identifying a particular impl.
525 VtableImpl(VtableImplData<'tcx, N>),
527 /// Vtable for auto trait implementations.
528 /// This carries the information and nested obligations with regards
529 /// to an auto implementation for a trait `Trait`. The nested obligations
530 /// ensure the trait implementation holds for all the constituent types.
531 VtableAutoImpl(VtableAutoImplData<N>),
533 /// Successful resolution to an obligation provided by the caller
534 /// for some type parameter. The `Vec<N>` represents the
535 /// obligations incurred from normalizing the where-clause (if
539 /// Virtual calls through an object.
540 VtableObject(VtableObjectData<'tcx, N>),
542 /// Successful resolution for a builtin trait.
543 VtableBuiltin(VtableBuiltinData<N>),
545 /// Vtable automatically generated for a closure. The `DefId` is the ID
546 /// of the closure expression. This is a `VtableImpl` in spirit, but the
547 /// impl is generated by the compiler and does not appear in the source.
548 VtableClosure(VtableClosureData<'tcx, N>),
550 /// Same as above, but for a function pointer type with the given signature.
551 VtableFnPointer(VtableFnPointerData<'tcx, N>),
553 /// Vtable automatically generated for a generator.
554 VtableGenerator(VtableGeneratorData<'tcx, N>),
556 /// Vtable for a trait alias.
557 VtableTraitAlias(VtableTraitAliasData<'tcx, N>),
560 /// Identifies a particular impl in the source, along with a set of
561 /// substitutions from the impl's type/lifetime parameters. The
562 /// `nested` vector corresponds to the nested obligations attached to
563 /// the impl's type parameters.
565 /// The type parameter `N` indicates the type used for "nested
566 /// obligations" that are required by the impl. During type check, this
567 /// is `Obligation`, as one might expect. During codegen, however, this
568 /// is `()`, because codegen only requires a shallow resolution of an
569 /// impl, and nested obligations are satisfied later.
570 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
571 pub struct VtableImplData<'tcx, N> {
572 pub impl_def_id: DefId,
573 pub substs: SubstsRef<'tcx>,
577 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
578 pub struct VtableGeneratorData<'tcx, N> {
579 pub generator_def_id: DefId,
580 pub substs: ty::GeneratorSubsts<'tcx>,
581 /// Nested obligations. This can be non-empty if the generator
582 /// signature contains associated types.
586 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
587 pub struct VtableClosureData<'tcx, N> {
588 pub closure_def_id: DefId,
589 pub substs: ty::ClosureSubsts<'tcx>,
590 /// Nested obligations. This can be non-empty if the closure
591 /// signature contains associated types.
595 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
596 pub struct VtableAutoImplData<N> {
597 pub trait_def_id: DefId,
601 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
602 pub struct VtableBuiltinData<N> {
606 /// A vtable for some object-safe trait `Foo` automatically derived
607 /// for the object type `Foo`.
608 #[derive(PartialEq, Eq, Clone, RustcEncodable, RustcDecodable, HashStable)]
609 pub struct VtableObjectData<'tcx, N> {
610 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
611 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
613 /// The vtable is formed by concatenating together the method lists of
614 /// the base object trait and all supertraits; this is the start of
615 /// `upcast_trait_ref`'s methods in that vtable.
616 pub vtable_base: usize,
621 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
622 pub struct VtableFnPointerData<'tcx, N> {
627 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
628 pub struct VtableTraitAliasData<'tcx, N> {
629 pub alias_def_id: DefId,
630 pub substs: SubstsRef<'tcx>,
634 /// Creates predicate obligations from the generic bounds.
635 pub fn predicates_for_generics<'tcx>(cause: ObligationCause<'tcx>,
636 param_env: ty::ParamEnv<'tcx>,
637 generic_bounds: &ty::InstantiatedPredicates<'tcx>)
638 -> PredicateObligations<'tcx>
640 util::predicates_for_generics(cause, 0, param_env, generic_bounds)
643 /// Determines whether the type `ty` is known to meet `bound` and
644 /// returns true if so. Returns false if `ty` either does not meet
645 /// `bound` or is not known to meet bound (note that this is
646 /// conservative towards *no impl*, which is the opposite of the
647 /// `evaluate` methods).
648 pub fn type_known_to_meet_bound_modulo_regions<'a, 'gcx, 'tcx>(
649 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
650 param_env: ty::ParamEnv<'tcx>,
655 debug!("type_known_to_meet_bound_modulo_regions(ty={:?}, bound={:?})",
657 infcx.tcx.def_path_str(def_id));
659 let trait_ref = ty::TraitRef {
661 substs: infcx.tcx.mk_substs_trait(ty, &[]),
663 let obligation = Obligation {
665 cause: ObligationCause::misc(span, hir::DUMMY_HIR_ID),
667 predicate: trait_ref.to_predicate(),
670 let result = infcx.predicate_must_hold_modulo_regions(&obligation);
671 debug!("type_known_to_meet_ty={:?} bound={} => {:?}",
672 ty, infcx.tcx.def_path_str(def_id), result);
674 if result && (ty.has_infer_types() || ty.has_closure_types()) {
675 // Because of inference "guessing", selection can sometimes claim
676 // to succeed while the success requires a guess. To ensure
677 // this function's result remains infallible, we must confirm
678 // that guess. While imperfect, I believe this is sound.
680 // The handling of regions in this area of the code is terrible,
681 // see issue #29149. We should be able to improve on this with
683 let mut fulfill_cx = FulfillmentContext::new_ignoring_regions();
685 // We can use a dummy node-id here because we won't pay any mind
686 // to region obligations that arise (there shouldn't really be any
688 let cause = ObligationCause::misc(span, hir::DUMMY_HIR_ID);
690 fulfill_cx.register_bound(infcx, param_env, ty, def_id, cause);
692 // Note: we only assume something is `Copy` if we can
693 // *definitively* show that it implements `Copy`. Otherwise,
694 // assume it is move; linear is always ok.
695 match fulfill_cx.select_all_or_error(infcx) {
697 debug!("type_known_to_meet_bound_modulo_regions: ty={:?} bound={} success",
699 infcx.tcx.def_path_str(def_id));
703 debug!("type_known_to_meet_bound_modulo_regions: ty={:?} bound={} errors={:?}",
705 infcx.tcx.def_path_str(def_id),
715 fn do_normalize_predicates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
716 region_context: DefId,
717 cause: ObligationCause<'tcx>,
718 elaborated_env: ty::ParamEnv<'tcx>,
719 predicates: Vec<ty::Predicate<'tcx>>)
720 -> Result<Vec<ty::Predicate<'tcx>>, ErrorReported>
723 "do_normalize_predicates(predicates={:?}, region_context={:?}, cause={:?})",
728 let span = cause.span;
729 tcx.infer_ctxt().enter(|infcx| {
730 // FIXME. We should really... do something with these region
731 // obligations. But this call just continues the older
732 // behavior (i.e., doesn't cause any new bugs), and it would
733 // take some further refactoring to actually solve them. In
734 // particular, we would have to handle implied bounds
735 // properly, and that code is currently largely confined to
736 // regionck (though I made some efforts to extract it
739 // @arielby: In any case, these obligations are checked
740 // by wfcheck anyway, so I'm not sure we have to check
741 // them here too, and we will remove this function when
742 // we move over to lazy normalization *anyway*.
743 let fulfill_cx = FulfillmentContext::new_ignoring_regions();
744 let predicates = match fully_normalize(
751 Ok(predicates) => predicates,
753 infcx.report_fulfillment_errors(&errors, None, false);
754 return Err(ErrorReported)
758 debug!("do_normalize_predictes: normalized predicates = {:?}", predicates);
760 let region_scope_tree = region::ScopeTree::default();
762 // We can use the `elaborated_env` here; the region code only
763 // cares about declarations like `'a: 'b`.
764 let outlives_env = OutlivesEnvironment::new(elaborated_env);
766 infcx.resolve_regions_and_report_errors(
770 SuppressRegionErrors::default(),
773 let predicates = match infcx.fully_resolve(&predicates) {
774 Ok(predicates) => predicates,
776 // If we encounter a fixup error, it means that some type
777 // variable wound up unconstrained. I actually don't know
778 // if this can happen, and I certainly don't expect it to
779 // happen often, but if it did happen it probably
780 // represents a legitimate failure due to some kind of
781 // unconstrained variable, and it seems better not to ICE,
782 // all things considered.
783 tcx.sess.span_err(span, &fixup_err.to_string());
784 return Err(ErrorReported)
788 match tcx.lift_to_global(&predicates) {
789 Some(predicates) => Ok(predicates),
791 // FIXME: shouldn't we, you know, actually report an error here? or an ICE?
798 // FIXME: this is gonna need to be removed ...
799 /// Normalizes the parameter environment, reporting errors if they occur.
800 pub fn normalize_param_env_or_error<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
801 region_context: DefId,
802 unnormalized_env: ty::ParamEnv<'tcx>,
803 cause: ObligationCause<'tcx>)
804 -> ty::ParamEnv<'tcx>
806 // I'm not wild about reporting errors here; I'd prefer to
807 // have the errors get reported at a defined place (e.g.,
808 // during typeck). Instead I have all parameter
809 // environments, in effect, going through this function
810 // and hence potentially reporting errors. This ensures of
811 // course that we never forget to normalize (the
812 // alternative seemed like it would involve a lot of
813 // manual invocations of this fn -- and then we'd have to
814 // deal with the errors at each of those sites).
816 // In any case, in practice, typeck constructs all the
817 // parameter environments once for every fn as it goes,
818 // and errors will get reported then; so after typeck we
819 // can be sure that no errors should occur.
821 debug!("normalize_param_env_or_error(region_context={:?}, unnormalized_env={:?}, cause={:?})",
822 region_context, unnormalized_env, cause);
824 let mut predicates: Vec<_> =
825 util::elaborate_predicates(tcx, unnormalized_env.caller_bounds.to_vec())
828 debug!("normalize_param_env_or_error: elaborated-predicates={:?}",
831 let elaborated_env = ty::ParamEnv::new(
832 tcx.intern_predicates(&predicates),
833 unnormalized_env.reveal,
834 unnormalized_env.def_id
837 // HACK: we are trying to normalize the param-env inside *itself*. The problem is that
838 // normalization expects its param-env to be already normalized, which means we have
841 // The way we handle this is by normalizing the param-env inside an unnormalized version
842 // of the param-env, which means that if the param-env contains unnormalized projections,
843 // we'll have some normalization failures. This is unfortunate.
845 // Lazy normalization would basically handle this by treating just the
846 // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
848 // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
849 // types, so to make the situation less bad, we normalize all the predicates *but*
850 // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
851 // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
853 // This works fairly well because trait matching does not actually care about param-env
854 // TypeOutlives predicates - these are normally used by regionck.
855 let outlives_predicates: Vec<_> = predicates.drain_filter(|predicate| {
857 ty::Predicate::TypeOutlives(..) => true,
862 debug!("normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
863 predicates, outlives_predicates);
864 let non_outlives_predicates =
865 match do_normalize_predicates(tcx, region_context, cause.clone(),
866 elaborated_env, predicates) {
867 Ok(predicates) => predicates,
868 // An unnormalized env is better than nothing.
869 Err(ErrorReported) => {
870 debug!("normalize_param_env_or_error: errored resolving non-outlives predicates");
871 return elaborated_env
875 debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates);
877 // Not sure whether it is better to include the unnormalized TypeOutlives predicates
878 // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
879 // predicates here anyway. Keeping them here anyway because it seems safer.
880 let outlives_env: Vec<_> =
881 non_outlives_predicates.iter().chain(&outlives_predicates).cloned().collect();
882 let outlives_env = ty::ParamEnv::new(
883 tcx.intern_predicates(&outlives_env),
884 unnormalized_env.reveal,
887 let outlives_predicates =
888 match do_normalize_predicates(tcx, region_context, cause,
889 outlives_env, outlives_predicates) {
890 Ok(predicates) => predicates,
891 // An unnormalized env is better than nothing.
892 Err(ErrorReported) => {
893 debug!("normalize_param_env_or_error: errored resolving outlives predicates");
894 return elaborated_env
897 debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates);
899 let mut predicates = non_outlives_predicates;
900 predicates.extend(outlives_predicates);
901 debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
903 tcx.intern_predicates(&predicates),
904 unnormalized_env.reveal,
905 unnormalized_env.def_id
909 pub fn fully_normalize<'a, 'gcx, 'tcx, T>(
910 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
911 mut fulfill_cx: FulfillmentContext<'tcx>,
912 cause: ObligationCause<'tcx>,
913 param_env: ty::ParamEnv<'tcx>,
915 -> Result<T, Vec<FulfillmentError<'tcx>>>
916 where T : TypeFoldable<'tcx>
918 debug!("fully_normalize_with_fulfillcx(value={:?})", value);
919 let selcx = &mut SelectionContext::new(infcx);
920 let Normalized { value: normalized_value, obligations } =
921 project::normalize(selcx, param_env, cause, value);
922 debug!("fully_normalize: normalized_value={:?} obligations={:?}",
925 for obligation in obligations {
926 fulfill_cx.register_predicate_obligation(selcx.infcx(), obligation);
929 debug!("fully_normalize: select_all_or_error start");
930 fulfill_cx.select_all_or_error(infcx)?;
931 debug!("fully_normalize: select_all_or_error complete");
932 let resolved_value = infcx.resolve_type_vars_if_possible(&normalized_value);
933 debug!("fully_normalize: resolved_value={:?}", resolved_value);
937 /// Normalizes the predicates and checks whether they hold in an empty
938 /// environment. If this returns false, then either normalize
939 /// encountered an error or one of the predicates did not hold. Used
940 /// when creating vtables to check for unsatisfiable methods.
941 fn normalize_and_test_predicates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
942 predicates: Vec<ty::Predicate<'tcx>>)
945 debug!("normalize_and_test_predicates(predicates={:?})",
948 let result = tcx.infer_ctxt().enter(|infcx| {
949 let param_env = ty::ParamEnv::reveal_all();
950 let mut selcx = SelectionContext::new(&infcx);
951 let mut fulfill_cx = FulfillmentContext::new();
952 let cause = ObligationCause::dummy();
953 let Normalized { value: predicates, obligations } =
954 normalize(&mut selcx, param_env, cause.clone(), &predicates);
955 for obligation in obligations {
956 fulfill_cx.register_predicate_obligation(&infcx, obligation);
958 for predicate in predicates {
959 let obligation = Obligation::new(cause.clone(), param_env, predicate);
960 fulfill_cx.register_predicate_obligation(&infcx, obligation);
963 fulfill_cx.select_all_or_error(&infcx).is_ok()
965 debug!("normalize_and_test_predicates(predicates={:?}) = {:?}",
970 fn substitute_normalize_and_test_predicates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
971 key: (DefId, SubstsRef<'tcx>))
974 debug!("substitute_normalize_and_test_predicates(key={:?})",
977 let predicates = tcx.predicates_of(key.0).instantiate(tcx, key.1).predicates;
978 let result = normalize_and_test_predicates(tcx, predicates);
980 debug!("substitute_normalize_and_test_predicates(key={:?}) = {:?}",
985 /// Given a trait `trait_ref`, iterates the vtable entries
986 /// that come from `trait_ref`, including its supertraits.
987 #[inline] // FIXME(#35870): avoid closures being unexported due to `impl Trait`.
988 fn vtable_methods<'a, 'tcx>(
989 tcx: TyCtxt<'a, 'tcx, 'tcx>,
990 trait_ref: ty::PolyTraitRef<'tcx>)
991 -> &'tcx [Option<(DefId, SubstsRef<'tcx>)>]
993 debug!("vtable_methods({:?})", trait_ref);
995 tcx.arena.alloc_from_iter(
996 supertraits(tcx, trait_ref).flat_map(move |trait_ref| {
997 let trait_methods = tcx.associated_items(trait_ref.def_id())
998 .filter(|item| item.kind == ty::AssociatedKind::Method);
1000 // Now list each method's DefId and InternalSubsts (for within its trait).
1001 // If the method can never be called from this object, produce None.
1002 trait_methods.map(move |trait_method| {
1003 debug!("vtable_methods: trait_method={:?}", trait_method);
1004 let def_id = trait_method.def_id;
1006 // Some methods cannot be called on an object; skip those.
1007 if !tcx.is_vtable_safe_method(trait_ref.def_id(), &trait_method) {
1008 debug!("vtable_methods: not vtable safe");
1012 // the method may have some early-bound lifetimes, add
1013 // regions for those
1014 let substs = trait_ref.map_bound(|trait_ref|
1015 InternalSubsts::for_item(tcx, def_id, |param, _|
1017 GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(),
1018 GenericParamDefKind::Type { .. } |
1019 GenericParamDefKind::Const => {
1020 trait_ref.substs[param.index as usize]
1026 // the trait type may have higher-ranked lifetimes in it;
1027 // so erase them if they appear, so that we get the type
1028 // at some particular call site
1029 let substs = tcx.normalize_erasing_late_bound_regions(
1030 ty::ParamEnv::reveal_all(),
1034 // It's possible that the method relies on where clauses that
1035 // do not hold for this particular set of type parameters.
1036 // Note that this method could then never be called, so we
1037 // do not want to try and codegen it, in that case (see #23435).
1038 let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs);
1039 if !normalize_and_test_predicates(tcx, predicates.predicates) {
1040 debug!("vtable_methods: predicates do not hold");
1044 Some((def_id, substs))
1050 impl<'tcx, O> Obligation<'tcx, O> {
1051 pub fn new(cause: ObligationCause<'tcx>,
1052 param_env: ty::ParamEnv<'tcx>,
1054 -> Obligation<'tcx, O>
1056 Obligation { cause, param_env, recursion_depth: 0, predicate }
1059 fn with_depth(cause: ObligationCause<'tcx>,
1060 recursion_depth: usize,
1061 param_env: ty::ParamEnv<'tcx>,
1063 -> Obligation<'tcx, O>
1065 Obligation { cause, param_env, recursion_depth, predicate }
1068 pub fn misc(span: Span,
1069 body_id: hir::HirId,
1070 param_env: ty::ParamEnv<'tcx>,
1072 -> Obligation<'tcx, O> {
1073 Obligation::new(ObligationCause::misc(span, body_id), param_env, trait_ref)
1076 pub fn with<P>(&self, value: P) -> Obligation<'tcx,P> {
1077 Obligation { cause: self.cause.clone(),
1078 param_env: self.param_env,
1079 recursion_depth: self.recursion_depth,
1084 impl<'tcx> ObligationCause<'tcx> {
1086 pub fn new(span: Span,
1087 body_id: hir::HirId,
1088 code: ObligationCauseCode<'tcx>)
1089 -> ObligationCause<'tcx> {
1090 ObligationCause { span, body_id, code }
1093 pub fn misc(span: Span, body_id: hir::HirId) -> ObligationCause<'tcx> {
1094 ObligationCause { span, body_id, code: MiscObligation }
1097 pub fn dummy() -> ObligationCause<'tcx> {
1098 ObligationCause { span: DUMMY_SP, body_id: hir::CRATE_HIR_ID, code: MiscObligation }
1102 impl<'tcx, N> Vtable<'tcx, N> {
1103 pub fn nested_obligations(self) -> Vec<N> {
1105 VtableImpl(i) => i.nested,
1106 VtableParam(n) => n,
1107 VtableBuiltin(i) => i.nested,
1108 VtableAutoImpl(d) => d.nested,
1109 VtableClosure(c) => c.nested,
1110 VtableGenerator(c) => c.nested,
1111 VtableObject(d) => d.nested,
1112 VtableFnPointer(d) => d.nested,
1113 VtableTraitAlias(d) => d.nested,
1117 pub fn map<M, F>(self, f: F) -> Vtable<'tcx, M> where F: FnMut(N) -> M {
1119 VtableImpl(i) => VtableImpl(VtableImplData {
1120 impl_def_id: i.impl_def_id,
1122 nested: i.nested.into_iter().map(f).collect(),
1124 VtableParam(n) => VtableParam(n.into_iter().map(f).collect()),
1125 VtableBuiltin(i) => VtableBuiltin(VtableBuiltinData {
1126 nested: i.nested.into_iter().map(f).collect(),
1128 VtableObject(o) => VtableObject(VtableObjectData {
1129 upcast_trait_ref: o.upcast_trait_ref,
1130 vtable_base: o.vtable_base,
1131 nested: o.nested.into_iter().map(f).collect(),
1133 VtableAutoImpl(d) => VtableAutoImpl(VtableAutoImplData {
1134 trait_def_id: d.trait_def_id,
1135 nested: d.nested.into_iter().map(f).collect(),
1137 VtableClosure(c) => VtableClosure(VtableClosureData {
1138 closure_def_id: c.closure_def_id,
1140 nested: c.nested.into_iter().map(f).collect(),
1142 VtableGenerator(c) => VtableGenerator(VtableGeneratorData {
1143 generator_def_id: c.generator_def_id,
1145 nested: c.nested.into_iter().map(f).collect(),
1147 VtableFnPointer(p) => VtableFnPointer(VtableFnPointerData {
1149 nested: p.nested.into_iter().map(f).collect(),
1151 VtableTraitAlias(d) => VtableTraitAlias(VtableTraitAliasData {
1152 alias_def_id: d.alias_def_id,
1154 nested: d.nested.into_iter().map(f).collect(),
1160 impl<'tcx> FulfillmentError<'tcx> {
1161 fn new(obligation: PredicateObligation<'tcx>,
1162 code: FulfillmentErrorCode<'tcx>)
1163 -> FulfillmentError<'tcx>
1165 FulfillmentError { obligation: obligation, code: code }
1169 impl<'tcx> TraitObligation<'tcx> {
1170 fn self_ty(&self) -> ty::Binder<Ty<'tcx>> {
1171 self.predicate.map_bound(|p| p.self_ty())
1175 pub fn provide(providers: &mut ty::query::Providers<'_>) {
1176 *providers = ty::query::Providers {
1177 is_object_safe: object_safety::is_object_safe_provider,
1178 specialization_graph_of: specialize::specialization_graph_provider,
1179 specializes: specialize::specializes,
1180 codegen_fulfill_obligation: codegen::codegen_fulfill_obligation,
1182 substitute_normalize_and_test_predicates,
1187 pub trait ExClauseFold<'tcx>
1189 Self: chalk_engine::context::Context + Clone,
1191 fn fold_ex_clause_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(
1192 ex_clause: &chalk_engine::ExClause<Self>,
1194 ) -> chalk_engine::ExClause<Self>;
1196 fn visit_ex_clause_with<'gcx: 'tcx, V: TypeVisitor<'tcx>>(
1197 ex_clause: &chalk_engine::ExClause<Self>,
1202 pub trait ChalkContextLift<'tcx>
1204 Self: chalk_engine::context::Context + Clone,
1206 type LiftedExClause: Debug + 'tcx;
1207 type LiftedDelayedLiteral: Debug + 'tcx;
1208 type LiftedLiteral: Debug + 'tcx;
1210 fn lift_ex_clause_to_tcx<'a, 'gcx>(
1211 ex_clause: &chalk_engine::ExClause<Self>,
1212 tcx: TyCtxt<'a, 'gcx, 'tcx>,
1213 ) -> Option<Self::LiftedExClause>;
1215 fn lift_delayed_literal_to_tcx<'a, 'gcx>(
1216 ex_clause: &chalk_engine::DelayedLiteral<Self>,
1217 tcx: TyCtxt<'a, 'gcx, 'tcx>,
1218 ) -> Option<Self::LiftedDelayedLiteral>;
1220 fn lift_literal_to_tcx<'a, 'gcx>(
1221 ex_clause: &chalk_engine::Literal<Self>,
1222 tcx: TyCtxt<'a, 'gcx, 'tcx>,
1223 ) -> Option<Self::LiftedLiteral>;