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 [rustc guide] for more info on how this works.
13 //! [rustc guide]: https://rust-lang-nursery.github.io/rustc-guide/traits/resolution.html
15 pub use self::SelectionError::*;
16 pub use self::FulfillmentErrorCode::*;
17 pub use self::Vtable::*;
18 pub use self::ObligationCauseCode::*;
22 use hir::def_id::DefId;
23 use infer::SuppressRegionErrors;
24 use infer::outlives::env::OutlivesEnvironment;
26 use ty::subst::Substs;
27 use ty::{self, AdtKind, List, Ty, TyCtxt, GenericParamDefKind, ToPredicate};
28 use ty::error::{ExpectedFound, TypeError};
29 use ty::fold::{TypeFolder, TypeFoldable, TypeVisitor};
30 use infer::{InferCtxt};
31 use util::common::ErrorReported;
33 use rustc_data_structures::sync::Lrc;
37 use syntax_pos::{Span, DUMMY_SP};
39 pub use self::coherence::{orphan_check, overlapping_impls, OrphanCheckErr, OverlapResult};
40 pub use self::fulfill::{FulfillmentContext, PendingPredicateObligation};
41 pub use self::project::MismatchedProjectionTypes;
42 pub use self::project::{normalize, normalize_projection_type, poly_project_and_unify_type};
43 pub use self::project::{ProjectionCache, ProjectionCacheSnapshot, Reveal, Normalized};
44 pub use self::object_safety::ObjectSafetyViolation;
45 pub use self::object_safety::MethodViolationCode;
46 pub use self::on_unimplemented::{OnUnimplementedDirective, OnUnimplementedNote};
47 pub use self::select::{EvaluationCache, SelectionContext, SelectionCache};
48 pub use self::select::{EvaluationResult, IntercrateAmbiguityCause, OverflowError};
49 pub use self::specialize::{OverlapError, specialization_graph, translate_substs};
50 pub use self::specialize::find_associated_item;
51 pub use self::engine::{TraitEngine, TraitEngineExt};
52 pub use self::util::elaborate_predicates;
53 pub use self::util::supertraits;
54 pub use self::util::Supertraits;
55 pub use self::util::supertrait_def_ids;
56 pub use self::util::SupertraitDefIds;
57 pub use self::util::transitive_bounds;
62 pub mod error_reporting;
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
223 MatchExpressionArm { arm_span: Span,
224 source: hir::MatchSource },
226 /// Computing common supertype in an if expression
229 /// Computing common supertype of an if expression with no else counter-part
230 IfExpressionWithNoElse,
232 /// `main` has wrong type
235 /// `start` has wrong type
238 /// intrinsic has wrong type
244 /// `return` with no expression
247 /// `return` with an expression
248 ReturnType(ast::NodeId),
250 /// Block implicit return
251 BlockTailExpression(ast::NodeId),
253 /// #[feature(trivial_bounds)] is not enabled
257 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
258 pub struct DerivedObligationCause<'tcx> {
259 /// The trait reference of the parent obligation that led to the
260 /// current obligation. Note that only trait obligations lead to
261 /// derived obligations, so we just store the trait reference here
263 parent_trait_ref: ty::PolyTraitRef<'tcx>,
265 /// The parent trait had this cause
266 parent_code: Rc<ObligationCauseCode<'tcx>>
269 pub type Obligations<'tcx, O> = Vec<Obligation<'tcx, O>>;
270 pub type PredicateObligations<'tcx> = Vec<PredicateObligation<'tcx>>;
271 pub type TraitObligations<'tcx> = Vec<TraitObligation<'tcx>>;
273 /// The following types:
281 /// * `InEnvironment`
282 /// are used for representing the trait system in the form of
283 /// logic programming clauses. They are part of the interface
284 /// for the chalk SLG solver.
285 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
286 pub enum WhereClause<'tcx> {
287 Implemented(ty::TraitPredicate<'tcx>),
288 ProjectionEq(ty::ProjectionPredicate<'tcx>),
289 RegionOutlives(ty::RegionOutlivesPredicate<'tcx>),
290 TypeOutlives(ty::TypeOutlivesPredicate<'tcx>),
293 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
294 pub enum WellFormed<'tcx> {
295 Trait(ty::TraitPredicate<'tcx>),
299 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
300 pub enum FromEnv<'tcx> {
301 Trait(ty::TraitPredicate<'tcx>),
305 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
306 pub enum DomainGoal<'tcx> {
307 Holds(WhereClause<'tcx>),
308 WellFormed(WellFormed<'tcx>),
309 FromEnv(FromEnv<'tcx>),
310 Normalize(ty::ProjectionPredicate<'tcx>),
313 pub type PolyDomainGoal<'tcx> = ty::Binder<DomainGoal<'tcx>>;
315 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
316 pub enum QuantifierKind {
321 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
322 pub enum GoalKind<'tcx> {
323 Implies(Clauses<'tcx>, Goal<'tcx>),
324 And(Goal<'tcx>, Goal<'tcx>),
326 DomainGoal(DomainGoal<'tcx>),
327 Quantified(QuantifierKind, ty::Binder<Goal<'tcx>>),
331 pub type Goal<'tcx> = &'tcx GoalKind<'tcx>;
333 pub type Goals<'tcx> = &'tcx List<Goal<'tcx>>;
335 impl<'tcx> DomainGoal<'tcx> {
336 pub fn into_goal(self) -> GoalKind<'tcx> {
337 GoalKind::DomainGoal(self)
340 pub fn into_program_clause(self) -> ProgramClause<'tcx> {
343 hypotheses: ty::List::empty(),
344 category: ProgramClauseCategory::Other,
349 impl<'tcx> GoalKind<'tcx> {
350 pub fn from_poly_domain_goal<'a>(
351 domain_goal: PolyDomainGoal<'tcx>,
352 tcx: TyCtxt<'a, 'tcx, 'tcx>,
353 ) -> GoalKind<'tcx> {
354 match domain_goal.no_late_bound_regions() {
355 Some(p) => p.into_goal(),
356 None => GoalKind::Quantified(
357 QuantifierKind::Universal,
358 domain_goal.map_bound(|p| tcx.mk_goal(p.into_goal()))
364 /// This matches the definition from Page 7 of "A Proof Procedure for the Logic of Hereditary
365 /// Harrop Formulas".
366 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
367 pub enum Clause<'tcx> {
368 Implies(ProgramClause<'tcx>),
369 ForAll(ty::Binder<ProgramClause<'tcx>>),
373 pub fn category(self) -> ProgramClauseCategory {
375 Clause::Implies(clause) => clause.category,
376 Clause::ForAll(clause) => clause.skip_binder().category,
381 /// Multiple clauses.
382 pub type Clauses<'tcx> = &'tcx List<Clause<'tcx>>;
384 /// A "program clause" has the form `D :- G1, ..., Gn`. It is saying
385 /// that the domain goal `D` is true if `G1...Gn` are provable. This
386 /// is equivalent to the implication `G1..Gn => D`; we usually write
387 /// it with the reverse implication operator `:-` to emphasize the way
388 /// that programs are actually solved (via backchaining, which starts
389 /// with the goal to solve and proceeds from there).
390 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
391 pub struct ProgramClause<'tcx> {
392 /// This goal will be considered true...
393 pub goal: DomainGoal<'tcx>,
395 /// ...if we can prove these hypotheses (there may be no hypotheses at all):
396 pub hypotheses: Goals<'tcx>,
398 /// Useful for filtering clauses.
399 pub category: ProgramClauseCategory,
402 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
403 pub enum ProgramClauseCategory {
409 /// A set of clauses that we assume to be true.
410 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
411 pub struct Environment<'tcx> {
412 pub clauses: Clauses<'tcx>,
415 impl Environment<'tcx> {
416 pub fn with<G>(self, goal: G) -> InEnvironment<'tcx, G> {
424 /// Something (usually a goal), along with an environment.
425 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
426 pub struct InEnvironment<'tcx, G> {
427 pub environment: Environment<'tcx>,
431 pub type Selection<'tcx> = Vtable<'tcx, PredicateObligation<'tcx>>;
433 #[derive(Clone,Debug)]
434 pub enum SelectionError<'tcx> {
436 OutputTypeParameterMismatch(ty::PolyTraitRef<'tcx>,
437 ty::PolyTraitRef<'tcx>,
438 ty::error::TypeError<'tcx>),
439 TraitNotObjectSafe(DefId),
444 pub struct FulfillmentError<'tcx> {
445 pub obligation: PredicateObligation<'tcx>,
446 pub code: FulfillmentErrorCode<'tcx>
450 pub enum FulfillmentErrorCode<'tcx> {
451 CodeSelectionError(SelectionError<'tcx>),
452 CodeProjectionError(MismatchedProjectionTypes<'tcx>),
453 CodeSubtypeError(ExpectedFound<Ty<'tcx>>,
454 TypeError<'tcx>), // always comes from a SubtypePredicate
458 /// When performing resolution, it is typically the case that there
459 /// can be one of three outcomes:
461 /// - `Ok(Some(r))`: success occurred with result `r`
462 /// - `Ok(None)`: could not definitely determine anything, usually due
463 /// to inconclusive type inference.
464 /// - `Err(e)`: error `e` occurred
465 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
467 /// Given the successful resolution of an obligation, the `Vtable`
468 /// indicates where the vtable comes from. Note that while we call this
469 /// a "vtable", it does not necessarily indicate dynamic dispatch at
470 /// runtime. `Vtable` instances just tell the compiler where to find
471 /// methods, but in generic code those methods are typically statically
472 /// dispatched -- only when an object is constructed is a `Vtable`
473 /// instance reified into an actual vtable.
475 /// For example, the vtable may be tied to a specific impl (case A),
476 /// or it may be relative to some bound that is in scope (case B).
480 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
481 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
482 /// impl Clone for int { ... } // Impl_3
484 /// fn foo<T:Clone>(concrete: Option<Box<int>>,
486 /// mixed: Option<T>) {
488 /// // Case A: Vtable points at a specific impl. Only possible when
489 /// // type is concretely known. If the impl itself has bounded
490 /// // type parameters, Vtable will carry resolutions for those as well:
491 /// concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
493 /// // Case B: Vtable must be provided by caller. This applies when
494 /// // type is a type parameter.
495 /// param.clone(); // VtableParam
497 /// // Case C: A mix of cases A and B.
498 /// mixed.clone(); // Vtable(Impl_1, [VtableParam])
502 /// ### The type parameter `N`
504 /// See explanation on `VtableImplData`.
505 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
506 pub enum Vtable<'tcx, N> {
507 /// Vtable identifying a particular impl.
508 VtableImpl(VtableImplData<'tcx, N>),
510 /// Vtable for auto trait implementations
511 /// This carries the information and nested obligations with regards
512 /// to an auto implementation for a trait `Trait`. The nested obligations
513 /// ensure the trait implementation holds for all the constituent types.
514 VtableAutoImpl(VtableAutoImplData<N>),
516 /// Successful resolution to an obligation provided by the caller
517 /// for some type parameter. The `Vec<N>` represents the
518 /// obligations incurred from normalizing the where-clause (if
522 /// Virtual calls through an object
523 VtableObject(VtableObjectData<'tcx, N>),
525 /// Successful resolution for a builtin trait.
526 VtableBuiltin(VtableBuiltinData<N>),
528 /// Vtable automatically generated for a closure. The def ID is the ID
529 /// of the closure expression. This is a `VtableImpl` in spirit, but the
530 /// impl is generated by the compiler and does not appear in the source.
531 VtableClosure(VtableClosureData<'tcx, N>),
533 /// Same as above, but for a fn pointer type with the given signature.
534 VtableFnPointer(VtableFnPointerData<'tcx, N>),
536 /// Vtable automatically generated for a generator
537 VtableGenerator(VtableGeneratorData<'tcx, N>),
540 /// Identifies a particular impl in the source, along with a set of
541 /// substitutions from the impl's type/lifetime parameters. The
542 /// `nested` vector corresponds to the nested obligations attached to
543 /// the impl's type parameters.
545 /// The type parameter `N` indicates the type used for "nested
546 /// obligations" that are required by the impl. During type check, this
547 /// is `Obligation`, as one might expect. During codegen, however, this
548 /// is `()`, because codegen only requires a shallow resolution of an
549 /// impl, and nested obligations are satisfied later.
550 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
551 pub struct VtableImplData<'tcx, N> {
552 pub impl_def_id: DefId,
553 pub substs: &'tcx Substs<'tcx>,
557 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
558 pub struct VtableGeneratorData<'tcx, N> {
559 pub generator_def_id: DefId,
560 pub substs: ty::GeneratorSubsts<'tcx>,
561 /// Nested obligations. This can be non-empty if the generator
562 /// signature contains associated types.
566 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
567 pub struct VtableClosureData<'tcx, N> {
568 pub closure_def_id: DefId,
569 pub substs: ty::ClosureSubsts<'tcx>,
570 /// Nested obligations. This can be non-empty if the closure
571 /// signature contains associated types.
575 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
576 pub struct VtableAutoImplData<N> {
577 pub trait_def_id: DefId,
581 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
582 pub struct VtableBuiltinData<N> {
586 /// A vtable for some object-safe trait `Foo` automatically derived
587 /// for the object type `Foo`.
588 #[derive(PartialEq, Eq, Clone, RustcEncodable, RustcDecodable)]
589 pub struct VtableObjectData<'tcx, N> {
590 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
591 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
593 /// The vtable is formed by concatenating together the method lists of
594 /// the base object trait and all supertraits; this is the start of
595 /// `upcast_trait_ref`'s methods in that vtable.
596 pub vtable_base: usize,
601 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
602 pub struct VtableFnPointerData<'tcx, N> {
607 /// Creates predicate obligations from the generic bounds.
608 pub fn predicates_for_generics<'tcx>(cause: ObligationCause<'tcx>,
609 param_env: ty::ParamEnv<'tcx>,
610 generic_bounds: &ty::InstantiatedPredicates<'tcx>)
611 -> PredicateObligations<'tcx>
613 util::predicates_for_generics(cause, 0, param_env, generic_bounds)
616 /// Determines whether the type `ty` is known to meet `bound` and
617 /// returns true if so. Returns false if `ty` either does not meet
618 /// `bound` or is not known to meet bound (note that this is
619 /// conservative towards *no impl*, which is the opposite of the
620 /// `evaluate` methods).
621 pub fn type_known_to_meet_bound<'a, 'gcx, 'tcx>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
622 param_env: ty::ParamEnv<'tcx>,
628 debug!("type_known_to_meet_bound(ty={:?}, bound={:?})",
630 infcx.tcx.item_path_str(def_id));
632 let trait_ref = ty::TraitRef {
634 substs: infcx.tcx.mk_substs_trait(ty, &[]),
636 let obligation = Obligation {
638 cause: ObligationCause::misc(span, ast::DUMMY_NODE_ID),
640 predicate: trait_ref.to_predicate(),
643 let result = infcx.predicate_must_hold(&obligation);
644 debug!("type_known_to_meet_ty={:?} bound={} => {:?}",
645 ty, infcx.tcx.item_path_str(def_id), result);
647 if result && (ty.has_infer_types() || ty.has_closure_types()) {
648 // Because of inference "guessing", selection can sometimes claim
649 // to succeed while the success requires a guess. To ensure
650 // this function's result remains infallible, we must confirm
651 // that guess. While imperfect, I believe this is sound.
653 // The handling of regions in this area of the code is terrible,
654 // see issue #29149. We should be able to improve on this with
656 let mut fulfill_cx = FulfillmentContext::new_ignoring_regions();
658 // We can use a dummy node-id here because we won't pay any mind
659 // to region obligations that arise (there shouldn't really be any
661 let cause = ObligationCause::misc(span, ast::DUMMY_NODE_ID);
663 fulfill_cx.register_bound(infcx, param_env, ty, def_id, cause);
665 // Note: we only assume something is `Copy` if we can
666 // *definitively* show that it implements `Copy`. Otherwise,
667 // assume it is move; linear is always ok.
668 match fulfill_cx.select_all_or_error(infcx) {
670 debug!("type_known_to_meet_bound: ty={:?} bound={} success",
672 infcx.tcx.item_path_str(def_id));
676 debug!("type_known_to_meet_bound: ty={:?} bound={} errors={:?}",
678 infcx.tcx.item_path_str(def_id),
688 fn do_normalize_predicates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
689 region_context: DefId,
690 cause: ObligationCause<'tcx>,
691 elaborated_env: ty::ParamEnv<'tcx>,
692 predicates: Vec<ty::Predicate<'tcx>>)
693 -> Result<Vec<ty::Predicate<'tcx>>, ErrorReported>
695 debug!("do_normalize_predicates({:?})", predicates);
696 let span = cause.span;
697 tcx.infer_ctxt().enter(|infcx| {
698 // FIXME. We should really... do something with these region
699 // obligations. But this call just continues the older
700 // behavior (i.e., doesn't cause any new bugs), and it would
701 // take some further refactoring to actually solve them. In
702 // particular, we would have to handle implied bounds
703 // properly, and that code is currently largely confined to
704 // regionck (though I made some efforts to extract it
707 // @arielby: In any case, these obligations are checked
708 // by wfcheck anyway, so I'm not sure we have to check
709 // them here too, and we will remove this function when
710 // we move over to lazy normalization *anyway*.
711 let fulfill_cx = FulfillmentContext::new_ignoring_regions();
712 let predicates = match fully_normalize(
719 Ok(predicates) => predicates,
721 infcx.report_fulfillment_errors(&errors, None, false);
722 return Err(ErrorReported)
726 debug!("do_normalize_predictes: normalized predicates = {:?}", predicates);
728 let region_scope_tree = region::ScopeTree::default();
730 // We can use the `elaborated_env` here; the region code only
731 // cares about declarations like `'a: 'b`.
732 let outlives_env = OutlivesEnvironment::new(elaborated_env);
734 infcx.resolve_regions_and_report_errors(
738 SuppressRegionErrors::default(),
741 let predicates = match infcx.fully_resolve(&predicates) {
742 Ok(predicates) => predicates,
744 // If we encounter a fixup error, it means that some type
745 // variable wound up unconstrained. I actually don't know
746 // if this can happen, and I certainly don't expect it to
747 // happen often, but if it did happen it probably
748 // represents a legitimate failure due to some kind of
749 // unconstrained variable, and it seems better not to ICE,
750 // all things considered.
751 tcx.sess.span_err(span, &fixup_err.to_string());
752 return Err(ErrorReported)
756 match tcx.lift_to_global(&predicates) {
757 Some(predicates) => Ok(predicates),
759 // FIXME: shouldn't we, you know, actually report an error here? or an ICE?
766 // FIXME: this is gonna need to be removed ...
767 /// Normalizes the parameter environment, reporting errors if they occur.
768 pub fn normalize_param_env_or_error<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
769 region_context: DefId,
770 unnormalized_env: ty::ParamEnv<'tcx>,
771 cause: ObligationCause<'tcx>)
772 -> ty::ParamEnv<'tcx>
774 // I'm not wild about reporting errors here; I'd prefer to
775 // have the errors get reported at a defined place (e.g.,
776 // during typeck). Instead I have all parameter
777 // environments, in effect, going through this function
778 // and hence potentially reporting errors. This ensures of
779 // course that we never forget to normalize (the
780 // alternative seemed like it would involve a lot of
781 // manual invocations of this fn -- and then we'd have to
782 // deal with the errors at each of those sites).
784 // In any case, in practice, typeck constructs all the
785 // parameter environments once for every fn as it goes,
786 // and errors will get reported then; so after typeck we
787 // can be sure that no errors should occur.
789 debug!("normalize_param_env_or_error(region_context={:?}, unnormalized_env={:?}, cause={:?})",
790 region_context, unnormalized_env, cause);
792 let mut predicates: Vec<_> =
793 util::elaborate_predicates(tcx, unnormalized_env.caller_bounds.to_vec())
796 debug!("normalize_param_env_or_error: elaborated-predicates={:?}",
799 let elaborated_env = ty::ParamEnv::new(tcx.intern_predicates(&predicates),
800 unnormalized_env.reveal);
802 // HACK: we are trying to normalize the param-env inside *itself*. The problem is that
803 // normalization expects its param-env to be already normalized, which means we have
806 // The way we handle this is by normalizing the param-env inside an unnormalized version
807 // of the param-env, which means that if the param-env contains unnormalized projections,
808 // we'll have some normalization failures. This is unfortunate.
810 // Lazy normalization would basically handle this by treating just the
811 // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
813 // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
814 // types, so to make the situation less bad, we normalize all the predicates *but*
815 // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
816 // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
818 // This works fairly well because trait matching does not actually care about param-env
819 // TypeOutlives predicates - these are normally used by regionck.
820 let outlives_predicates: Vec<_> = predicates.drain_filter(|predicate| {
822 ty::Predicate::TypeOutlives(..) => true,
827 debug!("normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
828 predicates, outlives_predicates);
829 let non_outlives_predicates =
830 match do_normalize_predicates(tcx, region_context, cause.clone(),
831 elaborated_env, predicates) {
832 Ok(predicates) => predicates,
833 // An unnormalized env is better than nothing.
834 Err(ErrorReported) => {
835 debug!("normalize_param_env_or_error: errored resolving non-outlives predicates");
836 return elaborated_env
840 debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates);
842 // Not sure whether it is better to include the unnormalized TypeOutlives predicates
843 // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
844 // predicates here anyway. Keeping them here anyway because it seems safer.
845 let outlives_env: Vec<_> =
846 non_outlives_predicates.iter().chain(&outlives_predicates).cloned().collect();
847 let outlives_env = ty::ParamEnv::new(tcx.intern_predicates(&outlives_env),
848 unnormalized_env.reveal);
849 let outlives_predicates =
850 match do_normalize_predicates(tcx, region_context, cause,
851 outlives_env, outlives_predicates) {
852 Ok(predicates) => predicates,
853 // An unnormalized env is better than nothing.
854 Err(ErrorReported) => {
855 debug!("normalize_param_env_or_error: errored resolving outlives predicates");
856 return elaborated_env
859 debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates);
861 let mut predicates = non_outlives_predicates;
862 predicates.extend(outlives_predicates);
863 debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
864 ty::ParamEnv::new(tcx.intern_predicates(&predicates), unnormalized_env.reveal)
867 pub fn fully_normalize<'a, 'gcx, 'tcx, T>(
868 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
869 mut fulfill_cx: FulfillmentContext<'tcx>,
870 cause: ObligationCause<'tcx>,
871 param_env: ty::ParamEnv<'tcx>,
873 -> Result<T, Vec<FulfillmentError<'tcx>>>
874 where T : TypeFoldable<'tcx>
876 debug!("fully_normalize_with_fulfillcx(value={:?})", value);
877 let selcx = &mut SelectionContext::new(infcx);
878 let Normalized { value: normalized_value, obligations } =
879 project::normalize(selcx, param_env, cause, value);
880 debug!("fully_normalize: normalized_value={:?} obligations={:?}",
883 for obligation in obligations {
884 fulfill_cx.register_predicate_obligation(selcx.infcx(), obligation);
887 debug!("fully_normalize: select_all_or_error start");
888 fulfill_cx.select_all_or_error(infcx)?;
889 debug!("fully_normalize: select_all_or_error complete");
890 let resolved_value = infcx.resolve_type_vars_if_possible(&normalized_value);
891 debug!("fully_normalize: resolved_value={:?}", resolved_value);
895 /// Normalizes the predicates and checks whether they hold in an empty
896 /// environment. If this returns false, then either normalize
897 /// encountered an error or one of the predicates did not hold. Used
898 /// when creating vtables to check for unsatisfiable methods.
899 fn normalize_and_test_predicates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
900 predicates: Vec<ty::Predicate<'tcx>>)
903 debug!("normalize_and_test_predicates(predicates={:?})",
906 let result = tcx.infer_ctxt().enter(|infcx| {
907 let param_env = ty::ParamEnv::reveal_all();
908 let mut selcx = SelectionContext::new(&infcx);
909 let mut fulfill_cx = FulfillmentContext::new();
910 let cause = ObligationCause::dummy();
911 let Normalized { value: predicates, obligations } =
912 normalize(&mut selcx, param_env, cause.clone(), &predicates);
913 for obligation in obligations {
914 fulfill_cx.register_predicate_obligation(&infcx, obligation);
916 for predicate in predicates {
917 let obligation = Obligation::new(cause.clone(), param_env, predicate);
918 fulfill_cx.register_predicate_obligation(&infcx, obligation);
921 fulfill_cx.select_all_or_error(&infcx).is_ok()
923 debug!("normalize_and_test_predicates(predicates={:?}) = {:?}",
928 fn substitute_normalize_and_test_predicates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
929 key: (DefId, &'tcx Substs<'tcx>))
932 debug!("substitute_normalize_and_test_predicates(key={:?})",
935 let predicates = tcx.predicates_of(key.0).instantiate(tcx, key.1).predicates;
936 let result = normalize_and_test_predicates(tcx, predicates);
938 debug!("substitute_normalize_and_test_predicates(key={:?}) = {:?}",
943 /// Given a trait `trait_ref`, iterates the vtable entries
944 /// that come from `trait_ref`, including its supertraits.
945 #[inline] // FIXME(#35870) Avoid closures being unexported due to impl Trait.
946 fn vtable_methods<'a, 'tcx>(
947 tcx: TyCtxt<'a, 'tcx, 'tcx>,
948 trait_ref: ty::PolyTraitRef<'tcx>)
949 -> Lrc<Vec<Option<(DefId, &'tcx Substs<'tcx>)>>>
951 debug!("vtable_methods({:?})", trait_ref);
954 supertraits(tcx, trait_ref).flat_map(move |trait_ref| {
955 let trait_methods = tcx.associated_items(trait_ref.def_id())
956 .filter(|item| item.kind == ty::AssociatedKind::Method);
958 // Now list each method's DefId and Substs (for within its trait).
959 // If the method can never be called from this object, produce None.
960 trait_methods.map(move |trait_method| {
961 debug!("vtable_methods: trait_method={:?}", trait_method);
962 let def_id = trait_method.def_id;
964 // Some methods cannot be called on an object; skip those.
965 if !tcx.is_vtable_safe_method(trait_ref.def_id(), &trait_method) {
966 debug!("vtable_methods: not vtable safe");
970 // the method may have some early-bound lifetimes, add
972 let substs = trait_ref.map_bound(|trait_ref|
973 Substs::for_item(tcx, def_id, |param, _|
975 GenericParamDefKind::Lifetime => tcx.types.re_erased.into(),
976 GenericParamDefKind::Type {..} => {
977 trait_ref.substs[param.index as usize]
983 // the trait type may have higher-ranked lifetimes in it;
984 // so erase them if they appear, so that we get the type
985 // at some particular call site
986 let substs = tcx.normalize_erasing_late_bound_regions(
987 ty::ParamEnv::reveal_all(),
991 // It's possible that the method relies on where clauses that
992 // do not hold for this particular set of type parameters.
993 // Note that this method could then never be called, so we
994 // do not want to try and codegen it, in that case (see #23435).
995 let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs);
996 if !normalize_and_test_predicates(tcx, predicates.predicates) {
997 debug!("vtable_methods: predicates do not hold");
1001 Some((def_id, substs))
1007 impl<'tcx,O> Obligation<'tcx,O> {
1008 pub fn new(cause: ObligationCause<'tcx>,
1009 param_env: ty::ParamEnv<'tcx>,
1011 -> Obligation<'tcx, O>
1013 Obligation { cause, param_env, recursion_depth: 0, predicate }
1016 fn with_depth(cause: ObligationCause<'tcx>,
1017 recursion_depth: usize,
1018 param_env: ty::ParamEnv<'tcx>,
1020 -> Obligation<'tcx, O>
1022 Obligation { cause, param_env, recursion_depth, predicate }
1025 pub fn misc(span: Span,
1026 body_id: ast::NodeId,
1027 param_env: ty::ParamEnv<'tcx>,
1029 -> Obligation<'tcx, O> {
1030 Obligation::new(ObligationCause::misc(span, body_id), param_env, trait_ref)
1033 pub fn with<P>(&self, value: P) -> Obligation<'tcx,P> {
1034 Obligation { cause: self.cause.clone(),
1035 param_env: self.param_env,
1036 recursion_depth: self.recursion_depth,
1041 impl<'tcx> ObligationCause<'tcx> {
1042 pub fn new(span: Span,
1043 body_id: ast::NodeId,
1044 code: ObligationCauseCode<'tcx>)
1045 -> ObligationCause<'tcx> {
1046 ObligationCause { span: span, body_id: body_id, code: code }
1049 pub fn misc(span: Span, body_id: ast::NodeId) -> ObligationCause<'tcx> {
1050 ObligationCause { span: span, body_id: body_id, code: MiscObligation }
1053 pub fn dummy() -> ObligationCause<'tcx> {
1054 ObligationCause { span: DUMMY_SP, body_id: ast::CRATE_NODE_ID, code: MiscObligation }
1058 impl<'tcx, N> Vtable<'tcx, N> {
1059 pub fn nested_obligations(self) -> Vec<N> {
1061 VtableImpl(i) => i.nested,
1062 VtableParam(n) => n,
1063 VtableBuiltin(i) => i.nested,
1064 VtableAutoImpl(d) => d.nested,
1065 VtableClosure(c) => c.nested,
1066 VtableGenerator(c) => c.nested,
1067 VtableObject(d) => d.nested,
1068 VtableFnPointer(d) => d.nested,
1072 pub fn map<M, F>(self, f: F) -> Vtable<'tcx, M> where F: FnMut(N) -> M {
1074 VtableImpl(i) => VtableImpl(VtableImplData {
1075 impl_def_id: i.impl_def_id,
1077 nested: i.nested.into_iter().map(f).collect(),
1079 VtableParam(n) => VtableParam(n.into_iter().map(f).collect()),
1080 VtableBuiltin(i) => VtableBuiltin(VtableBuiltinData {
1081 nested: i.nested.into_iter().map(f).collect(),
1083 VtableObject(o) => VtableObject(VtableObjectData {
1084 upcast_trait_ref: o.upcast_trait_ref,
1085 vtable_base: o.vtable_base,
1086 nested: o.nested.into_iter().map(f).collect(),
1088 VtableAutoImpl(d) => VtableAutoImpl(VtableAutoImplData {
1089 trait_def_id: d.trait_def_id,
1090 nested: d.nested.into_iter().map(f).collect(),
1092 VtableFnPointer(p) => VtableFnPointer(VtableFnPointerData {
1094 nested: p.nested.into_iter().map(f).collect(),
1096 VtableGenerator(c) => VtableGenerator(VtableGeneratorData {
1097 generator_def_id: c.generator_def_id,
1099 nested: c.nested.into_iter().map(f).collect(),
1101 VtableClosure(c) => VtableClosure(VtableClosureData {
1102 closure_def_id: c.closure_def_id,
1104 nested: c.nested.into_iter().map(f).collect(),
1110 impl<'tcx> FulfillmentError<'tcx> {
1111 fn new(obligation: PredicateObligation<'tcx>,
1112 code: FulfillmentErrorCode<'tcx>)
1113 -> FulfillmentError<'tcx>
1115 FulfillmentError { obligation: obligation, code: code }
1119 impl<'tcx> TraitObligation<'tcx> {
1120 fn self_ty(&self) -> ty::Binder<Ty<'tcx>> {
1121 self.predicate.map_bound(|p| p.self_ty())
1125 pub fn provide(providers: &mut ty::query::Providers<'_>) {
1126 *providers = ty::query::Providers {
1127 is_object_safe: object_safety::is_object_safe_provider,
1128 specialization_graph_of: specialize::specialization_graph_provider,
1129 specializes: specialize::specializes,
1130 codegen_fulfill_obligation: codegen::codegen_fulfill_obligation,
1132 substitute_normalize_and_test_predicates,
1137 pub trait ExClauseFold<'tcx>
1139 Self: chalk_engine::context::Context + Clone,
1141 fn fold_ex_clause_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(
1142 ex_clause: &chalk_engine::ExClause<Self>,
1144 ) -> chalk_engine::ExClause<Self>;
1146 fn visit_ex_clause_with<'gcx: 'tcx, V: TypeVisitor<'tcx>>(
1147 ex_clause: &chalk_engine::ExClause<Self>,
1152 pub trait ExClauseLift<'tcx>
1154 Self: chalk_engine::context::Context + Clone,
1156 type LiftedExClause: Debug + 'tcx;
1158 fn lift_ex_clause_to_tcx<'a, 'gcx>(
1159 ex_clause: &chalk_engine::ExClause<Self>,
1160 tcx: TyCtxt<'a, 'gcx, 'tcx>,
1161 ) -> Option<Self::LiftedExClause>;