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 /// Error derived when matching traits/impls; see ObligationCause for more details
234 CompareImplTypeObligation {
235 item_name: ast::Name,
236 impl_item_def_id: DefId,
237 trait_item_def_id: DefId,
240 /// Checking that this expression can be assigned where it needs to be
241 // FIXME(eddyb) #11161 is the original Expr required?
244 /// Computing common supertype in the arms of a match expression
245 MatchExpressionArm(Box<MatchExpressionArmCause<'tcx>>),
247 /// Computing common supertype in the pattern guard for the arms of a match expression
248 MatchExpressionArmPattern { span: Span, ty: Ty<'tcx> },
250 /// Constants in patterns must have `Structural` type.
251 ConstPatternStructural,
253 /// Computing common supertype in an if expression
254 IfExpression(Box<IfExpressionCause>),
256 /// Computing common supertype of an if expression with no else counter-part
257 IfExpressionWithNoElse,
259 /// `main` has wrong type
262 /// `start` has wrong type
265 /// Intrinsic has wrong type
271 /// `return` with no expression
274 /// `return` with an expression
275 ReturnValue(hir::HirId),
277 /// Return type of this function
280 /// Block implicit return
281 BlockTailExpression(hir::HirId),
283 /// #[feature(trivial_bounds)] is not enabled
286 AssocTypeBound(Box<AssocTypeBoundData>),
289 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
290 pub struct AssocTypeBoundData {
291 pub impl_span: Option<Span>,
293 pub bounds: Vec<Span>,
296 // `ObligationCauseCode` is used a lot. Make sure it doesn't unintentionally get bigger.
297 #[cfg(target_arch = "x86_64")]
298 static_assert_size!(ObligationCauseCode<'_>, 32);
300 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
301 pub struct MatchExpressionArmCause<'tcx> {
303 pub source: hir::MatchSource,
304 pub prior_arms: Vec<Span>,
305 pub last_ty: Ty<'tcx>,
306 pub discrim_hir_id: hir::HirId,
309 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
310 pub struct IfExpressionCause {
312 pub outer: Option<Span>,
313 pub semicolon: Option<Span>,
316 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
317 pub struct DerivedObligationCause<'tcx> {
318 /// The trait reference of the parent obligation that led to the
319 /// current obligation. Note that only trait obligations lead to
320 /// derived obligations, so we just store the trait reference here
322 parent_trait_ref: ty::PolyTraitRef<'tcx>,
324 /// The parent trait had this cause.
325 parent_code: Rc<ObligationCauseCode<'tcx>>
328 pub type Obligations<'tcx, O> = Vec<Obligation<'tcx, O>>;
329 pub type PredicateObligations<'tcx> = Vec<PredicateObligation<'tcx>>;
330 pub type TraitObligations<'tcx> = Vec<TraitObligation<'tcx>>;
332 /// The following types:
340 /// * `InEnvironment`,
341 /// are used for representing the trait system in the form of
342 /// logic programming clauses. They are part of the interface
343 /// for the chalk SLG solver.
344 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
345 pub enum WhereClause<'tcx> {
346 Implemented(ty::TraitPredicate<'tcx>),
347 ProjectionEq(ty::ProjectionPredicate<'tcx>),
348 RegionOutlives(ty::RegionOutlivesPredicate<'tcx>),
349 TypeOutlives(ty::TypeOutlivesPredicate<'tcx>),
352 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
353 pub enum WellFormed<'tcx> {
354 Trait(ty::TraitPredicate<'tcx>),
358 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
359 pub enum FromEnv<'tcx> {
360 Trait(ty::TraitPredicate<'tcx>),
364 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
365 pub enum DomainGoal<'tcx> {
366 Holds(WhereClause<'tcx>),
367 WellFormed(WellFormed<'tcx>),
368 FromEnv(FromEnv<'tcx>),
369 Normalize(ty::ProjectionPredicate<'tcx>),
372 pub type PolyDomainGoal<'tcx> = ty::Binder<DomainGoal<'tcx>>;
374 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
375 pub enum QuantifierKind {
380 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
381 pub enum GoalKind<'tcx> {
382 Implies(Clauses<'tcx>, Goal<'tcx>),
383 And(Goal<'tcx>, Goal<'tcx>),
385 DomainGoal(DomainGoal<'tcx>),
386 Quantified(QuantifierKind, ty::Binder<Goal<'tcx>>),
387 Subtype(Ty<'tcx>, Ty<'tcx>),
391 pub type Goal<'tcx> = &'tcx GoalKind<'tcx>;
393 pub type Goals<'tcx> = &'tcx List<Goal<'tcx>>;
395 impl<'tcx> DomainGoal<'tcx> {
396 pub fn into_goal(self) -> GoalKind<'tcx> {
397 GoalKind::DomainGoal(self)
400 pub fn into_program_clause(self) -> ProgramClause<'tcx> {
403 hypotheses: ty::List::empty(),
404 category: ProgramClauseCategory::Other,
409 impl<'tcx> GoalKind<'tcx> {
410 pub fn from_poly_domain_goal(
411 domain_goal: PolyDomainGoal<'tcx>,
413 ) -> GoalKind<'tcx> {
414 match domain_goal.no_bound_vars() {
415 Some(p) => p.into_goal(),
416 None => GoalKind::Quantified(
417 QuantifierKind::Universal,
418 domain_goal.map_bound(|p| tcx.mk_goal(p.into_goal()))
424 /// This matches the definition from Page 7 of "A Proof Procedure for the Logic of Hereditary
425 /// Harrop Formulas".
426 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
427 pub enum Clause<'tcx> {
428 Implies(ProgramClause<'tcx>),
429 ForAll(ty::Binder<ProgramClause<'tcx>>),
433 pub fn category(self) -> ProgramClauseCategory {
435 Clause::Implies(clause) => clause.category,
436 Clause::ForAll(clause) => clause.skip_binder().category,
441 /// Multiple clauses.
442 pub type Clauses<'tcx> = &'tcx List<Clause<'tcx>>;
444 /// A "program clause" has the form `D :- G1, ..., Gn`. It is saying
445 /// that the domain goal `D` is true if `G1...Gn` are provable. This
446 /// is equivalent to the implication `G1..Gn => D`; we usually write
447 /// it with the reverse implication operator `:-` to emphasize the way
448 /// that programs are actually solved (via backchaining, which starts
449 /// with the goal to solve and proceeds from there).
450 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
451 pub struct ProgramClause<'tcx> {
452 /// This goal will be considered true ...
453 pub goal: DomainGoal<'tcx>,
455 /// ... if we can prove these hypotheses (there may be no hypotheses at all):
456 pub hypotheses: Goals<'tcx>,
458 /// Useful for filtering clauses.
459 pub category: ProgramClauseCategory,
462 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
463 pub enum ProgramClauseCategory {
469 /// A set of clauses that we assume to be true.
470 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
471 pub struct Environment<'tcx> {
472 pub clauses: Clauses<'tcx>,
475 impl Environment<'tcx> {
476 pub fn with<G>(self, goal: G) -> InEnvironment<'tcx, G> {
484 /// Something (usually a goal), along with an environment.
485 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
486 pub struct InEnvironment<'tcx, G> {
487 pub environment: Environment<'tcx>,
491 pub type Selection<'tcx> = Vtable<'tcx, PredicateObligation<'tcx>>;
493 #[derive(Clone,Debug,TypeFoldable)]
494 pub enum SelectionError<'tcx> {
496 OutputTypeParameterMismatch(ty::PolyTraitRef<'tcx>,
497 ty::PolyTraitRef<'tcx>,
498 ty::error::TypeError<'tcx>),
499 TraitNotObjectSafe(DefId),
500 ConstEvalFailure(ErrorHandled),
504 pub struct FulfillmentError<'tcx> {
505 pub obligation: PredicateObligation<'tcx>,
506 pub code: FulfillmentErrorCode<'tcx>,
507 /// Diagnostics only: we opportunistically change the `code.span` when we encounter an
508 /// obligation error caused by a call argument. When this is the case, we also signal that in
509 /// this field to ensure accuracy of suggestions.
510 pub points_at_arg_span: bool,
514 pub enum FulfillmentErrorCode<'tcx> {
515 CodeSelectionError(SelectionError<'tcx>),
516 CodeProjectionError(MismatchedProjectionTypes<'tcx>),
517 CodeSubtypeError(ExpectedFound<Ty<'tcx>>,
518 TypeError<'tcx>), // always comes from a SubtypePredicate
522 /// When performing resolution, it is typically the case that there
523 /// can be one of three outcomes:
525 /// - `Ok(Some(r))`: success occurred with result `r`
526 /// - `Ok(None)`: could not definitely determine anything, usually due
527 /// to inconclusive type inference.
528 /// - `Err(e)`: error `e` occurred
529 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
531 /// Given the successful resolution of an obligation, the `Vtable`
532 /// indicates where the vtable comes from. Note that while we call this
533 /// a "vtable", it does not necessarily indicate dynamic dispatch at
534 /// runtime. `Vtable` instances just tell the compiler where to find
535 /// methods, but in generic code those methods are typically statically
536 /// dispatched -- only when an object is constructed is a `Vtable`
537 /// instance reified into an actual vtable.
539 /// For example, the vtable may be tied to a specific impl (case A),
540 /// or it may be relative to some bound that is in scope (case B).
543 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
544 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
545 /// impl Clone for int { ... } // Impl_3
547 /// fn foo<T:Clone>(concrete: Option<Box<int>>,
549 /// mixed: Option<T>) {
551 /// // Case A: Vtable points at a specific impl. Only possible when
552 /// // type is concretely known. If the impl itself has bounded
553 /// // type parameters, Vtable will carry resolutions for those as well:
554 /// concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
556 /// // Case B: Vtable must be provided by caller. This applies when
557 /// // type is a type parameter.
558 /// param.clone(); // VtableParam
560 /// // Case C: A mix of cases A and B.
561 /// mixed.clone(); // Vtable(Impl_1, [VtableParam])
565 /// ### The type parameter `N`
567 /// See explanation on `VtableImplData`.
568 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
569 pub enum Vtable<'tcx, N> {
570 /// Vtable identifying a particular impl.
571 VtableImpl(VtableImplData<'tcx, N>),
573 /// Vtable for auto trait implementations.
574 /// This carries the information and nested obligations with regards
575 /// to an auto implementation for a trait `Trait`. The nested obligations
576 /// ensure the trait implementation holds for all the constituent types.
577 VtableAutoImpl(VtableAutoImplData<N>),
579 /// Successful resolution to an obligation provided by the caller
580 /// for some type parameter. The `Vec<N>` represents the
581 /// obligations incurred from normalizing the where-clause (if
585 /// Virtual calls through an object.
586 VtableObject(VtableObjectData<'tcx, N>),
588 /// Successful resolution for a builtin trait.
589 VtableBuiltin(VtableBuiltinData<N>),
591 /// Vtable automatically generated for a closure. The `DefId` is the ID
592 /// of the closure expression. This is a `VtableImpl` in spirit, but the
593 /// impl is generated by the compiler and does not appear in the source.
594 VtableClosure(VtableClosureData<'tcx, N>),
596 /// Same as above, but for a function pointer type with the given signature.
597 VtableFnPointer(VtableFnPointerData<'tcx, N>),
599 /// Vtable automatically generated for a generator.
600 VtableGenerator(VtableGeneratorData<'tcx, N>),
602 /// Vtable for a trait alias.
603 VtableTraitAlias(VtableTraitAliasData<'tcx, N>),
606 /// Identifies a particular impl in the source, along with a set of
607 /// substitutions from the impl's type/lifetime parameters. The
608 /// `nested` vector corresponds to the nested obligations attached to
609 /// the impl's type parameters.
611 /// The type parameter `N` indicates the type used for "nested
612 /// obligations" that are required by the impl. During type-check, this
613 /// is `Obligation`, as one might expect. During codegen, however, this
614 /// is `()`, because codegen only requires a shallow resolution of an
615 /// impl, and nested obligations are satisfied later.
616 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
617 pub struct VtableImplData<'tcx, N> {
618 pub impl_def_id: DefId,
619 pub substs: SubstsRef<'tcx>,
623 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
624 pub struct VtableGeneratorData<'tcx, N> {
625 pub generator_def_id: DefId,
626 pub substs: SubstsRef<'tcx>,
627 /// Nested obligations. This can be non-empty if the generator
628 /// signature contains associated types.
632 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
633 pub struct VtableClosureData<'tcx, N> {
634 pub closure_def_id: DefId,
635 pub substs: SubstsRef<'tcx>,
636 /// Nested obligations. This can be non-empty if the closure
637 /// signature contains associated types.
641 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
642 pub struct VtableAutoImplData<N> {
643 pub trait_def_id: DefId,
647 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
648 pub struct VtableBuiltinData<N> {
652 /// A vtable for some object-safe trait `Foo` automatically derived
653 /// for the object type `Foo`.
654 #[derive(PartialEq, Eq, Clone, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
655 pub struct VtableObjectData<'tcx, N> {
656 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
657 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
659 /// The vtable is formed by concatenating together the method lists of
660 /// the base object trait and all supertraits; this is the start of
661 /// `upcast_trait_ref`'s methods in that vtable.
662 pub vtable_base: usize,
667 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
668 pub struct VtableFnPointerData<'tcx, N> {
673 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
674 pub struct VtableTraitAliasData<'tcx, N> {
675 pub alias_def_id: DefId,
676 pub substs: SubstsRef<'tcx>,
680 /// Creates predicate obligations from the generic bounds.
681 pub fn predicates_for_generics<'tcx>(
682 cause: ObligationCause<'tcx>,
683 param_env: ty::ParamEnv<'tcx>,
684 generic_bounds: &ty::InstantiatedPredicates<'tcx>,
685 ) -> PredicateObligations<'tcx> {
686 util::predicates_for_generics(cause, 0, param_env, generic_bounds)
689 /// Determines whether the type `ty` is known to meet `bound` and
690 /// returns true if so. Returns false if `ty` either does not meet
691 /// `bound` or is not known to meet bound (note that this is
692 /// conservative towards *no impl*, which is the opposite of the
693 /// `evaluate` methods).
694 pub fn type_known_to_meet_bound_modulo_regions<'a, 'tcx>(
695 infcx: &InferCtxt<'a, 'tcx>,
696 param_env: ty::ParamEnv<'tcx>,
701 debug!("type_known_to_meet_bound_modulo_regions(ty={:?}, bound={:?})",
703 infcx.tcx.def_path_str(def_id));
705 let trait_ref = ty::TraitRef {
707 substs: infcx.tcx.mk_substs_trait(ty, &[]),
709 let obligation = Obligation {
711 cause: ObligationCause::misc(span, hir::DUMMY_HIR_ID),
713 predicate: trait_ref.to_predicate(),
716 let result = infcx.predicate_must_hold_modulo_regions(&obligation);
717 debug!("type_known_to_meet_ty={:?} bound={} => {:?}",
718 ty, infcx.tcx.def_path_str(def_id), result);
720 if result && (ty.has_infer_types() || ty.has_closure_types()) {
721 // Because of inference "guessing", selection can sometimes claim
722 // to succeed while the success requires a guess. To ensure
723 // this function's result remains infallible, we must confirm
724 // that guess. While imperfect, I believe this is sound.
726 // The handling of regions in this area of the code is terrible,
727 // see issue #29149. We should be able to improve on this with
729 let mut fulfill_cx = FulfillmentContext::new_ignoring_regions();
731 // We can use a dummy node-id here because we won't pay any mind
732 // to region obligations that arise (there shouldn't really be any
734 let cause = ObligationCause::misc(span, hir::DUMMY_HIR_ID);
736 fulfill_cx.register_bound(infcx, param_env, ty, def_id, cause);
738 // Note: we only assume something is `Copy` if we can
739 // *definitively* show that it implements `Copy`. Otherwise,
740 // assume it is move; linear is always ok.
741 match fulfill_cx.select_all_or_error(infcx) {
743 debug!("type_known_to_meet_bound_modulo_regions: ty={:?} bound={} success",
745 infcx.tcx.def_path_str(def_id));
749 debug!("type_known_to_meet_bound_modulo_regions: ty={:?} bound={} errors={:?}",
751 infcx.tcx.def_path_str(def_id),
761 fn do_normalize_predicates<'tcx>(
763 region_context: DefId,
764 cause: ObligationCause<'tcx>,
765 elaborated_env: ty::ParamEnv<'tcx>,
766 predicates: Vec<ty::Predicate<'tcx>>,
767 ) -> Result<Vec<ty::Predicate<'tcx>>, ErrorReported> {
769 "do_normalize_predicates(predicates={:?}, region_context={:?}, cause={:?})",
774 let span = cause.span;
775 tcx.infer_ctxt().enter(|infcx| {
776 // FIXME. We should really... do something with these region
777 // obligations. But this call just continues the older
778 // behavior (i.e., doesn't cause any new bugs), and it would
779 // take some further refactoring to actually solve them. In
780 // particular, we would have to handle implied bounds
781 // properly, and that code is currently largely confined to
782 // regionck (though I made some efforts to extract it
785 // @arielby: In any case, these obligations are checked
786 // by wfcheck anyway, so I'm not sure we have to check
787 // them here too, and we will remove this function when
788 // we move over to lazy normalization *anyway*.
789 let fulfill_cx = FulfillmentContext::new_ignoring_regions();
790 let predicates = match fully_normalize(
797 Ok(predicates) => predicates,
799 infcx.report_fulfillment_errors(&errors, None, false);
800 return Err(ErrorReported)
804 debug!("do_normalize_predictes: normalized predicates = {:?}", predicates);
806 let region_scope_tree = region::ScopeTree::default();
808 // We can use the `elaborated_env` here; the region code only
809 // cares about declarations like `'a: 'b`.
810 let outlives_env = OutlivesEnvironment::new(elaborated_env);
812 infcx.resolve_regions_and_report_errors(
816 SuppressRegionErrors::default(),
819 let predicates = match infcx.fully_resolve(&predicates) {
820 Ok(predicates) => predicates,
822 // If we encounter a fixup error, it means that some type
823 // variable wound up unconstrained. I actually don't know
824 // if this can happen, and I certainly don't expect it to
825 // happen often, but if it did happen it probably
826 // represents a legitimate failure due to some kind of
827 // unconstrained variable, and it seems better not to ICE,
828 // all things considered.
829 tcx.sess.span_err(span, &fixup_err.to_string());
830 return Err(ErrorReported)
833 if predicates.has_local_value() {
834 // FIXME: shouldn't we, you know, actually report an error here? or an ICE?
842 // FIXME: this is gonna need to be removed ...
843 /// Normalizes the parameter environment, reporting errors if they occur.
844 pub fn normalize_param_env_or_error<'tcx>(
846 region_context: DefId,
847 unnormalized_env: ty::ParamEnv<'tcx>,
848 cause: ObligationCause<'tcx>,
849 ) -> ty::ParamEnv<'tcx> {
850 // I'm not wild about reporting errors here; I'd prefer to
851 // have the errors get reported at a defined place (e.g.,
852 // during typeck). Instead I have all parameter
853 // environments, in effect, going through this function
854 // and hence potentially reporting errors. This ensures of
855 // course that we never forget to normalize (the
856 // alternative seemed like it would involve a lot of
857 // manual invocations of this fn -- and then we'd have to
858 // deal with the errors at each of those sites).
860 // In any case, in practice, typeck constructs all the
861 // parameter environments once for every fn as it goes,
862 // and errors will get reported then; so after typeck we
863 // can be sure that no errors should occur.
865 debug!("normalize_param_env_or_error(region_context={:?}, unnormalized_env={:?}, cause={:?})",
866 region_context, unnormalized_env, cause);
868 let mut predicates: Vec<_> =
869 util::elaborate_predicates(tcx, unnormalized_env.caller_bounds.to_vec())
872 debug!("normalize_param_env_or_error: elaborated-predicates={:?}",
875 let elaborated_env = ty::ParamEnv::new(
876 tcx.intern_predicates(&predicates),
877 unnormalized_env.reveal,
878 unnormalized_env.def_id
881 // HACK: we are trying to normalize the param-env inside *itself*. The problem is that
882 // normalization expects its param-env to be already normalized, which means we have
885 // The way we handle this is by normalizing the param-env inside an unnormalized version
886 // of the param-env, which means that if the param-env contains unnormalized projections,
887 // we'll have some normalization failures. This is unfortunate.
889 // Lazy normalization would basically handle this by treating just the
890 // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
892 // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
893 // types, so to make the situation less bad, we normalize all the predicates *but*
894 // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
895 // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
897 // This works fairly well because trait matching does not actually care about param-env
898 // TypeOutlives predicates - these are normally used by regionck.
899 let outlives_predicates: Vec<_> = predicates.drain_filter(|predicate| {
901 ty::Predicate::TypeOutlives(..) => true,
906 debug!("normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
907 predicates, outlives_predicates);
908 let non_outlives_predicates =
909 match do_normalize_predicates(tcx, region_context, cause.clone(),
910 elaborated_env, predicates) {
911 Ok(predicates) => predicates,
912 // An unnormalized env is better than nothing.
913 Err(ErrorReported) => {
914 debug!("normalize_param_env_or_error: errored resolving non-outlives predicates");
915 return elaborated_env
919 debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates);
921 // Not sure whether it is better to include the unnormalized TypeOutlives predicates
922 // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
923 // predicates here anyway. Keeping them here anyway because it seems safer.
924 let outlives_env: Vec<_> =
925 non_outlives_predicates.iter().chain(&outlives_predicates).cloned().collect();
926 let outlives_env = ty::ParamEnv::new(
927 tcx.intern_predicates(&outlives_env),
928 unnormalized_env.reveal,
931 let outlives_predicates =
932 match do_normalize_predicates(tcx, region_context, cause,
933 outlives_env, outlives_predicates) {
934 Ok(predicates) => predicates,
935 // An unnormalized env is better than nothing.
936 Err(ErrorReported) => {
937 debug!("normalize_param_env_or_error: errored resolving outlives predicates");
938 return elaborated_env
941 debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates);
943 let mut predicates = non_outlives_predicates;
944 predicates.extend(outlives_predicates);
945 debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
947 tcx.intern_predicates(&predicates),
948 unnormalized_env.reveal,
949 unnormalized_env.def_id
953 pub fn fully_normalize<'a, 'tcx, T>(
954 infcx: &InferCtxt<'a, 'tcx>,
955 mut fulfill_cx: FulfillmentContext<'tcx>,
956 cause: ObligationCause<'tcx>,
957 param_env: ty::ParamEnv<'tcx>,
959 ) -> Result<T, Vec<FulfillmentError<'tcx>>>
961 T: TypeFoldable<'tcx>,
963 debug!("fully_normalize_with_fulfillcx(value={:?})", value);
964 let selcx = &mut SelectionContext::new(infcx);
965 let Normalized { value: normalized_value, obligations } =
966 project::normalize(selcx, param_env, cause, value);
967 debug!("fully_normalize: normalized_value={:?} obligations={:?}",
970 for obligation in obligations {
971 fulfill_cx.register_predicate_obligation(selcx.infcx(), obligation);
974 debug!("fully_normalize: select_all_or_error start");
975 fulfill_cx.select_all_or_error(infcx)?;
976 debug!("fully_normalize: select_all_or_error complete");
977 let resolved_value = infcx.resolve_vars_if_possible(&normalized_value);
978 debug!("fully_normalize: resolved_value={:?}", resolved_value);
982 /// Normalizes the predicates and checks whether they hold in an empty
983 /// environment. If this returns false, then either normalize
984 /// encountered an error or one of the predicates did not hold. Used
985 /// when creating vtables to check for unsatisfiable methods.
986 fn normalize_and_test_predicates<'tcx>(
988 predicates: Vec<ty::Predicate<'tcx>>,
990 debug!("normalize_and_test_predicates(predicates={:?})",
993 let result = tcx.infer_ctxt().enter(|infcx| {
994 let param_env = ty::ParamEnv::reveal_all();
995 let mut selcx = SelectionContext::new(&infcx);
996 let mut fulfill_cx = FulfillmentContext::new();
997 let cause = ObligationCause::dummy();
998 let Normalized { value: predicates, obligations } =
999 normalize(&mut selcx, param_env, cause.clone(), &predicates);
1000 for obligation in obligations {
1001 fulfill_cx.register_predicate_obligation(&infcx, obligation);
1003 for predicate in predicates {
1004 let obligation = Obligation::new(cause.clone(), param_env, predicate);
1005 fulfill_cx.register_predicate_obligation(&infcx, obligation);
1008 fulfill_cx.select_all_or_error(&infcx).is_ok()
1010 debug!("normalize_and_test_predicates(predicates={:?}) = {:?}",
1011 predicates, result);
1015 fn substitute_normalize_and_test_predicates<'tcx>(
1017 key: (DefId, SubstsRef<'tcx>),
1019 debug!("substitute_normalize_and_test_predicates(key={:?})",
1022 let predicates = tcx.predicates_of(key.0).instantiate(tcx, key.1).predicates;
1023 let result = normalize_and_test_predicates(tcx, predicates);
1025 debug!("substitute_normalize_and_test_predicates(key={:?}) = {:?}",
1030 /// Given a trait `trait_ref`, iterates the vtable entries
1031 /// that come from `trait_ref`, including its supertraits.
1032 #[inline] // FIXME(#35870): avoid closures being unexported due to `impl Trait`.
1033 fn vtable_methods<'tcx>(
1035 trait_ref: ty::PolyTraitRef<'tcx>,
1036 ) -> &'tcx [Option<(DefId, SubstsRef<'tcx>)>] {
1037 debug!("vtable_methods({:?})", trait_ref);
1039 tcx.arena.alloc_from_iter(
1040 supertraits(tcx, trait_ref).flat_map(move |trait_ref| {
1041 let trait_methods = tcx.associated_items(trait_ref.def_id())
1042 .filter(|item| item.kind == ty::AssocKind::Method);
1044 // Now list each method's DefId and InternalSubsts (for within its trait).
1045 // If the method can never be called from this object, produce None.
1046 trait_methods.map(move |trait_method| {
1047 debug!("vtable_methods: trait_method={:?}", trait_method);
1048 let def_id = trait_method.def_id;
1050 // Some methods cannot be called on an object; skip those.
1051 if !tcx.is_vtable_safe_method(trait_ref.def_id(), &trait_method) {
1052 debug!("vtable_methods: not vtable safe");
1056 // The method may have some early-bound lifetimes; add regions for those.
1057 let substs = trait_ref.map_bound(|trait_ref|
1058 InternalSubsts::for_item(tcx, def_id, |param, _|
1060 GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(),
1061 GenericParamDefKind::Type { .. } |
1062 GenericParamDefKind::Const => {
1063 trait_ref.substs[param.index as usize]
1069 // The trait type may have higher-ranked lifetimes in it;
1070 // erase them if they appear, so that we get the type
1071 // at some particular call site.
1072 let substs = tcx.normalize_erasing_late_bound_regions(
1073 ty::ParamEnv::reveal_all(),
1077 // It's possible that the method relies on where-clauses that
1078 // do not hold for this particular set of type parameters.
1079 // Note that this method could then never be called, so we
1080 // do not want to try and codegen it, in that case (see #23435).
1081 let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs);
1082 if !normalize_and_test_predicates(tcx, predicates.predicates) {
1083 debug!("vtable_methods: predicates do not hold");
1087 Some((def_id, substs))
1093 impl<'tcx, O> Obligation<'tcx, O> {
1094 pub fn new(cause: ObligationCause<'tcx>,
1095 param_env: ty::ParamEnv<'tcx>,
1097 -> Obligation<'tcx, O>
1099 Obligation { cause, param_env, recursion_depth: 0, predicate }
1102 fn with_depth(cause: ObligationCause<'tcx>,
1103 recursion_depth: usize,
1104 param_env: ty::ParamEnv<'tcx>,
1106 -> Obligation<'tcx, O>
1108 Obligation { cause, param_env, recursion_depth, predicate }
1111 pub fn misc(span: Span,
1112 body_id: hir::HirId,
1113 param_env: ty::ParamEnv<'tcx>,
1115 -> Obligation<'tcx, O> {
1116 Obligation::new(ObligationCause::misc(span, body_id), param_env, trait_ref)
1119 pub fn with<P>(&self, value: P) -> Obligation<'tcx,P> {
1120 Obligation { cause: self.cause.clone(),
1121 param_env: self.param_env,
1122 recursion_depth: self.recursion_depth,
1127 impl<'tcx> ObligationCause<'tcx> {
1129 pub fn new(span: Span,
1130 body_id: hir::HirId,
1131 code: ObligationCauseCode<'tcx>)
1132 -> ObligationCause<'tcx> {
1133 ObligationCause { span, body_id, code }
1136 pub fn misc(span: Span, body_id: hir::HirId) -> ObligationCause<'tcx> {
1137 ObligationCause { span, body_id, code: MiscObligation }
1140 pub fn dummy() -> ObligationCause<'tcx> {
1141 ObligationCause { span: DUMMY_SP, body_id: hir::CRATE_HIR_ID, code: MiscObligation }
1145 impl<'tcx, N> Vtable<'tcx, N> {
1146 pub fn nested_obligations(self) -> Vec<N> {
1148 VtableImpl(i) => i.nested,
1149 VtableParam(n) => n,
1150 VtableBuiltin(i) => i.nested,
1151 VtableAutoImpl(d) => d.nested,
1152 VtableClosure(c) => c.nested,
1153 VtableGenerator(c) => c.nested,
1154 VtableObject(d) => d.nested,
1155 VtableFnPointer(d) => d.nested,
1156 VtableTraitAlias(d) => d.nested,
1160 pub fn map<M, F>(self, f: F) -> Vtable<'tcx, M> where F: FnMut(N) -> M {
1162 VtableImpl(i) => VtableImpl(VtableImplData {
1163 impl_def_id: i.impl_def_id,
1165 nested: i.nested.into_iter().map(f).collect(),
1167 VtableParam(n) => VtableParam(n.into_iter().map(f).collect()),
1168 VtableBuiltin(i) => VtableBuiltin(VtableBuiltinData {
1169 nested: i.nested.into_iter().map(f).collect(),
1171 VtableObject(o) => VtableObject(VtableObjectData {
1172 upcast_trait_ref: o.upcast_trait_ref,
1173 vtable_base: o.vtable_base,
1174 nested: o.nested.into_iter().map(f).collect(),
1176 VtableAutoImpl(d) => VtableAutoImpl(VtableAutoImplData {
1177 trait_def_id: d.trait_def_id,
1178 nested: d.nested.into_iter().map(f).collect(),
1180 VtableClosure(c) => VtableClosure(VtableClosureData {
1181 closure_def_id: c.closure_def_id,
1183 nested: c.nested.into_iter().map(f).collect(),
1185 VtableGenerator(c) => VtableGenerator(VtableGeneratorData {
1186 generator_def_id: c.generator_def_id,
1188 nested: c.nested.into_iter().map(f).collect(),
1190 VtableFnPointer(p) => VtableFnPointer(VtableFnPointerData {
1192 nested: p.nested.into_iter().map(f).collect(),
1194 VtableTraitAlias(d) => VtableTraitAlias(VtableTraitAliasData {
1195 alias_def_id: d.alias_def_id,
1197 nested: d.nested.into_iter().map(f).collect(),
1203 impl<'tcx> FulfillmentError<'tcx> {
1204 fn new(obligation: PredicateObligation<'tcx>,
1205 code: FulfillmentErrorCode<'tcx>)
1206 -> FulfillmentError<'tcx>
1208 FulfillmentError { obligation: obligation, code: code, points_at_arg_span: false }
1212 impl<'tcx> TraitObligation<'tcx> {
1213 fn self_ty(&self) -> ty::Binder<Ty<'tcx>> {
1214 self.predicate.map_bound(|p| p.self_ty())
1218 pub fn provide(providers: &mut ty::query::Providers<'_>) {
1219 *providers = ty::query::Providers {
1220 is_object_safe: object_safety::is_object_safe_provider,
1221 specialization_graph_of: specialize::specialization_graph_provider,
1222 specializes: specialize::specializes,
1223 codegen_fulfill_obligation: codegen::codegen_fulfill_obligation,
1225 substitute_normalize_and_test_predicates,
1230 pub trait ExClauseFold<'tcx>
1232 Self: chalk_engine::context::Context + Clone,
1234 fn fold_ex_clause_with<F: TypeFolder<'tcx>>(
1235 ex_clause: &chalk_engine::ExClause<Self>,
1237 ) -> chalk_engine::ExClause<Self>;
1239 fn visit_ex_clause_with<V: TypeVisitor<'tcx>>(
1240 ex_clause: &chalk_engine::ExClause<Self>,
1245 pub trait ChalkContextLift<'tcx>
1247 Self: chalk_engine::context::Context + Clone,
1249 type LiftedExClause: Debug + 'tcx;
1250 type LiftedDelayedLiteral: Debug + 'tcx;
1251 type LiftedLiteral: Debug + 'tcx;
1253 fn lift_ex_clause_to_tcx(
1254 ex_clause: &chalk_engine::ExClause<Self>,
1256 ) -> Option<Self::LiftedExClause>;
1258 fn lift_delayed_literal_to_tcx(
1259 ex_clause: &chalk_engine::DelayedLiteral<Self>,
1261 ) -> Option<Self::LiftedDelayedLiteral>;
1263 fn lift_literal_to_tcx(
1264 ex_clause: &chalk_engine::Literal<Self>,
1266 ) -> Option<Self::LiftedLiteral>;