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