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]` implies that `T` must be `Copy`.
210 /// If `true`, suggest `const_in_array_repeat_expressions` feature flag.
213 /// Types of fields (other than the last, except for packed structs) in a struct must be sized.
214 FieldSized { adt_kind: AdtKind, last: bool },
216 /// Constant expressions must be sized.
219 /// `static` items must have `Sync` type.
222 BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
224 ImplDerivedObligation(DerivedObligationCause<'tcx>),
226 /// Error derived when matching traits/impls; see ObligationCause for more details
227 CompareImplMethodObligation {
228 item_name: ast::Name,
229 impl_item_def_id: DefId,
230 trait_item_def_id: DefId,
233 /// Checking that this expression can be assigned where it needs to be
234 // FIXME(eddyb) #11161 is the original Expr required?
237 /// Computing common supertype in the arms of a match expression
238 MatchExpressionArm(Box<MatchExpressionArmCause<'tcx>>),
240 /// Computing common supertype in the pattern guard for the arms of a match expression
241 MatchExpressionArmPattern { span: Span, ty: Ty<'tcx> },
243 /// Constants in patterns must have `Structural` type.
244 ConstPatternStructural,
246 /// Computing common supertype in an if expression
247 IfExpression(Box<IfExpressionCause>),
249 /// Computing common supertype of an if expression with no else counter-part
250 IfExpressionWithNoElse,
252 /// `main` has wrong type
255 /// `start` has wrong type
258 /// Intrinsic has wrong type
264 /// `return` with no expression
267 /// `return` with an expression
268 ReturnValue(hir::HirId),
270 /// Return type of this function
273 /// Block implicit return
274 BlockTailExpression(hir::HirId),
276 /// #[feature(trivial_bounds)] is not enabled
279 AssocTypeBound(Box<AssocTypeBoundData>),
282 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
283 pub struct AssocTypeBoundData {
284 pub impl_span: Option<Span>,
286 pub bounds: Vec<Span>,
289 // `ObligationCauseCode` is used a lot. Make sure it doesn't unintentionally get bigger.
290 #[cfg(target_arch = "x86_64")]
291 static_assert_size!(ObligationCauseCode<'_>, 32);
293 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
294 pub struct MatchExpressionArmCause<'tcx> {
296 pub source: hir::MatchSource,
297 pub prior_arms: Vec<Span>,
298 pub last_ty: Ty<'tcx>,
299 pub discrim_hir_id: hir::HirId,
302 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
303 pub struct IfExpressionCause {
305 pub outer: Option<Span>,
306 pub semicolon: Option<Span>,
309 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
310 pub struct DerivedObligationCause<'tcx> {
311 /// The trait reference of the parent obligation that led to the
312 /// current obligation. Note that only trait obligations lead to
313 /// derived obligations, so we just store the trait reference here
315 parent_trait_ref: ty::PolyTraitRef<'tcx>,
317 /// The parent trait had this cause.
318 parent_code: Rc<ObligationCauseCode<'tcx>>
321 pub type Obligations<'tcx, O> = Vec<Obligation<'tcx, O>>;
322 pub type PredicateObligations<'tcx> = Vec<PredicateObligation<'tcx>>;
323 pub type TraitObligations<'tcx> = Vec<TraitObligation<'tcx>>;
325 /// The following types:
333 /// * `InEnvironment`,
334 /// are used for representing the trait system in the form of
335 /// logic programming clauses. They are part of the interface
336 /// for the chalk SLG solver.
337 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
338 pub enum WhereClause<'tcx> {
339 Implemented(ty::TraitPredicate<'tcx>),
340 ProjectionEq(ty::ProjectionPredicate<'tcx>),
341 RegionOutlives(ty::RegionOutlivesPredicate<'tcx>),
342 TypeOutlives(ty::TypeOutlivesPredicate<'tcx>),
345 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
346 pub enum WellFormed<'tcx> {
347 Trait(ty::TraitPredicate<'tcx>),
351 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
352 pub enum FromEnv<'tcx> {
353 Trait(ty::TraitPredicate<'tcx>),
357 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
358 pub enum DomainGoal<'tcx> {
359 Holds(WhereClause<'tcx>),
360 WellFormed(WellFormed<'tcx>),
361 FromEnv(FromEnv<'tcx>),
362 Normalize(ty::ProjectionPredicate<'tcx>),
365 pub type PolyDomainGoal<'tcx> = ty::Binder<DomainGoal<'tcx>>;
367 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
368 pub enum QuantifierKind {
373 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
374 pub enum GoalKind<'tcx> {
375 Implies(Clauses<'tcx>, Goal<'tcx>),
376 And(Goal<'tcx>, Goal<'tcx>),
378 DomainGoal(DomainGoal<'tcx>),
379 Quantified(QuantifierKind, ty::Binder<Goal<'tcx>>),
380 Subtype(Ty<'tcx>, Ty<'tcx>),
384 pub type Goal<'tcx> = &'tcx GoalKind<'tcx>;
386 pub type Goals<'tcx> = &'tcx List<Goal<'tcx>>;
388 impl<'tcx> DomainGoal<'tcx> {
389 pub fn into_goal(self) -> GoalKind<'tcx> {
390 GoalKind::DomainGoal(self)
393 pub fn into_program_clause(self) -> ProgramClause<'tcx> {
396 hypotheses: ty::List::empty(),
397 category: ProgramClauseCategory::Other,
402 impl<'tcx> GoalKind<'tcx> {
403 pub fn from_poly_domain_goal(
404 domain_goal: PolyDomainGoal<'tcx>,
406 ) -> GoalKind<'tcx> {
407 match domain_goal.no_bound_vars() {
408 Some(p) => p.into_goal(),
409 None => GoalKind::Quantified(
410 QuantifierKind::Universal,
411 domain_goal.map_bound(|p| tcx.mk_goal(p.into_goal()))
417 /// This matches the definition from Page 7 of "A Proof Procedure for the Logic of Hereditary
418 /// Harrop Formulas".
419 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
420 pub enum Clause<'tcx> {
421 Implies(ProgramClause<'tcx>),
422 ForAll(ty::Binder<ProgramClause<'tcx>>),
426 pub fn category(self) -> ProgramClauseCategory {
428 Clause::Implies(clause) => clause.category,
429 Clause::ForAll(clause) => clause.skip_binder().category,
434 /// Multiple clauses.
435 pub type Clauses<'tcx> = &'tcx List<Clause<'tcx>>;
437 /// A "program clause" has the form `D :- G1, ..., Gn`. It is saying
438 /// that the domain goal `D` is true if `G1...Gn` are provable. This
439 /// is equivalent to the implication `G1..Gn => D`; we usually write
440 /// it with the reverse implication operator `:-` to emphasize the way
441 /// that programs are actually solved (via backchaining, which starts
442 /// with the goal to solve and proceeds from there).
443 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
444 pub struct ProgramClause<'tcx> {
445 /// This goal will be considered true ...
446 pub goal: DomainGoal<'tcx>,
448 /// ... if we can prove these hypotheses (there may be no hypotheses at all):
449 pub hypotheses: Goals<'tcx>,
451 /// Useful for filtering clauses.
452 pub category: ProgramClauseCategory,
455 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
456 pub enum ProgramClauseCategory {
462 /// A set of clauses that we assume to be true.
463 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
464 pub struct Environment<'tcx> {
465 pub clauses: Clauses<'tcx>,
468 impl Environment<'tcx> {
469 pub fn with<G>(self, goal: G) -> InEnvironment<'tcx, G> {
477 /// Something (usually a goal), along with an environment.
478 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
479 pub struct InEnvironment<'tcx, G> {
480 pub environment: Environment<'tcx>,
484 pub type Selection<'tcx> = Vtable<'tcx, PredicateObligation<'tcx>>;
486 #[derive(Clone,Debug,TypeFoldable)]
487 pub enum SelectionError<'tcx> {
489 OutputTypeParameterMismatch(ty::PolyTraitRef<'tcx>,
490 ty::PolyTraitRef<'tcx>,
491 ty::error::TypeError<'tcx>),
492 TraitNotObjectSafe(DefId),
493 ConstEvalFailure(ErrorHandled),
497 pub struct FulfillmentError<'tcx> {
498 pub obligation: PredicateObligation<'tcx>,
499 pub code: FulfillmentErrorCode<'tcx>,
500 /// Diagnostics only: we opportunistically change the `code.span` when we encounter an
501 /// obligation error caused by a call argument. When this is the case, we also signal that in
502 /// this field to ensure accuracy of suggestions.
503 pub points_at_arg_span: bool,
507 pub enum FulfillmentErrorCode<'tcx> {
508 CodeSelectionError(SelectionError<'tcx>),
509 CodeProjectionError(MismatchedProjectionTypes<'tcx>),
510 CodeSubtypeError(ExpectedFound<Ty<'tcx>>,
511 TypeError<'tcx>), // always comes from a SubtypePredicate
515 /// When performing resolution, it is typically the case that there
516 /// can be one of three outcomes:
518 /// - `Ok(Some(r))`: success occurred with result `r`
519 /// - `Ok(None)`: could not definitely determine anything, usually due
520 /// to inconclusive type inference.
521 /// - `Err(e)`: error `e` occurred
522 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
524 /// Given the successful resolution of an obligation, the `Vtable`
525 /// indicates where the vtable comes from. Note that while we call this
526 /// a "vtable", it does not necessarily indicate dynamic dispatch at
527 /// runtime. `Vtable` instances just tell the compiler where to find
528 /// methods, but in generic code those methods are typically statically
529 /// dispatched -- only when an object is constructed is a `Vtable`
530 /// instance reified into an actual vtable.
532 /// For example, the vtable may be tied to a specific impl (case A),
533 /// or it may be relative to some bound that is in scope (case B).
536 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
537 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
538 /// impl Clone for int { ... } // Impl_3
540 /// fn foo<T:Clone>(concrete: Option<Box<int>>,
542 /// mixed: Option<T>) {
544 /// // Case A: Vtable points at a specific impl. Only possible when
545 /// // type is concretely known. If the impl itself has bounded
546 /// // type parameters, Vtable will carry resolutions for those as well:
547 /// concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
549 /// // Case B: Vtable must be provided by caller. This applies when
550 /// // type is a type parameter.
551 /// param.clone(); // VtableParam
553 /// // Case C: A mix of cases A and B.
554 /// mixed.clone(); // Vtable(Impl_1, [VtableParam])
558 /// ### The type parameter `N`
560 /// See explanation on `VtableImplData`.
561 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
562 pub enum Vtable<'tcx, N> {
563 /// Vtable identifying a particular impl.
564 VtableImpl(VtableImplData<'tcx, N>),
566 /// Vtable for auto trait implementations.
567 /// This carries the information and nested obligations with regards
568 /// to an auto implementation for a trait `Trait`. The nested obligations
569 /// ensure the trait implementation holds for all the constituent types.
570 VtableAutoImpl(VtableAutoImplData<N>),
572 /// Successful resolution to an obligation provided by the caller
573 /// for some type parameter. The `Vec<N>` represents the
574 /// obligations incurred from normalizing the where-clause (if
578 /// Virtual calls through an object.
579 VtableObject(VtableObjectData<'tcx, N>),
581 /// Successful resolution for a builtin trait.
582 VtableBuiltin(VtableBuiltinData<N>),
584 /// Vtable automatically generated for a closure. The `DefId` is the ID
585 /// of the closure expression. This is a `VtableImpl` in spirit, but the
586 /// impl is generated by the compiler and does not appear in the source.
587 VtableClosure(VtableClosureData<'tcx, N>),
589 /// Same as above, but for a function pointer type with the given signature.
590 VtableFnPointer(VtableFnPointerData<'tcx, N>),
592 /// Vtable automatically generated for a generator.
593 VtableGenerator(VtableGeneratorData<'tcx, N>),
595 /// Vtable for a trait alias.
596 VtableTraitAlias(VtableTraitAliasData<'tcx, N>),
599 /// Identifies a particular impl in the source, along with a set of
600 /// substitutions from the impl's type/lifetime parameters. The
601 /// `nested` vector corresponds to the nested obligations attached to
602 /// the impl's type parameters.
604 /// The type parameter `N` indicates the type used for "nested
605 /// obligations" that are required by the impl. During type-check, this
606 /// is `Obligation`, as one might expect. During codegen, however, this
607 /// is `()`, because codegen only requires a shallow resolution of an
608 /// impl, and nested obligations are satisfied later.
609 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
610 pub struct VtableImplData<'tcx, N> {
611 pub impl_def_id: DefId,
612 pub substs: SubstsRef<'tcx>,
616 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
617 pub struct VtableGeneratorData<'tcx, N> {
618 pub generator_def_id: DefId,
619 pub substs: SubstsRef<'tcx>,
620 /// Nested obligations. This can be non-empty if the generator
621 /// signature contains associated types.
625 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
626 pub struct VtableClosureData<'tcx, N> {
627 pub closure_def_id: DefId,
628 pub substs: SubstsRef<'tcx>,
629 /// Nested obligations. This can be non-empty if the closure
630 /// signature contains associated types.
634 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
635 pub struct VtableAutoImplData<N> {
636 pub trait_def_id: DefId,
640 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
641 pub struct VtableBuiltinData<N> {
645 /// A vtable for some object-safe trait `Foo` automatically derived
646 /// for the object type `Foo`.
647 #[derive(PartialEq, Eq, Clone, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
648 pub struct VtableObjectData<'tcx, N> {
649 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
650 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
652 /// The vtable is formed by concatenating together the method lists of
653 /// the base object trait and all supertraits; this is the start of
654 /// `upcast_trait_ref`'s methods in that vtable.
655 pub vtable_base: usize,
660 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
661 pub struct VtableFnPointerData<'tcx, N> {
666 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
667 pub struct VtableTraitAliasData<'tcx, N> {
668 pub alias_def_id: DefId,
669 pub substs: SubstsRef<'tcx>,
673 /// Creates predicate obligations from the generic bounds.
674 pub fn predicates_for_generics<'tcx>(
675 cause: ObligationCause<'tcx>,
676 param_env: ty::ParamEnv<'tcx>,
677 generic_bounds: &ty::InstantiatedPredicates<'tcx>,
678 ) -> PredicateObligations<'tcx> {
679 util::predicates_for_generics(cause, 0, param_env, generic_bounds)
682 /// Determines whether the type `ty` is known to meet `bound` and
683 /// returns true if so. Returns false if `ty` either does not meet
684 /// `bound` or is not known to meet bound (note that this is
685 /// conservative towards *no impl*, which is the opposite of the
686 /// `evaluate` methods).
687 pub fn type_known_to_meet_bound_modulo_regions<'a, 'tcx>(
688 infcx: &InferCtxt<'a, 'tcx>,
689 param_env: ty::ParamEnv<'tcx>,
694 debug!("type_known_to_meet_bound_modulo_regions(ty={:?}, bound={:?})",
696 infcx.tcx.def_path_str(def_id));
698 let trait_ref = ty::TraitRef {
700 substs: infcx.tcx.mk_substs_trait(ty, &[]),
702 let obligation = Obligation {
704 cause: ObligationCause::misc(span, hir::DUMMY_HIR_ID),
706 predicate: trait_ref.to_predicate(),
709 let result = infcx.predicate_must_hold_modulo_regions(&obligation);
710 debug!("type_known_to_meet_ty={:?} bound={} => {:?}",
711 ty, infcx.tcx.def_path_str(def_id), result);
713 if result && (ty.has_infer_types() || ty.has_closure_types()) {
714 // Because of inference "guessing", selection can sometimes claim
715 // to succeed while the success requires a guess. To ensure
716 // this function's result remains infallible, we must confirm
717 // that guess. While imperfect, I believe this is sound.
719 // The handling of regions in this area of the code is terrible,
720 // see issue #29149. We should be able to improve on this with
722 let mut fulfill_cx = FulfillmentContext::new_ignoring_regions();
724 // We can use a dummy node-id here because we won't pay any mind
725 // to region obligations that arise (there shouldn't really be any
727 let cause = ObligationCause::misc(span, hir::DUMMY_HIR_ID);
729 fulfill_cx.register_bound(infcx, param_env, ty, def_id, cause);
731 // Note: we only assume something is `Copy` if we can
732 // *definitively* show that it implements `Copy`. Otherwise,
733 // assume it is move; linear is always ok.
734 match fulfill_cx.select_all_or_error(infcx) {
736 debug!("type_known_to_meet_bound_modulo_regions: ty={:?} bound={} success",
738 infcx.tcx.def_path_str(def_id));
742 debug!("type_known_to_meet_bound_modulo_regions: ty={:?} bound={} errors={:?}",
744 infcx.tcx.def_path_str(def_id),
754 fn do_normalize_predicates<'tcx>(
756 region_context: DefId,
757 cause: ObligationCause<'tcx>,
758 elaborated_env: ty::ParamEnv<'tcx>,
759 predicates: Vec<ty::Predicate<'tcx>>,
760 ) -> Result<Vec<ty::Predicate<'tcx>>, ErrorReported> {
762 "do_normalize_predicates(predicates={:?}, region_context={:?}, cause={:?})",
767 let span = cause.span;
768 tcx.infer_ctxt().enter(|infcx| {
769 // FIXME. We should really... do something with these region
770 // obligations. But this call just continues the older
771 // behavior (i.e., doesn't cause any new bugs), and it would
772 // take some further refactoring to actually solve them. In
773 // particular, we would have to handle implied bounds
774 // properly, and that code is currently largely confined to
775 // regionck (though I made some efforts to extract it
778 // @arielby: In any case, these obligations are checked
779 // by wfcheck anyway, so I'm not sure we have to check
780 // them here too, and we will remove this function when
781 // we move over to lazy normalization *anyway*.
782 let fulfill_cx = FulfillmentContext::new_ignoring_regions();
783 let predicates = match fully_normalize(
790 Ok(predicates) => predicates,
792 infcx.report_fulfillment_errors(&errors, None, false);
793 return Err(ErrorReported)
797 debug!("do_normalize_predictes: normalized predicates = {:?}", predicates);
799 let region_scope_tree = region::ScopeTree::default();
801 // We can use the `elaborated_env` here; the region code only
802 // cares about declarations like `'a: 'b`.
803 let outlives_env = OutlivesEnvironment::new(elaborated_env);
805 infcx.resolve_regions_and_report_errors(
809 SuppressRegionErrors::default(),
812 let predicates = match infcx.fully_resolve(&predicates) {
813 Ok(predicates) => predicates,
815 // If we encounter a fixup error, it means that some type
816 // variable wound up unconstrained. I actually don't know
817 // if this can happen, and I certainly don't expect it to
818 // happen often, but if it did happen it probably
819 // represents a legitimate failure due to some kind of
820 // unconstrained variable, and it seems better not to ICE,
821 // all things considered.
822 tcx.sess.span_err(span, &fixup_err.to_string());
823 return Err(ErrorReported)
826 if predicates.has_local_value() {
827 // FIXME: shouldn't we, you know, actually report an error here? or an ICE?
835 // FIXME: this is gonna need to be removed ...
836 /// Normalizes the parameter environment, reporting errors if they occur.
837 pub fn normalize_param_env_or_error<'tcx>(
839 region_context: DefId,
840 unnormalized_env: ty::ParamEnv<'tcx>,
841 cause: ObligationCause<'tcx>,
842 ) -> ty::ParamEnv<'tcx> {
843 // I'm not wild about reporting errors here; I'd prefer to
844 // have the errors get reported at a defined place (e.g.,
845 // during typeck). Instead I have all parameter
846 // environments, in effect, going through this function
847 // and hence potentially reporting errors. This ensures of
848 // course that we never forget to normalize (the
849 // alternative seemed like it would involve a lot of
850 // manual invocations of this fn -- and then we'd have to
851 // deal with the errors at each of those sites).
853 // In any case, in practice, typeck constructs all the
854 // parameter environments once for every fn as it goes,
855 // and errors will get reported then; so after typeck we
856 // can be sure that no errors should occur.
858 debug!("normalize_param_env_or_error(region_context={:?}, unnormalized_env={:?}, cause={:?})",
859 region_context, unnormalized_env, cause);
861 let mut predicates: Vec<_> =
862 util::elaborate_predicates(tcx, unnormalized_env.caller_bounds.to_vec())
865 debug!("normalize_param_env_or_error: elaborated-predicates={:?}",
868 let elaborated_env = ty::ParamEnv::new(
869 tcx.intern_predicates(&predicates),
870 unnormalized_env.reveal,
871 unnormalized_env.def_id
874 // HACK: we are trying to normalize the param-env inside *itself*. The problem is that
875 // normalization expects its param-env to be already normalized, which means we have
878 // The way we handle this is by normalizing the param-env inside an unnormalized version
879 // of the param-env, which means that if the param-env contains unnormalized projections,
880 // we'll have some normalization failures. This is unfortunate.
882 // Lazy normalization would basically handle this by treating just the
883 // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
885 // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
886 // types, so to make the situation less bad, we normalize all the predicates *but*
887 // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
888 // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
890 // This works fairly well because trait matching does not actually care about param-env
891 // TypeOutlives predicates - these are normally used by regionck.
892 let outlives_predicates: Vec<_> = predicates.drain_filter(|predicate| {
894 ty::Predicate::TypeOutlives(..) => true,
899 debug!("normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
900 predicates, outlives_predicates);
901 let non_outlives_predicates =
902 match do_normalize_predicates(tcx, region_context, cause.clone(),
903 elaborated_env, predicates) {
904 Ok(predicates) => predicates,
905 // An unnormalized env is better than nothing.
906 Err(ErrorReported) => {
907 debug!("normalize_param_env_or_error: errored resolving non-outlives predicates");
908 return elaborated_env
912 debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates);
914 // Not sure whether it is better to include the unnormalized TypeOutlives predicates
915 // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
916 // predicates here anyway. Keeping them here anyway because it seems safer.
917 let outlives_env: Vec<_> =
918 non_outlives_predicates.iter().chain(&outlives_predicates).cloned().collect();
919 let outlives_env = ty::ParamEnv::new(
920 tcx.intern_predicates(&outlives_env),
921 unnormalized_env.reveal,
924 let outlives_predicates =
925 match do_normalize_predicates(tcx, region_context, cause,
926 outlives_env, outlives_predicates) {
927 Ok(predicates) => predicates,
928 // An unnormalized env is better than nothing.
929 Err(ErrorReported) => {
930 debug!("normalize_param_env_or_error: errored resolving outlives predicates");
931 return elaborated_env
934 debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates);
936 let mut predicates = non_outlives_predicates;
937 predicates.extend(outlives_predicates);
938 debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
940 tcx.intern_predicates(&predicates),
941 unnormalized_env.reveal,
942 unnormalized_env.def_id
946 pub fn fully_normalize<'a, 'tcx, T>(
947 infcx: &InferCtxt<'a, 'tcx>,
948 mut fulfill_cx: FulfillmentContext<'tcx>,
949 cause: ObligationCause<'tcx>,
950 param_env: ty::ParamEnv<'tcx>,
952 ) -> Result<T, Vec<FulfillmentError<'tcx>>>
954 T: TypeFoldable<'tcx>,
956 debug!("fully_normalize_with_fulfillcx(value={:?})", value);
957 let selcx = &mut SelectionContext::new(infcx);
958 let Normalized { value: normalized_value, obligations } =
959 project::normalize(selcx, param_env, cause, value);
960 debug!("fully_normalize: normalized_value={:?} obligations={:?}",
963 for obligation in obligations {
964 fulfill_cx.register_predicate_obligation(selcx.infcx(), obligation);
967 debug!("fully_normalize: select_all_or_error start");
968 fulfill_cx.select_all_or_error(infcx)?;
969 debug!("fully_normalize: select_all_or_error complete");
970 let resolved_value = infcx.resolve_vars_if_possible(&normalized_value);
971 debug!("fully_normalize: resolved_value={:?}", resolved_value);
975 /// Normalizes the predicates and checks whether they hold in an empty
976 /// environment. If this returns false, then either normalize
977 /// encountered an error or one of the predicates did not hold. Used
978 /// when creating vtables to check for unsatisfiable methods.
979 fn normalize_and_test_predicates<'tcx>(
981 predicates: Vec<ty::Predicate<'tcx>>,
983 debug!("normalize_and_test_predicates(predicates={:?})",
986 let result = tcx.infer_ctxt().enter(|infcx| {
987 let param_env = ty::ParamEnv::reveal_all();
988 let mut selcx = SelectionContext::new(&infcx);
989 let mut fulfill_cx = FulfillmentContext::new();
990 let cause = ObligationCause::dummy();
991 let Normalized { value: predicates, obligations } =
992 normalize(&mut selcx, param_env, cause.clone(), &predicates);
993 for obligation in obligations {
994 fulfill_cx.register_predicate_obligation(&infcx, obligation);
996 for predicate in predicates {
997 let obligation = Obligation::new(cause.clone(), param_env, predicate);
998 fulfill_cx.register_predicate_obligation(&infcx, obligation);
1001 fulfill_cx.select_all_or_error(&infcx).is_ok()
1003 debug!("normalize_and_test_predicates(predicates={:?}) = {:?}",
1004 predicates, result);
1008 fn substitute_normalize_and_test_predicates<'tcx>(
1010 key: (DefId, SubstsRef<'tcx>),
1012 debug!("substitute_normalize_and_test_predicates(key={:?})",
1015 let predicates = tcx.predicates_of(key.0).instantiate(tcx, key.1).predicates;
1016 let result = normalize_and_test_predicates(tcx, predicates);
1018 debug!("substitute_normalize_and_test_predicates(key={:?}) = {:?}",
1023 /// Given a trait `trait_ref`, iterates the vtable entries
1024 /// that come from `trait_ref`, including its supertraits.
1025 #[inline] // FIXME(#35870): avoid closures being unexported due to `impl Trait`.
1026 fn vtable_methods<'tcx>(
1028 trait_ref: ty::PolyTraitRef<'tcx>,
1029 ) -> &'tcx [Option<(DefId, SubstsRef<'tcx>)>] {
1030 debug!("vtable_methods({:?})", trait_ref);
1032 tcx.arena.alloc_from_iter(
1033 supertraits(tcx, trait_ref).flat_map(move |trait_ref| {
1034 let trait_methods = tcx.associated_items(trait_ref.def_id())
1035 .filter(|item| item.kind == ty::AssocKind::Method);
1037 // Now list each method's DefId and InternalSubsts (for within its trait).
1038 // If the method can never be called from this object, produce None.
1039 trait_methods.map(move |trait_method| {
1040 debug!("vtable_methods: trait_method={:?}", trait_method);
1041 let def_id = trait_method.def_id;
1043 // Some methods cannot be called on an object; skip those.
1044 if !tcx.is_vtable_safe_method(trait_ref.def_id(), &trait_method) {
1045 debug!("vtable_methods: not vtable safe");
1049 // The method may have some early-bound lifetimes; add 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 // 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>;