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