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/trait-resolution.html
15 pub use self::SelectionError::*;
16 pub use self::FulfillmentErrorCode::*;
17 pub use self::Vtable::*;
18 pub use self::ObligationCauseCode::*;
21 use hir::def_id::DefId;
22 use infer::outlives::env::OutlivesEnvironment;
24 use middle::const_val::ConstEvalErr;
25 use ty::subst::Substs;
26 use ty::{self, AdtKind, Slice, Ty, TyCtxt, TypeFoldable, ToPredicate};
27 use ty::error::{ExpectedFound, TypeError};
28 use infer::{InferCtxt};
30 use rustc_data_structures::sync::Lrc;
33 use syntax_pos::{Span, DUMMY_SP};
35 pub use self::coherence::{orphan_check, overlapping_impls, OrphanCheckErr, OverlapResult};
36 pub use self::fulfill::{FulfillmentContext, PendingPredicateObligation};
37 pub use self::project::MismatchedProjectionTypes;
38 pub use self::project::{normalize, normalize_projection_type, poly_project_and_unify_type};
39 pub use self::project::{ProjectionCache, ProjectionCacheSnapshot, Reveal, Normalized};
40 pub use self::object_safety::ObjectSafetyViolation;
41 pub use self::object_safety::MethodViolationCode;
42 pub use self::on_unimplemented::{OnUnimplementedDirective, OnUnimplementedNote};
43 pub use self::select::{EvaluationCache, SelectionContext, SelectionCache};
44 pub use self::select::{EvaluationResult, IntercrateAmbiguityCause, OverflowError};
45 pub use self::specialize::{OverlapError, specialization_graph, translate_substs};
46 pub use self::specialize::{SpecializesCache, find_associated_item};
47 pub use self::engine::TraitEngine;
48 pub use self::util::elaborate_predicates;
49 pub use self::util::supertraits;
50 pub use self::util::Supertraits;
51 pub use self::util::supertrait_def_ids;
52 pub use self::util::SupertraitDefIds;
53 pub use self::util::transitive_bounds;
58 pub mod error_reporting;
72 // Whether to enable bug compatibility with issue #43355
73 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
74 pub enum IntercrateMode {
79 // The mode that trait queries run in
80 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
81 pub enum TraitQueryMode {
82 // Standard/un-canonicalized queries get accurate
83 // spans etc. passed in and hence can do reasonable
84 // error reporting on their own.
86 // Canonicalized queries get dummy spans and hence
87 // must generally propagate errors to
88 // pre-canonicalization callsites.
92 /// An `Obligation` represents some trait reference (e.g. `int:Eq`) for
93 /// which the vtable must be found. The process of finding a vtable is
94 /// called "resolving" the `Obligation`. This process consists of
95 /// either identifying an `impl` (e.g., `impl Eq for int`) that
96 /// provides the required vtable, or else finding a bound that is in
97 /// scope. The eventual result is usually a `Selection` (defined below).
98 #[derive(Clone, PartialEq, Eq, Hash)]
99 pub struct Obligation<'tcx, T> {
100 /// Why do we have to prove this thing?
101 pub cause: ObligationCause<'tcx>,
103 /// In which environment should we prove this thing?
104 pub param_env: ty::ParamEnv<'tcx>,
106 /// What are we trying to prove?
109 /// If we started proving this as a result of trying to prove
110 /// something else, track the total depth to ensure termination.
111 /// If this goes over a certain threshold, we abort compilation --
112 /// in such cases, we can not say whether or not the predicate
113 /// holds for certain. Stupid halting problem. Such a drag.
114 pub recursion_depth: usize,
117 pub type PredicateObligation<'tcx> = Obligation<'tcx, ty::Predicate<'tcx>>;
118 pub type TraitObligation<'tcx> = Obligation<'tcx, ty::PolyTraitPredicate<'tcx>>;
120 /// Why did we incur this obligation? Used for error reporting.
121 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
122 pub struct ObligationCause<'tcx> {
125 // The id of the fn body that triggered this obligation. This is
126 // used for region obligations to determine the precise
127 // environment in which the region obligation should be evaluated
128 // (in particular, closures can add new assumptions). See the
129 // field `region_obligations` of the `FulfillmentContext` for more
131 pub body_id: ast::NodeId,
133 pub code: ObligationCauseCode<'tcx>
136 impl<'tcx> ObligationCause<'tcx> {
137 pub fn span<'a, 'gcx>(&self, tcx: &TyCtxt<'a, 'gcx, 'tcx>) -> Span {
139 ObligationCauseCode::CompareImplMethodObligation { .. } |
140 ObligationCauseCode::MainFunctionType |
141 ObligationCauseCode::StartFunctionType => {
142 tcx.sess.codemap().def_span(self.span)
149 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
150 pub enum ObligationCauseCode<'tcx> {
151 /// Not well classified or should be obvious from span.
154 /// A slice or array is WF only if `T: Sized`
157 /// A tuple is WF only if its middle elements are Sized
160 /// This is the trait reference from the given projection
161 ProjectionWf(ty::ProjectionTy<'tcx>),
163 /// In an impl of trait X for type Y, type Y must
164 /// also implement all supertraits of X.
165 ItemObligation(DefId),
167 /// A type like `&'a T` is WF only if `T: 'a`.
168 ReferenceOutlivesReferent(Ty<'tcx>),
170 /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
171 ObjectTypeBound(Ty<'tcx>, ty::Region<'tcx>),
173 /// Obligation incurred due to an object cast.
174 ObjectCastObligation(/* Object type */ Ty<'tcx>),
176 // Various cases where expressions must be sized/copy/etc:
177 /// L = X implies that L is Sized
179 /// (x1, .., xn) must be Sized
180 TupleInitializerSized,
181 /// S { ... } must be Sized
182 StructInitializerSized,
183 /// Type of each variable must be Sized
184 VariableType(ast::NodeId),
185 /// Return type must be Sized
187 /// Yield type must be Sized
189 /// [T,..n] --> T must be Copy
192 /// Types of fields (other than the last) in a struct must be sized.
195 /// Constant expressions must be sized.
198 /// static items must have `Sync` type
201 BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
203 ImplDerivedObligation(DerivedObligationCause<'tcx>),
205 /// error derived when matching traits/impls; see ObligationCause for more details
206 CompareImplMethodObligation {
207 item_name: ast::Name,
208 impl_item_def_id: DefId,
209 trait_item_def_id: DefId,
212 /// Checking that this expression can be assigned where it needs to be
213 // FIXME(eddyb) #11161 is the original Expr required?
216 /// Computing common supertype in the arms of a match expression
217 MatchExpressionArm { arm_span: Span,
218 source: hir::MatchSource },
220 /// Computing common supertype in an if expression
223 /// Computing common supertype of an if expression with no else counter-part
224 IfExpressionWithNoElse,
226 /// `main` has wrong type
229 /// `start` has wrong type
232 /// intrinsic has wrong type
238 /// `return` with no expression
241 /// `return` with an expression
242 ReturnType(ast::NodeId),
244 /// Block implicit return
245 BlockTailExpression(ast::NodeId),
247 /// #[feature(trivial_bounds)] is not enabled
251 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
252 pub struct DerivedObligationCause<'tcx> {
253 /// The trait reference of the parent obligation that led to the
254 /// current obligation. Note that only trait obligations lead to
255 /// derived obligations, so we just store the trait reference here
257 parent_trait_ref: ty::PolyTraitRef<'tcx>,
259 /// The parent trait had this cause
260 parent_code: Rc<ObligationCauseCode<'tcx>>
263 pub type Obligations<'tcx, O> = Vec<Obligation<'tcx, O>>;
264 pub type PredicateObligations<'tcx> = Vec<PredicateObligation<'tcx>>;
265 pub type TraitObligations<'tcx> = Vec<TraitObligation<'tcx>>;
267 /// The following types:
268 /// * `WhereClauseAtom`
272 /// are used for representing the trait system in the form of
273 /// logic programming clauses. They are part of the interface
274 /// for the chalk SLG solver.
275 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
276 pub enum WhereClauseAtom<'tcx> {
277 Implemented(ty::TraitPredicate<'tcx>),
278 ProjectionEq(ty::ProjectionPredicate<'tcx>),
281 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
282 pub enum DomainGoal<'tcx> {
283 Holds(WhereClauseAtom<'tcx>),
284 WellFormed(WhereClauseAtom<'tcx>),
285 FromEnv(WhereClauseAtom<'tcx>),
286 WellFormedTy(Ty<'tcx>),
287 Normalize(ty::ProjectionPredicate<'tcx>),
289 RegionOutlives(ty::RegionOutlivesPredicate<'tcx>),
290 TypeOutlives(ty::TypeOutlivesPredicate<'tcx>),
293 pub type PolyDomainGoal<'tcx> = ty::Binder<DomainGoal<'tcx>>;
295 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
296 pub enum QuantifierKind {
301 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
302 pub enum Goal<'tcx> {
303 Implies(Clauses<'tcx>, &'tcx Goal<'tcx>),
304 And(&'tcx Goal<'tcx>, &'tcx Goal<'tcx>),
305 Not(&'tcx Goal<'tcx>),
306 DomainGoal(DomainGoal<'tcx>),
307 Quantified(QuantifierKind, ty::Binder<&'tcx Goal<'tcx>>),
311 pub type Goals<'tcx> = &'tcx Slice<Goal<'tcx>>;
313 impl<'tcx> Goal<'tcx> {
314 pub fn from_poly_domain_goal<'a>(
315 domain_goal: PolyDomainGoal<'tcx>,
316 tcx: TyCtxt<'a, 'tcx, 'tcx>,
318 match domain_goal.no_late_bound_regions() {
320 None => Goal::Quantified(
321 QuantifierKind::Universal,
322 domain_goal.map_bound(|p| tcx.mk_goal(Goal::from(p)))
328 impl<'tcx> From<DomainGoal<'tcx>> for Goal<'tcx> {
329 fn from(domain_goal: DomainGoal<'tcx>) -> Self {
330 Goal::DomainGoal(domain_goal)
334 /// This matches the definition from Page 7 of "A Proof Procedure for the Logic of Hereditary
335 /// Harrop Formulas".
336 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
337 pub enum Clause<'tcx> {
338 Implies(ProgramClause<'tcx>),
339 ForAll(ty::Binder<ProgramClause<'tcx>>),
342 /// Multiple clauses.
343 pub type Clauses<'tcx> = &'tcx Slice<Clause<'tcx>>;
345 /// A "program clause" has the form `D :- G1, ..., Gn`. It is saying
346 /// that the domain goal `D` is true if `G1...Gn` are provable. This
347 /// is equivalent to the implication `G1..Gn => D`; we usually write
348 /// it with the reverse implication operator `:-` to emphasize the way
349 /// that programs are actually solved (via backchaining, which starts
350 /// with the goal to solve and proceeds from there).
351 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
352 pub struct ProgramClause<'tcx> {
353 /// This goal will be considered true...
354 pub goal: DomainGoal<'tcx>,
356 /// ...if we can prove these hypotheses (there may be no hypotheses at all):
357 pub hypotheses: Goals<'tcx>,
360 pub type Selection<'tcx> = Vtable<'tcx, PredicateObligation<'tcx>>;
362 #[derive(Clone,Debug)]
363 pub enum SelectionError<'tcx> {
365 OutputTypeParameterMismatch(ty::PolyTraitRef<'tcx>,
366 ty::PolyTraitRef<'tcx>,
367 ty::error::TypeError<'tcx>),
368 TraitNotObjectSafe(DefId),
369 ConstEvalFailure(ConstEvalErr<'tcx>),
373 pub struct FulfillmentError<'tcx> {
374 pub obligation: PredicateObligation<'tcx>,
375 pub code: FulfillmentErrorCode<'tcx>
379 pub enum FulfillmentErrorCode<'tcx> {
380 CodeSelectionError(SelectionError<'tcx>),
381 CodeProjectionError(MismatchedProjectionTypes<'tcx>),
382 CodeSubtypeError(ExpectedFound<Ty<'tcx>>,
383 TypeError<'tcx>), // always comes from a SubtypePredicate
387 /// When performing resolution, it is typically the case that there
388 /// can be one of three outcomes:
390 /// - `Ok(Some(r))`: success occurred with result `r`
391 /// - `Ok(None)`: could not definitely determine anything, usually due
392 /// to inconclusive type inference.
393 /// - `Err(e)`: error `e` occurred
394 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
396 /// Given the successful resolution of an obligation, the `Vtable`
397 /// indicates where the vtable comes from. Note that while we call this
398 /// a "vtable", it does not necessarily indicate dynamic dispatch at
399 /// runtime. `Vtable` instances just tell the compiler where to find
400 /// methods, but in generic code those methods are typically statically
401 /// dispatched -- only when an object is constructed is a `Vtable`
402 /// instance reified into an actual vtable.
404 /// For example, the vtable may be tied to a specific impl (case A),
405 /// or it may be relative to some bound that is in scope (case B).
409 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
410 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
411 /// impl Clone for int { ... } // Impl_3
413 /// fn foo<T:Clone>(concrete: Option<Box<int>>,
415 /// mixed: Option<T>) {
417 /// // Case A: Vtable points at a specific impl. Only possible when
418 /// // type is concretely known. If the impl itself has bounded
419 /// // type parameters, Vtable will carry resolutions for those as well:
420 /// concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
422 /// // Case B: Vtable must be provided by caller. This applies when
423 /// // type is a type parameter.
424 /// param.clone(); // VtableParam
426 /// // Case C: A mix of cases A and B.
427 /// mixed.clone(); // Vtable(Impl_1, [VtableParam])
431 /// ### The type parameter `N`
433 /// See explanation on `VtableImplData`.
434 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
435 pub enum Vtable<'tcx, N> {
436 /// Vtable identifying a particular impl.
437 VtableImpl(VtableImplData<'tcx, N>),
439 /// Vtable for auto trait implementations
440 /// This carries the information and nested obligations with regards
441 /// to an auto implementation for a trait `Trait`. The nested obligations
442 /// ensure the trait implementation holds for all the constituent types.
443 VtableAutoImpl(VtableAutoImplData<N>),
445 /// Successful resolution to an obligation provided by the caller
446 /// for some type parameter. The `Vec<N>` represents the
447 /// obligations incurred from normalizing the where-clause (if
451 /// Virtual calls through an object
452 VtableObject(VtableObjectData<'tcx, N>),
454 /// Successful resolution for a builtin trait.
455 VtableBuiltin(VtableBuiltinData<N>),
457 /// Vtable automatically generated for a closure. The def ID is the ID
458 /// of the closure expression. This is a `VtableImpl` in spirit, but the
459 /// impl is generated by the compiler and does not appear in the source.
460 VtableClosure(VtableClosureData<'tcx, N>),
462 /// Same as above, but for a fn pointer type with the given signature.
463 VtableFnPointer(VtableFnPointerData<'tcx, N>),
465 /// Vtable automatically generated for a generator
466 VtableGenerator(VtableGeneratorData<'tcx, N>),
469 /// Identifies a particular impl in the source, along with a set of
470 /// substitutions from the impl's type/lifetime parameters. The
471 /// `nested` vector corresponds to the nested obligations attached to
472 /// the impl's type parameters.
474 /// The type parameter `N` indicates the type used for "nested
475 /// obligations" that are required by the impl. During type check, this
476 /// is `Obligation`, as one might expect. During trans, however, this
477 /// is `()`, because trans only requires a shallow resolution of an
478 /// impl, and nested obligations are satisfied later.
479 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
480 pub struct VtableImplData<'tcx, N> {
481 pub impl_def_id: DefId,
482 pub substs: &'tcx Substs<'tcx>,
486 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
487 pub struct VtableGeneratorData<'tcx, N> {
488 pub generator_def_id: DefId,
489 pub substs: ty::GeneratorSubsts<'tcx>,
490 /// Nested obligations. This can be non-empty if the generator
491 /// signature contains associated types.
495 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
496 pub struct VtableClosureData<'tcx, N> {
497 pub closure_def_id: DefId,
498 pub substs: ty::ClosureSubsts<'tcx>,
499 /// Nested obligations. This can be non-empty if the closure
500 /// signature contains associated types.
504 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
505 pub struct VtableAutoImplData<N> {
506 pub trait_def_id: DefId,
510 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
511 pub struct VtableBuiltinData<N> {
515 /// A vtable for some object-safe trait `Foo` automatically derived
516 /// for the object type `Foo`.
517 #[derive(PartialEq, Eq, Clone, RustcEncodable, RustcDecodable)]
518 pub struct VtableObjectData<'tcx, N> {
519 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
520 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
522 /// The vtable is formed by concatenating together the method lists of
523 /// the base object trait and all supertraits; this is the start of
524 /// `upcast_trait_ref`'s methods in that vtable.
525 pub vtable_base: usize,
530 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
531 pub struct VtableFnPointerData<'tcx, N> {
536 /// Creates predicate obligations from the generic bounds.
537 pub fn predicates_for_generics<'tcx>(cause: ObligationCause<'tcx>,
538 param_env: ty::ParamEnv<'tcx>,
539 generic_bounds: &ty::InstantiatedPredicates<'tcx>)
540 -> PredicateObligations<'tcx>
542 util::predicates_for_generics(cause, 0, param_env, generic_bounds)
545 /// Determines whether the type `ty` is known to meet `bound` and
546 /// returns true if so. Returns false if `ty` either does not meet
547 /// `bound` or is not known to meet bound (note that this is
548 /// conservative towards *no impl*, which is the opposite of the
549 /// `evaluate` methods).
550 pub fn type_known_to_meet_bound<'a, 'gcx, 'tcx>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
551 param_env: ty::ParamEnv<'tcx>,
557 debug!("type_known_to_meet_bound(ty={:?}, bound={:?})",
559 infcx.tcx.item_path_str(def_id));
561 let trait_ref = ty::TraitRef {
563 substs: infcx.tcx.mk_substs_trait(ty, &[]),
565 let obligation = Obligation {
567 cause: ObligationCause::misc(span, ast::DUMMY_NODE_ID),
569 predicate: trait_ref.to_predicate(),
572 let result = infcx.predicate_must_hold(&obligation);
573 debug!("type_known_to_meet_ty={:?} bound={} => {:?}",
574 ty, infcx.tcx.item_path_str(def_id), result);
576 if result && (ty.has_infer_types() || ty.has_closure_types()) {
577 // Because of inference "guessing", selection can sometimes claim
578 // to succeed while the success requires a guess. To ensure
579 // this function's result remains infallible, we must confirm
580 // that guess. While imperfect, I believe this is sound.
582 // The handling of regions in this area of the code is terrible,
583 // see issue #29149. We should be able to improve on this with
585 let mut fulfill_cx = FulfillmentContext::new_ignoring_regions();
587 // We can use a dummy node-id here because we won't pay any mind
588 // to region obligations that arise (there shouldn't really be any
590 let cause = ObligationCause::misc(span, ast::DUMMY_NODE_ID);
592 fulfill_cx.register_bound(infcx, param_env, ty, def_id, cause);
594 // Note: we only assume something is `Copy` if we can
595 // *definitively* show that it implements `Copy`. Otherwise,
596 // assume it is move; linear is always ok.
597 match fulfill_cx.select_all_or_error(infcx) {
599 debug!("type_known_to_meet_bound: ty={:?} bound={} success",
601 infcx.tcx.item_path_str(def_id));
605 debug!("type_known_to_meet_bound: ty={:?} bound={} errors={:?}",
607 infcx.tcx.item_path_str(def_id),
617 // FIXME: this is gonna need to be removed ...
618 /// Normalizes the parameter environment, reporting errors if they occur.
619 pub fn normalize_param_env_or_error<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
620 region_context: DefId,
621 unnormalized_env: ty::ParamEnv<'tcx>,
622 cause: ObligationCause<'tcx>)
623 -> ty::ParamEnv<'tcx>
625 // I'm not wild about reporting errors here; I'd prefer to
626 // have the errors get reported at a defined place (e.g.,
627 // during typeck). Instead I have all parameter
628 // environments, in effect, going through this function
629 // and hence potentially reporting errors. This ensurse of
630 // course that we never forget to normalize (the
631 // alternative seemed like it would involve a lot of
632 // manual invocations of this fn -- and then we'd have to
633 // deal with the errors at each of those sites).
635 // In any case, in practice, typeck constructs all the
636 // parameter environments once for every fn as it goes,
637 // and errors will get reported then; so after typeck we
638 // can be sure that no errors should occur.
640 let span = cause.span;
642 debug!("normalize_param_env_or_error(unnormalized_env={:?})",
645 let predicates: Vec<_> =
646 util::elaborate_predicates(tcx, unnormalized_env.caller_bounds.to_vec())
649 debug!("normalize_param_env_or_error: elaborated-predicates={:?}",
652 let elaborated_env = ty::ParamEnv::new(tcx.intern_predicates(&predicates),
653 unnormalized_env.reveal);
655 tcx.infer_ctxt().enter(|infcx| {
656 // FIXME. We should really... do something with these region
657 // obligations. But this call just continues the older
658 // behavior (i.e., doesn't cause any new bugs), and it would
659 // take some further refactoring to actually solve them. In
660 // particular, we would have to handle implied bounds
661 // properly, and that code is currently largely confined to
662 // regionck (though I made some efforts to extract it
665 // @arielby: In any case, these obligations are checked
666 // by wfcheck anyway, so I'm not sure we have to check
667 // them here too, and we will remove this function when
668 // we move over to lazy normalization *anyway*.
669 let fulfill_cx = FulfillmentContext::new_ignoring_regions();
671 let predicates = match fully_normalize(
676 // You would really want to pass infcx.param_env.caller_bounds here,
677 // but that is an interned slice, and fully_normalize takes &T and returns T, so
678 // without further refactoring, a slice can't be used. Luckily, we still have the
679 // predicate vector from which we created the ParamEnv in infcx, so we
680 // can pass that instead. It's roundabout and a bit brittle, but this code path
681 // ought to be refactored anyway, and until then it saves us from having to copy.
684 Ok(predicates) => predicates,
686 infcx.report_fulfillment_errors(&errors, None, false);
687 // An unnormalized env is better than nothing.
688 return elaborated_env;
692 debug!("normalize_param_env_or_error: normalized predicates={:?}",
695 let region_scope_tree = region::ScopeTree::default();
697 // We can use the `elaborated_env` here; the region code only
698 // cares about declarations like `'a: 'b`.
699 let outlives_env = OutlivesEnvironment::new(elaborated_env);
701 infcx.resolve_regions_and_report_errors(region_context, ®ion_scope_tree, &outlives_env);
703 let predicates = match infcx.fully_resolve(&predicates) {
704 Ok(predicates) => predicates,
706 // If we encounter a fixup error, it means that some type
707 // variable wound up unconstrained. I actually don't know
708 // if this can happen, and I certainly don't expect it to
709 // happen often, but if it did happen it probably
710 // represents a legitimate failure due to some kind of
711 // unconstrained variable, and it seems better not to ICE,
712 // all things considered.
713 tcx.sess.span_err(span, &fixup_err.to_string());
714 // An unnormalized env is better than nothing.
715 return elaborated_env;
719 let predicates = match tcx.lift_to_global(&predicates) {
720 Some(predicates) => predicates,
721 None => return elaborated_env,
724 debug!("normalize_param_env_or_error: resolved predicates={:?}",
727 ty::ParamEnv::new(tcx.intern_predicates(&predicates), unnormalized_env.reveal)
731 pub fn fully_normalize<'a, 'gcx, 'tcx, T>(
732 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
733 mut fulfill_cx: FulfillmentContext<'tcx>,
734 cause: ObligationCause<'tcx>,
735 param_env: ty::ParamEnv<'tcx>,
737 -> Result<T, Vec<FulfillmentError<'tcx>>>
738 where T : TypeFoldable<'tcx>
740 debug!("fully_normalize_with_fulfillcx(value={:?})", value);
741 let selcx = &mut SelectionContext::new(infcx);
742 let Normalized { value: normalized_value, obligations } =
743 project::normalize(selcx, param_env, cause, value);
744 debug!("fully_normalize: normalized_value={:?} obligations={:?}",
747 for obligation in obligations {
748 fulfill_cx.register_predicate_obligation(selcx.infcx(), obligation);
751 debug!("fully_normalize: select_all_or_error start");
752 fulfill_cx.select_all_or_error(infcx)?;
753 debug!("fully_normalize: select_all_or_error complete");
754 let resolved_value = infcx.resolve_type_vars_if_possible(&normalized_value);
755 debug!("fully_normalize: resolved_value={:?}", resolved_value);
759 /// Normalizes the predicates and checks whether they hold in an empty
760 /// environment. If this returns false, then either normalize
761 /// encountered an error or one of the predicates did not hold. Used
762 /// when creating vtables to check for unsatisfiable methods.
763 fn normalize_and_test_predicates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
764 predicates: Vec<ty::Predicate<'tcx>>)
767 debug!("normalize_and_test_predicates(predicates={:?})",
770 let result = tcx.infer_ctxt().enter(|infcx| {
771 let param_env = ty::ParamEnv::reveal_all();
772 let mut selcx = SelectionContext::new(&infcx);
773 let mut fulfill_cx = FulfillmentContext::new();
774 let cause = ObligationCause::dummy();
775 let Normalized { value: predicates, obligations } =
776 normalize(&mut selcx, param_env, cause.clone(), &predicates);
777 for obligation in obligations {
778 fulfill_cx.register_predicate_obligation(&infcx, obligation);
780 for predicate in predicates {
781 let obligation = Obligation::new(cause.clone(), param_env, predicate);
782 fulfill_cx.register_predicate_obligation(&infcx, obligation);
785 fulfill_cx.select_all_or_error(&infcx).is_ok()
787 debug!("normalize_and_test_predicates(predicates={:?}) = {:?}",
792 fn substitute_normalize_and_test_predicates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
793 key: (DefId, &'tcx Substs<'tcx>))
796 use ty::subst::Subst;
797 debug!("substitute_normalize_and_test_predicates(key={:?})",
800 let predicates = tcx.predicates_of(key.0).predicates.subst(tcx, key.1);
801 let result = normalize_and_test_predicates(tcx, predicates);
803 debug!("substitute_normalize_and_test_predicates(key={:?}) = {:?}",
808 /// Given a trait `trait_ref`, iterates the vtable entries
809 /// that come from `trait_ref`, including its supertraits.
810 #[inline] // FIXME(#35870) Avoid closures being unexported due to impl Trait.
811 fn vtable_methods<'a, 'tcx>(
812 tcx: TyCtxt<'a, 'tcx, 'tcx>,
813 trait_ref: ty::PolyTraitRef<'tcx>)
814 -> Lrc<Vec<Option<(DefId, &'tcx Substs<'tcx>)>>>
816 debug!("vtable_methods({:?})", trait_ref);
819 supertraits(tcx, trait_ref).flat_map(move |trait_ref| {
820 let trait_methods = tcx.associated_items(trait_ref.def_id())
821 .filter(|item| item.kind == ty::AssociatedKind::Method);
823 // Now list each method's DefId and Substs (for within its trait).
824 // If the method can never be called from this object, produce None.
825 trait_methods.map(move |trait_method| {
826 debug!("vtable_methods: trait_method={:?}", trait_method);
827 let def_id = trait_method.def_id;
829 // Some methods cannot be called on an object; skip those.
830 if !tcx.is_vtable_safe_method(trait_ref.def_id(), &trait_method) {
831 debug!("vtable_methods: not vtable safe");
835 // the method may have some early-bound lifetimes, add
837 let substs = trait_ref.map_bound(|trait_ref| {
840 |_, _| tcx.types.re_erased,
841 |def, _| trait_ref.substs.type_for_def(def))
844 // the trait type may have higher-ranked lifetimes in it;
845 // so erase them if they appear, so that we get the type
846 // at some particular call site
847 let substs = tcx.normalize_erasing_late_bound_regions(
848 ty::ParamEnv::reveal_all(),
852 // It's possible that the method relies on where clauses that
853 // do not hold for this particular set of type parameters.
854 // Note that this method could then never be called, so we
855 // do not want to try and trans it, in that case (see #23435).
856 let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs);
857 if !normalize_and_test_predicates(tcx, predicates.predicates) {
858 debug!("vtable_methods: predicates do not hold");
862 Some((def_id, substs))
868 impl<'tcx,O> Obligation<'tcx,O> {
869 pub fn new(cause: ObligationCause<'tcx>,
870 param_env: ty::ParamEnv<'tcx>,
872 -> Obligation<'tcx, O>
874 Obligation { cause, param_env, recursion_depth: 0, predicate }
877 fn with_depth(cause: ObligationCause<'tcx>,
878 recursion_depth: usize,
879 param_env: ty::ParamEnv<'tcx>,
881 -> Obligation<'tcx, O>
883 Obligation { cause, param_env, recursion_depth, predicate }
886 pub fn misc(span: Span,
887 body_id: ast::NodeId,
888 param_env: ty::ParamEnv<'tcx>,
890 -> Obligation<'tcx, O> {
891 Obligation::new(ObligationCause::misc(span, body_id), param_env, trait_ref)
894 pub fn with<P>(&self, value: P) -> Obligation<'tcx,P> {
895 Obligation { cause: self.cause.clone(),
896 param_env: self.param_env,
897 recursion_depth: self.recursion_depth,
902 impl<'tcx> ObligationCause<'tcx> {
903 pub fn new(span: Span,
904 body_id: ast::NodeId,
905 code: ObligationCauseCode<'tcx>)
906 -> ObligationCause<'tcx> {
907 ObligationCause { span: span, body_id: body_id, code: code }
910 pub fn misc(span: Span, body_id: ast::NodeId) -> ObligationCause<'tcx> {
911 ObligationCause { span: span, body_id: body_id, code: MiscObligation }
914 pub fn dummy() -> ObligationCause<'tcx> {
915 ObligationCause { span: DUMMY_SP, body_id: ast::CRATE_NODE_ID, code: MiscObligation }
919 impl<'tcx, N> Vtable<'tcx, N> {
920 pub fn nested_obligations(self) -> Vec<N> {
922 VtableImpl(i) => i.nested,
924 VtableBuiltin(i) => i.nested,
925 VtableAutoImpl(d) => d.nested,
926 VtableClosure(c) => c.nested,
927 VtableGenerator(c) => c.nested,
928 VtableObject(d) => d.nested,
929 VtableFnPointer(d) => d.nested,
933 pub fn map<M, F>(self, f: F) -> Vtable<'tcx, M> where F: FnMut(N) -> M {
935 VtableImpl(i) => VtableImpl(VtableImplData {
936 impl_def_id: i.impl_def_id,
938 nested: i.nested.into_iter().map(f).collect(),
940 VtableParam(n) => VtableParam(n.into_iter().map(f).collect()),
941 VtableBuiltin(i) => VtableBuiltin(VtableBuiltinData {
942 nested: i.nested.into_iter().map(f).collect(),
944 VtableObject(o) => VtableObject(VtableObjectData {
945 upcast_trait_ref: o.upcast_trait_ref,
946 vtable_base: o.vtable_base,
947 nested: o.nested.into_iter().map(f).collect(),
949 VtableAutoImpl(d) => VtableAutoImpl(VtableAutoImplData {
950 trait_def_id: d.trait_def_id,
951 nested: d.nested.into_iter().map(f).collect(),
953 VtableFnPointer(p) => VtableFnPointer(VtableFnPointerData {
955 nested: p.nested.into_iter().map(f).collect(),
957 VtableGenerator(c) => VtableGenerator(VtableGeneratorData {
958 generator_def_id: c.generator_def_id,
960 nested: c.nested.into_iter().map(f).collect(),
962 VtableClosure(c) => VtableClosure(VtableClosureData {
963 closure_def_id: c.closure_def_id,
965 nested: c.nested.into_iter().map(f).collect(),
971 impl<'tcx> FulfillmentError<'tcx> {
972 fn new(obligation: PredicateObligation<'tcx>,
973 code: FulfillmentErrorCode<'tcx>)
974 -> FulfillmentError<'tcx>
976 FulfillmentError { obligation: obligation, code: code }
980 impl<'tcx> TraitObligation<'tcx> {
981 fn self_ty(&self) -> ty::Binder<Ty<'tcx>> {
982 self.predicate.map_bound(|p| p.self_ty())
986 pub fn provide(providers: &mut ty::maps::Providers) {
987 *providers = ty::maps::Providers {
988 is_object_safe: object_safety::is_object_safe_provider,
989 specialization_graph_of: specialize::specialization_graph_provider,
990 specializes: specialize::specializes,
991 trans_fulfill_obligation: trans::trans_fulfill_obligation,
993 substitute_normalize_and_test_predicates,