1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Trait Resolution. See the [rustc guide] for more information on how this works.
13 //! [rustc guide]: https://rust-lang.github.io/rustc-guide/traits/resolution.html
18 pub mod error_reporting;
33 use hir::def_id::DefId;
34 use infer::{InferCtxt, SuppressRegionErrors};
35 use infer::outlives::env::OutlivesEnvironment;
37 use mir::interpret::ErrorHandled;
38 use rustc_data_structures::sync::Lrc;
40 use syntax_pos::{Span, DUMMY_SP};
41 use ty::subst::Substs;
42 use ty::{self, AdtKind, List, Ty, TyCtxt, GenericParamDefKind, ToPredicate};
43 use ty::error::{ExpectedFound, TypeError};
44 use ty::fold::{TypeFolder, TypeFoldable, TypeVisitor};
45 use util::common::ErrorReported;
47 pub use self::SelectionError::*;
48 pub use self::FulfillmentErrorCode::*;
49 pub use self::Vtable::*;
50 pub use self::ObligationCauseCode::*;
52 pub use self::coherence::{orphan_check, overlapping_impls, OrphanCheckErr, OverlapResult};
53 pub use self::fulfill::{FulfillmentContext, PendingPredicateObligation};
54 pub use self::project::MismatchedProjectionTypes;
55 pub use self::project::{normalize, normalize_projection_type, poly_project_and_unify_type};
56 pub use self::project::{ProjectionCache, ProjectionCacheSnapshot, Reveal, Normalized};
57 pub use self::object_safety::ObjectSafetyViolation;
58 pub use self::object_safety::MethodViolationCode;
59 pub use self::on_unimplemented::{OnUnimplementedDirective, OnUnimplementedNote};
60 pub use self::select::{EvaluationCache, SelectionContext, SelectionCache};
61 pub use self::select::{EvaluationResult, IntercrateAmbiguityCause, OverflowError};
62 pub use self::specialize::{OverlapError, specialization_graph, translate_substs};
63 pub use self::specialize::find_associated_item;
64 pub use self::engine::{TraitEngine, TraitEngineExt};
65 pub use self::util::{elaborate_predicates, elaborate_trait_ref, elaborate_trait_refs};
66 pub use self::util::{supertraits, supertrait_def_ids, transitive_bounds,
67 Supertraits, SupertraitDefIds};
69 pub use self::ObligationCauseCode::*;
70 pub use self::FulfillmentErrorCode::*;
71 pub use self::SelectionError::*;
72 pub use self::Vtable::*;
74 // Whether to enable bug compatibility with issue #43355
75 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
76 pub enum IntercrateMode {
81 // The mode that trait queries run in
82 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
83 pub enum TraitQueryMode {
84 // Standard/un-canonicalized queries get accurate
85 // spans etc. passed in and hence can do reasonable
86 // error reporting on their own.
88 // Canonicalized queries get dummy spans and hence
89 // must generally propagate errors to
90 // pre-canonicalization callsites.
94 /// An `Obligation` represents some trait reference (e.g., `int:Eq`) for
95 /// which the vtable must be found. The process of finding a vtable is
96 /// called "resolving" the `Obligation`. This process consists of
97 /// either identifying an `impl` (e.g., `impl Eq for int`) that
98 /// provides the required vtable, or else finding a bound that is in
99 /// scope. The eventual result is usually a `Selection` (defined below).
100 #[derive(Clone, PartialEq, Eq, Hash)]
101 pub struct Obligation<'tcx, T> {
102 /// Why do we have to prove this thing?
103 pub cause: ObligationCause<'tcx>,
105 /// In which environment should we prove this thing?
106 pub param_env: ty::ParamEnv<'tcx>,
108 /// What are we trying to prove?
111 /// If we started proving this as a result of trying to prove
112 /// something else, track the total depth to ensure termination.
113 /// If this goes over a certain threshold, we abort compilation --
114 /// in such cases, we can not say whether or not the predicate
115 /// holds for certain. Stupid halting problem. Such a drag.
116 pub recursion_depth: usize,
119 pub type PredicateObligation<'tcx> = Obligation<'tcx, ty::Predicate<'tcx>>;
120 pub type TraitObligation<'tcx> = Obligation<'tcx, ty::PolyTraitPredicate<'tcx>>;
122 /// Why did we incur this obligation? Used for error reporting.
123 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
124 pub struct ObligationCause<'tcx> {
127 // The id of the fn body that triggered this obligation. This is
128 // used for region obligations to determine the precise
129 // environment in which the region obligation should be evaluated
130 // (in particular, closures can add new assumptions). See the
131 // field `region_obligations` of the `FulfillmentContext` for more
133 pub body_id: ast::NodeId,
135 pub code: ObligationCauseCode<'tcx>
138 impl<'tcx> ObligationCause<'tcx> {
139 pub fn span<'a, 'gcx>(&self, tcx: &TyCtxt<'a, 'gcx, 'tcx>) -> Span {
141 ObligationCauseCode::CompareImplMethodObligation { .. } |
142 ObligationCauseCode::MainFunctionType |
143 ObligationCauseCode::StartFunctionType => {
144 tcx.sess.source_map().def_span(self.span)
151 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
152 pub enum ObligationCauseCode<'tcx> {
153 /// Not well classified or should be obvious from span.
156 /// A slice or array is WF only if `T: Sized`
159 /// A tuple is WF only if its middle elements are Sized
162 /// This is the trait reference from the given projection
163 ProjectionWf(ty::ProjectionTy<'tcx>),
165 /// In an impl of trait X for type Y, type Y must
166 /// also implement all supertraits of X.
167 ItemObligation(DefId),
169 /// A type like `&'a T` is WF only if `T: 'a`.
170 ReferenceOutlivesReferent(Ty<'tcx>),
172 /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
173 ObjectTypeBound(Ty<'tcx>, ty::Region<'tcx>),
175 /// Obligation incurred due to an object cast.
176 ObjectCastObligation(/* Object type */ Ty<'tcx>),
178 // Various cases where expressions must be sized/copy/etc:
179 /// L = X implies that L is Sized
181 /// (x1, .., xn) must be Sized
182 TupleInitializerSized,
183 /// S { ... } must be Sized
184 StructInitializerSized,
185 /// Type of each variable must be Sized
186 VariableType(ast::NodeId),
187 /// Argument type must be Sized
189 /// Return type must be Sized
191 /// Yield type must be Sized
193 /// [T,..n] --> T must be Copy
196 /// Types of fields (other than the last, except for packed structs) in a struct must be sized.
197 FieldSized { adt_kind: AdtKind, last: bool },
199 /// Constant expressions must be sized.
202 /// static items must have `Sync` type
205 BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
207 ImplDerivedObligation(DerivedObligationCause<'tcx>),
209 /// error derived when matching traits/impls; see ObligationCause for more details
210 CompareImplMethodObligation {
211 item_name: ast::Name,
212 impl_item_def_id: DefId,
213 trait_item_def_id: DefId,
216 /// Checking that this expression can be assigned where it needs to be
217 // FIXME(eddyb) #11161 is the original Expr required?
220 /// Computing common supertype in the arms of a match expression
221 MatchExpressionArm { arm_span: Span,
222 source: hir::MatchSource },
224 /// Computing common supertype in an if expression
227 /// Computing common supertype of an if expression with no else counter-part
228 IfExpressionWithNoElse,
230 /// `main` has wrong type
233 /// `start` has wrong type
236 /// intrinsic has wrong type
242 /// `return` with no expression
245 /// `return` with an expression
246 ReturnType(ast::NodeId),
248 /// Block implicit return
249 BlockTailExpression(ast::NodeId),
251 /// #[feature(trivial_bounds)] is not enabled
255 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
256 pub struct DerivedObligationCause<'tcx> {
257 /// The trait reference of the parent obligation that led to the
258 /// current obligation. Note that only trait obligations lead to
259 /// derived obligations, so we just store the trait reference here
261 parent_trait_ref: ty::PolyTraitRef<'tcx>,
263 /// The parent trait had this cause
264 parent_code: Rc<ObligationCauseCode<'tcx>>
267 pub type Obligations<'tcx, O> = Vec<Obligation<'tcx, O>>;
268 pub type PredicateObligations<'tcx> = Vec<PredicateObligation<'tcx>>;
269 pub type TraitObligations<'tcx> = Vec<TraitObligation<'tcx>>;
271 /// The following types:
279 /// * `InEnvironment`
280 /// are used for representing the trait system in the form of
281 /// logic programming clauses. They are part of the interface
282 /// for the chalk SLG solver.
283 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
284 pub enum WhereClause<'tcx> {
285 Implemented(ty::TraitPredicate<'tcx>),
286 ProjectionEq(ty::ProjectionPredicate<'tcx>),
287 RegionOutlives(ty::RegionOutlivesPredicate<'tcx>),
288 TypeOutlives(ty::TypeOutlivesPredicate<'tcx>),
291 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
292 pub enum WellFormed<'tcx> {
293 Trait(ty::TraitPredicate<'tcx>),
297 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
298 pub enum FromEnv<'tcx> {
299 Trait(ty::TraitPredicate<'tcx>),
303 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
304 pub enum DomainGoal<'tcx> {
305 Holds(WhereClause<'tcx>),
306 WellFormed(WellFormed<'tcx>),
307 FromEnv(FromEnv<'tcx>),
308 Normalize(ty::ProjectionPredicate<'tcx>),
311 pub type PolyDomainGoal<'tcx> = ty::Binder<DomainGoal<'tcx>>;
313 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
314 pub enum QuantifierKind {
319 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
320 pub enum GoalKind<'tcx> {
321 Implies(Clauses<'tcx>, Goal<'tcx>),
322 And(Goal<'tcx>, Goal<'tcx>),
324 DomainGoal(DomainGoal<'tcx>),
325 Quantified(QuantifierKind, ty::Binder<Goal<'tcx>>),
329 pub type Goal<'tcx> = &'tcx GoalKind<'tcx>;
331 pub type Goals<'tcx> = &'tcx List<Goal<'tcx>>;
333 impl<'tcx> DomainGoal<'tcx> {
334 pub fn into_goal(self) -> GoalKind<'tcx> {
335 GoalKind::DomainGoal(self)
338 pub fn into_program_clause(self) -> ProgramClause<'tcx> {
341 hypotheses: ty::List::empty(),
342 category: ProgramClauseCategory::Other,
347 impl<'tcx> GoalKind<'tcx> {
348 pub fn from_poly_domain_goal<'a>(
349 domain_goal: PolyDomainGoal<'tcx>,
350 tcx: TyCtxt<'a, 'tcx, 'tcx>,
351 ) -> GoalKind<'tcx> {
352 match domain_goal.no_bound_vars() {
353 Some(p) => p.into_goal(),
354 None => GoalKind::Quantified(
355 QuantifierKind::Universal,
356 domain_goal.map_bound(|p| tcx.mk_goal(p.into_goal()))
362 /// This matches the definition from Page 7 of "A Proof Procedure for the Logic of Hereditary
363 /// Harrop Formulas".
364 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
365 pub enum Clause<'tcx> {
366 Implies(ProgramClause<'tcx>),
367 ForAll(ty::Binder<ProgramClause<'tcx>>),
371 pub fn category(self) -> ProgramClauseCategory {
373 Clause::Implies(clause) => clause.category,
374 Clause::ForAll(clause) => clause.skip_binder().category,
379 /// Multiple clauses.
380 pub type Clauses<'tcx> = &'tcx List<Clause<'tcx>>;
382 /// A "program clause" has the form `D :- G1, ..., Gn`. It is saying
383 /// that the domain goal `D` is true if `G1...Gn` are provable. This
384 /// is equivalent to the implication `G1..Gn => D`; we usually write
385 /// it with the reverse implication operator `:-` to emphasize the way
386 /// that programs are actually solved (via backchaining, which starts
387 /// with the goal to solve and proceeds from there).
388 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
389 pub struct ProgramClause<'tcx> {
390 /// This goal will be considered true...
391 pub goal: DomainGoal<'tcx>,
393 /// ...if we can prove these hypotheses (there may be no hypotheses at all):
394 pub hypotheses: Goals<'tcx>,
396 /// Useful for filtering clauses.
397 pub category: ProgramClauseCategory,
400 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
401 pub enum ProgramClauseCategory {
407 /// A set of clauses that we assume to be true.
408 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
409 pub struct Environment<'tcx> {
410 pub clauses: Clauses<'tcx>,
413 impl Environment<'tcx> {
414 pub fn with<G>(self, goal: G) -> InEnvironment<'tcx, G> {
422 /// Something (usually a goal), along with an environment.
423 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
424 pub struct InEnvironment<'tcx, G> {
425 pub environment: Environment<'tcx>,
429 pub type Selection<'tcx> = Vtable<'tcx, PredicateObligation<'tcx>>;
431 #[derive(Clone,Debug)]
432 pub enum SelectionError<'tcx> {
434 OutputTypeParameterMismatch(ty::PolyTraitRef<'tcx>,
435 ty::PolyTraitRef<'tcx>,
436 ty::error::TypeError<'tcx>),
437 TraitNotObjectSafe(DefId),
438 ConstEvalFailure(ErrorHandled),
442 pub struct FulfillmentError<'tcx> {
443 pub obligation: PredicateObligation<'tcx>,
444 pub code: FulfillmentErrorCode<'tcx>
448 pub enum FulfillmentErrorCode<'tcx> {
449 CodeSelectionError(SelectionError<'tcx>),
450 CodeProjectionError(MismatchedProjectionTypes<'tcx>),
451 CodeSubtypeError(ExpectedFound<Ty<'tcx>>,
452 TypeError<'tcx>), // always comes from a SubtypePredicate
456 /// When performing resolution, it is typically the case that there
457 /// can be one of three outcomes:
459 /// - `Ok(Some(r))`: success occurred with result `r`
460 /// - `Ok(None)`: could not definitely determine anything, usually due
461 /// to inconclusive type inference.
462 /// - `Err(e)`: error `e` occurred
463 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
465 /// Given the successful resolution of an obligation, the `Vtable`
466 /// indicates where the vtable comes from. Note that while we call this
467 /// a "vtable", it does not necessarily indicate dynamic dispatch at
468 /// runtime. `Vtable` instances just tell the compiler where to find
469 /// methods, but in generic code those methods are typically statically
470 /// dispatched -- only when an object is constructed is a `Vtable`
471 /// instance reified into an actual vtable.
473 /// For example, the vtable may be tied to a specific impl (case A),
474 /// or it may be relative to some bound that is in scope (case B).
478 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
479 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
480 /// impl Clone for int { ... } // Impl_3
482 /// fn foo<T:Clone>(concrete: Option<Box<int>>,
484 /// mixed: Option<T>) {
486 /// // Case A: Vtable points at a specific impl. Only possible when
487 /// // type is concretely known. If the impl itself has bounded
488 /// // type parameters, Vtable will carry resolutions for those as well:
489 /// concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
491 /// // Case B: Vtable must be provided by caller. This applies when
492 /// // type is a type parameter.
493 /// param.clone(); // VtableParam
495 /// // Case C: A mix of cases A and B.
496 /// mixed.clone(); // Vtable(Impl_1, [VtableParam])
500 /// ### The type parameter `N`
502 /// See explanation on `VtableImplData`.
503 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
504 pub enum Vtable<'tcx, N> {
505 /// Vtable identifying a particular impl.
506 VtableImpl(VtableImplData<'tcx, N>),
508 /// Vtable for auto trait implementations
509 /// This carries the information and nested obligations with regards
510 /// to an auto implementation for a trait `Trait`. The nested obligations
511 /// ensure the trait implementation holds for all the constituent types.
512 VtableAutoImpl(VtableAutoImplData<N>),
514 /// Successful resolution to an obligation provided by the caller
515 /// for some type parameter. The `Vec<N>` represents the
516 /// obligations incurred from normalizing the where-clause (if
520 /// Virtual calls through an object
521 VtableObject(VtableObjectData<'tcx, N>),
523 /// Successful resolution for a builtin trait.
524 VtableBuiltin(VtableBuiltinData<N>),
526 /// Vtable automatically generated for a closure. The def ID is the ID
527 /// of the closure expression. This is a `VtableImpl` in spirit, but the
528 /// impl is generated by the compiler and does not appear in the source.
529 VtableClosure(VtableClosureData<'tcx, N>),
531 /// Same as above, but for a fn pointer type with the given signature.
532 VtableFnPointer(VtableFnPointerData<'tcx, N>),
534 /// Vtable automatically generated for a generator.
535 VtableGenerator(VtableGeneratorData<'tcx, N>),
537 /// Vtable for a trait alias.
538 VtableTraitAlias(VtableTraitAliasData<'tcx, N>),
541 /// Identifies a particular impl in the source, along with a set of
542 /// substitutions from the impl's type/lifetime parameters. The
543 /// `nested` vector corresponds to the nested obligations attached to
544 /// the impl's type parameters.
546 /// The type parameter `N` indicates the type used for "nested
547 /// obligations" that are required by the impl. During type check, this
548 /// is `Obligation`, as one might expect. During codegen, however, this
549 /// is `()`, because codegen only requires a shallow resolution of an
550 /// impl, and nested obligations are satisfied later.
551 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
552 pub struct VtableImplData<'tcx, N> {
553 pub impl_def_id: DefId,
554 pub substs: &'tcx Substs<'tcx>,
558 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
559 pub struct VtableGeneratorData<'tcx, N> {
560 pub generator_def_id: DefId,
561 pub substs: ty::GeneratorSubsts<'tcx>,
562 /// Nested obligations. This can be non-empty if the generator
563 /// signature contains associated types.
567 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
568 pub struct VtableClosureData<'tcx, N> {
569 pub closure_def_id: DefId,
570 pub substs: ty::ClosureSubsts<'tcx>,
571 /// Nested obligations. This can be non-empty if the closure
572 /// signature contains associated types.
576 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
577 pub struct VtableAutoImplData<N> {
578 pub trait_def_id: DefId,
582 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
583 pub struct VtableBuiltinData<N> {
587 /// A vtable for some object-safe trait `Foo` automatically derived
588 /// for the object type `Foo`.
589 #[derive(PartialEq, Eq, Clone, RustcEncodable, RustcDecodable)]
590 pub struct VtableObjectData<'tcx, N> {
591 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
592 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
594 /// The vtable is formed by concatenating together the method lists of
595 /// the base object trait and all supertraits; this is the start of
596 /// `upcast_trait_ref`'s methods in that vtable.
597 pub vtable_base: usize,
602 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
603 pub struct VtableFnPointerData<'tcx, N> {
608 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
609 pub struct VtableTraitAliasData<'tcx, N> {
610 pub alias_def_id: DefId,
611 pub substs: &'tcx Substs<'tcx>,
615 /// Creates predicate obligations from the generic bounds.
616 pub fn predicates_for_generics<'tcx>(cause: ObligationCause<'tcx>,
617 param_env: ty::ParamEnv<'tcx>,
618 generic_bounds: &ty::InstantiatedPredicates<'tcx>)
619 -> PredicateObligations<'tcx>
621 util::predicates_for_generics(cause, 0, param_env, generic_bounds)
624 /// Determines whether the type `ty` is known to meet `bound` and
625 /// returns true if so. Returns false if `ty` either does not meet
626 /// `bound` or is not known to meet bound (note that this is
627 /// conservative towards *no impl*, which is the opposite of the
628 /// `evaluate` methods).
629 pub fn type_known_to_meet_bound<'a, 'gcx, 'tcx>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
630 param_env: ty::ParamEnv<'tcx>,
636 debug!("type_known_to_meet_bound(ty={:?}, bound={:?})",
638 infcx.tcx.item_path_str(def_id));
640 let trait_ref = ty::TraitRef {
642 substs: infcx.tcx.mk_substs_trait(ty, &[]),
644 let obligation = Obligation {
646 cause: ObligationCause::misc(span, ast::DUMMY_NODE_ID),
648 predicate: trait_ref.to_predicate(),
651 let result = infcx.predicate_must_hold(&obligation);
652 debug!("type_known_to_meet_ty={:?} bound={} => {:?}",
653 ty, infcx.tcx.item_path_str(def_id), result);
655 if result && (ty.has_infer_types() || ty.has_closure_types()) {
656 // Because of inference "guessing", selection can sometimes claim
657 // to succeed while the success requires a guess. To ensure
658 // this function's result remains infallible, we must confirm
659 // that guess. While imperfect, I believe this is sound.
661 // The handling of regions in this area of the code is terrible,
662 // see issue #29149. We should be able to improve on this with
664 let mut fulfill_cx = FulfillmentContext::new_ignoring_regions();
666 // We can use a dummy node-id here because we won't pay any mind
667 // to region obligations that arise (there shouldn't really be any
669 let cause = ObligationCause::misc(span, ast::DUMMY_NODE_ID);
671 fulfill_cx.register_bound(infcx, param_env, ty, def_id, cause);
673 // Note: we only assume something is `Copy` if we can
674 // *definitively* show that it implements `Copy`. Otherwise,
675 // assume it is move; linear is always ok.
676 match fulfill_cx.select_all_or_error(infcx) {
678 debug!("type_known_to_meet_bound: ty={:?} bound={} success",
680 infcx.tcx.item_path_str(def_id));
684 debug!("type_known_to_meet_bound: ty={:?} bound={} errors={:?}",
686 infcx.tcx.item_path_str(def_id),
696 fn do_normalize_predicates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
697 region_context: DefId,
698 cause: ObligationCause<'tcx>,
699 elaborated_env: ty::ParamEnv<'tcx>,
700 predicates: Vec<ty::Predicate<'tcx>>)
701 -> Result<Vec<ty::Predicate<'tcx>>, ErrorReported>
704 "do_normalize_predicates(predicates={:?}, region_context={:?}, cause={:?})",
709 let span = cause.span;
710 tcx.infer_ctxt().enter(|infcx| {
711 // FIXME. We should really... do something with these region
712 // obligations. But this call just continues the older
713 // behavior (i.e., doesn't cause any new bugs), and it would
714 // take some further refactoring to actually solve them. In
715 // particular, we would have to handle implied bounds
716 // properly, and that code is currently largely confined to
717 // regionck (though I made some efforts to extract it
720 // @arielby: In any case, these obligations are checked
721 // by wfcheck anyway, so I'm not sure we have to check
722 // them here too, and we will remove this function when
723 // we move over to lazy normalization *anyway*.
724 let fulfill_cx = FulfillmentContext::new_ignoring_regions();
725 let predicates = match fully_normalize(
732 Ok(predicates) => predicates,
734 infcx.report_fulfillment_errors(&errors, None, false);
735 return Err(ErrorReported)
739 debug!("do_normalize_predictes: normalized predicates = {:?}", predicates);
741 let region_scope_tree = region::ScopeTree::default();
743 // We can use the `elaborated_env` here; the region code only
744 // cares about declarations like `'a: 'b`.
745 let outlives_env = OutlivesEnvironment::new(elaborated_env);
747 infcx.resolve_regions_and_report_errors(
751 SuppressRegionErrors::default(),
754 let predicates = match infcx.fully_resolve(&predicates) {
755 Ok(predicates) => predicates,
757 // If we encounter a fixup error, it means that some type
758 // variable wound up unconstrained. I actually don't know
759 // if this can happen, and I certainly don't expect it to
760 // happen often, but if it did happen it probably
761 // represents a legitimate failure due to some kind of
762 // unconstrained variable, and it seems better not to ICE,
763 // all things considered.
764 tcx.sess.span_err(span, &fixup_err.to_string());
765 return Err(ErrorReported)
769 match tcx.lift_to_global(&predicates) {
770 Some(predicates) => Ok(predicates),
772 // FIXME: shouldn't we, you know, actually report an error here? or an ICE?
779 // FIXME: this is gonna need to be removed ...
780 /// Normalizes the parameter environment, reporting errors if they occur.
781 pub fn normalize_param_env_or_error<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
782 region_context: DefId,
783 unnormalized_env: ty::ParamEnv<'tcx>,
784 cause: ObligationCause<'tcx>)
785 -> ty::ParamEnv<'tcx>
787 // I'm not wild about reporting errors here; I'd prefer to
788 // have the errors get reported at a defined place (e.g.,
789 // during typeck). Instead I have all parameter
790 // environments, in effect, going through this function
791 // and hence potentially reporting errors. This ensures of
792 // course that we never forget to normalize (the
793 // alternative seemed like it would involve a lot of
794 // manual invocations of this fn -- and then we'd have to
795 // deal with the errors at each of those sites).
797 // In any case, in practice, typeck constructs all the
798 // parameter environments once for every fn as it goes,
799 // and errors will get reported then; so after typeck we
800 // can be sure that no errors should occur.
802 debug!("normalize_param_env_or_error(region_context={:?}, unnormalized_env={:?}, cause={:?})",
803 region_context, unnormalized_env, cause);
805 let mut predicates: Vec<_> =
806 util::elaborate_predicates(tcx, unnormalized_env.caller_bounds.to_vec())
809 debug!("normalize_param_env_or_error: elaborated-predicates={:?}",
812 let elaborated_env = ty::ParamEnv::new(tcx.intern_predicates(&predicates),
813 unnormalized_env.reveal);
815 // HACK: we are trying to normalize the param-env inside *itself*. The problem is that
816 // normalization expects its param-env to be already normalized, which means we have
819 // The way we handle this is by normalizing the param-env inside an unnormalized version
820 // of the param-env, which means that if the param-env contains unnormalized projections,
821 // we'll have some normalization failures. This is unfortunate.
823 // Lazy normalization would basically handle this by treating just the
824 // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
826 // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
827 // types, so to make the situation less bad, we normalize all the predicates *but*
828 // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
829 // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
831 // This works fairly well because trait matching does not actually care about param-env
832 // TypeOutlives predicates - these are normally used by regionck.
833 let outlives_predicates: Vec<_> = predicates.drain_filter(|predicate| {
835 ty::Predicate::TypeOutlives(..) => true,
840 debug!("normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
841 predicates, outlives_predicates);
842 let non_outlives_predicates =
843 match do_normalize_predicates(tcx, region_context, cause.clone(),
844 elaborated_env, predicates) {
845 Ok(predicates) => predicates,
846 // An unnormalized env is better than nothing.
847 Err(ErrorReported) => {
848 debug!("normalize_param_env_or_error: errored resolving non-outlives predicates");
849 return elaborated_env
853 debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates);
855 // Not sure whether it is better to include the unnormalized TypeOutlives predicates
856 // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
857 // predicates here anyway. Keeping them here anyway because it seems safer.
858 let outlives_env: Vec<_> =
859 non_outlives_predicates.iter().chain(&outlives_predicates).cloned().collect();
860 let outlives_env = ty::ParamEnv::new(tcx.intern_predicates(&outlives_env),
861 unnormalized_env.reveal);
862 let outlives_predicates =
863 match do_normalize_predicates(tcx, region_context, cause,
864 outlives_env, outlives_predicates) {
865 Ok(predicates) => predicates,
866 // An unnormalized env is better than nothing.
867 Err(ErrorReported) => {
868 debug!("normalize_param_env_or_error: errored resolving outlives predicates");
869 return elaborated_env
872 debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates);
874 let mut predicates = non_outlives_predicates;
875 predicates.extend(outlives_predicates);
876 debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
877 ty::ParamEnv::new(tcx.intern_predicates(&predicates), unnormalized_env.reveal)
880 pub fn fully_normalize<'a, 'gcx, 'tcx, T>(
881 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
882 mut fulfill_cx: FulfillmentContext<'tcx>,
883 cause: ObligationCause<'tcx>,
884 param_env: ty::ParamEnv<'tcx>,
886 -> Result<T, Vec<FulfillmentError<'tcx>>>
887 where T : TypeFoldable<'tcx>
889 debug!("fully_normalize_with_fulfillcx(value={:?})", value);
890 let selcx = &mut SelectionContext::new(infcx);
891 let Normalized { value: normalized_value, obligations } =
892 project::normalize(selcx, param_env, cause, value);
893 debug!("fully_normalize: normalized_value={:?} obligations={:?}",
896 for obligation in obligations {
897 fulfill_cx.register_predicate_obligation(selcx.infcx(), obligation);
900 debug!("fully_normalize: select_all_or_error start");
901 fulfill_cx.select_all_or_error(infcx)?;
902 debug!("fully_normalize: select_all_or_error complete");
903 let resolved_value = infcx.resolve_type_vars_if_possible(&normalized_value);
904 debug!("fully_normalize: resolved_value={:?}", resolved_value);
908 /// Normalizes the predicates and checks whether they hold in an empty
909 /// environment. If this returns false, then either normalize
910 /// encountered an error or one of the predicates did not hold. Used
911 /// when creating vtables to check for unsatisfiable methods.
912 fn normalize_and_test_predicates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
913 predicates: Vec<ty::Predicate<'tcx>>)
916 debug!("normalize_and_test_predicates(predicates={:?})",
919 let result = tcx.infer_ctxt().enter(|infcx| {
920 let param_env = ty::ParamEnv::reveal_all();
921 let mut selcx = SelectionContext::new(&infcx);
922 let mut fulfill_cx = FulfillmentContext::new();
923 let cause = ObligationCause::dummy();
924 let Normalized { value: predicates, obligations } =
925 normalize(&mut selcx, param_env, cause.clone(), &predicates);
926 for obligation in obligations {
927 fulfill_cx.register_predicate_obligation(&infcx, obligation);
929 for predicate in predicates {
930 let obligation = Obligation::new(cause.clone(), param_env, predicate);
931 fulfill_cx.register_predicate_obligation(&infcx, obligation);
934 fulfill_cx.select_all_or_error(&infcx).is_ok()
936 debug!("normalize_and_test_predicates(predicates={:?}) = {:?}",
941 fn substitute_normalize_and_test_predicates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
942 key: (DefId, &'tcx Substs<'tcx>))
945 debug!("substitute_normalize_and_test_predicates(key={:?})",
948 let predicates = tcx.predicates_of(key.0).instantiate(tcx, key.1).predicates;
949 let result = normalize_and_test_predicates(tcx, predicates);
951 debug!("substitute_normalize_and_test_predicates(key={:?}) = {:?}",
956 /// Given a trait `trait_ref`, iterates the vtable entries
957 /// that come from `trait_ref`, including its supertraits.
958 #[inline] // FIXME(#35870): avoid closures being unexported due to `impl Trait`.
959 fn vtable_methods<'a, 'tcx>(
960 tcx: TyCtxt<'a, 'tcx, 'tcx>,
961 trait_ref: ty::PolyTraitRef<'tcx>)
962 -> Lrc<Vec<Option<(DefId, &'tcx Substs<'tcx>)>>>
964 debug!("vtable_methods({:?})", trait_ref);
967 supertraits(tcx, trait_ref).flat_map(move |trait_ref| {
968 let trait_methods = tcx.associated_items(trait_ref.def_id())
969 .filter(|item| item.kind == ty::AssociatedKind::Method);
971 // Now list each method's DefId and Substs (for within its trait).
972 // If the method can never be called from this object, produce None.
973 trait_methods.map(move |trait_method| {
974 debug!("vtable_methods: trait_method={:?}", trait_method);
975 let def_id = trait_method.def_id;
977 // Some methods cannot be called on an object; skip those.
978 if !tcx.is_vtable_safe_method(trait_ref.def_id(), &trait_method) {
979 debug!("vtable_methods: not vtable safe");
983 // the method may have some early-bound lifetimes, add
985 let substs = trait_ref.map_bound(|trait_ref|
986 Substs::for_item(tcx, def_id, |param, _|
988 GenericParamDefKind::Lifetime => tcx.types.re_erased.into(),
989 GenericParamDefKind::Type {..} => {
990 trait_ref.substs[param.index as usize]
996 // the trait type may have higher-ranked lifetimes in it;
997 // so erase them if they appear, so that we get the type
998 // at some particular call site
999 let substs = tcx.normalize_erasing_late_bound_regions(
1000 ty::ParamEnv::reveal_all(),
1004 // It's possible that the method relies on where clauses that
1005 // do not hold for this particular set of type parameters.
1006 // Note that this method could then never be called, so we
1007 // do not want to try and codegen it, in that case (see #23435).
1008 let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs);
1009 if !normalize_and_test_predicates(tcx, predicates.predicates) {
1010 debug!("vtable_methods: predicates do not hold");
1014 Some((def_id, substs))
1020 impl<'tcx,O> Obligation<'tcx,O> {
1021 pub fn new(cause: ObligationCause<'tcx>,
1022 param_env: ty::ParamEnv<'tcx>,
1024 -> Obligation<'tcx, O>
1026 Obligation { cause, param_env, recursion_depth: 0, predicate }
1029 fn with_depth(cause: ObligationCause<'tcx>,
1030 recursion_depth: usize,
1031 param_env: ty::ParamEnv<'tcx>,
1033 -> Obligation<'tcx, O>
1035 Obligation { cause, param_env, recursion_depth, predicate }
1038 pub fn misc(span: Span,
1039 body_id: ast::NodeId,
1040 param_env: ty::ParamEnv<'tcx>,
1042 -> Obligation<'tcx, O> {
1043 Obligation::new(ObligationCause::misc(span, body_id), param_env, trait_ref)
1046 pub fn with<P>(&self, value: P) -> Obligation<'tcx,P> {
1047 Obligation { cause: self.cause.clone(),
1048 param_env: self.param_env,
1049 recursion_depth: self.recursion_depth,
1054 impl<'tcx> ObligationCause<'tcx> {
1056 pub fn new(span: Span,
1057 body_id: ast::NodeId,
1058 code: ObligationCauseCode<'tcx>)
1059 -> ObligationCause<'tcx> {
1060 ObligationCause { span: span, body_id: body_id, code: code }
1063 pub fn misc(span: Span, body_id: ast::NodeId) -> ObligationCause<'tcx> {
1064 ObligationCause { span: span, body_id: body_id, code: MiscObligation }
1067 pub fn dummy() -> ObligationCause<'tcx> {
1068 ObligationCause { span: DUMMY_SP, body_id: ast::CRATE_NODE_ID, code: MiscObligation }
1072 impl<'tcx, N> Vtable<'tcx, N> {
1073 pub fn nested_obligations(self) -> Vec<N> {
1075 VtableImpl(i) => i.nested,
1076 VtableParam(n) => n,
1077 VtableBuiltin(i) => i.nested,
1078 VtableAutoImpl(d) => d.nested,
1079 VtableClosure(c) => c.nested,
1080 VtableGenerator(c) => c.nested,
1081 VtableObject(d) => d.nested,
1082 VtableFnPointer(d) => d.nested,
1083 VtableTraitAlias(d) => d.nested,
1087 pub fn map<M, F>(self, f: F) -> Vtable<'tcx, M> where F: FnMut(N) -> M {
1089 VtableImpl(i) => VtableImpl(VtableImplData {
1090 impl_def_id: i.impl_def_id,
1092 nested: i.nested.into_iter().map(f).collect(),
1094 VtableParam(n) => VtableParam(n.into_iter().map(f).collect()),
1095 VtableBuiltin(i) => VtableBuiltin(VtableBuiltinData {
1096 nested: i.nested.into_iter().map(f).collect(),
1098 VtableObject(o) => VtableObject(VtableObjectData {
1099 upcast_trait_ref: o.upcast_trait_ref,
1100 vtable_base: o.vtable_base,
1101 nested: o.nested.into_iter().map(f).collect(),
1103 VtableAutoImpl(d) => VtableAutoImpl(VtableAutoImplData {
1104 trait_def_id: d.trait_def_id,
1105 nested: d.nested.into_iter().map(f).collect(),
1107 VtableClosure(c) => VtableClosure(VtableClosureData {
1108 closure_def_id: c.closure_def_id,
1110 nested: c.nested.into_iter().map(f).collect(),
1112 VtableGenerator(c) => VtableGenerator(VtableGeneratorData {
1113 generator_def_id: c.generator_def_id,
1115 nested: c.nested.into_iter().map(f).collect(),
1117 VtableFnPointer(p) => VtableFnPointer(VtableFnPointerData {
1119 nested: p.nested.into_iter().map(f).collect(),
1121 VtableTraitAlias(d) => VtableTraitAlias(VtableTraitAliasData {
1122 alias_def_id: d.alias_def_id,
1124 nested: d.nested.into_iter().map(f).collect(),
1130 impl<'tcx> FulfillmentError<'tcx> {
1131 fn new(obligation: PredicateObligation<'tcx>,
1132 code: FulfillmentErrorCode<'tcx>)
1133 -> FulfillmentError<'tcx>
1135 FulfillmentError { obligation: obligation, code: code }
1139 impl<'tcx> TraitObligation<'tcx> {
1140 fn self_ty(&self) -> ty::Binder<Ty<'tcx>> {
1141 self.predicate.map_bound(|p| p.self_ty())
1145 pub fn provide(providers: &mut ty::query::Providers<'_>) {
1146 *providers = ty::query::Providers {
1147 is_object_safe: object_safety::is_object_safe_provider,
1148 specialization_graph_of: specialize::specialization_graph_provider,
1149 specializes: specialize::specializes,
1150 codegen_fulfill_obligation: codegen::codegen_fulfill_obligation,
1152 substitute_normalize_and_test_predicates,
1157 pub trait ExClauseFold<'tcx>
1159 Self: chalk_engine::context::Context + Clone,
1161 fn fold_ex_clause_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(
1162 ex_clause: &chalk_engine::ExClause<Self>,
1164 ) -> chalk_engine::ExClause<Self>;
1166 fn visit_ex_clause_with<'gcx: 'tcx, V: TypeVisitor<'tcx>>(
1167 ex_clause: &chalk_engine::ExClause<Self>,
1172 pub trait ExClauseLift<'tcx>
1174 Self: chalk_engine::context::Context + Clone,
1176 type LiftedExClause: Debug + 'tcx;
1178 fn lift_ex_clause_to_tcx<'a, 'gcx>(
1179 ex_clause: &chalk_engine::ExClause<Self>,
1180 tcx: TyCtxt<'a, 'gcx, 'tcx>,
1181 ) -> Option<Self::LiftedExClause>;