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