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
11 pub mod error_reporting;
25 use crate::infer::outlives::env::OutlivesEnvironment;
26 use crate::infer::{InferCtxt, SuppressRegionErrors};
27 use crate::middle::region;
28 use crate::mir::interpret::ErrorHandled;
29 use crate::ty::error::{ExpectedFound, TypeError};
30 use crate::ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
31 use crate::ty::subst::{InternalSubsts, SubstsRef};
32 use crate::ty::{self, AdtKind, GenericParamDefKind, List, ToPredicate, Ty, TyCtxt, WithConstness};
33 use crate::util::common::ErrorReported;
36 use rustc_hir::def_id::DefId;
37 use rustc_macros::HashStable;
38 use rustc_span::{Span, DUMMY_SP};
44 pub use self::FulfillmentErrorCode::*;
45 pub use self::ObligationCauseCode::*;
46 pub use self::SelectionError::*;
47 pub use self::Vtable::*;
49 pub use self::coherence::{add_placeholder_note, orphan_check, overlapping_impls};
50 pub use self::coherence::{OrphanCheckErr, OverlapResult};
51 pub use self::engine::{TraitEngine, TraitEngineExt};
52 pub use self::fulfill::{FulfillmentContext, PendingPredicateObligation};
53 pub use self::object_safety::astconv_object_safety_violations;
54 pub use self::object_safety::is_vtable_safe_method;
55 pub use self::object_safety::object_safety_violations;
56 pub use self::object_safety::MethodViolationCode;
57 pub use self::object_safety::ObjectSafetyViolation;
58 pub use self::on_unimplemented::{OnUnimplementedDirective, OnUnimplementedNote};
59 pub use self::project::MismatchedProjectionTypes;
60 pub use self::project::{normalize, normalize_projection_type, poly_project_and_unify_type};
61 pub use self::project::{Normalized, ProjectionCache, ProjectionCacheSnapshot, Reveal};
62 pub use self::select::{EvaluationCache, SelectionCache, SelectionContext};
63 pub use self::select::{EvaluationResult, IntercrateAmbiguityCause, OverflowError};
64 pub use self::specialize::find_associated_item;
65 pub use self::specialize::specialization_graph::FutureCompatOverlapError;
66 pub use self::specialize::specialization_graph::FutureCompatOverlapErrorKind;
67 pub use self::specialize::{specialization_graph, translate_substs, OverlapError};
68 pub use self::structural_match::search_for_structural_match_violation;
69 pub use self::structural_match::type_marked_structural;
70 pub use self::structural_match::NonStructuralMatchTy;
71 pub use self::util::{elaborate_predicates, elaborate_trait_ref, elaborate_trait_refs};
72 pub use self::util::{expand_trait_aliases, TraitAliasExpander};
74 get_vtable_index_of_object_method, impl_is_default, impl_item_is_final,
75 predicate_for_trait_def, upcast_choices,
78 supertrait_def_ids, supertraits, transitive_bounds, SupertraitDefIds, Supertraits,
81 pub use self::chalk_fulfill::{
82 CanonicalGoal as ChalkCanonicalGoal, FulfillmentContext as ChalkFulfillmentContext,
85 pub use self::FulfillmentErrorCode::*;
86 pub use self::ObligationCauseCode::*;
87 pub use self::SelectionError::*;
88 pub use self::Vtable::*;
90 /// Whether to enable bug compatibility with issue #43355.
91 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
92 pub enum IntercrateMode {
97 /// The mode that trait queries run in.
98 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
99 pub enum TraitQueryMode {
100 // Standard/un-canonicalized queries get accurate
101 // spans etc. passed in and hence can do reasonable
102 // error reporting on their own.
104 // Canonicalized queries get dummy spans and hence
105 // must generally propagate errors to
106 // pre-canonicalization callsites.
110 /// An `Obligation` represents some trait reference (e.g., `int: Eq`) for
111 /// which the vtable must be found. The process of finding a vtable is
112 /// called "resolving" the `Obligation`. This process consists of
113 /// either identifying an `impl` (e.g., `impl Eq for int`) that
114 /// provides the required vtable, or else finding a bound that is in
115 /// scope. The eventual result is usually a `Selection` (defined below).
116 #[derive(Clone, PartialEq, Eq, Hash)]
117 pub struct Obligation<'tcx, T> {
118 /// The reason we have to prove this thing.
119 pub cause: ObligationCause<'tcx>,
121 /// The environment in which we should prove this thing.
122 pub param_env: ty::ParamEnv<'tcx>,
124 /// The thing we are trying to prove.
127 /// If we started proving this as a result of trying to prove
128 /// something else, track the total depth to ensure termination.
129 /// If this goes over a certain threshold, we abort compilation --
130 /// in such cases, we can not say whether or not the predicate
131 /// holds for certain. Stupid halting problem; such a drag.
132 pub recursion_depth: usize,
135 pub type PredicateObligation<'tcx> = Obligation<'tcx, ty::Predicate<'tcx>>;
136 pub type TraitObligation<'tcx> = Obligation<'tcx, ty::PolyTraitPredicate<'tcx>>;
138 // `PredicateObligation` is used a lot. Make sure it doesn't unintentionally get bigger.
139 #[cfg(target_arch = "x86_64")]
140 static_assert_size!(PredicateObligation<'_>, 112);
142 /// The reason why we incurred this obligation; used for error reporting.
143 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
144 pub struct ObligationCause<'tcx> {
147 /// The ID of the fn body that triggered this obligation. This is
148 /// used for region obligations to determine the precise
149 /// environment in which the region obligation should be evaluated
150 /// (in particular, closures can add new assumptions). See the
151 /// field `region_obligations` of the `FulfillmentContext` for more
153 pub body_id: hir::HirId,
155 pub code: ObligationCauseCode<'tcx>,
158 impl ObligationCause<'_> {
159 pub fn span(&self, tcx: TyCtxt<'_>) -> Span {
161 ObligationCauseCode::CompareImplMethodObligation { .. }
162 | ObligationCauseCode::MainFunctionType
163 | ObligationCauseCode::StartFunctionType => tcx.sess.source_map().def_span(self.span),
164 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
173 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
174 pub enum ObligationCauseCode<'tcx> {
175 /// Not well classified or should be obvious from the span.
178 /// A slice or array is WF only if `T: Sized`.
181 /// A tuple is WF only if its middle elements are `Sized`.
184 /// This is the trait reference from the given projection.
185 ProjectionWf(ty::ProjectionTy<'tcx>),
187 /// In an impl of trait `X` for type `Y`, type `Y` must
188 /// also implement all supertraits of `X`.
189 ItemObligation(DefId),
191 /// Like `ItemObligation`, but with extra detail on the source of the obligation.
192 BindingObligation(DefId, Span),
194 /// A type like `&'a T` is WF only if `T: 'a`.
195 ReferenceOutlivesReferent(Ty<'tcx>),
197 /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
198 ObjectTypeBound(Ty<'tcx>, ty::Region<'tcx>),
200 /// Obligation incurred due to an object cast.
201 ObjectCastObligation(/* Object type */ Ty<'tcx>),
203 /// Obligation incurred due to a coercion.
209 /// Various cases where expressions must be `Sized` / `Copy` / etc.
210 /// `L = X` implies that `L` is `Sized`.
212 /// `(x1, .., xn)` must be `Sized`.
213 TupleInitializerSized,
214 /// `S { ... }` must be `Sized`.
215 StructInitializerSized,
216 /// Type of each variable must be `Sized`.
217 VariableType(hir::HirId),
218 /// Argument type must be `Sized`.
220 /// Return type must be `Sized`.
222 /// Yield type must be `Sized`.
224 /// `[T, ..n]` implies that `T` must be `Copy`.
225 /// If `true`, suggest `const_in_array_repeat_expressions` feature flag.
228 /// Types of fields (other than the last, except for packed structs) in a struct must be sized.
234 /// Constant expressions must be sized.
237 /// `static` items must have `Sync` type.
240 BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
242 ImplDerivedObligation(DerivedObligationCause<'tcx>),
244 /// Error derived when matching traits/impls; see ObligationCause for more details
245 CompareImplMethodObligation {
246 item_name: ast::Name,
247 impl_item_def_id: DefId,
248 trait_item_def_id: DefId,
251 /// Error derived when matching traits/impls; see ObligationCause for more details
252 CompareImplTypeObligation {
253 item_name: ast::Name,
254 impl_item_def_id: DefId,
255 trait_item_def_id: DefId,
258 /// Checking that this expression can be assigned where it needs to be
259 // FIXME(eddyb) #11161 is the original Expr required?
262 /// Computing common supertype in the arms of a match expression
263 MatchExpressionArm(Box<MatchExpressionArmCause<'tcx>>),
265 /// Type error arising from type checking a pattern against an expected type.
267 /// The span of the scrutinee or type expression which caused the `root_ty` type.
269 /// The root expected type induced by a scrutinee or type expression.
271 /// Whether the `Span` came from an expression or a type expression.
275 /// Constants in patterns must have `Structural` type.
276 ConstPatternStructural,
278 /// Computing common supertype in an if expression
279 IfExpression(Box<IfExpressionCause>),
281 /// Computing common supertype of an if expression with no else counter-part
282 IfExpressionWithNoElse,
284 /// `main` has wrong type
287 /// `start` has wrong type
290 /// Intrinsic has wrong type
296 /// `return` with no expression
299 /// `return` with an expression
300 ReturnValue(hir::HirId),
302 /// Return type of this function
305 /// Block implicit return
306 BlockTailExpression(hir::HirId),
308 /// #[feature(trivial_bounds)] is not enabled
311 AssocTypeBound(Box<AssocTypeBoundData>),
314 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
315 pub struct AssocTypeBoundData {
316 pub impl_span: Option<Span>,
318 pub bounds: Vec<Span>,
321 // `ObligationCauseCode` is used a lot. Make sure it doesn't unintentionally get bigger.
322 #[cfg(target_arch = "x86_64")]
323 static_assert_size!(ObligationCauseCode<'_>, 32);
325 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
326 pub struct MatchExpressionArmCause<'tcx> {
328 pub source: hir::MatchSource,
329 pub prior_arms: Vec<Span>,
330 pub last_ty: Ty<'tcx>,
331 pub scrut_hir_id: hir::HirId,
334 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
335 pub struct IfExpressionCause {
337 pub outer: Option<Span>,
338 pub semicolon: Option<Span>,
341 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
342 pub struct DerivedObligationCause<'tcx> {
343 /// The trait reference of the parent obligation that led to the
344 /// current obligation. Note that only trait obligations lead to
345 /// derived obligations, so we just store the trait reference here
347 parent_trait_ref: ty::PolyTraitRef<'tcx>,
349 /// The parent trait had this cause.
350 parent_code: Rc<ObligationCauseCode<'tcx>>,
353 pub type Obligations<'tcx, O> = Vec<Obligation<'tcx, O>>;
354 pub type PredicateObligations<'tcx> = Vec<PredicateObligation<'tcx>>;
355 pub type TraitObligations<'tcx> = Vec<TraitObligation<'tcx>>;
357 /// The following types:
365 /// * `InEnvironment`,
366 /// are used for representing the trait system in the form of
367 /// logic programming clauses. They are part of the interface
368 /// for the chalk SLG solver.
369 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
370 pub enum WhereClause<'tcx> {
371 Implemented(ty::TraitPredicate<'tcx>),
372 ProjectionEq(ty::ProjectionPredicate<'tcx>),
373 RegionOutlives(ty::RegionOutlivesPredicate<'tcx>),
374 TypeOutlives(ty::TypeOutlivesPredicate<'tcx>),
377 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
378 pub enum WellFormed<'tcx> {
379 Trait(ty::TraitPredicate<'tcx>),
383 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
384 pub enum FromEnv<'tcx> {
385 Trait(ty::TraitPredicate<'tcx>),
389 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
390 pub enum DomainGoal<'tcx> {
391 Holds(WhereClause<'tcx>),
392 WellFormed(WellFormed<'tcx>),
393 FromEnv(FromEnv<'tcx>),
394 Normalize(ty::ProjectionPredicate<'tcx>),
397 pub type PolyDomainGoal<'tcx> = ty::Binder<DomainGoal<'tcx>>;
399 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
400 pub enum QuantifierKind {
405 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
406 pub enum GoalKind<'tcx> {
407 Implies(Clauses<'tcx>, Goal<'tcx>),
408 And(Goal<'tcx>, Goal<'tcx>),
410 DomainGoal(DomainGoal<'tcx>),
411 Quantified(QuantifierKind, ty::Binder<Goal<'tcx>>),
412 Subtype(Ty<'tcx>, Ty<'tcx>),
416 pub type Goal<'tcx> = &'tcx GoalKind<'tcx>;
418 pub type Goals<'tcx> = &'tcx List<Goal<'tcx>>;
420 impl<'tcx> DomainGoal<'tcx> {
421 pub fn into_goal(self) -> GoalKind<'tcx> {
422 GoalKind::DomainGoal(self)
425 pub fn into_program_clause(self) -> ProgramClause<'tcx> {
428 hypotheses: ty::List::empty(),
429 category: ProgramClauseCategory::Other,
434 impl<'tcx> GoalKind<'tcx> {
435 pub fn from_poly_domain_goal(
436 domain_goal: PolyDomainGoal<'tcx>,
438 ) -> GoalKind<'tcx> {
439 match domain_goal.no_bound_vars() {
440 Some(p) => p.into_goal(),
441 None => GoalKind::Quantified(
442 QuantifierKind::Universal,
443 domain_goal.map_bound(|p| tcx.mk_goal(p.into_goal())),
449 /// This matches the definition from Page 7 of "A Proof Procedure for the Logic of Hereditary
450 /// Harrop Formulas".
451 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
452 pub enum Clause<'tcx> {
453 Implies(ProgramClause<'tcx>),
454 ForAll(ty::Binder<ProgramClause<'tcx>>),
458 pub fn category(self) -> ProgramClauseCategory {
460 Clause::Implies(clause) => clause.category,
461 Clause::ForAll(clause) => clause.skip_binder().category,
466 /// Multiple clauses.
467 pub type Clauses<'tcx> = &'tcx List<Clause<'tcx>>;
469 /// A "program clause" has the form `D :- G1, ..., Gn`. It is saying
470 /// that the domain goal `D` is true if `G1...Gn` are provable. This
471 /// is equivalent to the implication `G1..Gn => D`; we usually write
472 /// it with the reverse implication operator `:-` to emphasize the way
473 /// that programs are actually solved (via backchaining, which starts
474 /// with the goal to solve and proceeds from there).
475 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
476 pub struct ProgramClause<'tcx> {
477 /// This goal will be considered true ...
478 pub goal: DomainGoal<'tcx>,
480 /// ... if we can prove these hypotheses (there may be no hypotheses at all):
481 pub hypotheses: Goals<'tcx>,
483 /// Useful for filtering clauses.
484 pub category: ProgramClauseCategory,
487 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
488 pub enum ProgramClauseCategory {
494 /// A set of clauses that we assume to be true.
495 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
496 pub struct Environment<'tcx> {
497 pub clauses: Clauses<'tcx>,
500 impl Environment<'tcx> {
501 pub fn with<G>(self, goal: G) -> InEnvironment<'tcx, G> {
502 InEnvironment { environment: self, goal }
506 /// Something (usually a goal), along with an environment.
507 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
508 pub struct InEnvironment<'tcx, G> {
509 pub environment: Environment<'tcx>,
513 pub type Selection<'tcx> = Vtable<'tcx, PredicateObligation<'tcx>>;
515 #[derive(Clone, Debug, TypeFoldable)]
516 pub enum SelectionError<'tcx> {
518 OutputTypeParameterMismatch(
519 ty::PolyTraitRef<'tcx>,
520 ty::PolyTraitRef<'tcx>,
521 ty::error::TypeError<'tcx>,
523 TraitNotObjectSafe(DefId),
524 ConstEvalFailure(ErrorHandled),
528 pub struct FulfillmentError<'tcx> {
529 pub obligation: PredicateObligation<'tcx>,
530 pub code: FulfillmentErrorCode<'tcx>,
531 /// Diagnostics only: we opportunistically change the `code.span` when we encounter an
532 /// obligation error caused by a call argument. When this is the case, we also signal that in
533 /// this field to ensure accuracy of suggestions.
534 pub points_at_arg_span: bool,
538 pub enum FulfillmentErrorCode<'tcx> {
539 CodeSelectionError(SelectionError<'tcx>),
540 CodeProjectionError(MismatchedProjectionTypes<'tcx>),
541 CodeSubtypeError(ExpectedFound<Ty<'tcx>>, TypeError<'tcx>), // always comes from a SubtypePredicate
545 /// When performing resolution, it is typically the case that there
546 /// can be one of three outcomes:
548 /// - `Ok(Some(r))`: success occurred with result `r`
549 /// - `Ok(None)`: could not definitely determine anything, usually due
550 /// to inconclusive type inference.
551 /// - `Err(e)`: error `e` occurred
552 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
554 /// Given the successful resolution of an obligation, the `Vtable`
555 /// indicates where the vtable comes from. Note that while we call this
556 /// a "vtable", it does not necessarily indicate dynamic dispatch at
557 /// runtime. `Vtable` instances just tell the compiler where to find
558 /// methods, but in generic code those methods are typically statically
559 /// dispatched -- only when an object is constructed is a `Vtable`
560 /// instance reified into an actual vtable.
562 /// For example, the vtable may be tied to a specific impl (case A),
563 /// or it may be relative to some bound that is in scope (case B).
566 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
567 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
568 /// impl Clone for int { ... } // Impl_3
570 /// fn foo<T:Clone>(concrete: Option<Box<int>>,
572 /// mixed: Option<T>) {
574 /// // Case A: Vtable points at a specific impl. Only possible when
575 /// // type is concretely known. If the impl itself has bounded
576 /// // type parameters, Vtable will carry resolutions for those as well:
577 /// concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
579 /// // Case B: Vtable must be provided by caller. This applies when
580 /// // type is a type parameter.
581 /// param.clone(); // VtableParam
583 /// // Case C: A mix of cases A and B.
584 /// mixed.clone(); // Vtable(Impl_1, [VtableParam])
588 /// ### The type parameter `N`
590 /// See explanation on `VtableImplData`.
591 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
592 pub enum Vtable<'tcx, N> {
593 /// Vtable identifying a particular impl.
594 VtableImpl(VtableImplData<'tcx, N>),
596 /// Vtable for auto trait implementations.
597 /// This carries the information and nested obligations with regards
598 /// to an auto implementation for a trait `Trait`. The nested obligations
599 /// ensure the trait implementation holds for all the constituent types.
600 VtableAutoImpl(VtableAutoImplData<N>),
602 /// Successful resolution to an obligation provided by the caller
603 /// for some type parameter. The `Vec<N>` represents the
604 /// obligations incurred from normalizing the where-clause (if
608 /// Virtual calls through an object.
609 VtableObject(VtableObjectData<'tcx, N>),
611 /// Successful resolution for a builtin trait.
612 VtableBuiltin(VtableBuiltinData<N>),
614 /// Vtable automatically generated for a closure. The `DefId` is the ID
615 /// of the closure expression. This is a `VtableImpl` in spirit, but the
616 /// impl is generated by the compiler and does not appear in the source.
617 VtableClosure(VtableClosureData<'tcx, N>),
619 /// Same as above, but for a function pointer type with the given signature.
620 VtableFnPointer(VtableFnPointerData<'tcx, N>),
622 /// Vtable automatically generated for a generator.
623 VtableGenerator(VtableGeneratorData<'tcx, N>),
625 /// Vtable for a trait alias.
626 VtableTraitAlias(VtableTraitAliasData<'tcx, N>),
629 /// Identifies a particular impl in the source, along with a set of
630 /// substitutions from the impl's type/lifetime parameters. The
631 /// `nested` vector corresponds to the nested obligations attached to
632 /// the impl's type parameters.
634 /// The type parameter `N` indicates the type used for "nested
635 /// obligations" that are required by the impl. During type-check, this
636 /// is `Obligation`, as one might expect. During codegen, however, this
637 /// is `()`, because codegen only requires a shallow resolution of an
638 /// impl, and nested obligations are satisfied later.
639 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
640 pub struct VtableImplData<'tcx, N> {
641 pub impl_def_id: DefId,
642 pub substs: SubstsRef<'tcx>,
646 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
647 pub struct VtableGeneratorData<'tcx, N> {
648 pub generator_def_id: DefId,
649 pub substs: SubstsRef<'tcx>,
650 /// Nested obligations. This can be non-empty if the generator
651 /// signature contains associated types.
655 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
656 pub struct VtableClosureData<'tcx, N> {
657 pub closure_def_id: DefId,
658 pub substs: SubstsRef<'tcx>,
659 /// Nested obligations. This can be non-empty if the closure
660 /// signature contains associated types.
664 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
665 pub struct VtableAutoImplData<N> {
666 pub trait_def_id: DefId,
670 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
671 pub struct VtableBuiltinData<N> {
675 /// A vtable for some object-safe trait `Foo` automatically derived
676 /// for the object type `Foo`.
677 #[derive(PartialEq, Eq, Clone, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
678 pub struct VtableObjectData<'tcx, N> {
679 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
680 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
682 /// The vtable is formed by concatenating together the method lists of
683 /// the base object trait and all supertraits; this is the start of
684 /// `upcast_trait_ref`'s methods in that vtable.
685 pub vtable_base: usize,
690 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
691 pub struct VtableFnPointerData<'tcx, N> {
696 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
697 pub struct VtableTraitAliasData<'tcx, N> {
698 pub alias_def_id: DefId,
699 pub substs: SubstsRef<'tcx>,
703 /// Creates predicate obligations from the generic bounds.
704 pub fn predicates_for_generics<'tcx>(
705 cause: ObligationCause<'tcx>,
706 param_env: ty::ParamEnv<'tcx>,
707 generic_bounds: &ty::InstantiatedPredicates<'tcx>,
708 ) -> PredicateObligations<'tcx> {
709 util::predicates_for_generics(cause, 0, param_env, generic_bounds)
712 /// Determines whether the type `ty` is known to meet `bound` and
713 /// returns true if so. Returns false if `ty` either does not meet
714 /// `bound` or is not known to meet bound (note that this is
715 /// conservative towards *no impl*, which is the opposite of the
716 /// `evaluate` methods).
717 pub fn type_known_to_meet_bound_modulo_regions<'a, 'tcx>(
718 infcx: &InferCtxt<'a, 'tcx>,
719 param_env: ty::ParamEnv<'tcx>,
725 "type_known_to_meet_bound_modulo_regions(ty={:?}, bound={:?})",
727 infcx.tcx.def_path_str(def_id)
730 let trait_ref = ty::TraitRef { def_id, substs: infcx.tcx.mk_substs_trait(ty, &[]) };
731 let obligation = Obligation {
733 cause: ObligationCause::misc(span, hir::DUMMY_HIR_ID),
735 predicate: trait_ref.without_const().to_predicate(),
738 let result = infcx.predicate_must_hold_modulo_regions(&obligation);
740 "type_known_to_meet_ty={:?} bound={} => {:?}",
742 infcx.tcx.def_path_str(def_id),
746 if result && (ty.has_infer_types() || ty.has_closure_types()) {
747 // Because of inference "guessing", selection can sometimes claim
748 // to succeed while the success requires a guess. To ensure
749 // this function's result remains infallible, we must confirm
750 // that guess. While imperfect, I believe this is sound.
752 // The handling of regions in this area of the code is terrible,
753 // see issue #29149. We should be able to improve on this with
755 let mut fulfill_cx = FulfillmentContext::new_ignoring_regions();
757 // We can use a dummy node-id here because we won't pay any mind
758 // to region obligations that arise (there shouldn't really be any
760 let cause = ObligationCause::misc(span, hir::DUMMY_HIR_ID);
762 fulfill_cx.register_bound(infcx, param_env, ty, def_id, cause);
764 // Note: we only assume something is `Copy` if we can
765 // *definitively* show that it implements `Copy`. Otherwise,
766 // assume it is move; linear is always ok.
767 match fulfill_cx.select_all_or_error(infcx) {
770 "type_known_to_meet_bound_modulo_regions: ty={:?} bound={} success",
772 infcx.tcx.def_path_str(def_id)
778 "type_known_to_meet_bound_modulo_regions: ty={:?} bound={} errors={:?}",
780 infcx.tcx.def_path_str(def_id),
791 fn do_normalize_predicates<'tcx>(
793 region_context: DefId,
794 cause: ObligationCause<'tcx>,
795 elaborated_env: ty::ParamEnv<'tcx>,
796 predicates: Vec<ty::Predicate<'tcx>>,
797 ) -> Result<Vec<ty::Predicate<'tcx>>, ErrorReported> {
799 "do_normalize_predicates(predicates={:?}, region_context={:?}, cause={:?})",
800 predicates, region_context, cause,
802 let span = cause.span;
803 tcx.infer_ctxt().enter(|infcx| {
804 // FIXME. We should really... do something with these region
805 // obligations. But this call just continues the older
806 // behavior (i.e., doesn't cause any new bugs), and it would
807 // take some further refactoring to actually solve them. In
808 // particular, we would have to handle implied bounds
809 // properly, and that code is currently largely confined to
810 // regionck (though I made some efforts to extract it
813 // @arielby: In any case, these obligations are checked
814 // by wfcheck anyway, so I'm not sure we have to check
815 // them here too, and we will remove this function when
816 // we move over to lazy normalization *anyway*.
817 let fulfill_cx = FulfillmentContext::new_ignoring_regions();
819 match fully_normalize(&infcx, fulfill_cx, cause, elaborated_env, &predicates) {
820 Ok(predicates) => predicates,
822 infcx.report_fulfillment_errors(&errors, None, false);
823 return Err(ErrorReported);
827 debug!("do_normalize_predictes: normalized predicates = {:?}", predicates);
829 let region_scope_tree = region::ScopeTree::default();
831 // We can use the `elaborated_env` here; the region code only
832 // cares about declarations like `'a: 'b`.
833 let outlives_env = OutlivesEnvironment::new(elaborated_env);
835 infcx.resolve_regions_and_report_errors(
839 SuppressRegionErrors::default(),
842 let predicates = match infcx.fully_resolve(&predicates) {
843 Ok(predicates) => predicates,
845 // If we encounter a fixup error, it means that some type
846 // variable wound up unconstrained. I actually don't know
847 // if this can happen, and I certainly don't expect it to
848 // happen often, but if it did happen it probably
849 // represents a legitimate failure due to some kind of
850 // unconstrained variable, and it seems better not to ICE,
851 // all things considered.
852 tcx.sess.span_err(span, &fixup_err.to_string());
853 return Err(ErrorReported);
856 if predicates.has_local_value() {
857 // FIXME: shouldn't we, you know, actually report an error here? or an ICE?
865 // FIXME: this is gonna need to be removed ...
866 /// Normalizes the parameter environment, reporting errors if they occur.
867 pub fn normalize_param_env_or_error<'tcx>(
869 region_context: DefId,
870 unnormalized_env: ty::ParamEnv<'tcx>,
871 cause: ObligationCause<'tcx>,
872 ) -> ty::ParamEnv<'tcx> {
873 // I'm not wild about reporting errors here; I'd prefer to
874 // have the errors get reported at a defined place (e.g.,
875 // during typeck). Instead I have all parameter
876 // environments, in effect, going through this function
877 // and hence potentially reporting errors. This ensures of
878 // course that we never forget to normalize (the
879 // alternative seemed like it would involve a lot of
880 // manual invocations of this fn -- and then we'd have to
881 // deal with the errors at each of those sites).
883 // In any case, in practice, typeck constructs all the
884 // parameter environments once for every fn as it goes,
885 // and errors will get reported then; so after typeck we
886 // can be sure that no errors should occur.
889 "normalize_param_env_or_error(region_context={:?}, unnormalized_env={:?}, cause={:?})",
890 region_context, unnormalized_env, cause
893 let mut predicates: Vec<_> =
894 util::elaborate_predicates(tcx, unnormalized_env.caller_bounds.to_vec()).collect();
896 debug!("normalize_param_env_or_error: elaborated-predicates={:?}", predicates);
898 let elaborated_env = ty::ParamEnv::new(
899 tcx.intern_predicates(&predicates),
900 unnormalized_env.reveal,
901 unnormalized_env.def_id,
904 // HACK: we are trying to normalize the param-env inside *itself*. The problem is that
905 // normalization expects its param-env to be already normalized, which means we have
908 // The way we handle this is by normalizing the param-env inside an unnormalized version
909 // of the param-env, which means that if the param-env contains unnormalized projections,
910 // we'll have some normalization failures. This is unfortunate.
912 // Lazy normalization would basically handle this by treating just the
913 // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
915 // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
916 // types, so to make the situation less bad, we normalize all the predicates *but*
917 // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
918 // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
920 // This works fairly well because trait matching does not actually care about param-env
921 // TypeOutlives predicates - these are normally used by regionck.
922 let outlives_predicates: Vec<_> = predicates
923 .drain_filter(|predicate| match predicate {
924 ty::Predicate::TypeOutlives(..) => true,
930 "normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
931 predicates, outlives_predicates
933 let non_outlives_predicates = match do_normalize_predicates(
940 Ok(predicates) => predicates,
941 // An unnormalized env is better than nothing.
942 Err(ErrorReported) => {
943 debug!("normalize_param_env_or_error: errored resolving non-outlives predicates");
944 return elaborated_env;
948 debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates);
950 // Not sure whether it is better to include the unnormalized TypeOutlives predicates
951 // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
952 // predicates here anyway. Keeping them here anyway because it seems safer.
953 let outlives_env: Vec<_> =
954 non_outlives_predicates.iter().chain(&outlives_predicates).cloned().collect();
956 ty::ParamEnv::new(tcx.intern_predicates(&outlives_env), unnormalized_env.reveal, None);
957 let outlives_predicates = match do_normalize_predicates(
964 Ok(predicates) => predicates,
965 // An unnormalized env is better than nothing.
966 Err(ErrorReported) => {
967 debug!("normalize_param_env_or_error: errored resolving outlives predicates");
968 return elaborated_env;
971 debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates);
973 let mut predicates = non_outlives_predicates;
974 predicates.extend(outlives_predicates);
975 debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
977 tcx.intern_predicates(&predicates),
978 unnormalized_env.reveal,
979 unnormalized_env.def_id,
983 pub fn fully_normalize<'a, 'tcx, T>(
984 infcx: &InferCtxt<'a, 'tcx>,
985 mut fulfill_cx: FulfillmentContext<'tcx>,
986 cause: ObligationCause<'tcx>,
987 param_env: ty::ParamEnv<'tcx>,
989 ) -> Result<T, Vec<FulfillmentError<'tcx>>>
991 T: TypeFoldable<'tcx>,
993 debug!("fully_normalize_with_fulfillcx(value={:?})", value);
994 let selcx = &mut SelectionContext::new(infcx);
995 let Normalized { value: normalized_value, obligations } =
996 project::normalize(selcx, param_env, cause, value);
998 "fully_normalize: normalized_value={:?} obligations={:?}",
999 normalized_value, obligations
1001 for obligation in obligations {
1002 fulfill_cx.register_predicate_obligation(selcx.infcx(), obligation);
1005 debug!("fully_normalize: select_all_or_error start");
1006 fulfill_cx.select_all_or_error(infcx)?;
1007 debug!("fully_normalize: select_all_or_error complete");
1008 let resolved_value = infcx.resolve_vars_if_possible(&normalized_value);
1009 debug!("fully_normalize: resolved_value={:?}", resolved_value);
1013 /// Normalizes the predicates and checks whether they hold in an empty
1014 /// environment. If this returns false, then either normalize
1015 /// encountered an error or one of the predicates did not hold. Used
1016 /// when creating vtables to check for unsatisfiable methods.
1017 pub fn normalize_and_test_predicates<'tcx>(
1019 predicates: Vec<ty::Predicate<'tcx>>,
1021 debug!("normalize_and_test_predicates(predicates={:?})", predicates);
1023 let result = tcx.infer_ctxt().enter(|infcx| {
1024 let param_env = ty::ParamEnv::reveal_all();
1025 let mut selcx = SelectionContext::new(&infcx);
1026 let mut fulfill_cx = FulfillmentContext::new();
1027 let cause = ObligationCause::dummy();
1028 let Normalized { value: predicates, obligations } =
1029 normalize(&mut selcx, param_env, cause.clone(), &predicates);
1030 for obligation in obligations {
1031 fulfill_cx.register_predicate_obligation(&infcx, obligation);
1033 for predicate in predicates {
1034 let obligation = Obligation::new(cause.clone(), param_env, predicate);
1035 fulfill_cx.register_predicate_obligation(&infcx, obligation);
1038 fulfill_cx.select_all_or_error(&infcx).is_ok()
1040 debug!("normalize_and_test_predicates(predicates={:?}) = {:?}", predicates, result);
1044 fn substitute_normalize_and_test_predicates<'tcx>(
1046 key: (DefId, SubstsRef<'tcx>),
1048 debug!("substitute_normalize_and_test_predicates(key={:?})", key);
1050 let predicates = tcx.predicates_of(key.0).instantiate(tcx, key.1).predicates;
1051 let result = normalize_and_test_predicates(tcx, predicates);
1053 debug!("substitute_normalize_and_test_predicates(key={:?}) = {:?}", key, result);
1057 /// Given a trait `trait_ref`, iterates the vtable entries
1058 /// that come from `trait_ref`, including its supertraits.
1059 #[inline] // FIXME(#35870): avoid closures being unexported due to `impl Trait`.
1060 fn vtable_methods<'tcx>(
1062 trait_ref: ty::PolyTraitRef<'tcx>,
1063 ) -> &'tcx [Option<(DefId, SubstsRef<'tcx>)>] {
1064 debug!("vtable_methods({:?})", trait_ref);
1066 tcx.arena.alloc_from_iter(supertraits(tcx, trait_ref).flat_map(move |trait_ref| {
1067 let trait_methods = tcx
1068 .associated_items(trait_ref.def_id())
1069 .filter(|item| item.kind == ty::AssocKind::Method);
1071 // Now list each method's DefId and InternalSubsts (for within its trait).
1072 // If the method can never be called from this object, produce None.
1073 trait_methods.map(move |trait_method| {
1074 debug!("vtable_methods: trait_method={:?}", trait_method);
1075 let def_id = trait_method.def_id;
1077 // Some methods cannot be called on an object; skip those.
1078 if !is_vtable_safe_method(tcx, trait_ref.def_id(), &trait_method) {
1079 debug!("vtable_methods: not vtable safe");
1083 // The method may have some early-bound lifetimes; add regions for those.
1084 let substs = trait_ref.map_bound(|trait_ref| {
1085 InternalSubsts::for_item(tcx, def_id, |param, _| match param.kind {
1086 GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(),
1087 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const => {
1088 trait_ref.substs[param.index as usize]
1093 // The trait type may have higher-ranked lifetimes in it;
1094 // erase them if they appear, so that we get the type
1095 // at some particular call site.
1097 tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &substs);
1099 // It's possible that the method relies on where-clauses that
1100 // do not hold for this particular set of type parameters.
1101 // Note that this method could then never be called, so we
1102 // do not want to try and codegen it, in that case (see #23435).
1103 let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs);
1104 if !normalize_and_test_predicates(tcx, predicates.predicates) {
1105 debug!("vtable_methods: predicates do not hold");
1109 Some((def_id, substs))
1114 impl<'tcx, O> Obligation<'tcx, O> {
1116 cause: ObligationCause<'tcx>,
1117 param_env: ty::ParamEnv<'tcx>,
1119 ) -> Obligation<'tcx, O> {
1120 Obligation { cause, param_env, recursion_depth: 0, predicate }
1124 cause: ObligationCause<'tcx>,
1125 recursion_depth: usize,
1126 param_env: ty::ParamEnv<'tcx>,
1128 ) -> Obligation<'tcx, O> {
1129 Obligation { cause, param_env, recursion_depth, predicate }
1134 body_id: hir::HirId,
1135 param_env: ty::ParamEnv<'tcx>,
1137 ) -> Obligation<'tcx, O> {
1138 Obligation::new(ObligationCause::misc(span, body_id), param_env, trait_ref)
1141 pub fn with<P>(&self, value: P) -> Obligation<'tcx, P> {
1143 cause: self.cause.clone(),
1144 param_env: self.param_env,
1145 recursion_depth: self.recursion_depth,
1151 impl<'tcx> ObligationCause<'tcx> {
1155 body_id: hir::HirId,
1156 code: ObligationCauseCode<'tcx>,
1157 ) -> ObligationCause<'tcx> {
1158 ObligationCause { span, body_id, code }
1161 pub fn misc(span: Span, body_id: hir::HirId) -> ObligationCause<'tcx> {
1162 ObligationCause { span, body_id, code: MiscObligation }
1165 pub fn dummy() -> ObligationCause<'tcx> {
1166 ObligationCause { span: DUMMY_SP, body_id: hir::CRATE_HIR_ID, code: MiscObligation }
1170 impl ObligationCauseCode<'_> {
1171 // Return the base obligation, ignoring derived obligations.
1172 pub fn peel_derives(&self) -> &Self {
1173 let mut base_cause = self;
1174 while let BuiltinDerivedObligation(cause) | ImplDerivedObligation(cause) = base_cause {
1175 base_cause = &cause.parent_code;
1181 impl<'tcx, N> Vtable<'tcx, N> {
1182 pub fn nested_obligations(self) -> Vec<N> {
1184 VtableImpl(i) => i.nested,
1185 VtableParam(n) => n,
1186 VtableBuiltin(i) => i.nested,
1187 VtableAutoImpl(d) => d.nested,
1188 VtableClosure(c) => c.nested,
1189 VtableGenerator(c) => c.nested,
1190 VtableObject(d) => d.nested,
1191 VtableFnPointer(d) => d.nested,
1192 VtableTraitAlias(d) => d.nested,
1196 pub fn map<M, F>(self, f: F) -> Vtable<'tcx, M>
1201 VtableImpl(i) => VtableImpl(VtableImplData {
1202 impl_def_id: i.impl_def_id,
1204 nested: i.nested.into_iter().map(f).collect(),
1206 VtableParam(n) => VtableParam(n.into_iter().map(f).collect()),
1207 VtableBuiltin(i) => {
1208 VtableBuiltin(VtableBuiltinData { nested: i.nested.into_iter().map(f).collect() })
1210 VtableObject(o) => VtableObject(VtableObjectData {
1211 upcast_trait_ref: o.upcast_trait_ref,
1212 vtable_base: o.vtable_base,
1213 nested: o.nested.into_iter().map(f).collect(),
1215 VtableAutoImpl(d) => VtableAutoImpl(VtableAutoImplData {
1216 trait_def_id: d.trait_def_id,
1217 nested: d.nested.into_iter().map(f).collect(),
1219 VtableClosure(c) => VtableClosure(VtableClosureData {
1220 closure_def_id: c.closure_def_id,
1222 nested: c.nested.into_iter().map(f).collect(),
1224 VtableGenerator(c) => VtableGenerator(VtableGeneratorData {
1225 generator_def_id: c.generator_def_id,
1227 nested: c.nested.into_iter().map(f).collect(),
1229 VtableFnPointer(p) => VtableFnPointer(VtableFnPointerData {
1231 nested: p.nested.into_iter().map(f).collect(),
1233 VtableTraitAlias(d) => VtableTraitAlias(VtableTraitAliasData {
1234 alias_def_id: d.alias_def_id,
1236 nested: d.nested.into_iter().map(f).collect(),
1242 impl<'tcx> FulfillmentError<'tcx> {
1244 obligation: PredicateObligation<'tcx>,
1245 code: FulfillmentErrorCode<'tcx>,
1246 ) -> FulfillmentError<'tcx> {
1247 FulfillmentError { obligation: obligation, code: code, points_at_arg_span: false }
1251 impl<'tcx> TraitObligation<'tcx> {
1252 fn self_ty(&self) -> ty::Binder<Ty<'tcx>> {
1253 self.predicate.map_bound(|p| p.self_ty())
1257 pub fn provide(providers: &mut ty::query::Providers<'_>) {
1258 misc::provide(providers);
1259 *providers = ty::query::Providers {
1260 is_object_safe: object_safety::is_object_safe_provider,
1261 specialization_graph_of: specialize::specialization_graph_provider,
1262 specializes: specialize::specializes,
1263 codegen_fulfill_obligation: codegen::codegen_fulfill_obligation,
1265 substitute_normalize_and_test_predicates,
1270 pub trait ExClauseFold<'tcx>
1272 Self: chalk_engine::context::Context + Clone,
1274 fn fold_ex_clause_with<F: TypeFolder<'tcx>>(
1275 ex_clause: &chalk_engine::ExClause<Self>,
1277 ) -> chalk_engine::ExClause<Self>;
1279 fn visit_ex_clause_with<V: TypeVisitor<'tcx>>(
1280 ex_clause: &chalk_engine::ExClause<Self>,
1285 pub trait ChalkContextLift<'tcx>
1287 Self: chalk_engine::context::Context + Clone,
1289 type LiftedExClause: Debug + 'tcx;
1290 type LiftedDelayedLiteral: Debug + 'tcx;
1291 type LiftedLiteral: Debug + 'tcx;
1293 fn lift_ex_clause_to_tcx(
1294 ex_clause: &chalk_engine::ExClause<Self>,
1296 ) -> Option<Self::LiftedExClause>;
1298 fn lift_delayed_literal_to_tcx(
1299 ex_clause: &chalk_engine::DelayedLiteral<Self>,
1301 ) -> Option<Self::LiftedDelayedLiteral>;
1303 fn lift_literal_to_tcx(
1304 ex_clause: &chalk_engine::Literal<Self>,
1306 ) -> Option<Self::LiftedLiteral>;