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<'_>, 136);
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 { arm_span, .. } => arm_span,
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 /// A type like `&'a T` is WF only if `T: 'a`.
179 ReferenceOutlivesReferent(Ty<'tcx>),
181 /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
182 ObjectTypeBound(Ty<'tcx>, ty::Region<'tcx>),
184 /// Obligation incurred due to an object cast.
185 ObjectCastObligation(/* Object type */ Ty<'tcx>),
187 // Various cases where expressions must be sized/copy/etc:
188 /// L = X implies that L is Sized
190 /// (x1, .., xn) must be Sized
191 TupleInitializerSized,
192 /// S { ... } must be Sized
193 StructInitializerSized,
194 /// Type of each variable must be Sized
195 VariableType(hir::HirId),
196 /// Argument type must be Sized
198 /// Return type must be Sized
200 /// Yield type must be Sized
202 /// [T,..n] --> T must be Copy
205 /// Types of fields (other than the last, except for packed structs) in a struct must be sized.
206 FieldSized { adt_kind: AdtKind, last: bool },
208 /// Constant expressions must be sized.
211 /// static items must have `Sync` type
214 BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
216 ImplDerivedObligation(DerivedObligationCause<'tcx>),
218 /// error derived when matching traits/impls; see ObligationCause for more details
219 CompareImplMethodObligation {
220 item_name: ast::Name,
221 impl_item_def_id: DefId,
222 trait_item_def_id: DefId,
225 /// Checking that this expression can be assigned where it needs to be
226 // FIXME(eddyb) #11161 is the original Expr required?
229 /// Computing common supertype in the arms of a match expression
232 source: hir::MatchSource,
233 prior_arms: Vec<Span>,
235 discrim_hir_id: hir::HirId,
238 /// Computing common supertype in the pattern guard for the arms of a match expression
239 MatchExpressionArmPattern { span: Span, ty: Ty<'tcx> },
241 /// Computing common supertype in an if expression
245 semicolon: Option<Span>,
248 /// Computing common supertype of an if expression with no else counter-part
249 IfExpressionWithNoElse,
251 /// `main` has wrong type
254 /// `start` has wrong type
257 /// intrinsic has wrong type
263 /// `return` with no expression
266 /// `return` with an expression
267 ReturnType(hir::HirId),
269 /// Block implicit return
270 BlockTailExpression(hir::HirId),
272 /// #[feature(trivial_bounds)] is not enabled
276 // `ObligationCauseCode` is used a lot. Make sure it doesn't unintentionally get bigger.
277 #[cfg(target_arch = "x86_64")]
278 static_assert_size!(ObligationCauseCode<'_>, 56);
280 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
281 pub struct DerivedObligationCause<'tcx> {
282 /// The trait reference of the parent obligation that led to the
283 /// current obligation. Note that only trait obligations lead to
284 /// derived obligations, so we just store the trait reference here
286 parent_trait_ref: ty::PolyTraitRef<'tcx>,
288 /// The parent trait had this cause.
289 parent_code: Rc<ObligationCauseCode<'tcx>>
292 pub type Obligations<'tcx, O> = Vec<Obligation<'tcx, O>>;
293 pub type PredicateObligations<'tcx> = Vec<PredicateObligation<'tcx>>;
294 pub type TraitObligations<'tcx> = Vec<TraitObligation<'tcx>>;
296 /// The following types:
304 /// * `InEnvironment`,
305 /// are used for representing the trait system in the form of
306 /// logic programming clauses. They are part of the interface
307 /// for the chalk SLG solver.
308 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable)]
309 pub enum WhereClause<'tcx> {
310 Implemented(ty::TraitPredicate<'tcx>),
311 ProjectionEq(ty::ProjectionPredicate<'tcx>),
312 RegionOutlives(ty::RegionOutlivesPredicate<'tcx>),
313 TypeOutlives(ty::TypeOutlivesPredicate<'tcx>),
316 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable)]
317 pub enum WellFormed<'tcx> {
318 Trait(ty::TraitPredicate<'tcx>),
322 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable)]
323 pub enum FromEnv<'tcx> {
324 Trait(ty::TraitPredicate<'tcx>),
328 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable)]
329 pub enum DomainGoal<'tcx> {
330 Holds(WhereClause<'tcx>),
331 WellFormed(WellFormed<'tcx>),
332 FromEnv(FromEnv<'tcx>),
333 Normalize(ty::ProjectionPredicate<'tcx>),
336 pub type PolyDomainGoal<'tcx> = ty::Binder<DomainGoal<'tcx>>;
338 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
339 pub enum QuantifierKind {
344 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
345 pub enum GoalKind<'tcx> {
346 Implies(Clauses<'tcx>, Goal<'tcx>),
347 And(Goal<'tcx>, Goal<'tcx>),
349 DomainGoal(DomainGoal<'tcx>),
350 Quantified(QuantifierKind, ty::Binder<Goal<'tcx>>),
351 Subtype(Ty<'tcx>, Ty<'tcx>),
355 pub type Goal<'tcx> = &'tcx GoalKind<'tcx>;
357 pub type Goals<'tcx> = &'tcx List<Goal<'tcx>>;
359 impl<'tcx> DomainGoal<'tcx> {
360 pub fn into_goal(self) -> GoalKind<'tcx> {
361 GoalKind::DomainGoal(self)
364 pub fn into_program_clause(self) -> ProgramClause<'tcx> {
367 hypotheses: ty::List::empty(),
368 category: ProgramClauseCategory::Other,
373 impl<'tcx> GoalKind<'tcx> {
374 pub fn from_poly_domain_goal(
375 domain_goal: PolyDomainGoal<'tcx>,
377 ) -> GoalKind<'tcx> {
378 match domain_goal.no_bound_vars() {
379 Some(p) => p.into_goal(),
380 None => GoalKind::Quantified(
381 QuantifierKind::Universal,
382 domain_goal.map_bound(|p| tcx.mk_goal(p.into_goal()))
388 /// This matches the definition from Page 7 of "A Proof Procedure for the Logic of Hereditary
389 /// Harrop Formulas".
390 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
391 pub enum Clause<'tcx> {
392 Implies(ProgramClause<'tcx>),
393 ForAll(ty::Binder<ProgramClause<'tcx>>),
397 pub fn category(self) -> ProgramClauseCategory {
399 Clause::Implies(clause) => clause.category,
400 Clause::ForAll(clause) => clause.skip_binder().category,
405 /// Multiple clauses.
406 pub type Clauses<'tcx> = &'tcx List<Clause<'tcx>>;
408 /// A "program clause" has the form `D :- G1, ..., Gn`. It is saying
409 /// that the domain goal `D` is true if `G1...Gn` are provable. This
410 /// is equivalent to the implication `G1..Gn => D`; we usually write
411 /// it with the reverse implication operator `:-` to emphasize the way
412 /// that programs are actually solved (via backchaining, which starts
413 /// with the goal to solve and proceeds from there).
414 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
415 pub struct ProgramClause<'tcx> {
416 /// This goal will be considered true ...
417 pub goal: DomainGoal<'tcx>,
419 /// ... if we can prove these hypotheses (there may be no hypotheses at all):
420 pub hypotheses: Goals<'tcx>,
422 /// Useful for filtering clauses.
423 pub category: ProgramClauseCategory,
426 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
427 pub enum ProgramClauseCategory {
433 /// A set of clauses that we assume to be true.
434 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
435 pub struct Environment<'tcx> {
436 pub clauses: Clauses<'tcx>,
439 impl Environment<'tcx> {
440 pub fn with<G>(self, goal: G) -> InEnvironment<'tcx, G> {
448 /// Something (usually a goal), along with an environment.
449 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
450 pub struct InEnvironment<'tcx, G> {
451 pub environment: Environment<'tcx>,
455 pub type Selection<'tcx> = Vtable<'tcx, PredicateObligation<'tcx>>;
457 #[derive(Clone,Debug)]
458 pub enum SelectionError<'tcx> {
460 OutputTypeParameterMismatch(ty::PolyTraitRef<'tcx>,
461 ty::PolyTraitRef<'tcx>,
462 ty::error::TypeError<'tcx>),
463 TraitNotObjectSafe(DefId),
464 ConstEvalFailure(ErrorHandled),
468 EnumTypeFoldableImpl! {
469 impl<'tcx> TypeFoldable<'tcx> for SelectionError<'tcx> {
470 (SelectionError::Unimplemented),
471 (SelectionError::OutputTypeParameterMismatch)(a, b, c),
472 (SelectionError::TraitNotObjectSafe)(a),
473 (SelectionError::ConstEvalFailure)(a),
474 (SelectionError::Overflow),
478 pub struct FulfillmentError<'tcx> {
479 pub obligation: PredicateObligation<'tcx>,
480 pub code: FulfillmentErrorCode<'tcx>
484 pub enum FulfillmentErrorCode<'tcx> {
485 CodeSelectionError(SelectionError<'tcx>),
486 CodeProjectionError(MismatchedProjectionTypes<'tcx>),
487 CodeSubtypeError(ExpectedFound<Ty<'tcx>>,
488 TypeError<'tcx>), // always comes from a SubtypePredicate
492 /// When performing resolution, it is typically the case that there
493 /// can be one of three outcomes:
495 /// - `Ok(Some(r))`: success occurred with result `r`
496 /// - `Ok(None)`: could not definitely determine anything, usually due
497 /// to inconclusive type inference.
498 /// - `Err(e)`: error `e` occurred
499 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
501 /// Given the successful resolution of an obligation, the `Vtable`
502 /// indicates where the vtable comes from. Note that while we call this
503 /// a "vtable", it does not necessarily indicate dynamic dispatch at
504 /// runtime. `Vtable` instances just tell the compiler where to find
505 /// methods, but in generic code those methods are typically statically
506 /// dispatched -- only when an object is constructed is a `Vtable`
507 /// instance reified into an actual vtable.
509 /// For example, the vtable may be tied to a specific impl (case A),
510 /// or it may be relative to some bound that is in scope (case B).
513 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
514 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
515 /// impl Clone for int { ... } // Impl_3
517 /// fn foo<T:Clone>(concrete: Option<Box<int>>,
519 /// mixed: Option<T>) {
521 /// // Case A: Vtable points at a specific impl. Only possible when
522 /// // type is concretely known. If the impl itself has bounded
523 /// // type parameters, Vtable will carry resolutions for those as well:
524 /// concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
526 /// // Case B: Vtable must be provided by caller. This applies when
527 /// // type is a type parameter.
528 /// param.clone(); // VtableParam
530 /// // Case C: A mix of cases A and B.
531 /// mixed.clone(); // Vtable(Impl_1, [VtableParam])
535 /// ### The type parameter `N`
537 /// See explanation on `VtableImplData`.
538 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
539 pub enum Vtable<'tcx, N> {
540 /// Vtable identifying a particular impl.
541 VtableImpl(VtableImplData<'tcx, N>),
543 /// Vtable for auto trait implementations.
544 /// This carries the information and nested obligations with regards
545 /// to an auto implementation for a trait `Trait`. The nested obligations
546 /// ensure the trait implementation holds for all the constituent types.
547 VtableAutoImpl(VtableAutoImplData<N>),
549 /// Successful resolution to an obligation provided by the caller
550 /// for some type parameter. The `Vec<N>` represents the
551 /// obligations incurred from normalizing the where-clause (if
555 /// Virtual calls through an object.
556 VtableObject(VtableObjectData<'tcx, N>),
558 /// Successful resolution for a builtin trait.
559 VtableBuiltin(VtableBuiltinData<N>),
561 /// Vtable automatically generated for a closure. The `DefId` is the ID
562 /// of the closure expression. This is a `VtableImpl` in spirit, but the
563 /// impl is generated by the compiler and does not appear in the source.
564 VtableClosure(VtableClosureData<'tcx, N>),
566 /// Same as above, but for a function pointer type with the given signature.
567 VtableFnPointer(VtableFnPointerData<'tcx, N>),
569 /// Vtable automatically generated for a generator.
570 VtableGenerator(VtableGeneratorData<'tcx, N>),
572 /// Vtable for a trait alias.
573 VtableTraitAlias(VtableTraitAliasData<'tcx, N>),
576 /// Identifies a particular impl in the source, along with a set of
577 /// substitutions from the impl's type/lifetime parameters. The
578 /// `nested` vector corresponds to the nested obligations attached to
579 /// the impl's type parameters.
581 /// The type parameter `N` indicates the type used for "nested
582 /// obligations" that are required by the impl. During type check, this
583 /// is `Obligation`, as one might expect. During codegen, however, this
584 /// is `()`, because codegen only requires a shallow resolution of an
585 /// impl, and nested obligations are satisfied later.
586 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
587 pub struct VtableImplData<'tcx, N> {
588 pub impl_def_id: DefId,
589 pub substs: SubstsRef<'tcx>,
593 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
594 pub struct VtableGeneratorData<'tcx, N> {
595 pub generator_def_id: DefId,
596 pub substs: ty::GeneratorSubsts<'tcx>,
597 /// Nested obligations. This can be non-empty if the generator
598 /// signature contains associated types.
602 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
603 pub struct VtableClosureData<'tcx, N> {
604 pub closure_def_id: DefId,
605 pub substs: ty::ClosureSubsts<'tcx>,
606 /// Nested obligations. This can be non-empty if the closure
607 /// signature contains associated types.
611 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
612 pub struct VtableAutoImplData<N> {
613 pub trait_def_id: DefId,
617 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
618 pub struct VtableBuiltinData<N> {
622 /// A vtable for some object-safe trait `Foo` automatically derived
623 /// for the object type `Foo`.
624 #[derive(PartialEq, Eq, Clone, RustcEncodable, RustcDecodable, HashStable)]
625 pub struct VtableObjectData<'tcx, N> {
626 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
627 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
629 /// The vtable is formed by concatenating together the method lists of
630 /// the base object trait and all supertraits; this is the start of
631 /// `upcast_trait_ref`'s methods in that vtable.
632 pub vtable_base: usize,
637 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
638 pub struct VtableFnPointerData<'tcx, N> {
643 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
644 pub struct VtableTraitAliasData<'tcx, N> {
645 pub alias_def_id: DefId,
646 pub substs: SubstsRef<'tcx>,
650 /// Creates predicate obligations from the generic bounds.
651 pub fn predicates_for_generics<'tcx>(cause: ObligationCause<'tcx>,
652 param_env: ty::ParamEnv<'tcx>,
653 generic_bounds: &ty::InstantiatedPredicates<'tcx>)
654 -> PredicateObligations<'tcx>
656 util::predicates_for_generics(cause, 0, param_env, generic_bounds)
659 /// Determines whether the type `ty` is known to meet `bound` and
660 /// returns true if so. Returns false if `ty` either does not meet
661 /// `bound` or is not known to meet bound (note that this is
662 /// conservative towards *no impl*, which is the opposite of the
663 /// `evaluate` methods).
664 pub fn type_known_to_meet_bound_modulo_regions<'a, 'tcx>(
665 infcx: &InferCtxt<'a, 'tcx>,
666 param_env: ty::ParamEnv<'tcx>,
671 debug!("type_known_to_meet_bound_modulo_regions(ty={:?}, bound={:?})",
673 infcx.tcx.def_path_str(def_id));
675 let trait_ref = ty::TraitRef {
677 substs: infcx.tcx.mk_substs_trait(ty, &[]),
679 let obligation = Obligation {
681 cause: ObligationCause::misc(span, hir::DUMMY_HIR_ID),
683 predicate: trait_ref.to_predicate(),
686 let result = infcx.predicate_must_hold_modulo_regions(&obligation);
687 debug!("type_known_to_meet_ty={:?} bound={} => {:?}",
688 ty, infcx.tcx.def_path_str(def_id), result);
690 if result && (ty.has_infer_types() || ty.has_closure_types()) {
691 // Because of inference "guessing", selection can sometimes claim
692 // to succeed while the success requires a guess. To ensure
693 // this function's result remains infallible, we must confirm
694 // that guess. While imperfect, I believe this is sound.
696 // The handling of regions in this area of the code is terrible,
697 // see issue #29149. We should be able to improve on this with
699 let mut fulfill_cx = FulfillmentContext::new_ignoring_regions();
701 // We can use a dummy node-id here because we won't pay any mind
702 // to region obligations that arise (there shouldn't really be any
704 let cause = ObligationCause::misc(span, hir::DUMMY_HIR_ID);
706 fulfill_cx.register_bound(infcx, param_env, ty, def_id, cause);
708 // Note: we only assume something is `Copy` if we can
709 // *definitively* show that it implements `Copy`. Otherwise,
710 // assume it is move; linear is always ok.
711 match fulfill_cx.select_all_or_error(infcx) {
713 debug!("type_known_to_meet_bound_modulo_regions: ty={:?} bound={} success",
715 infcx.tcx.def_path_str(def_id));
719 debug!("type_known_to_meet_bound_modulo_regions: ty={:?} bound={} errors={:?}",
721 infcx.tcx.def_path_str(def_id),
731 fn do_normalize_predicates<'tcx>(
733 region_context: DefId,
734 cause: ObligationCause<'tcx>,
735 elaborated_env: ty::ParamEnv<'tcx>,
736 predicates: Vec<ty::Predicate<'tcx>>,
737 ) -> Result<Vec<ty::Predicate<'tcx>>, ErrorReported> {
739 "do_normalize_predicates(predicates={:?}, region_context={:?}, cause={:?})",
744 let span = cause.span;
745 tcx.infer_ctxt().enter(|infcx| {
746 // FIXME. We should really... do something with these region
747 // obligations. But this call just continues the older
748 // behavior (i.e., doesn't cause any new bugs), and it would
749 // take some further refactoring to actually solve them. In
750 // particular, we would have to handle implied bounds
751 // properly, and that code is currently largely confined to
752 // regionck (though I made some efforts to extract it
755 // @arielby: In any case, these obligations are checked
756 // by wfcheck anyway, so I'm not sure we have to check
757 // them here too, and we will remove this function when
758 // we move over to lazy normalization *anyway*.
759 let fulfill_cx = FulfillmentContext::new_ignoring_regions();
760 let predicates = match fully_normalize(
767 Ok(predicates) => predicates,
769 infcx.report_fulfillment_errors(&errors, None, false);
770 return Err(ErrorReported)
774 debug!("do_normalize_predictes: normalized predicates = {:?}", predicates);
776 let region_scope_tree = region::ScopeTree::default();
778 // We can use the `elaborated_env` here; the region code only
779 // cares about declarations like `'a: 'b`.
780 let outlives_env = OutlivesEnvironment::new(elaborated_env);
782 infcx.resolve_regions_and_report_errors(
786 SuppressRegionErrors::default(),
789 let predicates = match infcx.fully_resolve(&predicates) {
790 Ok(predicates) => predicates,
792 // If we encounter a fixup error, it means that some type
793 // variable wound up unconstrained. I actually don't know
794 // if this can happen, and I certainly don't expect it to
795 // happen often, but if it did happen it probably
796 // represents a legitimate failure due to some kind of
797 // unconstrained variable, and it seems better not to ICE,
798 // all things considered.
799 tcx.sess.span_err(span, &fixup_err.to_string());
800 return Err(ErrorReported)
803 if predicates.has_local_value() {
804 // FIXME: shouldn't we, you know, actually report an error here? or an ICE?
812 // FIXME: this is gonna need to be removed ...
813 /// Normalizes the parameter environment, reporting errors if they occur.
814 pub fn normalize_param_env_or_error<'tcx>(
816 region_context: DefId,
817 unnormalized_env: ty::ParamEnv<'tcx>,
818 cause: ObligationCause<'tcx>,
819 ) -> ty::ParamEnv<'tcx> {
820 // I'm not wild about reporting errors here; I'd prefer to
821 // have the errors get reported at a defined place (e.g.,
822 // during typeck). Instead I have all parameter
823 // environments, in effect, going through this function
824 // and hence potentially reporting errors. This ensures of
825 // course that we never forget to normalize (the
826 // alternative seemed like it would involve a lot of
827 // manual invocations of this fn -- and then we'd have to
828 // deal with the errors at each of those sites).
830 // In any case, in practice, typeck constructs all the
831 // parameter environments once for every fn as it goes,
832 // and errors will get reported then; so after typeck we
833 // can be sure that no errors should occur.
835 debug!("normalize_param_env_or_error(region_context={:?}, unnormalized_env={:?}, cause={:?})",
836 region_context, unnormalized_env, cause);
838 let mut predicates: Vec<_> =
839 util::elaborate_predicates(tcx, unnormalized_env.caller_bounds.to_vec())
842 debug!("normalize_param_env_or_error: elaborated-predicates={:?}",
845 let elaborated_env = ty::ParamEnv::new(
846 tcx.intern_predicates(&predicates),
847 unnormalized_env.reveal,
848 unnormalized_env.def_id
851 // HACK: we are trying to normalize the param-env inside *itself*. The problem is that
852 // normalization expects its param-env to be already normalized, which means we have
855 // The way we handle this is by normalizing the param-env inside an unnormalized version
856 // of the param-env, which means that if the param-env contains unnormalized projections,
857 // we'll have some normalization failures. This is unfortunate.
859 // Lazy normalization would basically handle this by treating just the
860 // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
862 // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
863 // types, so to make the situation less bad, we normalize all the predicates *but*
864 // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
865 // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
867 // This works fairly well because trait matching does not actually care about param-env
868 // TypeOutlives predicates - these are normally used by regionck.
869 let outlives_predicates: Vec<_> = predicates.drain_filter(|predicate| {
871 ty::Predicate::TypeOutlives(..) => true,
876 debug!("normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
877 predicates, outlives_predicates);
878 let non_outlives_predicates =
879 match do_normalize_predicates(tcx, region_context, cause.clone(),
880 elaborated_env, predicates) {
881 Ok(predicates) => predicates,
882 // An unnormalized env is better than nothing.
883 Err(ErrorReported) => {
884 debug!("normalize_param_env_or_error: errored resolving non-outlives predicates");
885 return elaborated_env
889 debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates);
891 // Not sure whether it is better to include the unnormalized TypeOutlives predicates
892 // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
893 // predicates here anyway. Keeping them here anyway because it seems safer.
894 let outlives_env: Vec<_> =
895 non_outlives_predicates.iter().chain(&outlives_predicates).cloned().collect();
896 let outlives_env = ty::ParamEnv::new(
897 tcx.intern_predicates(&outlives_env),
898 unnormalized_env.reveal,
901 let outlives_predicates =
902 match do_normalize_predicates(tcx, region_context, cause,
903 outlives_env, outlives_predicates) {
904 Ok(predicates) => predicates,
905 // An unnormalized env is better than nothing.
906 Err(ErrorReported) => {
907 debug!("normalize_param_env_or_error: errored resolving outlives predicates");
908 return elaborated_env
911 debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates);
913 let mut predicates = non_outlives_predicates;
914 predicates.extend(outlives_predicates);
915 debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
917 tcx.intern_predicates(&predicates),
918 unnormalized_env.reveal,
919 unnormalized_env.def_id
923 pub fn fully_normalize<'a, 'tcx, T>(
924 infcx: &InferCtxt<'a, 'tcx>,
925 mut fulfill_cx: FulfillmentContext<'tcx>,
926 cause: ObligationCause<'tcx>,
927 param_env: ty::ParamEnv<'tcx>,
929 ) -> Result<T, Vec<FulfillmentError<'tcx>>>
931 T: TypeFoldable<'tcx>,
933 debug!("fully_normalize_with_fulfillcx(value={:?})", value);
934 let selcx = &mut SelectionContext::new(infcx);
935 let Normalized { value: normalized_value, obligations } =
936 project::normalize(selcx, param_env, cause, value);
937 debug!("fully_normalize: normalized_value={:?} obligations={:?}",
940 for obligation in obligations {
941 fulfill_cx.register_predicate_obligation(selcx.infcx(), obligation);
944 debug!("fully_normalize: select_all_or_error start");
945 fulfill_cx.select_all_or_error(infcx)?;
946 debug!("fully_normalize: select_all_or_error complete");
947 let resolved_value = infcx.resolve_vars_if_possible(&normalized_value);
948 debug!("fully_normalize: resolved_value={:?}", resolved_value);
952 /// Normalizes the predicates and checks whether they hold in an empty
953 /// environment. If this returns false, then either normalize
954 /// encountered an error or one of the predicates did not hold. Used
955 /// when creating vtables to check for unsatisfiable methods.
956 fn normalize_and_test_predicates<'tcx>(
958 predicates: Vec<ty::Predicate<'tcx>>,
960 debug!("normalize_and_test_predicates(predicates={:?})",
963 let result = tcx.infer_ctxt().enter(|infcx| {
964 let param_env = ty::ParamEnv::reveal_all();
965 let mut selcx = SelectionContext::new(&infcx);
966 let mut fulfill_cx = FulfillmentContext::new();
967 let cause = ObligationCause::dummy();
968 let Normalized { value: predicates, obligations } =
969 normalize(&mut selcx, param_env, cause.clone(), &predicates);
970 for obligation in obligations {
971 fulfill_cx.register_predicate_obligation(&infcx, obligation);
973 for predicate in predicates {
974 let obligation = Obligation::new(cause.clone(), param_env, predicate);
975 fulfill_cx.register_predicate_obligation(&infcx, obligation);
978 fulfill_cx.select_all_or_error(&infcx).is_ok()
980 debug!("normalize_and_test_predicates(predicates={:?}) = {:?}",
985 fn substitute_normalize_and_test_predicates<'tcx>(
987 key: (DefId, SubstsRef<'tcx>),
989 debug!("substitute_normalize_and_test_predicates(key={:?})",
992 let predicates = tcx.predicates_of(key.0).instantiate(tcx, key.1).predicates;
993 let result = normalize_and_test_predicates(tcx, predicates);
995 debug!("substitute_normalize_and_test_predicates(key={:?}) = {:?}",
1000 /// Given a trait `trait_ref`, iterates the vtable entries
1001 /// that come from `trait_ref`, including its supertraits.
1002 #[inline] // FIXME(#35870): avoid closures being unexported due to `impl Trait`.
1003 fn vtable_methods<'tcx>(
1005 trait_ref: ty::PolyTraitRef<'tcx>,
1006 ) -> &'tcx [Option<(DefId, SubstsRef<'tcx>)>] {
1007 debug!("vtable_methods({:?})", trait_ref);
1009 tcx.arena.alloc_from_iter(
1010 supertraits(tcx, trait_ref).flat_map(move |trait_ref| {
1011 let trait_methods = tcx.associated_items(trait_ref.def_id())
1012 .filter(|item| item.kind == ty::AssocKind::Method);
1014 // Now list each method's DefId and InternalSubsts (for within its trait).
1015 // If the method can never be called from this object, produce None.
1016 trait_methods.map(move |trait_method| {
1017 debug!("vtable_methods: trait_method={:?}", trait_method);
1018 let def_id = trait_method.def_id;
1020 // Some methods cannot be called on an object; skip those.
1021 if !tcx.is_vtable_safe_method(trait_ref.def_id(), &trait_method) {
1022 debug!("vtable_methods: not vtable safe");
1026 // the method may have some early-bound lifetimes, add
1027 // regions for those
1028 let substs = trait_ref.map_bound(|trait_ref|
1029 InternalSubsts::for_item(tcx, def_id, |param, _|
1031 GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(),
1032 GenericParamDefKind::Type { .. } |
1033 GenericParamDefKind::Const => {
1034 trait_ref.substs[param.index as usize]
1040 // the trait type may have higher-ranked lifetimes in it;
1041 // so erase them if they appear, so that we get the type
1042 // at some particular call site
1043 let substs = tcx.normalize_erasing_late_bound_regions(
1044 ty::ParamEnv::reveal_all(),
1048 // It's possible that the method relies on where clauses that
1049 // do not hold for this particular set of type parameters.
1050 // Note that this method could then never be called, so we
1051 // do not want to try and codegen it, in that case (see #23435).
1052 let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs);
1053 if !normalize_and_test_predicates(tcx, predicates.predicates) {
1054 debug!("vtable_methods: predicates do not hold");
1058 Some((def_id, substs))
1064 impl<'tcx, O> Obligation<'tcx, O> {
1065 pub fn new(cause: ObligationCause<'tcx>,
1066 param_env: ty::ParamEnv<'tcx>,
1068 -> Obligation<'tcx, O>
1070 Obligation { cause, param_env, recursion_depth: 0, predicate }
1073 fn with_depth(cause: ObligationCause<'tcx>,
1074 recursion_depth: usize,
1075 param_env: ty::ParamEnv<'tcx>,
1077 -> Obligation<'tcx, O>
1079 Obligation { cause, param_env, recursion_depth, predicate }
1082 pub fn misc(span: Span,
1083 body_id: hir::HirId,
1084 param_env: ty::ParamEnv<'tcx>,
1086 -> Obligation<'tcx, O> {
1087 Obligation::new(ObligationCause::misc(span, body_id), param_env, trait_ref)
1090 pub fn with<P>(&self, value: P) -> Obligation<'tcx,P> {
1091 Obligation { cause: self.cause.clone(),
1092 param_env: self.param_env,
1093 recursion_depth: self.recursion_depth,
1098 impl<'tcx> ObligationCause<'tcx> {
1100 pub fn new(span: Span,
1101 body_id: hir::HirId,
1102 code: ObligationCauseCode<'tcx>)
1103 -> ObligationCause<'tcx> {
1104 ObligationCause { span, body_id, code }
1107 pub fn misc(span: Span, body_id: hir::HirId) -> ObligationCause<'tcx> {
1108 ObligationCause { span, body_id, code: MiscObligation }
1111 pub fn dummy() -> ObligationCause<'tcx> {
1112 ObligationCause { span: DUMMY_SP, body_id: hir::CRATE_HIR_ID, code: MiscObligation }
1116 impl<'tcx, N> Vtable<'tcx, N> {
1117 pub fn nested_obligations(self) -> Vec<N> {
1119 VtableImpl(i) => i.nested,
1120 VtableParam(n) => n,
1121 VtableBuiltin(i) => i.nested,
1122 VtableAutoImpl(d) => d.nested,
1123 VtableClosure(c) => c.nested,
1124 VtableGenerator(c) => c.nested,
1125 VtableObject(d) => d.nested,
1126 VtableFnPointer(d) => d.nested,
1127 VtableTraitAlias(d) => d.nested,
1131 pub fn map<M, F>(self, f: F) -> Vtable<'tcx, M> where F: FnMut(N) -> M {
1133 VtableImpl(i) => VtableImpl(VtableImplData {
1134 impl_def_id: i.impl_def_id,
1136 nested: i.nested.into_iter().map(f).collect(),
1138 VtableParam(n) => VtableParam(n.into_iter().map(f).collect()),
1139 VtableBuiltin(i) => VtableBuiltin(VtableBuiltinData {
1140 nested: i.nested.into_iter().map(f).collect(),
1142 VtableObject(o) => VtableObject(VtableObjectData {
1143 upcast_trait_ref: o.upcast_trait_ref,
1144 vtable_base: o.vtable_base,
1145 nested: o.nested.into_iter().map(f).collect(),
1147 VtableAutoImpl(d) => VtableAutoImpl(VtableAutoImplData {
1148 trait_def_id: d.trait_def_id,
1149 nested: d.nested.into_iter().map(f).collect(),
1151 VtableClosure(c) => VtableClosure(VtableClosureData {
1152 closure_def_id: c.closure_def_id,
1154 nested: c.nested.into_iter().map(f).collect(),
1156 VtableGenerator(c) => VtableGenerator(VtableGeneratorData {
1157 generator_def_id: c.generator_def_id,
1159 nested: c.nested.into_iter().map(f).collect(),
1161 VtableFnPointer(p) => VtableFnPointer(VtableFnPointerData {
1163 nested: p.nested.into_iter().map(f).collect(),
1165 VtableTraitAlias(d) => VtableTraitAlias(VtableTraitAliasData {
1166 alias_def_id: d.alias_def_id,
1168 nested: d.nested.into_iter().map(f).collect(),
1174 impl<'tcx> FulfillmentError<'tcx> {
1175 fn new(obligation: PredicateObligation<'tcx>,
1176 code: FulfillmentErrorCode<'tcx>)
1177 -> FulfillmentError<'tcx>
1179 FulfillmentError { obligation: obligation, code: code }
1183 impl<'tcx> TraitObligation<'tcx> {
1184 fn self_ty(&self) -> ty::Binder<Ty<'tcx>> {
1185 self.predicate.map_bound(|p| p.self_ty())
1189 pub fn provide(providers: &mut ty::query::Providers<'_>) {
1190 *providers = ty::query::Providers {
1191 is_object_safe: object_safety::is_object_safe_provider,
1192 specialization_graph_of: specialize::specialization_graph_provider,
1193 specializes: specialize::specializes,
1194 codegen_fulfill_obligation: codegen::codegen_fulfill_obligation,
1196 substitute_normalize_and_test_predicates,
1201 pub trait ExClauseFold<'tcx>
1203 Self: chalk_engine::context::Context + Clone,
1205 fn fold_ex_clause_with<F: TypeFolder<'tcx>>(
1206 ex_clause: &chalk_engine::ExClause<Self>,
1208 ) -> chalk_engine::ExClause<Self>;
1210 fn visit_ex_clause_with<V: TypeVisitor<'tcx>>(
1211 ex_clause: &chalk_engine::ExClause<Self>,
1216 pub trait ChalkContextLift<'tcx>
1218 Self: chalk_engine::context::Context + Clone,
1220 type LiftedExClause: Debug + 'tcx;
1221 type LiftedDelayedLiteral: Debug + 'tcx;
1222 type LiftedLiteral: Debug + 'tcx;
1224 fn lift_ex_clause_to_tcx(
1225 ex_clause: &chalk_engine::ExClause<Self>,
1227 ) -> Option<Self::LiftedExClause>;
1229 fn lift_delayed_literal_to_tcx(
1230 ex_clause: &chalk_engine::DelayedLiteral<Self>,
1232 ) -> Option<Self::LiftedDelayedLiteral>;
1234 fn lift_literal_to_tcx(
1235 ex_clause: &chalk_engine::Literal<Self>,
1237 ) -> Option<Self::LiftedLiteral>;