]> git.lizzy.rs Git - rust.git/blob - src/librustc/traits/mod.rs
Auto merge of #65288 - estebank:point-at-assoc-type, r=nikomatsakis
[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] --> T must be Copy
210     RepeatVec,
211
212     /// Types of fields (other than the last, except for packed structs) in a struct must be sized.
213     FieldSized { adt_kind: AdtKind, last: bool },
214
215     /// Constant expressions must be sized.
216     ConstSized,
217
218     /// Static items must have `Sync` type
219     SharedStatic,
220
221     BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
222
223     ImplDerivedObligation(DerivedObligationCause<'tcx>),
224
225     /// Error derived when matching traits/impls; see ObligationCause for more details
226     CompareImplMethodObligation {
227         item_name: ast::Name,
228         impl_item_def_id: DefId,
229         trait_item_def_id: DefId,
230     },
231
232     /// Checking that this expression can be assigned where it needs to be
233     // FIXME(eddyb) #11161 is the original Expr required?
234     ExprAssignable,
235
236     /// Computing common supertype in the arms of a match expression
237     MatchExpressionArm(Box<MatchExpressionArmCause<'tcx>>),
238
239     /// Computing common supertype in the pattern guard for the arms of a match expression
240     MatchExpressionArmPattern { span: Span, ty: Ty<'tcx> },
241
242     /// Computing common supertype in an if expression
243     IfExpression(Box<IfExpressionCause>),
244
245     /// Computing common supertype of an if expression with no else counter-part
246     IfExpressionWithNoElse,
247
248     /// `main` has wrong type
249     MainFunctionType,
250
251     /// `start` has wrong type
252     StartFunctionType,
253
254     /// Intrinsic has wrong type
255     IntrinsicType,
256
257     /// Method receiver
258     MethodReceiver,
259
260     /// `return` with no expression
261     ReturnNoExpression,
262
263     /// `return` with an expression
264     ReturnValue(hir::HirId),
265
266     /// Return type of this function
267     ReturnType,
268
269     /// Block implicit return
270     BlockTailExpression(hir::HirId),
271
272     /// #[feature(trivial_bounds)] is not enabled
273     TrivialBound,
274
275     AssocTypeBound(/*impl*/ Option<Span>, /*original*/ Span),
276 }
277
278 // `ObligationCauseCode` is used a lot. Make sure it doesn't unintentionally get bigger.
279 #[cfg(target_arch = "x86_64")]
280 static_assert_size!(ObligationCauseCode<'_>, 32);
281
282 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
283 pub struct MatchExpressionArmCause<'tcx> {
284     pub arm_span: Span,
285     pub source: hir::MatchSource,
286     pub prior_arms: Vec<Span>,
287     pub last_ty: Ty<'tcx>,
288     pub discrim_hir_id: hir::HirId,
289 }
290
291 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
292 pub struct IfExpressionCause {
293     pub then: Span,
294     pub outer: Option<Span>,
295     pub semicolon: Option<Span>,
296 }
297
298 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
299 pub struct DerivedObligationCause<'tcx> {
300     /// The trait reference of the parent obligation that led to the
301     /// current obligation. Note that only trait obligations lead to
302     /// derived obligations, so we just store the trait reference here
303     /// directly.
304     parent_trait_ref: ty::PolyTraitRef<'tcx>,
305
306     /// The parent trait had this cause.
307     parent_code: Rc<ObligationCauseCode<'tcx>>
308 }
309
310 pub type Obligations<'tcx, O> = Vec<Obligation<'tcx, O>>;
311 pub type PredicateObligations<'tcx> = Vec<PredicateObligation<'tcx>>;
312 pub type TraitObligations<'tcx> = Vec<TraitObligation<'tcx>>;
313
314 /// The following types:
315 /// * `WhereClause`,
316 /// * `WellFormed`,
317 /// * `FromEnv`,
318 /// * `DomainGoal`,
319 /// * `Goal`,
320 /// * `Clause`,
321 /// * `Environment`,
322 /// * `InEnvironment`,
323 /// are used for representing the trait system in the form of
324 /// logic programming clauses. They are part of the interface
325 /// for the chalk SLG solver.
326 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable)]
327 pub enum WhereClause<'tcx> {
328     Implemented(ty::TraitPredicate<'tcx>),
329     ProjectionEq(ty::ProjectionPredicate<'tcx>),
330     RegionOutlives(ty::RegionOutlivesPredicate<'tcx>),
331     TypeOutlives(ty::TypeOutlivesPredicate<'tcx>),
332 }
333
334 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable)]
335 pub enum WellFormed<'tcx> {
336     Trait(ty::TraitPredicate<'tcx>),
337     Ty(Ty<'tcx>),
338 }
339
340 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable)]
341 pub enum FromEnv<'tcx> {
342     Trait(ty::TraitPredicate<'tcx>),
343     Ty(Ty<'tcx>),
344 }
345
346 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable)]
347 pub enum DomainGoal<'tcx> {
348     Holds(WhereClause<'tcx>),
349     WellFormed(WellFormed<'tcx>),
350     FromEnv(FromEnv<'tcx>),
351     Normalize(ty::ProjectionPredicate<'tcx>),
352 }
353
354 pub type PolyDomainGoal<'tcx> = ty::Binder<DomainGoal<'tcx>>;
355
356 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
357 pub enum QuantifierKind {
358     Universal,
359     Existential,
360 }
361
362 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
363 pub enum GoalKind<'tcx> {
364     Implies(Clauses<'tcx>, Goal<'tcx>),
365     And(Goal<'tcx>, Goal<'tcx>),
366     Not(Goal<'tcx>),
367     DomainGoal(DomainGoal<'tcx>),
368     Quantified(QuantifierKind, ty::Binder<Goal<'tcx>>),
369     Subtype(Ty<'tcx>, Ty<'tcx>),
370     CannotProve,
371 }
372
373 pub type Goal<'tcx> = &'tcx GoalKind<'tcx>;
374
375 pub type Goals<'tcx> = &'tcx List<Goal<'tcx>>;
376
377 impl<'tcx> DomainGoal<'tcx> {
378     pub fn into_goal(self) -> GoalKind<'tcx> {
379         GoalKind::DomainGoal(self)
380     }
381
382     pub fn into_program_clause(self) -> ProgramClause<'tcx> {
383         ProgramClause {
384             goal: self,
385             hypotheses: ty::List::empty(),
386             category: ProgramClauseCategory::Other,
387         }
388     }
389 }
390
391 impl<'tcx> GoalKind<'tcx> {
392     pub fn from_poly_domain_goal(
393         domain_goal: PolyDomainGoal<'tcx>,
394         tcx: TyCtxt<'tcx>,
395     ) -> GoalKind<'tcx> {
396         match domain_goal.no_bound_vars() {
397             Some(p) => p.into_goal(),
398             None => GoalKind::Quantified(
399                 QuantifierKind::Universal,
400                 domain_goal.map_bound(|p| tcx.mk_goal(p.into_goal()))
401             ),
402         }
403     }
404 }
405
406 /// This matches the definition from Page 7 of "A Proof Procedure for the Logic of Hereditary
407 /// Harrop Formulas".
408 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
409 pub enum Clause<'tcx> {
410     Implies(ProgramClause<'tcx>),
411     ForAll(ty::Binder<ProgramClause<'tcx>>),
412 }
413
414 impl Clause<'tcx> {
415     pub fn category(self) -> ProgramClauseCategory {
416         match self {
417             Clause::Implies(clause) => clause.category,
418             Clause::ForAll(clause) => clause.skip_binder().category,
419         }
420     }
421 }
422
423 /// Multiple clauses.
424 pub type Clauses<'tcx> = &'tcx List<Clause<'tcx>>;
425
426 /// A "program clause" has the form `D :- G1, ..., Gn`. It is saying
427 /// that the domain goal `D` is true if `G1...Gn` are provable. This
428 /// is equivalent to the implication `G1..Gn => D`; we usually write
429 /// it with the reverse implication operator `:-` to emphasize the way
430 /// that programs are actually solved (via backchaining, which starts
431 /// with the goal to solve and proceeds from there).
432 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
433 pub struct ProgramClause<'tcx> {
434     /// This goal will be considered true ...
435     pub goal: DomainGoal<'tcx>,
436
437     /// ... if we can prove these hypotheses (there may be no hypotheses at all):
438     pub hypotheses: Goals<'tcx>,
439
440     /// Useful for filtering clauses.
441     pub category: ProgramClauseCategory,
442 }
443
444 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
445 pub enum ProgramClauseCategory {
446     ImpliedBound,
447     WellFormed,
448     Other,
449 }
450
451 /// A set of clauses that we assume to be true.
452 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
453 pub struct Environment<'tcx> {
454     pub clauses: Clauses<'tcx>,
455 }
456
457 impl Environment<'tcx> {
458     pub fn with<G>(self, goal: G) -> InEnvironment<'tcx, G> {
459         InEnvironment {
460             environment: self,
461             goal,
462         }
463     }
464 }
465
466 /// Something (usually a goal), along with an environment.
467 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
468 pub struct InEnvironment<'tcx, G> {
469     pub environment: Environment<'tcx>,
470     pub goal: G,
471 }
472
473 pub type Selection<'tcx> = Vtable<'tcx, PredicateObligation<'tcx>>;
474
475 #[derive(Clone,Debug)]
476 pub enum SelectionError<'tcx> {
477     Unimplemented,
478     OutputTypeParameterMismatch(ty::PolyTraitRef<'tcx>,
479                                 ty::PolyTraitRef<'tcx>,
480                                 ty::error::TypeError<'tcx>),
481     TraitNotObjectSafe(DefId),
482     ConstEvalFailure(ErrorHandled),
483     Overflow,
484 }
485
486 EnumTypeFoldableImpl! {
487     impl<'tcx> TypeFoldable<'tcx> for SelectionError<'tcx> {
488         (SelectionError::Unimplemented),
489         (SelectionError::OutputTypeParameterMismatch)(a, b, c),
490         (SelectionError::TraitNotObjectSafe)(a),
491         (SelectionError::ConstEvalFailure)(a),
492         (SelectionError::Overflow),
493     }
494 }
495
496 pub struct FulfillmentError<'tcx> {
497     pub obligation: PredicateObligation<'tcx>,
498     pub code: FulfillmentErrorCode<'tcx>,
499     /// Diagnostics only: we opportunistically change the `code.span` when we encounter an
500     /// obligation error caused by a call argument. When this is the case, we also signal that in
501     /// this field to ensure accuracy of suggestions.
502     pub points_at_arg_span: bool,
503 }
504
505 #[derive(Clone)]
506 pub enum FulfillmentErrorCode<'tcx> {
507     CodeSelectionError(SelectionError<'tcx>),
508     CodeProjectionError(MismatchedProjectionTypes<'tcx>),
509     CodeSubtypeError(ExpectedFound<Ty<'tcx>>,
510                      TypeError<'tcx>), // always comes from a SubtypePredicate
511     CodeAmbiguity,
512 }
513
514 /// When performing resolution, it is typically the case that there
515 /// can be one of three outcomes:
516 ///
517 /// - `Ok(Some(r))`: success occurred with result `r`
518 /// - `Ok(None)`: could not definitely determine anything, usually due
519 ///   to inconclusive type inference.
520 /// - `Err(e)`: error `e` occurred
521 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
522
523 /// Given the successful resolution of an obligation, the `Vtable`
524 /// indicates where the vtable comes from. Note that while we call this
525 /// a "vtable", it does not necessarily indicate dynamic dispatch at
526 /// runtime. `Vtable` instances just tell the compiler where to find
527 /// methods, but in generic code those methods are typically statically
528 /// dispatched -- only when an object is constructed is a `Vtable`
529 /// instance reified into an actual vtable.
530 ///
531 /// For example, the vtable may be tied to a specific impl (case A),
532 /// or it may be relative to some bound that is in scope (case B).
533 ///
534 /// ```
535 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
536 /// impl<T:Clone> Clone<T> for Box<T> { ... }    // Impl_2
537 /// impl Clone for int { ... }             // Impl_3
538 ///
539 /// fn foo<T:Clone>(concrete: Option<Box<int>>,
540 ///                 param: T,
541 ///                 mixed: Option<T>) {
542 ///
543 ///    // Case A: Vtable points at a specific impl. Only possible when
544 ///    // type is concretely known. If the impl itself has bounded
545 ///    // type parameters, Vtable will carry resolutions for those as well:
546 ///    concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
547 ///
548 ///    // Case B: Vtable must be provided by caller. This applies when
549 ///    // type is a type parameter.
550 ///    param.clone();    // VtableParam
551 ///
552 ///    // Case C: A mix of cases A and B.
553 ///    mixed.clone();    // Vtable(Impl_1, [VtableParam])
554 /// }
555 /// ```
556 ///
557 /// ### The type parameter `N`
558 ///
559 /// See explanation on `VtableImplData`.
560 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
561 pub enum Vtable<'tcx, N> {
562     /// Vtable identifying a particular impl.
563     VtableImpl(VtableImplData<'tcx, N>),
564
565     /// Vtable for auto trait implementations.
566     /// This carries the information and nested obligations with regards
567     /// to an auto implementation for a trait `Trait`. The nested obligations
568     /// ensure the trait implementation holds for all the constituent types.
569     VtableAutoImpl(VtableAutoImplData<N>),
570
571     /// Successful resolution to an obligation provided by the caller
572     /// for some type parameter. The `Vec<N>` represents the
573     /// obligations incurred from normalizing the where-clause (if
574     /// any).
575     VtableParam(Vec<N>),
576
577     /// Virtual calls through an object.
578     VtableObject(VtableObjectData<'tcx, N>),
579
580     /// Successful resolution for a builtin trait.
581     VtableBuiltin(VtableBuiltinData<N>),
582
583     /// Vtable automatically generated for a closure. The `DefId` is the ID
584     /// of the closure expression. This is a `VtableImpl` in spirit, but the
585     /// impl is generated by the compiler and does not appear in the source.
586     VtableClosure(VtableClosureData<'tcx, N>),
587
588     /// Same as above, but for a function pointer type with the given signature.
589     VtableFnPointer(VtableFnPointerData<'tcx, N>),
590
591     /// Vtable automatically generated for a generator.
592     VtableGenerator(VtableGeneratorData<'tcx, N>),
593
594     /// Vtable for a trait alias.
595     VtableTraitAlias(VtableTraitAliasData<'tcx, N>),
596 }
597
598 /// Identifies a particular impl in the source, along with a set of
599 /// substitutions from the impl's type/lifetime parameters. The
600 /// `nested` vector corresponds to the nested obligations attached to
601 /// the impl's type parameters.
602 ///
603 /// The type parameter `N` indicates the type used for "nested
604 /// obligations" that are required by the impl. During type check, this
605 /// is `Obligation`, as one might expect. During codegen, however, this
606 /// is `()`, because codegen only requires a shallow resolution of an
607 /// impl, and nested obligations are satisfied later.
608 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
609 pub struct VtableImplData<'tcx, N> {
610     pub impl_def_id: DefId,
611     pub substs: SubstsRef<'tcx>,
612     pub nested: Vec<N>
613 }
614
615 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
616 pub struct VtableGeneratorData<'tcx, N> {
617     pub generator_def_id: DefId,
618     pub substs: SubstsRef<'tcx>,
619     /// Nested obligations. This can be non-empty if the generator
620     /// signature contains associated types.
621     pub nested: Vec<N>
622 }
623
624 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
625 pub struct VtableClosureData<'tcx, N> {
626     pub closure_def_id: DefId,
627     pub substs: SubstsRef<'tcx>,
628     /// Nested obligations. This can be non-empty if the closure
629     /// signature contains associated types.
630     pub nested: Vec<N>
631 }
632
633 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
634 pub struct VtableAutoImplData<N> {
635     pub trait_def_id: DefId,
636     pub nested: Vec<N>
637 }
638
639 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
640 pub struct VtableBuiltinData<N> {
641     pub nested: Vec<N>
642 }
643
644 /// A vtable for some object-safe trait `Foo` automatically derived
645 /// for the object type `Foo`.
646 #[derive(PartialEq, Eq, Clone, RustcEncodable, RustcDecodable, HashStable)]
647 pub struct VtableObjectData<'tcx, N> {
648     /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
649     pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
650
651     /// The vtable is formed by concatenating together the method lists of
652     /// the base object trait and all supertraits; this is the start of
653     /// `upcast_trait_ref`'s methods in that vtable.
654     pub vtable_base: usize,
655
656     pub nested: Vec<N>,
657 }
658
659 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
660 pub struct VtableFnPointerData<'tcx, N> {
661     pub fn_ty: Ty<'tcx>,
662     pub nested: Vec<N>
663 }
664
665 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
666 pub struct VtableTraitAliasData<'tcx, N> {
667     pub alias_def_id: DefId,
668     pub substs: SubstsRef<'tcx>,
669     pub nested: Vec<N>,
670 }
671
672 /// Creates predicate obligations from the generic bounds.
673 pub fn predicates_for_generics<'tcx>(
674     cause: ObligationCause<'tcx>,
675     param_env: ty::ParamEnv<'tcx>,
676     generic_bounds: &ty::InstantiatedPredicates<'tcx>,
677 ) -> PredicateObligations<'tcx> {
678     util::predicates_for_generics(cause, 0, param_env, generic_bounds)
679 }
680
681 /// Determines whether the type `ty` is known to meet `bound` and
682 /// returns true if so. Returns false if `ty` either does not meet
683 /// `bound` or is not known to meet bound (note that this is
684 /// conservative towards *no impl*, which is the opposite of the
685 /// `evaluate` methods).
686 pub fn type_known_to_meet_bound_modulo_regions<'a, 'tcx>(
687     infcx: &InferCtxt<'a, 'tcx>,
688     param_env: ty::ParamEnv<'tcx>,
689     ty: Ty<'tcx>,
690     def_id: DefId,
691     span: Span,
692 ) -> bool {
693     debug!("type_known_to_meet_bound_modulo_regions(ty={:?}, bound={:?})",
694            ty,
695            infcx.tcx.def_path_str(def_id));
696
697     let trait_ref = ty::TraitRef {
698         def_id,
699         substs: infcx.tcx.mk_substs_trait(ty, &[]),
700     };
701     let obligation = Obligation {
702         param_env,
703         cause: ObligationCause::misc(span, hir::DUMMY_HIR_ID),
704         recursion_depth: 0,
705         predicate: trait_ref.to_predicate(),
706     };
707
708     let result = infcx.predicate_must_hold_modulo_regions(&obligation);
709     debug!("type_known_to_meet_ty={:?} bound={} => {:?}",
710            ty, infcx.tcx.def_path_str(def_id), result);
711
712     if result && (ty.has_infer_types() || ty.has_closure_types()) {
713         // Because of inference "guessing", selection can sometimes claim
714         // to succeed while the success requires a guess. To ensure
715         // this function's result remains infallible, we must confirm
716         // that guess. While imperfect, I believe this is sound.
717
718         // The handling of regions in this area of the code is terrible,
719         // see issue #29149. We should be able to improve on this with
720         // NLL.
721         let mut fulfill_cx = FulfillmentContext::new_ignoring_regions();
722
723         // We can use a dummy node-id here because we won't pay any mind
724         // to region obligations that arise (there shouldn't really be any
725         // anyhow).
726         let cause = ObligationCause::misc(span, hir::DUMMY_HIR_ID);
727
728         fulfill_cx.register_bound(infcx, param_env, ty, def_id, cause);
729
730         // Note: we only assume something is `Copy` if we can
731         // *definitively* show that it implements `Copy`. Otherwise,
732         // assume it is move; linear is always ok.
733         match fulfill_cx.select_all_or_error(infcx) {
734             Ok(()) => {
735                 debug!("type_known_to_meet_bound_modulo_regions: ty={:?} bound={} success",
736                        ty,
737                        infcx.tcx.def_path_str(def_id));
738                 true
739             }
740             Err(e) => {
741                 debug!("type_known_to_meet_bound_modulo_regions: ty={:?} bound={} errors={:?}",
742                        ty,
743                        infcx.tcx.def_path_str(def_id),
744                        e);
745                 false
746             }
747         }
748     } else {
749         result
750     }
751 }
752
753 fn do_normalize_predicates<'tcx>(
754     tcx: TyCtxt<'tcx>,
755     region_context: DefId,
756     cause: ObligationCause<'tcx>,
757     elaborated_env: ty::ParamEnv<'tcx>,
758     predicates: Vec<ty::Predicate<'tcx>>,
759 ) -> Result<Vec<ty::Predicate<'tcx>>, ErrorReported> {
760     debug!(
761         "do_normalize_predicates(predicates={:?}, region_context={:?}, cause={:?})",
762         predicates,
763         region_context,
764         cause,
765     );
766     let span = cause.span;
767     tcx.infer_ctxt().enter(|infcx| {
768         // FIXME. We should really... do something with these region
769         // obligations. But this call just continues the older
770         // behavior (i.e., doesn't cause any new bugs), and it would
771         // take some further refactoring to actually solve them. In
772         // particular, we would have to handle implied bounds
773         // properly, and that code is currently largely confined to
774         // regionck (though I made some efforts to extract it
775         // out). -nmatsakis
776         //
777         // @arielby: In any case, these obligations are checked
778         // by wfcheck anyway, so I'm not sure we have to check
779         // them here too, and we will remove this function when
780         // we move over to lazy normalization *anyway*.
781         let fulfill_cx = FulfillmentContext::new_ignoring_regions();
782         let predicates = match fully_normalize(
783             &infcx,
784             fulfill_cx,
785             cause,
786             elaborated_env,
787             &predicates,
788         ) {
789             Ok(predicates) => predicates,
790             Err(errors) => {
791                 infcx.report_fulfillment_errors(&errors, None, false);
792                 return Err(ErrorReported)
793             }
794         };
795
796         debug!("do_normalize_predictes: normalized predicates = {:?}", predicates);
797
798         let region_scope_tree = region::ScopeTree::default();
799
800         // We can use the `elaborated_env` here; the region code only
801         // cares about declarations like `'a: 'b`.
802         let outlives_env = OutlivesEnvironment::new(elaborated_env);
803
804         infcx.resolve_regions_and_report_errors(
805             region_context,
806             &region_scope_tree,
807             &outlives_env,
808             SuppressRegionErrors::default(),
809         );
810
811         let predicates = match infcx.fully_resolve(&predicates) {
812             Ok(predicates) => predicates,
813             Err(fixup_err) => {
814                 // If we encounter a fixup error, it means that some type
815                 // variable wound up unconstrained. I actually don't know
816                 // if this can happen, and I certainly don't expect it to
817                 // happen often, but if it did happen it probably
818                 // represents a legitimate failure due to some kind of
819                 // unconstrained variable, and it seems better not to ICE,
820                 // all things considered.
821                 tcx.sess.span_err(span, &fixup_err.to_string());
822                 return Err(ErrorReported)
823             }
824         };
825         if predicates.has_local_value() {
826             // FIXME: shouldn't we, you know, actually report an error here? or an ICE?
827             Err(ErrorReported)
828         } else {
829             Ok(predicates)
830         }
831     })
832 }
833
834 // FIXME: this is gonna need to be removed ...
835 /// Normalizes the parameter environment, reporting errors if they occur.
836 pub fn normalize_param_env_or_error<'tcx>(
837     tcx: TyCtxt<'tcx>,
838     region_context: DefId,
839     unnormalized_env: ty::ParamEnv<'tcx>,
840     cause: ObligationCause<'tcx>,
841 ) -> ty::ParamEnv<'tcx> {
842     // I'm not wild about reporting errors here; I'd prefer to
843     // have the errors get reported at a defined place (e.g.,
844     // during typeck). Instead I have all parameter
845     // environments, in effect, going through this function
846     // and hence potentially reporting errors. This ensures of
847     // course that we never forget to normalize (the
848     // alternative seemed like it would involve a lot of
849     // manual invocations of this fn -- and then we'd have to
850     // deal with the errors at each of those sites).
851     //
852     // In any case, in practice, typeck constructs all the
853     // parameter environments once for every fn as it goes,
854     // and errors will get reported then; so after typeck we
855     // can be sure that no errors should occur.
856
857     debug!("normalize_param_env_or_error(region_context={:?}, unnormalized_env={:?}, cause={:?})",
858            region_context, unnormalized_env, cause);
859
860     let mut predicates: Vec<_> =
861         util::elaborate_predicates(tcx, unnormalized_env.caller_bounds.to_vec())
862             .collect();
863
864     debug!("normalize_param_env_or_error: elaborated-predicates={:?}",
865            predicates);
866
867     let elaborated_env = ty::ParamEnv::new(
868         tcx.intern_predicates(&predicates),
869         unnormalized_env.reveal,
870         unnormalized_env.def_id
871     );
872
873     // HACK: we are trying to normalize the param-env inside *itself*. The problem is that
874     // normalization expects its param-env to be already normalized, which means we have
875     // a circularity.
876     //
877     // The way we handle this is by normalizing the param-env inside an unnormalized version
878     // of the param-env, which means that if the param-env contains unnormalized projections,
879     // we'll have some normalization failures. This is unfortunate.
880     //
881     // Lazy normalization would basically handle this by treating just the
882     // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
883     //
884     // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
885     // types, so to make the situation less bad, we normalize all the predicates *but*
886     // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
887     // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
888     //
889     // This works fairly well because trait matching  does not actually care about param-env
890     // TypeOutlives predicates - these are normally used by regionck.
891     let outlives_predicates: Vec<_> = predicates.drain_filter(|predicate| {
892         match predicate {
893             ty::Predicate::TypeOutlives(..) => true,
894             _ => false
895         }
896     }).collect();
897
898     debug!("normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
899            predicates, outlives_predicates);
900     let non_outlives_predicates =
901         match do_normalize_predicates(tcx, region_context, cause.clone(),
902                                       elaborated_env, predicates) {
903             Ok(predicates) => predicates,
904             // An unnormalized env is better than nothing.
905             Err(ErrorReported) => {
906                 debug!("normalize_param_env_or_error: errored resolving non-outlives predicates");
907                 return elaborated_env
908             }
909         };
910
911     debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates);
912
913     // Not sure whether it is better to include the unnormalized TypeOutlives predicates
914     // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
915     // predicates here anyway. Keeping them here anyway because it seems safer.
916     let outlives_env: Vec<_> =
917         non_outlives_predicates.iter().chain(&outlives_predicates).cloned().collect();
918     let outlives_env = ty::ParamEnv::new(
919         tcx.intern_predicates(&outlives_env),
920         unnormalized_env.reveal,
921         None
922     );
923     let outlives_predicates =
924         match do_normalize_predicates(tcx, region_context, cause,
925                                       outlives_env, outlives_predicates) {
926             Ok(predicates) => predicates,
927             // An unnormalized env is better than nothing.
928             Err(ErrorReported) => {
929                 debug!("normalize_param_env_or_error: errored resolving outlives predicates");
930                 return elaborated_env
931             }
932         };
933     debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates);
934
935     let mut predicates = non_outlives_predicates;
936     predicates.extend(outlives_predicates);
937     debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
938     ty::ParamEnv::new(
939         tcx.intern_predicates(&predicates),
940         unnormalized_env.reveal,
941         unnormalized_env.def_id
942     )
943 }
944
945 pub fn fully_normalize<'a, 'tcx, T>(
946     infcx: &InferCtxt<'a, 'tcx>,
947     mut fulfill_cx: FulfillmentContext<'tcx>,
948     cause: ObligationCause<'tcx>,
949     param_env: ty::ParamEnv<'tcx>,
950     value: &T,
951 ) -> Result<T, Vec<FulfillmentError<'tcx>>>
952 where
953     T: TypeFoldable<'tcx>,
954 {
955     debug!("fully_normalize_with_fulfillcx(value={:?})", value);
956     let selcx = &mut SelectionContext::new(infcx);
957     let Normalized { value: normalized_value, obligations } =
958         project::normalize(selcx, param_env, cause, value);
959     debug!("fully_normalize: normalized_value={:?} obligations={:?}",
960            normalized_value,
961            obligations);
962     for obligation in obligations {
963         fulfill_cx.register_predicate_obligation(selcx.infcx(), obligation);
964     }
965
966     debug!("fully_normalize: select_all_or_error start");
967     fulfill_cx.select_all_or_error(infcx)?;
968     debug!("fully_normalize: select_all_or_error complete");
969     let resolved_value = infcx.resolve_vars_if_possible(&normalized_value);
970     debug!("fully_normalize: resolved_value={:?}", resolved_value);
971     Ok(resolved_value)
972 }
973
974 /// Normalizes the predicates and checks whether they hold in an empty
975 /// environment. If this returns false, then either normalize
976 /// encountered an error or one of the predicates did not hold. Used
977 /// when creating vtables to check for unsatisfiable methods.
978 fn normalize_and_test_predicates<'tcx>(
979     tcx: TyCtxt<'tcx>,
980     predicates: Vec<ty::Predicate<'tcx>>,
981 ) -> bool {
982     debug!("normalize_and_test_predicates(predicates={:?})",
983            predicates);
984
985     let result = tcx.infer_ctxt().enter(|infcx| {
986         let param_env = ty::ParamEnv::reveal_all();
987         let mut selcx = SelectionContext::new(&infcx);
988         let mut fulfill_cx = FulfillmentContext::new();
989         let cause = ObligationCause::dummy();
990         let Normalized { value: predicates, obligations } =
991             normalize(&mut selcx, param_env, cause.clone(), &predicates);
992         for obligation in obligations {
993             fulfill_cx.register_predicate_obligation(&infcx, obligation);
994         }
995         for predicate in predicates {
996             let obligation = Obligation::new(cause.clone(), param_env, predicate);
997             fulfill_cx.register_predicate_obligation(&infcx, obligation);
998         }
999
1000         fulfill_cx.select_all_or_error(&infcx).is_ok()
1001     });
1002     debug!("normalize_and_test_predicates(predicates={:?}) = {:?}",
1003            predicates, result);
1004     result
1005 }
1006
1007 fn substitute_normalize_and_test_predicates<'tcx>(
1008     tcx: TyCtxt<'tcx>,
1009     key: (DefId, SubstsRef<'tcx>),
1010 ) -> bool {
1011     debug!("substitute_normalize_and_test_predicates(key={:?})",
1012            key);
1013
1014     let predicates = tcx.predicates_of(key.0).instantiate(tcx, key.1).predicates;
1015     let result = normalize_and_test_predicates(tcx, predicates);
1016
1017     debug!("substitute_normalize_and_test_predicates(key={:?}) = {:?}",
1018            key, result);
1019     result
1020 }
1021
1022 /// Given a trait `trait_ref`, iterates the vtable entries
1023 /// that come from `trait_ref`, including its supertraits.
1024 #[inline] // FIXME(#35870): avoid closures being unexported due to `impl Trait`.
1025 fn vtable_methods<'tcx>(
1026     tcx: TyCtxt<'tcx>,
1027     trait_ref: ty::PolyTraitRef<'tcx>,
1028 ) -> &'tcx [Option<(DefId, SubstsRef<'tcx>)>] {
1029     debug!("vtable_methods({:?})", trait_ref);
1030
1031     tcx.arena.alloc_from_iter(
1032         supertraits(tcx, trait_ref).flat_map(move |trait_ref| {
1033             let trait_methods = tcx.associated_items(trait_ref.def_id())
1034                 .filter(|item| item.kind == ty::AssocKind::Method);
1035
1036             // Now list each method's DefId and InternalSubsts (for within its trait).
1037             // If the method can never be called from this object, produce None.
1038             trait_methods.map(move |trait_method| {
1039                 debug!("vtable_methods: trait_method={:?}", trait_method);
1040                 let def_id = trait_method.def_id;
1041
1042                 // Some methods cannot be called on an object; skip those.
1043                 if !tcx.is_vtable_safe_method(trait_ref.def_id(), &trait_method) {
1044                     debug!("vtable_methods: not vtable safe");
1045                     return None;
1046                 }
1047
1048                 // the method may have some early-bound lifetimes, add
1049                 // 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                 // so 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 }