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