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,
66 pub use self::util::{expand_trait_aliases, TraitAliasExpander};
68 pub use self::chalk_fulfill::{
69 CanonicalGoal as ChalkCanonicalGoal,
70 FulfillmentContext as ChalkFulfillmentContext
73 pub use self::ObligationCauseCode::*;
74 pub use self::FulfillmentErrorCode::*;
75 pub use self::SelectionError::*;
76 pub use self::Vtable::*;
78 /// Whether to enable bug compatibility with issue #43355.
79 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
80 pub enum IntercrateMode {
85 /// The mode that trait queries run in.
86 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
87 pub enum TraitQueryMode {
88 // Standard/un-canonicalized queries get accurate
89 // spans etc. passed in and hence can do reasonable
90 // error reporting on their own.
92 // Canonicalized queries get dummy spans and hence
93 // must generally propagate errors to
94 // pre-canonicalization callsites.
98 /// An `Obligation` represents some trait reference (e.g., `int: Eq`) for
99 /// which the vtable must be found. The process of finding a vtable is
100 /// called "resolving" the `Obligation`. This process consists of
101 /// either identifying an `impl` (e.g., `impl Eq for int`) that
102 /// provides the required vtable, or else finding a bound that is in
103 /// scope. The eventual result is usually a `Selection` (defined below).
104 #[derive(Clone, PartialEq, Eq, Hash)]
105 pub struct Obligation<'tcx, T> {
106 /// The reason we have to prove this thing.
107 pub cause: ObligationCause<'tcx>,
109 /// The environment in which we should prove this thing.
110 pub param_env: ty::ParamEnv<'tcx>,
112 /// The thing we are trying to prove.
115 /// If we started proving this as a result of trying to prove
116 /// something else, track the total depth to ensure termination.
117 /// If this goes over a certain threshold, we abort compilation --
118 /// in such cases, we can not say whether or not the predicate
119 /// holds for certain. Stupid halting problem; such a drag.
120 pub recursion_depth: usize,
123 pub type PredicateObligation<'tcx> = Obligation<'tcx, ty::Predicate<'tcx>>;
124 pub type TraitObligation<'tcx> = Obligation<'tcx, ty::PolyTraitPredicate<'tcx>>;
126 // `PredicateObligation` is used a lot. Make sure it doesn't unintentionally get bigger.
127 #[cfg(target_arch = "x86_64")]
128 static_assert_size!(PredicateObligation<'_>, 112);
130 /// The reason why we incurred this obligation; used for error reporting.
131 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
132 pub struct ObligationCause<'tcx> {
135 /// The ID of the fn body that triggered this obligation. This is
136 /// used for region obligations to determine the precise
137 /// environment in which the region obligation should be evaluated
138 /// (in particular, closures can add new assumptions). See the
139 /// field `region_obligations` of the `FulfillmentContext` for more
141 pub body_id: hir::HirId,
143 pub code: ObligationCauseCode<'tcx>
146 impl<'tcx> ObligationCause<'tcx> {
147 pub fn span(&self, tcx: TyCtxt<'tcx>) -> Span {
149 ObligationCauseCode::CompareImplMethodObligation { .. } |
150 ObligationCauseCode::MainFunctionType |
151 ObligationCauseCode::StartFunctionType => {
152 tcx.sess.source_map().def_span(self.span)
154 ObligationCauseCode::MatchExpressionArm(
155 box MatchExpressionArmCause { arm_span, .. }) => arm_span,
161 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
162 pub enum ObligationCauseCode<'tcx> {
163 /// Not well classified or should be obvious from the span.
166 /// A slice or array is WF only if `T: Sized`.
169 /// A tuple is WF only if its middle elements are `Sized`.
172 /// This is the trait reference from the given projection.
173 ProjectionWf(ty::ProjectionTy<'tcx>),
175 /// In an impl of trait `X` for type `Y`, type `Y` must
176 /// also implement all supertraits of `X`.
177 ItemObligation(DefId),
179 /// Like `ItemObligation`, but with extra detail on the source of the obligation.
180 BindingObligation(DefId, Span),
182 /// A type like `&'a T` is WF only if `T: 'a`.
183 ReferenceOutlivesReferent(Ty<'tcx>),
185 /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
186 ObjectTypeBound(Ty<'tcx>, ty::Region<'tcx>),
188 /// Obligation incurred due to an object cast.
189 ObjectCastObligation(/* Object type */ Ty<'tcx>),
191 /// Obligation incurred due to a coercion.
192 Coercion { source: Ty<'tcx>, target: Ty<'tcx> },
194 // Various cases where expressions must be sized/copy/etc:
195 /// L = X implies that L is Sized
197 /// (x1, .., xn) must be Sized
198 TupleInitializerSized,
199 /// S { ... } must be Sized
200 StructInitializerSized,
201 /// Type of each variable must be Sized
202 VariableType(hir::HirId),
203 /// Argument type must be Sized
205 /// Return type must be Sized
207 /// Yield type must be Sized
209 /// [T,..n] --> T must be Copy
212 /// Types of fields (other than the last, except for packed structs) in a struct must be sized.
213 FieldSized { adt_kind: AdtKind, last: bool },
215 /// Constant expressions must be sized.
218 /// Static items must have `Sync` type
221 BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
223 ImplDerivedObligation(DerivedObligationCause<'tcx>),
225 /// Error derived when matching traits/impls; see ObligationCause for more details
226 CompareImplMethodObligation {
227 item_name: ast::Name,
228 impl_item_def_id: DefId,
229 trait_item_def_id: DefId,
232 /// Checking that this expression can be assigned where it needs to be
233 // FIXME(eddyb) #11161 is the original Expr required?
236 /// Computing common supertype in the arms of a match expression
237 MatchExpressionArm(Box<MatchExpressionArmCause<'tcx>>),
239 /// Computing common supertype in the pattern guard for the arms of a match expression
240 MatchExpressionArmPattern { span: Span, ty: Ty<'tcx> },
242 /// Computing common supertype in an if expression
243 IfExpression(Box<IfExpressionCause>),
245 /// Computing common supertype of an if expression with no else counter-part
246 IfExpressionWithNoElse,
248 /// `main` has wrong type
251 /// `start` has wrong type
254 /// Intrinsic has wrong type
260 /// `return` with no expression
263 /// `return` with an expression
264 ReturnValue(hir::HirId),
266 /// Return type of this function
269 /// Block implicit return
270 BlockTailExpression(hir::HirId),
272 /// #[feature(trivial_bounds)] is not enabled
275 AssocTypeBound(/*impl*/ Option<Span>, /*original*/ Span),
278 // `ObligationCauseCode` is used a lot. Make sure it doesn't unintentionally get bigger.
279 #[cfg(target_arch = "x86_64")]
280 static_assert_size!(ObligationCauseCode<'_>, 32);
282 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
283 pub struct MatchExpressionArmCause<'tcx> {
285 pub source: hir::MatchSource,
286 pub prior_arms: Vec<Span>,
287 pub last_ty: Ty<'tcx>,
288 pub discrim_hir_id: hir::HirId,
291 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
292 pub struct IfExpressionCause {
294 pub outer: Option<Span>,
295 pub semicolon: Option<Span>,
298 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
299 pub struct DerivedObligationCause<'tcx> {
300 /// The trait reference of the parent obligation that led to the
301 /// current obligation. Note that only trait obligations lead to
302 /// derived obligations, so we just store the trait reference here
304 parent_trait_ref: ty::PolyTraitRef<'tcx>,
306 /// The parent trait had this cause.
307 parent_code: Rc<ObligationCauseCode<'tcx>>
310 pub type Obligations<'tcx, O> = Vec<Obligation<'tcx, O>>;
311 pub type PredicateObligations<'tcx> = Vec<PredicateObligation<'tcx>>;
312 pub type TraitObligations<'tcx> = Vec<TraitObligation<'tcx>>;
314 /// The following types:
322 /// * `InEnvironment`,
323 /// are used for representing the trait system in the form of
324 /// logic programming clauses. They are part of the interface
325 /// for the chalk SLG solver.
326 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable)]
327 pub enum WhereClause<'tcx> {
328 Implemented(ty::TraitPredicate<'tcx>),
329 ProjectionEq(ty::ProjectionPredicate<'tcx>),
330 RegionOutlives(ty::RegionOutlivesPredicate<'tcx>),
331 TypeOutlives(ty::TypeOutlivesPredicate<'tcx>),
334 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable)]
335 pub enum WellFormed<'tcx> {
336 Trait(ty::TraitPredicate<'tcx>),
340 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable)]
341 pub enum FromEnv<'tcx> {
342 Trait(ty::TraitPredicate<'tcx>),
346 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable)]
347 pub enum DomainGoal<'tcx> {
348 Holds(WhereClause<'tcx>),
349 WellFormed(WellFormed<'tcx>),
350 FromEnv(FromEnv<'tcx>),
351 Normalize(ty::ProjectionPredicate<'tcx>),
354 pub type PolyDomainGoal<'tcx> = ty::Binder<DomainGoal<'tcx>>;
356 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
357 pub enum QuantifierKind {
362 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
363 pub enum GoalKind<'tcx> {
364 Implies(Clauses<'tcx>, Goal<'tcx>),
365 And(Goal<'tcx>, Goal<'tcx>),
367 DomainGoal(DomainGoal<'tcx>),
368 Quantified(QuantifierKind, ty::Binder<Goal<'tcx>>),
369 Subtype(Ty<'tcx>, Ty<'tcx>),
373 pub type Goal<'tcx> = &'tcx GoalKind<'tcx>;
375 pub type Goals<'tcx> = &'tcx List<Goal<'tcx>>;
377 impl<'tcx> DomainGoal<'tcx> {
378 pub fn into_goal(self) -> GoalKind<'tcx> {
379 GoalKind::DomainGoal(self)
382 pub fn into_program_clause(self) -> ProgramClause<'tcx> {
385 hypotheses: ty::List::empty(),
386 category: ProgramClauseCategory::Other,
391 impl<'tcx> GoalKind<'tcx> {
392 pub fn from_poly_domain_goal(
393 domain_goal: PolyDomainGoal<'tcx>,
395 ) -> GoalKind<'tcx> {
396 match domain_goal.no_bound_vars() {
397 Some(p) => p.into_goal(),
398 None => GoalKind::Quantified(
399 QuantifierKind::Universal,
400 domain_goal.map_bound(|p| tcx.mk_goal(p.into_goal()))
406 /// This matches the definition from Page 7 of "A Proof Procedure for the Logic of Hereditary
407 /// Harrop Formulas".
408 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
409 pub enum Clause<'tcx> {
410 Implies(ProgramClause<'tcx>),
411 ForAll(ty::Binder<ProgramClause<'tcx>>),
415 pub fn category(self) -> ProgramClauseCategory {
417 Clause::Implies(clause) => clause.category,
418 Clause::ForAll(clause) => clause.skip_binder().category,
423 /// Multiple clauses.
424 pub type Clauses<'tcx> = &'tcx List<Clause<'tcx>>;
426 /// A "program clause" has the form `D :- G1, ..., Gn`. It is saying
427 /// that the domain goal `D` is true if `G1...Gn` are provable. This
428 /// is equivalent to the implication `G1..Gn => D`; we usually write
429 /// it with the reverse implication operator `:-` to emphasize the way
430 /// that programs are actually solved (via backchaining, which starts
431 /// with the goal to solve and proceeds from there).
432 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
433 pub struct ProgramClause<'tcx> {
434 /// This goal will be considered true ...
435 pub goal: DomainGoal<'tcx>,
437 /// ... if we can prove these hypotheses (there may be no hypotheses at all):
438 pub hypotheses: Goals<'tcx>,
440 /// Useful for filtering clauses.
441 pub category: ProgramClauseCategory,
444 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
445 pub enum ProgramClauseCategory {
451 /// A set of clauses that we assume to be true.
452 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
453 pub struct Environment<'tcx> {
454 pub clauses: Clauses<'tcx>,
457 impl Environment<'tcx> {
458 pub fn with<G>(self, goal: G) -> InEnvironment<'tcx, G> {
466 /// Something (usually a goal), along with an environment.
467 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
468 pub struct InEnvironment<'tcx, G> {
469 pub environment: Environment<'tcx>,
473 pub type Selection<'tcx> = Vtable<'tcx, PredicateObligation<'tcx>>;
475 #[derive(Clone,Debug)]
476 pub enum SelectionError<'tcx> {
478 OutputTypeParameterMismatch(ty::PolyTraitRef<'tcx>,
479 ty::PolyTraitRef<'tcx>,
480 ty::error::TypeError<'tcx>),
481 TraitNotObjectSafe(DefId),
482 ConstEvalFailure(ErrorHandled),
486 EnumTypeFoldableImpl! {
487 impl<'tcx> TypeFoldable<'tcx> for SelectionError<'tcx> {
488 (SelectionError::Unimplemented),
489 (SelectionError::OutputTypeParameterMismatch)(a, b, c),
490 (SelectionError::TraitNotObjectSafe)(a),
491 (SelectionError::ConstEvalFailure)(a),
492 (SelectionError::Overflow),
496 pub struct FulfillmentError<'tcx> {
497 pub obligation: PredicateObligation<'tcx>,
498 pub code: FulfillmentErrorCode<'tcx>,
499 /// Diagnostics only: we opportunistically change the `code.span` when we encounter an
500 /// obligation error caused by a call argument. When this is the case, we also signal that in
501 /// this field to ensure accuracy of suggestions.
502 pub points_at_arg_span: bool,
506 pub enum FulfillmentErrorCode<'tcx> {
507 CodeSelectionError(SelectionError<'tcx>),
508 CodeProjectionError(MismatchedProjectionTypes<'tcx>),
509 CodeSubtypeError(ExpectedFound<Ty<'tcx>>,
510 TypeError<'tcx>), // always comes from a SubtypePredicate
514 /// When performing resolution, it is typically the case that there
515 /// can be one of three outcomes:
517 /// - `Ok(Some(r))`: success occurred with result `r`
518 /// - `Ok(None)`: could not definitely determine anything, usually due
519 /// to inconclusive type inference.
520 /// - `Err(e)`: error `e` occurred
521 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
523 /// Given the successful resolution of an obligation, the `Vtable`
524 /// indicates where the vtable comes from. Note that while we call this
525 /// a "vtable", it does not necessarily indicate dynamic dispatch at
526 /// runtime. `Vtable` instances just tell the compiler where to find
527 /// methods, but in generic code those methods are typically statically
528 /// dispatched -- only when an object is constructed is a `Vtable`
529 /// instance reified into an actual vtable.
531 /// For example, the vtable may be tied to a specific impl (case A),
532 /// or it may be relative to some bound that is in scope (case B).
535 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
536 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
537 /// impl Clone for int { ... } // Impl_3
539 /// fn foo<T:Clone>(concrete: Option<Box<int>>,
541 /// mixed: Option<T>) {
543 /// // Case A: Vtable points at a specific impl. Only possible when
544 /// // type is concretely known. If the impl itself has bounded
545 /// // type parameters, Vtable will carry resolutions for those as well:
546 /// concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
548 /// // Case B: Vtable must be provided by caller. This applies when
549 /// // type is a type parameter.
550 /// param.clone(); // VtableParam
552 /// // Case C: A mix of cases A and B.
553 /// mixed.clone(); // Vtable(Impl_1, [VtableParam])
557 /// ### The type parameter `N`
559 /// See explanation on `VtableImplData`.
560 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
561 pub enum Vtable<'tcx, N> {
562 /// Vtable identifying a particular impl.
563 VtableImpl(VtableImplData<'tcx, N>),
565 /// Vtable for auto trait implementations.
566 /// This carries the information and nested obligations with regards
567 /// to an auto implementation for a trait `Trait`. The nested obligations
568 /// ensure the trait implementation holds for all the constituent types.
569 VtableAutoImpl(VtableAutoImplData<N>),
571 /// Successful resolution to an obligation provided by the caller
572 /// for some type parameter. The `Vec<N>` represents the
573 /// obligations incurred from normalizing the where-clause (if
577 /// Virtual calls through an object.
578 VtableObject(VtableObjectData<'tcx, N>),
580 /// Successful resolution for a builtin trait.
581 VtableBuiltin(VtableBuiltinData<N>),
583 /// Vtable automatically generated for a closure. The `DefId` is the ID
584 /// of the closure expression. This is a `VtableImpl` in spirit, but the
585 /// impl is generated by the compiler and does not appear in the source.
586 VtableClosure(VtableClosureData<'tcx, N>),
588 /// Same as above, but for a function pointer type with the given signature.
589 VtableFnPointer(VtableFnPointerData<'tcx, N>),
591 /// Vtable automatically generated for a generator.
592 VtableGenerator(VtableGeneratorData<'tcx, N>),
594 /// Vtable for a trait alias.
595 VtableTraitAlias(VtableTraitAliasData<'tcx, N>),
598 /// Identifies a particular impl in the source, along with a set of
599 /// substitutions from the impl's type/lifetime parameters. The
600 /// `nested` vector corresponds to the nested obligations attached to
601 /// the impl's type parameters.
603 /// The type parameter `N` indicates the type used for "nested
604 /// obligations" that are required by the impl. During type check, this
605 /// is `Obligation`, as one might expect. During codegen, however, this
606 /// is `()`, because codegen only requires a shallow resolution of an
607 /// impl, and nested obligations are satisfied later.
608 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
609 pub struct VtableImplData<'tcx, N> {
610 pub impl_def_id: DefId,
611 pub substs: SubstsRef<'tcx>,
615 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
616 pub struct VtableGeneratorData<'tcx, N> {
617 pub generator_def_id: DefId,
618 pub substs: SubstsRef<'tcx>,
619 /// Nested obligations. This can be non-empty if the generator
620 /// signature contains associated types.
624 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
625 pub struct VtableClosureData<'tcx, N> {
626 pub closure_def_id: DefId,
627 pub substs: SubstsRef<'tcx>,
628 /// Nested obligations. This can be non-empty if the closure
629 /// signature contains associated types.
633 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
634 pub struct VtableAutoImplData<N> {
635 pub trait_def_id: DefId,
639 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
640 pub struct VtableBuiltinData<N> {
644 /// A vtable for some object-safe trait `Foo` automatically derived
645 /// for the object type `Foo`.
646 #[derive(PartialEq, Eq, Clone, RustcEncodable, RustcDecodable, HashStable)]
647 pub struct VtableObjectData<'tcx, N> {
648 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
649 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
651 /// The vtable is formed by concatenating together the method lists of
652 /// the base object trait and all supertraits; this is the start of
653 /// `upcast_trait_ref`'s methods in that vtable.
654 pub vtable_base: usize,
659 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
660 pub struct VtableFnPointerData<'tcx, N> {
665 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
666 pub struct VtableTraitAliasData<'tcx, N> {
667 pub alias_def_id: DefId,
668 pub substs: SubstsRef<'tcx>,
672 /// Creates predicate obligations from the generic bounds.
673 pub fn predicates_for_generics<'tcx>(
674 cause: ObligationCause<'tcx>,
675 param_env: ty::ParamEnv<'tcx>,
676 generic_bounds: &ty::InstantiatedPredicates<'tcx>,
677 ) -> PredicateObligations<'tcx> {
678 util::predicates_for_generics(cause, 0, param_env, generic_bounds)
681 /// Determines whether the type `ty` is known to meet `bound` and
682 /// returns true if so. Returns false if `ty` either does not meet
683 /// `bound` or is not known to meet bound (note that this is
684 /// conservative towards *no impl*, which is the opposite of the
685 /// `evaluate` methods).
686 pub fn type_known_to_meet_bound_modulo_regions<'a, 'tcx>(
687 infcx: &InferCtxt<'a, 'tcx>,
688 param_env: ty::ParamEnv<'tcx>,
693 debug!("type_known_to_meet_bound_modulo_regions(ty={:?}, bound={:?})",
695 infcx.tcx.def_path_str(def_id));
697 let trait_ref = ty::TraitRef {
699 substs: infcx.tcx.mk_substs_trait(ty, &[]),
701 let obligation = Obligation {
703 cause: ObligationCause::misc(span, hir::DUMMY_HIR_ID),
705 predicate: trait_ref.to_predicate(),
708 let result = infcx.predicate_must_hold_modulo_regions(&obligation);
709 debug!("type_known_to_meet_ty={:?} bound={} => {:?}",
710 ty, infcx.tcx.def_path_str(def_id), result);
712 if result && (ty.has_infer_types() || ty.has_closure_types()) {
713 // Because of inference "guessing", selection can sometimes claim
714 // to succeed while the success requires a guess. To ensure
715 // this function's result remains infallible, we must confirm
716 // that guess. While imperfect, I believe this is sound.
718 // The handling of regions in this area of the code is terrible,
719 // see issue #29149. We should be able to improve on this with
721 let mut fulfill_cx = FulfillmentContext::new_ignoring_regions();
723 // We can use a dummy node-id here because we won't pay any mind
724 // to region obligations that arise (there shouldn't really be any
726 let cause = ObligationCause::misc(span, hir::DUMMY_HIR_ID);
728 fulfill_cx.register_bound(infcx, param_env, ty, def_id, cause);
730 // Note: we only assume something is `Copy` if we can
731 // *definitively* show that it implements `Copy`. Otherwise,
732 // assume it is move; linear is always ok.
733 match fulfill_cx.select_all_or_error(infcx) {
735 debug!("type_known_to_meet_bound_modulo_regions: ty={:?} bound={} success",
737 infcx.tcx.def_path_str(def_id));
741 debug!("type_known_to_meet_bound_modulo_regions: ty={:?} bound={} errors={:?}",
743 infcx.tcx.def_path_str(def_id),
753 fn do_normalize_predicates<'tcx>(
755 region_context: DefId,
756 cause: ObligationCause<'tcx>,
757 elaborated_env: ty::ParamEnv<'tcx>,
758 predicates: Vec<ty::Predicate<'tcx>>,
759 ) -> Result<Vec<ty::Predicate<'tcx>>, ErrorReported> {
761 "do_normalize_predicates(predicates={:?}, region_context={:?}, cause={:?})",
766 let span = cause.span;
767 tcx.infer_ctxt().enter(|infcx| {
768 // FIXME. We should really... do something with these region
769 // obligations. But this call just continues the older
770 // behavior (i.e., doesn't cause any new bugs), and it would
771 // take some further refactoring to actually solve them. In
772 // particular, we would have to handle implied bounds
773 // properly, and that code is currently largely confined to
774 // regionck (though I made some efforts to extract it
777 // @arielby: In any case, these obligations are checked
778 // by wfcheck anyway, so I'm not sure we have to check
779 // them here too, and we will remove this function when
780 // we move over to lazy normalization *anyway*.
781 let fulfill_cx = FulfillmentContext::new_ignoring_regions();
782 let predicates = match fully_normalize(
789 Ok(predicates) => predicates,
791 infcx.report_fulfillment_errors(&errors, None, false);
792 return Err(ErrorReported)
796 debug!("do_normalize_predictes: normalized predicates = {:?}", predicates);
798 let region_scope_tree = region::ScopeTree::default();
800 // We can use the `elaborated_env` here; the region code only
801 // cares about declarations like `'a: 'b`.
802 let outlives_env = OutlivesEnvironment::new(elaborated_env);
804 infcx.resolve_regions_and_report_errors(
808 SuppressRegionErrors::default(),
811 let predicates = match infcx.fully_resolve(&predicates) {
812 Ok(predicates) => predicates,
814 // If we encounter a fixup error, it means that some type
815 // variable wound up unconstrained. I actually don't know
816 // if this can happen, and I certainly don't expect it to
817 // happen often, but if it did happen it probably
818 // represents a legitimate failure due to some kind of
819 // unconstrained variable, and it seems better not to ICE,
820 // all things considered.
821 tcx.sess.span_err(span, &fixup_err.to_string());
822 return Err(ErrorReported)
825 if predicates.has_local_value() {
826 // FIXME: shouldn't we, you know, actually report an error here? or an ICE?
834 // FIXME: this is gonna need to be removed ...
835 /// Normalizes the parameter environment, reporting errors if they occur.
836 pub fn normalize_param_env_or_error<'tcx>(
838 region_context: DefId,
839 unnormalized_env: ty::ParamEnv<'tcx>,
840 cause: ObligationCause<'tcx>,
841 ) -> ty::ParamEnv<'tcx> {
842 // I'm not wild about reporting errors here; I'd prefer to
843 // have the errors get reported at a defined place (e.g.,
844 // during typeck). Instead I have all parameter
845 // environments, in effect, going through this function
846 // and hence potentially reporting errors. This ensures of
847 // course that we never forget to normalize (the
848 // alternative seemed like it would involve a lot of
849 // manual invocations of this fn -- and then we'd have to
850 // deal with the errors at each of those sites).
852 // In any case, in practice, typeck constructs all the
853 // parameter environments once for every fn as it goes,
854 // and errors will get reported then; so after typeck we
855 // can be sure that no errors should occur.
857 debug!("normalize_param_env_or_error(region_context={:?}, unnormalized_env={:?}, cause={:?})",
858 region_context, unnormalized_env, cause);
860 let mut predicates: Vec<_> =
861 util::elaborate_predicates(tcx, unnormalized_env.caller_bounds.to_vec())
864 debug!("normalize_param_env_or_error: elaborated-predicates={:?}",
867 let elaborated_env = ty::ParamEnv::new(
868 tcx.intern_predicates(&predicates),
869 unnormalized_env.reveal,
870 unnormalized_env.def_id
873 // HACK: we are trying to normalize the param-env inside *itself*. The problem is that
874 // normalization expects its param-env to be already normalized, which means we have
877 // The way we handle this is by normalizing the param-env inside an unnormalized version
878 // of the param-env, which means that if the param-env contains unnormalized projections,
879 // we'll have some normalization failures. This is unfortunate.
881 // Lazy normalization would basically handle this by treating just the
882 // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
884 // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
885 // types, so to make the situation less bad, we normalize all the predicates *but*
886 // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
887 // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
889 // This works fairly well because trait matching does not actually care about param-env
890 // TypeOutlives predicates - these are normally used by regionck.
891 let outlives_predicates: Vec<_> = predicates.drain_filter(|predicate| {
893 ty::Predicate::TypeOutlives(..) => true,
898 debug!("normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
899 predicates, outlives_predicates);
900 let non_outlives_predicates =
901 match do_normalize_predicates(tcx, region_context, cause.clone(),
902 elaborated_env, predicates) {
903 Ok(predicates) => predicates,
904 // An unnormalized env is better than nothing.
905 Err(ErrorReported) => {
906 debug!("normalize_param_env_or_error: errored resolving non-outlives predicates");
907 return elaborated_env
911 debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates);
913 // Not sure whether it is better to include the unnormalized TypeOutlives predicates
914 // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
915 // predicates here anyway. Keeping them here anyway because it seems safer.
916 let outlives_env: Vec<_> =
917 non_outlives_predicates.iter().chain(&outlives_predicates).cloned().collect();
918 let outlives_env = ty::ParamEnv::new(
919 tcx.intern_predicates(&outlives_env),
920 unnormalized_env.reveal,
923 let outlives_predicates =
924 match do_normalize_predicates(tcx, region_context, cause,
925 outlives_env, outlives_predicates) {
926 Ok(predicates) => predicates,
927 // An unnormalized env is better than nothing.
928 Err(ErrorReported) => {
929 debug!("normalize_param_env_or_error: errored resolving outlives predicates");
930 return elaborated_env
933 debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates);
935 let mut predicates = non_outlives_predicates;
936 predicates.extend(outlives_predicates);
937 debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
939 tcx.intern_predicates(&predicates),
940 unnormalized_env.reveal,
941 unnormalized_env.def_id
945 pub fn fully_normalize<'a, 'tcx, T>(
946 infcx: &InferCtxt<'a, 'tcx>,
947 mut fulfill_cx: FulfillmentContext<'tcx>,
948 cause: ObligationCause<'tcx>,
949 param_env: ty::ParamEnv<'tcx>,
951 ) -> Result<T, Vec<FulfillmentError<'tcx>>>
953 T: TypeFoldable<'tcx>,
955 debug!("fully_normalize_with_fulfillcx(value={:?})", value);
956 let selcx = &mut SelectionContext::new(infcx);
957 let Normalized { value: normalized_value, obligations } =
958 project::normalize(selcx, param_env, cause, value);
959 debug!("fully_normalize: normalized_value={:?} obligations={:?}",
962 for obligation in obligations {
963 fulfill_cx.register_predicate_obligation(selcx.infcx(), obligation);
966 debug!("fully_normalize: select_all_or_error start");
967 fulfill_cx.select_all_or_error(infcx)?;
968 debug!("fully_normalize: select_all_or_error complete");
969 let resolved_value = infcx.resolve_vars_if_possible(&normalized_value);
970 debug!("fully_normalize: resolved_value={:?}", resolved_value);
974 /// Normalizes the predicates and checks whether they hold in an empty
975 /// environment. If this returns false, then either normalize
976 /// encountered an error or one of the predicates did not hold. Used
977 /// when creating vtables to check for unsatisfiable methods.
978 fn normalize_and_test_predicates<'tcx>(
980 predicates: Vec<ty::Predicate<'tcx>>,
982 debug!("normalize_and_test_predicates(predicates={:?})",
985 let result = tcx.infer_ctxt().enter(|infcx| {
986 let param_env = ty::ParamEnv::reveal_all();
987 let mut selcx = SelectionContext::new(&infcx);
988 let mut fulfill_cx = FulfillmentContext::new();
989 let cause = ObligationCause::dummy();
990 let Normalized { value: predicates, obligations } =
991 normalize(&mut selcx, param_env, cause.clone(), &predicates);
992 for obligation in obligations {
993 fulfill_cx.register_predicate_obligation(&infcx, obligation);
995 for predicate in predicates {
996 let obligation = Obligation::new(cause.clone(), param_env, predicate);
997 fulfill_cx.register_predicate_obligation(&infcx, obligation);
1000 fulfill_cx.select_all_or_error(&infcx).is_ok()
1002 debug!("normalize_and_test_predicates(predicates={:?}) = {:?}",
1003 predicates, result);
1007 fn substitute_normalize_and_test_predicates<'tcx>(
1009 key: (DefId, SubstsRef<'tcx>),
1011 debug!("substitute_normalize_and_test_predicates(key={:?})",
1014 let predicates = tcx.predicates_of(key.0).instantiate(tcx, key.1).predicates;
1015 let result = normalize_and_test_predicates(tcx, predicates);
1017 debug!("substitute_normalize_and_test_predicates(key={:?}) = {:?}",
1022 /// Given a trait `trait_ref`, iterates the vtable entries
1023 /// that come from `trait_ref`, including its supertraits.
1024 #[inline] // FIXME(#35870): avoid closures being unexported due to `impl Trait`.
1025 fn vtable_methods<'tcx>(
1027 trait_ref: ty::PolyTraitRef<'tcx>,
1028 ) -> &'tcx [Option<(DefId, SubstsRef<'tcx>)>] {
1029 debug!("vtable_methods({:?})", trait_ref);
1031 tcx.arena.alloc_from_iter(
1032 supertraits(tcx, trait_ref).flat_map(move |trait_ref| {
1033 let trait_methods = tcx.associated_items(trait_ref.def_id())
1034 .filter(|item| item.kind == ty::AssocKind::Method);
1036 // Now list each method's DefId and InternalSubsts (for within its trait).
1037 // If the method can never be called from this object, produce None.
1038 trait_methods.map(move |trait_method| {
1039 debug!("vtable_methods: trait_method={:?}", trait_method);
1040 let def_id = trait_method.def_id;
1042 // Some methods cannot be called on an object; skip those.
1043 if !tcx.is_vtable_safe_method(trait_ref.def_id(), &trait_method) {
1044 debug!("vtable_methods: not vtable safe");
1048 // the method may have some early-bound lifetimes, add
1049 // regions for those
1050 let substs = trait_ref.map_bound(|trait_ref|
1051 InternalSubsts::for_item(tcx, def_id, |param, _|
1053 GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(),
1054 GenericParamDefKind::Type { .. } |
1055 GenericParamDefKind::Const => {
1056 trait_ref.substs[param.index as usize]
1062 // the trait type may have higher-ranked lifetimes in it;
1063 // so erase them if they appear, so that we get the type
1064 // at some particular call site
1065 let substs = tcx.normalize_erasing_late_bound_regions(
1066 ty::ParamEnv::reveal_all(),
1070 // It's possible that the method relies on where clauses that
1071 // do not hold for this particular set of type parameters.
1072 // Note that this method could then never be called, so we
1073 // do not want to try and codegen it, in that case (see #23435).
1074 let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs);
1075 if !normalize_and_test_predicates(tcx, predicates.predicates) {
1076 debug!("vtable_methods: predicates do not hold");
1080 Some((def_id, substs))
1086 impl<'tcx, O> Obligation<'tcx, O> {
1087 pub fn new(cause: ObligationCause<'tcx>,
1088 param_env: ty::ParamEnv<'tcx>,
1090 -> Obligation<'tcx, O>
1092 Obligation { cause, param_env, recursion_depth: 0, predicate }
1095 fn with_depth(cause: ObligationCause<'tcx>,
1096 recursion_depth: usize,
1097 param_env: ty::ParamEnv<'tcx>,
1099 -> Obligation<'tcx, O>
1101 Obligation { cause, param_env, recursion_depth, predicate }
1104 pub fn misc(span: Span,
1105 body_id: hir::HirId,
1106 param_env: ty::ParamEnv<'tcx>,
1108 -> Obligation<'tcx, O> {
1109 Obligation::new(ObligationCause::misc(span, body_id), param_env, trait_ref)
1112 pub fn with<P>(&self, value: P) -> Obligation<'tcx,P> {
1113 Obligation { cause: self.cause.clone(),
1114 param_env: self.param_env,
1115 recursion_depth: self.recursion_depth,
1120 impl<'tcx> ObligationCause<'tcx> {
1122 pub fn new(span: Span,
1123 body_id: hir::HirId,
1124 code: ObligationCauseCode<'tcx>)
1125 -> ObligationCause<'tcx> {
1126 ObligationCause { span, body_id, code }
1129 pub fn misc(span: Span, body_id: hir::HirId) -> ObligationCause<'tcx> {
1130 ObligationCause { span, body_id, code: MiscObligation }
1133 pub fn dummy() -> ObligationCause<'tcx> {
1134 ObligationCause { span: DUMMY_SP, body_id: hir::CRATE_HIR_ID, code: MiscObligation }
1138 impl<'tcx, N> Vtable<'tcx, N> {
1139 pub fn nested_obligations(self) -> Vec<N> {
1141 VtableImpl(i) => i.nested,
1142 VtableParam(n) => n,
1143 VtableBuiltin(i) => i.nested,
1144 VtableAutoImpl(d) => d.nested,
1145 VtableClosure(c) => c.nested,
1146 VtableGenerator(c) => c.nested,
1147 VtableObject(d) => d.nested,
1148 VtableFnPointer(d) => d.nested,
1149 VtableTraitAlias(d) => d.nested,
1153 pub fn map<M, F>(self, f: F) -> Vtable<'tcx, M> where F: FnMut(N) -> M {
1155 VtableImpl(i) => VtableImpl(VtableImplData {
1156 impl_def_id: i.impl_def_id,
1158 nested: i.nested.into_iter().map(f).collect(),
1160 VtableParam(n) => VtableParam(n.into_iter().map(f).collect()),
1161 VtableBuiltin(i) => VtableBuiltin(VtableBuiltinData {
1162 nested: i.nested.into_iter().map(f).collect(),
1164 VtableObject(o) => VtableObject(VtableObjectData {
1165 upcast_trait_ref: o.upcast_trait_ref,
1166 vtable_base: o.vtable_base,
1167 nested: o.nested.into_iter().map(f).collect(),
1169 VtableAutoImpl(d) => VtableAutoImpl(VtableAutoImplData {
1170 trait_def_id: d.trait_def_id,
1171 nested: d.nested.into_iter().map(f).collect(),
1173 VtableClosure(c) => VtableClosure(VtableClosureData {
1174 closure_def_id: c.closure_def_id,
1176 nested: c.nested.into_iter().map(f).collect(),
1178 VtableGenerator(c) => VtableGenerator(VtableGeneratorData {
1179 generator_def_id: c.generator_def_id,
1181 nested: c.nested.into_iter().map(f).collect(),
1183 VtableFnPointer(p) => VtableFnPointer(VtableFnPointerData {
1185 nested: p.nested.into_iter().map(f).collect(),
1187 VtableTraitAlias(d) => VtableTraitAlias(VtableTraitAliasData {
1188 alias_def_id: d.alias_def_id,
1190 nested: d.nested.into_iter().map(f).collect(),
1196 impl<'tcx> FulfillmentError<'tcx> {
1197 fn new(obligation: PredicateObligation<'tcx>,
1198 code: FulfillmentErrorCode<'tcx>)
1199 -> FulfillmentError<'tcx>
1201 FulfillmentError { obligation: obligation, code: code, points_at_arg_span: false }
1205 impl<'tcx> TraitObligation<'tcx> {
1206 fn self_ty(&self) -> ty::Binder<Ty<'tcx>> {
1207 self.predicate.map_bound(|p| p.self_ty())
1211 pub fn provide(providers: &mut ty::query::Providers<'_>) {
1212 *providers = ty::query::Providers {
1213 is_object_safe: object_safety::is_object_safe_provider,
1214 specialization_graph_of: specialize::specialization_graph_provider,
1215 specializes: specialize::specializes,
1216 codegen_fulfill_obligation: codegen::codegen_fulfill_obligation,
1218 substitute_normalize_and_test_predicates,
1223 pub trait ExClauseFold<'tcx>
1225 Self: chalk_engine::context::Context + Clone,
1227 fn fold_ex_clause_with<F: TypeFolder<'tcx>>(
1228 ex_clause: &chalk_engine::ExClause<Self>,
1230 ) -> chalk_engine::ExClause<Self>;
1232 fn visit_ex_clause_with<V: TypeVisitor<'tcx>>(
1233 ex_clause: &chalk_engine::ExClause<Self>,
1238 pub trait ChalkContextLift<'tcx>
1240 Self: chalk_engine::context::Context + Clone,
1242 type LiftedExClause: Debug + 'tcx;
1243 type LiftedDelayedLiteral: Debug + 'tcx;
1244 type LiftedLiteral: Debug + 'tcx;
1246 fn lift_ex_clause_to_tcx(
1247 ex_clause: &chalk_engine::ExClause<Self>,
1249 ) -> Option<Self::LiftedExClause>;
1251 fn lift_delayed_literal_to_tcx(
1252 ex_clause: &chalk_engine::DelayedLiteral<Self>,
1254 ) -> Option<Self::LiftedDelayedLiteral>;
1256 fn lift_literal_to_tcx(
1257 ex_clause: &chalk_engine::Literal<Self>,
1259 ) -> Option<Self::LiftedLiteral>;