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_data_structures::sync::Lrc;
31 use syntax_pos::{Span, DUMMY_SP};
32 use crate::ty::subst::Substs;
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};
63 pub use self::util::{supertraits, supertrait_def_ids, transitive_bounds,
64 Supertraits, SupertraitDefIds};
66 pub use self::chalk_fulfill::{
67 CanonicalGoal as ChalkCanonicalGoal,
68 FulfillmentContext as ChalkFulfillmentContext
71 pub use self::ObligationCauseCode::*;
72 pub use self::FulfillmentErrorCode::*;
73 pub use self::SelectionError::*;
74 pub use self::Vtable::*;
76 // Whether to enable bug compatibility with issue #43355
77 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
78 pub enum IntercrateMode {
83 // The mode that trait queries run in
84 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
85 pub enum TraitQueryMode {
86 // Standard/un-canonicalized queries get accurate
87 // spans etc. passed in and hence can do reasonable
88 // error reporting on their own.
90 // Canonicalized queries get dummy spans and hence
91 // must generally propagate errors to
92 // pre-canonicalization callsites.
96 /// An `Obligation` represents some trait reference (e.g., `int:Eq`) for
97 /// which the vtable must be found. The process of finding a vtable is
98 /// called "resolving" the `Obligation`. This process consists of
99 /// either identifying an `impl` (e.g., `impl Eq for int`) that
100 /// provides the required vtable, or else finding a bound that is in
101 /// scope. The eventual result is usually a `Selection` (defined below).
102 #[derive(Clone, PartialEq, Eq, Hash)]
103 pub struct Obligation<'tcx, T> {
104 /// Why do we have to prove this thing?
105 pub cause: ObligationCause<'tcx>,
107 /// In which environment should we prove this thing?
108 pub param_env: ty::ParamEnv<'tcx>,
110 /// What are we trying to prove?
113 /// If we started proving this as a result of trying to prove
114 /// something else, track the total depth to ensure termination.
115 /// If this goes over a certain threshold, we abort compilation --
116 /// in such cases, we can not say whether or not the predicate
117 /// holds for certain. Stupid halting problem. Such a drag.
118 pub recursion_depth: usize,
121 pub type PredicateObligation<'tcx> = Obligation<'tcx, ty::Predicate<'tcx>>;
122 pub type TraitObligation<'tcx> = Obligation<'tcx, ty::PolyTraitPredicate<'tcx>>;
124 /// Why did we incur this obligation? Used for error reporting.
125 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
126 pub struct ObligationCause<'tcx> {
129 // The id of the fn body that triggered this obligation. This is
130 // used for region obligations to determine the precise
131 // environment in which the region obligation should be evaluated
132 // (in particular, closures can add new assumptions). See the
133 // field `region_obligations` of the `FulfillmentContext` for more
135 pub body_id: ast::NodeId,
137 pub code: ObligationCauseCode<'tcx>
140 impl<'tcx> ObligationCause<'tcx> {
141 pub fn span<'a, 'gcx>(&self, tcx: &TyCtxt<'a, 'gcx, 'tcx>) -> Span {
143 ObligationCauseCode::CompareImplMethodObligation { .. } |
144 ObligationCauseCode::MainFunctionType |
145 ObligationCauseCode::StartFunctionType => {
146 tcx.sess.source_map().def_span(self.span)
153 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
154 pub enum ObligationCauseCode<'tcx> {
155 /// Not well classified or should be obvious from span.
158 /// A slice or array is WF only if `T: Sized`
161 /// A tuple is WF only if its middle elements are Sized
164 /// This is the trait reference from the given projection
165 ProjectionWf(ty::ProjectionTy<'tcx>),
167 /// In an impl of trait X for type Y, type Y must
168 /// also implement all supertraits of X.
169 ItemObligation(DefId),
171 /// A type like `&'a T` is WF only if `T: 'a`.
172 ReferenceOutlivesReferent(Ty<'tcx>),
174 /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
175 ObjectTypeBound(Ty<'tcx>, ty::Region<'tcx>),
177 /// Obligation incurred due to an object cast.
178 ObjectCastObligation(/* Object type */ Ty<'tcx>),
180 // Various cases where expressions must be sized/copy/etc:
181 /// L = X implies that L is Sized
183 /// (x1, .., xn) must be Sized
184 TupleInitializerSized,
185 /// S { ... } must be Sized
186 StructInitializerSized,
187 /// Type of each variable must be Sized
188 VariableType(ast::NodeId),
189 /// Argument type must be Sized
191 /// Return type must be Sized
193 /// Yield type must be Sized
195 /// [T,..n] --> T must be Copy
198 /// Types of fields (other than the last, except for packed structs) in a struct must be sized.
199 FieldSized { adt_kind: AdtKind, last: bool },
201 /// Constant expressions must be sized.
204 /// static items must have `Sync` type
207 BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
209 ImplDerivedObligation(DerivedObligationCause<'tcx>),
211 /// error derived when matching traits/impls; see ObligationCause for more details
212 CompareImplMethodObligation {
213 item_name: ast::Name,
214 impl_item_def_id: DefId,
215 trait_item_def_id: DefId,
218 /// Checking that this expression can be assigned where it needs to be
219 // FIXME(eddyb) #11161 is the original Expr required?
222 /// Computing common supertype in the arms of a match expression
225 source: hir::MatchSource,
228 /// Computing common supertype in the pattern guard for the arms of a match expression
229 MatchExpressionArmPattern { span: Span, ty: Ty<'tcx> },
231 /// Computing common supertype in an if expression
235 semicolon: Option<Span>,
238 /// Computing common supertype of an if expression with no else counter-part
239 IfExpressionWithNoElse,
241 /// `main` has wrong type
244 /// `start` has wrong type
247 /// intrinsic has wrong type
253 /// `return` with no expression
256 /// `return` with an expression
257 ReturnType(ast::NodeId),
259 /// Block implicit return
260 BlockTailExpression(ast::NodeId),
262 /// #[feature(trivial_bounds)] is not enabled
266 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
267 pub struct DerivedObligationCause<'tcx> {
268 /// The trait reference of the parent obligation that led to the
269 /// current obligation. Note that only trait obligations lead to
270 /// derived obligations, so we just store the trait reference here
272 parent_trait_ref: ty::PolyTraitRef<'tcx>,
274 /// The parent trait had this cause
275 parent_code: Rc<ObligationCauseCode<'tcx>>
278 pub type Obligations<'tcx, O> = Vec<Obligation<'tcx, O>>;
279 pub type PredicateObligations<'tcx> = Vec<PredicateObligation<'tcx>>;
280 pub type TraitObligations<'tcx> = Vec<TraitObligation<'tcx>>;
282 /// The following types:
290 /// * `InEnvironment`
291 /// are used for representing the trait system in the form of
292 /// logic programming clauses. They are part of the interface
293 /// for the chalk SLG solver.
294 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
295 pub enum WhereClause<'tcx> {
296 Implemented(ty::TraitPredicate<'tcx>),
297 ProjectionEq(ty::ProjectionPredicate<'tcx>),
298 RegionOutlives(ty::RegionOutlivesPredicate<'tcx>),
299 TypeOutlives(ty::TypeOutlivesPredicate<'tcx>),
302 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
303 pub enum WellFormed<'tcx> {
304 Trait(ty::TraitPredicate<'tcx>),
308 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
309 pub enum FromEnv<'tcx> {
310 Trait(ty::TraitPredicate<'tcx>),
314 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
315 pub enum DomainGoal<'tcx> {
316 Holds(WhereClause<'tcx>),
317 WellFormed(WellFormed<'tcx>),
318 FromEnv(FromEnv<'tcx>),
319 Normalize(ty::ProjectionPredicate<'tcx>),
322 pub type PolyDomainGoal<'tcx> = ty::Binder<DomainGoal<'tcx>>;
324 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
325 pub enum QuantifierKind {
330 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
331 pub enum GoalKind<'tcx> {
332 Implies(Clauses<'tcx>, Goal<'tcx>),
333 And(Goal<'tcx>, Goal<'tcx>),
335 DomainGoal(DomainGoal<'tcx>),
336 Quantified(QuantifierKind, ty::Binder<Goal<'tcx>>),
337 Subtype(Ty<'tcx>, Ty<'tcx>),
341 pub type Goal<'tcx> = &'tcx GoalKind<'tcx>;
343 pub type Goals<'tcx> = &'tcx List<Goal<'tcx>>;
345 impl<'tcx> DomainGoal<'tcx> {
346 pub fn into_goal(self) -> GoalKind<'tcx> {
347 GoalKind::DomainGoal(self)
350 pub fn into_program_clause(self) -> ProgramClause<'tcx> {
353 hypotheses: ty::List::empty(),
354 category: ProgramClauseCategory::Other,
359 impl<'tcx> GoalKind<'tcx> {
360 pub fn from_poly_domain_goal<'a, 'gcx>(
361 domain_goal: PolyDomainGoal<'tcx>,
362 tcx: TyCtxt<'a, 'gcx, 'tcx>,
363 ) -> GoalKind<'tcx> {
364 match domain_goal.no_bound_vars() {
365 Some(p) => p.into_goal(),
366 None => GoalKind::Quantified(
367 QuantifierKind::Universal,
368 domain_goal.map_bound(|p| tcx.mk_goal(p.into_goal()))
374 /// This matches the definition from Page 7 of "A Proof Procedure for the Logic of Hereditary
375 /// Harrop Formulas".
376 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
377 pub enum Clause<'tcx> {
378 Implies(ProgramClause<'tcx>),
379 ForAll(ty::Binder<ProgramClause<'tcx>>),
383 pub fn category(self) -> ProgramClauseCategory {
385 Clause::Implies(clause) => clause.category,
386 Clause::ForAll(clause) => clause.skip_binder().category,
391 /// Multiple clauses.
392 pub type Clauses<'tcx> = &'tcx List<Clause<'tcx>>;
394 /// A "program clause" has the form `D :- G1, ..., Gn`. It is saying
395 /// that the domain goal `D` is true if `G1...Gn` are provable. This
396 /// is equivalent to the implication `G1..Gn => D`; we usually write
397 /// it with the reverse implication operator `:-` to emphasize the way
398 /// that programs are actually solved (via backchaining, which starts
399 /// with the goal to solve and proceeds from there).
400 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
401 pub struct ProgramClause<'tcx> {
402 /// This goal will be considered true...
403 pub goal: DomainGoal<'tcx>,
405 /// ...if we can prove these hypotheses (there may be no hypotheses at all):
406 pub hypotheses: Goals<'tcx>,
408 /// Useful for filtering clauses.
409 pub category: ProgramClauseCategory,
412 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
413 pub enum ProgramClauseCategory {
419 /// A set of clauses that we assume to be true.
420 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
421 pub struct Environment<'tcx> {
422 pub clauses: Clauses<'tcx>,
425 impl Environment<'tcx> {
426 pub fn with<G>(self, goal: G) -> InEnvironment<'tcx, G> {
434 /// Something (usually a goal), along with an environment.
435 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
436 pub struct InEnvironment<'tcx, G> {
437 pub environment: Environment<'tcx>,
441 pub type Selection<'tcx> = Vtable<'tcx, PredicateObligation<'tcx>>;
443 #[derive(Clone,Debug)]
444 pub enum SelectionError<'tcx> {
446 OutputTypeParameterMismatch(ty::PolyTraitRef<'tcx>,
447 ty::PolyTraitRef<'tcx>,
448 ty::error::TypeError<'tcx>),
449 TraitNotObjectSafe(DefId),
450 ConstEvalFailure(ErrorHandled),
454 pub struct FulfillmentError<'tcx> {
455 pub obligation: PredicateObligation<'tcx>,
456 pub code: FulfillmentErrorCode<'tcx>
460 pub enum FulfillmentErrorCode<'tcx> {
461 CodeSelectionError(SelectionError<'tcx>),
462 CodeProjectionError(MismatchedProjectionTypes<'tcx>),
463 CodeSubtypeError(ExpectedFound<Ty<'tcx>>,
464 TypeError<'tcx>), // always comes from a SubtypePredicate
468 /// When performing resolution, it is typically the case that there
469 /// can be one of three outcomes:
471 /// - `Ok(Some(r))`: success occurred with result `r`
472 /// - `Ok(None)`: could not definitely determine anything, usually due
473 /// to inconclusive type inference.
474 /// - `Err(e)`: error `e` occurred
475 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
477 /// Given the successful resolution of an obligation, the `Vtable`
478 /// indicates where the vtable comes from. Note that while we call this
479 /// a "vtable", it does not necessarily indicate dynamic dispatch at
480 /// runtime. `Vtable` instances just tell the compiler where to find
481 /// methods, but in generic code those methods are typically statically
482 /// dispatched -- only when an object is constructed is a `Vtable`
483 /// instance reified into an actual vtable.
485 /// For example, the vtable may be tied to a specific impl (case A),
486 /// or it may be relative to some bound that is in scope (case B).
490 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
491 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
492 /// impl Clone for int { ... } // Impl_3
494 /// fn foo<T:Clone>(concrete: Option<Box<int>>,
496 /// mixed: Option<T>) {
498 /// // Case A: Vtable points at a specific impl. Only possible when
499 /// // type is concretely known. If the impl itself has bounded
500 /// // type parameters, Vtable will carry resolutions for those as well:
501 /// concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
503 /// // Case B: Vtable must be provided by caller. This applies when
504 /// // type is a type parameter.
505 /// param.clone(); // VtableParam
507 /// // Case C: A mix of cases A and B.
508 /// mixed.clone(); // Vtable(Impl_1, [VtableParam])
512 /// ### The type parameter `N`
514 /// See explanation on `VtableImplData`.
515 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
516 pub enum Vtable<'tcx, N> {
517 /// Vtable identifying a particular impl.
518 VtableImpl(VtableImplData<'tcx, N>),
520 /// Vtable for auto trait implementations
521 /// This carries the information and nested obligations with regards
522 /// to an auto implementation for a trait `Trait`. The nested obligations
523 /// ensure the trait implementation holds for all the constituent types.
524 VtableAutoImpl(VtableAutoImplData<N>),
526 /// Successful resolution to an obligation provided by the caller
527 /// for some type parameter. The `Vec<N>` represents the
528 /// obligations incurred from normalizing the where-clause (if
532 /// Virtual calls through an object
533 VtableObject(VtableObjectData<'tcx, N>),
535 /// Successful resolution for a builtin trait.
536 VtableBuiltin(VtableBuiltinData<N>),
538 /// Vtable automatically generated for a closure. The def ID is the ID
539 /// of the closure expression. This is a `VtableImpl` in spirit, but the
540 /// impl is generated by the compiler and does not appear in the source.
541 VtableClosure(VtableClosureData<'tcx, N>),
543 /// Same as above, but for a fn pointer type with the given signature.
544 VtableFnPointer(VtableFnPointerData<'tcx, N>),
546 /// Vtable automatically generated for a generator.
547 VtableGenerator(VtableGeneratorData<'tcx, N>),
549 /// Vtable for a trait alias.
550 VtableTraitAlias(VtableTraitAliasData<'tcx, N>),
553 /// Identifies a particular impl in the source, along with a set of
554 /// substitutions from the impl's type/lifetime parameters. The
555 /// `nested` vector corresponds to the nested obligations attached to
556 /// the impl's type parameters.
558 /// The type parameter `N` indicates the type used for "nested
559 /// obligations" that are required by the impl. During type check, this
560 /// is `Obligation`, as one might expect. During codegen, however, this
561 /// is `()`, because codegen only requires a shallow resolution of an
562 /// impl, and nested obligations are satisfied later.
563 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
564 pub struct VtableImplData<'tcx, N> {
565 pub impl_def_id: DefId,
566 pub substs: &'tcx Substs<'tcx>,
570 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
571 pub struct VtableGeneratorData<'tcx, N> {
572 pub generator_def_id: DefId,
573 pub substs: ty::GeneratorSubsts<'tcx>,
574 /// Nested obligations. This can be non-empty if the generator
575 /// signature contains associated types.
579 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
580 pub struct VtableClosureData<'tcx, N> {
581 pub closure_def_id: DefId,
582 pub substs: ty::ClosureSubsts<'tcx>,
583 /// Nested obligations. This can be non-empty if the closure
584 /// signature contains associated types.
588 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
589 pub struct VtableAutoImplData<N> {
590 pub trait_def_id: DefId,
594 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
595 pub struct VtableBuiltinData<N> {
599 /// A vtable for some object-safe trait `Foo` automatically derived
600 /// for the object type `Foo`.
601 #[derive(PartialEq, Eq, Clone, RustcEncodable, RustcDecodable)]
602 pub struct VtableObjectData<'tcx, N> {
603 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
604 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
606 /// The vtable is formed by concatenating together the method lists of
607 /// the base object trait and all supertraits; this is the start of
608 /// `upcast_trait_ref`'s methods in that vtable.
609 pub vtable_base: usize,
614 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
615 pub struct VtableFnPointerData<'tcx, N> {
620 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
621 pub struct VtableTraitAliasData<'tcx, N> {
622 pub alias_def_id: DefId,
623 pub substs: &'tcx Substs<'tcx>,
627 /// Creates predicate obligations from the generic bounds.
628 pub fn predicates_for_generics<'tcx>(cause: ObligationCause<'tcx>,
629 param_env: ty::ParamEnv<'tcx>,
630 generic_bounds: &ty::InstantiatedPredicates<'tcx>)
631 -> PredicateObligations<'tcx>
633 util::predicates_for_generics(cause, 0, param_env, generic_bounds)
636 /// Determines whether the type `ty` is known to meet `bound` and
637 /// returns true if so. Returns false if `ty` either does not meet
638 /// `bound` or is not known to meet bound (note that this is
639 /// conservative towards *no impl*, which is the opposite of the
640 /// `evaluate` methods).
641 pub fn type_known_to_meet_bound_modulo_regions<'a, 'gcx, 'tcx>(
642 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
643 param_env: ty::ParamEnv<'tcx>,
648 debug!("type_known_to_meet_bound_modulo_regions(ty={:?}, bound={:?})",
650 infcx.tcx.item_path_str(def_id));
652 let trait_ref = ty::TraitRef {
654 substs: infcx.tcx.mk_substs_trait(ty, &[]),
656 let obligation = Obligation {
658 cause: ObligationCause::misc(span, ast::DUMMY_NODE_ID),
660 predicate: trait_ref.to_predicate(),
663 let result = infcx.predicate_must_hold_modulo_regions(&obligation);
664 debug!("type_known_to_meet_ty={:?} bound={} => {:?}",
665 ty, infcx.tcx.item_path_str(def_id), result);
667 if result && (ty.has_infer_types() || ty.has_closure_types()) {
668 // Because of inference "guessing", selection can sometimes claim
669 // to succeed while the success requires a guess. To ensure
670 // this function's result remains infallible, we must confirm
671 // that guess. While imperfect, I believe this is sound.
673 // The handling of regions in this area of the code is terrible,
674 // see issue #29149. We should be able to improve on this with
676 let mut fulfill_cx = FulfillmentContext::new_ignoring_regions();
678 // We can use a dummy node-id here because we won't pay any mind
679 // to region obligations that arise (there shouldn't really be any
681 let cause = ObligationCause::misc(span, ast::DUMMY_NODE_ID);
683 fulfill_cx.register_bound(infcx, param_env, ty, def_id, cause);
685 // Note: we only assume something is `Copy` if we can
686 // *definitively* show that it implements `Copy`. Otherwise,
687 // assume it is move; linear is always ok.
688 match fulfill_cx.select_all_or_error(infcx) {
690 debug!("type_known_to_meet_bound_modulo_regions: ty={:?} bound={} success",
692 infcx.tcx.item_path_str(def_id));
696 debug!("type_known_to_meet_bound_modulo_regions: ty={:?} bound={} errors={:?}",
698 infcx.tcx.item_path_str(def_id),
708 fn do_normalize_predicates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
709 region_context: DefId,
710 cause: ObligationCause<'tcx>,
711 elaborated_env: ty::ParamEnv<'tcx>,
712 predicates: Vec<ty::Predicate<'tcx>>)
713 -> Result<Vec<ty::Predicate<'tcx>>, ErrorReported>
716 "do_normalize_predicates(predicates={:?}, region_context={:?}, cause={:?})",
721 let span = cause.span;
722 tcx.infer_ctxt().enter(|infcx| {
723 // FIXME. We should really... do something with these region
724 // obligations. But this call just continues the older
725 // behavior (i.e., doesn't cause any new bugs), and it would
726 // take some further refactoring to actually solve them. In
727 // particular, we would have to handle implied bounds
728 // properly, and that code is currently largely confined to
729 // regionck (though I made some efforts to extract it
732 // @arielby: In any case, these obligations are checked
733 // by wfcheck anyway, so I'm not sure we have to check
734 // them here too, and we will remove this function when
735 // we move over to lazy normalization *anyway*.
736 let fulfill_cx = FulfillmentContext::new_ignoring_regions();
737 let predicates = match fully_normalize(
744 Ok(predicates) => predicates,
746 infcx.report_fulfillment_errors(&errors, None, false);
747 return Err(ErrorReported)
751 debug!("do_normalize_predictes: normalized predicates = {:?}", predicates);
753 let region_scope_tree = region::ScopeTree::default();
755 // We can use the `elaborated_env` here; the region code only
756 // cares about declarations like `'a: 'b`.
757 let outlives_env = OutlivesEnvironment::new(elaborated_env);
759 infcx.resolve_regions_and_report_errors(
763 SuppressRegionErrors::default(),
766 let predicates = match infcx.fully_resolve(&predicates) {
767 Ok(predicates) => predicates,
769 // If we encounter a fixup error, it means that some type
770 // variable wound up unconstrained. I actually don't know
771 // if this can happen, and I certainly don't expect it to
772 // happen often, but if it did happen it probably
773 // represents a legitimate failure due to some kind of
774 // unconstrained variable, and it seems better not to ICE,
775 // all things considered.
776 tcx.sess.span_err(span, &fixup_err.to_string());
777 return Err(ErrorReported)
781 match tcx.lift_to_global(&predicates) {
782 Some(predicates) => Ok(predicates),
784 // FIXME: shouldn't we, you know, actually report an error here? or an ICE?
791 // FIXME: this is gonna need to be removed ...
792 /// Normalizes the parameter environment, reporting errors if they occur.
793 pub fn normalize_param_env_or_error<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
794 region_context: DefId,
795 unnormalized_env: ty::ParamEnv<'tcx>,
796 cause: ObligationCause<'tcx>)
797 -> ty::ParamEnv<'tcx>
799 // I'm not wild about reporting errors here; I'd prefer to
800 // have the errors get reported at a defined place (e.g.,
801 // during typeck). Instead I have all parameter
802 // environments, in effect, going through this function
803 // and hence potentially reporting errors. This ensures of
804 // course that we never forget to normalize (the
805 // alternative seemed like it would involve a lot of
806 // manual invocations of this fn -- and then we'd have to
807 // deal with the errors at each of those sites).
809 // In any case, in practice, typeck constructs all the
810 // parameter environments once for every fn as it goes,
811 // and errors will get reported then; so after typeck we
812 // can be sure that no errors should occur.
814 debug!("normalize_param_env_or_error(region_context={:?}, unnormalized_env={:?}, cause={:?})",
815 region_context, unnormalized_env, cause);
817 let mut predicates: Vec<_> =
818 util::elaborate_predicates(tcx, unnormalized_env.caller_bounds.to_vec())
821 debug!("normalize_param_env_or_error: elaborated-predicates={:?}",
824 let elaborated_env = ty::ParamEnv::new(
825 tcx.intern_predicates(&predicates),
826 unnormalized_env.reveal,
827 unnormalized_env.def_id
830 // HACK: we are trying to normalize the param-env inside *itself*. The problem is that
831 // normalization expects its param-env to be already normalized, which means we have
834 // The way we handle this is by normalizing the param-env inside an unnormalized version
835 // of the param-env, which means that if the param-env contains unnormalized projections,
836 // we'll have some normalization failures. This is unfortunate.
838 // Lazy normalization would basically handle this by treating just the
839 // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
841 // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
842 // types, so to make the situation less bad, we normalize all the predicates *but*
843 // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
844 // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
846 // This works fairly well because trait matching does not actually care about param-env
847 // TypeOutlives predicates - these are normally used by regionck.
848 let outlives_predicates: Vec<_> = predicates.drain_filter(|predicate| {
850 ty::Predicate::TypeOutlives(..) => true,
855 debug!("normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
856 predicates, outlives_predicates);
857 let non_outlives_predicates =
858 match do_normalize_predicates(tcx, region_context, cause.clone(),
859 elaborated_env, predicates) {
860 Ok(predicates) => predicates,
861 // An unnormalized env is better than nothing.
862 Err(ErrorReported) => {
863 debug!("normalize_param_env_or_error: errored resolving non-outlives predicates");
864 return elaborated_env
868 debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates);
870 // Not sure whether it is better to include the unnormalized TypeOutlives predicates
871 // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
872 // predicates here anyway. Keeping them here anyway because it seems safer.
873 let outlives_env: Vec<_> =
874 non_outlives_predicates.iter().chain(&outlives_predicates).cloned().collect();
875 let outlives_env = ty::ParamEnv::new(
876 tcx.intern_predicates(&outlives_env),
877 unnormalized_env.reveal,
880 let outlives_predicates =
881 match do_normalize_predicates(tcx, region_context, cause,
882 outlives_env, outlives_predicates) {
883 Ok(predicates) => predicates,
884 // An unnormalized env is better than nothing.
885 Err(ErrorReported) => {
886 debug!("normalize_param_env_or_error: errored resolving outlives predicates");
887 return elaborated_env
890 debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates);
892 let mut predicates = non_outlives_predicates;
893 predicates.extend(outlives_predicates);
894 debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
896 tcx.intern_predicates(&predicates),
897 unnormalized_env.reveal,
898 unnormalized_env.def_id
902 pub fn fully_normalize<'a, 'gcx, 'tcx, T>(
903 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
904 mut fulfill_cx: FulfillmentContext<'tcx>,
905 cause: ObligationCause<'tcx>,
906 param_env: ty::ParamEnv<'tcx>,
908 -> Result<T, Vec<FulfillmentError<'tcx>>>
909 where T : TypeFoldable<'tcx>
911 debug!("fully_normalize_with_fulfillcx(value={:?})", value);
912 let selcx = &mut SelectionContext::new(infcx);
913 let Normalized { value: normalized_value, obligations } =
914 project::normalize(selcx, param_env, cause, value);
915 debug!("fully_normalize: normalized_value={:?} obligations={:?}",
918 for obligation in obligations {
919 fulfill_cx.register_predicate_obligation(selcx.infcx(), obligation);
922 debug!("fully_normalize: select_all_or_error start");
923 fulfill_cx.select_all_or_error(infcx)?;
924 debug!("fully_normalize: select_all_or_error complete");
925 let resolved_value = infcx.resolve_type_vars_if_possible(&normalized_value);
926 debug!("fully_normalize: resolved_value={:?}", resolved_value);
930 /// Normalizes the predicates and checks whether they hold in an empty
931 /// environment. If this returns false, then either normalize
932 /// encountered an error or one of the predicates did not hold. Used
933 /// when creating vtables to check for unsatisfiable methods.
934 fn normalize_and_test_predicates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
935 predicates: Vec<ty::Predicate<'tcx>>)
938 debug!("normalize_and_test_predicates(predicates={:?})",
941 let result = tcx.infer_ctxt().enter(|infcx| {
942 let param_env = ty::ParamEnv::reveal_all();
943 let mut selcx = SelectionContext::new(&infcx);
944 let mut fulfill_cx = FulfillmentContext::new();
945 let cause = ObligationCause::dummy();
946 let Normalized { value: predicates, obligations } =
947 normalize(&mut selcx, param_env, cause.clone(), &predicates);
948 for obligation in obligations {
949 fulfill_cx.register_predicate_obligation(&infcx, obligation);
951 for predicate in predicates {
952 let obligation = Obligation::new(cause.clone(), param_env, predicate);
953 fulfill_cx.register_predicate_obligation(&infcx, obligation);
956 fulfill_cx.select_all_or_error(&infcx).is_ok()
958 debug!("normalize_and_test_predicates(predicates={:?}) = {:?}",
963 fn substitute_normalize_and_test_predicates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
964 key: (DefId, &'tcx Substs<'tcx>))
967 debug!("substitute_normalize_and_test_predicates(key={:?})",
970 let predicates = tcx.predicates_of(key.0).instantiate(tcx, key.1).predicates;
971 let result = normalize_and_test_predicates(tcx, predicates);
973 debug!("substitute_normalize_and_test_predicates(key={:?}) = {:?}",
978 /// Given a trait `trait_ref`, iterates the vtable entries
979 /// that come from `trait_ref`, including its supertraits.
980 #[inline] // FIXME(#35870): avoid closures being unexported due to `impl Trait`.
981 fn vtable_methods<'a, 'tcx>(
982 tcx: TyCtxt<'a, 'tcx, 'tcx>,
983 trait_ref: ty::PolyTraitRef<'tcx>)
984 -> Lrc<Vec<Option<(DefId, &'tcx Substs<'tcx>)>>>
986 debug!("vtable_methods({:?})", trait_ref);
989 supertraits(tcx, trait_ref).flat_map(move |trait_ref| {
990 let trait_methods = tcx.associated_items(trait_ref.def_id())
991 .filter(|item| item.kind == ty::AssociatedKind::Method);
993 // Now list each method's DefId and Substs (for within its trait).
994 // If the method can never be called from this object, produce None.
995 trait_methods.map(move |trait_method| {
996 debug!("vtable_methods: trait_method={:?}", trait_method);
997 let def_id = trait_method.def_id;
999 // Some methods cannot be called on an object; skip those.
1000 if !tcx.is_vtable_safe_method(trait_ref.def_id(), &trait_method) {
1001 debug!("vtable_methods: not vtable safe");
1005 // the method may have some early-bound lifetimes, add
1006 // regions for those
1007 let substs = trait_ref.map_bound(|trait_ref|
1008 Substs::for_item(tcx, def_id, |param, _|
1010 GenericParamDefKind::Lifetime => tcx.types.re_erased.into(),
1011 GenericParamDefKind::Type {..} => {
1012 trait_ref.substs[param.index as usize]
1018 // the trait type may have higher-ranked lifetimes in it;
1019 // so erase them if they appear, so that we get the type
1020 // at some particular call site
1021 let substs = tcx.normalize_erasing_late_bound_regions(
1022 ty::ParamEnv::reveal_all(),
1026 // It's possible that the method relies on where clauses that
1027 // do not hold for this particular set of type parameters.
1028 // Note that this method could then never be called, so we
1029 // do not want to try and codegen it, in that case (see #23435).
1030 let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs);
1031 if !normalize_and_test_predicates(tcx, predicates.predicates) {
1032 debug!("vtable_methods: predicates do not hold");
1036 Some((def_id, substs))
1042 impl<'tcx,O> Obligation<'tcx,O> {
1043 pub fn new(cause: ObligationCause<'tcx>,
1044 param_env: ty::ParamEnv<'tcx>,
1046 -> Obligation<'tcx, O>
1048 Obligation { cause, param_env, recursion_depth: 0, predicate }
1051 fn with_depth(cause: ObligationCause<'tcx>,
1052 recursion_depth: usize,
1053 param_env: ty::ParamEnv<'tcx>,
1055 -> Obligation<'tcx, O>
1057 Obligation { cause, param_env, recursion_depth, predicate }
1060 pub fn misc(span: Span,
1061 body_id: ast::NodeId,
1062 param_env: ty::ParamEnv<'tcx>,
1064 -> Obligation<'tcx, O> {
1065 Obligation::new(ObligationCause::misc(span, body_id), param_env, trait_ref)
1068 pub fn with<P>(&self, value: P) -> Obligation<'tcx,P> {
1069 Obligation { cause: self.cause.clone(),
1070 param_env: self.param_env,
1071 recursion_depth: self.recursion_depth,
1076 impl<'tcx> ObligationCause<'tcx> {
1078 pub fn new(span: Span,
1079 body_id: ast::NodeId,
1080 code: ObligationCauseCode<'tcx>)
1081 -> ObligationCause<'tcx> {
1082 ObligationCause { span: span, body_id: body_id, code: code }
1085 pub fn misc(span: Span, body_id: ast::NodeId) -> ObligationCause<'tcx> {
1086 ObligationCause { span: span, body_id: body_id, code: MiscObligation }
1089 pub fn dummy() -> ObligationCause<'tcx> {
1090 ObligationCause { span: DUMMY_SP, body_id: ast::CRATE_NODE_ID, code: MiscObligation }
1094 impl<'tcx, N> Vtable<'tcx, N> {
1095 pub fn nested_obligations(self) -> Vec<N> {
1097 VtableImpl(i) => i.nested,
1098 VtableParam(n) => n,
1099 VtableBuiltin(i) => i.nested,
1100 VtableAutoImpl(d) => d.nested,
1101 VtableClosure(c) => c.nested,
1102 VtableGenerator(c) => c.nested,
1103 VtableObject(d) => d.nested,
1104 VtableFnPointer(d) => d.nested,
1105 VtableTraitAlias(d) => d.nested,
1109 pub fn map<M, F>(self, f: F) -> Vtable<'tcx, M> where F: FnMut(N) -> M {
1111 VtableImpl(i) => VtableImpl(VtableImplData {
1112 impl_def_id: i.impl_def_id,
1114 nested: i.nested.into_iter().map(f).collect(),
1116 VtableParam(n) => VtableParam(n.into_iter().map(f).collect()),
1117 VtableBuiltin(i) => VtableBuiltin(VtableBuiltinData {
1118 nested: i.nested.into_iter().map(f).collect(),
1120 VtableObject(o) => VtableObject(VtableObjectData {
1121 upcast_trait_ref: o.upcast_trait_ref,
1122 vtable_base: o.vtable_base,
1123 nested: o.nested.into_iter().map(f).collect(),
1125 VtableAutoImpl(d) => VtableAutoImpl(VtableAutoImplData {
1126 trait_def_id: d.trait_def_id,
1127 nested: d.nested.into_iter().map(f).collect(),
1129 VtableClosure(c) => VtableClosure(VtableClosureData {
1130 closure_def_id: c.closure_def_id,
1132 nested: c.nested.into_iter().map(f).collect(),
1134 VtableGenerator(c) => VtableGenerator(VtableGeneratorData {
1135 generator_def_id: c.generator_def_id,
1137 nested: c.nested.into_iter().map(f).collect(),
1139 VtableFnPointer(p) => VtableFnPointer(VtableFnPointerData {
1141 nested: p.nested.into_iter().map(f).collect(),
1143 VtableTraitAlias(d) => VtableTraitAlias(VtableTraitAliasData {
1144 alias_def_id: d.alias_def_id,
1146 nested: d.nested.into_iter().map(f).collect(),
1152 impl<'tcx> FulfillmentError<'tcx> {
1153 fn new(obligation: PredicateObligation<'tcx>,
1154 code: FulfillmentErrorCode<'tcx>)
1155 -> FulfillmentError<'tcx>
1157 FulfillmentError { obligation: obligation, code: code }
1161 impl<'tcx> TraitObligation<'tcx> {
1162 fn self_ty(&self) -> ty::Binder<Ty<'tcx>> {
1163 self.predicate.map_bound(|p| p.self_ty())
1167 pub fn provide(providers: &mut ty::query::Providers<'_>) {
1168 *providers = ty::query::Providers {
1169 is_object_safe: object_safety::is_object_safe_provider,
1170 specialization_graph_of: specialize::specialization_graph_provider,
1171 specializes: specialize::specializes,
1172 codegen_fulfill_obligation: codegen::codegen_fulfill_obligation,
1174 substitute_normalize_and_test_predicates,
1179 pub trait ExClauseFold<'tcx>
1181 Self: chalk_engine::context::Context + Clone,
1183 fn fold_ex_clause_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(
1184 ex_clause: &chalk_engine::ExClause<Self>,
1186 ) -> chalk_engine::ExClause<Self>;
1188 fn visit_ex_clause_with<'gcx: 'tcx, V: TypeVisitor<'tcx>>(
1189 ex_clause: &chalk_engine::ExClause<Self>,
1194 pub trait ChalkContextLift<'tcx>
1196 Self: chalk_engine::context::Context + Clone,
1198 type LiftedExClause: Debug + 'tcx;
1199 type LiftedDelayedLiteral: Debug + 'tcx;
1200 type LiftedLiteral: Debug + 'tcx;
1202 fn lift_ex_clause_to_tcx<'a, 'gcx>(
1203 ex_clause: &chalk_engine::ExClause<Self>,
1204 tcx: TyCtxt<'a, 'gcx, 'tcx>,
1205 ) -> Option<Self::LiftedExClause>;
1207 fn lift_delayed_literal_to_tcx<'a, 'gcx>(
1208 ex_clause: &chalk_engine::DelayedLiteral<Self>,
1209 tcx: TyCtxt<'a, 'gcx, 'tcx>,
1210 ) -> Option<Self::LiftedDelayedLiteral>;
1212 fn lift_literal_to_tcx<'a, 'gcx>(
1213 ex_clause: &chalk_engine::Literal<Self>,
1214 tcx: TyCtxt<'a, 'gcx, 'tcx>,
1215 ) -> Option<Self::LiftedLiteral>;