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 mir::interpret::ConstEvalErr;
27 use ty::subst::Substs;
28 use ty::{self, AdtKind, List, Ty, TyCtxt, GenericParamDefKind, ToPredicate};
29 use ty::error::{ExpectedFound, TypeError};
30 use ty::fold::{TypeFolder, TypeFoldable, TypeVisitor};
31 use infer::{InferCtxt};
32 use util::common::ErrorReported;
34 use rustc_data_structures::sync::Lrc;
38 use syntax_pos::{Span, DUMMY_SP};
40 pub use self::coherence::{orphan_check, overlapping_impls, OrphanCheckErr, OverlapResult};
41 pub use self::fulfill::{FulfillmentContext, PendingPredicateObligation};
42 pub use self::project::MismatchedProjectionTypes;
43 pub use self::project::{normalize, normalize_projection_type, poly_project_and_unify_type};
44 pub use self::project::{ProjectionCache, ProjectionCacheSnapshot, Reveal, Normalized};
45 pub use self::object_safety::ObjectSafetyViolation;
46 pub use self::object_safety::MethodViolationCode;
47 pub use self::on_unimplemented::{OnUnimplementedDirective, OnUnimplementedNote};
48 pub use self::select::{EvaluationCache, SelectionContext, SelectionCache};
49 pub use self::select::{EvaluationResult, IntercrateAmbiguityCause, OverflowError};
50 pub use self::specialize::{OverlapError, specialization_graph, translate_substs};
51 pub use self::specialize::{SpecializesCache, find_associated_item};
52 pub use self::engine::{TraitEngine, TraitEngineExt};
53 pub use self::util::elaborate_predicates;
54 pub use self::util::supertraits;
55 pub use self::util::Supertraits;
56 pub use self::util::supertrait_def_ids;
57 pub use self::util::SupertraitDefIds;
58 pub use self::util::transitive_bounds;
63 pub mod error_reporting;
77 // Whether to enable bug compatibility with issue #43355
78 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
79 pub enum IntercrateMode {
84 // The mode that trait queries run in
85 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
86 pub enum TraitQueryMode {
87 // Standard/un-canonicalized queries get accurate
88 // spans etc. passed in and hence can do reasonable
89 // error reporting on their own.
91 // Canonicalized queries get dummy spans and hence
92 // must generally propagate errors to
93 // pre-canonicalization callsites.
97 /// An `Obligation` represents some trait reference (e.g. `int:Eq`) for
98 /// which the vtable must be found. The process of finding a vtable is
99 /// called "resolving" the `Obligation`. This process consists of
100 /// either identifying an `impl` (e.g., `impl Eq for int`) that
101 /// provides the required vtable, or else finding a bound that is in
102 /// scope. The eventual result is usually a `Selection` (defined below).
103 #[derive(Clone, PartialEq, Eq, Hash)]
104 pub struct Obligation<'tcx, T> {
105 /// Why do we have to prove this thing?
106 pub cause: ObligationCause<'tcx>,
108 /// In which environment should we prove this thing?
109 pub param_env: ty::ParamEnv<'tcx>,
111 /// What are we trying to prove?
114 /// If we started proving this as a result of trying to prove
115 /// something else, track the total depth to ensure termination.
116 /// If this goes over a certain threshold, we abort compilation --
117 /// in such cases, we can not say whether or not the predicate
118 /// holds for certain. Stupid halting problem. Such a drag.
119 pub recursion_depth: usize,
122 pub type PredicateObligation<'tcx> = Obligation<'tcx, ty::Predicate<'tcx>>;
123 pub type TraitObligation<'tcx> = Obligation<'tcx, ty::PolyTraitPredicate<'tcx>>;
125 /// Why did we incur this obligation? Used for error reporting.
126 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
127 pub struct ObligationCause<'tcx> {
130 // The id of the fn body that triggered this obligation. This is
131 // used for region obligations to determine the precise
132 // environment in which the region obligation should be evaluated
133 // (in particular, closures can add new assumptions). See the
134 // field `region_obligations` of the `FulfillmentContext` for more
136 pub body_id: ast::NodeId,
138 pub code: ObligationCauseCode<'tcx>
141 impl<'tcx> ObligationCause<'tcx> {
142 pub fn span<'a, 'gcx>(&self, tcx: &TyCtxt<'a, 'gcx, 'tcx>) -> Span {
144 ObligationCauseCode::CompareImplMethodObligation { .. } |
145 ObligationCauseCode::MainFunctionType |
146 ObligationCauseCode::StartFunctionType => {
147 tcx.sess.source_map().def_span(self.span)
154 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
155 pub enum ObligationCauseCode<'tcx> {
156 /// Not well classified or should be obvious from span.
159 /// A slice or array is WF only if `T: Sized`
162 /// A tuple is WF only if its middle elements are Sized
165 /// This is the trait reference from the given projection
166 ProjectionWf(ty::ProjectionTy<'tcx>),
168 /// In an impl of trait X for type Y, type Y must
169 /// also implement all supertraits of X.
170 ItemObligation(DefId),
172 /// A type like `&'a T` is WF only if `T: 'a`.
173 ReferenceOutlivesReferent(Ty<'tcx>),
175 /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
176 ObjectTypeBound(Ty<'tcx>, ty::Region<'tcx>),
178 /// Obligation incurred due to an object cast.
179 ObjectCastObligation(/* Object type */ Ty<'tcx>),
181 // Various cases where expressions must be sized/copy/etc:
182 /// L = X implies that L is Sized
184 /// (x1, .., xn) must be Sized
185 TupleInitializerSized,
186 /// S { ... } must be Sized
187 StructInitializerSized,
188 /// Type of each variable must be Sized
189 VariableType(ast::NodeId),
190 /// Argument type must be Sized
192 /// Return type must be Sized
194 /// Yield type must be Sized
196 /// [T,..n] --> T must be Copy
199 /// Types of fields (other than the last, except for packed structs) in a struct must be sized.
200 FieldSized { adt_kind: AdtKind, last: bool },
202 /// Constant expressions must be sized.
205 /// static items must have `Sync` type
208 BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
210 ImplDerivedObligation(DerivedObligationCause<'tcx>),
212 /// error derived when matching traits/impls; see ObligationCause for more details
213 CompareImplMethodObligation {
214 item_name: ast::Name,
215 impl_item_def_id: DefId,
216 trait_item_def_id: DefId,
219 /// Checking that this expression can be assigned where it needs to be
220 // FIXME(eddyb) #11161 is the original Expr required?
223 /// Computing common supertype in the arms of a match expression
224 MatchExpressionArm { arm_span: Span,
225 source: hir::MatchSource },
227 /// Computing common supertype in an if expression
230 /// Computing common supertype of an if expression with no else counter-part
231 IfExpressionWithNoElse,
233 /// `main` has wrong type
236 /// `start` has wrong type
239 /// intrinsic has wrong type
245 /// `return` with no expression
248 /// `return` with an expression
249 ReturnType(ast::NodeId),
251 /// Block implicit return
252 BlockTailExpression(ast::NodeId),
254 /// #[feature(trivial_bounds)] is not enabled
258 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
259 pub struct DerivedObligationCause<'tcx> {
260 /// The trait reference of the parent obligation that led to the
261 /// current obligation. Note that only trait obligations lead to
262 /// derived obligations, so we just store the trait reference here
264 parent_trait_ref: ty::PolyTraitRef<'tcx>,
266 /// The parent trait had this cause
267 parent_code: Rc<ObligationCauseCode<'tcx>>
270 pub type Obligations<'tcx, O> = Vec<Obligation<'tcx, O>>;
271 pub type PredicateObligations<'tcx> = Vec<PredicateObligation<'tcx>>;
272 pub type TraitObligations<'tcx> = Vec<TraitObligation<'tcx>>;
274 /// The following types:
281 /// are used for representing the trait system in the form of
282 /// logic programming clauses. They are part of the interface
283 /// for the chalk SLG solver.
284 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
285 pub enum WhereClause<'tcx> {
286 Implemented(ty::TraitPredicate<'tcx>),
287 ProjectionEq(ty::ProjectionPredicate<'tcx>),
288 RegionOutlives(ty::RegionOutlivesPredicate<'tcx>),
289 TypeOutlives(ty::TypeOutlivesPredicate<'tcx>),
292 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
293 pub enum WellFormed<'tcx> {
294 Trait(ty::TraitPredicate<'tcx>),
298 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
299 pub enum FromEnv<'tcx> {
300 Trait(ty::TraitPredicate<'tcx>),
304 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
305 pub enum DomainGoal<'tcx> {
306 Holds(WhereClause<'tcx>),
307 WellFormed(WellFormed<'tcx>),
308 FromEnv(FromEnv<'tcx>),
309 Normalize(ty::ProjectionPredicate<'tcx>),
312 pub type PolyDomainGoal<'tcx> = ty::Binder<DomainGoal<'tcx>>;
314 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
315 pub enum QuantifierKind {
320 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
321 pub enum GoalKind<'tcx> {
322 Implies(Clauses<'tcx>, Goal<'tcx>),
323 And(Goal<'tcx>, Goal<'tcx>),
325 DomainGoal(DomainGoal<'tcx>),
326 Quantified(QuantifierKind, ty::Binder<Goal<'tcx>>),
330 pub type Goal<'tcx> = &'tcx GoalKind<'tcx>;
332 pub type Goals<'tcx> = &'tcx List<Goal<'tcx>>;
334 impl<'tcx> DomainGoal<'tcx> {
335 pub fn into_goal(self) -> GoalKind<'tcx> {
336 GoalKind::DomainGoal(self)
340 impl<'tcx> GoalKind<'tcx> {
341 pub fn from_poly_domain_goal<'a>(
342 domain_goal: PolyDomainGoal<'tcx>,
343 tcx: TyCtxt<'a, 'tcx, 'tcx>,
344 ) -> GoalKind<'tcx> {
345 match domain_goal.no_late_bound_regions() {
346 Some(p) => p.into_goal(),
347 None => GoalKind::Quantified(
348 QuantifierKind::Universal,
349 domain_goal.map_bound(|p| tcx.mk_goal(p.into_goal()))
355 /// This matches the definition from Page 7 of "A Proof Procedure for the Logic of Hereditary
356 /// Harrop Formulas".
357 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
358 pub enum Clause<'tcx> {
359 Implies(ProgramClause<'tcx>),
360 ForAll(ty::Binder<ProgramClause<'tcx>>),
363 /// Multiple clauses.
364 pub type Clauses<'tcx> = &'tcx List<Clause<'tcx>>;
366 /// A "program clause" has the form `D :- G1, ..., Gn`. It is saying
367 /// that the domain goal `D` is true if `G1...Gn` are provable. This
368 /// is equivalent to the implication `G1..Gn => D`; we usually write
369 /// it with the reverse implication operator `:-` to emphasize the way
370 /// that programs are actually solved (via backchaining, which starts
371 /// with the goal to solve and proceeds from there).
372 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
373 pub struct ProgramClause<'tcx> {
374 /// This goal will be considered true...
375 pub goal: DomainGoal<'tcx>,
377 /// ...if we can prove these hypotheses (there may be no hypotheses at all):
378 pub hypotheses: Goals<'tcx>,
381 pub type Selection<'tcx> = Vtable<'tcx, PredicateObligation<'tcx>>;
383 #[derive(Clone,Debug)]
384 pub enum SelectionError<'tcx> {
386 OutputTypeParameterMismatch(ty::PolyTraitRef<'tcx>,
387 ty::PolyTraitRef<'tcx>,
388 ty::error::TypeError<'tcx>),
389 TraitNotObjectSafe(DefId),
390 ConstEvalFailure(Lrc<ConstEvalErr<'tcx>>),
394 pub struct FulfillmentError<'tcx> {
395 pub obligation: PredicateObligation<'tcx>,
396 pub code: FulfillmentErrorCode<'tcx>
400 pub enum FulfillmentErrorCode<'tcx> {
401 CodeSelectionError(SelectionError<'tcx>),
402 CodeProjectionError(MismatchedProjectionTypes<'tcx>),
403 CodeSubtypeError(ExpectedFound<Ty<'tcx>>,
404 TypeError<'tcx>), // always comes from a SubtypePredicate
408 /// When performing resolution, it is typically the case that there
409 /// can be one of three outcomes:
411 /// - `Ok(Some(r))`: success occurred with result `r`
412 /// - `Ok(None)`: could not definitely determine anything, usually due
413 /// to inconclusive type inference.
414 /// - `Err(e)`: error `e` occurred
415 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
417 /// Given the successful resolution of an obligation, the `Vtable`
418 /// indicates where the vtable comes from. Note that while we call this
419 /// a "vtable", it does not necessarily indicate dynamic dispatch at
420 /// runtime. `Vtable` instances just tell the compiler where to find
421 /// methods, but in generic code those methods are typically statically
422 /// dispatched -- only when an object is constructed is a `Vtable`
423 /// instance reified into an actual vtable.
425 /// For example, the vtable may be tied to a specific impl (case A),
426 /// or it may be relative to some bound that is in scope (case B).
430 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
431 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
432 /// impl Clone for int { ... } // Impl_3
434 /// fn foo<T:Clone>(concrete: Option<Box<int>>,
436 /// mixed: Option<T>) {
438 /// // Case A: Vtable points at a specific impl. Only possible when
439 /// // type is concretely known. If the impl itself has bounded
440 /// // type parameters, Vtable will carry resolutions for those as well:
441 /// concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
443 /// // Case B: Vtable must be provided by caller. This applies when
444 /// // type is a type parameter.
445 /// param.clone(); // VtableParam
447 /// // Case C: A mix of cases A and B.
448 /// mixed.clone(); // Vtable(Impl_1, [VtableParam])
452 /// ### The type parameter `N`
454 /// See explanation on `VtableImplData`.
455 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
456 pub enum Vtable<'tcx, N> {
457 /// Vtable identifying a particular impl.
458 VtableImpl(VtableImplData<'tcx, N>),
460 /// Vtable for auto trait implementations
461 /// This carries the information and nested obligations with regards
462 /// to an auto implementation for a trait `Trait`. The nested obligations
463 /// ensure the trait implementation holds for all the constituent types.
464 VtableAutoImpl(VtableAutoImplData<N>),
466 /// Successful resolution to an obligation provided by the caller
467 /// for some type parameter. The `Vec<N>` represents the
468 /// obligations incurred from normalizing the where-clause (if
472 /// Virtual calls through an object
473 VtableObject(VtableObjectData<'tcx, N>),
475 /// Successful resolution for a builtin trait.
476 VtableBuiltin(VtableBuiltinData<N>),
478 /// Vtable automatically generated for a closure. The def ID is the ID
479 /// of the closure expression. This is a `VtableImpl` in spirit, but the
480 /// impl is generated by the compiler and does not appear in the source.
481 VtableClosure(VtableClosureData<'tcx, N>),
483 /// Same as above, but for a fn pointer type with the given signature.
484 VtableFnPointer(VtableFnPointerData<'tcx, N>),
486 /// Vtable automatically generated for a generator
487 VtableGenerator(VtableGeneratorData<'tcx, N>),
490 /// Identifies a particular impl in the source, along with a set of
491 /// substitutions from the impl's type/lifetime parameters. The
492 /// `nested` vector corresponds to the nested obligations attached to
493 /// the impl's type parameters.
495 /// The type parameter `N` indicates the type used for "nested
496 /// obligations" that are required by the impl. During type check, this
497 /// is `Obligation`, as one might expect. During codegen, however, this
498 /// is `()`, because codegen only requires a shallow resolution of an
499 /// impl, and nested obligations are satisfied later.
500 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
501 pub struct VtableImplData<'tcx, N> {
502 pub impl_def_id: DefId,
503 pub substs: &'tcx Substs<'tcx>,
507 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
508 pub struct VtableGeneratorData<'tcx, N> {
509 pub generator_def_id: DefId,
510 pub substs: ty::GeneratorSubsts<'tcx>,
511 /// Nested obligations. This can be non-empty if the generator
512 /// signature contains associated types.
516 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
517 pub struct VtableClosureData<'tcx, N> {
518 pub closure_def_id: DefId,
519 pub substs: ty::ClosureSubsts<'tcx>,
520 /// Nested obligations. This can be non-empty if the closure
521 /// signature contains associated types.
525 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
526 pub struct VtableAutoImplData<N> {
527 pub trait_def_id: DefId,
531 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
532 pub struct VtableBuiltinData<N> {
536 /// A vtable for some object-safe trait `Foo` automatically derived
537 /// for the object type `Foo`.
538 #[derive(PartialEq, Eq, Clone, RustcEncodable, RustcDecodable)]
539 pub struct VtableObjectData<'tcx, N> {
540 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
541 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
543 /// The vtable is formed by concatenating together the method lists of
544 /// the base object trait and all supertraits; this is the start of
545 /// `upcast_trait_ref`'s methods in that vtable.
546 pub vtable_base: usize,
551 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
552 pub struct VtableFnPointerData<'tcx, N> {
557 /// Creates predicate obligations from the generic bounds.
558 pub fn predicates_for_generics<'tcx>(cause: ObligationCause<'tcx>,
559 param_env: ty::ParamEnv<'tcx>,
560 generic_bounds: &ty::InstantiatedPredicates<'tcx>)
561 -> PredicateObligations<'tcx>
563 util::predicates_for_generics(cause, 0, param_env, generic_bounds)
566 /// Determines whether the type `ty` is known to meet `bound` and
567 /// returns true if so. Returns false if `ty` either does not meet
568 /// `bound` or is not known to meet bound (note that this is
569 /// conservative towards *no impl*, which is the opposite of the
570 /// `evaluate` methods).
571 pub fn type_known_to_meet_bound<'a, 'gcx, 'tcx>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
572 param_env: ty::ParamEnv<'tcx>,
578 debug!("type_known_to_meet_bound(ty={:?}, bound={:?})",
580 infcx.tcx.item_path_str(def_id));
582 let trait_ref = ty::TraitRef {
584 substs: infcx.tcx.mk_substs_trait(ty, &[]),
586 let obligation = Obligation {
588 cause: ObligationCause::misc(span, ast::DUMMY_NODE_ID),
590 predicate: trait_ref.to_predicate(),
593 let result = infcx.predicate_must_hold(&obligation);
594 debug!("type_known_to_meet_ty={:?} bound={} => {:?}",
595 ty, infcx.tcx.item_path_str(def_id), result);
597 if result && (ty.has_infer_types() || ty.has_closure_types()) {
598 // Because of inference "guessing", selection can sometimes claim
599 // to succeed while the success requires a guess. To ensure
600 // this function's result remains infallible, we must confirm
601 // that guess. While imperfect, I believe this is sound.
603 // The handling of regions in this area of the code is terrible,
604 // see issue #29149. We should be able to improve on this with
606 let mut fulfill_cx = FulfillmentContext::new_ignoring_regions();
608 // We can use a dummy node-id here because we won't pay any mind
609 // to region obligations that arise (there shouldn't really be any
611 let cause = ObligationCause::misc(span, ast::DUMMY_NODE_ID);
613 fulfill_cx.register_bound(infcx, param_env, ty, def_id, cause);
615 // Note: we only assume something is `Copy` if we can
616 // *definitively* show that it implements `Copy`. Otherwise,
617 // assume it is move; linear is always ok.
618 match fulfill_cx.select_all_or_error(infcx) {
620 debug!("type_known_to_meet_bound: ty={:?} bound={} success",
622 infcx.tcx.item_path_str(def_id));
626 debug!("type_known_to_meet_bound: ty={:?} bound={} errors={:?}",
628 infcx.tcx.item_path_str(def_id),
638 fn do_normalize_predicates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
639 region_context: DefId,
640 cause: ObligationCause<'tcx>,
641 elaborated_env: ty::ParamEnv<'tcx>,
642 predicates: Vec<ty::Predicate<'tcx>>)
643 -> Result<Vec<ty::Predicate<'tcx>>, ErrorReported>
645 debug!("do_normalize_predicates({:?})", predicates);
646 let span = cause.span;
647 tcx.infer_ctxt().enter(|infcx| {
648 // FIXME. We should really... do something with these region
649 // obligations. But this call just continues the older
650 // behavior (i.e., doesn't cause any new bugs), and it would
651 // take some further refactoring to actually solve them. In
652 // particular, we would have to handle implied bounds
653 // properly, and that code is currently largely confined to
654 // regionck (though I made some efforts to extract it
657 // @arielby: In any case, these obligations are checked
658 // by wfcheck anyway, so I'm not sure we have to check
659 // them here too, and we will remove this function when
660 // we move over to lazy normalization *anyway*.
661 let fulfill_cx = FulfillmentContext::new_ignoring_regions();
662 let predicates = match fully_normalize(
669 Ok(predicates) => predicates,
671 infcx.report_fulfillment_errors(&errors, None, false);
672 return Err(ErrorReported)
676 debug!("do_normalize_predictes: normalized predicates = {:?}", predicates);
678 let region_scope_tree = region::ScopeTree::default();
680 // We can use the `elaborated_env` here; the region code only
681 // cares about declarations like `'a: 'b`.
682 let outlives_env = OutlivesEnvironment::new(elaborated_env);
684 infcx.resolve_regions_and_report_errors(
688 SuppressRegionErrors::default(),
691 let predicates = match infcx.fully_resolve(&predicates) {
692 Ok(predicates) => predicates,
694 // If we encounter a fixup error, it means that some type
695 // variable wound up unconstrained. I actually don't know
696 // if this can happen, and I certainly don't expect it to
697 // happen often, but if it did happen it probably
698 // represents a legitimate failure due to some kind of
699 // unconstrained variable, and it seems better not to ICE,
700 // all things considered.
701 tcx.sess.span_err(span, &fixup_err.to_string());
702 return Err(ErrorReported)
706 match tcx.lift_to_global(&predicates) {
707 Some(predicates) => Ok(predicates),
709 // FIXME: shouldn't we, you know, actually report an error here? or an ICE?
716 // FIXME: this is gonna need to be removed ...
717 /// Normalizes the parameter environment, reporting errors if they occur.
718 pub fn normalize_param_env_or_error<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
719 region_context: DefId,
720 unnormalized_env: ty::ParamEnv<'tcx>,
721 cause: ObligationCause<'tcx>)
722 -> ty::ParamEnv<'tcx>
724 // I'm not wild about reporting errors here; I'd prefer to
725 // have the errors get reported at a defined place (e.g.,
726 // during typeck). Instead I have all parameter
727 // environments, in effect, going through this function
728 // and hence potentially reporting errors. This ensures of
729 // course that we never forget to normalize (the
730 // alternative seemed like it would involve a lot of
731 // manual invocations of this fn -- and then we'd have to
732 // deal with the errors at each of those sites).
734 // In any case, in practice, typeck constructs all the
735 // parameter environments once for every fn as it goes,
736 // and errors will get reported then; so after typeck we
737 // can be sure that no errors should occur.
739 debug!("normalize_param_env_or_error(region_context={:?}, unnormalized_env={:?}, cause={:?})",
740 region_context, unnormalized_env, cause);
742 let mut predicates: Vec<_> =
743 util::elaborate_predicates(tcx, unnormalized_env.caller_bounds.to_vec())
746 debug!("normalize_param_env_or_error: elaborated-predicates={:?}",
749 let elaborated_env = ty::ParamEnv::new(tcx.intern_predicates(&predicates),
750 unnormalized_env.reveal);
752 // HACK: we are trying to normalize the param-env inside *itself*. The problem is that
753 // normalization expects its param-env to be already normalized, which means we have
756 // The way we handle this is by normalizing the param-env inside an unnormalized version
757 // of the param-env, which means that if the param-env contains unnormalized projections,
758 // we'll have some normalization failures. This is unfortunate.
760 // Lazy normalization would basically handle this by treating just the
761 // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
763 // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
764 // types, so to make the situation less bad, we normalize all the predicates *but*
765 // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
766 // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
768 // This works fairly well because trait matching does not actually care about param-env
769 // TypeOutlives predicates - these are normally used by regionck.
770 let outlives_predicates: Vec<_> = predicates.drain_filter(|predicate| {
772 ty::Predicate::TypeOutlives(..) => true,
777 debug!("normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
778 predicates, outlives_predicates);
779 let non_outlives_predicates =
780 match do_normalize_predicates(tcx, region_context, cause.clone(),
781 elaborated_env, predicates) {
782 Ok(predicates) => predicates,
783 // An unnormalized env is better than nothing.
784 Err(ErrorReported) => {
785 debug!("normalize_param_env_or_error: errored resolving non-outlives predicates");
786 return elaborated_env
790 debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates);
792 // Not sure whether it is better to include the unnormalized TypeOutlives predicates
793 // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
794 // predicates here anyway. Keeping them here anyway because it seems safer.
795 let outlives_env: Vec<_> =
796 non_outlives_predicates.iter().chain(&outlives_predicates).cloned().collect();
797 let outlives_env = ty::ParamEnv::new(tcx.intern_predicates(&outlives_env),
798 unnormalized_env.reveal);
799 let outlives_predicates =
800 match do_normalize_predicates(tcx, region_context, cause,
801 outlives_env, outlives_predicates) {
802 Ok(predicates) => predicates,
803 // An unnormalized env is better than nothing.
804 Err(ErrorReported) => {
805 debug!("normalize_param_env_or_error: errored resolving outlives predicates");
806 return elaborated_env
809 debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates);
811 let mut predicates = non_outlives_predicates;
812 predicates.extend(outlives_predicates);
813 debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
814 ty::ParamEnv::new(tcx.intern_predicates(&predicates), unnormalized_env.reveal)
817 pub fn fully_normalize<'a, 'gcx, 'tcx, T>(
818 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
819 mut fulfill_cx: FulfillmentContext<'tcx>,
820 cause: ObligationCause<'tcx>,
821 param_env: ty::ParamEnv<'tcx>,
823 -> Result<T, Vec<FulfillmentError<'tcx>>>
824 where T : TypeFoldable<'tcx>
826 debug!("fully_normalize_with_fulfillcx(value={:?})", value);
827 let selcx = &mut SelectionContext::new(infcx);
828 let Normalized { value: normalized_value, obligations } =
829 project::normalize(selcx, param_env, cause, value);
830 debug!("fully_normalize: normalized_value={:?} obligations={:?}",
833 for obligation in obligations {
834 fulfill_cx.register_predicate_obligation(selcx.infcx(), obligation);
837 debug!("fully_normalize: select_all_or_error start");
838 fulfill_cx.select_all_or_error(infcx)?;
839 debug!("fully_normalize: select_all_or_error complete");
840 let resolved_value = infcx.resolve_type_vars_if_possible(&normalized_value);
841 debug!("fully_normalize: resolved_value={:?}", resolved_value);
845 /// Normalizes the predicates and checks whether they hold in an empty
846 /// environment. If this returns false, then either normalize
847 /// encountered an error or one of the predicates did not hold. Used
848 /// when creating vtables to check for unsatisfiable methods.
849 fn normalize_and_test_predicates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
850 predicates: Vec<ty::Predicate<'tcx>>)
853 debug!("normalize_and_test_predicates(predicates={:?})",
856 let result = tcx.infer_ctxt().enter(|infcx| {
857 let param_env = ty::ParamEnv::reveal_all();
858 let mut selcx = SelectionContext::new(&infcx);
859 let mut fulfill_cx = FulfillmentContext::new();
860 let cause = ObligationCause::dummy();
861 let Normalized { value: predicates, obligations } =
862 normalize(&mut selcx, param_env, cause.clone(), &predicates);
863 for obligation in obligations {
864 fulfill_cx.register_predicate_obligation(&infcx, obligation);
866 for predicate in predicates {
867 let obligation = Obligation::new(cause.clone(), param_env, predicate);
868 fulfill_cx.register_predicate_obligation(&infcx, obligation);
871 fulfill_cx.select_all_or_error(&infcx).is_ok()
873 debug!("normalize_and_test_predicates(predicates={:?}) = {:?}",
878 fn substitute_normalize_and_test_predicates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
879 key: (DefId, &'tcx Substs<'tcx>))
882 debug!("substitute_normalize_and_test_predicates(key={:?})",
885 let predicates = tcx.predicates_of(key.0).instantiate(tcx, key.1).predicates;
886 let result = normalize_and_test_predicates(tcx, predicates);
888 debug!("substitute_normalize_and_test_predicates(key={:?}) = {:?}",
893 /// Given a trait `trait_ref`, iterates the vtable entries
894 /// that come from `trait_ref`, including its supertraits.
895 #[inline] // FIXME(#35870) Avoid closures being unexported due to impl Trait.
896 fn vtable_methods<'a, 'tcx>(
897 tcx: TyCtxt<'a, 'tcx, 'tcx>,
898 trait_ref: ty::PolyTraitRef<'tcx>)
899 -> Lrc<Vec<Option<(DefId, &'tcx Substs<'tcx>)>>>
901 debug!("vtable_methods({:?})", trait_ref);
904 supertraits(tcx, trait_ref).flat_map(move |trait_ref| {
905 let trait_methods = tcx.associated_items(trait_ref.def_id())
906 .filter(|item| item.kind == ty::AssociatedKind::Method);
908 // Now list each method's DefId and Substs (for within its trait).
909 // If the method can never be called from this object, produce None.
910 trait_methods.map(move |trait_method| {
911 debug!("vtable_methods: trait_method={:?}", trait_method);
912 let def_id = trait_method.def_id;
914 // Some methods cannot be called on an object; skip those.
915 if !tcx.is_vtable_safe_method(trait_ref.def_id(), &trait_method) {
916 debug!("vtable_methods: not vtable safe");
920 // the method may have some early-bound lifetimes, add
922 let substs = trait_ref.map_bound(|trait_ref|
923 Substs::for_item(tcx, def_id, |param, _|
925 GenericParamDefKind::Lifetime => tcx.types.re_erased.into(),
926 GenericParamDefKind::Type {..} => {
927 trait_ref.substs[param.index as usize]
933 // the trait type may have higher-ranked lifetimes in it;
934 // so erase them if they appear, so that we get the type
935 // at some particular call site
936 let substs = tcx.normalize_erasing_late_bound_regions(
937 ty::ParamEnv::reveal_all(),
941 // It's possible that the method relies on where clauses that
942 // do not hold for this particular set of type parameters.
943 // Note that this method could then never be called, so we
944 // do not want to try and codegen it, in that case (see #23435).
945 let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs);
946 if !normalize_and_test_predicates(tcx, predicates.predicates) {
947 debug!("vtable_methods: predicates do not hold");
951 Some((def_id, substs))
957 impl<'tcx,O> Obligation<'tcx,O> {
958 pub fn new(cause: ObligationCause<'tcx>,
959 param_env: ty::ParamEnv<'tcx>,
961 -> Obligation<'tcx, O>
963 Obligation { cause, param_env, recursion_depth: 0, predicate }
966 fn with_depth(cause: ObligationCause<'tcx>,
967 recursion_depth: usize,
968 param_env: ty::ParamEnv<'tcx>,
970 -> Obligation<'tcx, O>
972 Obligation { cause, param_env, recursion_depth, predicate }
975 pub fn misc(span: Span,
976 body_id: ast::NodeId,
977 param_env: ty::ParamEnv<'tcx>,
979 -> Obligation<'tcx, O> {
980 Obligation::new(ObligationCause::misc(span, body_id), param_env, trait_ref)
983 pub fn with<P>(&self, value: P) -> Obligation<'tcx,P> {
984 Obligation { cause: self.cause.clone(),
985 param_env: self.param_env,
986 recursion_depth: self.recursion_depth,
991 impl<'tcx> ObligationCause<'tcx> {
992 pub fn new(span: Span,
993 body_id: ast::NodeId,
994 code: ObligationCauseCode<'tcx>)
995 -> ObligationCause<'tcx> {
996 ObligationCause { span: span, body_id: body_id, code: code }
999 pub fn misc(span: Span, body_id: ast::NodeId) -> ObligationCause<'tcx> {
1000 ObligationCause { span: span, body_id: body_id, code: MiscObligation }
1003 pub fn dummy() -> ObligationCause<'tcx> {
1004 ObligationCause { span: DUMMY_SP, body_id: ast::CRATE_NODE_ID, code: MiscObligation }
1008 impl<'tcx, N> Vtable<'tcx, N> {
1009 pub fn nested_obligations(self) -> Vec<N> {
1011 VtableImpl(i) => i.nested,
1012 VtableParam(n) => n,
1013 VtableBuiltin(i) => i.nested,
1014 VtableAutoImpl(d) => d.nested,
1015 VtableClosure(c) => c.nested,
1016 VtableGenerator(c) => c.nested,
1017 VtableObject(d) => d.nested,
1018 VtableFnPointer(d) => d.nested,
1022 pub fn map<M, F>(self, f: F) -> Vtable<'tcx, M> where F: FnMut(N) -> M {
1024 VtableImpl(i) => VtableImpl(VtableImplData {
1025 impl_def_id: i.impl_def_id,
1027 nested: i.nested.into_iter().map(f).collect(),
1029 VtableParam(n) => VtableParam(n.into_iter().map(f).collect()),
1030 VtableBuiltin(i) => VtableBuiltin(VtableBuiltinData {
1031 nested: i.nested.into_iter().map(f).collect(),
1033 VtableObject(o) => VtableObject(VtableObjectData {
1034 upcast_trait_ref: o.upcast_trait_ref,
1035 vtable_base: o.vtable_base,
1036 nested: o.nested.into_iter().map(f).collect(),
1038 VtableAutoImpl(d) => VtableAutoImpl(VtableAutoImplData {
1039 trait_def_id: d.trait_def_id,
1040 nested: d.nested.into_iter().map(f).collect(),
1042 VtableFnPointer(p) => VtableFnPointer(VtableFnPointerData {
1044 nested: p.nested.into_iter().map(f).collect(),
1046 VtableGenerator(c) => VtableGenerator(VtableGeneratorData {
1047 generator_def_id: c.generator_def_id,
1049 nested: c.nested.into_iter().map(f).collect(),
1051 VtableClosure(c) => VtableClosure(VtableClosureData {
1052 closure_def_id: c.closure_def_id,
1054 nested: c.nested.into_iter().map(f).collect(),
1060 impl<'tcx> FulfillmentError<'tcx> {
1061 fn new(obligation: PredicateObligation<'tcx>,
1062 code: FulfillmentErrorCode<'tcx>)
1063 -> FulfillmentError<'tcx>
1065 FulfillmentError { obligation: obligation, code: code }
1069 impl<'tcx> TraitObligation<'tcx> {
1070 fn self_ty(&self) -> ty::Binder<Ty<'tcx>> {
1071 self.predicate.map_bound(|p| p.self_ty())
1075 pub fn provide(providers: &mut ty::query::Providers<'_>) {
1076 *providers = ty::query::Providers {
1077 is_object_safe: object_safety::is_object_safe_provider,
1078 specialization_graph_of: specialize::specialization_graph_provider,
1079 specializes: specialize::specializes,
1080 codegen_fulfill_obligation: codegen::codegen_fulfill_obligation,
1082 substitute_normalize_and_test_predicates,
1087 pub trait ExClauseFold<'tcx>
1089 Self: chalk_engine::context::Context + Clone,
1091 fn fold_ex_clause_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(
1092 ex_clause: &chalk_engine::ExClause<Self>,
1094 ) -> chalk_engine::ExClause<Self>;
1096 fn visit_ex_clause_with<'gcx: 'tcx, V: TypeVisitor<'tcx>>(
1097 ex_clause: &chalk_engine::ExClause<Self>,
1102 pub trait ExClauseLift<'tcx>
1104 Self: chalk_engine::context::Context + Clone,
1106 type LiftedExClause: Debug + 'tcx;
1108 fn lift_ex_clause_to_tcx<'a, 'gcx>(
1109 ex_clause: &chalk_engine::ExClause<Self>,
1110 tcx: TyCtxt<'a, 'gcx, 'tcx>,
1111 ) -> Option<Self::LiftedExClause>;