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::hir::def_id::DefId;
24 use crate::infer::outlives::env::OutlivesEnvironment;
25 use crate::infer::{InferCtxt, SuppressRegionErrors};
26 use crate::middle::region;
27 use crate::mir::interpret::ErrorHandled;
28 use crate::ty::error::{ExpectedFound, TypeError};
29 use crate::ty::fold::{TypeFoldable, TypeFolder, TypeVisitor};
30 use crate::ty::subst::{InternalSubsts, SubstsRef};
31 use crate::ty::{self, AdtKind, GenericParamDefKind, List, ToPredicate, Ty, TyCtxt};
32 use crate::util::common::ErrorReported;
34 use rustc_macros::HashStable;
36 use syntax_pos::{Span, DUMMY_SP};
41 pub use self::FulfillmentErrorCode::*;
42 pub use self::ObligationCauseCode::*;
43 pub use self::SelectionError::*;
44 pub use self::Vtable::*;
46 pub use self::coherence::{add_placeholder_note, orphan_check, overlapping_impls};
47 pub use self::coherence::{OrphanCheckErr, OverlapResult};
48 pub use self::engine::{TraitEngine, TraitEngineExt};
49 pub use self::fulfill::{FulfillmentContext, PendingPredicateObligation};
50 pub use self::object_safety::MethodViolationCode;
51 pub use self::object_safety::ObjectSafetyViolation;
52 pub use self::on_unimplemented::{OnUnimplementedDirective, OnUnimplementedNote};
53 pub use self::project::MismatchedProjectionTypes;
54 pub use self::project::{normalize, normalize_projection_type, poly_project_and_unify_type};
55 pub use self::project::{Normalized, ProjectionCache, ProjectionCacheSnapshot, Reveal};
56 pub use self::select::{EvaluationCache, SelectionCache, SelectionContext};
57 pub use self::select::{EvaluationResult, IntercrateAmbiguityCause, OverflowError};
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::specialize::{specialization_graph, translate_substs, OverlapError};
62 pub use self::util::{elaborate_predicates, elaborate_trait_ref, elaborate_trait_refs};
63 pub use self::util::{expand_trait_aliases, TraitAliasExpander};
65 supertrait_def_ids, supertraits, transitive_bounds, SupertraitDefIds, Supertraits,
68 pub use self::chalk_fulfill::{
69 CanonicalGoal as ChalkCanonicalGoal, FulfillmentContext as ChalkFulfillmentContext,
72 pub use self::FulfillmentErrorCode::*;
73 pub use self::ObligationCauseCode::*;
74 pub use self::SelectionError::*;
75 pub use self::Vtable::*;
77 /// Whether to enable bug compatibility with issue #43355.
78 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
79 pub enum IntercrateMode {
84 /// The mode that trait queries run in.
85 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
86 pub enum TraitQueryMode {
87 // Standard/un-canonicalized queries get accurate
88 // spans etc. passed in and hence can do reasonable
89 // error reporting on their own.
91 // Canonicalized queries get dummy spans and hence
92 // must generally propagate errors to
93 // pre-canonicalization callsites.
97 /// An `Obligation` represents some trait reference (e.g., `int: Eq`) for
98 /// which the vtable must be found. The process of finding a vtable is
99 /// called "resolving" the `Obligation`. This process consists of
100 /// either identifying an `impl` (e.g., `impl Eq for int`) that
101 /// provides the required vtable, or else finding a bound that is in
102 /// scope. The eventual result is usually a `Selection` (defined below).
103 #[derive(Clone, PartialEq, Eq, Hash)]
104 pub struct Obligation<'tcx, T> {
105 /// The reason we have to prove this thing.
106 pub cause: ObligationCause<'tcx>,
108 /// The environment in which we should prove this thing.
109 pub param_env: ty::ParamEnv<'tcx>,
111 /// The thing we are trying to prove.
114 /// If we started proving this as a result of trying to prove
115 /// something else, track the total depth to ensure termination.
116 /// If this goes over a certain threshold, we abort compilation --
117 /// in such cases, we can not say whether or not the predicate
118 /// holds for certain. Stupid halting problem; such a drag.
119 pub recursion_depth: usize,
122 pub type PredicateObligation<'tcx> = Obligation<'tcx, ty::Predicate<'tcx>>;
123 pub type TraitObligation<'tcx> = Obligation<'tcx, ty::PolyTraitPredicate<'tcx>>;
125 // `PredicateObligation` is used a lot. Make sure it doesn't unintentionally get bigger.
126 #[cfg(target_arch = "x86_64")]
127 static_assert_size!(PredicateObligation<'_>, 112);
129 /// The reason why we incurred this obligation; used for error reporting.
130 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
131 pub struct ObligationCause<'tcx> {
134 /// The ID of the fn body that triggered this obligation. This is
135 /// used for region obligations to determine the precise
136 /// environment in which the region obligation should be evaluated
137 /// (in particular, closures can add new assumptions). See the
138 /// field `region_obligations` of the `FulfillmentContext` for more
140 pub body_id: hir::HirId,
142 pub code: ObligationCauseCode<'tcx>,
145 impl<'tcx> ObligationCause<'tcx> {
146 pub fn span(&self, tcx: TyCtxt<'tcx>) -> Span {
148 ObligationCauseCode::CompareImplMethodObligation { .. }
149 | ObligationCauseCode::MainFunctionType
150 | ObligationCauseCode::StartFunctionType => tcx.sess.source_map().def_span(self.span),
151 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
160 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
161 pub enum ObligationCauseCode<'tcx> {
162 /// Not well classified or should be obvious from the span.
165 /// A slice or array is WF only if `T: Sized`.
168 /// A tuple is WF only if its middle elements are `Sized`.
171 /// This is the trait reference from the given projection.
172 ProjectionWf(ty::ProjectionTy<'tcx>),
174 /// In an impl of trait `X` for type `Y`, type `Y` must
175 /// also implement all supertraits of `X`.
176 ItemObligation(DefId),
178 /// Like `ItemObligation`, but with extra detail on the source of the obligation.
179 BindingObligation(DefId, Span),
181 /// A type like `&'a T` is WF only if `T: 'a`.
182 ReferenceOutlivesReferent(Ty<'tcx>),
184 /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
185 ObjectTypeBound(Ty<'tcx>, ty::Region<'tcx>),
187 /// Obligation incurred due to an object cast.
188 ObjectCastObligation(/* Object type */ Ty<'tcx>),
190 /// Obligation incurred due to a coercion.
196 /// Various cases where expressions must be `Sized` / `Copy` / etc.
197 /// `L = X` implies that `L` is `Sized`.
199 /// `(x1, .., xn)` must be `Sized`.
200 TupleInitializerSized,
201 /// `S { ... }` must be `Sized`.
202 StructInitializerSized,
203 /// Type of each variable must be `Sized`.
204 VariableType(hir::HirId),
205 /// Argument type must be `Sized`.
207 /// Return type must be `Sized`.
209 /// Yield type must be `Sized`.
211 /// `[T, ..n]` implies that `T` must be `Copy`.
212 /// If `true`, suggest `const_in_array_repeat_expressions` feature flag.
215 /// Types of fields (other than the last, except for packed structs) in a struct must be sized.
221 /// Constant expressions must be sized.
224 /// `static` items must have `Sync` type.
227 BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
229 ImplDerivedObligation(DerivedObligationCause<'tcx>),
231 /// Error derived when matching traits/impls; see ObligationCause for more details
232 CompareImplMethodObligation {
233 item_name: ast::Name,
234 impl_item_def_id: DefId,
235 trait_item_def_id: DefId,
238 /// Error derived when matching traits/impls; see ObligationCause for more details
239 CompareImplTypeObligation {
240 item_name: ast::Name,
241 impl_item_def_id: DefId,
242 trait_item_def_id: DefId,
245 /// Checking that this expression can be assigned where it needs to be
246 // FIXME(eddyb) #11161 is the original Expr required?
249 /// Computing common supertype in the arms of a match expression
250 MatchExpressionArm(Box<MatchExpressionArmCause<'tcx>>),
252 /// Computing common supertype in the pattern guard for the arms of a match expression
253 MatchExpressionArmPattern {
258 /// Constants in patterns must have `Structural` type.
259 ConstPatternStructural,
261 /// Computing common supertype in an if expression
262 IfExpression(Box<IfExpressionCause>),
264 /// Computing common supertype of an if expression with no else counter-part
265 IfExpressionWithNoElse,
267 /// `main` has wrong type
270 /// `start` has wrong type
273 /// Intrinsic has wrong type
279 /// `return` with no expression
282 /// `return` with an expression
283 ReturnValue(hir::HirId),
285 /// Return type of this function
288 /// Block implicit return
289 BlockTailExpression(hir::HirId),
291 /// #[feature(trivial_bounds)] is not enabled
294 AssocTypeBound(Box<AssocTypeBoundData>),
297 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
298 pub struct AssocTypeBoundData {
299 pub impl_span: Option<Span>,
301 pub bounds: Vec<Span>,
304 // `ObligationCauseCode` is used a lot. Make sure it doesn't unintentionally get bigger.
305 #[cfg(target_arch = "x86_64")]
306 static_assert_size!(ObligationCauseCode<'_>, 32);
308 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
309 pub struct MatchExpressionArmCause<'tcx> {
311 pub source: hir::MatchSource,
312 pub prior_arms: Vec<Span>,
313 pub last_ty: Ty<'tcx>,
314 pub discrim_hir_id: hir::HirId,
317 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
318 pub struct IfExpressionCause {
320 pub outer: Option<Span>,
321 pub semicolon: Option<Span>,
324 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
325 pub struct DerivedObligationCause<'tcx> {
326 /// The trait reference of the parent obligation that led to the
327 /// current obligation. Note that only trait obligations lead to
328 /// derived obligations, so we just store the trait reference here
330 parent_trait_ref: ty::PolyTraitRef<'tcx>,
332 /// The parent trait had this cause.
333 parent_code: Rc<ObligationCauseCode<'tcx>>,
336 pub type Obligations<'tcx, O> = Vec<Obligation<'tcx, O>>;
337 pub type PredicateObligations<'tcx> = Vec<PredicateObligation<'tcx>>;
338 pub type TraitObligations<'tcx> = Vec<TraitObligation<'tcx>>;
340 /// The following types:
348 /// * `InEnvironment`,
349 /// are used for representing the trait system in the form of
350 /// logic programming clauses. They are part of the interface
351 /// for the chalk SLG solver.
352 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
353 pub enum WhereClause<'tcx> {
354 Implemented(ty::TraitPredicate<'tcx>),
355 ProjectionEq(ty::ProjectionPredicate<'tcx>),
356 RegionOutlives(ty::RegionOutlivesPredicate<'tcx>),
357 TypeOutlives(ty::TypeOutlivesPredicate<'tcx>),
360 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
361 pub enum WellFormed<'tcx> {
362 Trait(ty::TraitPredicate<'tcx>),
366 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
367 pub enum FromEnv<'tcx> {
368 Trait(ty::TraitPredicate<'tcx>),
372 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
373 pub enum DomainGoal<'tcx> {
374 Holds(WhereClause<'tcx>),
375 WellFormed(WellFormed<'tcx>),
376 FromEnv(FromEnv<'tcx>),
377 Normalize(ty::ProjectionPredicate<'tcx>),
380 pub type PolyDomainGoal<'tcx> = ty::Binder<DomainGoal<'tcx>>;
382 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
383 pub enum QuantifierKind {
388 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
389 pub enum GoalKind<'tcx> {
390 Implies(Clauses<'tcx>, Goal<'tcx>),
391 And(Goal<'tcx>, Goal<'tcx>),
393 DomainGoal(DomainGoal<'tcx>),
394 Quantified(QuantifierKind, ty::Binder<Goal<'tcx>>),
395 Subtype(Ty<'tcx>, Ty<'tcx>),
399 pub type Goal<'tcx> = &'tcx GoalKind<'tcx>;
401 pub type Goals<'tcx> = &'tcx List<Goal<'tcx>>;
403 impl<'tcx> DomainGoal<'tcx> {
404 pub fn into_goal(self) -> GoalKind<'tcx> {
405 GoalKind::DomainGoal(self)
408 pub fn into_program_clause(self) -> ProgramClause<'tcx> {
411 hypotheses: ty::List::empty(),
412 category: ProgramClauseCategory::Other,
417 impl<'tcx> GoalKind<'tcx> {
418 pub fn from_poly_domain_goal(
419 domain_goal: PolyDomainGoal<'tcx>,
421 ) -> GoalKind<'tcx> {
422 match domain_goal.no_bound_vars() {
423 Some(p) => p.into_goal(),
424 None => GoalKind::Quantified(
425 QuantifierKind::Universal,
426 domain_goal.map_bound(|p| tcx.mk_goal(p.into_goal())),
432 /// This matches the definition from Page 7 of "A Proof Procedure for the Logic of Hereditary
433 /// Harrop Formulas".
434 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
435 pub enum Clause<'tcx> {
436 Implies(ProgramClause<'tcx>),
437 ForAll(ty::Binder<ProgramClause<'tcx>>),
441 pub fn category(self) -> ProgramClauseCategory {
443 Clause::Implies(clause) => clause.category,
444 Clause::ForAll(clause) => clause.skip_binder().category,
449 /// Multiple clauses.
450 pub type Clauses<'tcx> = &'tcx List<Clause<'tcx>>;
452 /// A "program clause" has the form `D :- G1, ..., Gn`. It is saying
453 /// that the domain goal `D` is true if `G1...Gn` are provable. This
454 /// is equivalent to the implication `G1..Gn => D`; we usually write
455 /// it with the reverse implication operator `:-` to emphasize the way
456 /// that programs are actually solved (via backchaining, which starts
457 /// with the goal to solve and proceeds from there).
458 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
459 pub struct ProgramClause<'tcx> {
460 /// This goal will be considered true ...
461 pub goal: DomainGoal<'tcx>,
463 /// ... if we can prove these hypotheses (there may be no hypotheses at all):
464 pub hypotheses: Goals<'tcx>,
466 /// Useful for filtering clauses.
467 pub category: ProgramClauseCategory,
470 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
471 pub enum ProgramClauseCategory {
477 /// A set of clauses that we assume to be true.
478 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
479 pub struct Environment<'tcx> {
480 pub clauses: Clauses<'tcx>,
483 impl Environment<'tcx> {
484 pub fn with<G>(self, goal: G) -> InEnvironment<'tcx, G> {
485 InEnvironment { environment: self, goal }
489 /// Something (usually a goal), along with an environment.
490 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
491 pub struct InEnvironment<'tcx, G> {
492 pub environment: Environment<'tcx>,
496 pub type Selection<'tcx> = Vtable<'tcx, PredicateObligation<'tcx>>;
498 #[derive(Clone, Debug, TypeFoldable)]
499 pub enum SelectionError<'tcx> {
501 OutputTypeParameterMismatch(
502 ty::PolyTraitRef<'tcx>,
503 ty::PolyTraitRef<'tcx>,
504 ty::error::TypeError<'tcx>,
506 TraitNotObjectSafe(DefId),
507 ConstEvalFailure(ErrorHandled),
511 pub struct FulfillmentError<'tcx> {
512 pub obligation: PredicateObligation<'tcx>,
513 pub code: FulfillmentErrorCode<'tcx>,
514 /// Diagnostics only: we opportunistically change the `code.span` when we encounter an
515 /// obligation error caused by a call argument. When this is the case, we also signal that in
516 /// this field to ensure accuracy of suggestions.
517 pub points_at_arg_span: bool,
521 pub enum FulfillmentErrorCode<'tcx> {
522 CodeSelectionError(SelectionError<'tcx>),
523 CodeProjectionError(MismatchedProjectionTypes<'tcx>),
524 CodeSubtypeError(ExpectedFound<Ty<'tcx>>, TypeError<'tcx>), // always comes from a SubtypePredicate
528 /// When performing resolution, it is typically the case that there
529 /// can be one of three outcomes:
531 /// - `Ok(Some(r))`: success occurred with result `r`
532 /// - `Ok(None)`: could not definitely determine anything, usually due
533 /// to inconclusive type inference.
534 /// - `Err(e)`: error `e` occurred
535 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
537 /// Given the successful resolution of an obligation, the `Vtable`
538 /// indicates where the vtable comes from. Note that while we call this
539 /// a "vtable", it does not necessarily indicate dynamic dispatch at
540 /// runtime. `Vtable` instances just tell the compiler where to find
541 /// methods, but in generic code those methods are typically statically
542 /// dispatched -- only when an object is constructed is a `Vtable`
543 /// instance reified into an actual vtable.
545 /// For example, the vtable may be tied to a specific impl (case A),
546 /// or it may be relative to some bound that is in scope (case B).
549 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
550 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
551 /// impl Clone for int { ... } // Impl_3
553 /// fn foo<T:Clone>(concrete: Option<Box<int>>,
555 /// mixed: Option<T>) {
557 /// // Case A: Vtable points at a specific impl. Only possible when
558 /// // type is concretely known. If the impl itself has bounded
559 /// // type parameters, Vtable will carry resolutions for those as well:
560 /// concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
562 /// // Case B: Vtable must be provided by caller. This applies when
563 /// // type is a type parameter.
564 /// param.clone(); // VtableParam
566 /// // Case C: A mix of cases A and B.
567 /// mixed.clone(); // Vtable(Impl_1, [VtableParam])
571 /// ### The type parameter `N`
573 /// See explanation on `VtableImplData`.
574 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
575 pub enum Vtable<'tcx, N> {
576 /// Vtable identifying a particular impl.
577 VtableImpl(VtableImplData<'tcx, N>),
579 /// Vtable for auto trait implementations.
580 /// This carries the information and nested obligations with regards
581 /// to an auto implementation for a trait `Trait`. The nested obligations
582 /// ensure the trait implementation holds for all the constituent types.
583 VtableAutoImpl(VtableAutoImplData<N>),
585 /// Successful resolution to an obligation provided by the caller
586 /// for some type parameter. The `Vec<N>` represents the
587 /// obligations incurred from normalizing the where-clause (if
591 /// Virtual calls through an object.
592 VtableObject(VtableObjectData<'tcx, N>),
594 /// Successful resolution for a builtin trait.
595 VtableBuiltin(VtableBuiltinData<N>),
597 /// Vtable automatically generated for a closure. The `DefId` is the ID
598 /// of the closure expression. This is a `VtableImpl` in spirit, but the
599 /// impl is generated by the compiler and does not appear in the source.
600 VtableClosure(VtableClosureData<'tcx, N>),
602 /// Same as above, but for a function pointer type with the given signature.
603 VtableFnPointer(VtableFnPointerData<'tcx, N>),
605 /// Vtable automatically generated for a generator.
606 VtableGenerator(VtableGeneratorData<'tcx, N>),
608 /// Vtable for a trait alias.
609 VtableTraitAlias(VtableTraitAliasData<'tcx, N>),
612 /// Identifies a particular impl in the source, along with a set of
613 /// substitutions from the impl's type/lifetime parameters. The
614 /// `nested` vector corresponds to the nested obligations attached to
615 /// the impl's type parameters.
617 /// The type parameter `N` indicates the type used for "nested
618 /// obligations" that are required by the impl. During type-check, this
619 /// is `Obligation`, as one might expect. During codegen, however, this
620 /// is `()`, because codegen only requires a shallow resolution of an
621 /// impl, and nested obligations are satisfied later.
622 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
623 pub struct VtableImplData<'tcx, N> {
624 pub impl_def_id: DefId,
625 pub substs: SubstsRef<'tcx>,
629 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
630 pub struct VtableGeneratorData<'tcx, N> {
631 pub generator_def_id: DefId,
632 pub substs: SubstsRef<'tcx>,
633 /// Nested obligations. This can be non-empty if the generator
634 /// signature contains associated types.
638 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
639 pub struct VtableClosureData<'tcx, N> {
640 pub closure_def_id: DefId,
641 pub substs: SubstsRef<'tcx>,
642 /// Nested obligations. This can be non-empty if the closure
643 /// signature contains associated types.
647 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
648 pub struct VtableAutoImplData<N> {
649 pub trait_def_id: DefId,
653 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
654 pub struct VtableBuiltinData<N> {
658 /// A vtable for some object-safe trait `Foo` automatically derived
659 /// for the object type `Foo`.
660 #[derive(PartialEq, Eq, Clone, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
661 pub struct VtableObjectData<'tcx, N> {
662 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
663 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
665 /// The vtable is formed by concatenating together the method lists of
666 /// the base object trait and all supertraits; this is the start of
667 /// `upcast_trait_ref`'s methods in that vtable.
668 pub vtable_base: usize,
673 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
674 pub struct VtableFnPointerData<'tcx, N> {
679 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
680 pub struct VtableTraitAliasData<'tcx, N> {
681 pub alias_def_id: DefId,
682 pub substs: SubstsRef<'tcx>,
686 /// Creates predicate obligations from the generic bounds.
687 pub fn predicates_for_generics<'tcx>(
688 cause: ObligationCause<'tcx>,
689 param_env: ty::ParamEnv<'tcx>,
690 generic_bounds: &ty::InstantiatedPredicates<'tcx>,
691 ) -> PredicateObligations<'tcx> {
692 util::predicates_for_generics(cause, 0, param_env, generic_bounds)
695 /// Determines whether the type `ty` is known to meet `bound` and
696 /// returns true if so. Returns false if `ty` either does not meet
697 /// `bound` or is not known to meet bound (note that this is
698 /// conservative towards *no impl*, which is the opposite of the
699 /// `evaluate` methods).
700 pub fn type_known_to_meet_bound_modulo_regions<'a, 'tcx>(
701 infcx: &InferCtxt<'a, 'tcx>,
702 param_env: ty::ParamEnv<'tcx>,
708 "type_known_to_meet_bound_modulo_regions(ty={:?}, bound={:?})",
710 infcx.tcx.def_path_str(def_id)
713 let trait_ref = ty::TraitRef { def_id, substs: infcx.tcx.mk_substs_trait(ty, &[]) };
714 let obligation = Obligation {
716 cause: ObligationCause::misc(span, hir::DUMMY_HIR_ID),
718 predicate: trait_ref.to_predicate(),
721 let result = infcx.predicate_must_hold_modulo_regions(&obligation);
723 "type_known_to_meet_ty={:?} bound={} => {:?}",
725 infcx.tcx.def_path_str(def_id),
729 if result && (ty.has_infer_types() || ty.has_closure_types()) {
730 // Because of inference "guessing", selection can sometimes claim
731 // to succeed while the success requires a guess. To ensure
732 // this function's result remains infallible, we must confirm
733 // that guess. While imperfect, I believe this is sound.
735 // The handling of regions in this area of the code is terrible,
736 // see issue #29149. We should be able to improve on this with
738 let mut fulfill_cx = FulfillmentContext::new_ignoring_regions();
740 // We can use a dummy node-id here because we won't pay any mind
741 // to region obligations that arise (there shouldn't really be any
743 let cause = ObligationCause::misc(span, hir::DUMMY_HIR_ID);
745 fulfill_cx.register_bound(infcx, param_env, ty, def_id, cause);
747 // Note: we only assume something is `Copy` if we can
748 // *definitively* show that it implements `Copy`. Otherwise,
749 // assume it is move; linear is always ok.
750 match fulfill_cx.select_all_or_error(infcx) {
753 "type_known_to_meet_bound_modulo_regions: ty={:?} bound={} success",
755 infcx.tcx.def_path_str(def_id)
761 "type_known_to_meet_bound_modulo_regions: ty={:?} bound={} errors={:?}",
763 infcx.tcx.def_path_str(def_id),
774 fn do_normalize_predicates<'tcx>(
776 region_context: DefId,
777 cause: ObligationCause<'tcx>,
778 elaborated_env: ty::ParamEnv<'tcx>,
779 predicates: Vec<ty::Predicate<'tcx>>,
780 ) -> Result<Vec<ty::Predicate<'tcx>>, ErrorReported> {
782 "do_normalize_predicates(predicates={:?}, region_context={:?}, cause={:?})",
783 predicates, region_context, cause,
785 let span = cause.span;
786 tcx.infer_ctxt().enter(|infcx| {
787 // FIXME. We should really... do something with these region
788 // obligations. But this call just continues the older
789 // behavior (i.e., doesn't cause any new bugs), and it would
790 // take some further refactoring to actually solve them. In
791 // particular, we would have to handle implied bounds
792 // properly, and that code is currently largely confined to
793 // regionck (though I made some efforts to extract it
796 // @arielby: In any case, these obligations are checked
797 // by wfcheck anyway, so I'm not sure we have to check
798 // them here too, and we will remove this function when
799 // we move over to lazy normalization *anyway*.
800 let fulfill_cx = FulfillmentContext::new_ignoring_regions();
802 match fully_normalize(&infcx, fulfill_cx, cause, elaborated_env, &predicates) {
803 Ok(predicates) => predicates,
805 infcx.report_fulfillment_errors(&errors, None, false);
806 return Err(ErrorReported);
810 debug!("do_normalize_predictes: normalized predicates = {:?}", predicates);
812 let region_scope_tree = region::ScopeTree::default();
814 // We can use the `elaborated_env` here; the region code only
815 // cares about declarations like `'a: 'b`.
816 let outlives_env = OutlivesEnvironment::new(elaborated_env);
818 infcx.resolve_regions_and_report_errors(
822 SuppressRegionErrors::default(),
825 let predicates = match infcx.fully_resolve(&predicates) {
826 Ok(predicates) => predicates,
828 // If we encounter a fixup error, it means that some type
829 // variable wound up unconstrained. I actually don't know
830 // if this can happen, and I certainly don't expect it to
831 // happen often, but if it did happen it probably
832 // represents a legitimate failure due to some kind of
833 // unconstrained variable, and it seems better not to ICE,
834 // all things considered.
835 tcx.sess.span_err(span, &fixup_err.to_string());
836 return Err(ErrorReported);
839 if predicates.has_local_value() {
840 // FIXME: shouldn't we, you know, actually report an error here? or an ICE?
848 // FIXME: this is gonna need to be removed ...
849 /// Normalizes the parameter environment, reporting errors if they occur.
850 pub fn normalize_param_env_or_error<'tcx>(
852 region_context: DefId,
853 unnormalized_env: ty::ParamEnv<'tcx>,
854 cause: ObligationCause<'tcx>,
855 ) -> ty::ParamEnv<'tcx> {
856 // I'm not wild about reporting errors here; I'd prefer to
857 // have the errors get reported at a defined place (e.g.,
858 // during typeck). Instead I have all parameter
859 // environments, in effect, going through this function
860 // and hence potentially reporting errors. This ensures of
861 // course that we never forget to normalize (the
862 // alternative seemed like it would involve a lot of
863 // manual invocations of this fn -- and then we'd have to
864 // deal with the errors at each of those sites).
866 // In any case, in practice, typeck constructs all the
867 // parameter environments once for every fn as it goes,
868 // and errors will get reported then; so after typeck we
869 // can be sure that no errors should occur.
872 "normalize_param_env_or_error(region_context={:?}, unnormalized_env={:?}, cause={:?})",
873 region_context, unnormalized_env, cause
876 let mut predicates: Vec<_> =
877 util::elaborate_predicates(tcx, unnormalized_env.caller_bounds.to_vec()).collect();
879 debug!("normalize_param_env_or_error: elaborated-predicates={:?}", predicates);
881 let elaborated_env = ty::ParamEnv::new(
882 tcx.intern_predicates(&predicates),
883 unnormalized_env.reveal,
884 unnormalized_env.def_id,
887 // HACK: we are trying to normalize the param-env inside *itself*. The problem is that
888 // normalization expects its param-env to be already normalized, which means we have
891 // The way we handle this is by normalizing the param-env inside an unnormalized version
892 // of the param-env, which means that if the param-env contains unnormalized projections,
893 // we'll have some normalization failures. This is unfortunate.
895 // Lazy normalization would basically handle this by treating just the
896 // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
898 // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
899 // types, so to make the situation less bad, we normalize all the predicates *but*
900 // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
901 // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
903 // This works fairly well because trait matching does not actually care about param-env
904 // TypeOutlives predicates - these are normally used by regionck.
905 let outlives_predicates: Vec<_> = predicates
906 .drain_filter(|predicate| match predicate {
907 ty::Predicate::TypeOutlives(..) => true,
913 "normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
914 predicates, outlives_predicates
916 let non_outlives_predicates = match do_normalize_predicates(
923 Ok(predicates) => predicates,
924 // An unnormalized env is better than nothing.
925 Err(ErrorReported) => {
926 debug!("normalize_param_env_or_error: errored resolving non-outlives predicates");
927 return elaborated_env;
931 debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates);
933 // Not sure whether it is better to include the unnormalized TypeOutlives predicates
934 // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
935 // predicates here anyway. Keeping them here anyway because it seems safer.
936 let outlives_env: Vec<_> =
937 non_outlives_predicates.iter().chain(&outlives_predicates).cloned().collect();
939 ty::ParamEnv::new(tcx.intern_predicates(&outlives_env), unnormalized_env.reveal, None);
940 let outlives_predicates = match do_normalize_predicates(
947 Ok(predicates) => predicates,
948 // An unnormalized env is better than nothing.
949 Err(ErrorReported) => {
950 debug!("normalize_param_env_or_error: errored resolving outlives predicates");
951 return elaborated_env;
954 debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates);
956 let mut predicates = non_outlives_predicates;
957 predicates.extend(outlives_predicates);
958 debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
960 tcx.intern_predicates(&predicates),
961 unnormalized_env.reveal,
962 unnormalized_env.def_id,
966 pub fn fully_normalize<'a, 'tcx, T>(
967 infcx: &InferCtxt<'a, 'tcx>,
968 mut fulfill_cx: FulfillmentContext<'tcx>,
969 cause: ObligationCause<'tcx>,
970 param_env: ty::ParamEnv<'tcx>,
972 ) -> Result<T, Vec<FulfillmentError<'tcx>>>
974 T: TypeFoldable<'tcx>,
976 debug!("fully_normalize_with_fulfillcx(value={:?})", value);
977 let selcx = &mut SelectionContext::new(infcx);
978 let Normalized { value: normalized_value, obligations } =
979 project::normalize(selcx, param_env, cause, value);
981 "fully_normalize: normalized_value={:?} obligations={:?}",
982 normalized_value, obligations
984 for obligation in obligations {
985 fulfill_cx.register_predicate_obligation(selcx.infcx(), obligation);
988 debug!("fully_normalize: select_all_or_error start");
989 fulfill_cx.select_all_or_error(infcx)?;
990 debug!("fully_normalize: select_all_or_error complete");
991 let resolved_value = infcx.resolve_vars_if_possible(&normalized_value);
992 debug!("fully_normalize: resolved_value={:?}", resolved_value);
996 /// Normalizes the predicates and checks whether they hold in an empty
997 /// environment. If this returns false, then either normalize
998 /// encountered an error or one of the predicates did not hold. Used
999 /// when creating vtables to check for unsatisfiable methods.
1000 fn normalize_and_test_predicates<'tcx>(
1002 predicates: Vec<ty::Predicate<'tcx>>,
1004 debug!("normalize_and_test_predicates(predicates={:?})", predicates);
1006 let result = tcx.infer_ctxt().enter(|infcx| {
1007 let param_env = ty::ParamEnv::reveal_all();
1008 let mut selcx = SelectionContext::new(&infcx);
1009 let mut fulfill_cx = FulfillmentContext::new();
1010 let cause = ObligationCause::dummy();
1011 let Normalized { value: predicates, obligations } =
1012 normalize(&mut selcx, param_env, cause.clone(), &predicates);
1013 for obligation in obligations {
1014 fulfill_cx.register_predicate_obligation(&infcx, obligation);
1016 for predicate in predicates {
1017 let obligation = Obligation::new(cause.clone(), param_env, predicate);
1018 fulfill_cx.register_predicate_obligation(&infcx, obligation);
1021 fulfill_cx.select_all_or_error(&infcx).is_ok()
1023 debug!("normalize_and_test_predicates(predicates={:?}) = {:?}", predicates, result);
1027 fn substitute_normalize_and_test_predicates<'tcx>(
1029 key: (DefId, SubstsRef<'tcx>),
1031 debug!("substitute_normalize_and_test_predicates(key={:?})", key);
1033 let predicates = tcx.predicates_of(key.0).instantiate(tcx, key.1).predicates;
1034 let result = normalize_and_test_predicates(tcx, predicates);
1036 debug!("substitute_normalize_and_test_predicates(key={:?}) = {:?}", key, result);
1040 /// Given a trait `trait_ref`, iterates the vtable entries
1041 /// that come from `trait_ref`, including its supertraits.
1042 #[inline] // FIXME(#35870): avoid closures being unexported due to `impl Trait`.
1043 fn vtable_methods<'tcx>(
1045 trait_ref: ty::PolyTraitRef<'tcx>,
1046 ) -> &'tcx [Option<(DefId, SubstsRef<'tcx>)>] {
1047 debug!("vtable_methods({:?})", trait_ref);
1049 tcx.arena.alloc_from_iter(supertraits(tcx, trait_ref).flat_map(move |trait_ref| {
1050 let trait_methods = tcx
1051 .associated_items(trait_ref.def_id())
1052 .filter(|item| item.kind == ty::AssocKind::Method);
1054 // Now list each method's DefId and InternalSubsts (for within its trait).
1055 // If the method can never be called from this object, produce None.
1056 trait_methods.map(move |trait_method| {
1057 debug!("vtable_methods: trait_method={:?}", trait_method);
1058 let def_id = trait_method.def_id;
1060 // Some methods cannot be called on an object; skip those.
1061 if !tcx.is_vtable_safe_method(trait_ref.def_id(), &trait_method) {
1062 debug!("vtable_methods: not vtable safe");
1066 // The method may have some early-bound lifetimes; add regions for those.
1067 let substs = trait_ref.map_bound(|trait_ref| {
1068 InternalSubsts::for_item(tcx, def_id, |param, _| match param.kind {
1069 GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(),
1070 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const => {
1071 trait_ref.substs[param.index as usize]
1076 // The trait type may have higher-ranked lifetimes in it;
1077 // erase them if they appear, so that we get the type
1078 // at some particular call site.
1080 tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &substs);
1082 // It's possible that the method relies on where-clauses that
1083 // do not hold for this particular set of type parameters.
1084 // Note that this method could then never be called, so we
1085 // do not want to try and codegen it, in that case (see #23435).
1086 let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs);
1087 if !normalize_and_test_predicates(tcx, predicates.predicates) {
1088 debug!("vtable_methods: predicates do not hold");
1092 Some((def_id, substs))
1097 impl<'tcx, O> Obligation<'tcx, O> {
1099 cause: ObligationCause<'tcx>,
1100 param_env: ty::ParamEnv<'tcx>,
1102 ) -> Obligation<'tcx, O> {
1103 Obligation { cause, param_env, recursion_depth: 0, predicate }
1107 cause: ObligationCause<'tcx>,
1108 recursion_depth: usize,
1109 param_env: ty::ParamEnv<'tcx>,
1111 ) -> Obligation<'tcx, O> {
1112 Obligation { cause, param_env, recursion_depth, predicate }
1117 body_id: hir::HirId,
1118 param_env: ty::ParamEnv<'tcx>,
1120 ) -> Obligation<'tcx, O> {
1121 Obligation::new(ObligationCause::misc(span, body_id), param_env, trait_ref)
1124 pub fn with<P>(&self, value: P) -> Obligation<'tcx, P> {
1126 cause: self.cause.clone(),
1127 param_env: self.param_env,
1128 recursion_depth: self.recursion_depth,
1134 impl<'tcx> ObligationCause<'tcx> {
1138 body_id: hir::HirId,
1139 code: ObligationCauseCode<'tcx>,
1140 ) -> ObligationCause<'tcx> {
1141 ObligationCause { span, body_id, code }
1144 pub fn misc(span: Span, body_id: hir::HirId) -> ObligationCause<'tcx> {
1145 ObligationCause { span, body_id, code: MiscObligation }
1148 pub fn dummy() -> ObligationCause<'tcx> {
1149 ObligationCause { span: DUMMY_SP, body_id: hir::CRATE_HIR_ID, code: MiscObligation }
1153 impl<'tcx, N> Vtable<'tcx, N> {
1154 pub fn nested_obligations(self) -> Vec<N> {
1156 VtableImpl(i) => i.nested,
1157 VtableParam(n) => n,
1158 VtableBuiltin(i) => i.nested,
1159 VtableAutoImpl(d) => d.nested,
1160 VtableClosure(c) => c.nested,
1161 VtableGenerator(c) => c.nested,
1162 VtableObject(d) => d.nested,
1163 VtableFnPointer(d) => d.nested,
1164 VtableTraitAlias(d) => d.nested,
1168 pub fn map<M, F>(self, f: F) -> Vtable<'tcx, M>
1173 VtableImpl(i) => VtableImpl(VtableImplData {
1174 impl_def_id: i.impl_def_id,
1176 nested: i.nested.into_iter().map(f).collect(),
1178 VtableParam(n) => VtableParam(n.into_iter().map(f).collect()),
1179 VtableBuiltin(i) => {
1180 VtableBuiltin(VtableBuiltinData { nested: i.nested.into_iter().map(f).collect() })
1182 VtableObject(o) => VtableObject(VtableObjectData {
1183 upcast_trait_ref: o.upcast_trait_ref,
1184 vtable_base: o.vtable_base,
1185 nested: o.nested.into_iter().map(f).collect(),
1187 VtableAutoImpl(d) => VtableAutoImpl(VtableAutoImplData {
1188 trait_def_id: d.trait_def_id,
1189 nested: d.nested.into_iter().map(f).collect(),
1191 VtableClosure(c) => VtableClosure(VtableClosureData {
1192 closure_def_id: c.closure_def_id,
1194 nested: c.nested.into_iter().map(f).collect(),
1196 VtableGenerator(c) => VtableGenerator(VtableGeneratorData {
1197 generator_def_id: c.generator_def_id,
1199 nested: c.nested.into_iter().map(f).collect(),
1201 VtableFnPointer(p) => VtableFnPointer(VtableFnPointerData {
1203 nested: p.nested.into_iter().map(f).collect(),
1205 VtableTraitAlias(d) => VtableTraitAlias(VtableTraitAliasData {
1206 alias_def_id: d.alias_def_id,
1208 nested: d.nested.into_iter().map(f).collect(),
1214 impl<'tcx> FulfillmentError<'tcx> {
1216 obligation: PredicateObligation<'tcx>,
1217 code: FulfillmentErrorCode<'tcx>,
1218 ) -> FulfillmentError<'tcx> {
1219 FulfillmentError { obligation: obligation, code: code, points_at_arg_span: false }
1223 impl<'tcx> TraitObligation<'tcx> {
1224 fn self_ty(&self) -> ty::Binder<Ty<'tcx>> {
1225 self.predicate.map_bound(|p| p.self_ty())
1229 pub fn provide(providers: &mut ty::query::Providers<'_>) {
1230 *providers = ty::query::Providers {
1231 is_object_safe: object_safety::is_object_safe_provider,
1232 specialization_graph_of: specialize::specialization_graph_provider,
1233 specializes: specialize::specializes,
1234 codegen_fulfill_obligation: codegen::codegen_fulfill_obligation,
1236 substitute_normalize_and_test_predicates,
1241 pub trait ExClauseFold<'tcx>
1243 Self: chalk_engine::context::Context + Clone,
1245 fn fold_ex_clause_with<F: TypeFolder<'tcx>>(
1246 ex_clause: &chalk_engine::ExClause<Self>,
1248 ) -> chalk_engine::ExClause<Self>;
1250 fn visit_ex_clause_with<V: TypeVisitor<'tcx>>(
1251 ex_clause: &chalk_engine::ExClause<Self>,
1256 pub trait ChalkContextLift<'tcx>
1258 Self: chalk_engine::context::Context + Clone,
1260 type LiftedExClause: Debug + 'tcx;
1261 type LiftedDelayedLiteral: Debug + 'tcx;
1262 type LiftedLiteral: Debug + 'tcx;
1264 fn lift_ex_clause_to_tcx(
1265 ex_clause: &chalk_engine::ExClause<Self>,
1267 ) -> Option<Self::LiftedExClause>;
1269 fn lift_delayed_literal_to_tcx(
1270 ex_clause: &chalk_engine::DelayedLiteral<Self>,
1272 ) -> Option<Self::LiftedDelayedLiteral>;
1274 fn lift_literal_to_tcx(
1275 ex_clause: &chalk_engine::Literal<Self>,
1277 ) -> Option<Self::LiftedLiteral>;