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;
23 use crate::infer::outlives::env::OutlivesEnvironment;
24 use crate::infer::{InferCtxt, SuppressRegionErrors};
25 use crate::middle::region;
26 use crate::mir::interpret::ErrorHandled;
27 use crate::ty::error::{ExpectedFound, TypeError};
28 use crate::ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
29 use crate::ty::subst::{InternalSubsts, SubstsRef};
30 use crate::ty::{self, AdtKind, GenericParamDefKind, List, ToPredicate, Ty, TyCtxt};
31 use crate::util::common::ErrorReported;
34 use rustc_hir::def_id::DefId;
35 use rustc_macros::HashStable;
36 use rustc_span::{Span, DUMMY_SP};
42 pub use self::FulfillmentErrorCode::*;
43 pub use self::ObligationCauseCode::*;
44 pub use self::SelectionError::*;
45 pub use self::Vtable::*;
47 pub use self::coherence::{add_placeholder_note, orphan_check, overlapping_impls};
48 pub use self::coherence::{OrphanCheckErr, OverlapResult};
49 pub use self::engine::{TraitEngine, TraitEngineExt};
50 pub use self::fulfill::{FulfillmentContext, PendingPredicateObligation};
51 pub use self::object_safety::astconv_object_safety_violations;
52 pub use self::object_safety::is_vtable_safe_method;
53 pub use self::object_safety::object_safety_violations;
54 pub use self::object_safety::MethodViolationCode;
55 pub use self::object_safety::ObjectSafetyViolation;
56 pub use self::on_unimplemented::{OnUnimplementedDirective, OnUnimplementedNote};
57 pub use self::project::MismatchedProjectionTypes;
58 pub use self::project::{normalize, normalize_projection_type, poly_project_and_unify_type};
59 pub use self::project::{Normalized, ProjectionCache, ProjectionCacheSnapshot, Reveal};
60 pub use self::select::{EvaluationCache, SelectionCache, SelectionContext};
61 pub use self::select::{EvaluationResult, IntercrateAmbiguityCause, OverflowError};
62 pub use self::specialize::find_associated_item;
63 pub use self::specialize::specialization_graph::FutureCompatOverlapError;
64 pub use self::specialize::specialization_graph::FutureCompatOverlapErrorKind;
65 pub use self::specialize::{specialization_graph, translate_substs, OverlapError};
66 pub use self::util::{elaborate_predicates, elaborate_trait_ref, elaborate_trait_refs};
67 pub use self::util::{expand_trait_aliases, TraitAliasExpander};
69 get_vtable_index_of_object_method, impl_is_default, impl_item_is_final,
70 predicate_for_trait_def, upcast_choices,
73 supertrait_def_ids, supertraits, transitive_bounds, SupertraitDefIds, Supertraits,
76 pub use self::chalk_fulfill::{
77 CanonicalGoal as ChalkCanonicalGoal, FulfillmentContext as ChalkFulfillmentContext,
80 pub use self::FulfillmentErrorCode::*;
81 pub use self::ObligationCauseCode::*;
82 pub use self::SelectionError::*;
83 pub use self::Vtable::*;
85 /// Whether to enable bug compatibility with issue #43355.
86 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
87 pub enum IntercrateMode {
92 /// The mode that trait queries run in.
93 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
94 pub enum TraitQueryMode {
95 // Standard/un-canonicalized queries get accurate
96 // spans etc. passed in and hence can do reasonable
97 // error reporting on their own.
99 // Canonicalized queries get dummy spans and hence
100 // must generally propagate errors to
101 // pre-canonicalization callsites.
105 /// An `Obligation` represents some trait reference (e.g., `int: Eq`) for
106 /// which the vtable must be found. The process of finding a vtable is
107 /// called "resolving" the `Obligation`. This process consists of
108 /// either identifying an `impl` (e.g., `impl Eq for int`) that
109 /// provides the required vtable, or else finding a bound that is in
110 /// scope. The eventual result is usually a `Selection` (defined below).
111 #[derive(Clone, PartialEq, Eq, Hash)]
112 pub struct Obligation<'tcx, T> {
113 /// The reason we have to prove this thing.
114 pub cause: ObligationCause<'tcx>,
116 /// The environment in which we should prove this thing.
117 pub param_env: ty::ParamEnv<'tcx>,
119 /// The thing we are trying to prove.
122 /// If we started proving this as a result of trying to prove
123 /// something else, track the total depth to ensure termination.
124 /// If this goes over a certain threshold, we abort compilation --
125 /// in such cases, we can not say whether or not the predicate
126 /// holds for certain. Stupid halting problem; such a drag.
127 pub recursion_depth: usize,
130 pub type PredicateObligation<'tcx> = Obligation<'tcx, ty::Predicate<'tcx>>;
131 pub type TraitObligation<'tcx> = Obligation<'tcx, ty::PolyTraitPredicate<'tcx>>;
133 // `PredicateObligation` is used a lot. Make sure it doesn't unintentionally get bigger.
134 #[cfg(target_arch = "x86_64")]
135 static_assert_size!(PredicateObligation<'_>, 112);
137 /// The reason why we incurred this obligation; used for error reporting.
138 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
139 pub struct ObligationCause<'tcx> {
142 /// The ID of the fn body that triggered this obligation. This is
143 /// used for region obligations to determine the precise
144 /// environment in which the region obligation should be evaluated
145 /// (in particular, closures can add new assumptions). See the
146 /// field `region_obligations` of the `FulfillmentContext` for more
148 pub body_id: hir::HirId,
150 pub code: ObligationCauseCode<'tcx>,
153 impl<'tcx> ObligationCause<'tcx> {
154 pub fn span(&self, tcx: TyCtxt<'tcx>) -> Span {
156 ObligationCauseCode::CompareImplMethodObligation { .. }
157 | ObligationCauseCode::MainFunctionType
158 | ObligationCauseCode::StartFunctionType => tcx.sess.source_map().def_span(self.span),
159 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
168 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
169 pub enum ObligationCauseCode<'tcx> {
170 /// Not well classified or should be obvious from the span.
173 /// A slice or array is WF only if `T: Sized`.
176 /// A tuple is WF only if its middle elements are `Sized`.
179 /// This is the trait reference from the given projection.
180 ProjectionWf(ty::ProjectionTy<'tcx>),
182 /// In an impl of trait `X` for type `Y`, type `Y` must
183 /// also implement all supertraits of `X`.
184 ItemObligation(DefId),
186 /// Like `ItemObligation`, but with extra detail on the source of the obligation.
187 BindingObligation(DefId, Span),
189 /// A type like `&'a T` is WF only if `T: 'a`.
190 ReferenceOutlivesReferent(Ty<'tcx>),
192 /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
193 ObjectTypeBound(Ty<'tcx>, ty::Region<'tcx>),
195 /// Obligation incurred due to an object cast.
196 ObjectCastObligation(/* Object type */ Ty<'tcx>),
198 /// Obligation incurred due to a coercion.
204 /// Various cases where expressions must be `Sized` / `Copy` / etc.
205 /// `L = X` implies that `L` is `Sized`.
207 /// `(x1, .., xn)` must be `Sized`.
208 TupleInitializerSized,
209 /// `S { ... }` must be `Sized`.
210 StructInitializerSized,
211 /// Type of each variable must be `Sized`.
212 VariableType(hir::HirId),
213 /// Argument type must be `Sized`.
215 /// Return type must be `Sized`.
217 /// Yield type must be `Sized`.
219 /// `[T, ..n]` implies that `T` must be `Copy`.
220 /// If `true`, suggest `const_in_array_repeat_expressions` feature flag.
223 /// Types of fields (other than the last, except for packed structs) in a struct must be sized.
229 /// Constant expressions must be sized.
232 /// `static` items must have `Sync` type.
235 BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
237 ImplDerivedObligation(DerivedObligationCause<'tcx>),
239 /// Error derived when matching traits/impls; see ObligationCause for more details
240 CompareImplMethodObligation {
241 item_name: ast::Name,
242 impl_item_def_id: DefId,
243 trait_item_def_id: DefId,
246 /// Error derived when matching traits/impls; see ObligationCause for more details
247 CompareImplTypeObligation {
248 item_name: ast::Name,
249 impl_item_def_id: DefId,
250 trait_item_def_id: DefId,
253 /// Checking that this expression can be assigned where it needs to be
254 // FIXME(eddyb) #11161 is the original Expr required?
257 /// Computing common supertype in the arms of a match expression
258 MatchExpressionArm(Box<MatchExpressionArmCause<'tcx>>),
260 /// Type error arising from type checking a pattern against an expected type.
262 /// The span of the scrutinee or type expression which caused the `root_ty` type.
264 /// The root expected type induced by a scrutinee or type expression.
266 /// Whether the `Span` came from an expression or a type expression.
270 /// Constants in patterns must have `Structural` type.
271 ConstPatternStructural,
273 /// Computing common supertype in an if expression
274 IfExpression(Box<IfExpressionCause>),
276 /// Computing common supertype of an if expression with no else counter-part
277 IfExpressionWithNoElse,
279 /// `main` has wrong type
282 /// `start` has wrong type
285 /// Intrinsic has wrong type
291 /// `return` with no expression
294 /// `return` with an expression
295 ReturnValue(hir::HirId),
297 /// Return type of this function
300 /// Block implicit return
301 BlockTailExpression(hir::HirId),
303 /// #[feature(trivial_bounds)] is not enabled
306 AssocTypeBound(Box<AssocTypeBoundData>),
309 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
310 pub struct AssocTypeBoundData {
311 pub impl_span: Option<Span>,
313 pub bounds: Vec<Span>,
316 // `ObligationCauseCode` is used a lot. Make sure it doesn't unintentionally get bigger.
317 #[cfg(target_arch = "x86_64")]
318 static_assert_size!(ObligationCauseCode<'_>, 32);
320 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
321 pub struct MatchExpressionArmCause<'tcx> {
323 pub source: hir::MatchSource,
324 pub prior_arms: Vec<Span>,
325 pub last_ty: Ty<'tcx>,
326 pub scrut_hir_id: hir::HirId,
329 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
330 pub struct IfExpressionCause {
332 pub outer: Option<Span>,
333 pub semicolon: Option<Span>,
336 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
337 pub struct DerivedObligationCause<'tcx> {
338 /// The trait reference of the parent obligation that led to the
339 /// current obligation. Note that only trait obligations lead to
340 /// derived obligations, so we just store the trait reference here
342 parent_trait_ref: ty::PolyTraitRef<'tcx>,
344 /// The parent trait had this cause.
345 parent_code: Rc<ObligationCauseCode<'tcx>>,
348 pub type Obligations<'tcx, O> = Vec<Obligation<'tcx, O>>;
349 pub type PredicateObligations<'tcx> = Vec<PredicateObligation<'tcx>>;
350 pub type TraitObligations<'tcx> = Vec<TraitObligation<'tcx>>;
352 /// The following types:
360 /// * `InEnvironment`,
361 /// are used for representing the trait system in the form of
362 /// logic programming clauses. They are part of the interface
363 /// for the chalk SLG solver.
364 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
365 pub enum WhereClause<'tcx> {
366 Implemented(ty::TraitPredicate<'tcx>),
367 ProjectionEq(ty::ProjectionPredicate<'tcx>),
368 RegionOutlives(ty::RegionOutlivesPredicate<'tcx>),
369 TypeOutlives(ty::TypeOutlivesPredicate<'tcx>),
372 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
373 pub enum WellFormed<'tcx> {
374 Trait(ty::TraitPredicate<'tcx>),
378 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
379 pub enum FromEnv<'tcx> {
380 Trait(ty::TraitPredicate<'tcx>),
384 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
385 pub enum DomainGoal<'tcx> {
386 Holds(WhereClause<'tcx>),
387 WellFormed(WellFormed<'tcx>),
388 FromEnv(FromEnv<'tcx>),
389 Normalize(ty::ProjectionPredicate<'tcx>),
392 pub type PolyDomainGoal<'tcx> = ty::Binder<DomainGoal<'tcx>>;
394 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
395 pub enum QuantifierKind {
400 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
401 pub enum GoalKind<'tcx> {
402 Implies(Clauses<'tcx>, Goal<'tcx>),
403 And(Goal<'tcx>, Goal<'tcx>),
405 DomainGoal(DomainGoal<'tcx>),
406 Quantified(QuantifierKind, ty::Binder<Goal<'tcx>>),
407 Subtype(Ty<'tcx>, Ty<'tcx>),
411 pub type Goal<'tcx> = &'tcx GoalKind<'tcx>;
413 pub type Goals<'tcx> = &'tcx List<Goal<'tcx>>;
415 impl<'tcx> DomainGoal<'tcx> {
416 pub fn into_goal(self) -> GoalKind<'tcx> {
417 GoalKind::DomainGoal(self)
420 pub fn into_program_clause(self) -> ProgramClause<'tcx> {
423 hypotheses: ty::List::empty(),
424 category: ProgramClauseCategory::Other,
429 impl<'tcx> GoalKind<'tcx> {
430 pub fn from_poly_domain_goal(
431 domain_goal: PolyDomainGoal<'tcx>,
433 ) -> GoalKind<'tcx> {
434 match domain_goal.no_bound_vars() {
435 Some(p) => p.into_goal(),
436 None => GoalKind::Quantified(
437 QuantifierKind::Universal,
438 domain_goal.map_bound(|p| tcx.mk_goal(p.into_goal())),
444 /// This matches the definition from Page 7 of "A Proof Procedure for the Logic of Hereditary
445 /// Harrop Formulas".
446 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
447 pub enum Clause<'tcx> {
448 Implies(ProgramClause<'tcx>),
449 ForAll(ty::Binder<ProgramClause<'tcx>>),
453 pub fn category(self) -> ProgramClauseCategory {
455 Clause::Implies(clause) => clause.category,
456 Clause::ForAll(clause) => clause.skip_binder().category,
461 /// Multiple clauses.
462 pub type Clauses<'tcx> = &'tcx List<Clause<'tcx>>;
464 /// A "program clause" has the form `D :- G1, ..., Gn`. It is saying
465 /// that the domain goal `D` is true if `G1...Gn` are provable. This
466 /// is equivalent to the implication `G1..Gn => D`; we usually write
467 /// it with the reverse implication operator `:-` to emphasize the way
468 /// that programs are actually solved (via backchaining, which starts
469 /// with the goal to solve and proceeds from there).
470 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
471 pub struct ProgramClause<'tcx> {
472 /// This goal will be considered true ...
473 pub goal: DomainGoal<'tcx>,
475 /// ... if we can prove these hypotheses (there may be no hypotheses at all):
476 pub hypotheses: Goals<'tcx>,
478 /// Useful for filtering clauses.
479 pub category: ProgramClauseCategory,
482 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
483 pub enum ProgramClauseCategory {
489 /// A set of clauses that we assume to be true.
490 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
491 pub struct Environment<'tcx> {
492 pub clauses: Clauses<'tcx>,
495 impl Environment<'tcx> {
496 pub fn with<G>(self, goal: G) -> InEnvironment<'tcx, G> {
497 InEnvironment { environment: self, goal }
501 /// Something (usually a goal), along with an environment.
502 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
503 pub struct InEnvironment<'tcx, G> {
504 pub environment: Environment<'tcx>,
508 pub type Selection<'tcx> = Vtable<'tcx, PredicateObligation<'tcx>>;
510 #[derive(Clone, Debug, TypeFoldable)]
511 pub enum SelectionError<'tcx> {
513 OutputTypeParameterMismatch(
514 ty::PolyTraitRef<'tcx>,
515 ty::PolyTraitRef<'tcx>,
516 ty::error::TypeError<'tcx>,
518 TraitNotObjectSafe(DefId),
519 ConstEvalFailure(ErrorHandled),
523 pub struct FulfillmentError<'tcx> {
524 pub obligation: PredicateObligation<'tcx>,
525 pub code: FulfillmentErrorCode<'tcx>,
526 /// Diagnostics only: we opportunistically change the `code.span` when we encounter an
527 /// obligation error caused by a call argument. When this is the case, we also signal that in
528 /// this field to ensure accuracy of suggestions.
529 pub points_at_arg_span: bool,
533 pub enum FulfillmentErrorCode<'tcx> {
534 CodeSelectionError(SelectionError<'tcx>),
535 CodeProjectionError(MismatchedProjectionTypes<'tcx>),
536 CodeSubtypeError(ExpectedFound<Ty<'tcx>>, TypeError<'tcx>), // always comes from a SubtypePredicate
540 /// When performing resolution, it is typically the case that there
541 /// can be one of three outcomes:
543 /// - `Ok(Some(r))`: success occurred with result `r`
544 /// - `Ok(None)`: could not definitely determine anything, usually due
545 /// to inconclusive type inference.
546 /// - `Err(e)`: error `e` occurred
547 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
549 /// Given the successful resolution of an obligation, the `Vtable`
550 /// indicates where the vtable comes from. Note that while we call this
551 /// a "vtable", it does not necessarily indicate dynamic dispatch at
552 /// runtime. `Vtable` instances just tell the compiler where to find
553 /// methods, but in generic code those methods are typically statically
554 /// dispatched -- only when an object is constructed is a `Vtable`
555 /// instance reified into an actual vtable.
557 /// For example, the vtable may be tied to a specific impl (case A),
558 /// or it may be relative to some bound that is in scope (case B).
561 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
562 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
563 /// impl Clone for int { ... } // Impl_3
565 /// fn foo<T:Clone>(concrete: Option<Box<int>>,
567 /// mixed: Option<T>) {
569 /// // Case A: Vtable points at a specific impl. Only possible when
570 /// // type is concretely known. If the impl itself has bounded
571 /// // type parameters, Vtable will carry resolutions for those as well:
572 /// concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
574 /// // Case B: Vtable must be provided by caller. This applies when
575 /// // type is a type parameter.
576 /// param.clone(); // VtableParam
578 /// // Case C: A mix of cases A and B.
579 /// mixed.clone(); // Vtable(Impl_1, [VtableParam])
583 /// ### The type parameter `N`
585 /// See explanation on `VtableImplData`.
586 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
587 pub enum Vtable<'tcx, N> {
588 /// Vtable identifying a particular impl.
589 VtableImpl(VtableImplData<'tcx, N>),
591 /// Vtable for auto trait implementations.
592 /// This carries the information and nested obligations with regards
593 /// to an auto implementation for a trait `Trait`. The nested obligations
594 /// ensure the trait implementation holds for all the constituent types.
595 VtableAutoImpl(VtableAutoImplData<N>),
597 /// Successful resolution to an obligation provided by the caller
598 /// for some type parameter. The `Vec<N>` represents the
599 /// obligations incurred from normalizing the where-clause (if
603 /// Virtual calls through an object.
604 VtableObject(VtableObjectData<'tcx, N>),
606 /// Successful resolution for a builtin trait.
607 VtableBuiltin(VtableBuiltinData<N>),
609 /// Vtable automatically generated for a closure. The `DefId` is the ID
610 /// of the closure expression. This is a `VtableImpl` in spirit, but the
611 /// impl is generated by the compiler and does not appear in the source.
612 VtableClosure(VtableClosureData<'tcx, N>),
614 /// Same as above, but for a function pointer type with the given signature.
615 VtableFnPointer(VtableFnPointerData<'tcx, N>),
617 /// Vtable automatically generated for a generator.
618 VtableGenerator(VtableGeneratorData<'tcx, N>),
620 /// Vtable for a trait alias.
621 VtableTraitAlias(VtableTraitAliasData<'tcx, N>),
624 /// Identifies a particular impl in the source, along with a set of
625 /// substitutions from the impl's type/lifetime parameters. The
626 /// `nested` vector corresponds to the nested obligations attached to
627 /// the impl's type parameters.
629 /// The type parameter `N` indicates the type used for "nested
630 /// obligations" that are required by the impl. During type-check, this
631 /// is `Obligation`, as one might expect. During codegen, however, this
632 /// is `()`, because codegen only requires a shallow resolution of an
633 /// impl, and nested obligations are satisfied later.
634 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
635 pub struct VtableImplData<'tcx, N> {
636 pub impl_def_id: DefId,
637 pub substs: SubstsRef<'tcx>,
641 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
642 pub struct VtableGeneratorData<'tcx, N> {
643 pub generator_def_id: DefId,
644 pub substs: SubstsRef<'tcx>,
645 /// Nested obligations. This can be non-empty if the generator
646 /// signature contains associated types.
650 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
651 pub struct VtableClosureData<'tcx, N> {
652 pub closure_def_id: DefId,
653 pub substs: SubstsRef<'tcx>,
654 /// Nested obligations. This can be non-empty if the closure
655 /// signature contains associated types.
659 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
660 pub struct VtableAutoImplData<N> {
661 pub trait_def_id: DefId,
665 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
666 pub struct VtableBuiltinData<N> {
670 /// A vtable for some object-safe trait `Foo` automatically derived
671 /// for the object type `Foo`.
672 #[derive(PartialEq, Eq, Clone, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
673 pub struct VtableObjectData<'tcx, N> {
674 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
675 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
677 /// The vtable is formed by concatenating together the method lists of
678 /// the base object trait and all supertraits; this is the start of
679 /// `upcast_trait_ref`'s methods in that vtable.
680 pub vtable_base: usize,
685 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
686 pub struct VtableFnPointerData<'tcx, N> {
691 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
692 pub struct VtableTraitAliasData<'tcx, N> {
693 pub alias_def_id: DefId,
694 pub substs: SubstsRef<'tcx>,
698 /// Creates predicate obligations from the generic bounds.
699 pub fn predicates_for_generics<'tcx>(
700 cause: ObligationCause<'tcx>,
701 param_env: ty::ParamEnv<'tcx>,
702 generic_bounds: &ty::InstantiatedPredicates<'tcx>,
703 ) -> PredicateObligations<'tcx> {
704 util::predicates_for_generics(cause, 0, param_env, generic_bounds)
707 /// Determines whether the type `ty` is known to meet `bound` and
708 /// returns true if so. Returns false if `ty` either does not meet
709 /// `bound` or is not known to meet bound (note that this is
710 /// conservative towards *no impl*, which is the opposite of the
711 /// `evaluate` methods).
712 pub fn type_known_to_meet_bound_modulo_regions<'a, 'tcx>(
713 infcx: &InferCtxt<'a, 'tcx>,
714 param_env: ty::ParamEnv<'tcx>,
720 "type_known_to_meet_bound_modulo_regions(ty={:?}, bound={:?})",
722 infcx.tcx.def_path_str(def_id)
725 let trait_ref = ty::TraitRef { def_id, substs: infcx.tcx.mk_substs_trait(ty, &[]) };
726 let obligation = Obligation {
728 cause: ObligationCause::misc(span, hir::DUMMY_HIR_ID),
730 predicate: trait_ref.to_predicate(),
733 let result = infcx.predicate_must_hold_modulo_regions(&obligation);
735 "type_known_to_meet_ty={:?} bound={} => {:?}",
737 infcx.tcx.def_path_str(def_id),
741 if result && (ty.has_infer_types() || ty.has_closure_types()) {
742 // Because of inference "guessing", selection can sometimes claim
743 // to succeed while the success requires a guess. To ensure
744 // this function's result remains infallible, we must confirm
745 // that guess. While imperfect, I believe this is sound.
747 // The handling of regions in this area of the code is terrible,
748 // see issue #29149. We should be able to improve on this with
750 let mut fulfill_cx = FulfillmentContext::new_ignoring_regions();
752 // We can use a dummy node-id here because we won't pay any mind
753 // to region obligations that arise (there shouldn't really be any
755 let cause = ObligationCause::misc(span, hir::DUMMY_HIR_ID);
757 fulfill_cx.register_bound(infcx, param_env, ty, def_id, cause);
759 // Note: we only assume something is `Copy` if we can
760 // *definitively* show that it implements `Copy`. Otherwise,
761 // assume it is move; linear is always ok.
762 match fulfill_cx.select_all_or_error(infcx) {
765 "type_known_to_meet_bound_modulo_regions: ty={:?} bound={} success",
767 infcx.tcx.def_path_str(def_id)
773 "type_known_to_meet_bound_modulo_regions: ty={:?} bound={} errors={:?}",
775 infcx.tcx.def_path_str(def_id),
786 fn do_normalize_predicates<'tcx>(
788 region_context: DefId,
789 cause: ObligationCause<'tcx>,
790 elaborated_env: ty::ParamEnv<'tcx>,
791 predicates: Vec<ty::Predicate<'tcx>>,
792 ) -> Result<Vec<ty::Predicate<'tcx>>, ErrorReported> {
794 "do_normalize_predicates(predicates={:?}, region_context={:?}, cause={:?})",
795 predicates, region_context, cause,
797 let span = cause.span;
798 tcx.infer_ctxt().enter(|infcx| {
799 // FIXME. We should really... do something with these region
800 // obligations. But this call just continues the older
801 // behavior (i.e., doesn't cause any new bugs), and it would
802 // take some further refactoring to actually solve them. In
803 // particular, we would have to handle implied bounds
804 // properly, and that code is currently largely confined to
805 // regionck (though I made some efforts to extract it
808 // @arielby: In any case, these obligations are checked
809 // by wfcheck anyway, so I'm not sure we have to check
810 // them here too, and we will remove this function when
811 // we move over to lazy normalization *anyway*.
812 let fulfill_cx = FulfillmentContext::new_ignoring_regions();
814 match fully_normalize(&infcx, fulfill_cx, cause, elaborated_env, &predicates) {
815 Ok(predicates) => predicates,
817 infcx.report_fulfillment_errors(&errors, None, false);
818 return Err(ErrorReported);
822 debug!("do_normalize_predictes: normalized predicates = {:?}", predicates);
824 let region_scope_tree = region::ScopeTree::default();
826 // We can use the `elaborated_env` here; the region code only
827 // cares about declarations like `'a: 'b`.
828 let outlives_env = OutlivesEnvironment::new(elaborated_env);
830 infcx.resolve_regions_and_report_errors(
834 SuppressRegionErrors::default(),
837 let predicates = match infcx.fully_resolve(&predicates) {
838 Ok(predicates) => predicates,
840 // If we encounter a fixup error, it means that some type
841 // variable wound up unconstrained. I actually don't know
842 // if this can happen, and I certainly don't expect it to
843 // happen often, but if it did happen it probably
844 // represents a legitimate failure due to some kind of
845 // unconstrained variable, and it seems better not to ICE,
846 // all things considered.
847 tcx.sess.span_err(span, &fixup_err.to_string());
848 return Err(ErrorReported);
851 if predicates.has_local_value() {
852 // FIXME: shouldn't we, you know, actually report an error here? or an ICE?
860 // FIXME: this is gonna need to be removed ...
861 /// Normalizes the parameter environment, reporting errors if they occur.
862 pub fn normalize_param_env_or_error<'tcx>(
864 region_context: DefId,
865 unnormalized_env: ty::ParamEnv<'tcx>,
866 cause: ObligationCause<'tcx>,
867 ) -> ty::ParamEnv<'tcx> {
868 // I'm not wild about reporting errors here; I'd prefer to
869 // have the errors get reported at a defined place (e.g.,
870 // during typeck). Instead I have all parameter
871 // environments, in effect, going through this function
872 // and hence potentially reporting errors. This ensures of
873 // course that we never forget to normalize (the
874 // alternative seemed like it would involve a lot of
875 // manual invocations of this fn -- and then we'd have to
876 // deal with the errors at each of those sites).
878 // In any case, in practice, typeck constructs all the
879 // parameter environments once for every fn as it goes,
880 // and errors will get reported then; so after typeck we
881 // can be sure that no errors should occur.
884 "normalize_param_env_or_error(region_context={:?}, unnormalized_env={:?}, cause={:?})",
885 region_context, unnormalized_env, cause
888 let mut predicates: Vec<_> =
889 util::elaborate_predicates(tcx, unnormalized_env.caller_bounds.to_vec()).collect();
891 debug!("normalize_param_env_or_error: elaborated-predicates={:?}", predicates);
893 let elaborated_env = ty::ParamEnv::new(
894 tcx.intern_predicates(&predicates),
895 unnormalized_env.reveal,
896 unnormalized_env.def_id,
899 // HACK: we are trying to normalize the param-env inside *itself*. The problem is that
900 // normalization expects its param-env to be already normalized, which means we have
903 // The way we handle this is by normalizing the param-env inside an unnormalized version
904 // of the param-env, which means that if the param-env contains unnormalized projections,
905 // we'll have some normalization failures. This is unfortunate.
907 // Lazy normalization would basically handle this by treating just the
908 // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
910 // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
911 // types, so to make the situation less bad, we normalize all the predicates *but*
912 // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
913 // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
915 // This works fairly well because trait matching does not actually care about param-env
916 // TypeOutlives predicates - these are normally used by regionck.
917 let outlives_predicates: Vec<_> = predicates
918 .drain_filter(|predicate| match predicate {
919 ty::Predicate::TypeOutlives(..) => true,
925 "normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
926 predicates, outlives_predicates
928 let non_outlives_predicates = match do_normalize_predicates(
935 Ok(predicates) => predicates,
936 // An unnormalized env is better than nothing.
937 Err(ErrorReported) => {
938 debug!("normalize_param_env_or_error: errored resolving non-outlives predicates");
939 return elaborated_env;
943 debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates);
945 // Not sure whether it is better to include the unnormalized TypeOutlives predicates
946 // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
947 // predicates here anyway. Keeping them here anyway because it seems safer.
948 let outlives_env: Vec<_> =
949 non_outlives_predicates.iter().chain(&outlives_predicates).cloned().collect();
951 ty::ParamEnv::new(tcx.intern_predicates(&outlives_env), unnormalized_env.reveal, None);
952 let outlives_predicates = match do_normalize_predicates(
959 Ok(predicates) => predicates,
960 // An unnormalized env is better than nothing.
961 Err(ErrorReported) => {
962 debug!("normalize_param_env_or_error: errored resolving outlives predicates");
963 return elaborated_env;
966 debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates);
968 let mut predicates = non_outlives_predicates;
969 predicates.extend(outlives_predicates);
970 debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
972 tcx.intern_predicates(&predicates),
973 unnormalized_env.reveal,
974 unnormalized_env.def_id,
978 pub fn fully_normalize<'a, 'tcx, T>(
979 infcx: &InferCtxt<'a, 'tcx>,
980 mut fulfill_cx: FulfillmentContext<'tcx>,
981 cause: ObligationCause<'tcx>,
982 param_env: ty::ParamEnv<'tcx>,
984 ) -> Result<T, Vec<FulfillmentError<'tcx>>>
986 T: TypeFoldable<'tcx>,
988 debug!("fully_normalize_with_fulfillcx(value={:?})", value);
989 let selcx = &mut SelectionContext::new(infcx);
990 let Normalized { value: normalized_value, obligations } =
991 project::normalize(selcx, param_env, cause, value);
993 "fully_normalize: normalized_value={:?} obligations={:?}",
994 normalized_value, obligations
996 for obligation in obligations {
997 fulfill_cx.register_predicate_obligation(selcx.infcx(), obligation);
1000 debug!("fully_normalize: select_all_or_error start");
1001 fulfill_cx.select_all_or_error(infcx)?;
1002 debug!("fully_normalize: select_all_or_error complete");
1003 let resolved_value = infcx.resolve_vars_if_possible(&normalized_value);
1004 debug!("fully_normalize: resolved_value={:?}", resolved_value);
1008 /// Normalizes the predicates and checks whether they hold in an empty
1009 /// environment. If this returns false, then either normalize
1010 /// encountered an error or one of the predicates did not hold. Used
1011 /// when creating vtables to check for unsatisfiable methods.
1012 fn normalize_and_test_predicates<'tcx>(
1014 predicates: Vec<ty::Predicate<'tcx>>,
1016 debug!("normalize_and_test_predicates(predicates={:?})", predicates);
1018 let result = tcx.infer_ctxt().enter(|infcx| {
1019 let param_env = ty::ParamEnv::reveal_all();
1020 let mut selcx = SelectionContext::new(&infcx);
1021 let mut fulfill_cx = FulfillmentContext::new();
1022 let cause = ObligationCause::dummy();
1023 let Normalized { value: predicates, obligations } =
1024 normalize(&mut selcx, param_env, cause.clone(), &predicates);
1025 for obligation in obligations {
1026 fulfill_cx.register_predicate_obligation(&infcx, obligation);
1028 for predicate in predicates {
1029 let obligation = Obligation::new(cause.clone(), param_env, predicate);
1030 fulfill_cx.register_predicate_obligation(&infcx, obligation);
1033 fulfill_cx.select_all_or_error(&infcx).is_ok()
1035 debug!("normalize_and_test_predicates(predicates={:?}) = {:?}", predicates, result);
1039 fn substitute_normalize_and_test_predicates<'tcx>(
1041 key: (DefId, SubstsRef<'tcx>),
1043 debug!("substitute_normalize_and_test_predicates(key={:?})", key);
1045 let predicates = tcx.predicates_of(key.0).instantiate(tcx, key.1).predicates;
1046 let result = normalize_and_test_predicates(tcx, predicates);
1048 debug!("substitute_normalize_and_test_predicates(key={:?}) = {:?}", key, result);
1052 /// Given a trait `trait_ref`, iterates the vtable entries
1053 /// that come from `trait_ref`, including its supertraits.
1054 #[inline] // FIXME(#35870): avoid closures being unexported due to `impl Trait`.
1055 fn vtable_methods<'tcx>(
1057 trait_ref: ty::PolyTraitRef<'tcx>,
1058 ) -> &'tcx [Option<(DefId, SubstsRef<'tcx>)>] {
1059 debug!("vtable_methods({:?})", trait_ref);
1061 tcx.arena.alloc_from_iter(supertraits(tcx, trait_ref).flat_map(move |trait_ref| {
1062 let trait_methods = tcx
1063 .associated_items(trait_ref.def_id())
1064 .filter(|item| item.kind == ty::AssocKind::Method);
1066 // Now list each method's DefId and InternalSubsts (for within its trait).
1067 // If the method can never be called from this object, produce None.
1068 trait_methods.map(move |trait_method| {
1069 debug!("vtable_methods: trait_method={:?}", trait_method);
1070 let def_id = trait_method.def_id;
1072 // Some methods cannot be called on an object; skip those.
1073 if !is_vtable_safe_method(tcx, trait_ref.def_id(), &trait_method) {
1074 debug!("vtable_methods: not vtable safe");
1078 // The method may have some early-bound lifetimes; add regions for those.
1079 let substs = trait_ref.map_bound(|trait_ref| {
1080 InternalSubsts::for_item(tcx, def_id, |param, _| match param.kind {
1081 GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(),
1082 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const => {
1083 trait_ref.substs[param.index as usize]
1088 // The trait type may have higher-ranked lifetimes in it;
1089 // erase them if they appear, so that we get the type
1090 // at some particular call site.
1092 tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &substs);
1094 // It's possible that the method relies on where-clauses that
1095 // do not hold for this particular set of type parameters.
1096 // Note that this method could then never be called, so we
1097 // do not want to try and codegen it, in that case (see #23435).
1098 let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs);
1099 if !normalize_and_test_predicates(tcx, predicates.predicates) {
1100 debug!("vtable_methods: predicates do not hold");
1104 Some((def_id, substs))
1109 impl<'tcx, O> Obligation<'tcx, O> {
1111 cause: ObligationCause<'tcx>,
1112 param_env: ty::ParamEnv<'tcx>,
1114 ) -> Obligation<'tcx, O> {
1115 Obligation { cause, param_env, recursion_depth: 0, predicate }
1119 cause: ObligationCause<'tcx>,
1120 recursion_depth: usize,
1121 param_env: ty::ParamEnv<'tcx>,
1123 ) -> Obligation<'tcx, O> {
1124 Obligation { cause, param_env, recursion_depth, predicate }
1129 body_id: hir::HirId,
1130 param_env: ty::ParamEnv<'tcx>,
1132 ) -> Obligation<'tcx, O> {
1133 Obligation::new(ObligationCause::misc(span, body_id), param_env, trait_ref)
1136 pub fn with<P>(&self, value: P) -> Obligation<'tcx, P> {
1138 cause: self.cause.clone(),
1139 param_env: self.param_env,
1140 recursion_depth: self.recursion_depth,
1146 impl<'tcx> ObligationCause<'tcx> {
1150 body_id: hir::HirId,
1151 code: ObligationCauseCode<'tcx>,
1152 ) -> ObligationCause<'tcx> {
1153 ObligationCause { span, body_id, code }
1156 pub fn misc(span: Span, body_id: hir::HirId) -> ObligationCause<'tcx> {
1157 ObligationCause { span, body_id, code: MiscObligation }
1160 pub fn dummy() -> ObligationCause<'tcx> {
1161 ObligationCause { span: DUMMY_SP, body_id: hir::CRATE_HIR_ID, code: MiscObligation }
1165 impl<'tcx, N> Vtable<'tcx, N> {
1166 pub fn nested_obligations(self) -> Vec<N> {
1168 VtableImpl(i) => i.nested,
1169 VtableParam(n) => n,
1170 VtableBuiltin(i) => i.nested,
1171 VtableAutoImpl(d) => d.nested,
1172 VtableClosure(c) => c.nested,
1173 VtableGenerator(c) => c.nested,
1174 VtableObject(d) => d.nested,
1175 VtableFnPointer(d) => d.nested,
1176 VtableTraitAlias(d) => d.nested,
1180 pub fn map<M, F>(self, f: F) -> Vtable<'tcx, M>
1185 VtableImpl(i) => VtableImpl(VtableImplData {
1186 impl_def_id: i.impl_def_id,
1188 nested: i.nested.into_iter().map(f).collect(),
1190 VtableParam(n) => VtableParam(n.into_iter().map(f).collect()),
1191 VtableBuiltin(i) => {
1192 VtableBuiltin(VtableBuiltinData { nested: i.nested.into_iter().map(f).collect() })
1194 VtableObject(o) => VtableObject(VtableObjectData {
1195 upcast_trait_ref: o.upcast_trait_ref,
1196 vtable_base: o.vtable_base,
1197 nested: o.nested.into_iter().map(f).collect(),
1199 VtableAutoImpl(d) => VtableAutoImpl(VtableAutoImplData {
1200 trait_def_id: d.trait_def_id,
1201 nested: d.nested.into_iter().map(f).collect(),
1203 VtableClosure(c) => VtableClosure(VtableClosureData {
1204 closure_def_id: c.closure_def_id,
1206 nested: c.nested.into_iter().map(f).collect(),
1208 VtableGenerator(c) => VtableGenerator(VtableGeneratorData {
1209 generator_def_id: c.generator_def_id,
1211 nested: c.nested.into_iter().map(f).collect(),
1213 VtableFnPointer(p) => VtableFnPointer(VtableFnPointerData {
1215 nested: p.nested.into_iter().map(f).collect(),
1217 VtableTraitAlias(d) => VtableTraitAlias(VtableTraitAliasData {
1218 alias_def_id: d.alias_def_id,
1220 nested: d.nested.into_iter().map(f).collect(),
1226 impl<'tcx> FulfillmentError<'tcx> {
1228 obligation: PredicateObligation<'tcx>,
1229 code: FulfillmentErrorCode<'tcx>,
1230 ) -> FulfillmentError<'tcx> {
1231 FulfillmentError { obligation: obligation, code: code, points_at_arg_span: false }
1235 impl<'tcx> TraitObligation<'tcx> {
1236 fn self_ty(&self) -> ty::Binder<Ty<'tcx>> {
1237 self.predicate.map_bound(|p| p.self_ty())
1241 pub fn provide(providers: &mut ty::query::Providers<'_>) {
1242 *providers = ty::query::Providers {
1243 is_object_safe: object_safety::is_object_safe_provider,
1244 specialization_graph_of: specialize::specialization_graph_provider,
1245 specializes: specialize::specializes,
1246 codegen_fulfill_obligation: codegen::codegen_fulfill_obligation,
1248 substitute_normalize_and_test_predicates,
1253 pub trait ExClauseFold<'tcx>
1255 Self: chalk_engine::context::Context + Clone,
1257 fn fold_ex_clause_with<F: TypeFolder<'tcx>>(
1258 ex_clause: &chalk_engine::ExClause<Self>,
1260 ) -> chalk_engine::ExClause<Self>;
1262 fn visit_ex_clause_with<V: TypeVisitor<'tcx>>(
1263 ex_clause: &chalk_engine::ExClause<Self>,
1268 pub trait ChalkContextLift<'tcx>
1270 Self: chalk_engine::context::Context + Clone,
1272 type LiftedExClause: Debug + 'tcx;
1273 type LiftedDelayedLiteral: Debug + 'tcx;
1274 type LiftedLiteral: Debug + 'tcx;
1276 fn lift_ex_clause_to_tcx(
1277 ex_clause: &chalk_engine::ExClause<Self>,
1279 ) -> Option<Self::LiftedExClause>;
1281 fn lift_delayed_literal_to_tcx(
1282 ex_clause: &chalk_engine::DelayedLiteral<Self>,
1284 ) -> Option<Self::LiftedDelayedLiteral>;
1286 fn lift_literal_to_tcx(
1287 ex_clause: &chalk_engine::Literal<Self>,
1289 ) -> Option<Self::LiftedLiteral>;