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_data_structures::sync::Lrc;
30 use rustc_macros::HashStable;
32 use syntax_pos::{Span, DUMMY_SP};
33 use crate::ty::subst::{InternalSubsts, SubstsRef};
34 use crate::ty::{self, AdtKind, List, Ty, TyCtxt, GenericParamDefKind, ToPredicate};
35 use crate::ty::error::{ExpectedFound, TypeError};
36 use crate::ty::fold::{TypeFolder, TypeFoldable, TypeVisitor};
37 use crate::util::common::ErrorReported;
42 pub use self::SelectionError::*;
43 pub use self::FulfillmentErrorCode::*;
44 pub use self::Vtable::*;
45 pub use self::ObligationCauseCode::*;
47 pub use self::coherence::{add_placeholder_note, orphan_check, overlapping_impls};
48 pub use self::coherence::{OrphanCheckErr, OverlapResult};
49 pub use self::fulfill::{FulfillmentContext, PendingPredicateObligation};
50 pub use self::project::MismatchedProjectionTypes;
51 pub use self::project::{normalize, normalize_projection_type, poly_project_and_unify_type};
52 pub use self::project::{ProjectionCache, ProjectionCacheSnapshot, Reveal, Normalized};
53 pub use self::object_safety::ObjectSafetyViolation;
54 pub use self::object_safety::MethodViolationCode;
55 pub use self::on_unimplemented::{OnUnimplementedDirective, OnUnimplementedNote};
56 pub use self::select::{EvaluationCache, SelectionContext, SelectionCache};
57 pub use self::select::{EvaluationResult, IntercrateAmbiguityCause, OverflowError};
58 pub use self::specialize::{OverlapError, specialization_graph, translate_substs};
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::engine::{TraitEngine, TraitEngineExt};
63 pub use self::util::{elaborate_predicates, elaborate_trait_ref, elaborate_trait_refs};
64 pub use self::util::{supertraits, supertrait_def_ids, transitive_bounds,
65 Supertraits, SupertraitDefIds};
67 pub use self::chalk_fulfill::{
68 CanonicalGoal as ChalkCanonicalGoal,
69 FulfillmentContext as ChalkFulfillmentContext
72 pub use self::ObligationCauseCode::*;
73 pub use self::FulfillmentErrorCode::*;
74 pub use self::SelectionError::*;
75 pub use self::Vtable::*;
77 /// Whether to enable bug compatibility with issue #43355.
78 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
79 pub enum IntercrateMode {
84 /// The mode that trait queries run in.
85 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
86 pub enum TraitQueryMode {
87 // Standard/un-canonicalized queries get accurate
88 // spans etc. passed in and hence can do reasonable
89 // error reporting on their own.
91 // Canonicalized queries get dummy spans and hence
92 // must generally propagate errors to
93 // pre-canonicalization callsites.
97 /// An `Obligation` represents some trait reference (e.g., `int: Eq`) for
98 /// which the vtable must be found. The process of finding a vtable is
99 /// called "resolving" the `Obligation`. This process consists of
100 /// either identifying an `impl` (e.g., `impl Eq for int`) that
101 /// provides the required vtable, or else finding a bound that is in
102 /// scope. The eventual result is usually a `Selection` (defined below).
103 #[derive(Clone, PartialEq, Eq, Hash)]
104 pub struct Obligation<'tcx, T> {
105 /// The reason we have to prove this thing.
106 pub cause: ObligationCause<'tcx>,
108 /// The environment in which we should prove this thing.
109 pub param_env: ty::ParamEnv<'tcx>,
111 /// The thing we are trying to prove.
114 /// If we started proving this as a result of trying to prove
115 /// something else, track the total depth to ensure termination.
116 /// If this goes over a certain threshold, we abort compilation --
117 /// in such cases, we can not say whether or not the predicate
118 /// holds for certain. Stupid halting problem; such a drag.
119 pub recursion_depth: usize,
122 pub type PredicateObligation<'tcx> = Obligation<'tcx, ty::Predicate<'tcx>>;
123 pub type TraitObligation<'tcx> = Obligation<'tcx, ty::PolyTraitPredicate<'tcx>>;
125 /// The reason why we incurred this obligation; used for error reporting.
126 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
127 pub struct ObligationCause<'tcx> {
130 /// The ID of the fn body that triggered this obligation. This is
131 /// used for region obligations to determine the precise
132 /// environment in which the region obligation should be evaluated
133 /// (in particular, closures can add new assumptions). See the
134 /// field `region_obligations` of the `FulfillmentContext` for more
136 pub body_id: hir::HirId,
138 pub code: ObligationCauseCode<'tcx>
141 impl<'tcx> ObligationCause<'tcx> {
142 pub fn span<'a, 'gcx>(&self, tcx: &TyCtxt<'a, 'gcx, 'tcx>) -> Span {
144 ObligationCauseCode::CompareImplMethodObligation { .. } |
145 ObligationCauseCode::MainFunctionType |
146 ObligationCauseCode::StartFunctionType => {
147 tcx.sess.source_map().def_span(self.span)
149 ObligationCauseCode::MatchExpressionArm { arm_span, .. } => arm_span,
155 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
156 pub enum ObligationCauseCode<'tcx> {
157 /// Not well classified or should be obvious from the span.
160 /// A slice or array is WF only if `T: Sized`.
163 /// A tuple is WF only if its middle elements are `Sized`.
166 /// This is the trait reference from the given projection.
167 ProjectionWf(ty::ProjectionTy<'tcx>),
169 /// In an impl of trait `X` for type `Y`, type `Y` must
170 /// also implement all supertraits of `X`.
171 ItemObligation(DefId),
173 /// A type like `&'a T` is WF only if `T: 'a`.
174 ReferenceOutlivesReferent(Ty<'tcx>),
176 /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
177 ObjectTypeBound(Ty<'tcx>, ty::Region<'tcx>),
179 /// Obligation incurred due to an object cast.
180 ObjectCastObligation(/* Object type */ Ty<'tcx>),
182 // Various cases where expressions must be sized/copy/etc:
183 /// L = X implies that L is Sized
185 /// (x1, .., xn) must be Sized
186 TupleInitializerSized,
187 /// S { ... } must be Sized
188 StructInitializerSized,
189 /// Type of each variable must be Sized
190 VariableType(ast::NodeId),
191 /// Argument type must be Sized
193 /// Return type must be Sized
195 /// Yield type must be Sized
197 /// [T,..n] --> T must be Copy
200 /// Types of fields (other than the last, except for packed structs) in a struct must be sized.
201 FieldSized { adt_kind: AdtKind, last: bool },
203 /// Constant expressions must be sized.
206 /// static items must have `Sync` type
209 BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
211 ImplDerivedObligation(DerivedObligationCause<'tcx>),
213 /// error derived when matching traits/impls; see ObligationCause for more details
214 CompareImplMethodObligation {
215 item_name: ast::Name,
216 impl_item_def_id: DefId,
217 trait_item_def_id: DefId,
220 /// Checking that this expression can be assigned where it needs to be
221 // FIXME(eddyb) #11161 is the original Expr required?
224 /// Computing common supertype in the arms of a match expression
227 source: hir::MatchSource,
228 prior_arms: Vec<Span>,
230 discrim_hir_id: hir::HirId,
233 /// Computing common supertype in the pattern guard for the arms of a match expression
234 MatchExpressionArmPattern { span: Span, ty: Ty<'tcx> },
236 /// Computing common supertype in an if expression
240 semicolon: Option<Span>,
243 /// Computing common supertype of an if expression with no else counter-part
244 IfExpressionWithNoElse,
246 /// `main` has wrong type
249 /// `start` has wrong type
252 /// intrinsic has wrong type
258 /// `return` with no expression
261 /// `return` with an expression
262 ReturnType(hir::HirId),
264 /// Block implicit return
265 BlockTailExpression(hir::HirId),
267 /// #[feature(trivial_bounds)] is not enabled
271 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
272 pub struct DerivedObligationCause<'tcx> {
273 /// The trait reference of the parent obligation that led to the
274 /// current obligation. Note that only trait obligations lead to
275 /// derived obligations, so we just store the trait reference here
277 parent_trait_ref: ty::PolyTraitRef<'tcx>,
279 /// The parent trait had this cause.
280 parent_code: Rc<ObligationCauseCode<'tcx>>
283 pub type Obligations<'tcx, O> = Vec<Obligation<'tcx, O>>;
284 pub type PredicateObligations<'tcx> = Vec<PredicateObligation<'tcx>>;
285 pub type TraitObligations<'tcx> = Vec<TraitObligation<'tcx>>;
287 /// The following types:
295 /// * `InEnvironment`,
296 /// are used for representing the trait system in the form of
297 /// logic programming clauses. They are part of the interface
298 /// for the chalk SLG solver.
299 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable)]
300 pub enum WhereClause<'tcx> {
301 Implemented(ty::TraitPredicate<'tcx>),
302 ProjectionEq(ty::ProjectionPredicate<'tcx>),
303 RegionOutlives(ty::RegionOutlivesPredicate<'tcx>),
304 TypeOutlives(ty::TypeOutlivesPredicate<'tcx>),
307 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable)]
308 pub enum WellFormed<'tcx> {
309 Trait(ty::TraitPredicate<'tcx>),
313 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable)]
314 pub enum FromEnv<'tcx> {
315 Trait(ty::TraitPredicate<'tcx>),
319 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable)]
320 pub enum DomainGoal<'tcx> {
321 Holds(WhereClause<'tcx>),
322 WellFormed(WellFormed<'tcx>),
323 FromEnv(FromEnv<'tcx>),
324 Normalize(ty::ProjectionPredicate<'tcx>),
327 pub type PolyDomainGoal<'tcx> = ty::Binder<DomainGoal<'tcx>>;
329 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
330 pub enum QuantifierKind {
335 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
336 pub enum GoalKind<'tcx> {
337 Implies(Clauses<'tcx>, Goal<'tcx>),
338 And(Goal<'tcx>, Goal<'tcx>),
340 DomainGoal(DomainGoal<'tcx>),
341 Quantified(QuantifierKind, ty::Binder<Goal<'tcx>>),
342 Subtype(Ty<'tcx>, Ty<'tcx>),
346 pub type Goal<'tcx> = &'tcx GoalKind<'tcx>;
348 pub type Goals<'tcx> = &'tcx List<Goal<'tcx>>;
350 impl<'tcx> DomainGoal<'tcx> {
351 pub fn into_goal(self) -> GoalKind<'tcx> {
352 GoalKind::DomainGoal(self)
355 pub fn into_program_clause(self) -> ProgramClause<'tcx> {
358 hypotheses: ty::List::empty(),
359 category: ProgramClauseCategory::Other,
364 impl<'tcx> GoalKind<'tcx> {
365 pub fn from_poly_domain_goal<'a, 'gcx>(
366 domain_goal: PolyDomainGoal<'tcx>,
367 tcx: TyCtxt<'a, 'gcx, 'tcx>,
368 ) -> GoalKind<'tcx> {
369 match domain_goal.no_bound_vars() {
370 Some(p) => p.into_goal(),
371 None => GoalKind::Quantified(
372 QuantifierKind::Universal,
373 domain_goal.map_bound(|p| tcx.mk_goal(p.into_goal()))
379 /// This matches the definition from Page 7 of "A Proof Procedure for the Logic of Hereditary
380 /// Harrop Formulas".
381 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
382 pub enum Clause<'tcx> {
383 Implies(ProgramClause<'tcx>),
384 ForAll(ty::Binder<ProgramClause<'tcx>>),
388 pub fn category(self) -> ProgramClauseCategory {
390 Clause::Implies(clause) => clause.category,
391 Clause::ForAll(clause) => clause.skip_binder().category,
396 /// Multiple clauses.
397 pub type Clauses<'tcx> = &'tcx List<Clause<'tcx>>;
399 /// A "program clause" has the form `D :- G1, ..., Gn`. It is saying
400 /// that the domain goal `D` is true if `G1...Gn` are provable. This
401 /// is equivalent to the implication `G1..Gn => D`; we usually write
402 /// it with the reverse implication operator `:-` to emphasize the way
403 /// that programs are actually solved (via backchaining, which starts
404 /// with the goal to solve and proceeds from there).
405 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
406 pub struct ProgramClause<'tcx> {
407 /// This goal will be considered true ...
408 pub goal: DomainGoal<'tcx>,
410 /// ... if we can prove these hypotheses (there may be no hypotheses at all):
411 pub hypotheses: Goals<'tcx>,
413 /// Useful for filtering clauses.
414 pub category: ProgramClauseCategory,
417 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
418 pub enum ProgramClauseCategory {
424 /// A set of clauses that we assume to be true.
425 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
426 pub struct Environment<'tcx> {
427 pub clauses: Clauses<'tcx>,
430 impl Environment<'tcx> {
431 pub fn with<G>(self, goal: G) -> InEnvironment<'tcx, G> {
439 /// Something (usually a goal), along with an environment.
440 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
441 pub struct InEnvironment<'tcx, G> {
442 pub environment: Environment<'tcx>,
446 pub type Selection<'tcx> = Vtable<'tcx, PredicateObligation<'tcx>>;
448 #[derive(Clone,Debug)]
449 pub enum SelectionError<'tcx> {
451 OutputTypeParameterMismatch(ty::PolyTraitRef<'tcx>,
452 ty::PolyTraitRef<'tcx>,
453 ty::error::TypeError<'tcx>),
454 TraitNotObjectSafe(DefId),
455 ConstEvalFailure(ErrorHandled),
459 pub struct FulfillmentError<'tcx> {
460 pub obligation: PredicateObligation<'tcx>,
461 pub code: FulfillmentErrorCode<'tcx>
465 pub enum FulfillmentErrorCode<'tcx> {
466 CodeSelectionError(SelectionError<'tcx>),
467 CodeProjectionError(MismatchedProjectionTypes<'tcx>),
468 CodeSubtypeError(ExpectedFound<Ty<'tcx>>,
469 TypeError<'tcx>), // always comes from a SubtypePredicate
473 /// When performing resolution, it is typically the case that there
474 /// can be one of three outcomes:
476 /// - `Ok(Some(r))`: success occurred with result `r`
477 /// - `Ok(None)`: could not definitely determine anything, usually due
478 /// to inconclusive type inference.
479 /// - `Err(e)`: error `e` occurred
480 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
482 /// Given the successful resolution of an obligation, the `Vtable`
483 /// indicates where the vtable comes from. Note that while we call this
484 /// a "vtable", it does not necessarily indicate dynamic dispatch at
485 /// runtime. `Vtable` instances just tell the compiler where to find
486 /// methods, but in generic code those methods are typically statically
487 /// dispatched -- only when an object is constructed is a `Vtable`
488 /// instance reified into an actual vtable.
490 /// For example, the vtable may be tied to a specific impl (case A),
491 /// or it may be relative to some bound that is in scope (case B).
494 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
495 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
496 /// impl Clone for int { ... } // Impl_3
498 /// fn foo<T:Clone>(concrete: Option<Box<int>>,
500 /// mixed: Option<T>) {
502 /// // Case A: Vtable points at a specific impl. Only possible when
503 /// // type is concretely known. If the impl itself has bounded
504 /// // type parameters, Vtable will carry resolutions for those as well:
505 /// concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
507 /// // Case B: Vtable must be provided by caller. This applies when
508 /// // type is a type parameter.
509 /// param.clone(); // VtableParam
511 /// // Case C: A mix of cases A and B.
512 /// mixed.clone(); // Vtable(Impl_1, [VtableParam])
516 /// ### The type parameter `N`
518 /// See explanation on `VtableImplData`.
519 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
520 pub enum Vtable<'tcx, N> {
521 /// Vtable identifying a particular impl.
522 VtableImpl(VtableImplData<'tcx, N>),
524 /// Vtable for auto trait implementations.
525 /// This carries the information and nested obligations with regards
526 /// to an auto implementation for a trait `Trait`. The nested obligations
527 /// ensure the trait implementation holds for all the constituent types.
528 VtableAutoImpl(VtableAutoImplData<N>),
530 /// Successful resolution to an obligation provided by the caller
531 /// for some type parameter. The `Vec<N>` represents the
532 /// obligations incurred from normalizing the where-clause (if
536 /// Virtual calls through an object.
537 VtableObject(VtableObjectData<'tcx, N>),
539 /// Successful resolution for a builtin trait.
540 VtableBuiltin(VtableBuiltinData<N>),
542 /// Vtable automatically generated for a closure. The `DefId` is the ID
543 /// of the closure expression. This is a `VtableImpl` in spirit, but the
544 /// impl is generated by the compiler and does not appear in the source.
545 VtableClosure(VtableClosureData<'tcx, N>),
547 /// Same as above, but for a function pointer type with the given signature.
548 VtableFnPointer(VtableFnPointerData<'tcx, N>),
550 /// Vtable automatically generated for a generator.
551 VtableGenerator(VtableGeneratorData<'tcx, N>),
553 /// Vtable for a trait alias.
554 VtableTraitAlias(VtableTraitAliasData<'tcx, N>),
557 /// Identifies a particular impl in the source, along with a set of
558 /// substitutions from the impl's type/lifetime parameters. The
559 /// `nested` vector corresponds to the nested obligations attached to
560 /// the impl's type parameters.
562 /// The type parameter `N` indicates the type used for "nested
563 /// obligations" that are required by the impl. During type check, this
564 /// is `Obligation`, as one might expect. During codegen, however, this
565 /// is `()`, because codegen only requires a shallow resolution of an
566 /// impl, and nested obligations are satisfied later.
567 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
568 pub struct VtableImplData<'tcx, N> {
569 pub impl_def_id: DefId,
570 pub substs: SubstsRef<'tcx>,
574 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
575 pub struct VtableGeneratorData<'tcx, N> {
576 pub generator_def_id: DefId,
577 pub substs: ty::GeneratorSubsts<'tcx>,
578 /// Nested obligations. This can be non-empty if the generator
579 /// signature contains associated types.
583 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
584 pub struct VtableClosureData<'tcx, N> {
585 pub closure_def_id: DefId,
586 pub substs: ty::ClosureSubsts<'tcx>,
587 /// Nested obligations. This can be non-empty if the closure
588 /// signature contains associated types.
592 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
593 pub struct VtableAutoImplData<N> {
594 pub trait_def_id: DefId,
598 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
599 pub struct VtableBuiltinData<N> {
603 /// A vtable for some object-safe trait `Foo` automatically derived
604 /// for the object type `Foo`.
605 #[derive(PartialEq, Eq, Clone, RustcEncodable, RustcDecodable, HashStable)]
606 pub struct VtableObjectData<'tcx, N> {
607 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
608 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
610 /// The vtable is formed by concatenating together the method lists of
611 /// the base object trait and all supertraits; this is the start of
612 /// `upcast_trait_ref`'s methods in that vtable.
613 pub vtable_base: usize,
618 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
619 pub struct VtableFnPointerData<'tcx, N> {
624 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
625 pub struct VtableTraitAliasData<'tcx, N> {
626 pub alias_def_id: DefId,
627 pub substs: SubstsRef<'tcx>,
631 /// Creates predicate obligations from the generic bounds.
632 pub fn predicates_for_generics<'tcx>(cause: ObligationCause<'tcx>,
633 param_env: ty::ParamEnv<'tcx>,
634 generic_bounds: &ty::InstantiatedPredicates<'tcx>)
635 -> PredicateObligations<'tcx>
637 util::predicates_for_generics(cause, 0, param_env, generic_bounds)
640 /// Determines whether the type `ty` is known to meet `bound` and
641 /// returns true if so. Returns false if `ty` either does not meet
642 /// `bound` or is not known to meet bound (note that this is
643 /// conservative towards *no impl*, which is the opposite of the
644 /// `evaluate` methods).
645 pub fn type_known_to_meet_bound_modulo_regions<'a, 'gcx, 'tcx>(
646 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
647 param_env: ty::ParamEnv<'tcx>,
652 debug!("type_known_to_meet_bound_modulo_regions(ty={:?}, bound={:?})",
654 infcx.tcx.def_path_str(def_id));
656 let trait_ref = ty::TraitRef {
658 substs: infcx.tcx.mk_substs_trait(ty, &[]),
660 let obligation = Obligation {
662 cause: ObligationCause::misc(span, hir::DUMMY_HIR_ID),
664 predicate: trait_ref.to_predicate(),
667 let result = infcx.predicate_must_hold_modulo_regions(&obligation);
668 debug!("type_known_to_meet_ty={:?} bound={} => {:?}",
669 ty, infcx.tcx.def_path_str(def_id), result);
671 if result && (ty.has_infer_types() || ty.has_closure_types()) {
672 // Because of inference "guessing", selection can sometimes claim
673 // to succeed while the success requires a guess. To ensure
674 // this function's result remains infallible, we must confirm
675 // that guess. While imperfect, I believe this is sound.
677 // The handling of regions in this area of the code is terrible,
678 // see issue #29149. We should be able to improve on this with
680 let mut fulfill_cx = FulfillmentContext::new_ignoring_regions();
682 // We can use a dummy node-id here because we won't pay any mind
683 // to region obligations that arise (there shouldn't really be any
685 let cause = ObligationCause::misc(span, hir::DUMMY_HIR_ID);
687 fulfill_cx.register_bound(infcx, param_env, ty, def_id, cause);
689 // Note: we only assume something is `Copy` if we can
690 // *definitively* show that it implements `Copy`. Otherwise,
691 // assume it is move; linear is always ok.
692 match fulfill_cx.select_all_or_error(infcx) {
694 debug!("type_known_to_meet_bound_modulo_regions: ty={:?} bound={} success",
696 infcx.tcx.def_path_str(def_id));
700 debug!("type_known_to_meet_bound_modulo_regions: ty={:?} bound={} errors={:?}",
702 infcx.tcx.def_path_str(def_id),
712 fn do_normalize_predicates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
713 region_context: DefId,
714 cause: ObligationCause<'tcx>,
715 elaborated_env: ty::ParamEnv<'tcx>,
716 predicates: Vec<ty::Predicate<'tcx>>)
717 -> Result<Vec<ty::Predicate<'tcx>>, ErrorReported>
720 "do_normalize_predicates(predicates={:?}, region_context={:?}, cause={:?})",
725 let span = cause.span;
726 tcx.infer_ctxt().enter(|infcx| {
727 // FIXME. We should really... do something with these region
728 // obligations. But this call just continues the older
729 // behavior (i.e., doesn't cause any new bugs), and it would
730 // take some further refactoring to actually solve them. In
731 // particular, we would have to handle implied bounds
732 // properly, and that code is currently largely confined to
733 // regionck (though I made some efforts to extract it
736 // @arielby: In any case, these obligations are checked
737 // by wfcheck anyway, so I'm not sure we have to check
738 // them here too, and we will remove this function when
739 // we move over to lazy normalization *anyway*.
740 let fulfill_cx = FulfillmentContext::new_ignoring_regions();
741 let predicates = match fully_normalize(
748 Ok(predicates) => predicates,
750 infcx.report_fulfillment_errors(&errors, None, false);
751 return Err(ErrorReported)
755 debug!("do_normalize_predictes: normalized predicates = {:?}", predicates);
757 let region_scope_tree = region::ScopeTree::default();
759 // We can use the `elaborated_env` here; the region code only
760 // cares about declarations like `'a: 'b`.
761 let outlives_env = OutlivesEnvironment::new(elaborated_env);
763 infcx.resolve_regions_and_report_errors(
767 SuppressRegionErrors::default(),
770 let predicates = match infcx.fully_resolve(&predicates) {
771 Ok(predicates) => predicates,
773 // If we encounter a fixup error, it means that some type
774 // variable wound up unconstrained. I actually don't know
775 // if this can happen, and I certainly don't expect it to
776 // happen often, but if it did happen it probably
777 // represents a legitimate failure due to some kind of
778 // unconstrained variable, and it seems better not to ICE,
779 // all things considered.
780 tcx.sess.span_err(span, &fixup_err.to_string());
781 return Err(ErrorReported)
785 match tcx.lift_to_global(&predicates) {
786 Some(predicates) => Ok(predicates),
788 // FIXME: shouldn't we, you know, actually report an error here? or an ICE?
795 // FIXME: this is gonna need to be removed ...
796 /// Normalizes the parameter environment, reporting errors if they occur.
797 pub fn normalize_param_env_or_error<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
798 region_context: DefId,
799 unnormalized_env: ty::ParamEnv<'tcx>,
800 cause: ObligationCause<'tcx>)
801 -> ty::ParamEnv<'tcx>
803 // I'm not wild about reporting errors here; I'd prefer to
804 // have the errors get reported at a defined place (e.g.,
805 // during typeck). Instead I have all parameter
806 // environments, in effect, going through this function
807 // and hence potentially reporting errors. This ensures of
808 // course that we never forget to normalize (the
809 // alternative seemed like it would involve a lot of
810 // manual invocations of this fn -- and then we'd have to
811 // deal with the errors at each of those sites).
813 // In any case, in practice, typeck constructs all the
814 // parameter environments once for every fn as it goes,
815 // and errors will get reported then; so after typeck we
816 // can be sure that no errors should occur.
818 debug!("normalize_param_env_or_error(region_context={:?}, unnormalized_env={:?}, cause={:?})",
819 region_context, unnormalized_env, cause);
821 let mut predicates: Vec<_> =
822 util::elaborate_predicates(tcx, unnormalized_env.caller_bounds.to_vec())
825 debug!("normalize_param_env_or_error: elaborated-predicates={:?}",
828 let elaborated_env = ty::ParamEnv::new(
829 tcx.intern_predicates(&predicates),
830 unnormalized_env.reveal,
831 unnormalized_env.def_id
834 // HACK: we are trying to normalize the param-env inside *itself*. The problem is that
835 // normalization expects its param-env to be already normalized, which means we have
838 // The way we handle this is by normalizing the param-env inside an unnormalized version
839 // of the param-env, which means that if the param-env contains unnormalized projections,
840 // we'll have some normalization failures. This is unfortunate.
842 // Lazy normalization would basically handle this by treating just the
843 // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
845 // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
846 // types, so to make the situation less bad, we normalize all the predicates *but*
847 // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
848 // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
850 // This works fairly well because trait matching does not actually care about param-env
851 // TypeOutlives predicates - these are normally used by regionck.
852 let outlives_predicates: Vec<_> = predicates.drain_filter(|predicate| {
854 ty::Predicate::TypeOutlives(..) => true,
859 debug!("normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
860 predicates, outlives_predicates);
861 let non_outlives_predicates =
862 match do_normalize_predicates(tcx, region_context, cause.clone(),
863 elaborated_env, predicates) {
864 Ok(predicates) => predicates,
865 // An unnormalized env is better than nothing.
866 Err(ErrorReported) => {
867 debug!("normalize_param_env_or_error: errored resolving non-outlives predicates");
868 return elaborated_env
872 debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates);
874 // Not sure whether it is better to include the unnormalized TypeOutlives predicates
875 // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
876 // predicates here anyway. Keeping them here anyway because it seems safer.
877 let outlives_env: Vec<_> =
878 non_outlives_predicates.iter().chain(&outlives_predicates).cloned().collect();
879 let outlives_env = ty::ParamEnv::new(
880 tcx.intern_predicates(&outlives_env),
881 unnormalized_env.reveal,
884 let outlives_predicates =
885 match do_normalize_predicates(tcx, region_context, cause,
886 outlives_env, outlives_predicates) {
887 Ok(predicates) => predicates,
888 // An unnormalized env is better than nothing.
889 Err(ErrorReported) => {
890 debug!("normalize_param_env_or_error: errored resolving outlives predicates");
891 return elaborated_env
894 debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates);
896 let mut predicates = non_outlives_predicates;
897 predicates.extend(outlives_predicates);
898 debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
900 tcx.intern_predicates(&predicates),
901 unnormalized_env.reveal,
902 unnormalized_env.def_id
906 pub fn fully_normalize<'a, 'gcx, 'tcx, T>(
907 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
908 mut fulfill_cx: FulfillmentContext<'tcx>,
909 cause: ObligationCause<'tcx>,
910 param_env: ty::ParamEnv<'tcx>,
912 -> Result<T, Vec<FulfillmentError<'tcx>>>
913 where T : TypeFoldable<'tcx>
915 debug!("fully_normalize_with_fulfillcx(value={:?})", value);
916 let selcx = &mut SelectionContext::new(infcx);
917 let Normalized { value: normalized_value, obligations } =
918 project::normalize(selcx, param_env, cause, value);
919 debug!("fully_normalize: normalized_value={:?} obligations={:?}",
922 for obligation in obligations {
923 fulfill_cx.register_predicate_obligation(selcx.infcx(), obligation);
926 debug!("fully_normalize: select_all_or_error start");
927 fulfill_cx.select_all_or_error(infcx)?;
928 debug!("fully_normalize: select_all_or_error complete");
929 let resolved_value = infcx.resolve_type_vars_if_possible(&normalized_value);
930 debug!("fully_normalize: resolved_value={:?}", resolved_value);
934 /// Normalizes the predicates and checks whether they hold in an empty
935 /// environment. If this returns false, then either normalize
936 /// encountered an error or one of the predicates did not hold. Used
937 /// when creating vtables to check for unsatisfiable methods.
938 fn normalize_and_test_predicates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
939 predicates: Vec<ty::Predicate<'tcx>>)
942 debug!("normalize_and_test_predicates(predicates={:?})",
945 let result = tcx.infer_ctxt().enter(|infcx| {
946 let param_env = ty::ParamEnv::reveal_all();
947 let mut selcx = SelectionContext::new(&infcx);
948 let mut fulfill_cx = FulfillmentContext::new();
949 let cause = ObligationCause::dummy();
950 let Normalized { value: predicates, obligations } =
951 normalize(&mut selcx, param_env, cause.clone(), &predicates);
952 for obligation in obligations {
953 fulfill_cx.register_predicate_obligation(&infcx, obligation);
955 for predicate in predicates {
956 let obligation = Obligation::new(cause.clone(), param_env, predicate);
957 fulfill_cx.register_predicate_obligation(&infcx, obligation);
960 fulfill_cx.select_all_or_error(&infcx).is_ok()
962 debug!("normalize_and_test_predicates(predicates={:?}) = {:?}",
967 fn substitute_normalize_and_test_predicates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
968 key: (DefId, SubstsRef<'tcx>))
971 debug!("substitute_normalize_and_test_predicates(key={:?})",
974 let predicates = tcx.predicates_of(key.0).instantiate(tcx, key.1).predicates;
975 let result = normalize_and_test_predicates(tcx, predicates);
977 debug!("substitute_normalize_and_test_predicates(key={:?}) = {:?}",
982 /// Given a trait `trait_ref`, iterates the vtable entries
983 /// that come from `trait_ref`, including its supertraits.
984 #[inline] // FIXME(#35870): avoid closures being unexported due to `impl Trait`.
985 fn vtable_methods<'a, 'tcx>(
986 tcx: TyCtxt<'a, 'tcx, 'tcx>,
987 trait_ref: ty::PolyTraitRef<'tcx>)
988 -> Lrc<Vec<Option<(DefId, SubstsRef<'tcx>)>>>
990 debug!("vtable_methods({:?})", trait_ref);
993 supertraits(tcx, trait_ref).flat_map(move |trait_ref| {
994 let trait_methods = tcx.associated_items(trait_ref.def_id())
995 .filter(|item| item.kind == ty::AssociatedKind::Method);
997 // Now list each method's DefId and InternalSubsts (for within its trait).
998 // If the method can never be called from this object, produce None.
999 trait_methods.map(move |trait_method| {
1000 debug!("vtable_methods: trait_method={:?}", trait_method);
1001 let def_id = trait_method.def_id;
1003 // Some methods cannot be called on an object; skip those.
1004 if !tcx.is_vtable_safe_method(trait_ref.def_id(), &trait_method) {
1005 debug!("vtable_methods: not vtable safe");
1009 // the method may have some early-bound lifetimes, add
1010 // regions for those
1011 let substs = trait_ref.map_bound(|trait_ref|
1012 InternalSubsts::for_item(tcx, def_id, |param, _|
1014 GenericParamDefKind::Lifetime => tcx.types.re_erased.into(),
1015 GenericParamDefKind::Type { .. } |
1016 GenericParamDefKind::Const => {
1017 trait_ref.substs[param.index as usize]
1023 // the trait type may have higher-ranked lifetimes in it;
1024 // so erase them if they appear, so that we get the type
1025 // at some particular call site
1026 let substs = tcx.normalize_erasing_late_bound_regions(
1027 ty::ParamEnv::reveal_all(),
1031 // It's possible that the method relies on where clauses that
1032 // do not hold for this particular set of type parameters.
1033 // Note that this method could then never be called, so we
1034 // do not want to try and codegen it, in that case (see #23435).
1035 let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs);
1036 if !normalize_and_test_predicates(tcx, predicates.predicates) {
1037 debug!("vtable_methods: predicates do not hold");
1041 Some((def_id, substs))
1047 impl<'tcx,O> Obligation<'tcx,O> {
1048 pub fn new(cause: ObligationCause<'tcx>,
1049 param_env: ty::ParamEnv<'tcx>,
1051 -> Obligation<'tcx, O>
1053 Obligation { cause, param_env, recursion_depth: 0, predicate }
1056 fn with_depth(cause: ObligationCause<'tcx>,
1057 recursion_depth: usize,
1058 param_env: ty::ParamEnv<'tcx>,
1060 -> Obligation<'tcx, O>
1062 Obligation { cause, param_env, recursion_depth, predicate }
1065 pub fn misc(span: Span,
1066 body_id: hir::HirId,
1067 param_env: ty::ParamEnv<'tcx>,
1069 -> Obligation<'tcx, O> {
1070 Obligation::new(ObligationCause::misc(span, body_id), param_env, trait_ref)
1073 pub fn with<P>(&self, value: P) -> Obligation<'tcx,P> {
1074 Obligation { cause: self.cause.clone(),
1075 param_env: self.param_env,
1076 recursion_depth: self.recursion_depth,
1081 impl<'tcx> ObligationCause<'tcx> {
1083 pub fn new(span: Span,
1084 body_id: hir::HirId,
1085 code: ObligationCauseCode<'tcx>)
1086 -> ObligationCause<'tcx> {
1087 ObligationCause { span, body_id, code }
1090 pub fn misc(span: Span, body_id: hir::HirId) -> ObligationCause<'tcx> {
1091 ObligationCause { span, body_id, code: MiscObligation }
1094 pub fn dummy() -> ObligationCause<'tcx> {
1095 ObligationCause { span: DUMMY_SP, body_id: hir::CRATE_HIR_ID, code: MiscObligation }
1099 impl<'tcx, N> Vtable<'tcx, N> {
1100 pub fn nested_obligations(self) -> Vec<N> {
1102 VtableImpl(i) => i.nested,
1103 VtableParam(n) => n,
1104 VtableBuiltin(i) => i.nested,
1105 VtableAutoImpl(d) => d.nested,
1106 VtableClosure(c) => c.nested,
1107 VtableGenerator(c) => c.nested,
1108 VtableObject(d) => d.nested,
1109 VtableFnPointer(d) => d.nested,
1110 VtableTraitAlias(d) => d.nested,
1114 pub fn map<M, F>(self, f: F) -> Vtable<'tcx, M> where F: FnMut(N) -> M {
1116 VtableImpl(i) => VtableImpl(VtableImplData {
1117 impl_def_id: i.impl_def_id,
1119 nested: i.nested.into_iter().map(f).collect(),
1121 VtableParam(n) => VtableParam(n.into_iter().map(f).collect()),
1122 VtableBuiltin(i) => VtableBuiltin(VtableBuiltinData {
1123 nested: i.nested.into_iter().map(f).collect(),
1125 VtableObject(o) => VtableObject(VtableObjectData {
1126 upcast_trait_ref: o.upcast_trait_ref,
1127 vtable_base: o.vtable_base,
1128 nested: o.nested.into_iter().map(f).collect(),
1130 VtableAutoImpl(d) => VtableAutoImpl(VtableAutoImplData {
1131 trait_def_id: d.trait_def_id,
1132 nested: d.nested.into_iter().map(f).collect(),
1134 VtableClosure(c) => VtableClosure(VtableClosureData {
1135 closure_def_id: c.closure_def_id,
1137 nested: c.nested.into_iter().map(f).collect(),
1139 VtableGenerator(c) => VtableGenerator(VtableGeneratorData {
1140 generator_def_id: c.generator_def_id,
1142 nested: c.nested.into_iter().map(f).collect(),
1144 VtableFnPointer(p) => VtableFnPointer(VtableFnPointerData {
1146 nested: p.nested.into_iter().map(f).collect(),
1148 VtableTraitAlias(d) => VtableTraitAlias(VtableTraitAliasData {
1149 alias_def_id: d.alias_def_id,
1151 nested: d.nested.into_iter().map(f).collect(),
1157 impl<'tcx> FulfillmentError<'tcx> {
1158 fn new(obligation: PredicateObligation<'tcx>,
1159 code: FulfillmentErrorCode<'tcx>)
1160 -> FulfillmentError<'tcx>
1162 FulfillmentError { obligation: obligation, code: code }
1166 impl<'tcx> TraitObligation<'tcx> {
1167 fn self_ty(&self) -> ty::Binder<Ty<'tcx>> {
1168 self.predicate.map_bound(|p| p.self_ty())
1172 pub fn provide(providers: &mut ty::query::Providers<'_>) {
1173 *providers = ty::query::Providers {
1174 is_object_safe: object_safety::is_object_safe_provider,
1175 specialization_graph_of: specialize::specialization_graph_provider,
1176 specializes: specialize::specializes,
1177 codegen_fulfill_obligation: codegen::codegen_fulfill_obligation,
1179 substitute_normalize_and_test_predicates,
1184 pub trait ExClauseFold<'tcx>
1186 Self: chalk_engine::context::Context + Clone,
1188 fn fold_ex_clause_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(
1189 ex_clause: &chalk_engine::ExClause<Self>,
1191 ) -> chalk_engine::ExClause<Self>;
1193 fn visit_ex_clause_with<'gcx: 'tcx, V: TypeVisitor<'tcx>>(
1194 ex_clause: &chalk_engine::ExClause<Self>,
1199 pub trait ChalkContextLift<'tcx>
1201 Self: chalk_engine::context::Context + Clone,
1203 type LiftedExClause: Debug + 'tcx;
1204 type LiftedDelayedLiteral: Debug + 'tcx;
1205 type LiftedLiteral: Debug + 'tcx;
1207 fn lift_ex_clause_to_tcx<'a, 'gcx>(
1208 ex_clause: &chalk_engine::ExClause<Self>,
1209 tcx: TyCtxt<'a, 'gcx, 'tcx>,
1210 ) -> Option<Self::LiftedExClause>;
1212 fn lift_delayed_literal_to_tcx<'a, 'gcx>(
1213 ex_clause: &chalk_engine::DelayedLiteral<Self>,
1214 tcx: TyCtxt<'a, 'gcx, 'tcx>,
1215 ) -> Option<Self::LiftedDelayedLiteral>;
1217 fn lift_literal_to_tcx<'a, 'gcx>(
1218 ex_clause: &chalk_engine::Literal<Self>,
1219 tcx: TyCtxt<'a, 'gcx, 'tcx>,
1220 ) -> Option<Self::LiftedLiteral>;