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