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