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::outlives::env::OutlivesEnvironment;
25 use mir::interpret::ConstEvalErr;
26 use ty::subst::Substs;
27 use ty::{self, AdtKind, List, Ty, TyCtxt, GenericParamDefKind, ToPredicate};
28 use ty::error::{ExpectedFound, TypeError};
29 use ty::fold::{TypeFolder, TypeFoldable, TypeVisitor};
30 use infer::{InferCtxt};
32 use rustc_data_structures::sync::Lrc;
36 use syntax_pos::{Span, DUMMY_SP};
38 pub use self::coherence::{orphan_check, overlapping_impls, OrphanCheckErr, OverlapResult};
39 pub use self::fulfill::{FulfillmentContext, PendingPredicateObligation};
40 pub use self::project::MismatchedProjectionTypes;
41 pub use self::project::{normalize, normalize_projection_type, poly_project_and_unify_type};
42 pub use self::project::{ProjectionCache, ProjectionCacheSnapshot, Reveal, Normalized};
43 pub use self::object_safety::ObjectSafetyViolation;
44 pub use self::object_safety::MethodViolationCode;
45 pub use self::on_unimplemented::{OnUnimplementedDirective, OnUnimplementedNote};
46 pub use self::select::{EvaluationCache, SelectionContext, SelectionCache};
47 pub use self::select::{EvaluationResult, IntercrateAmbiguityCause, OverflowError};
48 pub use self::specialize::{OverlapError, specialization_graph, translate_substs};
49 pub use self::specialize::{SpecializesCache, find_associated_item};
50 pub use self::engine::{TraitEngine, TraitEngineExt};
51 pub use self::util::elaborate_predicates;
52 pub use self::util::supertraits;
53 pub use self::util::Supertraits;
54 pub use self::util::supertrait_def_ids;
55 pub use self::util::SupertraitDefIds;
56 pub use self::util::transitive_bounds;
61 pub mod error_reporting;
75 // Whether to enable bug compatibility with issue #43355
76 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
77 pub enum IntercrateMode {
82 // The mode that trait queries run in
83 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
84 pub enum TraitQueryMode {
85 // Standard/un-canonicalized queries get accurate
86 // spans etc. passed in and hence can do reasonable
87 // error reporting on their own.
89 // Canonicalized queries get dummy spans and hence
90 // must generally propagate errors to
91 // pre-canonicalization callsites.
95 /// An `Obligation` represents some trait reference (e.g. `int:Eq`) for
96 /// which the vtable must be found. The process of finding a vtable is
97 /// called "resolving" the `Obligation`. This process consists of
98 /// either identifying an `impl` (e.g., `impl Eq for int`) that
99 /// provides the required vtable, or else finding a bound that is in
100 /// scope. The eventual result is usually a `Selection` (defined below).
101 #[derive(Clone, PartialEq, Eq, Hash)]
102 pub struct Obligation<'tcx, T> {
103 /// Why do we have to prove this thing?
104 pub cause: ObligationCause<'tcx>,
106 /// In which environment should we prove this thing?
107 pub param_env: ty::ParamEnv<'tcx>,
109 /// What are we trying to prove?
112 /// If we started proving this as a result of trying to prove
113 /// something else, track the total depth to ensure termination.
114 /// If this goes over a certain threshold, we abort compilation --
115 /// in such cases, we can not say whether or not the predicate
116 /// holds for certain. Stupid halting problem. Such a drag.
117 pub recursion_depth: usize,
120 pub type PredicateObligation<'tcx> = Obligation<'tcx, ty::Predicate<'tcx>>;
121 pub type TraitObligation<'tcx> = Obligation<'tcx, ty::PolyTraitPredicate<'tcx>>;
123 /// Why did we incur this obligation? Used for error reporting.
124 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
125 pub struct ObligationCause<'tcx> {
128 // The id of the fn body that triggered this obligation. This is
129 // used for region obligations to determine the precise
130 // environment in which the region obligation should be evaluated
131 // (in particular, closures can add new assumptions). See the
132 // field `region_obligations` of the `FulfillmentContext` for more
134 pub body_id: ast::NodeId,
136 pub code: ObligationCauseCode<'tcx>
139 impl<'tcx> ObligationCause<'tcx> {
140 pub fn span<'a, 'gcx>(&self, tcx: &TyCtxt<'a, 'gcx, 'tcx>) -> Span {
142 ObligationCauseCode::CompareImplMethodObligation { .. } |
143 ObligationCauseCode::MainFunctionType |
144 ObligationCauseCode::StartFunctionType => {
145 tcx.sess.source_map().def_span(self.span)
152 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
153 pub enum ObligationCauseCode<'tcx> {
154 /// Not well classified or should be obvious from span.
157 /// A slice or array is WF only if `T: Sized`
160 /// A tuple is WF only if its middle elements are Sized
163 /// This is the trait reference from the given projection
164 ProjectionWf(ty::ProjectionTy<'tcx>),
166 /// In an impl of trait X for type Y, type Y must
167 /// also implement all supertraits of X.
168 ItemObligation(DefId),
170 /// A type like `&'a T` is WF only if `T: 'a`.
171 ReferenceOutlivesReferent(Ty<'tcx>),
173 /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
174 ObjectTypeBound(Ty<'tcx>, ty::Region<'tcx>),
176 /// Obligation incurred due to an object cast.
177 ObjectCastObligation(/* Object type */ Ty<'tcx>),
179 // Various cases where expressions must be sized/copy/etc:
180 /// L = X implies that L is Sized
182 /// (x1, .., xn) must be Sized
183 TupleInitializerSized,
184 /// S { ... } must be Sized
185 StructInitializerSized,
186 /// Type of each variable must be Sized
187 VariableType(ast::NodeId),
188 /// Argument type must be Sized
190 /// Return type must be Sized
192 /// Yield type must be Sized
194 /// [T,..n] --> T must be Copy
197 /// Types of fields (other than the last, except for packed structs) in a struct must be sized.
198 FieldSized { adt_kind: AdtKind, last: bool },
200 /// Constant expressions must be sized.
203 /// static items must have `Sync` type
206 BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
208 ImplDerivedObligation(DerivedObligationCause<'tcx>),
210 /// error derived when matching traits/impls; see ObligationCause for more details
211 CompareImplMethodObligation {
212 item_name: ast::Name,
213 impl_item_def_id: DefId,
214 trait_item_def_id: DefId,
217 /// Checking that this expression can be assigned where it needs to be
218 // FIXME(eddyb) #11161 is the original Expr required?
221 /// Computing common supertype in the arms of a match expression
222 MatchExpressionArm { arm_span: Span,
223 source: hir::MatchSource },
225 /// Computing common supertype in an if expression
228 /// Computing common supertype of an if expression with no else counter-part
229 IfExpressionWithNoElse,
231 /// `main` has wrong type
234 /// `start` has wrong type
237 /// intrinsic has wrong type
243 /// `return` with no expression
246 /// `return` with an expression
247 ReturnType(ast::NodeId),
249 /// Block implicit return
250 BlockTailExpression(ast::NodeId),
252 /// #[feature(trivial_bounds)] is not enabled
256 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
257 pub struct DerivedObligationCause<'tcx> {
258 /// The trait reference of the parent obligation that led to the
259 /// current obligation. Note that only trait obligations lead to
260 /// derived obligations, so we just store the trait reference here
262 parent_trait_ref: ty::PolyTraitRef<'tcx>,
264 /// The parent trait had this cause
265 parent_code: Rc<ObligationCauseCode<'tcx>>
268 pub type Obligations<'tcx, O> = Vec<Obligation<'tcx, O>>;
269 pub type PredicateObligations<'tcx> = Vec<PredicateObligation<'tcx>>;
270 pub type TraitObligations<'tcx> = Vec<TraitObligation<'tcx>>;
272 /// The following types:
279 /// are used for representing the trait system in the form of
280 /// logic programming clauses. They are part of the interface
281 /// for the chalk SLG solver.
282 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
283 pub enum WhereClause<'tcx> {
284 Implemented(ty::TraitPredicate<'tcx>),
285 ProjectionEq(ty::ProjectionPredicate<'tcx>),
286 RegionOutlives(ty::RegionOutlivesPredicate<'tcx>),
287 TypeOutlives(ty::TypeOutlivesPredicate<'tcx>),
290 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
291 pub enum WellFormed<'tcx> {
292 Trait(ty::TraitPredicate<'tcx>),
296 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
297 pub enum FromEnv<'tcx> {
298 Trait(ty::TraitPredicate<'tcx>),
302 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
303 pub enum DomainGoal<'tcx> {
304 Holds(WhereClause<'tcx>),
305 WellFormed(WellFormed<'tcx>),
306 FromEnv(FromEnv<'tcx>),
307 Normalize(ty::ProjectionPredicate<'tcx>),
310 pub type PolyDomainGoal<'tcx> = ty::Binder<DomainGoal<'tcx>>;
312 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
313 pub enum QuantifierKind {
318 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
319 pub enum Goal<'tcx> {
320 Implies(Clauses<'tcx>, &'tcx Goal<'tcx>),
321 And(&'tcx Goal<'tcx>, &'tcx Goal<'tcx>),
322 Not(&'tcx Goal<'tcx>),
323 DomainGoal(DomainGoal<'tcx>),
324 Quantified(QuantifierKind, ty::Binder<&'tcx Goal<'tcx>>),
328 pub type Goals<'tcx> = &'tcx List<Goal<'tcx>>;
330 impl<'tcx> DomainGoal<'tcx> {
331 pub fn into_goal(self) -> Goal<'tcx> {
332 Goal::DomainGoal(self)
336 impl<'tcx> Goal<'tcx> {
337 pub fn from_poly_domain_goal<'a>(
338 domain_goal: PolyDomainGoal<'tcx>,
339 tcx: TyCtxt<'a, 'tcx, 'tcx>,
341 match domain_goal.no_late_bound_regions() {
342 Some(p) => p.into_goal(),
343 None => Goal::Quantified(
344 QuantifierKind::Universal,
345 domain_goal.map_bound(|p| tcx.mk_goal(p.into_goal()))
351 /// This matches the definition from Page 7 of "A Proof Procedure for the Logic of Hereditary
352 /// Harrop Formulas".
353 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
354 pub enum Clause<'tcx> {
355 Implies(ProgramClause<'tcx>),
356 ForAll(ty::Binder<ProgramClause<'tcx>>),
359 /// Multiple clauses.
360 pub type Clauses<'tcx> = &'tcx List<Clause<'tcx>>;
362 /// A "program clause" has the form `D :- G1, ..., Gn`. It is saying
363 /// that the domain goal `D` is true if `G1...Gn` are provable. This
364 /// is equivalent to the implication `G1..Gn => D`; we usually write
365 /// it with the reverse implication operator `:-` to emphasize the way
366 /// that programs are actually solved (via backchaining, which starts
367 /// with the goal to solve and proceeds from there).
368 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
369 pub struct ProgramClause<'tcx> {
370 /// This goal will be considered true...
371 pub goal: DomainGoal<'tcx>,
373 /// ...if we can prove these hypotheses (there may be no hypotheses at all):
374 pub hypotheses: Goals<'tcx>,
377 pub type Selection<'tcx> = Vtable<'tcx, PredicateObligation<'tcx>>;
379 #[derive(Clone,Debug)]
380 pub enum SelectionError<'tcx> {
382 OutputTypeParameterMismatch(ty::PolyTraitRef<'tcx>,
383 ty::PolyTraitRef<'tcx>,
384 ty::error::TypeError<'tcx>),
385 TraitNotObjectSafe(DefId),
386 ConstEvalFailure(Lrc<ConstEvalErr<'tcx>>),
390 pub struct FulfillmentError<'tcx> {
391 pub obligation: PredicateObligation<'tcx>,
392 pub code: FulfillmentErrorCode<'tcx>
396 pub enum FulfillmentErrorCode<'tcx> {
397 CodeSelectionError(SelectionError<'tcx>),
398 CodeProjectionError(MismatchedProjectionTypes<'tcx>),
399 CodeSubtypeError(ExpectedFound<Ty<'tcx>>,
400 TypeError<'tcx>), // always comes from a SubtypePredicate
404 /// When performing resolution, it is typically the case that there
405 /// can be one of three outcomes:
407 /// - `Ok(Some(r))`: success occurred with result `r`
408 /// - `Ok(None)`: could not definitely determine anything, usually due
409 /// to inconclusive type inference.
410 /// - `Err(e)`: error `e` occurred
411 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
413 /// Given the successful resolution of an obligation, the `Vtable`
414 /// indicates where the vtable comes from. Note that while we call this
415 /// a "vtable", it does not necessarily indicate dynamic dispatch at
416 /// runtime. `Vtable` instances just tell the compiler where to find
417 /// methods, but in generic code those methods are typically statically
418 /// dispatched -- only when an object is constructed is a `Vtable`
419 /// instance reified into an actual vtable.
421 /// For example, the vtable may be tied to a specific impl (case A),
422 /// or it may be relative to some bound that is in scope (case B).
426 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
427 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
428 /// impl Clone for int { ... } // Impl_3
430 /// fn foo<T:Clone>(concrete: Option<Box<int>>,
432 /// mixed: Option<T>) {
434 /// // Case A: Vtable points at a specific impl. Only possible when
435 /// // type is concretely known. If the impl itself has bounded
436 /// // type parameters, Vtable will carry resolutions for those as well:
437 /// concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
439 /// // Case B: Vtable must be provided by caller. This applies when
440 /// // type is a type parameter.
441 /// param.clone(); // VtableParam
443 /// // Case C: A mix of cases A and B.
444 /// mixed.clone(); // Vtable(Impl_1, [VtableParam])
448 /// ### The type parameter `N`
450 /// See explanation on `VtableImplData`.
451 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
452 pub enum Vtable<'tcx, N> {
453 /// Vtable identifying a particular impl.
454 VtableImpl(VtableImplData<'tcx, N>),
456 /// Vtable for auto trait implementations
457 /// This carries the information and nested obligations with regards
458 /// to an auto implementation for a trait `Trait`. The nested obligations
459 /// ensure the trait implementation holds for all the constituent types.
460 VtableAutoImpl(VtableAutoImplData<N>),
462 /// Successful resolution to an obligation provided by the caller
463 /// for some type parameter. The `Vec<N>` represents the
464 /// obligations incurred from normalizing the where-clause (if
468 /// Virtual calls through an object
469 VtableObject(VtableObjectData<'tcx, N>),
471 /// Successful resolution for a builtin trait.
472 VtableBuiltin(VtableBuiltinData<N>),
474 /// Vtable automatically generated for a closure. The def ID is the ID
475 /// of the closure expression. This is a `VtableImpl` in spirit, but the
476 /// impl is generated by the compiler and does not appear in the source.
477 VtableClosure(VtableClosureData<'tcx, N>),
479 /// Same as above, but for a fn pointer type with the given signature.
480 VtableFnPointer(VtableFnPointerData<'tcx, N>),
482 /// Vtable automatically generated for a generator
483 VtableGenerator(VtableGeneratorData<'tcx, N>),
486 /// Identifies a particular impl in the source, along with a set of
487 /// substitutions from the impl's type/lifetime parameters. The
488 /// `nested` vector corresponds to the nested obligations attached to
489 /// the impl's type parameters.
491 /// The type parameter `N` indicates the type used for "nested
492 /// obligations" that are required by the impl. During type check, this
493 /// is `Obligation`, as one might expect. During codegen, however, this
494 /// is `()`, because codegen only requires a shallow resolution of an
495 /// impl, and nested obligations are satisfied later.
496 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
497 pub struct VtableImplData<'tcx, N> {
498 pub impl_def_id: DefId,
499 pub substs: &'tcx Substs<'tcx>,
503 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
504 pub struct VtableGeneratorData<'tcx, N> {
505 pub generator_def_id: DefId,
506 pub substs: ty::GeneratorSubsts<'tcx>,
507 /// Nested obligations. This can be non-empty if the generator
508 /// signature contains associated types.
512 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
513 pub struct VtableClosureData<'tcx, N> {
514 pub closure_def_id: DefId,
515 pub substs: ty::ClosureSubsts<'tcx>,
516 /// Nested obligations. This can be non-empty if the closure
517 /// signature contains associated types.
521 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
522 pub struct VtableAutoImplData<N> {
523 pub trait_def_id: DefId,
527 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
528 pub struct VtableBuiltinData<N> {
532 /// A vtable for some object-safe trait `Foo` automatically derived
533 /// for the object type `Foo`.
534 #[derive(PartialEq, Eq, Clone, RustcEncodable, RustcDecodable)]
535 pub struct VtableObjectData<'tcx, N> {
536 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
537 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
539 /// The vtable is formed by concatenating together the method lists of
540 /// the base object trait and all supertraits; this is the start of
541 /// `upcast_trait_ref`'s methods in that vtable.
542 pub vtable_base: usize,
547 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable)]
548 pub struct VtableFnPointerData<'tcx, N> {
553 /// Creates predicate obligations from the generic bounds.
554 pub fn predicates_for_generics<'tcx>(cause: ObligationCause<'tcx>,
555 param_env: ty::ParamEnv<'tcx>,
556 generic_bounds: &ty::InstantiatedPredicates<'tcx>)
557 -> PredicateObligations<'tcx>
559 util::predicates_for_generics(cause, 0, param_env, generic_bounds)
562 /// Determines whether the type `ty` is known to meet `bound` and
563 /// returns true if so. Returns false if `ty` either does not meet
564 /// `bound` or is not known to meet bound (note that this is
565 /// conservative towards *no impl*, which is the opposite of the
566 /// `evaluate` methods).
567 pub fn type_known_to_meet_bound<'a, 'gcx, 'tcx>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
568 param_env: ty::ParamEnv<'tcx>,
574 debug!("type_known_to_meet_bound(ty={:?}, bound={:?})",
576 infcx.tcx.item_path_str(def_id));
578 let trait_ref = ty::TraitRef {
580 substs: infcx.tcx.mk_substs_trait(ty, &[]),
582 let obligation = Obligation {
584 cause: ObligationCause::misc(span, ast::DUMMY_NODE_ID),
586 predicate: trait_ref.to_predicate(),
589 let result = infcx.predicate_must_hold(&obligation);
590 debug!("type_known_to_meet_ty={:?} bound={} => {:?}",
591 ty, infcx.tcx.item_path_str(def_id), result);
593 if result && (ty.has_infer_types() || ty.has_closure_types()) {
594 // Because of inference "guessing", selection can sometimes claim
595 // to succeed while the success requires a guess. To ensure
596 // this function's result remains infallible, we must confirm
597 // that guess. While imperfect, I believe this is sound.
599 // The handling of regions in this area of the code is terrible,
600 // see issue #29149. We should be able to improve on this with
602 let mut fulfill_cx = FulfillmentContext::new_ignoring_regions();
604 // We can use a dummy node-id here because we won't pay any mind
605 // to region obligations that arise (there shouldn't really be any
607 let cause = ObligationCause::misc(span, ast::DUMMY_NODE_ID);
609 fulfill_cx.register_bound(infcx, param_env, ty, def_id, cause);
611 // Note: we only assume something is `Copy` if we can
612 // *definitively* show that it implements `Copy`. Otherwise,
613 // assume it is move; linear is always ok.
614 match fulfill_cx.select_all_or_error(infcx) {
616 debug!("type_known_to_meet_bound: ty={:?} bound={} success",
618 infcx.tcx.item_path_str(def_id));
622 debug!("type_known_to_meet_bound: ty={:?} bound={} errors={:?}",
624 infcx.tcx.item_path_str(def_id),
634 // FIXME: this is gonna need to be removed ...
635 /// Normalizes the parameter environment, reporting errors if they occur.
636 pub fn normalize_param_env_or_error<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
637 region_context: DefId,
638 unnormalized_env: ty::ParamEnv<'tcx>,
639 cause: ObligationCause<'tcx>)
640 -> ty::ParamEnv<'tcx>
642 // I'm not wild about reporting errors here; I'd prefer to
643 // have the errors get reported at a defined place (e.g.,
644 // during typeck). Instead I have all parameter
645 // environments, in effect, going through this function
646 // and hence potentially reporting errors. This ensurse of
647 // course that we never forget to normalize (the
648 // alternative seemed like it would involve a lot of
649 // manual invocations of this fn -- and then we'd have to
650 // deal with the errors at each of those sites).
652 // In any case, in practice, typeck constructs all the
653 // parameter environments once for every fn as it goes,
654 // and errors will get reported then; so after typeck we
655 // can be sure that no errors should occur.
657 let span = cause.span;
659 debug!("normalize_param_env_or_error(unnormalized_env={:?})",
662 let predicates: Vec<_> =
663 util::elaborate_predicates(tcx, unnormalized_env.caller_bounds.to_vec())
666 debug!("normalize_param_env_or_error: elaborated-predicates={:?}",
669 let elaborated_env = ty::ParamEnv::new(tcx.intern_predicates(&predicates),
670 unnormalized_env.reveal);
672 tcx.infer_ctxt().enter(|infcx| {
673 // FIXME. We should really... do something with these region
674 // obligations. But this call just continues the older
675 // behavior (i.e., doesn't cause any new bugs), and it would
676 // take some further refactoring to actually solve them. In
677 // particular, we would have to handle implied bounds
678 // properly, and that code is currently largely confined to
679 // regionck (though I made some efforts to extract it
682 // @arielby: In any case, these obligations are checked
683 // by wfcheck anyway, so I'm not sure we have to check
684 // them here too, and we will remove this function when
685 // we move over to lazy normalization *anyway*.
686 let fulfill_cx = FulfillmentContext::new_ignoring_regions();
688 let predicates = match fully_normalize(
693 // You would really want to pass infcx.param_env.caller_bounds here,
694 // but that is an interned slice, and fully_normalize takes &T and returns T, so
695 // without further refactoring, a slice can't be used. Luckily, we still have the
696 // predicate vector from which we created the ParamEnv in infcx, so we
697 // can pass that instead. It's roundabout and a bit brittle, but this code path
698 // ought to be refactored anyway, and until then it saves us from having to copy.
701 Ok(predicates) => predicates,
703 infcx.report_fulfillment_errors(&errors, None, false);
704 // An unnormalized env is better than nothing.
705 return elaborated_env;
709 debug!("normalize_param_env_or_error: normalized predicates={:?}",
712 let region_scope_tree = region::ScopeTree::default();
714 // We can use the `elaborated_env` here; the region code only
715 // cares about declarations like `'a: 'b`.
716 let outlives_env = OutlivesEnvironment::new(elaborated_env);
718 infcx.resolve_regions_and_report_errors(region_context, ®ion_scope_tree, &outlives_env);
720 let predicates = match infcx.fully_resolve(&predicates) {
721 Ok(predicates) => predicates,
723 // If we encounter a fixup error, it means that some type
724 // variable wound up unconstrained. I actually don't know
725 // if this can happen, and I certainly don't expect it to
726 // happen often, but if it did happen it probably
727 // represents a legitimate failure due to some kind of
728 // unconstrained variable, and it seems better not to ICE,
729 // all things considered.
730 tcx.sess.span_err(span, &fixup_err.to_string());
731 // An unnormalized env is better than nothing.
732 return elaborated_env;
736 let predicates = match tcx.lift_to_global(&predicates) {
737 Some(predicates) => predicates,
738 None => return elaborated_env,
741 debug!("normalize_param_env_or_error: resolved predicates={:?}",
744 ty::ParamEnv::new(tcx.intern_predicates(&predicates), unnormalized_env.reveal)
748 pub fn fully_normalize<'a, 'gcx, 'tcx, T>(
749 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
750 mut fulfill_cx: FulfillmentContext<'tcx>,
751 cause: ObligationCause<'tcx>,
752 param_env: ty::ParamEnv<'tcx>,
754 -> Result<T, Vec<FulfillmentError<'tcx>>>
755 where T : TypeFoldable<'tcx>
757 debug!("fully_normalize_with_fulfillcx(value={:?})", value);
758 let selcx = &mut SelectionContext::new(infcx);
759 let Normalized { value: normalized_value, obligations } =
760 project::normalize(selcx, param_env, cause, value);
761 debug!("fully_normalize: normalized_value={:?} obligations={:?}",
764 for obligation in obligations {
765 fulfill_cx.register_predicate_obligation(selcx.infcx(), obligation);
768 debug!("fully_normalize: select_all_or_error start");
769 fulfill_cx.select_all_or_error(infcx)?;
770 debug!("fully_normalize: select_all_or_error complete");
771 let resolved_value = infcx.resolve_type_vars_if_possible(&normalized_value);
772 debug!("fully_normalize: resolved_value={:?}", resolved_value);
776 /// Normalizes the predicates and checks whether they hold in an empty
777 /// environment. If this returns false, then either normalize
778 /// encountered an error or one of the predicates did not hold. Used
779 /// when creating vtables to check for unsatisfiable methods.
780 fn normalize_and_test_predicates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
781 predicates: Vec<ty::Predicate<'tcx>>)
784 debug!("normalize_and_test_predicates(predicates={:?})",
787 let result = tcx.infer_ctxt().enter(|infcx| {
788 let param_env = ty::ParamEnv::reveal_all();
789 let mut selcx = SelectionContext::new(&infcx);
790 let mut fulfill_cx = FulfillmentContext::new();
791 let cause = ObligationCause::dummy();
792 let Normalized { value: predicates, obligations } =
793 normalize(&mut selcx, param_env, cause.clone(), &predicates);
794 for obligation in obligations {
795 fulfill_cx.register_predicate_obligation(&infcx, obligation);
797 for predicate in predicates {
798 let obligation = Obligation::new(cause.clone(), param_env, predicate);
799 fulfill_cx.register_predicate_obligation(&infcx, obligation);
802 fulfill_cx.select_all_or_error(&infcx).is_ok()
804 debug!("normalize_and_test_predicates(predicates={:?}) = {:?}",
809 fn substitute_normalize_and_test_predicates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
810 key: (DefId, &'tcx Substs<'tcx>))
813 use ty::subst::Subst;
814 debug!("substitute_normalize_and_test_predicates(key={:?})",
817 let predicates = tcx.predicates_of(key.0).predicates.subst(tcx, key.1);
818 let result = normalize_and_test_predicates(tcx, predicates);
820 debug!("substitute_normalize_and_test_predicates(key={:?}) = {:?}",
825 /// Given a trait `trait_ref`, iterates the vtable entries
826 /// that come from `trait_ref`, including its supertraits.
827 #[inline] // FIXME(#35870) Avoid closures being unexported due to impl Trait.
828 fn vtable_methods<'a, 'tcx>(
829 tcx: TyCtxt<'a, 'tcx, 'tcx>,
830 trait_ref: ty::PolyTraitRef<'tcx>)
831 -> Lrc<Vec<Option<(DefId, &'tcx Substs<'tcx>)>>>
833 debug!("vtable_methods({:?})", trait_ref);
836 supertraits(tcx, trait_ref).flat_map(move |trait_ref| {
837 let trait_methods = tcx.associated_items(trait_ref.def_id())
838 .filter(|item| item.kind == ty::AssociatedKind::Method);
840 // Now list each method's DefId and Substs (for within its trait).
841 // If the method can never be called from this object, produce None.
842 trait_methods.map(move |trait_method| {
843 debug!("vtable_methods: trait_method={:?}", trait_method);
844 let def_id = trait_method.def_id;
846 // Some methods cannot be called on an object; skip those.
847 if !tcx.is_vtable_safe_method(trait_ref.def_id(), &trait_method) {
848 debug!("vtable_methods: not vtable safe");
852 // the method may have some early-bound lifetimes, add
854 let substs = trait_ref.map_bound(|trait_ref|
855 Substs::for_item(tcx, def_id, |param, _|
857 GenericParamDefKind::Lifetime => tcx.types.re_erased.into(),
858 GenericParamDefKind::Type {..} => {
859 trait_ref.substs[param.index as usize]
865 // the trait type may have higher-ranked lifetimes in it;
866 // so erase them if they appear, so that we get the type
867 // at some particular call site
868 let substs = tcx.normalize_erasing_late_bound_regions(
869 ty::ParamEnv::reveal_all(),
873 // It's possible that the method relies on where clauses that
874 // do not hold for this particular set of type parameters.
875 // Note that this method could then never be called, so we
876 // do not want to try and codegen it, in that case (see #23435).
877 let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs);
878 if !normalize_and_test_predicates(tcx, predicates.predicates) {
879 debug!("vtable_methods: predicates do not hold");
883 Some((def_id, substs))
889 impl<'tcx,O> Obligation<'tcx,O> {
890 pub fn new(cause: ObligationCause<'tcx>,
891 param_env: ty::ParamEnv<'tcx>,
893 -> Obligation<'tcx, O>
895 Obligation { cause, param_env, recursion_depth: 0, predicate }
898 fn with_depth(cause: ObligationCause<'tcx>,
899 recursion_depth: usize,
900 param_env: ty::ParamEnv<'tcx>,
902 -> Obligation<'tcx, O>
904 Obligation { cause, param_env, recursion_depth, predicate }
907 pub fn misc(span: Span,
908 body_id: ast::NodeId,
909 param_env: ty::ParamEnv<'tcx>,
911 -> Obligation<'tcx, O> {
912 Obligation::new(ObligationCause::misc(span, body_id), param_env, trait_ref)
915 pub fn with<P>(&self, value: P) -> Obligation<'tcx,P> {
916 Obligation { cause: self.cause.clone(),
917 param_env: self.param_env,
918 recursion_depth: self.recursion_depth,
923 impl<'tcx> ObligationCause<'tcx> {
924 pub fn new(span: Span,
925 body_id: ast::NodeId,
926 code: ObligationCauseCode<'tcx>)
927 -> ObligationCause<'tcx> {
928 ObligationCause { span: span, body_id: body_id, code: code }
931 pub fn misc(span: Span, body_id: ast::NodeId) -> ObligationCause<'tcx> {
932 ObligationCause { span: span, body_id: body_id, code: MiscObligation }
935 pub fn dummy() -> ObligationCause<'tcx> {
936 ObligationCause { span: DUMMY_SP, body_id: ast::CRATE_NODE_ID, code: MiscObligation }
940 impl<'tcx, N> Vtable<'tcx, N> {
941 pub fn nested_obligations(self) -> Vec<N> {
943 VtableImpl(i) => i.nested,
945 VtableBuiltin(i) => i.nested,
946 VtableAutoImpl(d) => d.nested,
947 VtableClosure(c) => c.nested,
948 VtableGenerator(c) => c.nested,
949 VtableObject(d) => d.nested,
950 VtableFnPointer(d) => d.nested,
954 pub fn map<M, F>(self, f: F) -> Vtable<'tcx, M> where F: FnMut(N) -> M {
956 VtableImpl(i) => VtableImpl(VtableImplData {
957 impl_def_id: i.impl_def_id,
959 nested: i.nested.into_iter().map(f).collect(),
961 VtableParam(n) => VtableParam(n.into_iter().map(f).collect()),
962 VtableBuiltin(i) => VtableBuiltin(VtableBuiltinData {
963 nested: i.nested.into_iter().map(f).collect(),
965 VtableObject(o) => VtableObject(VtableObjectData {
966 upcast_trait_ref: o.upcast_trait_ref,
967 vtable_base: o.vtable_base,
968 nested: o.nested.into_iter().map(f).collect(),
970 VtableAutoImpl(d) => VtableAutoImpl(VtableAutoImplData {
971 trait_def_id: d.trait_def_id,
972 nested: d.nested.into_iter().map(f).collect(),
974 VtableFnPointer(p) => VtableFnPointer(VtableFnPointerData {
976 nested: p.nested.into_iter().map(f).collect(),
978 VtableGenerator(c) => VtableGenerator(VtableGeneratorData {
979 generator_def_id: c.generator_def_id,
981 nested: c.nested.into_iter().map(f).collect(),
983 VtableClosure(c) => VtableClosure(VtableClosureData {
984 closure_def_id: c.closure_def_id,
986 nested: c.nested.into_iter().map(f).collect(),
992 impl<'tcx> FulfillmentError<'tcx> {
993 fn new(obligation: PredicateObligation<'tcx>,
994 code: FulfillmentErrorCode<'tcx>)
995 -> FulfillmentError<'tcx>
997 FulfillmentError { obligation: obligation, code: code }
1001 impl<'tcx> TraitObligation<'tcx> {
1002 fn self_ty(&self) -> ty::Binder<Ty<'tcx>> {
1003 self.predicate.map_bound(|p| p.self_ty())
1007 pub fn provide(providers: &mut ty::query::Providers) {
1008 *providers = ty::query::Providers {
1009 is_object_safe: object_safety::is_object_safe_provider,
1010 specialization_graph_of: specialize::specialization_graph_provider,
1011 specializes: specialize::specializes,
1012 codegen_fulfill_obligation: codegen::codegen_fulfill_obligation,
1014 substitute_normalize_and_test_predicates,
1019 pub trait ExClauseFold<'tcx>
1021 Self: chalk_engine::context::Context + Clone,
1023 fn fold_ex_clause_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(
1024 ex_clause: &chalk_engine::ExClause<Self>,
1026 ) -> chalk_engine::ExClause<Self>;
1028 fn visit_ex_clause_with<'gcx: 'tcx, V: TypeVisitor<'tcx>>(
1029 ex_clause: &chalk_engine::ExClause<Self>,
1034 pub trait ExClauseLift<'tcx>
1036 Self: chalk_engine::context::Context + Clone,
1038 type LiftedExClause: Debug + 'tcx;
1040 fn lift_ex_clause_to_tcx<'a, 'gcx>(
1041 ex_clause: &chalk_engine::ExClause<Self>,
1042 tcx: TyCtxt<'a, 'gcx, 'tcx>,
1043 ) -> Option<Self::LiftedExClause>;