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;
50 pub use self::SelectionError::*;
51 pub use self::FulfillmentErrorCode::*;
52 pub use self::Vtable::*;
53 pub use self::ObligationCauseCode::*;
55 pub use self::coherence::{orphan_check, overlapping_impls, OrphanCheckErr, OverlapResult};
56 pub use self::fulfill::{FulfillmentContext, PendingPredicateObligation};
57 pub use self::project::MismatchedProjectionTypes;
58 pub use self::project::{normalize, normalize_projection_type, poly_project_and_unify_type};
59 pub use self::project::{ProjectionCache, ProjectionCacheSnapshot, Reveal, Normalized};
60 pub use self::object_safety::ObjectSafetyViolation;
61 pub use self::object_safety::MethodViolationCode;
62 pub use self::on_unimplemented::{OnUnimplementedDirective, OnUnimplementedNote};
63 pub use self::select::{EvaluationCache, SelectionContext, SelectionCache};
64 pub use self::select::{EvaluationResult, IntercrateAmbiguityCause, OverflowError};
65 pub use self::specialize::{OverlapError, specialization_graph, translate_substs};
66 pub use self::specialize::find_associated_item;
67 pub use self::specialize::specialization_graph::FutureCompatOverlapError;
68 pub use self::specialize::specialization_graph::FutureCompatOverlapErrorKind;
69 pub use self::engine::{TraitEngine, TraitEngineExt};
70 pub use self::util::{elaborate_predicates, elaborate_trait_ref, elaborate_trait_refs};
71 pub use self::util::{supertraits, supertrait_def_ids, transitive_bounds,
72 Supertraits, SupertraitDefIds};
74 pub use self::ObligationCauseCode::*;
75 pub use self::FulfillmentErrorCode::*;
76 pub use self::SelectionError::*;
77 pub use self::Vtable::*;
79 // Whether to enable bug compatibility with issue #43355
80 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
81 pub enum IntercrateMode {
86 // The mode that trait queries run in
87 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
88 pub enum TraitQueryMode {
89 // Standard/un-canonicalized queries get accurate
90 // spans etc. passed in and hence can do reasonable
91 // error reporting on their own.
93 // Canonicalized queries get dummy spans and hence
94 // must generally propagate errors to
95 // pre-canonicalization callsites.
99 /// An `Obligation` represents some trait reference (e.g., `int:Eq`) for
100 /// which the vtable must be found. The process of finding a vtable is
101 /// called "resolving" the `Obligation`. This process consists of
102 /// either identifying an `impl` (e.g., `impl Eq for int`) that
103 /// provides the required vtable, or else finding a bound that is in
104 /// scope. The eventual result is usually a `Selection` (defined below).
105 #[derive(Clone, PartialEq, Eq, Hash)]
106 pub struct Obligation<'tcx, T> {
107 /// Why do we have to prove this thing?
108 pub cause: ObligationCause<'tcx>,
110 /// In which environment should we prove this thing?
111 pub param_env: ty::ParamEnv<'tcx>,
113 /// What are we trying to prove?
116 /// If we started proving this as a result of trying to prove
117 /// something else, track the total depth to ensure termination.
118 /// If this goes over a certain threshold, we abort compilation --
119 /// in such cases, we can not say whether or not the predicate
120 /// holds for certain. Stupid halting problem. Such a drag.
121 pub recursion_depth: usize,
124 pub type PredicateObligation<'tcx> = Obligation<'tcx, ty::Predicate<'tcx>>;
125 pub type TraitObligation<'tcx> = Obligation<'tcx, ty::PolyTraitPredicate<'tcx>>;
127 /// Why did we incur this obligation? Used for error reporting.
128 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
129 pub struct ObligationCause<'tcx> {
132 // The id of the fn body that triggered this obligation. This is
133 // used for region obligations to determine the precise
134 // environment in which the region obligation should be evaluated
135 // (in particular, closures can add new assumptions). See the
136 // field `region_obligations` of the `FulfillmentContext` for more
138 pub body_id: ast::NodeId,
140 pub code: ObligationCauseCode<'tcx>
143 impl<'tcx> ObligationCause<'tcx> {
144 pub fn span<'a, 'gcx>(&self, tcx: &TyCtxt<'a, 'gcx, 'tcx>) -> Span {
146 ObligationCauseCode::CompareImplMethodObligation { .. } |
147 ObligationCauseCode::MainFunctionType |
148 ObligationCauseCode::StartFunctionType => {
149 tcx.sess.source_map().def_span(self.span)
156 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
157 pub enum ObligationCauseCode<'tcx> {
158 /// Not well classified or should be obvious from span.
161 /// A slice or array is WF only if `T: Sized`
164 /// A tuple is WF only if its middle elements are Sized
167 /// This is the trait reference from the given projection
168 ProjectionWf(ty::ProjectionTy<'tcx>),
170 /// In an impl of trait X for type Y, type Y must
171 /// also implement all supertraits of X.
172 ItemObligation(DefId),
174 /// A type like `&'a T` is WF only if `T: 'a`.
175 ReferenceOutlivesReferent(Ty<'tcx>),
177 /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
178 ObjectTypeBound(Ty<'tcx>, ty::Region<'tcx>),
180 /// Obligation incurred due to an object cast.
181 ObjectCastObligation(/* Object type */ Ty<'tcx>),
183 // Various cases where expressions must be sized/copy/etc:
184 /// L = X implies that L is Sized
186 /// (x1, .., xn) must be Sized
187 TupleInitializerSized,
188 /// S { ... } must be Sized
189 StructInitializerSized,
190 /// Type of each variable must be Sized
191 VariableType(ast::NodeId),
192 /// Argument type must be Sized
194 /// Return type must be Sized
196 /// Yield type must be Sized
198 /// [T,..n] --> T must be Copy
201 /// Types of fields (other than the last, except for packed structs) in a struct must be sized.
202 FieldSized { adt_kind: AdtKind, last: bool },
204 /// Constant expressions must be sized.
207 /// static items must have `Sync` type
210 BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
212 ImplDerivedObligation(DerivedObligationCause<'tcx>),
214 /// error derived when matching traits/impls; see ObligationCause for more details
215 CompareImplMethodObligation {
216 item_name: ast::Name,
217 impl_item_def_id: DefId,
218 trait_item_def_id: DefId,
221 /// Checking that this expression can be assigned where it needs to be
222 // FIXME(eddyb) #11161 is the original Expr required?
225 /// Computing common supertype in the arms of a match expression
226 MatchExpressionArm { arm_span: Span,
227 source: hir::MatchSource },
229 /// Computing common supertype in an if expression
232 /// Computing common supertype of an if expression with no else counter-part
233 IfExpressionWithNoElse,
235 /// `main` has wrong type
238 /// `start` has wrong type
241 /// intrinsic has wrong type
247 /// `return` with no expression
250 /// `return` with an expression
251 ReturnType(ast::NodeId),
253 /// Block implicit return
254 BlockTailExpression(ast::NodeId),
256 /// #[feature(trivial_bounds)] is not enabled
260 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
261 pub struct DerivedObligationCause<'tcx> {
262 /// The trait reference of the parent obligation that led to the
263 /// current obligation. Note that only trait obligations lead to
264 /// derived obligations, so we just store the trait reference here
266 parent_trait_ref: ty::PolyTraitRef<'tcx>,
268 /// The parent trait had this cause
269 parent_code: Rc<ObligationCauseCode<'tcx>>
272 pub type Obligations<'tcx, O> = Vec<Obligation<'tcx, O>>;
273 pub type PredicateObligations<'tcx> = Vec<PredicateObligation<'tcx>>;
274 pub type TraitObligations<'tcx> = Vec<TraitObligation<'tcx>>;
276 /// The following types:
284 /// * `InEnvironment`
285 /// are used for representing the trait system in the form of
286 /// logic programming clauses. They are part of the interface
287 /// for the chalk SLG solver.
288 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
289 pub enum WhereClause<'tcx> {
290 Implemented(ty::TraitPredicate<'tcx>),
291 ProjectionEq(ty::ProjectionPredicate<'tcx>),
292 RegionOutlives(ty::RegionOutlivesPredicate<'tcx>),
293 TypeOutlives(ty::TypeOutlivesPredicate<'tcx>),
296 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
297 pub enum WellFormed<'tcx> {
298 Trait(ty::TraitPredicate<'tcx>),
302 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
303 pub enum FromEnv<'tcx> {
304 Trait(ty::TraitPredicate<'tcx>),
308 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
309 pub enum DomainGoal<'tcx> {
310 Holds(WhereClause<'tcx>),
311 WellFormed(WellFormed<'tcx>),
312 FromEnv(FromEnv<'tcx>),
313 Normalize(ty::ProjectionPredicate<'tcx>),
316 pub type PolyDomainGoal<'tcx> = ty::Binder<DomainGoal<'tcx>>;
318 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
319 pub enum QuantifierKind {
324 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
325 pub enum GoalKind<'tcx> {
326 Implies(Clauses<'tcx>, Goal<'tcx>),
327 And(Goal<'tcx>, Goal<'tcx>),
329 DomainGoal(DomainGoal<'tcx>),
330 Quantified(QuantifierKind, ty::Binder<Goal<'tcx>>),
334 pub type Goal<'tcx> = &'tcx GoalKind<'tcx>;
336 pub type Goals<'tcx> = &'tcx List<Goal<'tcx>>;
338 impl<'tcx> DomainGoal<'tcx> {
339 pub fn into_goal(self) -> GoalKind<'tcx> {
340 GoalKind::DomainGoal(self)
343 pub fn into_program_clause(self) -> ProgramClause<'tcx> {
346 hypotheses: ty::List::empty(),
347 category: ProgramClauseCategory::Other,
352 impl<'tcx> GoalKind<'tcx> {
353 pub fn from_poly_domain_goal<'a>(
354 domain_goal: PolyDomainGoal<'tcx>,
355 tcx: TyCtxt<'a, 'tcx, 'tcx>,
356 ) -> GoalKind<'tcx> {
357 match domain_goal.no_bound_vars() {
358 Some(p) => p.into_goal(),
359 None => GoalKind::Quantified(
360 QuantifierKind::Universal,
361 domain_goal.map_bound(|p| tcx.mk_goal(p.into_goal()))
367 /// This matches the definition from Page 7 of "A Proof Procedure for the Logic of Hereditary
368 /// Harrop Formulas".
369 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
370 pub enum Clause<'tcx> {
371 Implies(ProgramClause<'tcx>),
372 ForAll(ty::Binder<ProgramClause<'tcx>>),
376 pub fn category(self) -> ProgramClauseCategory {
378 Clause::Implies(clause) => clause.category,
379 Clause::ForAll(clause) => clause.skip_binder().category,
384 /// Multiple clauses.
385 pub type Clauses<'tcx> = &'tcx List<Clause<'tcx>>;
387 /// A "program clause" has the form `D :- G1, ..., Gn`. It is saying
388 /// that the domain goal `D` is true if `G1...Gn` are provable. This
389 /// is equivalent to the implication `G1..Gn => D`; we usually write
390 /// it with the reverse implication operator `:-` to emphasize the way
391 /// that programs are actually solved (via backchaining, which starts
392 /// with the goal to solve and proceeds from there).
393 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
394 pub struct ProgramClause<'tcx> {
395 /// This goal will be considered true...
396 pub goal: DomainGoal<'tcx>,
398 /// ...if we can prove these hypotheses (there may be no hypotheses at all):
399 pub hypotheses: Goals<'tcx>,
401 /// Useful for filtering clauses.
402 pub category: ProgramClauseCategory,
405 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
406 pub enum ProgramClauseCategory {
412 /// A set of clauses that we assume to be true.
413 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
414 pub struct Environment<'tcx> {
415 pub clauses: Clauses<'tcx>,
418 impl Environment<'tcx> {
419 pub fn with<G>(self, goal: G) -> InEnvironment<'tcx, G> {
427 /// Something (usually a goal), along with an environment.
428 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
429 pub struct InEnvironment<'tcx, G> {
430 pub environment: Environment<'tcx>,
434 pub type Selection<'tcx> = Vtable<'tcx, PredicateObligation<'tcx>>;
436 #[derive(Clone,Debug)]
437 pub enum SelectionError<'tcx> {
439 OutputTypeParameterMismatch(ty::PolyTraitRef<'tcx>,
440 ty::PolyTraitRef<'tcx>,
441 ty::error::TypeError<'tcx>),
442 TraitNotObjectSafe(DefId),
443 ConstEvalFailure(ErrorHandled),
447 pub struct FulfillmentError<'tcx> {
448 pub obligation: PredicateObligation<'tcx>,
449 pub code: FulfillmentErrorCode<'tcx>
453 pub enum FulfillmentErrorCode<'tcx> {
454 CodeSelectionError(SelectionError<'tcx>),
455 CodeProjectionError(MismatchedProjectionTypes<'tcx>),
456 CodeSubtypeError(ExpectedFound<Ty<'tcx>>,
457 TypeError<'tcx>), // always comes from a SubtypePredicate
461 /// When performing resolution, it is typically the case that there
462 /// can be one of three outcomes:
464 /// - `Ok(Some(r))`: success occurred with result `r`
465 /// - `Ok(None)`: could not definitely determine anything, usually due
466 /// to inconclusive type inference.
467 /// - `Err(e)`: error `e` occurred
468 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
470 /// Given the successful resolution of an obligation, the `Vtable`
471 /// indicates where the vtable comes from. Note that while we call this
472 /// a "vtable", it does not necessarily indicate dynamic dispatch at
473 /// runtime. `Vtable` instances just tell the compiler where to find
474 /// methods, but in generic code those methods are typically statically
475 /// dispatched -- only when an object is constructed is a `Vtable`
476 /// instance reified into an actual vtable.
478 /// For example, the vtable may be tied to a specific impl (case A),
479 /// or it may be relative to some bound that is in scope (case B).
483 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
484 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
485 /// impl Clone for int { ... } // Impl_3
487 /// fn foo<T:Clone>(concrete: Option<Box<int>>,
489 /// mixed: Option<T>) {
491 /// // Case A: Vtable points at a specific impl. Only possible when
492 /// // type is concretely known. If the impl itself has bounded
493 /// // type parameters, Vtable will carry resolutions for those as well:
494 /// concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
496 /// // Case B: Vtable must be provided by caller. This applies when
497 /// // type is a type parameter.
498 /// param.clone(); // VtableParam
500 /// // Case C: A mix of cases A and B.
501 /// mixed.clone(); // Vtable(Impl_1, [VtableParam])
505 /// ### The type parameter `N`
507 /// See explanation on `VtableImplData`.
508 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
509 pub enum Vtable<'tcx, N> {
510 /// Vtable identifying a particular impl.
511 VtableImpl(VtableImplData<'tcx, N>),
513 /// Vtable for auto trait implementations
514 /// This carries the information and nested obligations with regards
515 /// to an auto implementation for a trait `Trait`. The nested obligations
516 /// ensure the trait implementation holds for all the constituent types.
517 VtableAutoImpl(VtableAutoImplData<N>),
519 /// Successful resolution to an obligation provided by the caller
520 /// for some type parameter. The `Vec<N>` represents the
521 /// obligations incurred from normalizing the where-clause (if
525 /// Virtual calls through an object
526 VtableObject(VtableObjectData<'tcx, N>),
528 /// Successful resolution for a builtin trait.
529 VtableBuiltin(VtableBuiltinData<N>),
531 /// Vtable automatically generated for a closure. The def ID is the ID
532 /// of the closure expression. This is a `VtableImpl` in spirit, but the
533 /// impl is generated by the compiler and does not appear in the source.
534 VtableClosure(VtableClosureData<'tcx, N>),
536 /// Same as above, but for a fn pointer type with the given signature.
537 VtableFnPointer(VtableFnPointerData<'tcx, N>),
539 /// Vtable automatically generated for a generator.
540 VtableGenerator(VtableGeneratorData<'tcx, N>),
542 /// Vtable for a trait alias.
543 VtableTraitAlias(VtableTraitAliasData<'tcx, N>),
546 /// Identifies a particular impl in the source, along with a set of
547 /// substitutions from the impl's type/lifetime parameters. The
548 /// `nested` vector corresponds to the nested obligations attached to
549 /// the impl's type parameters.
551 /// The type parameter `N` indicates the type used for "nested
552 /// obligations" that are required by the impl. During type check, this
553 /// is `Obligation`, as one might expect. During codegen, however, this
554 /// is `()`, because codegen only requires a shallow resolution of an
555 /// impl, and nested obligations are satisfied later.
556 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
557 pub struct VtableImplData<'tcx, N> {
558 pub impl_def_id: DefId,
559 pub substs: &'tcx Substs<'tcx>,
563 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
564 pub struct VtableGeneratorData<'tcx, N> {
565 pub generator_def_id: DefId,
566 pub substs: ty::GeneratorSubsts<'tcx>,
567 /// Nested obligations. This can be non-empty if the generator
568 /// signature contains associated types.
572 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
573 pub struct VtableClosureData<'tcx, N> {
574 pub closure_def_id: DefId,
575 pub substs: ty::ClosureSubsts<'tcx>,
576 /// Nested obligations. This can be non-empty if the closure
577 /// signature contains associated types.
581 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
582 pub struct VtableAutoImplData<N> {
583 pub trait_def_id: DefId,
587 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
588 pub struct VtableBuiltinData<N> {
592 /// A vtable for some object-safe trait `Foo` automatically derived
593 /// for the object type `Foo`.
594 #[derive(PartialEq, Eq, Clone, RustcEncodable, RustcDecodable)]
595 pub struct VtableObjectData<'tcx, N> {
596 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
597 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
599 /// The vtable is formed by concatenating together the method lists of
600 /// the base object trait and all supertraits; this is the start of
601 /// `upcast_trait_ref`'s methods in that vtable.
602 pub vtable_base: usize,
607 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
608 pub struct VtableFnPointerData<'tcx, N> {
613 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
614 pub struct VtableTraitAliasData<'tcx, N> {
615 pub alias_def_id: DefId,
616 pub substs: &'tcx Substs<'tcx>,
620 /// Creates predicate obligations from the generic bounds.
621 pub fn predicates_for_generics<'tcx>(cause: ObligationCause<'tcx>,
622 param_env: ty::ParamEnv<'tcx>,
623 generic_bounds: &ty::InstantiatedPredicates<'tcx>)
624 -> PredicateObligations<'tcx>
626 util::predicates_for_generics(cause, 0, param_env, generic_bounds)
629 /// Determines whether the type `ty` is known to meet `bound` and
630 /// returns true if so. Returns false if `ty` either does not meet
631 /// `bound` or is not known to meet bound (note that this is
632 /// conservative towards *no impl*, which is the opposite of the
633 /// `evaluate` methods).
634 pub fn type_known_to_meet_bound<'a, 'gcx, 'tcx>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
635 param_env: ty::ParamEnv<'tcx>,
641 debug!("type_known_to_meet_bound(ty={:?}, bound={:?})",
643 infcx.tcx.item_path_str(def_id));
645 let trait_ref = ty::TraitRef {
647 substs: infcx.tcx.mk_substs_trait(ty, &[]),
649 let obligation = Obligation {
651 cause: ObligationCause::misc(span, ast::DUMMY_NODE_ID),
653 predicate: trait_ref.to_predicate(),
656 let result = infcx.predicate_must_hold(&obligation);
657 debug!("type_known_to_meet_ty={:?} bound={} => {:?}",
658 ty, infcx.tcx.item_path_str(def_id), result);
660 if result && (ty.has_infer_types() || ty.has_closure_types()) {
661 // Because of inference "guessing", selection can sometimes claim
662 // to succeed while the success requires a guess. To ensure
663 // this function's result remains infallible, we must confirm
664 // that guess. While imperfect, I believe this is sound.
666 // The handling of regions in this area of the code is terrible,
667 // see issue #29149. We should be able to improve on this with
669 let mut fulfill_cx = FulfillmentContext::new_ignoring_regions();
671 // We can use a dummy node-id here because we won't pay any mind
672 // to region obligations that arise (there shouldn't really be any
674 let cause = ObligationCause::misc(span, ast::DUMMY_NODE_ID);
676 fulfill_cx.register_bound(infcx, param_env, ty, def_id, cause);
678 // Note: we only assume something is `Copy` if we can
679 // *definitively* show that it implements `Copy`. Otherwise,
680 // assume it is move; linear is always ok.
681 match fulfill_cx.select_all_or_error(infcx) {
683 debug!("type_known_to_meet_bound: ty={:?} bound={} success",
685 infcx.tcx.item_path_str(def_id));
689 debug!("type_known_to_meet_bound: ty={:?} bound={} errors={:?}",
691 infcx.tcx.item_path_str(def_id),
701 fn do_normalize_predicates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
702 region_context: DefId,
703 cause: ObligationCause<'tcx>,
704 elaborated_env: ty::ParamEnv<'tcx>,
705 predicates: Vec<ty::Predicate<'tcx>>)
706 -> Result<Vec<ty::Predicate<'tcx>>, ErrorReported>
709 "do_normalize_predicates(predicates={:?}, region_context={:?}, cause={:?})",
714 let span = cause.span;
715 tcx.infer_ctxt().enter(|infcx| {
716 // FIXME. We should really... do something with these region
717 // obligations. But this call just continues the older
718 // behavior (i.e., doesn't cause any new bugs), and it would
719 // take some further refactoring to actually solve them. In
720 // particular, we would have to handle implied bounds
721 // properly, and that code is currently largely confined to
722 // regionck (though I made some efforts to extract it
725 // @arielby: In any case, these obligations are checked
726 // by wfcheck anyway, so I'm not sure we have to check
727 // them here too, and we will remove this function when
728 // we move over to lazy normalization *anyway*.
729 let fulfill_cx = FulfillmentContext::new_ignoring_regions();
730 let predicates = match fully_normalize(
737 Ok(predicates) => predicates,
739 infcx.report_fulfillment_errors(&errors, None, false);
740 return Err(ErrorReported)
744 debug!("do_normalize_predictes: normalized predicates = {:?}", predicates);
746 let region_scope_tree = region::ScopeTree::default();
748 // We can use the `elaborated_env` here; the region code only
749 // cares about declarations like `'a: 'b`.
750 let outlives_env = OutlivesEnvironment::new(elaborated_env);
752 infcx.resolve_regions_and_report_errors(
756 SuppressRegionErrors::default(),
759 let predicates = match infcx.fully_resolve(&predicates) {
760 Ok(predicates) => predicates,
762 // If we encounter a fixup error, it means that some type
763 // variable wound up unconstrained. I actually don't know
764 // if this can happen, and I certainly don't expect it to
765 // happen often, but if it did happen it probably
766 // represents a legitimate failure due to some kind of
767 // unconstrained variable, and it seems better not to ICE,
768 // all things considered.
769 tcx.sess.span_err(span, &fixup_err.to_string());
770 return Err(ErrorReported)
774 match tcx.lift_to_global(&predicates) {
775 Some(predicates) => Ok(predicates),
777 // FIXME: shouldn't we, you know, actually report an error here? or an ICE?
784 // FIXME: this is gonna need to be removed ...
785 /// Normalizes the parameter environment, reporting errors if they occur.
786 pub fn normalize_param_env_or_error<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
787 region_context: DefId,
788 unnormalized_env: ty::ParamEnv<'tcx>,
789 cause: ObligationCause<'tcx>)
790 -> ty::ParamEnv<'tcx>
792 // I'm not wild about reporting errors here; I'd prefer to
793 // have the errors get reported at a defined place (e.g.,
794 // during typeck). Instead I have all parameter
795 // environments, in effect, going through this function
796 // and hence potentially reporting errors. This ensures of
797 // course that we never forget to normalize (the
798 // alternative seemed like it would involve a lot of
799 // manual invocations of this fn -- and then we'd have to
800 // deal with the errors at each of those sites).
802 // In any case, in practice, typeck constructs all the
803 // parameter environments once for every fn as it goes,
804 // and errors will get reported then; so after typeck we
805 // can be sure that no errors should occur.
807 debug!("normalize_param_env_or_error(region_context={:?}, unnormalized_env={:?}, cause={:?})",
808 region_context, unnormalized_env, cause);
810 let mut predicates: Vec<_> =
811 util::elaborate_predicates(tcx, unnormalized_env.caller_bounds.to_vec())
814 debug!("normalize_param_env_or_error: elaborated-predicates={:?}",
817 let elaborated_env = ty::ParamEnv::new(tcx.intern_predicates(&predicates),
818 unnormalized_env.reveal);
820 // HACK: we are trying to normalize the param-env inside *itself*. The problem is that
821 // normalization expects its param-env to be already normalized, which means we have
824 // The way we handle this is by normalizing the param-env inside an unnormalized version
825 // of the param-env, which means that if the param-env contains unnormalized projections,
826 // we'll have some normalization failures. This is unfortunate.
828 // Lazy normalization would basically handle this by treating just the
829 // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
831 // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
832 // types, so to make the situation less bad, we normalize all the predicates *but*
833 // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
834 // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
836 // This works fairly well because trait matching does not actually care about param-env
837 // TypeOutlives predicates - these are normally used by regionck.
838 let outlives_predicates: Vec<_> = predicates.drain_filter(|predicate| {
840 ty::Predicate::TypeOutlives(..) => true,
845 debug!("normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
846 predicates, outlives_predicates);
847 let non_outlives_predicates =
848 match do_normalize_predicates(tcx, region_context, cause.clone(),
849 elaborated_env, predicates) {
850 Ok(predicates) => predicates,
851 // An unnormalized env is better than nothing.
852 Err(ErrorReported) => {
853 debug!("normalize_param_env_or_error: errored resolving non-outlives predicates");
854 return elaborated_env
858 debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates);
860 // Not sure whether it is better to include the unnormalized TypeOutlives predicates
861 // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
862 // predicates here anyway. Keeping them here anyway because it seems safer.
863 let outlives_env: Vec<_> =
864 non_outlives_predicates.iter().chain(&outlives_predicates).cloned().collect();
865 let outlives_env = ty::ParamEnv::new(tcx.intern_predicates(&outlives_env),
866 unnormalized_env.reveal);
867 let outlives_predicates =
868 match do_normalize_predicates(tcx, region_context, cause,
869 outlives_env, outlives_predicates) {
870 Ok(predicates) => predicates,
871 // An unnormalized env is better than nothing.
872 Err(ErrorReported) => {
873 debug!("normalize_param_env_or_error: errored resolving outlives predicates");
874 return elaborated_env
877 debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates);
879 let mut predicates = non_outlives_predicates;
880 predicates.extend(outlives_predicates);
881 debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
882 ty::ParamEnv::new(tcx.intern_predicates(&predicates), unnormalized_env.reveal)
885 pub fn fully_normalize<'a, 'gcx, 'tcx, T>(
886 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
887 mut fulfill_cx: FulfillmentContext<'tcx>,
888 cause: ObligationCause<'tcx>,
889 param_env: ty::ParamEnv<'tcx>,
891 -> Result<T, Vec<FulfillmentError<'tcx>>>
892 where T : TypeFoldable<'tcx>
894 debug!("fully_normalize_with_fulfillcx(value={:?})", value);
895 let selcx = &mut SelectionContext::new(infcx);
896 let Normalized { value: normalized_value, obligations } =
897 project::normalize(selcx, param_env, cause, value);
898 debug!("fully_normalize: normalized_value={:?} obligations={:?}",
901 for obligation in obligations {
902 fulfill_cx.register_predicate_obligation(selcx.infcx(), obligation);
905 debug!("fully_normalize: select_all_or_error start");
906 fulfill_cx.select_all_or_error(infcx)?;
907 debug!("fully_normalize: select_all_or_error complete");
908 let resolved_value = infcx.resolve_type_vars_if_possible(&normalized_value);
909 debug!("fully_normalize: resolved_value={:?}", resolved_value);
913 /// Normalizes the predicates and checks whether they hold in an empty
914 /// environment. If this returns false, then either normalize
915 /// encountered an error or one of the predicates did not hold. Used
916 /// when creating vtables to check for unsatisfiable methods.
917 fn normalize_and_test_predicates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
918 predicates: Vec<ty::Predicate<'tcx>>)
921 debug!("normalize_and_test_predicates(predicates={:?})",
924 let result = tcx.infer_ctxt().enter(|infcx| {
925 let param_env = ty::ParamEnv::reveal_all();
926 let mut selcx = SelectionContext::new(&infcx);
927 let mut fulfill_cx = FulfillmentContext::new();
928 let cause = ObligationCause::dummy();
929 let Normalized { value: predicates, obligations } =
930 normalize(&mut selcx, param_env, cause.clone(), &predicates);
931 for obligation in obligations {
932 fulfill_cx.register_predicate_obligation(&infcx, obligation);
934 for predicate in predicates {
935 let obligation = Obligation::new(cause.clone(), param_env, predicate);
936 fulfill_cx.register_predicate_obligation(&infcx, obligation);
939 fulfill_cx.select_all_or_error(&infcx).is_ok()
941 debug!("normalize_and_test_predicates(predicates={:?}) = {:?}",
946 fn substitute_normalize_and_test_predicates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
947 key: (DefId, &'tcx Substs<'tcx>))
950 debug!("substitute_normalize_and_test_predicates(key={:?})",
953 let predicates = tcx.predicates_of(key.0).instantiate(tcx, key.1).predicates;
954 let result = normalize_and_test_predicates(tcx, predicates);
956 debug!("substitute_normalize_and_test_predicates(key={:?}) = {:?}",
961 /// Given a trait `trait_ref`, iterates the vtable entries
962 /// that come from `trait_ref`, including its supertraits.
963 #[inline] // FIXME(#35870): avoid closures being unexported due to `impl Trait`.
964 fn vtable_methods<'a, 'tcx>(
965 tcx: TyCtxt<'a, 'tcx, 'tcx>,
966 trait_ref: ty::PolyTraitRef<'tcx>)
967 -> Lrc<Vec<Option<(DefId, &'tcx Substs<'tcx>)>>>
969 debug!("vtable_methods({:?})", trait_ref);
972 supertraits(tcx, trait_ref).flat_map(move |trait_ref| {
973 let trait_methods = tcx.associated_items(trait_ref.def_id())
974 .filter(|item| item.kind == ty::AssociatedKind::Method);
976 // Now list each method's DefId and Substs (for within its trait).
977 // If the method can never be called from this object, produce None.
978 trait_methods.map(move |trait_method| {
979 debug!("vtable_methods: trait_method={:?}", trait_method);
980 let def_id = trait_method.def_id;
982 // Some methods cannot be called on an object; skip those.
983 if !tcx.is_vtable_safe_method(trait_ref.def_id(), &trait_method) {
984 debug!("vtable_methods: not vtable safe");
988 // the method may have some early-bound lifetimes, add
990 let substs = trait_ref.map_bound(|trait_ref|
991 Substs::for_item(tcx, def_id, |param, _|
993 GenericParamDefKind::Lifetime => tcx.types.re_erased.into(),
994 GenericParamDefKind::Type {..} => {
995 trait_ref.substs[param.index as usize]
1001 // the trait type may have higher-ranked lifetimes in it;
1002 // so erase them if they appear, so that we get the type
1003 // at some particular call site
1004 let substs = tcx.normalize_erasing_late_bound_regions(
1005 ty::ParamEnv::reveal_all(),
1009 // It's possible that the method relies on where clauses that
1010 // do not hold for this particular set of type parameters.
1011 // Note that this method could then never be called, so we
1012 // do not want to try and codegen it, in that case (see #23435).
1013 let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs);
1014 if !normalize_and_test_predicates(tcx, predicates.predicates) {
1015 debug!("vtable_methods: predicates do not hold");
1019 Some((def_id, substs))
1025 impl<'tcx,O> Obligation<'tcx,O> {
1026 pub fn new(cause: ObligationCause<'tcx>,
1027 param_env: ty::ParamEnv<'tcx>,
1029 -> Obligation<'tcx, O>
1031 Obligation { cause, param_env, recursion_depth: 0, predicate }
1034 fn with_depth(cause: ObligationCause<'tcx>,
1035 recursion_depth: usize,
1036 param_env: ty::ParamEnv<'tcx>,
1038 -> Obligation<'tcx, O>
1040 Obligation { cause, param_env, recursion_depth, predicate }
1043 pub fn misc(span: Span,
1044 body_id: ast::NodeId,
1045 param_env: ty::ParamEnv<'tcx>,
1047 -> Obligation<'tcx, O> {
1048 Obligation::new(ObligationCause::misc(span, body_id), param_env, trait_ref)
1051 pub fn with<P>(&self, value: P) -> Obligation<'tcx,P> {
1052 Obligation { cause: self.cause.clone(),
1053 param_env: self.param_env,
1054 recursion_depth: self.recursion_depth,
1059 impl<'tcx> ObligationCause<'tcx> {
1061 pub fn new(span: Span,
1062 body_id: ast::NodeId,
1063 code: ObligationCauseCode<'tcx>)
1064 -> ObligationCause<'tcx> {
1065 ObligationCause { span: span, body_id: body_id, code: code }
1068 pub fn misc(span: Span, body_id: ast::NodeId) -> ObligationCause<'tcx> {
1069 ObligationCause { span: span, body_id: body_id, code: MiscObligation }
1072 pub fn dummy() -> ObligationCause<'tcx> {
1073 ObligationCause { span: DUMMY_SP, body_id: ast::CRATE_NODE_ID, code: MiscObligation }
1077 impl<'tcx, N> Vtable<'tcx, N> {
1078 pub fn nested_obligations(self) -> Vec<N> {
1080 VtableImpl(i) => i.nested,
1081 VtableParam(n) => n,
1082 VtableBuiltin(i) => i.nested,
1083 VtableAutoImpl(d) => d.nested,
1084 VtableClosure(c) => c.nested,
1085 VtableGenerator(c) => c.nested,
1086 VtableObject(d) => d.nested,
1087 VtableFnPointer(d) => d.nested,
1088 VtableTraitAlias(d) => d.nested,
1092 pub fn map<M, F>(self, f: F) -> Vtable<'tcx, M> where F: FnMut(N) -> M {
1094 VtableImpl(i) => VtableImpl(VtableImplData {
1095 impl_def_id: i.impl_def_id,
1097 nested: i.nested.into_iter().map(f).collect(),
1099 VtableParam(n) => VtableParam(n.into_iter().map(f).collect()),
1100 VtableBuiltin(i) => VtableBuiltin(VtableBuiltinData {
1101 nested: i.nested.into_iter().map(f).collect(),
1103 VtableObject(o) => VtableObject(VtableObjectData {
1104 upcast_trait_ref: o.upcast_trait_ref,
1105 vtable_base: o.vtable_base,
1106 nested: o.nested.into_iter().map(f).collect(),
1108 VtableAutoImpl(d) => VtableAutoImpl(VtableAutoImplData {
1109 trait_def_id: d.trait_def_id,
1110 nested: d.nested.into_iter().map(f).collect(),
1112 VtableClosure(c) => VtableClosure(VtableClosureData {
1113 closure_def_id: c.closure_def_id,
1115 nested: c.nested.into_iter().map(f).collect(),
1117 VtableGenerator(c) => VtableGenerator(VtableGeneratorData {
1118 generator_def_id: c.generator_def_id,
1120 nested: c.nested.into_iter().map(f).collect(),
1122 VtableFnPointer(p) => VtableFnPointer(VtableFnPointerData {
1124 nested: p.nested.into_iter().map(f).collect(),
1126 VtableTraitAlias(d) => VtableTraitAlias(VtableTraitAliasData {
1127 alias_def_id: d.alias_def_id,
1129 nested: d.nested.into_iter().map(f).collect(),
1135 impl<'tcx> FulfillmentError<'tcx> {
1136 fn new(obligation: PredicateObligation<'tcx>,
1137 code: FulfillmentErrorCode<'tcx>)
1138 -> FulfillmentError<'tcx>
1140 FulfillmentError { obligation: obligation, code: code }
1144 impl<'tcx> TraitObligation<'tcx> {
1145 fn self_ty(&self) -> ty::Binder<Ty<'tcx>> {
1146 self.predicate.map_bound(|p| p.self_ty())
1150 pub fn provide(providers: &mut ty::query::Providers<'_>) {
1151 *providers = ty::query::Providers {
1152 is_object_safe: object_safety::is_object_safe_provider,
1153 specialization_graph_of: specialize::specialization_graph_provider,
1154 specializes: specialize::specializes,
1155 codegen_fulfill_obligation: codegen::codegen_fulfill_obligation,
1157 substitute_normalize_and_test_predicates,
1162 pub trait ExClauseFold<'tcx>
1164 Self: chalk_engine::context::Context + Clone,
1166 fn fold_ex_clause_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(
1167 ex_clause: &chalk_engine::ExClause<Self>,
1169 ) -> chalk_engine::ExClause<Self>;
1171 fn visit_ex_clause_with<'gcx: 'tcx, V: TypeVisitor<'tcx>>(
1172 ex_clause: &chalk_engine::ExClause<Self>,
1177 pub trait ExClauseLift<'tcx>
1179 Self: chalk_engine::context::Context + Clone,
1181 type LiftedExClause: Debug + 'tcx;
1183 fn lift_ex_clause_to_tcx<'a, 'gcx>(
1184 ex_clause: &chalk_engine::ExClause<Self>,
1185 tcx: TyCtxt<'a, 'gcx, 'tcx>,
1186 ) -> Option<Self::LiftedExClause>;