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 /// A type like `&'a T` is WF only if `T: 'a`.
180 ReferenceOutlivesReferent(Ty<'tcx>),
182 /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
183 ObjectTypeBound(Ty<'tcx>, ty::Region<'tcx>),
185 /// Obligation incurred due to an object cast.
186 ObjectCastObligation(/* Object type */ Ty<'tcx>),
188 // Various cases where expressions must be sized/copy/etc:
189 /// L = X implies that L is Sized
191 /// (x1, .., xn) must be Sized
192 TupleInitializerSized,
193 /// S { ... } must be Sized
194 StructInitializerSized,
195 /// Type of each variable must be Sized
196 VariableType(hir::HirId),
197 /// Argument type must be Sized
199 /// Return type must be Sized
201 /// Yield type must be Sized
203 /// [T,..n] --> T must be Copy
206 /// Types of fields (other than the last, except for packed structs) in a struct must be sized.
207 FieldSized { adt_kind: AdtKind, last: bool },
209 /// Constant expressions must be sized.
212 /// static items must have `Sync` type
215 BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
217 ImplDerivedObligation(DerivedObligationCause<'tcx>),
219 /// error derived when matching traits/impls; see ObligationCause for more details
220 CompareImplMethodObligation {
221 item_name: ast::Name,
222 impl_item_def_id: DefId,
223 trait_item_def_id: DefId,
226 /// Checking that this expression can be assigned where it needs to be
227 // FIXME(eddyb) #11161 is the original Expr required?
230 /// Computing common supertype in the arms of a match expression
231 MatchExpressionArm(Box<MatchExpressionArmCause<'tcx>>),
233 /// Computing common supertype in the pattern guard for the arms of a match expression
234 MatchExpressionArmPattern { span: Span, ty: Ty<'tcx> },
236 /// Computing common supertype in an if expression
237 IfExpression(Box<IfExpressionCause>),
239 /// Computing common supertype of an if expression with no else counter-part
240 IfExpressionWithNoElse,
242 /// `main` has wrong type
245 /// `start` has wrong type
248 /// intrinsic has wrong type
254 /// `return` with no expression
257 /// `return` with an expression
258 ReturnType(hir::HirId),
260 /// Block implicit return
261 BlockTailExpression(hir::HirId),
263 /// #[feature(trivial_bounds)] is not enabled
267 // `ObligationCauseCode` is used a lot. Make sure it doesn't unintentionally get bigger.
268 #[cfg(target_arch = "x86_64")]
269 static_assert_size!(ObligationCauseCode<'_>, 32);
271 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
272 pub struct MatchExpressionArmCause<'tcx> {
274 pub source: hir::MatchSource,
275 pub prior_arms: Vec<Span>,
276 pub last_ty: Ty<'tcx>,
277 pub discrim_hir_id: hir::HirId,
280 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
281 pub struct IfExpressionCause {
283 pub outer: Option<Span>,
284 pub semicolon: Option<Span>,
287 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
288 pub struct DerivedObligationCause<'tcx> {
289 /// The trait reference of the parent obligation that led to the
290 /// current obligation. Note that only trait obligations lead to
291 /// derived obligations, so we just store the trait reference here
293 parent_trait_ref: ty::PolyTraitRef<'tcx>,
295 /// The parent trait had this cause.
296 parent_code: Rc<ObligationCauseCode<'tcx>>
299 pub type Obligations<'tcx, O> = Vec<Obligation<'tcx, O>>;
300 pub type PredicateObligations<'tcx> = Vec<PredicateObligation<'tcx>>;
301 pub type TraitObligations<'tcx> = Vec<TraitObligation<'tcx>>;
303 /// The following types:
311 /// * `InEnvironment`,
312 /// are used for representing the trait system in the form of
313 /// logic programming clauses. They are part of the interface
314 /// for the chalk SLG solver.
315 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable)]
316 pub enum WhereClause<'tcx> {
317 Implemented(ty::TraitPredicate<'tcx>),
318 ProjectionEq(ty::ProjectionPredicate<'tcx>),
319 RegionOutlives(ty::RegionOutlivesPredicate<'tcx>),
320 TypeOutlives(ty::TypeOutlivesPredicate<'tcx>),
323 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable)]
324 pub enum WellFormed<'tcx> {
325 Trait(ty::TraitPredicate<'tcx>),
329 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable)]
330 pub enum FromEnv<'tcx> {
331 Trait(ty::TraitPredicate<'tcx>),
335 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable)]
336 pub enum DomainGoal<'tcx> {
337 Holds(WhereClause<'tcx>),
338 WellFormed(WellFormed<'tcx>),
339 FromEnv(FromEnv<'tcx>),
340 Normalize(ty::ProjectionPredicate<'tcx>),
343 pub type PolyDomainGoal<'tcx> = ty::Binder<DomainGoal<'tcx>>;
345 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
346 pub enum QuantifierKind {
351 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
352 pub enum GoalKind<'tcx> {
353 Implies(Clauses<'tcx>, Goal<'tcx>),
354 And(Goal<'tcx>, Goal<'tcx>),
356 DomainGoal(DomainGoal<'tcx>),
357 Quantified(QuantifierKind, ty::Binder<Goal<'tcx>>),
358 Subtype(Ty<'tcx>, Ty<'tcx>),
362 pub type Goal<'tcx> = &'tcx GoalKind<'tcx>;
364 pub type Goals<'tcx> = &'tcx List<Goal<'tcx>>;
366 impl<'tcx> DomainGoal<'tcx> {
367 pub fn into_goal(self) -> GoalKind<'tcx> {
368 GoalKind::DomainGoal(self)
371 pub fn into_program_clause(self) -> ProgramClause<'tcx> {
374 hypotheses: ty::List::empty(),
375 category: ProgramClauseCategory::Other,
380 impl<'tcx> GoalKind<'tcx> {
381 pub fn from_poly_domain_goal(
382 domain_goal: PolyDomainGoal<'tcx>,
384 ) -> GoalKind<'tcx> {
385 match domain_goal.no_bound_vars() {
386 Some(p) => p.into_goal(),
387 None => GoalKind::Quantified(
388 QuantifierKind::Universal,
389 domain_goal.map_bound(|p| tcx.mk_goal(p.into_goal()))
395 /// This matches the definition from Page 7 of "A Proof Procedure for the Logic of Hereditary
396 /// Harrop Formulas".
397 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
398 pub enum Clause<'tcx> {
399 Implies(ProgramClause<'tcx>),
400 ForAll(ty::Binder<ProgramClause<'tcx>>),
404 pub fn category(self) -> ProgramClauseCategory {
406 Clause::Implies(clause) => clause.category,
407 Clause::ForAll(clause) => clause.skip_binder().category,
412 /// Multiple clauses.
413 pub type Clauses<'tcx> = &'tcx List<Clause<'tcx>>;
415 /// A "program clause" has the form `D :- G1, ..., Gn`. It is saying
416 /// that the domain goal `D` is true if `G1...Gn` are provable. This
417 /// is equivalent to the implication `G1..Gn => D`; we usually write
418 /// it with the reverse implication operator `:-` to emphasize the way
419 /// that programs are actually solved (via backchaining, which starts
420 /// with the goal to solve and proceeds from there).
421 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
422 pub struct ProgramClause<'tcx> {
423 /// This goal will be considered true ...
424 pub goal: DomainGoal<'tcx>,
426 /// ... if we can prove these hypotheses (there may be no hypotheses at all):
427 pub hypotheses: Goals<'tcx>,
429 /// Useful for filtering clauses.
430 pub category: ProgramClauseCategory,
433 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
434 pub enum ProgramClauseCategory {
440 /// A set of clauses that we assume to be true.
441 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
442 pub struct Environment<'tcx> {
443 pub clauses: Clauses<'tcx>,
446 impl Environment<'tcx> {
447 pub fn with<G>(self, goal: G) -> InEnvironment<'tcx, G> {
455 /// Something (usually a goal), along with an environment.
456 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
457 pub struct InEnvironment<'tcx, G> {
458 pub environment: Environment<'tcx>,
462 pub type Selection<'tcx> = Vtable<'tcx, PredicateObligation<'tcx>>;
464 #[derive(Clone,Debug)]
465 pub enum SelectionError<'tcx> {
467 OutputTypeParameterMismatch(ty::PolyTraitRef<'tcx>,
468 ty::PolyTraitRef<'tcx>,
469 ty::error::TypeError<'tcx>),
470 TraitNotObjectSafe(DefId),
471 ConstEvalFailure(ErrorHandled),
475 EnumTypeFoldableImpl! {
476 impl<'tcx> TypeFoldable<'tcx> for SelectionError<'tcx> {
477 (SelectionError::Unimplemented),
478 (SelectionError::OutputTypeParameterMismatch)(a, b, c),
479 (SelectionError::TraitNotObjectSafe)(a),
480 (SelectionError::ConstEvalFailure)(a),
481 (SelectionError::Overflow),
485 pub struct FulfillmentError<'tcx> {
486 pub obligation: PredicateObligation<'tcx>,
487 pub code: FulfillmentErrorCode<'tcx>,
488 /// Diagnostics only: we opportunistically change the `code.span` when we encounter an
489 /// obligation error caused by a call argument. When this is the case, we also signal that in
490 /// this field to ensure accuracy of suggestions.
491 pub points_at_arg_span: bool,
495 pub enum FulfillmentErrorCode<'tcx> {
496 CodeSelectionError(SelectionError<'tcx>),
497 CodeProjectionError(MismatchedProjectionTypes<'tcx>),
498 CodeSubtypeError(ExpectedFound<Ty<'tcx>>,
499 TypeError<'tcx>), // always comes from a SubtypePredicate
503 /// When performing resolution, it is typically the case that there
504 /// can be one of three outcomes:
506 /// - `Ok(Some(r))`: success occurred with result `r`
507 /// - `Ok(None)`: could not definitely determine anything, usually due
508 /// to inconclusive type inference.
509 /// - `Err(e)`: error `e` occurred
510 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
512 /// Given the successful resolution of an obligation, the `Vtable`
513 /// indicates where the vtable comes from. Note that while we call this
514 /// a "vtable", it does not necessarily indicate dynamic dispatch at
515 /// runtime. `Vtable` instances just tell the compiler where to find
516 /// methods, but in generic code those methods are typically statically
517 /// dispatched -- only when an object is constructed is a `Vtable`
518 /// instance reified into an actual vtable.
520 /// For example, the vtable may be tied to a specific impl (case A),
521 /// or it may be relative to some bound that is in scope (case B).
524 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
525 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
526 /// impl Clone for int { ... } // Impl_3
528 /// fn foo<T:Clone>(concrete: Option<Box<int>>,
530 /// mixed: Option<T>) {
532 /// // Case A: Vtable points at a specific impl. Only possible when
533 /// // type is concretely known. If the impl itself has bounded
534 /// // type parameters, Vtable will carry resolutions for those as well:
535 /// concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
537 /// // Case B: Vtable must be provided by caller. This applies when
538 /// // type is a type parameter.
539 /// param.clone(); // VtableParam
541 /// // Case C: A mix of cases A and B.
542 /// mixed.clone(); // Vtable(Impl_1, [VtableParam])
546 /// ### The type parameter `N`
548 /// See explanation on `VtableImplData`.
549 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
550 pub enum Vtable<'tcx, N> {
551 /// Vtable identifying a particular impl.
552 VtableImpl(VtableImplData<'tcx, N>),
554 /// Vtable for auto trait implementations.
555 /// This carries the information and nested obligations with regards
556 /// to an auto implementation for a trait `Trait`. The nested obligations
557 /// ensure the trait implementation holds for all the constituent types.
558 VtableAutoImpl(VtableAutoImplData<N>),
560 /// Successful resolution to an obligation provided by the caller
561 /// for some type parameter. The `Vec<N>` represents the
562 /// obligations incurred from normalizing the where-clause (if
566 /// Virtual calls through an object.
567 VtableObject(VtableObjectData<'tcx, N>),
569 /// Successful resolution for a builtin trait.
570 VtableBuiltin(VtableBuiltinData<N>),
572 /// Vtable automatically generated for a closure. The `DefId` is the ID
573 /// of the closure expression. This is a `VtableImpl` in spirit, but the
574 /// impl is generated by the compiler and does not appear in the source.
575 VtableClosure(VtableClosureData<'tcx, N>),
577 /// Same as above, but for a function pointer type with the given signature.
578 VtableFnPointer(VtableFnPointerData<'tcx, N>),
580 /// Vtable automatically generated for a generator.
581 VtableGenerator(VtableGeneratorData<'tcx, N>),
583 /// Vtable for a trait alias.
584 VtableTraitAlias(VtableTraitAliasData<'tcx, N>),
587 /// Identifies a particular impl in the source, along with a set of
588 /// substitutions from the impl's type/lifetime parameters. The
589 /// `nested` vector corresponds to the nested obligations attached to
590 /// the impl's type parameters.
592 /// The type parameter `N` indicates the type used for "nested
593 /// obligations" that are required by the impl. During type check, this
594 /// is `Obligation`, as one might expect. During codegen, however, this
595 /// is `()`, because codegen only requires a shallow resolution of an
596 /// impl, and nested obligations are satisfied later.
597 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
598 pub struct VtableImplData<'tcx, N> {
599 pub impl_def_id: DefId,
600 pub substs: SubstsRef<'tcx>,
604 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
605 pub struct VtableGeneratorData<'tcx, N> {
606 pub generator_def_id: DefId,
607 pub substs: ty::GeneratorSubsts<'tcx>,
608 /// Nested obligations. This can be non-empty if the generator
609 /// signature contains associated types.
613 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
614 pub struct VtableClosureData<'tcx, N> {
615 pub closure_def_id: DefId,
616 pub substs: ty::ClosureSubsts<'tcx>,
617 /// Nested obligations. This can be non-empty if the closure
618 /// signature contains associated types.
622 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
623 pub struct VtableAutoImplData<N> {
624 pub trait_def_id: DefId,
628 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
629 pub struct VtableBuiltinData<N> {
633 /// A vtable for some object-safe trait `Foo` automatically derived
634 /// for the object type `Foo`.
635 #[derive(PartialEq, Eq, Clone, RustcEncodable, RustcDecodable, HashStable)]
636 pub struct VtableObjectData<'tcx, N> {
637 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
638 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
640 /// The vtable is formed by concatenating together the method lists of
641 /// the base object trait and all supertraits; this is the start of
642 /// `upcast_trait_ref`'s methods in that vtable.
643 pub vtable_base: usize,
648 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
649 pub struct VtableFnPointerData<'tcx, N> {
654 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
655 pub struct VtableTraitAliasData<'tcx, N> {
656 pub alias_def_id: DefId,
657 pub substs: SubstsRef<'tcx>,
661 /// Creates predicate obligations from the generic bounds.
662 pub fn predicates_for_generics<'tcx>(
663 cause: ObligationCause<'tcx>,
664 param_env: ty::ParamEnv<'tcx>,
665 generic_bounds: &ty::InstantiatedPredicates<'tcx>,
666 ) -> PredicateObligations<'tcx> {
667 util::predicates_for_generics(cause, 0, param_env, generic_bounds)
670 /// Determines whether the type `ty` is known to meet `bound` and
671 /// returns true if so. Returns false if `ty` either does not meet
672 /// `bound` or is not known to meet bound (note that this is
673 /// conservative towards *no impl*, which is the opposite of the
674 /// `evaluate` methods).
675 pub fn type_known_to_meet_bound_modulo_regions<'a, 'tcx>(
676 infcx: &InferCtxt<'a, 'tcx>,
677 param_env: ty::ParamEnv<'tcx>,
682 debug!("type_known_to_meet_bound_modulo_regions(ty={:?}, bound={:?})",
684 infcx.tcx.def_path_str(def_id));
686 let trait_ref = ty::TraitRef {
688 substs: infcx.tcx.mk_substs_trait(ty, &[]),
690 let obligation = Obligation {
692 cause: ObligationCause::misc(span, hir::DUMMY_HIR_ID),
694 predicate: trait_ref.to_predicate(),
697 let result = infcx.predicate_must_hold_modulo_regions(&obligation);
698 debug!("type_known_to_meet_ty={:?} bound={} => {:?}",
699 ty, infcx.tcx.def_path_str(def_id), result);
701 if result && (ty.has_infer_types() || ty.has_closure_types()) {
702 // Because of inference "guessing", selection can sometimes claim
703 // to succeed while the success requires a guess. To ensure
704 // this function's result remains infallible, we must confirm
705 // that guess. While imperfect, I believe this is sound.
707 // The handling of regions in this area of the code is terrible,
708 // see issue #29149. We should be able to improve on this with
710 let mut fulfill_cx = FulfillmentContext::new_ignoring_regions();
712 // We can use a dummy node-id here because we won't pay any mind
713 // to region obligations that arise (there shouldn't really be any
715 let cause = ObligationCause::misc(span, hir::DUMMY_HIR_ID);
717 fulfill_cx.register_bound(infcx, param_env, ty, def_id, cause);
719 // Note: we only assume something is `Copy` if we can
720 // *definitively* show that it implements `Copy`. Otherwise,
721 // assume it is move; linear is always ok.
722 match fulfill_cx.select_all_or_error(infcx) {
724 debug!("type_known_to_meet_bound_modulo_regions: ty={:?} bound={} success",
726 infcx.tcx.def_path_str(def_id));
730 debug!("type_known_to_meet_bound_modulo_regions: ty={:?} bound={} errors={:?}",
732 infcx.tcx.def_path_str(def_id),
742 fn do_normalize_predicates<'tcx>(
744 region_context: DefId,
745 cause: ObligationCause<'tcx>,
746 elaborated_env: ty::ParamEnv<'tcx>,
747 predicates: Vec<ty::Predicate<'tcx>>,
748 ) -> Result<Vec<ty::Predicate<'tcx>>, ErrorReported> {
750 "do_normalize_predicates(predicates={:?}, region_context={:?}, cause={:?})",
755 let span = cause.span;
756 tcx.infer_ctxt().enter(|infcx| {
757 // FIXME. We should really... do something with these region
758 // obligations. But this call just continues the older
759 // behavior (i.e., doesn't cause any new bugs), and it would
760 // take some further refactoring to actually solve them. In
761 // particular, we would have to handle implied bounds
762 // properly, and that code is currently largely confined to
763 // regionck (though I made some efforts to extract it
766 // @arielby: In any case, these obligations are checked
767 // by wfcheck anyway, so I'm not sure we have to check
768 // them here too, and we will remove this function when
769 // we move over to lazy normalization *anyway*.
770 let fulfill_cx = FulfillmentContext::new_ignoring_regions();
771 let predicates = match fully_normalize(
778 Ok(predicates) => predicates,
780 infcx.report_fulfillment_errors(&errors, None, false);
781 return Err(ErrorReported)
785 debug!("do_normalize_predictes: normalized predicates = {:?}", predicates);
787 let region_scope_tree = region::ScopeTree::default();
789 // We can use the `elaborated_env` here; the region code only
790 // cares about declarations like `'a: 'b`.
791 let outlives_env = OutlivesEnvironment::new(elaborated_env);
793 infcx.resolve_regions_and_report_errors(
797 SuppressRegionErrors::default(),
800 let predicates = match infcx.fully_resolve(&predicates) {
801 Ok(predicates) => predicates,
803 // If we encounter a fixup error, it means that some type
804 // variable wound up unconstrained. I actually don't know
805 // if this can happen, and I certainly don't expect it to
806 // happen often, but if it did happen it probably
807 // represents a legitimate failure due to some kind of
808 // unconstrained variable, and it seems better not to ICE,
809 // all things considered.
810 tcx.sess.span_err(span, &fixup_err.to_string());
811 return Err(ErrorReported)
814 if predicates.has_local_value() {
815 // FIXME: shouldn't we, you know, actually report an error here? or an ICE?
823 // FIXME: this is gonna need to be removed ...
824 /// Normalizes the parameter environment, reporting errors if they occur.
825 pub fn normalize_param_env_or_error<'tcx>(
827 region_context: DefId,
828 unnormalized_env: ty::ParamEnv<'tcx>,
829 cause: ObligationCause<'tcx>,
830 ) -> ty::ParamEnv<'tcx> {
831 // I'm not wild about reporting errors here; I'd prefer to
832 // have the errors get reported at a defined place (e.g.,
833 // during typeck). Instead I have all parameter
834 // environments, in effect, going through this function
835 // and hence potentially reporting errors. This ensures of
836 // course that we never forget to normalize (the
837 // alternative seemed like it would involve a lot of
838 // manual invocations of this fn -- and then we'd have to
839 // deal with the errors at each of those sites).
841 // In any case, in practice, typeck constructs all the
842 // parameter environments once for every fn as it goes,
843 // and errors will get reported then; so after typeck we
844 // can be sure that no errors should occur.
846 debug!("normalize_param_env_or_error(region_context={:?}, unnormalized_env={:?}, cause={:?})",
847 region_context, unnormalized_env, cause);
849 let mut predicates: Vec<_> =
850 util::elaborate_predicates(tcx, unnormalized_env.caller_bounds.to_vec())
853 debug!("normalize_param_env_or_error: elaborated-predicates={:?}",
856 let elaborated_env = ty::ParamEnv::new(
857 tcx.intern_predicates(&predicates),
858 unnormalized_env.reveal,
859 unnormalized_env.def_id
862 // HACK: we are trying to normalize the param-env inside *itself*. The problem is that
863 // normalization expects its param-env to be already normalized, which means we have
866 // The way we handle this is by normalizing the param-env inside an unnormalized version
867 // of the param-env, which means that if the param-env contains unnormalized projections,
868 // we'll have some normalization failures. This is unfortunate.
870 // Lazy normalization would basically handle this by treating just the
871 // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
873 // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
874 // types, so to make the situation less bad, we normalize all the predicates *but*
875 // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
876 // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
878 // This works fairly well because trait matching does not actually care about param-env
879 // TypeOutlives predicates - these are normally used by regionck.
880 let outlives_predicates: Vec<_> = predicates.drain_filter(|predicate| {
882 ty::Predicate::TypeOutlives(..) => true,
887 debug!("normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
888 predicates, outlives_predicates);
889 let non_outlives_predicates =
890 match do_normalize_predicates(tcx, region_context, cause.clone(),
891 elaborated_env, predicates) {
892 Ok(predicates) => predicates,
893 // An unnormalized env is better than nothing.
894 Err(ErrorReported) => {
895 debug!("normalize_param_env_or_error: errored resolving non-outlives predicates");
896 return elaborated_env
900 debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates);
902 // Not sure whether it is better to include the unnormalized TypeOutlives predicates
903 // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
904 // predicates here anyway. Keeping them here anyway because it seems safer.
905 let outlives_env: Vec<_> =
906 non_outlives_predicates.iter().chain(&outlives_predicates).cloned().collect();
907 let outlives_env = ty::ParamEnv::new(
908 tcx.intern_predicates(&outlives_env),
909 unnormalized_env.reveal,
912 let outlives_predicates =
913 match do_normalize_predicates(tcx, region_context, cause,
914 outlives_env, outlives_predicates) {
915 Ok(predicates) => predicates,
916 // An unnormalized env is better than nothing.
917 Err(ErrorReported) => {
918 debug!("normalize_param_env_or_error: errored resolving outlives predicates");
919 return elaborated_env
922 debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates);
924 let mut predicates = non_outlives_predicates;
925 predicates.extend(outlives_predicates);
926 debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
928 tcx.intern_predicates(&predicates),
929 unnormalized_env.reveal,
930 unnormalized_env.def_id
934 pub fn fully_normalize<'a, 'tcx, T>(
935 infcx: &InferCtxt<'a, 'tcx>,
936 mut fulfill_cx: FulfillmentContext<'tcx>,
937 cause: ObligationCause<'tcx>,
938 param_env: ty::ParamEnv<'tcx>,
940 ) -> Result<T, Vec<FulfillmentError<'tcx>>>
942 T: TypeFoldable<'tcx>,
944 debug!("fully_normalize_with_fulfillcx(value={:?})", value);
945 let selcx = &mut SelectionContext::new(infcx);
946 let Normalized { value: normalized_value, obligations } =
947 project::normalize(selcx, param_env, cause, value);
948 debug!("fully_normalize: normalized_value={:?} obligations={:?}",
951 for obligation in obligations {
952 fulfill_cx.register_predicate_obligation(selcx.infcx(), obligation);
955 debug!("fully_normalize: select_all_or_error start");
956 fulfill_cx.select_all_or_error(infcx)?;
957 debug!("fully_normalize: select_all_or_error complete");
958 let resolved_value = infcx.resolve_vars_if_possible(&normalized_value);
959 debug!("fully_normalize: resolved_value={:?}", resolved_value);
963 /// Normalizes the predicates and checks whether they hold in an empty
964 /// environment. If this returns false, then either normalize
965 /// encountered an error or one of the predicates did not hold. Used
966 /// when creating vtables to check for unsatisfiable methods.
967 fn normalize_and_test_predicates<'tcx>(
969 predicates: Vec<ty::Predicate<'tcx>>,
971 debug!("normalize_and_test_predicates(predicates={:?})",
974 let result = tcx.infer_ctxt().enter(|infcx| {
975 let param_env = ty::ParamEnv::reveal_all();
976 let mut selcx = SelectionContext::new(&infcx);
977 let mut fulfill_cx = FulfillmentContext::new();
978 let cause = ObligationCause::dummy();
979 let Normalized { value: predicates, obligations } =
980 normalize(&mut selcx, param_env, cause.clone(), &predicates);
981 for obligation in obligations {
982 fulfill_cx.register_predicate_obligation(&infcx, obligation);
984 for predicate in predicates {
985 let obligation = Obligation::new(cause.clone(), param_env, predicate);
986 fulfill_cx.register_predicate_obligation(&infcx, obligation);
989 fulfill_cx.select_all_or_error(&infcx).is_ok()
991 debug!("normalize_and_test_predicates(predicates={:?}) = {:?}",
996 fn substitute_normalize_and_test_predicates<'tcx>(
998 key: (DefId, SubstsRef<'tcx>),
1000 debug!("substitute_normalize_and_test_predicates(key={:?})",
1003 let predicates = tcx.predicates_of(key.0).instantiate(tcx, key.1).predicates;
1004 let result = normalize_and_test_predicates(tcx, predicates);
1006 debug!("substitute_normalize_and_test_predicates(key={:?}) = {:?}",
1011 /// Given a trait `trait_ref`, iterates the vtable entries
1012 /// that come from `trait_ref`, including its supertraits.
1013 #[inline] // FIXME(#35870): avoid closures being unexported due to `impl Trait`.
1014 fn vtable_methods<'tcx>(
1016 trait_ref: ty::PolyTraitRef<'tcx>,
1017 ) -> &'tcx [Option<(DefId, SubstsRef<'tcx>)>] {
1018 debug!("vtable_methods({:?})", trait_ref);
1020 tcx.arena.alloc_from_iter(
1021 supertraits(tcx, trait_ref).flat_map(move |trait_ref| {
1022 let trait_methods = tcx.associated_items(trait_ref.def_id())
1023 .filter(|item| item.kind == ty::AssocKind::Method);
1025 // Now list each method's DefId and InternalSubsts (for within its trait).
1026 // If the method can never be called from this object, produce None.
1027 trait_methods.map(move |trait_method| {
1028 debug!("vtable_methods: trait_method={:?}", trait_method);
1029 let def_id = trait_method.def_id;
1031 // Some methods cannot be called on an object; skip those.
1032 if !tcx.is_vtable_safe_method(trait_ref.def_id(), &trait_method) {
1033 debug!("vtable_methods: not vtable safe");
1037 // the method may have some early-bound lifetimes, add
1038 // regions for those
1039 let substs = trait_ref.map_bound(|trait_ref|
1040 InternalSubsts::for_item(tcx, def_id, |param, _|
1042 GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(),
1043 GenericParamDefKind::Type { .. } |
1044 GenericParamDefKind::Const => {
1045 trait_ref.substs[param.index as usize]
1051 // the trait type may have higher-ranked lifetimes in it;
1052 // so erase them if they appear, so that we get the type
1053 // at some particular call site
1054 let substs = tcx.normalize_erasing_late_bound_regions(
1055 ty::ParamEnv::reveal_all(),
1059 // It's possible that the method relies on where clauses that
1060 // do not hold for this particular set of type parameters.
1061 // Note that this method could then never be called, so we
1062 // do not want to try and codegen it, in that case (see #23435).
1063 let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs);
1064 if !normalize_and_test_predicates(tcx, predicates.predicates) {
1065 debug!("vtable_methods: predicates do not hold");
1069 Some((def_id, substs))
1075 impl<'tcx, O> Obligation<'tcx, O> {
1076 pub fn new(cause: ObligationCause<'tcx>,
1077 param_env: ty::ParamEnv<'tcx>,
1079 -> Obligation<'tcx, O>
1081 Obligation { cause, param_env, recursion_depth: 0, predicate }
1084 fn with_depth(cause: ObligationCause<'tcx>,
1085 recursion_depth: usize,
1086 param_env: ty::ParamEnv<'tcx>,
1088 -> Obligation<'tcx, O>
1090 Obligation { cause, param_env, recursion_depth, predicate }
1093 pub fn misc(span: Span,
1094 body_id: hir::HirId,
1095 param_env: ty::ParamEnv<'tcx>,
1097 -> Obligation<'tcx, O> {
1098 Obligation::new(ObligationCause::misc(span, body_id), param_env, trait_ref)
1101 pub fn with<P>(&self, value: P) -> Obligation<'tcx,P> {
1102 Obligation { cause: self.cause.clone(),
1103 param_env: self.param_env,
1104 recursion_depth: self.recursion_depth,
1109 impl<'tcx> ObligationCause<'tcx> {
1111 pub fn new(span: Span,
1112 body_id: hir::HirId,
1113 code: ObligationCauseCode<'tcx>)
1114 -> ObligationCause<'tcx> {
1115 ObligationCause { span, body_id, code }
1118 pub fn misc(span: Span, body_id: hir::HirId) -> ObligationCause<'tcx> {
1119 ObligationCause { span, body_id, code: MiscObligation }
1122 pub fn dummy() -> ObligationCause<'tcx> {
1123 ObligationCause { span: DUMMY_SP, body_id: hir::CRATE_HIR_ID, code: MiscObligation }
1127 impl<'tcx, N> Vtable<'tcx, N> {
1128 pub fn nested_obligations(self) -> Vec<N> {
1130 VtableImpl(i) => i.nested,
1131 VtableParam(n) => n,
1132 VtableBuiltin(i) => i.nested,
1133 VtableAutoImpl(d) => d.nested,
1134 VtableClosure(c) => c.nested,
1135 VtableGenerator(c) => c.nested,
1136 VtableObject(d) => d.nested,
1137 VtableFnPointer(d) => d.nested,
1138 VtableTraitAlias(d) => d.nested,
1142 pub fn map<M, F>(self, f: F) -> Vtable<'tcx, M> where F: FnMut(N) -> M {
1144 VtableImpl(i) => VtableImpl(VtableImplData {
1145 impl_def_id: i.impl_def_id,
1147 nested: i.nested.into_iter().map(f).collect(),
1149 VtableParam(n) => VtableParam(n.into_iter().map(f).collect()),
1150 VtableBuiltin(i) => VtableBuiltin(VtableBuiltinData {
1151 nested: i.nested.into_iter().map(f).collect(),
1153 VtableObject(o) => VtableObject(VtableObjectData {
1154 upcast_trait_ref: o.upcast_trait_ref,
1155 vtable_base: o.vtable_base,
1156 nested: o.nested.into_iter().map(f).collect(),
1158 VtableAutoImpl(d) => VtableAutoImpl(VtableAutoImplData {
1159 trait_def_id: d.trait_def_id,
1160 nested: d.nested.into_iter().map(f).collect(),
1162 VtableClosure(c) => VtableClosure(VtableClosureData {
1163 closure_def_id: c.closure_def_id,
1165 nested: c.nested.into_iter().map(f).collect(),
1167 VtableGenerator(c) => VtableGenerator(VtableGeneratorData {
1168 generator_def_id: c.generator_def_id,
1170 nested: c.nested.into_iter().map(f).collect(),
1172 VtableFnPointer(p) => VtableFnPointer(VtableFnPointerData {
1174 nested: p.nested.into_iter().map(f).collect(),
1176 VtableTraitAlias(d) => VtableTraitAlias(VtableTraitAliasData {
1177 alias_def_id: d.alias_def_id,
1179 nested: d.nested.into_iter().map(f).collect(),
1185 impl<'tcx> FulfillmentError<'tcx> {
1186 fn new(obligation: PredicateObligation<'tcx>,
1187 code: FulfillmentErrorCode<'tcx>)
1188 -> FulfillmentError<'tcx>
1190 FulfillmentError { obligation: obligation, code: code, points_at_arg_span: false }
1194 impl<'tcx> TraitObligation<'tcx> {
1195 fn self_ty(&self) -> ty::Binder<Ty<'tcx>> {
1196 self.predicate.map_bound(|p| p.self_ty())
1200 pub fn provide(providers: &mut ty::query::Providers<'_>) {
1201 *providers = ty::query::Providers {
1202 is_object_safe: object_safety::is_object_safe_provider,
1203 specialization_graph_of: specialize::specialization_graph_provider,
1204 specializes: specialize::specializes,
1205 codegen_fulfill_obligation: codegen::codegen_fulfill_obligation,
1207 substitute_normalize_and_test_predicates,
1212 pub trait ExClauseFold<'tcx>
1214 Self: chalk_engine::context::Context + Clone,
1216 fn fold_ex_clause_with<F: TypeFolder<'tcx>>(
1217 ex_clause: &chalk_engine::ExClause<Self>,
1219 ) -> chalk_engine::ExClause<Self>;
1221 fn visit_ex_clause_with<V: TypeVisitor<'tcx>>(
1222 ex_clause: &chalk_engine::ExClause<Self>,
1227 pub trait ChalkContextLift<'tcx>
1229 Self: chalk_engine::context::Context + Clone,
1231 type LiftedExClause: Debug + 'tcx;
1232 type LiftedDelayedLiteral: Debug + 'tcx;
1233 type LiftedLiteral: Debug + 'tcx;
1235 fn lift_ex_clause_to_tcx(
1236 ex_clause: &chalk_engine::ExClause<Self>,
1238 ) -> Option<Self::LiftedExClause>;
1240 fn lift_delayed_literal_to_tcx(
1241 ex_clause: &chalk_engine::DelayedLiteral<Self>,
1243 ) -> Option<Self::LiftedDelayedLiteral>;
1245 fn lift_literal_to_tcx(
1246 ex_clause: &chalk_engine::Literal<Self>,
1248 ) -> Option<Self::LiftedLiteral>;