1 //! Trait Resolution. See the [rustc guide] for more information on how this works.
3 //! [rustc guide]: https://rust-lang.github.io/rustc-guide/traits/resolution.html
9 pub mod error_reporting;
24 use crate::hir::def_id::DefId;
25 use crate::infer::{InferCtxt, SuppressRegionErrors};
26 use crate::infer::outlives::env::OutlivesEnvironment;
27 use crate::middle::region;
28 use crate::mir::interpret::ErrorHandled;
29 use rustc_macros::HashStable;
31 use syntax_pos::{Span, DUMMY_SP};
32 use crate::ty::subst::{InternalSubsts, SubstsRef};
33 use crate::ty::{self, AdtKind, List, Ty, TyCtxt, GenericParamDefKind, ToPredicate};
34 use crate::ty::error::{ExpectedFound, TypeError};
35 use crate::ty::fold::{TypeFolder, TypeFoldable, TypeVisitor};
36 use crate::util::common::ErrorReported;
41 pub use self::SelectionError::*;
42 pub use self::FulfillmentErrorCode::*;
43 pub use self::Vtable::*;
44 pub use self::ObligationCauseCode::*;
46 pub use self::coherence::{add_placeholder_note, orphan_check, overlapping_impls};
47 pub use self::coherence::{OrphanCheckErr, OverlapResult};
48 pub use self::fulfill::{FulfillmentContext, PendingPredicateObligation};
49 pub use self::project::MismatchedProjectionTypes;
50 pub use self::project::{normalize, normalize_projection_type, poly_project_and_unify_type};
51 pub use self::project::{ProjectionCache, ProjectionCacheSnapshot, Reveal, Normalized};
52 pub use self::object_safety::ObjectSafetyViolation;
53 pub use self::object_safety::MethodViolationCode;
54 pub use self::on_unimplemented::{OnUnimplementedDirective, OnUnimplementedNote};
55 pub use self::select::{EvaluationCache, SelectionContext, SelectionCache};
56 pub use self::select::{EvaluationResult, IntercrateAmbiguityCause, OverflowError};
57 pub use self::specialize::{OverlapError, specialization_graph, translate_substs};
58 pub use self::specialize::find_associated_item;
59 pub use self::specialize::specialization_graph::FutureCompatOverlapError;
60 pub use self::specialize::specialization_graph::FutureCompatOverlapErrorKind;
61 pub use self::engine::{TraitEngine, TraitEngineExt};
62 pub use self::util::{elaborate_predicates, elaborate_trait_ref, elaborate_trait_refs};
64 supertraits, supertrait_def_ids, transitive_bounds, Supertraits, SupertraitDefIds,
66 pub use self::util::{expand_trait_aliases, TraitAliasExpander};
68 pub use self::chalk_fulfill::{
69 CanonicalGoal as ChalkCanonicalGoal,
70 FulfillmentContext as ChalkFulfillmentContext
73 pub use self::ObligationCauseCode::*;
74 pub use self::FulfillmentErrorCode::*;
75 pub use self::SelectionError::*;
76 pub use self::Vtable::*;
78 /// Whether to enable bug compatibility with issue #43355.
79 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
80 pub enum IntercrateMode {
85 /// The mode that trait queries run in.
86 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
87 pub enum TraitQueryMode {
88 // Standard/un-canonicalized queries get accurate
89 // spans etc. passed in and hence can do reasonable
90 // error reporting on their own.
92 // Canonicalized queries get dummy spans and hence
93 // must generally propagate errors to
94 // pre-canonicalization callsites.
98 /// An `Obligation` represents some trait reference (e.g., `int: Eq`) for
99 /// which the vtable must be found. The process of finding a vtable is
100 /// called "resolving" the `Obligation`. This process consists of
101 /// either identifying an `impl` (e.g., `impl Eq for int`) that
102 /// provides the required vtable, or else finding a bound that is in
103 /// scope. The eventual result is usually a `Selection` (defined below).
104 #[derive(Clone, PartialEq, Eq, Hash)]
105 pub struct Obligation<'tcx, T> {
106 /// The reason we have to prove this thing.
107 pub cause: ObligationCause<'tcx>,
109 /// The environment in which we should prove this thing.
110 pub param_env: ty::ParamEnv<'tcx>,
112 /// The thing we are trying to prove.
115 /// If we started proving this as a result of trying to prove
116 /// something else, track the total depth to ensure termination.
117 /// If this goes over a certain threshold, we abort compilation --
118 /// in such cases, we can not say whether or not the predicate
119 /// holds for certain. Stupid halting problem; such a drag.
120 pub recursion_depth: usize,
123 pub type PredicateObligation<'tcx> = Obligation<'tcx, ty::Predicate<'tcx>>;
124 pub type TraitObligation<'tcx> = Obligation<'tcx, ty::PolyTraitPredicate<'tcx>>;
126 // `PredicateObligation` is used a lot. Make sure it doesn't unintentionally get bigger.
127 #[cfg(target_arch = "x86_64")]
128 static_assert_size!(PredicateObligation<'_>, 112);
130 /// The reason why we incurred this obligation; used for error reporting.
131 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
132 pub struct ObligationCause<'tcx> {
135 /// The ID of the fn body that triggered this obligation. This is
136 /// used for region obligations to determine the precise
137 /// environment in which the region obligation should be evaluated
138 /// (in particular, closures can add new assumptions). See the
139 /// field `region_obligations` of the `FulfillmentContext` for more
141 pub body_id: hir::HirId,
143 pub code: ObligationCauseCode<'tcx>
146 impl<'tcx> ObligationCause<'tcx> {
147 pub fn span(&self, tcx: TyCtxt<'tcx>) -> Span {
149 ObligationCauseCode::CompareImplMethodObligation { .. } |
150 ObligationCauseCode::MainFunctionType |
151 ObligationCauseCode::StartFunctionType => {
152 tcx.sess.source_map().def_span(self.span)
154 ObligationCauseCode::MatchExpressionArm(
155 box MatchExpressionArmCause { arm_span, .. }) => arm_span,
161 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
162 pub enum ObligationCauseCode<'tcx> {
163 /// Not well classified or should be obvious from the span.
166 /// A slice or array is WF only if `T: Sized`.
169 /// A tuple is WF only if its middle elements are `Sized`.
172 /// This is the trait reference from the given projection.
173 ProjectionWf(ty::ProjectionTy<'tcx>),
175 /// In an impl of trait `X` for type `Y`, type `Y` must
176 /// also implement all supertraits of `X`.
177 ItemObligation(DefId),
179 /// Like `ItemObligation`, but with extra detail on the source of the obligation.
180 BindingObligation(DefId, Span),
182 /// A type like `&'a T` is WF only if `T: 'a`.
183 ReferenceOutlivesReferent(Ty<'tcx>),
185 /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
186 ObjectTypeBound(Ty<'tcx>, ty::Region<'tcx>),
188 /// Obligation incurred due to an object cast.
189 ObjectCastObligation(/* Object type */ Ty<'tcx>),
191 /// Obligation incurred due to a coercion.
192 Coercion { source: Ty<'tcx>, target: Ty<'tcx> },
194 // Various cases where expressions must be sized/copy/etc:
195 /// L = X implies that L is Sized
197 /// (x1, .., xn) must be Sized
198 TupleInitializerSized,
199 /// S { ... } must be Sized
200 StructInitializerSized,
201 /// Type of each variable must be Sized
202 VariableType(hir::HirId),
203 /// Argument type must be Sized
205 /// Return type must be Sized
207 /// Yield type must be Sized
209 /// [T,..n] --> T must be Copy. If `true`, suggest `const_in_array_repeat_expressions` feature
213 /// Types of fields (other than the last, except for packed structs) in a struct must be sized.
214 FieldSized { adt_kind: AdtKind, last: bool },
216 /// Constant expressions must be sized.
219 /// Static items must have `Sync` type
222 BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
224 ImplDerivedObligation(DerivedObligationCause<'tcx>),
226 /// Error derived when matching traits/impls; see ObligationCause for more details
227 CompareImplMethodObligation {
228 item_name: ast::Name,
229 impl_item_def_id: DefId,
230 trait_item_def_id: DefId,
233 /// Checking that this expression can be assigned where it needs to be
234 // FIXME(eddyb) #11161 is the original Expr required?
237 /// Computing common supertype in the arms of a match expression
238 MatchExpressionArm(Box<MatchExpressionArmCause<'tcx>>),
240 /// Computing common supertype in the pattern guard for the arms of a match expression
241 MatchExpressionArmPattern { span: Span, ty: Ty<'tcx> },
243 /// Constants in patterns must have `Structural` type.
244 ConstPatternStructural,
246 /// Computing common supertype in an if expression
247 IfExpression(Box<IfExpressionCause>),
249 /// Computing common supertype of an if expression with no else counter-part
250 IfExpressionWithNoElse,
252 /// `main` has wrong type
255 /// `start` has wrong type
258 /// Intrinsic has wrong type
264 /// `return` with no expression
267 /// `return` with an expression
268 ReturnValue(hir::HirId),
270 /// Return type of this function
273 /// Block implicit return
274 BlockTailExpression(hir::HirId),
276 /// #[feature(trivial_bounds)] is not enabled
279 AssocTypeBound(Box<AssocTypeBoundData>),
282 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
283 pub struct AssocTypeBoundData {
284 pub impl_span: Option<Span>,
286 pub bounds: Vec<Span>,
289 // `ObligationCauseCode` is used a lot. Make sure it doesn't unintentionally get bigger.
290 #[cfg(target_arch = "x86_64")]
291 static_assert_size!(ObligationCauseCode<'_>, 32);
293 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
294 pub struct MatchExpressionArmCause<'tcx> {
296 pub source: hir::MatchSource,
297 pub prior_arms: Vec<Span>,
298 pub last_ty: Ty<'tcx>,
299 pub discrim_hir_id: hir::HirId,
302 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
303 pub struct IfExpressionCause {
305 pub outer: Option<Span>,
306 pub semicolon: Option<Span>,
309 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
310 pub struct DerivedObligationCause<'tcx> {
311 /// The trait reference of the parent obligation that led to the
312 /// current obligation. Note that only trait obligations lead to
313 /// derived obligations, so we just store the trait reference here
315 parent_trait_ref: ty::PolyTraitRef<'tcx>,
317 /// The parent trait had this cause.
318 parent_code: Rc<ObligationCauseCode<'tcx>>
321 pub type Obligations<'tcx, O> = Vec<Obligation<'tcx, O>>;
322 pub type PredicateObligations<'tcx> = Vec<PredicateObligation<'tcx>>;
323 pub type TraitObligations<'tcx> = Vec<TraitObligation<'tcx>>;
325 /// The following types:
333 /// * `InEnvironment`,
334 /// are used for representing the trait system in the form of
335 /// logic programming clauses. They are part of the interface
336 /// for the chalk SLG solver.
337 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable)]
338 pub enum WhereClause<'tcx> {
339 Implemented(ty::TraitPredicate<'tcx>),
340 ProjectionEq(ty::ProjectionPredicate<'tcx>),
341 RegionOutlives(ty::RegionOutlivesPredicate<'tcx>),
342 TypeOutlives(ty::TypeOutlivesPredicate<'tcx>),
345 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable)]
346 pub enum WellFormed<'tcx> {
347 Trait(ty::TraitPredicate<'tcx>),
351 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable)]
352 pub enum FromEnv<'tcx> {
353 Trait(ty::TraitPredicate<'tcx>),
357 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable)]
358 pub enum DomainGoal<'tcx> {
359 Holds(WhereClause<'tcx>),
360 WellFormed(WellFormed<'tcx>),
361 FromEnv(FromEnv<'tcx>),
362 Normalize(ty::ProjectionPredicate<'tcx>),
365 pub type PolyDomainGoal<'tcx> = ty::Binder<DomainGoal<'tcx>>;
367 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
368 pub enum QuantifierKind {
373 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
374 pub enum GoalKind<'tcx> {
375 Implies(Clauses<'tcx>, Goal<'tcx>),
376 And(Goal<'tcx>, Goal<'tcx>),
378 DomainGoal(DomainGoal<'tcx>),
379 Quantified(QuantifierKind, ty::Binder<Goal<'tcx>>),
380 Subtype(Ty<'tcx>, Ty<'tcx>),
384 pub type Goal<'tcx> = &'tcx GoalKind<'tcx>;
386 pub type Goals<'tcx> = &'tcx List<Goal<'tcx>>;
388 impl<'tcx> DomainGoal<'tcx> {
389 pub fn into_goal(self) -> GoalKind<'tcx> {
390 GoalKind::DomainGoal(self)
393 pub fn into_program_clause(self) -> ProgramClause<'tcx> {
396 hypotheses: ty::List::empty(),
397 category: ProgramClauseCategory::Other,
402 impl<'tcx> GoalKind<'tcx> {
403 pub fn from_poly_domain_goal(
404 domain_goal: PolyDomainGoal<'tcx>,
406 ) -> GoalKind<'tcx> {
407 match domain_goal.no_bound_vars() {
408 Some(p) => p.into_goal(),
409 None => GoalKind::Quantified(
410 QuantifierKind::Universal,
411 domain_goal.map_bound(|p| tcx.mk_goal(p.into_goal()))
417 /// This matches the definition from Page 7 of "A Proof Procedure for the Logic of Hereditary
418 /// Harrop Formulas".
419 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
420 pub enum Clause<'tcx> {
421 Implies(ProgramClause<'tcx>),
422 ForAll(ty::Binder<ProgramClause<'tcx>>),
426 pub fn category(self) -> ProgramClauseCategory {
428 Clause::Implies(clause) => clause.category,
429 Clause::ForAll(clause) => clause.skip_binder().category,
434 /// Multiple clauses.
435 pub type Clauses<'tcx> = &'tcx List<Clause<'tcx>>;
437 /// A "program clause" has the form `D :- G1, ..., Gn`. It is saying
438 /// that the domain goal `D` is true if `G1...Gn` are provable. This
439 /// is equivalent to the implication `G1..Gn => D`; we usually write
440 /// it with the reverse implication operator `:-` to emphasize the way
441 /// that programs are actually solved (via backchaining, which starts
442 /// with the goal to solve and proceeds from there).
443 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
444 pub struct ProgramClause<'tcx> {
445 /// This goal will be considered true ...
446 pub goal: DomainGoal<'tcx>,
448 /// ... if we can prove these hypotheses (there may be no hypotheses at all):
449 pub hypotheses: Goals<'tcx>,
451 /// Useful for filtering clauses.
452 pub category: ProgramClauseCategory,
455 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
456 pub enum ProgramClauseCategory {
462 /// A set of clauses that we assume to be true.
463 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
464 pub struct Environment<'tcx> {
465 pub clauses: Clauses<'tcx>,
468 impl Environment<'tcx> {
469 pub fn with<G>(self, goal: G) -> InEnvironment<'tcx, G> {
477 /// Something (usually a goal), along with an environment.
478 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
479 pub struct InEnvironment<'tcx, G> {
480 pub environment: Environment<'tcx>,
484 pub type Selection<'tcx> = Vtable<'tcx, PredicateObligation<'tcx>>;
486 #[derive(Clone,Debug)]
487 pub enum SelectionError<'tcx> {
489 OutputTypeParameterMismatch(ty::PolyTraitRef<'tcx>,
490 ty::PolyTraitRef<'tcx>,
491 ty::error::TypeError<'tcx>),
492 TraitNotObjectSafe(DefId),
493 ConstEvalFailure(ErrorHandled),
497 EnumTypeFoldableImpl! {
498 impl<'tcx> TypeFoldable<'tcx> for SelectionError<'tcx> {
499 (SelectionError::Unimplemented),
500 (SelectionError::OutputTypeParameterMismatch)(a, b, c),
501 (SelectionError::TraitNotObjectSafe)(a),
502 (SelectionError::ConstEvalFailure)(a),
503 (SelectionError::Overflow),
507 pub struct FulfillmentError<'tcx> {
508 pub obligation: PredicateObligation<'tcx>,
509 pub code: FulfillmentErrorCode<'tcx>,
510 /// Diagnostics only: we opportunistically change the `code.span` when we encounter an
511 /// obligation error caused by a call argument. When this is the case, we also signal that in
512 /// this field to ensure accuracy of suggestions.
513 pub points_at_arg_span: bool,
517 pub enum FulfillmentErrorCode<'tcx> {
518 CodeSelectionError(SelectionError<'tcx>),
519 CodeProjectionError(MismatchedProjectionTypes<'tcx>),
520 CodeSubtypeError(ExpectedFound<Ty<'tcx>>,
521 TypeError<'tcx>), // always comes from a SubtypePredicate
525 /// When performing resolution, it is typically the case that there
526 /// can be one of three outcomes:
528 /// - `Ok(Some(r))`: success occurred with result `r`
529 /// - `Ok(None)`: could not definitely determine anything, usually due
530 /// to inconclusive type inference.
531 /// - `Err(e)`: error `e` occurred
532 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
534 /// Given the successful resolution of an obligation, the `Vtable`
535 /// indicates where the vtable comes from. Note that while we call this
536 /// a "vtable", it does not necessarily indicate dynamic dispatch at
537 /// runtime. `Vtable` instances just tell the compiler where to find
538 /// methods, but in generic code those methods are typically statically
539 /// dispatched -- only when an object is constructed is a `Vtable`
540 /// instance reified into an actual vtable.
542 /// For example, the vtable may be tied to a specific impl (case A),
543 /// or it may be relative to some bound that is in scope (case B).
546 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
547 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
548 /// impl Clone for int { ... } // Impl_3
550 /// fn foo<T:Clone>(concrete: Option<Box<int>>,
552 /// mixed: Option<T>) {
554 /// // Case A: Vtable points at a specific impl. Only possible when
555 /// // type is concretely known. If the impl itself has bounded
556 /// // type parameters, Vtable will carry resolutions for those as well:
557 /// concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
559 /// // Case B: Vtable must be provided by caller. This applies when
560 /// // type is a type parameter.
561 /// param.clone(); // VtableParam
563 /// // Case C: A mix of cases A and B.
564 /// mixed.clone(); // Vtable(Impl_1, [VtableParam])
568 /// ### The type parameter `N`
570 /// See explanation on `VtableImplData`.
571 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
572 pub enum Vtable<'tcx, N> {
573 /// Vtable identifying a particular impl.
574 VtableImpl(VtableImplData<'tcx, N>),
576 /// Vtable for auto trait implementations.
577 /// This carries the information and nested obligations with regards
578 /// to an auto implementation for a trait `Trait`. The nested obligations
579 /// ensure the trait implementation holds for all the constituent types.
580 VtableAutoImpl(VtableAutoImplData<N>),
582 /// Successful resolution to an obligation provided by the caller
583 /// for some type parameter. The `Vec<N>` represents the
584 /// obligations incurred from normalizing the where-clause (if
588 /// Virtual calls through an object.
589 VtableObject(VtableObjectData<'tcx, N>),
591 /// Successful resolution for a builtin trait.
592 VtableBuiltin(VtableBuiltinData<N>),
594 /// Vtable automatically generated for a closure. The `DefId` is the ID
595 /// of the closure expression. This is a `VtableImpl` in spirit, but the
596 /// impl is generated by the compiler and does not appear in the source.
597 VtableClosure(VtableClosureData<'tcx, N>),
599 /// Same as above, but for a function pointer type with the given signature.
600 VtableFnPointer(VtableFnPointerData<'tcx, N>),
602 /// Vtable automatically generated for a generator.
603 VtableGenerator(VtableGeneratorData<'tcx, N>),
605 /// Vtable for a trait alias.
606 VtableTraitAlias(VtableTraitAliasData<'tcx, N>),
609 /// Identifies a particular impl in the source, along with a set of
610 /// substitutions from the impl's type/lifetime parameters. The
611 /// `nested` vector corresponds to the nested obligations attached to
612 /// the impl's type parameters.
614 /// The type parameter `N` indicates the type used for "nested
615 /// obligations" that are required by the impl. During type check, this
616 /// is `Obligation`, as one might expect. During codegen, however, this
617 /// is `()`, because codegen only requires a shallow resolution of an
618 /// impl, and nested obligations are satisfied later.
619 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
620 pub struct VtableImplData<'tcx, N> {
621 pub impl_def_id: DefId,
622 pub substs: SubstsRef<'tcx>,
626 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
627 pub struct VtableGeneratorData<'tcx, N> {
628 pub generator_def_id: DefId,
629 pub substs: SubstsRef<'tcx>,
630 /// Nested obligations. This can be non-empty if the generator
631 /// signature contains associated types.
635 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
636 pub struct VtableClosureData<'tcx, N> {
637 pub closure_def_id: DefId,
638 pub substs: SubstsRef<'tcx>,
639 /// Nested obligations. This can be non-empty if the closure
640 /// signature contains associated types.
644 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
645 pub struct VtableAutoImplData<N> {
646 pub trait_def_id: DefId,
650 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
651 pub struct VtableBuiltinData<N> {
655 /// A vtable for some object-safe trait `Foo` automatically derived
656 /// for the object type `Foo`.
657 #[derive(PartialEq, Eq, Clone, RustcEncodable, RustcDecodable, HashStable)]
658 pub struct VtableObjectData<'tcx, N> {
659 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
660 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
662 /// The vtable is formed by concatenating together the method lists of
663 /// the base object trait and all supertraits; this is the start of
664 /// `upcast_trait_ref`'s methods in that vtable.
665 pub vtable_base: usize,
670 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
671 pub struct VtableFnPointerData<'tcx, N> {
676 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
677 pub struct VtableTraitAliasData<'tcx, N> {
678 pub alias_def_id: DefId,
679 pub substs: SubstsRef<'tcx>,
683 /// Creates predicate obligations from the generic bounds.
684 pub fn predicates_for_generics<'tcx>(
685 cause: ObligationCause<'tcx>,
686 param_env: ty::ParamEnv<'tcx>,
687 generic_bounds: &ty::InstantiatedPredicates<'tcx>,
688 ) -> PredicateObligations<'tcx> {
689 util::predicates_for_generics(cause, 0, param_env, generic_bounds)
692 /// Determines whether the type `ty` is known to meet `bound` and
693 /// returns true if so. Returns false if `ty` either does not meet
694 /// `bound` or is not known to meet bound (note that this is
695 /// conservative towards *no impl*, which is the opposite of the
696 /// `evaluate` methods).
697 pub fn type_known_to_meet_bound_modulo_regions<'a, 'tcx>(
698 infcx: &InferCtxt<'a, 'tcx>,
699 param_env: ty::ParamEnv<'tcx>,
704 debug!("type_known_to_meet_bound_modulo_regions(ty={:?}, bound={:?})",
706 infcx.tcx.def_path_str(def_id));
708 let trait_ref = ty::TraitRef {
710 substs: infcx.tcx.mk_substs_trait(ty, &[]),
712 let obligation = Obligation {
714 cause: ObligationCause::misc(span, hir::DUMMY_HIR_ID),
716 predicate: trait_ref.to_predicate(),
719 let result = infcx.predicate_must_hold_modulo_regions(&obligation);
720 debug!("type_known_to_meet_ty={:?} bound={} => {:?}",
721 ty, infcx.tcx.def_path_str(def_id), result);
723 if result && (ty.has_infer_types() || ty.has_closure_types()) {
724 // Because of inference "guessing", selection can sometimes claim
725 // to succeed while the success requires a guess. To ensure
726 // this function's result remains infallible, we must confirm
727 // that guess. While imperfect, I believe this is sound.
729 // The handling of regions in this area of the code is terrible,
730 // see issue #29149. We should be able to improve on this with
732 let mut fulfill_cx = FulfillmentContext::new_ignoring_regions();
734 // We can use a dummy node-id here because we won't pay any mind
735 // to region obligations that arise (there shouldn't really be any
737 let cause = ObligationCause::misc(span, hir::DUMMY_HIR_ID);
739 fulfill_cx.register_bound(infcx, param_env, ty, def_id, cause);
741 // Note: we only assume something is `Copy` if we can
742 // *definitively* show that it implements `Copy`. Otherwise,
743 // assume it is move; linear is always ok.
744 match fulfill_cx.select_all_or_error(infcx) {
746 debug!("type_known_to_meet_bound_modulo_regions: ty={:?} bound={} success",
748 infcx.tcx.def_path_str(def_id));
752 debug!("type_known_to_meet_bound_modulo_regions: ty={:?} bound={} errors={:?}",
754 infcx.tcx.def_path_str(def_id),
764 fn do_normalize_predicates<'tcx>(
766 region_context: DefId,
767 cause: ObligationCause<'tcx>,
768 elaborated_env: ty::ParamEnv<'tcx>,
769 predicates: Vec<ty::Predicate<'tcx>>,
770 ) -> Result<Vec<ty::Predicate<'tcx>>, ErrorReported> {
772 "do_normalize_predicates(predicates={:?}, region_context={:?}, cause={:?})",
777 let span = cause.span;
778 tcx.infer_ctxt().enter(|infcx| {
779 // FIXME. We should really... do something with these region
780 // obligations. But this call just continues the older
781 // behavior (i.e., doesn't cause any new bugs), and it would
782 // take some further refactoring to actually solve them. In
783 // particular, we would have to handle implied bounds
784 // properly, and that code is currently largely confined to
785 // regionck (though I made some efforts to extract it
788 // @arielby: In any case, these obligations are checked
789 // by wfcheck anyway, so I'm not sure we have to check
790 // them here too, and we will remove this function when
791 // we move over to lazy normalization *anyway*.
792 let fulfill_cx = FulfillmentContext::new_ignoring_regions();
793 let predicates = match fully_normalize(
800 Ok(predicates) => predicates,
802 infcx.report_fulfillment_errors(&errors, None, false);
803 return Err(ErrorReported)
807 debug!("do_normalize_predictes: normalized predicates = {:?}", predicates);
809 let region_scope_tree = region::ScopeTree::default();
811 // We can use the `elaborated_env` here; the region code only
812 // cares about declarations like `'a: 'b`.
813 let outlives_env = OutlivesEnvironment::new(elaborated_env);
815 infcx.resolve_regions_and_report_errors(
819 SuppressRegionErrors::default(),
822 let predicates = match infcx.fully_resolve(&predicates) {
823 Ok(predicates) => predicates,
825 // If we encounter a fixup error, it means that some type
826 // variable wound up unconstrained. I actually don't know
827 // if this can happen, and I certainly don't expect it to
828 // happen often, but if it did happen it probably
829 // represents a legitimate failure due to some kind of
830 // unconstrained variable, and it seems better not to ICE,
831 // all things considered.
832 tcx.sess.span_err(span, &fixup_err.to_string());
833 return Err(ErrorReported)
836 if predicates.has_local_value() {
837 // FIXME: shouldn't we, you know, actually report an error here? or an ICE?
845 // FIXME: this is gonna need to be removed ...
846 /// Normalizes the parameter environment, reporting errors if they occur.
847 pub fn normalize_param_env_or_error<'tcx>(
849 region_context: DefId,
850 unnormalized_env: ty::ParamEnv<'tcx>,
851 cause: ObligationCause<'tcx>,
852 ) -> ty::ParamEnv<'tcx> {
853 // I'm not wild about reporting errors here; I'd prefer to
854 // have the errors get reported at a defined place (e.g.,
855 // during typeck). Instead I have all parameter
856 // environments, in effect, going through this function
857 // and hence potentially reporting errors. This ensures of
858 // course that we never forget to normalize (the
859 // alternative seemed like it would involve a lot of
860 // manual invocations of this fn -- and then we'd have to
861 // deal with the errors at each of those sites).
863 // In any case, in practice, typeck constructs all the
864 // parameter environments once for every fn as it goes,
865 // and errors will get reported then; so after typeck we
866 // can be sure that no errors should occur.
868 debug!("normalize_param_env_or_error(region_context={:?}, unnormalized_env={:?}, cause={:?})",
869 region_context, unnormalized_env, cause);
871 let mut predicates: Vec<_> =
872 util::elaborate_predicates(tcx, unnormalized_env.caller_bounds.to_vec())
875 debug!("normalize_param_env_or_error: elaborated-predicates={:?}",
878 let elaborated_env = ty::ParamEnv::new(
879 tcx.intern_predicates(&predicates),
880 unnormalized_env.reveal,
881 unnormalized_env.def_id
884 // HACK: we are trying to normalize the param-env inside *itself*. The problem is that
885 // normalization expects its param-env to be already normalized, which means we have
888 // The way we handle this is by normalizing the param-env inside an unnormalized version
889 // of the param-env, which means that if the param-env contains unnormalized projections,
890 // we'll have some normalization failures. This is unfortunate.
892 // Lazy normalization would basically handle this by treating just the
893 // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
895 // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
896 // types, so to make the situation less bad, we normalize all the predicates *but*
897 // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
898 // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
900 // This works fairly well because trait matching does not actually care about param-env
901 // TypeOutlives predicates - these are normally used by regionck.
902 let outlives_predicates: Vec<_> = predicates.drain_filter(|predicate| {
904 ty::Predicate::TypeOutlives(..) => true,
909 debug!("normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
910 predicates, outlives_predicates);
911 let non_outlives_predicates =
912 match do_normalize_predicates(tcx, region_context, cause.clone(),
913 elaborated_env, predicates) {
914 Ok(predicates) => predicates,
915 // An unnormalized env is better than nothing.
916 Err(ErrorReported) => {
917 debug!("normalize_param_env_or_error: errored resolving non-outlives predicates");
918 return elaborated_env
922 debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates);
924 // Not sure whether it is better to include the unnormalized TypeOutlives predicates
925 // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
926 // predicates here anyway. Keeping them here anyway because it seems safer.
927 let outlives_env: Vec<_> =
928 non_outlives_predicates.iter().chain(&outlives_predicates).cloned().collect();
929 let outlives_env = ty::ParamEnv::new(
930 tcx.intern_predicates(&outlives_env),
931 unnormalized_env.reveal,
934 let outlives_predicates =
935 match do_normalize_predicates(tcx, region_context, cause,
936 outlives_env, outlives_predicates) {
937 Ok(predicates) => predicates,
938 // An unnormalized env is better than nothing.
939 Err(ErrorReported) => {
940 debug!("normalize_param_env_or_error: errored resolving outlives predicates");
941 return elaborated_env
944 debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates);
946 let mut predicates = non_outlives_predicates;
947 predicates.extend(outlives_predicates);
948 debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
950 tcx.intern_predicates(&predicates),
951 unnormalized_env.reveal,
952 unnormalized_env.def_id
956 pub fn fully_normalize<'a, 'tcx, T>(
957 infcx: &InferCtxt<'a, 'tcx>,
958 mut fulfill_cx: FulfillmentContext<'tcx>,
959 cause: ObligationCause<'tcx>,
960 param_env: ty::ParamEnv<'tcx>,
962 ) -> Result<T, Vec<FulfillmentError<'tcx>>>
964 T: TypeFoldable<'tcx>,
966 debug!("fully_normalize_with_fulfillcx(value={:?})", value);
967 let selcx = &mut SelectionContext::new(infcx);
968 let Normalized { value: normalized_value, obligations } =
969 project::normalize(selcx, param_env, cause, value);
970 debug!("fully_normalize: normalized_value={:?} obligations={:?}",
973 for obligation in obligations {
974 fulfill_cx.register_predicate_obligation(selcx.infcx(), obligation);
977 debug!("fully_normalize: select_all_or_error start");
978 fulfill_cx.select_all_or_error(infcx)?;
979 debug!("fully_normalize: select_all_or_error complete");
980 let resolved_value = infcx.resolve_vars_if_possible(&normalized_value);
981 debug!("fully_normalize: resolved_value={:?}", resolved_value);
985 /// Normalizes the predicates and checks whether they hold in an empty
986 /// environment. If this returns false, then either normalize
987 /// encountered an error or one of the predicates did not hold. Used
988 /// when creating vtables to check for unsatisfiable methods.
989 fn normalize_and_test_predicates<'tcx>(
991 predicates: Vec<ty::Predicate<'tcx>>,
993 debug!("normalize_and_test_predicates(predicates={:?})",
996 let result = tcx.infer_ctxt().enter(|infcx| {
997 let param_env = ty::ParamEnv::reveal_all();
998 let mut selcx = SelectionContext::new(&infcx);
999 let mut fulfill_cx = FulfillmentContext::new();
1000 let cause = ObligationCause::dummy();
1001 let Normalized { value: predicates, obligations } =
1002 normalize(&mut selcx, param_env, cause.clone(), &predicates);
1003 for obligation in obligations {
1004 fulfill_cx.register_predicate_obligation(&infcx, obligation);
1006 for predicate in predicates {
1007 let obligation = Obligation::new(cause.clone(), param_env, predicate);
1008 fulfill_cx.register_predicate_obligation(&infcx, obligation);
1011 fulfill_cx.select_all_or_error(&infcx).is_ok()
1013 debug!("normalize_and_test_predicates(predicates={:?}) = {:?}",
1014 predicates, result);
1018 fn substitute_normalize_and_test_predicates<'tcx>(
1020 key: (DefId, SubstsRef<'tcx>),
1022 debug!("substitute_normalize_and_test_predicates(key={:?})",
1025 let predicates = tcx.predicates_of(key.0).instantiate(tcx, key.1).predicates;
1026 let result = normalize_and_test_predicates(tcx, predicates);
1028 debug!("substitute_normalize_and_test_predicates(key={:?}) = {:?}",
1033 /// Given a trait `trait_ref`, iterates the vtable entries
1034 /// that come from `trait_ref`, including its supertraits.
1035 #[inline] // FIXME(#35870): avoid closures being unexported due to `impl Trait`.
1036 fn vtable_methods<'tcx>(
1038 trait_ref: ty::PolyTraitRef<'tcx>,
1039 ) -> &'tcx [Option<(DefId, SubstsRef<'tcx>)>] {
1040 debug!("vtable_methods({:?})", trait_ref);
1042 tcx.arena.alloc_from_iter(
1043 supertraits(tcx, trait_ref).flat_map(move |trait_ref| {
1044 let trait_methods = tcx.associated_items(trait_ref.def_id())
1045 .filter(|item| item.kind == ty::AssocKind::Method);
1047 // Now list each method's DefId and InternalSubsts (for within its trait).
1048 // If the method can never be called from this object, produce None.
1049 trait_methods.map(move |trait_method| {
1050 debug!("vtable_methods: trait_method={:?}", trait_method);
1051 let def_id = trait_method.def_id;
1053 // Some methods cannot be called on an object; skip those.
1054 if !tcx.is_vtable_safe_method(trait_ref.def_id(), &trait_method) {
1055 debug!("vtable_methods: not vtable safe");
1059 // the method may have some early-bound lifetimes, add
1060 // regions for those
1061 let substs = trait_ref.map_bound(|trait_ref|
1062 InternalSubsts::for_item(tcx, def_id, |param, _|
1064 GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(),
1065 GenericParamDefKind::Type { .. } |
1066 GenericParamDefKind::Const => {
1067 trait_ref.substs[param.index as usize]
1073 // the trait type may have higher-ranked lifetimes in it;
1074 // so erase them if they appear, so that we get the type
1075 // at some particular call site
1076 let substs = tcx.normalize_erasing_late_bound_regions(
1077 ty::ParamEnv::reveal_all(),
1081 // It's possible that the method relies on where clauses that
1082 // do not hold for this particular set of type parameters.
1083 // Note that this method could then never be called, so we
1084 // do not want to try and codegen it, in that case (see #23435).
1085 let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs);
1086 if !normalize_and_test_predicates(tcx, predicates.predicates) {
1087 debug!("vtable_methods: predicates do not hold");
1091 Some((def_id, substs))
1097 impl<'tcx, O> Obligation<'tcx, O> {
1098 pub fn new(cause: ObligationCause<'tcx>,
1099 param_env: ty::ParamEnv<'tcx>,
1101 -> Obligation<'tcx, O>
1103 Obligation { cause, param_env, recursion_depth: 0, predicate }
1106 fn with_depth(cause: ObligationCause<'tcx>,
1107 recursion_depth: usize,
1108 param_env: ty::ParamEnv<'tcx>,
1110 -> Obligation<'tcx, O>
1112 Obligation { cause, param_env, recursion_depth, predicate }
1115 pub fn misc(span: Span,
1116 body_id: hir::HirId,
1117 param_env: ty::ParamEnv<'tcx>,
1119 -> Obligation<'tcx, O> {
1120 Obligation::new(ObligationCause::misc(span, body_id), param_env, trait_ref)
1123 pub fn with<P>(&self, value: P) -> Obligation<'tcx,P> {
1124 Obligation { cause: self.cause.clone(),
1125 param_env: self.param_env,
1126 recursion_depth: self.recursion_depth,
1131 impl<'tcx> ObligationCause<'tcx> {
1133 pub fn new(span: Span,
1134 body_id: hir::HirId,
1135 code: ObligationCauseCode<'tcx>)
1136 -> ObligationCause<'tcx> {
1137 ObligationCause { span, body_id, code }
1140 pub fn misc(span: Span, body_id: hir::HirId) -> ObligationCause<'tcx> {
1141 ObligationCause { span, body_id, code: MiscObligation }
1144 pub fn dummy() -> ObligationCause<'tcx> {
1145 ObligationCause { span: DUMMY_SP, body_id: hir::CRATE_HIR_ID, code: MiscObligation }
1149 impl<'tcx, N> Vtable<'tcx, N> {
1150 pub fn nested_obligations(self) -> Vec<N> {
1152 VtableImpl(i) => i.nested,
1153 VtableParam(n) => n,
1154 VtableBuiltin(i) => i.nested,
1155 VtableAutoImpl(d) => d.nested,
1156 VtableClosure(c) => c.nested,
1157 VtableGenerator(c) => c.nested,
1158 VtableObject(d) => d.nested,
1159 VtableFnPointer(d) => d.nested,
1160 VtableTraitAlias(d) => d.nested,
1164 pub fn map<M, F>(self, f: F) -> Vtable<'tcx, M> where F: FnMut(N) -> M {
1166 VtableImpl(i) => VtableImpl(VtableImplData {
1167 impl_def_id: i.impl_def_id,
1169 nested: i.nested.into_iter().map(f).collect(),
1171 VtableParam(n) => VtableParam(n.into_iter().map(f).collect()),
1172 VtableBuiltin(i) => VtableBuiltin(VtableBuiltinData {
1173 nested: i.nested.into_iter().map(f).collect(),
1175 VtableObject(o) => VtableObject(VtableObjectData {
1176 upcast_trait_ref: o.upcast_trait_ref,
1177 vtable_base: o.vtable_base,
1178 nested: o.nested.into_iter().map(f).collect(),
1180 VtableAutoImpl(d) => VtableAutoImpl(VtableAutoImplData {
1181 trait_def_id: d.trait_def_id,
1182 nested: d.nested.into_iter().map(f).collect(),
1184 VtableClosure(c) => VtableClosure(VtableClosureData {
1185 closure_def_id: c.closure_def_id,
1187 nested: c.nested.into_iter().map(f).collect(),
1189 VtableGenerator(c) => VtableGenerator(VtableGeneratorData {
1190 generator_def_id: c.generator_def_id,
1192 nested: c.nested.into_iter().map(f).collect(),
1194 VtableFnPointer(p) => VtableFnPointer(VtableFnPointerData {
1196 nested: p.nested.into_iter().map(f).collect(),
1198 VtableTraitAlias(d) => VtableTraitAlias(VtableTraitAliasData {
1199 alias_def_id: d.alias_def_id,
1201 nested: d.nested.into_iter().map(f).collect(),
1207 impl<'tcx> FulfillmentError<'tcx> {
1208 fn new(obligation: PredicateObligation<'tcx>,
1209 code: FulfillmentErrorCode<'tcx>)
1210 -> FulfillmentError<'tcx>
1212 FulfillmentError { obligation: obligation, code: code, points_at_arg_span: false }
1216 impl<'tcx> TraitObligation<'tcx> {
1217 fn self_ty(&self) -> ty::Binder<Ty<'tcx>> {
1218 self.predicate.map_bound(|p| p.self_ty())
1222 pub fn provide(providers: &mut ty::query::Providers<'_>) {
1223 *providers = ty::query::Providers {
1224 is_object_safe: object_safety::is_object_safe_provider,
1225 specialization_graph_of: specialize::specialization_graph_provider,
1226 specializes: specialize::specializes,
1227 codegen_fulfill_obligation: codegen::codegen_fulfill_obligation,
1229 substitute_normalize_and_test_predicates,
1234 pub trait ExClauseFold<'tcx>
1236 Self: chalk_engine::context::Context + Clone,
1238 fn fold_ex_clause_with<F: TypeFolder<'tcx>>(
1239 ex_clause: &chalk_engine::ExClause<Self>,
1241 ) -> chalk_engine::ExClause<Self>;
1243 fn visit_ex_clause_with<V: TypeVisitor<'tcx>>(
1244 ex_clause: &chalk_engine::ExClause<Self>,
1249 pub trait ChalkContextLift<'tcx>
1251 Self: chalk_engine::context::Context + Clone,
1253 type LiftedExClause: Debug + 'tcx;
1254 type LiftedDelayedLiteral: Debug + 'tcx;
1255 type LiftedLiteral: Debug + 'tcx;
1257 fn lift_ex_clause_to_tcx(
1258 ex_clause: &chalk_engine::ExClause<Self>,
1260 ) -> Option<Self::LiftedExClause>;
1262 fn lift_delayed_literal_to_tcx(
1263 ex_clause: &chalk_engine::DelayedLiteral<Self>,
1265 ) -> Option<Self::LiftedDelayedLiteral>;
1267 fn lift_literal_to_tcx(
1268 ex_clause: &chalk_engine::Literal<Self>,
1270 ) -> Option<Self::LiftedLiteral>;