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