]> git.lizzy.rs Git - rust.git/blob - src/librustc/traits/mod.rs
Rollup merge of #66574 - GuillaumeGomez:update-tidy-err-code-check, r=Mark-Simulacrum
[rust.git] / src / librustc / traits / mod.rs
1 //! Trait Resolution. See the [rustc guide] for more information on how this works.
2 //!
3 //! [rustc guide]: https://rust-lang.github.io/rustc-guide/traits/resolution.html
4
5 #[allow(dead_code)]
6 pub mod auto_trait;
7 mod chalk_fulfill;
8 mod coherence;
9 pub mod error_reporting;
10 mod engine;
11 mod fulfill;
12 mod project;
13 mod object_safety;
14 mod on_unimplemented;
15 mod select;
16 mod specialize;
17 mod structural_impls;
18 pub mod codegen;
19 mod util;
20 pub mod query;
21
22 use chalk_engine;
23 use crate::hir;
24 use crate::hir::def_id::DefId;
25 use crate::infer::{InferCtxt, SuppressRegionErrors};
26 use crate::infer::outlives::env::OutlivesEnvironment;
27 use crate::middle::region;
28 use crate::mir::interpret::ErrorHandled;
29 use rustc_macros::HashStable;
30 use syntax::ast;
31 use syntax_pos::{Span, DUMMY_SP};
32 use crate::ty::subst::{InternalSubsts, SubstsRef};
33 use crate::ty::{self, AdtKind, List, Ty, TyCtxt, GenericParamDefKind, ToPredicate};
34 use crate::ty::error::{ExpectedFound, TypeError};
35 use crate::ty::fold::{TypeFolder, TypeFoldable, TypeVisitor};
36 use crate::util::common::ErrorReported;
37
38 use std::fmt::Debug;
39 use std::rc::Rc;
40
41 pub use self::SelectionError::*;
42 pub use self::FulfillmentErrorCode::*;
43 pub use self::Vtable::*;
44 pub use self::ObligationCauseCode::*;
45
46 pub use self::coherence::{add_placeholder_note, orphan_check, overlapping_impls};
47 pub use self::coherence::{OrphanCheckErr, OverlapResult};
48 pub use self::fulfill::{FulfillmentContext, PendingPredicateObligation};
49 pub use self::project::MismatchedProjectionTypes;
50 pub use self::project::{normalize, normalize_projection_type, poly_project_and_unify_type};
51 pub use self::project::{ProjectionCache, ProjectionCacheSnapshot, Reveal, Normalized};
52 pub use self::object_safety::ObjectSafetyViolation;
53 pub use self::object_safety::MethodViolationCode;
54 pub use self::on_unimplemented::{OnUnimplementedDirective, OnUnimplementedNote};
55 pub use self::select::{EvaluationCache, SelectionContext, SelectionCache};
56 pub use self::select::{EvaluationResult, IntercrateAmbiguityCause, OverflowError};
57 pub use self::specialize::{OverlapError, specialization_graph, translate_substs};
58 pub use self::specialize::find_associated_item;
59 pub use self::specialize::specialization_graph::FutureCompatOverlapError;
60 pub use self::specialize::specialization_graph::FutureCompatOverlapErrorKind;
61 pub use self::engine::{TraitEngine, TraitEngineExt};
62 pub use self::util::{elaborate_predicates, elaborate_trait_ref, elaborate_trait_refs};
63 pub use self::util::{
64     supertraits, supertrait_def_ids, transitive_bounds, Supertraits, SupertraitDefIds,
65 };
66 pub use self::util::{expand_trait_aliases, TraitAliasExpander};
67
68 pub use self::chalk_fulfill::{
69     CanonicalGoal as ChalkCanonicalGoal,
70     FulfillmentContext as ChalkFulfillmentContext
71 };
72
73 pub use self::ObligationCauseCode::*;
74 pub use self::FulfillmentErrorCode::*;
75 pub use self::SelectionError::*;
76 pub use self::Vtable::*;
77
78 /// Whether to enable bug compatibility with issue #43355.
79 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
80 pub enum IntercrateMode {
81     Issue43355,
82     Fixed
83 }
84
85 /// The mode that trait queries run in.
86 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
87 pub enum TraitQueryMode {
88     // Standard/un-canonicalized queries get accurate
89     // spans etc. passed in and hence can do reasonable
90     // error reporting on their own.
91     Standard,
92     // Canonicalized queries get dummy spans and hence
93     // must generally propagate errors to
94     // pre-canonicalization callsites.
95     Canonical,
96 }
97
98 /// An `Obligation` represents some trait reference (e.g., `int: Eq`) for
99 /// which the vtable must be found. The process of finding a vtable is
100 /// called "resolving" the `Obligation`. This process consists of
101 /// either identifying an `impl` (e.g., `impl Eq for int`) that
102 /// provides the required vtable, or else finding a bound that is in
103 /// scope. The eventual result is usually a `Selection` (defined below).
104 #[derive(Clone, PartialEq, Eq, Hash)]
105 pub struct Obligation<'tcx, T> {
106     /// The reason we have to prove this thing.
107     pub cause: ObligationCause<'tcx>,
108
109     /// The environment in which we should prove this thing.
110     pub param_env: ty::ParamEnv<'tcx>,
111
112     /// The thing we are trying to prove.
113     pub predicate: T,
114
115     /// If we started proving this as a result of trying to prove
116     /// something else, track the total depth to ensure termination.
117     /// If this goes over a certain threshold, we abort compilation --
118     /// in such cases, we can not say whether or not the predicate
119     /// holds for certain. Stupid halting problem; such a drag.
120     pub recursion_depth: usize,
121 }
122
123 pub type PredicateObligation<'tcx> = Obligation<'tcx, ty::Predicate<'tcx>>;
124 pub type TraitObligation<'tcx> = Obligation<'tcx, ty::PolyTraitPredicate<'tcx>>;
125
126 // `PredicateObligation` is used a lot. Make sure it doesn't unintentionally get bigger.
127 #[cfg(target_arch = "x86_64")]
128 static_assert_size!(PredicateObligation<'_>, 112);
129
130 /// The reason why we incurred this obligation; used for error reporting.
131 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
132 pub struct ObligationCause<'tcx> {
133     pub span: Span,
134
135     /// The ID of the fn body that triggered this obligation. This is
136     /// used for region obligations to determine the precise
137     /// environment in which the region obligation should be evaluated
138     /// (in particular, closures can add new assumptions). See the
139     /// field `region_obligations` of the `FulfillmentContext` for more
140     /// information.
141     pub body_id: hir::HirId,
142
143     pub code: ObligationCauseCode<'tcx>
144 }
145
146 impl<'tcx> ObligationCause<'tcx> {
147     pub fn span(&self, tcx: TyCtxt<'tcx>) -> Span {
148         match self.code {
149             ObligationCauseCode::CompareImplMethodObligation { .. } |
150             ObligationCauseCode::MainFunctionType |
151             ObligationCauseCode::StartFunctionType => {
152                 tcx.sess.source_map().def_span(self.span)
153             }
154             ObligationCauseCode::MatchExpressionArm(
155                 box MatchExpressionArmCause { arm_span, .. }) => arm_span,
156             _ => self.span,
157         }
158     }
159 }
160
161 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
162 pub enum ObligationCauseCode<'tcx> {
163     /// Not well classified or should be obvious from the span.
164     MiscObligation,
165
166     /// A slice or array is WF only if `T: Sized`.
167     SliceOrArrayElem,
168
169     /// A tuple is WF only if its middle elements are `Sized`.
170     TupleElem,
171
172     /// This is the trait reference from the given projection.
173     ProjectionWf(ty::ProjectionTy<'tcx>),
174
175     /// In an impl of trait `X` for type `Y`, type `Y` must
176     /// also implement all supertraits of `X`.
177     ItemObligation(DefId),
178
179     /// Like `ItemObligation`, but with extra detail on the source of the obligation.
180     BindingObligation(DefId, Span),
181
182     /// A type like `&'a T` is WF only if `T: 'a`.
183     ReferenceOutlivesReferent(Ty<'tcx>),
184
185     /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
186     ObjectTypeBound(Ty<'tcx>, ty::Region<'tcx>),
187
188     /// Obligation incurred due to an object cast.
189     ObjectCastObligation(/* Object type */ Ty<'tcx>),
190
191     /// Obligation incurred due to a coercion.
192     Coercion { source: Ty<'tcx>, target: Ty<'tcx> },
193
194     /// Various cases where expressions must be `Sized` / `Copy` / etc.
195     /// `L = X` implies that `L` is `Sized`.
196     AssignmentLhsSized,
197     /// `(x1, .., xn)` must be `Sized`.
198     TupleInitializerSized,
199     /// `S { ... }` must be `Sized`.
200     StructInitializerSized,
201     /// Type of each variable must be `Sized`.
202     VariableType(hir::HirId),
203     /// Argument type must be `Sized`.
204     SizedArgumentType,
205     /// Return type must be `Sized`.
206     SizedReturnType,
207     /// Yield type must be `Sized`.
208     SizedYieldType,
209     /// `[T, ..n]` implies that `T` must be `Copy`.
210     /// If `true`, suggest `const_in_array_repeat_expressions` feature flag.
211     RepeatVec(bool),
212
213     /// Types of fields (other than the last, except for packed structs) in a struct must be sized.
214     FieldSized { adt_kind: AdtKind, last: bool },
215
216     /// Constant expressions must be sized.
217     ConstSized,
218
219     /// `static` items must have `Sync` type.
220     SharedStatic,
221
222     BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
223
224     ImplDerivedObligation(DerivedObligationCause<'tcx>),
225
226     /// Error derived when matching traits/impls; see ObligationCause for more details
227     CompareImplMethodObligation {
228         item_name: ast::Name,
229         impl_item_def_id: DefId,
230         trait_item_def_id: DefId,
231     },
232
233     /// Checking that this expression can be assigned where it needs to be
234     // FIXME(eddyb) #11161 is the original Expr required?
235     ExprAssignable,
236
237     /// Computing common supertype in the arms of a match expression
238     MatchExpressionArm(Box<MatchExpressionArmCause<'tcx>>),
239
240     /// Computing common supertype in the pattern guard for the arms of a match expression
241     MatchExpressionArmPattern { span: Span, ty: Ty<'tcx> },
242
243     /// Constants in patterns must have `Structural` type.
244     ConstPatternStructural,
245
246     /// Computing common supertype in an if expression
247     IfExpression(Box<IfExpressionCause>),
248
249     /// Computing common supertype of an if expression with no else counter-part
250     IfExpressionWithNoElse,
251
252     /// `main` has wrong type
253     MainFunctionType,
254
255     /// `start` has wrong type
256     StartFunctionType,
257
258     /// Intrinsic has wrong type
259     IntrinsicType,
260
261     /// Method receiver
262     MethodReceiver,
263
264     /// `return` with no expression
265     ReturnNoExpression,
266
267     /// `return` with an expression
268     ReturnValue(hir::HirId),
269
270     /// Return type of this function
271     ReturnType,
272
273     /// Block implicit return
274     BlockTailExpression(hir::HirId),
275
276     /// #[feature(trivial_bounds)] is not enabled
277     TrivialBound,
278
279     AssocTypeBound(Box<AssocTypeBoundData>),
280 }
281
282 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
283 pub struct AssocTypeBoundData {
284     pub impl_span: Option<Span>,
285     pub original: Span,
286     pub bounds: Vec<Span>,
287 }
288
289 // `ObligationCauseCode` is used a lot. Make sure it doesn't unintentionally get bigger.
290 #[cfg(target_arch = "x86_64")]
291 static_assert_size!(ObligationCauseCode<'_>, 32);
292
293 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
294 pub struct MatchExpressionArmCause<'tcx> {
295     pub arm_span: Span,
296     pub source: hir::MatchSource,
297     pub prior_arms: Vec<Span>,
298     pub last_ty: Ty<'tcx>,
299     pub discrim_hir_id: hir::HirId,
300 }
301
302 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
303 pub struct IfExpressionCause {
304     pub then: Span,
305     pub outer: Option<Span>,
306     pub semicolon: Option<Span>,
307 }
308
309 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
310 pub struct DerivedObligationCause<'tcx> {
311     /// The trait reference of the parent obligation that led to the
312     /// current obligation. Note that only trait obligations lead to
313     /// derived obligations, so we just store the trait reference here
314     /// directly.
315     parent_trait_ref: ty::PolyTraitRef<'tcx>,
316
317     /// The parent trait had this cause.
318     parent_code: Rc<ObligationCauseCode<'tcx>>
319 }
320
321 pub type Obligations<'tcx, O> = Vec<Obligation<'tcx, O>>;
322 pub type PredicateObligations<'tcx> = Vec<PredicateObligation<'tcx>>;
323 pub type TraitObligations<'tcx> = Vec<TraitObligation<'tcx>>;
324
325 /// The following types:
326 /// * `WhereClause`,
327 /// * `WellFormed`,
328 /// * `FromEnv`,
329 /// * `DomainGoal`,
330 /// * `Goal`,
331 /// * `Clause`,
332 /// * `Environment`,
333 /// * `InEnvironment`,
334 /// are used for representing the trait system in the form of
335 /// logic programming clauses. They are part of the interface
336 /// for the chalk SLG solver.
337 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
338 pub enum WhereClause<'tcx> {
339     Implemented(ty::TraitPredicate<'tcx>),
340     ProjectionEq(ty::ProjectionPredicate<'tcx>),
341     RegionOutlives(ty::RegionOutlivesPredicate<'tcx>),
342     TypeOutlives(ty::TypeOutlivesPredicate<'tcx>),
343 }
344
345 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
346 pub enum WellFormed<'tcx> {
347     Trait(ty::TraitPredicate<'tcx>),
348     Ty(Ty<'tcx>),
349 }
350
351 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
352 pub enum FromEnv<'tcx> {
353     Trait(ty::TraitPredicate<'tcx>),
354     Ty(Ty<'tcx>),
355 }
356
357 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
358 pub enum DomainGoal<'tcx> {
359     Holds(WhereClause<'tcx>),
360     WellFormed(WellFormed<'tcx>),
361     FromEnv(FromEnv<'tcx>),
362     Normalize(ty::ProjectionPredicate<'tcx>),
363 }
364
365 pub type PolyDomainGoal<'tcx> = ty::Binder<DomainGoal<'tcx>>;
366
367 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
368 pub enum QuantifierKind {
369     Universal,
370     Existential,
371 }
372
373 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
374 pub enum GoalKind<'tcx> {
375     Implies(Clauses<'tcx>, Goal<'tcx>),
376     And(Goal<'tcx>, Goal<'tcx>),
377     Not(Goal<'tcx>),
378     DomainGoal(DomainGoal<'tcx>),
379     Quantified(QuantifierKind, ty::Binder<Goal<'tcx>>),
380     Subtype(Ty<'tcx>, Ty<'tcx>),
381     CannotProve,
382 }
383
384 pub type Goal<'tcx> = &'tcx GoalKind<'tcx>;
385
386 pub type Goals<'tcx> = &'tcx List<Goal<'tcx>>;
387
388 impl<'tcx> DomainGoal<'tcx> {
389     pub fn into_goal(self) -> GoalKind<'tcx> {
390         GoalKind::DomainGoal(self)
391     }
392
393     pub fn into_program_clause(self) -> ProgramClause<'tcx> {
394         ProgramClause {
395             goal: self,
396             hypotheses: ty::List::empty(),
397             category: ProgramClauseCategory::Other,
398         }
399     }
400 }
401
402 impl<'tcx> GoalKind<'tcx> {
403     pub fn from_poly_domain_goal(
404         domain_goal: PolyDomainGoal<'tcx>,
405         tcx: TyCtxt<'tcx>,
406     ) -> GoalKind<'tcx> {
407         match domain_goal.no_bound_vars() {
408             Some(p) => p.into_goal(),
409             None => GoalKind::Quantified(
410                 QuantifierKind::Universal,
411                 domain_goal.map_bound(|p| tcx.mk_goal(p.into_goal()))
412             ),
413         }
414     }
415 }
416
417 /// This matches the definition from Page 7 of "A Proof Procedure for the Logic of Hereditary
418 /// Harrop Formulas".
419 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
420 pub enum Clause<'tcx> {
421     Implies(ProgramClause<'tcx>),
422     ForAll(ty::Binder<ProgramClause<'tcx>>),
423 }
424
425 impl Clause<'tcx> {
426     pub fn category(self) -> ProgramClauseCategory {
427         match self {
428             Clause::Implies(clause) => clause.category,
429             Clause::ForAll(clause) => clause.skip_binder().category,
430         }
431     }
432 }
433
434 /// Multiple clauses.
435 pub type Clauses<'tcx> = &'tcx List<Clause<'tcx>>;
436
437 /// A "program clause" has the form `D :- G1, ..., Gn`. It is saying
438 /// that the domain goal `D` is true if `G1...Gn` are provable. This
439 /// is equivalent to the implication `G1..Gn => D`; we usually write
440 /// it with the reverse implication operator `:-` to emphasize the way
441 /// that programs are actually solved (via backchaining, which starts
442 /// with the goal to solve and proceeds from there).
443 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
444 pub struct ProgramClause<'tcx> {
445     /// This goal will be considered true ...
446     pub goal: DomainGoal<'tcx>,
447
448     /// ... if we can prove these hypotheses (there may be no hypotheses at all):
449     pub hypotheses: Goals<'tcx>,
450
451     /// Useful for filtering clauses.
452     pub category: ProgramClauseCategory,
453 }
454
455 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
456 pub enum ProgramClauseCategory {
457     ImpliedBound,
458     WellFormed,
459     Other,
460 }
461
462 /// A set of clauses that we assume to be true.
463 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
464 pub struct Environment<'tcx> {
465     pub clauses: Clauses<'tcx>,
466 }
467
468 impl Environment<'tcx> {
469     pub fn with<G>(self, goal: G) -> InEnvironment<'tcx, G> {
470         InEnvironment {
471             environment: self,
472             goal,
473         }
474     }
475 }
476
477 /// Something (usually a goal), along with an environment.
478 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
479 pub struct InEnvironment<'tcx, G> {
480     pub environment: Environment<'tcx>,
481     pub goal: G,
482 }
483
484 pub type Selection<'tcx> = Vtable<'tcx, PredicateObligation<'tcx>>;
485
486 #[derive(Clone,Debug,TypeFoldable)]
487 pub enum SelectionError<'tcx> {
488     Unimplemented,
489     OutputTypeParameterMismatch(ty::PolyTraitRef<'tcx>,
490                                 ty::PolyTraitRef<'tcx>,
491                                 ty::error::TypeError<'tcx>),
492     TraitNotObjectSafe(DefId),
493     ConstEvalFailure(ErrorHandled),
494     Overflow,
495 }
496
497 pub struct FulfillmentError<'tcx> {
498     pub obligation: PredicateObligation<'tcx>,
499     pub code: FulfillmentErrorCode<'tcx>,
500     /// Diagnostics only: we opportunistically change the `code.span` when we encounter an
501     /// obligation error caused by a call argument. When this is the case, we also signal that in
502     /// this field to ensure accuracy of suggestions.
503     pub points_at_arg_span: bool,
504 }
505
506 #[derive(Clone)]
507 pub enum FulfillmentErrorCode<'tcx> {
508     CodeSelectionError(SelectionError<'tcx>),
509     CodeProjectionError(MismatchedProjectionTypes<'tcx>),
510     CodeSubtypeError(ExpectedFound<Ty<'tcx>>,
511                      TypeError<'tcx>), // always comes from a SubtypePredicate
512     CodeAmbiguity,
513 }
514
515 /// When performing resolution, it is typically the case that there
516 /// can be one of three outcomes:
517 ///
518 /// - `Ok(Some(r))`: success occurred with result `r`
519 /// - `Ok(None)`: could not definitely determine anything, usually due
520 ///   to inconclusive type inference.
521 /// - `Err(e)`: error `e` occurred
522 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
523
524 /// Given the successful resolution of an obligation, the `Vtable`
525 /// indicates where the vtable comes from. Note that while we call this
526 /// a "vtable", it does not necessarily indicate dynamic dispatch at
527 /// runtime. `Vtable` instances just tell the compiler where to find
528 /// methods, but in generic code those methods are typically statically
529 /// dispatched -- only when an object is constructed is a `Vtable`
530 /// instance reified into an actual vtable.
531 ///
532 /// For example, the vtable may be tied to a specific impl (case A),
533 /// or it may be relative to some bound that is in scope (case B).
534 ///
535 /// ```
536 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
537 /// impl<T:Clone> Clone<T> for Box<T> { ... }    // Impl_2
538 /// impl Clone for int { ... }             // Impl_3
539 ///
540 /// fn foo<T:Clone>(concrete: Option<Box<int>>,
541 ///                 param: T,
542 ///                 mixed: Option<T>) {
543 ///
544 ///    // Case A: Vtable points at a specific impl. Only possible when
545 ///    // type is concretely known. If the impl itself has bounded
546 ///    // type parameters, Vtable will carry resolutions for those as well:
547 ///    concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
548 ///
549 ///    // Case B: Vtable must be provided by caller. This applies when
550 ///    // type is a type parameter.
551 ///    param.clone();    // VtableParam
552 ///
553 ///    // Case C: A mix of cases A and B.
554 ///    mixed.clone();    // Vtable(Impl_1, [VtableParam])
555 /// }
556 /// ```
557 ///
558 /// ### The type parameter `N`
559 ///
560 /// See explanation on `VtableImplData`.
561 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
562 pub enum Vtable<'tcx, N> {
563     /// Vtable identifying a particular impl.
564     VtableImpl(VtableImplData<'tcx, N>),
565
566     /// Vtable for auto trait implementations.
567     /// This carries the information and nested obligations with regards
568     /// to an auto implementation for a trait `Trait`. The nested obligations
569     /// ensure the trait implementation holds for all the constituent types.
570     VtableAutoImpl(VtableAutoImplData<N>),
571
572     /// Successful resolution to an obligation provided by the caller
573     /// for some type parameter. The `Vec<N>` represents the
574     /// obligations incurred from normalizing the where-clause (if
575     /// any).
576     VtableParam(Vec<N>),
577
578     /// Virtual calls through an object.
579     VtableObject(VtableObjectData<'tcx, N>),
580
581     /// Successful resolution for a builtin trait.
582     VtableBuiltin(VtableBuiltinData<N>),
583
584     /// Vtable automatically generated for a closure. The `DefId` is the ID
585     /// of the closure expression. This is a `VtableImpl` in spirit, but the
586     /// impl is generated by the compiler and does not appear in the source.
587     VtableClosure(VtableClosureData<'tcx, N>),
588
589     /// Same as above, but for a function pointer type with the given signature.
590     VtableFnPointer(VtableFnPointerData<'tcx, N>),
591
592     /// Vtable automatically generated for a generator.
593     VtableGenerator(VtableGeneratorData<'tcx, N>),
594
595     /// Vtable for a trait alias.
596     VtableTraitAlias(VtableTraitAliasData<'tcx, N>),
597 }
598
599 /// Identifies a particular impl in the source, along with a set of
600 /// substitutions from the impl's type/lifetime parameters. The
601 /// `nested` vector corresponds to the nested obligations attached to
602 /// the impl's type parameters.
603 ///
604 /// The type parameter `N` indicates the type used for "nested
605 /// obligations" that are required by the impl. During type-check, this
606 /// is `Obligation`, as one might expect. During codegen, however, this
607 /// is `()`, because codegen only requires a shallow resolution of an
608 /// impl, and nested obligations are satisfied later.
609 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
610 pub struct VtableImplData<'tcx, N> {
611     pub impl_def_id: DefId,
612     pub substs: SubstsRef<'tcx>,
613     pub nested: Vec<N>
614 }
615
616 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
617 pub struct VtableGeneratorData<'tcx, N> {
618     pub generator_def_id: DefId,
619     pub substs: SubstsRef<'tcx>,
620     /// Nested obligations. This can be non-empty if the generator
621     /// signature contains associated types.
622     pub nested: Vec<N>
623 }
624
625 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
626 pub struct VtableClosureData<'tcx, N> {
627     pub closure_def_id: DefId,
628     pub substs: SubstsRef<'tcx>,
629     /// Nested obligations. This can be non-empty if the closure
630     /// signature contains associated types.
631     pub nested: Vec<N>
632 }
633
634 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
635 pub struct VtableAutoImplData<N> {
636     pub trait_def_id: DefId,
637     pub nested: Vec<N>
638 }
639
640 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
641 pub struct VtableBuiltinData<N> {
642     pub nested: Vec<N>
643 }
644
645 /// A vtable for some object-safe trait `Foo` automatically derived
646 /// for the object type `Foo`.
647 #[derive(PartialEq, Eq, Clone, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
648 pub struct VtableObjectData<'tcx, N> {
649     /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
650     pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
651
652     /// The vtable is formed by concatenating together the method lists of
653     /// the base object trait and all supertraits; this is the start of
654     /// `upcast_trait_ref`'s methods in that vtable.
655     pub vtable_base: usize,
656
657     pub nested: Vec<N>,
658 }
659
660 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
661 pub struct VtableFnPointerData<'tcx, N> {
662     pub fn_ty: Ty<'tcx>,
663     pub nested: Vec<N>
664 }
665
666 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
667 pub struct VtableTraitAliasData<'tcx, N> {
668     pub alias_def_id: DefId,
669     pub substs: SubstsRef<'tcx>,
670     pub nested: Vec<N>,
671 }
672
673 /// Creates predicate obligations from the generic bounds.
674 pub fn predicates_for_generics<'tcx>(
675     cause: ObligationCause<'tcx>,
676     param_env: ty::ParamEnv<'tcx>,
677     generic_bounds: &ty::InstantiatedPredicates<'tcx>,
678 ) -> PredicateObligations<'tcx> {
679     util::predicates_for_generics(cause, 0, param_env, generic_bounds)
680 }
681
682 /// Determines whether the type `ty` is known to meet `bound` and
683 /// returns true if so. Returns false if `ty` either does not meet
684 /// `bound` or is not known to meet bound (note that this is
685 /// conservative towards *no impl*, which is the opposite of the
686 /// `evaluate` methods).
687 pub fn type_known_to_meet_bound_modulo_regions<'a, 'tcx>(
688     infcx: &InferCtxt<'a, 'tcx>,
689     param_env: ty::ParamEnv<'tcx>,
690     ty: Ty<'tcx>,
691     def_id: DefId,
692     span: Span,
693 ) -> bool {
694     debug!("type_known_to_meet_bound_modulo_regions(ty={:?}, bound={:?})",
695            ty,
696            infcx.tcx.def_path_str(def_id));
697
698     let trait_ref = ty::TraitRef {
699         def_id,
700         substs: infcx.tcx.mk_substs_trait(ty, &[]),
701     };
702     let obligation = Obligation {
703         param_env,
704         cause: ObligationCause::misc(span, hir::DUMMY_HIR_ID),
705         recursion_depth: 0,
706         predicate: trait_ref.to_predicate(),
707     };
708
709     let result = infcx.predicate_must_hold_modulo_regions(&obligation);
710     debug!("type_known_to_meet_ty={:?} bound={} => {:?}",
711            ty, infcx.tcx.def_path_str(def_id), result);
712
713     if result && (ty.has_infer_types() || ty.has_closure_types()) {
714         // Because of inference "guessing", selection can sometimes claim
715         // to succeed while the success requires a guess. To ensure
716         // this function's result remains infallible, we must confirm
717         // that guess. While imperfect, I believe this is sound.
718
719         // The handling of regions in this area of the code is terrible,
720         // see issue #29149. We should be able to improve on this with
721         // NLL.
722         let mut fulfill_cx = FulfillmentContext::new_ignoring_regions();
723
724         // We can use a dummy node-id here because we won't pay any mind
725         // to region obligations that arise (there shouldn't really be any
726         // anyhow).
727         let cause = ObligationCause::misc(span, hir::DUMMY_HIR_ID);
728
729         fulfill_cx.register_bound(infcx, param_env, ty, def_id, cause);
730
731         // Note: we only assume something is `Copy` if we can
732         // *definitively* show that it implements `Copy`. Otherwise,
733         // assume it is move; linear is always ok.
734         match fulfill_cx.select_all_or_error(infcx) {
735             Ok(()) => {
736                 debug!("type_known_to_meet_bound_modulo_regions: ty={:?} bound={} success",
737                        ty,
738                        infcx.tcx.def_path_str(def_id));
739                 true
740             }
741             Err(e) => {
742                 debug!("type_known_to_meet_bound_modulo_regions: ty={:?} bound={} errors={:?}",
743                        ty,
744                        infcx.tcx.def_path_str(def_id),
745                        e);
746                 false
747             }
748         }
749     } else {
750         result
751     }
752 }
753
754 fn do_normalize_predicates<'tcx>(
755     tcx: TyCtxt<'tcx>,
756     region_context: DefId,
757     cause: ObligationCause<'tcx>,
758     elaborated_env: ty::ParamEnv<'tcx>,
759     predicates: Vec<ty::Predicate<'tcx>>,
760 ) -> Result<Vec<ty::Predicate<'tcx>>, ErrorReported> {
761     debug!(
762         "do_normalize_predicates(predicates={:?}, region_context={:?}, cause={:?})",
763         predicates,
764         region_context,
765         cause,
766     );
767     let span = cause.span;
768     tcx.infer_ctxt().enter(|infcx| {
769         // FIXME. We should really... do something with these region
770         // obligations. But this call just continues the older
771         // behavior (i.e., doesn't cause any new bugs), and it would
772         // take some further refactoring to actually solve them. In
773         // particular, we would have to handle implied bounds
774         // properly, and that code is currently largely confined to
775         // regionck (though I made some efforts to extract it
776         // out). -nmatsakis
777         //
778         // @arielby: In any case, these obligations are checked
779         // by wfcheck anyway, so I'm not sure we have to check
780         // them here too, and we will remove this function when
781         // we move over to lazy normalization *anyway*.
782         let fulfill_cx = FulfillmentContext::new_ignoring_regions();
783         let predicates = match fully_normalize(
784             &infcx,
785             fulfill_cx,
786             cause,
787             elaborated_env,
788             &predicates,
789         ) {
790             Ok(predicates) => predicates,
791             Err(errors) => {
792                 infcx.report_fulfillment_errors(&errors, None, false);
793                 return Err(ErrorReported)
794             }
795         };
796
797         debug!("do_normalize_predictes: normalized predicates = {:?}", predicates);
798
799         let region_scope_tree = region::ScopeTree::default();
800
801         // We can use the `elaborated_env` here; the region code only
802         // cares about declarations like `'a: 'b`.
803         let outlives_env = OutlivesEnvironment::new(elaborated_env);
804
805         infcx.resolve_regions_and_report_errors(
806             region_context,
807             &region_scope_tree,
808             &outlives_env,
809             SuppressRegionErrors::default(),
810         );
811
812         let predicates = match infcx.fully_resolve(&predicates) {
813             Ok(predicates) => predicates,
814             Err(fixup_err) => {
815                 // If we encounter a fixup error, it means that some type
816                 // variable wound up unconstrained. I actually don't know
817                 // if this can happen, and I certainly don't expect it to
818                 // happen often, but if it did happen it probably
819                 // represents a legitimate failure due to some kind of
820                 // unconstrained variable, and it seems better not to ICE,
821                 // all things considered.
822                 tcx.sess.span_err(span, &fixup_err.to_string());
823                 return Err(ErrorReported)
824             }
825         };
826         if predicates.has_local_value() {
827             // FIXME: shouldn't we, you know, actually report an error here? or an ICE?
828             Err(ErrorReported)
829         } else {
830             Ok(predicates)
831         }
832     })
833 }
834
835 // FIXME: this is gonna need to be removed ...
836 /// Normalizes the parameter environment, reporting errors if they occur.
837 pub fn normalize_param_env_or_error<'tcx>(
838     tcx: TyCtxt<'tcx>,
839     region_context: DefId,
840     unnormalized_env: ty::ParamEnv<'tcx>,
841     cause: ObligationCause<'tcx>,
842 ) -> ty::ParamEnv<'tcx> {
843     // I'm not wild about reporting errors here; I'd prefer to
844     // have the errors get reported at a defined place (e.g.,
845     // during typeck). Instead I have all parameter
846     // environments, in effect, going through this function
847     // and hence potentially reporting errors. This ensures of
848     // course that we never forget to normalize (the
849     // alternative seemed like it would involve a lot of
850     // manual invocations of this fn -- and then we'd have to
851     // deal with the errors at each of those sites).
852     //
853     // In any case, in practice, typeck constructs all the
854     // parameter environments once for every fn as it goes,
855     // and errors will get reported then; so after typeck we
856     // can be sure that no errors should occur.
857
858     debug!("normalize_param_env_or_error(region_context={:?}, unnormalized_env={:?}, cause={:?})",
859            region_context, unnormalized_env, cause);
860
861     let mut predicates: Vec<_> =
862         util::elaborate_predicates(tcx, unnormalized_env.caller_bounds.to_vec())
863             .collect();
864
865     debug!("normalize_param_env_or_error: elaborated-predicates={:?}",
866            predicates);
867
868     let elaborated_env = ty::ParamEnv::new(
869         tcx.intern_predicates(&predicates),
870         unnormalized_env.reveal,
871         unnormalized_env.def_id
872     );
873
874     // HACK: we are trying to normalize the param-env inside *itself*. The problem is that
875     // normalization expects its param-env to be already normalized, which means we have
876     // a circularity.
877     //
878     // The way we handle this is by normalizing the param-env inside an unnormalized version
879     // of the param-env, which means that if the param-env contains unnormalized projections,
880     // we'll have some normalization failures. This is unfortunate.
881     //
882     // Lazy normalization would basically handle this by treating just the
883     // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
884     //
885     // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
886     // types, so to make the situation less bad, we normalize all the predicates *but*
887     // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
888     // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
889     //
890     // This works fairly well because trait matching  does not actually care about param-env
891     // TypeOutlives predicates - these are normally used by regionck.
892     let outlives_predicates: Vec<_> = predicates.drain_filter(|predicate| {
893         match predicate {
894             ty::Predicate::TypeOutlives(..) => true,
895             _ => false
896         }
897     }).collect();
898
899     debug!("normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
900            predicates, outlives_predicates);
901     let non_outlives_predicates =
902         match do_normalize_predicates(tcx, region_context, cause.clone(),
903                                       elaborated_env, predicates) {
904             Ok(predicates) => predicates,
905             // An unnormalized env is better than nothing.
906             Err(ErrorReported) => {
907                 debug!("normalize_param_env_or_error: errored resolving non-outlives predicates");
908                 return elaborated_env
909             }
910         };
911
912     debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates);
913
914     // Not sure whether it is better to include the unnormalized TypeOutlives predicates
915     // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
916     // predicates here anyway. Keeping them here anyway because it seems safer.
917     let outlives_env: Vec<_> =
918         non_outlives_predicates.iter().chain(&outlives_predicates).cloned().collect();
919     let outlives_env = ty::ParamEnv::new(
920         tcx.intern_predicates(&outlives_env),
921         unnormalized_env.reveal,
922         None
923     );
924     let outlives_predicates =
925         match do_normalize_predicates(tcx, region_context, cause,
926                                       outlives_env, outlives_predicates) {
927             Ok(predicates) => predicates,
928             // An unnormalized env is better than nothing.
929             Err(ErrorReported) => {
930                 debug!("normalize_param_env_or_error: errored resolving outlives predicates");
931                 return elaborated_env
932             }
933         };
934     debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates);
935
936     let mut predicates = non_outlives_predicates;
937     predicates.extend(outlives_predicates);
938     debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
939     ty::ParamEnv::new(
940         tcx.intern_predicates(&predicates),
941         unnormalized_env.reveal,
942         unnormalized_env.def_id
943     )
944 }
945
946 pub fn fully_normalize<'a, 'tcx, T>(
947     infcx: &InferCtxt<'a, 'tcx>,
948     mut fulfill_cx: FulfillmentContext<'tcx>,
949     cause: ObligationCause<'tcx>,
950     param_env: ty::ParamEnv<'tcx>,
951     value: &T,
952 ) -> Result<T, Vec<FulfillmentError<'tcx>>>
953 where
954     T: TypeFoldable<'tcx>,
955 {
956     debug!("fully_normalize_with_fulfillcx(value={:?})", value);
957     let selcx = &mut SelectionContext::new(infcx);
958     let Normalized { value: normalized_value, obligations } =
959         project::normalize(selcx, param_env, cause, value);
960     debug!("fully_normalize: normalized_value={:?} obligations={:?}",
961            normalized_value,
962            obligations);
963     for obligation in obligations {
964         fulfill_cx.register_predicate_obligation(selcx.infcx(), obligation);
965     }
966
967     debug!("fully_normalize: select_all_or_error start");
968     fulfill_cx.select_all_or_error(infcx)?;
969     debug!("fully_normalize: select_all_or_error complete");
970     let resolved_value = infcx.resolve_vars_if_possible(&normalized_value);
971     debug!("fully_normalize: resolved_value={:?}", resolved_value);
972     Ok(resolved_value)
973 }
974
975 /// Normalizes the predicates and checks whether they hold in an empty
976 /// environment. If this returns false, then either normalize
977 /// encountered an error or one of the predicates did not hold. Used
978 /// when creating vtables to check for unsatisfiable methods.
979 fn normalize_and_test_predicates<'tcx>(
980     tcx: TyCtxt<'tcx>,
981     predicates: Vec<ty::Predicate<'tcx>>,
982 ) -> bool {
983     debug!("normalize_and_test_predicates(predicates={:?})",
984            predicates);
985
986     let result = tcx.infer_ctxt().enter(|infcx| {
987         let param_env = ty::ParamEnv::reveal_all();
988         let mut selcx = SelectionContext::new(&infcx);
989         let mut fulfill_cx = FulfillmentContext::new();
990         let cause = ObligationCause::dummy();
991         let Normalized { value: predicates, obligations } =
992             normalize(&mut selcx, param_env, cause.clone(), &predicates);
993         for obligation in obligations {
994             fulfill_cx.register_predicate_obligation(&infcx, obligation);
995         }
996         for predicate in predicates {
997             let obligation = Obligation::new(cause.clone(), param_env, predicate);
998             fulfill_cx.register_predicate_obligation(&infcx, obligation);
999         }
1000
1001         fulfill_cx.select_all_or_error(&infcx).is_ok()
1002     });
1003     debug!("normalize_and_test_predicates(predicates={:?}) = {:?}",
1004            predicates, result);
1005     result
1006 }
1007
1008 fn substitute_normalize_and_test_predicates<'tcx>(
1009     tcx: TyCtxt<'tcx>,
1010     key: (DefId, SubstsRef<'tcx>),
1011 ) -> bool {
1012     debug!("substitute_normalize_and_test_predicates(key={:?})",
1013            key);
1014
1015     let predicates = tcx.predicates_of(key.0).instantiate(tcx, key.1).predicates;
1016     let result = normalize_and_test_predicates(tcx, predicates);
1017
1018     debug!("substitute_normalize_and_test_predicates(key={:?}) = {:?}",
1019            key, result);
1020     result
1021 }
1022
1023 /// Given a trait `trait_ref`, iterates the vtable entries
1024 /// that come from `trait_ref`, including its supertraits.
1025 #[inline] // FIXME(#35870): avoid closures being unexported due to `impl Trait`.
1026 fn vtable_methods<'tcx>(
1027     tcx: TyCtxt<'tcx>,
1028     trait_ref: ty::PolyTraitRef<'tcx>,
1029 ) -> &'tcx [Option<(DefId, SubstsRef<'tcx>)>] {
1030     debug!("vtable_methods({:?})", trait_ref);
1031
1032     tcx.arena.alloc_from_iter(
1033         supertraits(tcx, trait_ref).flat_map(move |trait_ref| {
1034             let trait_methods = tcx.associated_items(trait_ref.def_id())
1035                 .filter(|item| item.kind == ty::AssocKind::Method);
1036
1037             // Now list each method's DefId and InternalSubsts (for within its trait).
1038             // If the method can never be called from this object, produce None.
1039             trait_methods.map(move |trait_method| {
1040                 debug!("vtable_methods: trait_method={:?}", trait_method);
1041                 let def_id = trait_method.def_id;
1042
1043                 // Some methods cannot be called on an object; skip those.
1044                 if !tcx.is_vtable_safe_method(trait_ref.def_id(), &trait_method) {
1045                     debug!("vtable_methods: not vtable safe");
1046                     return None;
1047                 }
1048
1049                 // The method may have some early-bound lifetimes; add regions for those.
1050                 let substs = trait_ref.map_bound(|trait_ref|
1051                     InternalSubsts::for_item(tcx, def_id, |param, _|
1052                         match param.kind {
1053                             GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(),
1054                             GenericParamDefKind::Type { .. } |
1055                             GenericParamDefKind::Const => {
1056                                 trait_ref.substs[param.index as usize]
1057                             }
1058                         }
1059                     )
1060                 );
1061
1062                 // The trait type may have higher-ranked lifetimes in it;
1063                 // erase them if they appear, so that we get the type
1064                 // at some particular call site.
1065                 let substs = tcx.normalize_erasing_late_bound_regions(
1066                     ty::ParamEnv::reveal_all(),
1067                     &substs
1068                 );
1069
1070                 // It's possible that the method relies on where-clauses that
1071                 // do not hold for this particular set of type parameters.
1072                 // Note that this method could then never be called, so we
1073                 // do not want to try and codegen it, in that case (see #23435).
1074                 let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs);
1075                 if !normalize_and_test_predicates(tcx, predicates.predicates) {
1076                     debug!("vtable_methods: predicates do not hold");
1077                     return None;
1078                 }
1079
1080                 Some((def_id, substs))
1081             })
1082         })
1083     )
1084 }
1085
1086 impl<'tcx, O> Obligation<'tcx, O> {
1087     pub fn new(cause: ObligationCause<'tcx>,
1088                param_env: ty::ParamEnv<'tcx>,
1089                predicate: O)
1090                -> Obligation<'tcx, O>
1091     {
1092         Obligation { cause, param_env, recursion_depth: 0, predicate }
1093     }
1094
1095     fn with_depth(cause: ObligationCause<'tcx>,
1096                   recursion_depth: usize,
1097                   param_env: ty::ParamEnv<'tcx>,
1098                   predicate: O)
1099                   -> Obligation<'tcx, O>
1100     {
1101         Obligation { cause, param_env, recursion_depth, predicate }
1102     }
1103
1104     pub fn misc(span: Span,
1105                 body_id: hir::HirId,
1106                 param_env: ty::ParamEnv<'tcx>,
1107                 trait_ref: O)
1108                 -> Obligation<'tcx, O> {
1109         Obligation::new(ObligationCause::misc(span, body_id), param_env, trait_ref)
1110     }
1111
1112     pub fn with<P>(&self, value: P) -> Obligation<'tcx,P> {
1113         Obligation { cause: self.cause.clone(),
1114                      param_env: self.param_env,
1115                      recursion_depth: self.recursion_depth,
1116                      predicate: value }
1117     }
1118 }
1119
1120 impl<'tcx> ObligationCause<'tcx> {
1121     #[inline]
1122     pub fn new(span: Span,
1123                body_id: hir::HirId,
1124                code: ObligationCauseCode<'tcx>)
1125                -> ObligationCause<'tcx> {
1126         ObligationCause { span, body_id, code }
1127     }
1128
1129     pub fn misc(span: Span, body_id: hir::HirId) -> ObligationCause<'tcx> {
1130         ObligationCause { span, body_id, code: MiscObligation }
1131     }
1132
1133     pub fn dummy() -> ObligationCause<'tcx> {
1134         ObligationCause { span: DUMMY_SP, body_id: hir::CRATE_HIR_ID, code: MiscObligation }
1135     }
1136 }
1137
1138 impl<'tcx, N> Vtable<'tcx, N> {
1139     pub fn nested_obligations(self) -> Vec<N> {
1140         match self {
1141             VtableImpl(i) => i.nested,
1142             VtableParam(n) => n,
1143             VtableBuiltin(i) => i.nested,
1144             VtableAutoImpl(d) => d.nested,
1145             VtableClosure(c) => c.nested,
1146             VtableGenerator(c) => c.nested,
1147             VtableObject(d) => d.nested,
1148             VtableFnPointer(d) => d.nested,
1149             VtableTraitAlias(d) => d.nested,
1150         }
1151     }
1152
1153     pub fn map<M, F>(self, f: F) -> Vtable<'tcx, M> where F: FnMut(N) -> M {
1154         match self {
1155             VtableImpl(i) => VtableImpl(VtableImplData {
1156                 impl_def_id: i.impl_def_id,
1157                 substs: i.substs,
1158                 nested: i.nested.into_iter().map(f).collect(),
1159             }),
1160             VtableParam(n) => VtableParam(n.into_iter().map(f).collect()),
1161             VtableBuiltin(i) => VtableBuiltin(VtableBuiltinData {
1162                 nested: i.nested.into_iter().map(f).collect(),
1163             }),
1164             VtableObject(o) => VtableObject(VtableObjectData {
1165                 upcast_trait_ref: o.upcast_trait_ref,
1166                 vtable_base: o.vtable_base,
1167                 nested: o.nested.into_iter().map(f).collect(),
1168             }),
1169             VtableAutoImpl(d) => VtableAutoImpl(VtableAutoImplData {
1170                 trait_def_id: d.trait_def_id,
1171                 nested: d.nested.into_iter().map(f).collect(),
1172             }),
1173             VtableClosure(c) => VtableClosure(VtableClosureData {
1174                 closure_def_id: c.closure_def_id,
1175                 substs: c.substs,
1176                 nested: c.nested.into_iter().map(f).collect(),
1177             }),
1178             VtableGenerator(c) => VtableGenerator(VtableGeneratorData {
1179                 generator_def_id: c.generator_def_id,
1180                 substs: c.substs,
1181                 nested: c.nested.into_iter().map(f).collect(),
1182             }),
1183             VtableFnPointer(p) => VtableFnPointer(VtableFnPointerData {
1184                 fn_ty: p.fn_ty,
1185                 nested: p.nested.into_iter().map(f).collect(),
1186             }),
1187             VtableTraitAlias(d) => VtableTraitAlias(VtableTraitAliasData {
1188                 alias_def_id: d.alias_def_id,
1189                 substs: d.substs,
1190                 nested: d.nested.into_iter().map(f).collect(),
1191             }),
1192         }
1193     }
1194 }
1195
1196 impl<'tcx> FulfillmentError<'tcx> {
1197     fn new(obligation: PredicateObligation<'tcx>,
1198            code: FulfillmentErrorCode<'tcx>)
1199            -> FulfillmentError<'tcx>
1200     {
1201         FulfillmentError { obligation: obligation, code: code, points_at_arg_span: false }
1202     }
1203 }
1204
1205 impl<'tcx> TraitObligation<'tcx> {
1206     fn self_ty(&self) -> ty::Binder<Ty<'tcx>> {
1207         self.predicate.map_bound(|p| p.self_ty())
1208     }
1209 }
1210
1211 pub fn provide(providers: &mut ty::query::Providers<'_>) {
1212     *providers = ty::query::Providers {
1213         is_object_safe: object_safety::is_object_safe_provider,
1214         specialization_graph_of: specialize::specialization_graph_provider,
1215         specializes: specialize::specializes,
1216         codegen_fulfill_obligation: codegen::codegen_fulfill_obligation,
1217         vtable_methods,
1218         substitute_normalize_and_test_predicates,
1219         ..*providers
1220     };
1221 }
1222
1223 pub trait ExClauseFold<'tcx>
1224 where
1225     Self: chalk_engine::context::Context + Clone,
1226 {
1227     fn fold_ex_clause_with<F: TypeFolder<'tcx>>(
1228         ex_clause: &chalk_engine::ExClause<Self>,
1229         folder: &mut F,
1230     ) -> chalk_engine::ExClause<Self>;
1231
1232     fn visit_ex_clause_with<V: TypeVisitor<'tcx>>(
1233         ex_clause: &chalk_engine::ExClause<Self>,
1234         visitor: &mut V,
1235     ) -> bool;
1236 }
1237
1238 pub trait ChalkContextLift<'tcx>
1239 where
1240     Self: chalk_engine::context::Context + Clone,
1241 {
1242     type LiftedExClause: Debug + 'tcx;
1243     type LiftedDelayedLiteral: Debug + 'tcx;
1244     type LiftedLiteral: Debug + 'tcx;
1245
1246     fn lift_ex_clause_to_tcx(
1247         ex_clause: &chalk_engine::ExClause<Self>,
1248         tcx: TyCtxt<'tcx>,
1249     ) -> Option<Self::LiftedExClause>;
1250
1251     fn lift_delayed_literal_to_tcx(
1252         ex_clause: &chalk_engine::DelayedLiteral<Self>,
1253         tcx: TyCtxt<'tcx>,
1254     ) -> Option<Self::LiftedDelayedLiteral>;
1255
1256     fn lift_literal_to_tcx(
1257         ex_clause: &chalk_engine::Literal<Self>,
1258         tcx: TyCtxt<'tcx>,
1259     ) -> Option<Self::LiftedLiteral>;
1260 }