1 //! Trait Resolution. See the [rustc guide] for more information on how this works.
3 //! [rustc guide]: https://rust-lang.github.io/rustc-guide/traits/resolution.html
9 pub mod error_reporting
;
24 use crate::hir
::def_id
::DefId
;
25 use crate::infer
::{InferCtxt, SuppressRegionErrors}
;
26 use crate::infer
::outlives
::env
::OutlivesEnvironment
;
27 use crate::middle
::region
;
28 use crate::mir
::interpret
::ErrorHandled
;
29 use rustc_data_structures
::sync
::Lrc
;
30 use rustc_macros
::HashStable
;
32 use syntax_pos
::{Span, DUMMY_SP}
;
33 use crate::ty
::subst
::{InternalSubsts, SubstsRef}
;
34 use crate::ty
::{self, AdtKind, List, Ty, TyCtxt, GenericParamDefKind, ToPredicate}
;
35 use crate::ty
::error
::{ExpectedFound, TypeError}
;
36 use crate::ty
::fold
::{TypeFolder, TypeFoldable, TypeVisitor}
;
37 use crate::util
::common
::ErrorReported
;
42 pub use self::SelectionError
::*;
43 pub use self::FulfillmentErrorCode
::*;
44 pub use self::Vtable
::*;
45 pub use self::ObligationCauseCode
::*;
47 pub use self::coherence
::{add_placeholder_note, orphan_check, overlapping_impls}
;
48 pub use self::coherence
::{OrphanCheckErr, OverlapResult}
;
49 pub use self::fulfill
::{FulfillmentContext, PendingPredicateObligation}
;
50 pub use self::project
::MismatchedProjectionTypes
;
51 pub use self::project
::{normalize, normalize_projection_type, poly_project_and_unify_type}
;
52 pub use self::project
::{ProjectionCache, ProjectionCacheSnapshot, Reveal, Normalized}
;
53 pub use self::object_safety
::ObjectSafetyViolation
;
54 pub use self::object_safety
::MethodViolationCode
;
55 pub use self::on_unimplemented
::{OnUnimplementedDirective, OnUnimplementedNote}
;
56 pub use self::select
::{EvaluationCache, SelectionContext, SelectionCache}
;
57 pub use self::select
::{EvaluationResult, IntercrateAmbiguityCause, OverflowError}
;
58 pub use self::specialize
::{OverlapError, specialization_graph, translate_substs}
;
59 pub use self::specialize
::find_associated_item
;
60 pub use self::specialize
::specialization_graph
::FutureCompatOverlapError
;
61 pub use self::specialize
::specialization_graph
::FutureCompatOverlapErrorKind
;
62 pub use self::engine
::{TraitEngine, TraitEngineExt}
;
63 pub use self::util
::{elaborate_predicates, elaborate_trait_ref, elaborate_trait_refs}
;
64 pub use self::util
::{supertraits
, supertrait_def_ids
, transitive_bounds
,
65 Supertraits
, SupertraitDefIds
};
67 pub use self::chalk_fulfill
::{
68 CanonicalGoal
as ChalkCanonicalGoal
,
69 FulfillmentContext
as ChalkFulfillmentContext
72 pub use self::ObligationCauseCode
::*;
73 pub use self::FulfillmentErrorCode
::*;
74 pub use self::SelectionError
::*;
75 pub use self::Vtable
::*;
77 /// Whether to enable bug compatibility with issue #43355.
78 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
79 pub enum IntercrateMode
{
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.
91 // Canonicalized queries get dummy spans and hence
92 // must generally propagate errors to
93 // pre-canonicalization callsites.
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 /// The reason we have to prove this thing.
106 pub cause
: ObligationCause
<'tcx
>,
108 /// The environment in which we should prove this thing.
109 pub param_env
: ty
::ParamEnv
<'tcx
>,
111 /// The thing we are trying to prove.
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,
122 pub type PredicateObligation
<'tcx
> = Obligation
<'tcx
, ty
::Predicate
<'tcx
>>;
123 pub type TraitObligation
<'tcx
> = Obligation
<'tcx
, ty
::PolyTraitPredicate
<'tcx
>>;
125 /// The reason why we incurred this obligation; used for error reporting.
126 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
127 pub struct ObligationCause
<'tcx
> {
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
136 pub body_id
: hir
::HirId
,
138 pub code
: ObligationCauseCode
<'tcx
>
141 impl<'tcx
> ObligationCause
<'tcx
> {
142 pub fn span
<'a
, 'gcx
>(&self, tcx
: &TyCtxt
<'a
, 'gcx
, 'tcx
>) -> Span
{
144 ObligationCauseCode
::CompareImplMethodObligation { .. }
|
145 ObligationCauseCode
::MainFunctionType
|
146 ObligationCauseCode
::StartFunctionType
=> {
147 tcx
.sess
.source_map().def_span(self.span
)
149 ObligationCauseCode
::MatchExpressionArm { arm_span, .. }
=> arm_span
,
155 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
156 pub enum ObligationCauseCode
<'tcx
> {
157 /// Not well classified or should be obvious from the span.
160 /// A slice or array is WF only if `T: Sized`.
163 /// A tuple is WF only if its middle elements are `Sized`.
166 /// This is the trait reference from the given projection.
167 ProjectionWf(ty
::ProjectionTy
<'tcx
>),
169 /// In an impl of trait `X` for type `Y`, type `Y` must
170 /// also implement all supertraits of `X`.
171 ItemObligation(DefId
),
173 /// A type like `&'a T` is WF only if `T: 'a`.
174 ReferenceOutlivesReferent(Ty
<'tcx
>),
176 /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
177 ObjectTypeBound(Ty
<'tcx
>, ty
::Region
<'tcx
>),
179 /// Obligation incurred due to an object cast.
180 ObjectCastObligation(/* Object type */ Ty
<'tcx
>),
182 // Various cases where expressions must be sized/copy/etc:
183 /// L = X implies that L is Sized
185 /// (x1, .., xn) must be Sized
186 TupleInitializerSized
,
187 /// S { ... } must be Sized
188 StructInitializerSized
,
189 /// Type of each variable must be Sized
190 VariableType(ast
::NodeId
),
191 /// Argument type must be Sized
193 /// Return type must be Sized
195 /// Yield type must be Sized
197 /// [T,..n] --> T must be Copy
200 /// Types of fields (other than the last, except for packed structs) in a struct must be sized.
201 FieldSized { adt_kind: AdtKind, last: bool }
,
203 /// Constant expressions must be sized.
206 /// static items must have `Sync` type
209 BuiltinDerivedObligation(DerivedObligationCause
<'tcx
>),
211 ImplDerivedObligation(DerivedObligationCause
<'tcx
>),
213 /// error derived when matching traits/impls; see ObligationCause for more details
214 CompareImplMethodObligation
{
215 item_name
: ast
::Name
,
216 impl_item_def_id
: DefId
,
217 trait_item_def_id
: DefId
,
220 /// Checking that this expression can be assigned where it needs to be
221 // FIXME(eddyb) #11161 is the original Expr required?
224 /// Computing common supertype in the arms of a match expression
227 source
: hir
::MatchSource
,
228 prior_arms
: Vec
<Span
>,
232 /// Computing common supertype in the pattern guard for the arms of a match expression
233 MatchExpressionArmPattern { span: Span, ty: Ty<'tcx> }
,
235 /// Computing common supertype in an if expression
239 semicolon
: Option
<Span
>,
242 /// Computing common supertype of an if expression with no else counter-part
243 IfExpressionWithNoElse
,
245 /// `main` has wrong type
248 /// `start` has wrong type
251 /// intrinsic has wrong type
257 /// `return` with no expression
260 /// `return` with an expression
261 ReturnType(hir
::HirId
),
263 /// Block implicit return
264 BlockTailExpression(hir
::HirId
),
266 /// #[feature(trivial_bounds)] is not enabled
270 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
271 pub struct DerivedObligationCause
<'tcx
> {
272 /// The trait reference of the parent obligation that led to the
273 /// current obligation. Note that only trait obligations lead to
274 /// derived obligations, so we just store the trait reference here
276 parent_trait_ref
: ty
::PolyTraitRef
<'tcx
>,
278 /// The parent trait had this cause.
279 parent_code
: Rc
<ObligationCauseCode
<'tcx
>>
282 pub type Obligations
<'tcx
, O
> = Vec
<Obligation
<'tcx
, O
>>;
283 pub type PredicateObligations
<'tcx
> = Vec
<PredicateObligation
<'tcx
>>;
284 pub type TraitObligations
<'tcx
> = Vec
<TraitObligation
<'tcx
>>;
286 /// The following types:
294 /// * `InEnvironment`,
295 /// are used for representing the trait system in the form of
296 /// logic programming clauses. They are part of the interface
297 /// for the chalk SLG solver.
298 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable)]
299 pub enum WhereClause
<'tcx
> {
300 Implemented(ty
::TraitPredicate
<'tcx
>),
301 ProjectionEq(ty
::ProjectionPredicate
<'tcx
>),
302 RegionOutlives(ty
::RegionOutlivesPredicate
<'tcx
>),
303 TypeOutlives(ty
::TypeOutlivesPredicate
<'tcx
>),
306 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable)]
307 pub enum WellFormed
<'tcx
> {
308 Trait(ty
::TraitPredicate
<'tcx
>),
312 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable)]
313 pub enum FromEnv
<'tcx
> {
314 Trait(ty
::TraitPredicate
<'tcx
>),
318 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable)]
319 pub enum DomainGoal
<'tcx
> {
320 Holds(WhereClause
<'tcx
>),
321 WellFormed(WellFormed
<'tcx
>),
322 FromEnv(FromEnv
<'tcx
>),
323 Normalize(ty
::ProjectionPredicate
<'tcx
>),
326 pub type PolyDomainGoal
<'tcx
> = ty
::Binder
<DomainGoal
<'tcx
>>;
328 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
329 pub enum QuantifierKind
{
334 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
335 pub enum GoalKind
<'tcx
> {
336 Implies(Clauses
<'tcx
>, Goal
<'tcx
>),
337 And(Goal
<'tcx
>, Goal
<'tcx
>),
339 DomainGoal(DomainGoal
<'tcx
>),
340 Quantified(QuantifierKind
, ty
::Binder
<Goal
<'tcx
>>),
341 Subtype(Ty
<'tcx
>, Ty
<'tcx
>),
345 pub type Goal
<'tcx
> = &'tcx GoalKind
<'tcx
>;
347 pub type Goals
<'tcx
> = &'tcx List
<Goal
<'tcx
>>;
349 impl<'tcx
> DomainGoal
<'tcx
> {
350 pub fn into_goal(self) -> GoalKind
<'tcx
> {
351 GoalKind
::DomainGoal(self)
354 pub fn into_program_clause(self) -> ProgramClause
<'tcx
> {
357 hypotheses
: ty
::List
::empty(),
358 category
: ProgramClauseCategory
::Other
,
363 impl<'tcx
> GoalKind
<'tcx
> {
364 pub fn from_poly_domain_goal
<'a
, 'gcx
>(
365 domain_goal
: PolyDomainGoal
<'tcx
>,
366 tcx
: TyCtxt
<'a
, 'gcx
, 'tcx
>,
367 ) -> GoalKind
<'tcx
> {
368 match domain_goal
.no_bound_vars() {
369 Some(p
) => p
.into_goal(),
370 None
=> GoalKind
::Quantified(
371 QuantifierKind
::Universal
,
372 domain_goal
.map_bound(|p
| tcx
.mk_goal(p
.into_goal()))
378 /// This matches the definition from Page 7 of "A Proof Procedure for the Logic of Hereditary
379 /// Harrop Formulas".
380 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
381 pub enum Clause
<'tcx
> {
382 Implies(ProgramClause
<'tcx
>),
383 ForAll(ty
::Binder
<ProgramClause
<'tcx
>>),
387 pub fn category(self) -> ProgramClauseCategory
{
389 Clause
::Implies(clause
) => clause
.category
,
390 Clause
::ForAll(clause
) => clause
.skip_binder().category
,
395 /// Multiple clauses.
396 pub type Clauses
<'tcx
> = &'tcx List
<Clause
<'tcx
>>;
398 /// A "program clause" has the form `D :- G1, ..., Gn`. It is saying
399 /// that the domain goal `D` is true if `G1...Gn` are provable. This
400 /// is equivalent to the implication `G1..Gn => D`; we usually write
401 /// it with the reverse implication operator `:-` to emphasize the way
402 /// that programs are actually solved (via backchaining, which starts
403 /// with the goal to solve and proceeds from there).
404 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
405 pub struct ProgramClause
<'tcx
> {
406 /// This goal will be considered true ...
407 pub goal
: DomainGoal
<'tcx
>,
409 /// ... if we can prove these hypotheses (there may be no hypotheses at all):
410 pub hypotheses
: Goals
<'tcx
>,
412 /// Useful for filtering clauses.
413 pub category
: ProgramClauseCategory
,
416 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
417 pub enum ProgramClauseCategory
{
423 /// A set of clauses that we assume to be true.
424 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
425 pub struct Environment
<'tcx
> {
426 pub clauses
: Clauses
<'tcx
>,
429 impl Environment
<'tcx
> {
430 pub fn with
<G
>(self, goal
: G
) -> InEnvironment
<'tcx
, G
> {
438 /// Something (usually a goal), along with an environment.
439 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
440 pub struct InEnvironment
<'tcx
, G
> {
441 pub environment
: Environment
<'tcx
>,
445 pub type Selection
<'tcx
> = Vtable
<'tcx
, PredicateObligation
<'tcx
>>;
447 #[derive(Clone,Debug)]
448 pub enum SelectionError
<'tcx
> {
450 OutputTypeParameterMismatch(ty
::PolyTraitRef
<'tcx
>,
451 ty
::PolyTraitRef
<'tcx
>,
452 ty
::error
::TypeError
<'tcx
>),
453 TraitNotObjectSafe(DefId
),
454 ConstEvalFailure(ErrorHandled
),
458 pub struct FulfillmentError
<'tcx
> {
459 pub obligation
: PredicateObligation
<'tcx
>,
460 pub code
: FulfillmentErrorCode
<'tcx
>
464 pub enum FulfillmentErrorCode
<'tcx
> {
465 CodeSelectionError(SelectionError
<'tcx
>),
466 CodeProjectionError(MismatchedProjectionTypes
<'tcx
>),
467 CodeSubtypeError(ExpectedFound
<Ty
<'tcx
>>,
468 TypeError
<'tcx
>), // always comes from a SubtypePredicate
472 /// When performing resolution, it is typically the case that there
473 /// can be one of three outcomes:
475 /// - `Ok(Some(r))`: success occurred with result `r`
476 /// - `Ok(None)`: could not definitely determine anything, usually due
477 /// to inconclusive type inference.
478 /// - `Err(e)`: error `e` occurred
479 pub type SelectionResult
<'tcx
, T
> = Result
<Option
<T
>, SelectionError
<'tcx
>>;
481 /// Given the successful resolution of an obligation, the `Vtable`
482 /// indicates where the vtable comes from. Note that while we call this
483 /// a "vtable", it does not necessarily indicate dynamic dispatch at
484 /// runtime. `Vtable` instances just tell the compiler where to find
485 /// methods, but in generic code those methods are typically statically
486 /// dispatched -- only when an object is constructed is a `Vtable`
487 /// instance reified into an actual vtable.
489 /// For example, the vtable may be tied to a specific impl (case A),
490 /// or it may be relative to some bound that is in scope (case B).
493 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
494 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
495 /// impl Clone for int { ... } // Impl_3
497 /// fn foo<T:Clone>(concrete: Option<Box<int>>,
499 /// mixed: Option<T>) {
501 /// // Case A: Vtable points at a specific impl. Only possible when
502 /// // type is concretely known. If the impl itself has bounded
503 /// // type parameters, Vtable will carry resolutions for those as well:
504 /// concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
506 /// // Case B: Vtable must be provided by caller. This applies when
507 /// // type is a type parameter.
508 /// param.clone(); // VtableParam
510 /// // Case C: A mix of cases A and B.
511 /// mixed.clone(); // Vtable(Impl_1, [VtableParam])
515 /// ### The type parameter `N`
517 /// See explanation on `VtableImplData`.
518 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
519 pub enum Vtable
<'tcx
, N
> {
520 /// Vtable identifying a particular impl.
521 VtableImpl(VtableImplData
<'tcx
, N
>),
523 /// Vtable for auto trait implementations.
524 /// This carries the information and nested obligations with regards
525 /// to an auto implementation for a trait `Trait`. The nested obligations
526 /// ensure the trait implementation holds for all the constituent types.
527 VtableAutoImpl(VtableAutoImplData
<N
>),
529 /// Successful resolution to an obligation provided by the caller
530 /// for some type parameter. The `Vec<N>` represents the
531 /// obligations incurred from normalizing the where-clause (if
535 /// Virtual calls through an object.
536 VtableObject(VtableObjectData
<'tcx
, N
>),
538 /// Successful resolution for a builtin trait.
539 VtableBuiltin(VtableBuiltinData
<N
>),
541 /// Vtable automatically generated for a closure. The `DefId` is the ID
542 /// of the closure expression. This is a `VtableImpl` in spirit, but the
543 /// impl is generated by the compiler and does not appear in the source.
544 VtableClosure(VtableClosureData
<'tcx
, N
>),
546 /// Same as above, but for a function pointer type with the given signature.
547 VtableFnPointer(VtableFnPointerData
<'tcx
, N
>),
549 /// Vtable automatically generated for a generator.
550 VtableGenerator(VtableGeneratorData
<'tcx
, N
>),
552 /// Vtable for a trait alias.
553 VtableTraitAlias(VtableTraitAliasData
<'tcx
, N
>),
556 /// Identifies a particular impl in the source, along with a set of
557 /// substitutions from the impl's type/lifetime parameters. The
558 /// `nested` vector corresponds to the nested obligations attached to
559 /// the impl's type parameters.
561 /// The type parameter `N` indicates the type used for "nested
562 /// obligations" that are required by the impl. During type check, this
563 /// is `Obligation`, as one might expect. During codegen, however, this
564 /// is `()`, because codegen only requires a shallow resolution of an
565 /// impl, and nested obligations are satisfied later.
566 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
567 pub struct VtableImplData
<'tcx
, N
> {
568 pub impl_def_id
: DefId
,
569 pub substs
: SubstsRef
<'tcx
>,
573 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
574 pub struct VtableGeneratorData
<'tcx
, N
> {
575 pub generator_def_id
: DefId
,
576 pub substs
: ty
::GeneratorSubsts
<'tcx
>,
577 /// Nested obligations. This can be non-empty if the generator
578 /// signature contains associated types.
582 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
583 pub struct VtableClosureData
<'tcx
, N
> {
584 pub closure_def_id
: DefId
,
585 pub substs
: ty
::ClosureSubsts
<'tcx
>,
586 /// Nested obligations. This can be non-empty if the closure
587 /// signature contains associated types.
591 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
592 pub struct VtableAutoImplData
<N
> {
593 pub trait_def_id
: DefId
,
597 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
598 pub struct VtableBuiltinData
<N
> {
602 /// A vtable for some object-safe trait `Foo` automatically derived
603 /// for the object type `Foo`.
604 #[derive(PartialEq, Eq, Clone, RustcEncodable, RustcDecodable, HashStable)]
605 pub struct VtableObjectData
<'tcx
, N
> {
606 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
607 pub upcast_trait_ref
: ty
::PolyTraitRef
<'tcx
>,
609 /// The vtable is formed by concatenating together the method lists of
610 /// the base object trait and all supertraits; this is the start of
611 /// `upcast_trait_ref`'s methods in that vtable.
612 pub vtable_base
: usize,
617 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
618 pub struct VtableFnPointerData
<'tcx
, N
> {
623 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable)]
624 pub struct VtableTraitAliasData
<'tcx
, N
> {
625 pub alias_def_id
: DefId
,
626 pub substs
: SubstsRef
<'tcx
>,
630 /// Creates predicate obligations from the generic bounds.
631 pub fn predicates_for_generics
<'tcx
>(cause
: ObligationCause
<'tcx
>,
632 param_env
: ty
::ParamEnv
<'tcx
>,
633 generic_bounds
: &ty
::InstantiatedPredicates
<'tcx
>)
634 -> PredicateObligations
<'tcx
>
636 util
::predicates_for_generics(cause
, 0, param_env
, generic_bounds
)
639 /// Determines whether the type `ty` is known to meet `bound` and
640 /// returns true if so. Returns false if `ty` either does not meet
641 /// `bound` or is not known to meet bound (note that this is
642 /// conservative towards *no impl*, which is the opposite of the
643 /// `evaluate` methods).
644 pub fn type_known_to_meet_bound_modulo_regions
<'a
, 'gcx
, 'tcx
>(
645 infcx
: &InferCtxt
<'a
, 'gcx
, 'tcx
>,
646 param_env
: ty
::ParamEnv
<'tcx
>,
651 debug
!("type_known_to_meet_bound_modulo_regions(ty={:?}, bound={:?})",
653 infcx
.tcx
.def_path_str(def_id
));
655 let trait_ref
= ty
::TraitRef
{
657 substs
: infcx
.tcx
.mk_substs_trait(ty
, &[]),
659 let obligation
= Obligation
{
661 cause
: ObligationCause
::misc(span
, hir
::DUMMY_HIR_ID
),
663 predicate
: trait_ref
.to_predicate(),
666 let result
= infcx
.predicate_must_hold_modulo_regions(&obligation
);
667 debug
!("type_known_to_meet_ty={:?} bound={} => {:?}",
668 ty
, infcx
.tcx
.def_path_str(def_id
), result
);
670 if result
&& (ty
.has_infer_types() || ty
.has_closure_types()) {
671 // Because of inference "guessing", selection can sometimes claim
672 // to succeed while the success requires a guess. To ensure
673 // this function's result remains infallible, we must confirm
674 // that guess. While imperfect, I believe this is sound.
676 // The handling of regions in this area of the code is terrible,
677 // see issue #29149. We should be able to improve on this with
679 let mut fulfill_cx
= FulfillmentContext
::new_ignoring_regions();
681 // We can use a dummy node-id here because we won't pay any mind
682 // to region obligations that arise (there shouldn't really be any
684 let cause
= ObligationCause
::misc(span
, hir
::DUMMY_HIR_ID
);
686 fulfill_cx
.register_bound(infcx
, param_env
, ty
, def_id
, cause
);
688 // Note: we only assume something is `Copy` if we can
689 // *definitively* show that it implements `Copy`. Otherwise,
690 // assume it is move; linear is always ok.
691 match fulfill_cx
.select_all_or_error(infcx
) {
693 debug
!("type_known_to_meet_bound_modulo_regions: ty={:?} bound={} success",
695 infcx
.tcx
.def_path_str(def_id
));
699 debug
!("type_known_to_meet_bound_modulo_regions: ty={:?} bound={} errors={:?}",
701 infcx
.tcx
.def_path_str(def_id
),
711 fn do_normalize_predicates
<'a
, 'tcx
>(tcx
: TyCtxt
<'a
, 'tcx
, 'tcx
>,
712 region_context
: DefId
,
713 cause
: ObligationCause
<'tcx
>,
714 elaborated_env
: ty
::ParamEnv
<'tcx
>,
715 predicates
: Vec
<ty
::Predicate
<'tcx
>>)
716 -> Result
<Vec
<ty
::Predicate
<'tcx
>>, ErrorReported
>
719 "do_normalize_predicates(predicates={:?}, region_context={:?}, cause={:?})",
724 let span
= cause
.span
;
725 tcx
.infer_ctxt().enter(|infcx
| {
726 // FIXME. We should really... do something with these region
727 // obligations. But this call just continues the older
728 // behavior (i.e., doesn't cause any new bugs), and it would
729 // take some further refactoring to actually solve them. In
730 // particular, we would have to handle implied bounds
731 // properly, and that code is currently largely confined to
732 // regionck (though I made some efforts to extract it
735 // @arielby: In any case, these obligations are checked
736 // by wfcheck anyway, so I'm not sure we have to check
737 // them here too, and we will remove this function when
738 // we move over to lazy normalization *anyway*.
739 let fulfill_cx
= FulfillmentContext
::new_ignoring_regions();
740 let predicates
= match fully_normalize(
747 Ok(predicates
) => predicates
,
749 infcx
.report_fulfillment_errors(&errors
, None
, false);
750 return Err(ErrorReported
)
754 debug
!("do_normalize_predictes: normalized predicates = {:?}", predicates
);
756 let region_scope_tree
= region
::ScopeTree
::default();
758 // We can use the `elaborated_env` here; the region code only
759 // cares about declarations like `'a: 'b`.
760 let outlives_env
= OutlivesEnvironment
::new(elaborated_env
);
762 infcx
.resolve_regions_and_report_errors(
766 SuppressRegionErrors
::default(),
769 let predicates
= match infcx
.fully_resolve(&predicates
) {
770 Ok(predicates
) => predicates
,
772 // If we encounter a fixup error, it means that some type
773 // variable wound up unconstrained. I actually don't know
774 // if this can happen, and I certainly don't expect it to
775 // happen often, but if it did happen it probably
776 // represents a legitimate failure due to some kind of
777 // unconstrained variable, and it seems better not to ICE,
778 // all things considered.
779 tcx
.sess
.span_err(span
, &fixup_err
.to_string());
780 return Err(ErrorReported
)
784 match tcx
.lift_to_global(&predicates
) {
785 Some(predicates
) => Ok(predicates
),
787 // FIXME: shouldn't we, you know, actually report an error here? or an ICE?
794 // FIXME: this is gonna need to be removed ...
795 /// Normalizes the parameter environment, reporting errors if they occur.
796 pub fn normalize_param_env_or_error
<'a
, 'tcx
>(tcx
: TyCtxt
<'a
, 'tcx
, 'tcx
>,
797 region_context
: DefId
,
798 unnormalized_env
: ty
::ParamEnv
<'tcx
>,
799 cause
: ObligationCause
<'tcx
>)
800 -> ty
::ParamEnv
<'tcx
>
802 // I'm not wild about reporting errors here; I'd prefer to
803 // have the errors get reported at a defined place (e.g.,
804 // during typeck). Instead I have all parameter
805 // environments, in effect, going through this function
806 // and hence potentially reporting errors. This ensures of
807 // course that we never forget to normalize (the
808 // alternative seemed like it would involve a lot of
809 // manual invocations of this fn -- and then we'd have to
810 // deal with the errors at each of those sites).
812 // In any case, in practice, typeck constructs all the
813 // parameter environments once for every fn as it goes,
814 // and errors will get reported then; so after typeck we
815 // can be sure that no errors should occur.
817 debug
!("normalize_param_env_or_error(region_context={:?}, unnormalized_env={:?}, cause={:?})",
818 region_context
, unnormalized_env
, cause
);
820 let mut predicates
: Vec
<_
> =
821 util
::elaborate_predicates(tcx
, unnormalized_env
.caller_bounds
.to_vec())
824 debug
!("normalize_param_env_or_error: elaborated-predicates={:?}",
827 let elaborated_env
= ty
::ParamEnv
::new(
828 tcx
.intern_predicates(&predicates
),
829 unnormalized_env
.reveal
,
830 unnormalized_env
.def_id
833 // HACK: we are trying to normalize the param-env inside *itself*. The problem is that
834 // normalization expects its param-env to be already normalized, which means we have
837 // The way we handle this is by normalizing the param-env inside an unnormalized version
838 // of the param-env, which means that if the param-env contains unnormalized projections,
839 // we'll have some normalization failures. This is unfortunate.
841 // Lazy normalization would basically handle this by treating just the
842 // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
844 // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
845 // types, so to make the situation less bad, we normalize all the predicates *but*
846 // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
847 // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
849 // This works fairly well because trait matching does not actually care about param-env
850 // TypeOutlives predicates - these are normally used by regionck.
851 let outlives_predicates
: Vec
<_
> = predicates
.drain_filter(|predicate
| {
853 ty
::Predicate
::TypeOutlives(..) => true,
858 debug
!("normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
859 predicates
, outlives_predicates
);
860 let non_outlives_predicates
=
861 match do_normalize_predicates(tcx
, region_context
, cause
.clone(),
862 elaborated_env
, predicates
) {
863 Ok(predicates
) => predicates
,
864 // An unnormalized env is better than nothing.
865 Err(ErrorReported
) => {
866 debug
!("normalize_param_env_or_error: errored resolving non-outlives predicates");
867 return elaborated_env
871 debug
!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates
);
873 // Not sure whether it is better to include the unnormalized TypeOutlives predicates
874 // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
875 // predicates here anyway. Keeping them here anyway because it seems safer.
876 let outlives_env
: Vec
<_
> =
877 non_outlives_predicates
.iter().chain(&outlives_predicates
).cloned().collect();
878 let outlives_env
= ty
::ParamEnv
::new(
879 tcx
.intern_predicates(&outlives_env
),
880 unnormalized_env
.reveal
,
883 let outlives_predicates
=
884 match do_normalize_predicates(tcx
, region_context
, cause
,
885 outlives_env
, outlives_predicates
) {
886 Ok(predicates
) => predicates
,
887 // An unnormalized env is better than nothing.
888 Err(ErrorReported
) => {
889 debug
!("normalize_param_env_or_error: errored resolving outlives predicates");
890 return elaborated_env
893 debug
!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates
);
895 let mut predicates
= non_outlives_predicates
;
896 predicates
.extend(outlives_predicates
);
897 debug
!("normalize_param_env_or_error: final predicates={:?}", predicates
);
899 tcx
.intern_predicates(&predicates
),
900 unnormalized_env
.reveal
,
901 unnormalized_env
.def_id
905 pub fn fully_normalize
<'a
, 'gcx
, 'tcx
, T
>(
906 infcx
: &InferCtxt
<'a
, 'gcx
, 'tcx
>,
907 mut fulfill_cx
: FulfillmentContext
<'tcx
>,
908 cause
: ObligationCause
<'tcx
>,
909 param_env
: ty
::ParamEnv
<'tcx
>,
911 -> Result
<T
, Vec
<FulfillmentError
<'tcx
>>>
912 where T
: TypeFoldable
<'tcx
>
914 debug
!("fully_normalize_with_fulfillcx(value={:?})", value
);
915 let selcx
= &mut SelectionContext
::new(infcx
);
916 let Normalized { value: normalized_value, obligations }
=
917 project
::normalize(selcx
, param_env
, cause
, value
);
918 debug
!("fully_normalize: normalized_value={:?} obligations={:?}",
921 for obligation
in obligations
{
922 fulfill_cx
.register_predicate_obligation(selcx
.infcx(), obligation
);
925 debug
!("fully_normalize: select_all_or_error start");
926 fulfill_cx
.select_all_or_error(infcx
)?
;
927 debug
!("fully_normalize: select_all_or_error complete");
928 let resolved_value
= infcx
.resolve_type_vars_if_possible(&normalized_value
);
929 debug
!("fully_normalize: resolved_value={:?}", resolved_value
);
933 /// Normalizes the predicates and checks whether they hold in an empty
934 /// environment. If this returns false, then either normalize
935 /// encountered an error or one of the predicates did not hold. Used
936 /// when creating vtables to check for unsatisfiable methods.
937 fn normalize_and_test_predicates
<'a
, 'tcx
>(tcx
: TyCtxt
<'a
, 'tcx
, 'tcx
>,
938 predicates
: Vec
<ty
::Predicate
<'tcx
>>)
941 debug
!("normalize_and_test_predicates(predicates={:?})",
944 let result
= tcx
.infer_ctxt().enter(|infcx
| {
945 let param_env
= ty
::ParamEnv
::reveal_all();
946 let mut selcx
= SelectionContext
::new(&infcx
);
947 let mut fulfill_cx
= FulfillmentContext
::new();
948 let cause
= ObligationCause
::dummy();
949 let Normalized { value: predicates, obligations }
=
950 normalize(&mut selcx
, param_env
, cause
.clone(), &predicates
);
951 for obligation
in obligations
{
952 fulfill_cx
.register_predicate_obligation(&infcx
, obligation
);
954 for predicate
in predicates
{
955 let obligation
= Obligation
::new(cause
.clone(), param_env
, predicate
);
956 fulfill_cx
.register_predicate_obligation(&infcx
, obligation
);
959 fulfill_cx
.select_all_or_error(&infcx
).is_ok()
961 debug
!("normalize_and_test_predicates(predicates={:?}) = {:?}",
966 fn substitute_normalize_and_test_predicates
<'a
, 'tcx
>(tcx
: TyCtxt
<'a
, 'tcx
, 'tcx
>,
967 key
: (DefId
, SubstsRef
<'tcx
>))
970 debug
!("substitute_normalize_and_test_predicates(key={:?})",
973 let predicates
= tcx
.predicates_of(key
.0).instantiate(tcx
, key
.1).predicates
;
974 let result
= normalize_and_test_predicates(tcx
, predicates
);
976 debug
!("substitute_normalize_and_test_predicates(key={:?}) = {:?}",
981 /// Given a trait `trait_ref`, iterates the vtable entries
982 /// that come from `trait_ref`, including its supertraits.
983 #[inline] // FIXME(#35870): avoid closures being unexported due to `impl Trait`.
984 fn vtable_methods
<'a
, 'tcx
>(
985 tcx
: TyCtxt
<'a
, 'tcx
, 'tcx
>,
986 trait_ref
: ty
::PolyTraitRef
<'tcx
>)
987 -> Lrc
<Vec
<Option
<(DefId
, SubstsRef
<'tcx
>)>>>
989 debug
!("vtable_methods({:?})", trait_ref
);
992 supertraits(tcx
, trait_ref
).flat_map(move |trait_ref
| {
993 let trait_methods
= tcx
.associated_items(trait_ref
.def_id())
994 .filter(|item
| item
.kind
== ty
::AssociatedKind
::Method
);
996 // Now list each method's DefId and InternalSubsts (for within its trait).
997 // If the method can never be called from this object, produce None.
998 trait_methods
.map(move |trait_method
| {
999 debug
!("vtable_methods: trait_method={:?}", trait_method
);
1000 let def_id
= trait_method
.def_id
;
1002 // Some methods cannot be called on an object; skip those.
1003 if !tcx
.is_vtable_safe_method(trait_ref
.def_id(), &trait_method
) {
1004 debug
!("vtable_methods: not vtable safe");
1008 // the method may have some early-bound lifetimes, add
1009 // regions for those
1010 let substs
= trait_ref
.map_bound(|trait_ref
|
1011 InternalSubsts
::for_item(tcx
, def_id
, |param
, _
|
1013 GenericParamDefKind
::Lifetime
=> tcx
.types
.re_erased
.into(),
1014 GenericParamDefKind
::Type { .. }
|
1015 GenericParamDefKind
::Const
=> {
1016 trait_ref
.substs
[param
.index
as usize]
1022 // the trait type may have higher-ranked lifetimes in it;
1023 // so erase them if they appear, so that we get the type
1024 // at some particular call site
1025 let substs
= tcx
.normalize_erasing_late_bound_regions(
1026 ty
::ParamEnv
::reveal_all(),
1030 // It's possible that the method relies on where clauses that
1031 // do not hold for this particular set of type parameters.
1032 // Note that this method could then never be called, so we
1033 // do not want to try and codegen it, in that case (see #23435).
1034 let predicates
= tcx
.predicates_of(def_id
).instantiate_own(tcx
, substs
);
1035 if !normalize_and_test_predicates(tcx
, predicates
.predicates
) {
1036 debug
!("vtable_methods: predicates do not hold");
1040 Some((def_id
, substs
))
1046 impl<'tcx
,O
> Obligation
<'tcx
,O
> {
1047 pub fn new(cause
: ObligationCause
<'tcx
>,
1048 param_env
: ty
::ParamEnv
<'tcx
>,
1050 -> Obligation
<'tcx
, O
>
1052 Obligation { cause, param_env, recursion_depth: 0, predicate }
1055 fn with_depth(cause
: ObligationCause
<'tcx
>,
1056 recursion_depth
: usize,
1057 param_env
: ty
::ParamEnv
<'tcx
>,
1059 -> Obligation
<'tcx
, O
>
1061 Obligation { cause, param_env, recursion_depth, predicate }
1064 pub fn misc(span
: Span
,
1065 body_id
: hir
::HirId
,
1066 param_env
: ty
::ParamEnv
<'tcx
>,
1068 -> Obligation
<'tcx
, O
> {
1069 Obligation
::new(ObligationCause
::misc(span
, body_id
), param_env
, trait_ref
)
1072 pub fn with
<P
>(&self, value
: P
) -> Obligation
<'tcx
,P
> {
1073 Obligation
{ cause
: self.cause
.clone(),
1074 param_env
: self.param_env
,
1075 recursion_depth
: self.recursion_depth
,
1080 impl<'tcx
> ObligationCause
<'tcx
> {
1082 pub fn new(span
: Span
,
1083 body_id
: hir
::HirId
,
1084 code
: ObligationCauseCode
<'tcx
>)
1085 -> ObligationCause
<'tcx
> {
1086 ObligationCause { span, body_id, code }
1089 pub fn misc(span
: Span
, body_id
: hir
::HirId
) -> ObligationCause
<'tcx
> {
1090 ObligationCause { span, body_id, code: MiscObligation }
1093 pub fn dummy() -> ObligationCause
<'tcx
> {
1094 ObligationCause { span: DUMMY_SP, body_id: hir::CRATE_HIR_ID, code: MiscObligation }
1098 impl<'tcx
, N
> Vtable
<'tcx
, N
> {
1099 pub fn nested_obligations(self) -> Vec
<N
> {
1101 VtableImpl(i
) => i
.nested
,
1102 VtableParam(n
) => n
,
1103 VtableBuiltin(i
) => i
.nested
,
1104 VtableAutoImpl(d
) => d
.nested
,
1105 VtableClosure(c
) => c
.nested
,
1106 VtableGenerator(c
) => c
.nested
,
1107 VtableObject(d
) => d
.nested
,
1108 VtableFnPointer(d
) => d
.nested
,
1109 VtableTraitAlias(d
) => d
.nested
,
1113 pub fn map
<M
, F
>(self, f
: F
) -> Vtable
<'tcx
, M
> where F
: FnMut(N
) -> M
{
1115 VtableImpl(i
) => VtableImpl(VtableImplData
{
1116 impl_def_id
: i
.impl_def_id
,
1118 nested
: i
.nested
.into_iter().map(f
).collect(),
1120 VtableParam(n
) => VtableParam(n
.into_iter().map(f
).collect()),
1121 VtableBuiltin(i
) => VtableBuiltin(VtableBuiltinData
{
1122 nested
: i
.nested
.into_iter().map(f
).collect(),
1124 VtableObject(o
) => VtableObject(VtableObjectData
{
1125 upcast_trait_ref
: o
.upcast_trait_ref
,
1126 vtable_base
: o
.vtable_base
,
1127 nested
: o
.nested
.into_iter().map(f
).collect(),
1129 VtableAutoImpl(d
) => VtableAutoImpl(VtableAutoImplData
{
1130 trait_def_id
: d
.trait_def_id
,
1131 nested
: d
.nested
.into_iter().map(f
).collect(),
1133 VtableClosure(c
) => VtableClosure(VtableClosureData
{
1134 closure_def_id
: c
.closure_def_id
,
1136 nested
: c
.nested
.into_iter().map(f
).collect(),
1138 VtableGenerator(c
) => VtableGenerator(VtableGeneratorData
{
1139 generator_def_id
: c
.generator_def_id
,
1141 nested
: c
.nested
.into_iter().map(f
).collect(),
1143 VtableFnPointer(p
) => VtableFnPointer(VtableFnPointerData
{
1145 nested
: p
.nested
.into_iter().map(f
).collect(),
1147 VtableTraitAlias(d
) => VtableTraitAlias(VtableTraitAliasData
{
1148 alias_def_id
: d
.alias_def_id
,
1150 nested
: d
.nested
.into_iter().map(f
).collect(),
1156 impl<'tcx
> FulfillmentError
<'tcx
> {
1157 fn new(obligation
: PredicateObligation
<'tcx
>,
1158 code
: FulfillmentErrorCode
<'tcx
>)
1159 -> FulfillmentError
<'tcx
>
1161 FulfillmentError { obligation: obligation, code: code }
1165 impl<'tcx
> TraitObligation
<'tcx
> {
1166 fn self_ty(&self) -> ty
::Binder
<Ty
<'tcx
>> {
1167 self.predicate
.map_bound(|p
| p
.self_ty())
1171 pub fn provide(providers
: &mut ty
::query
::Providers
<'_
>) {
1172 *providers
= ty
::query
::Providers
{
1173 is_object_safe
: object_safety
::is_object_safe_provider
,
1174 specialization_graph_of
: specialize
::specialization_graph_provider
,
1175 specializes
: specialize
::specializes
,
1176 codegen_fulfill_obligation
: codegen
::codegen_fulfill_obligation
,
1178 substitute_normalize_and_test_predicates
,
1183 pub trait ExClauseFold
<'tcx
>
1185 Self: chalk_engine
::context
::Context
+ Clone
,
1187 fn fold_ex_clause_with
<'gcx
: 'tcx
, F
: TypeFolder
<'gcx
, 'tcx
>>(
1188 ex_clause
: &chalk_engine
::ExClause
<Self>,
1190 ) -> chalk_engine
::ExClause
<Self>;
1192 fn visit_ex_clause_with
<'gcx
: 'tcx
, V
: TypeVisitor
<'tcx
>>(
1193 ex_clause
: &chalk_engine
::ExClause
<Self>,
1198 pub trait ChalkContextLift
<'tcx
>
1200 Self: chalk_engine
::context
::Context
+ Clone
,
1202 type LiftedExClause
: Debug
+ 'tcx
;
1203 type LiftedDelayedLiteral
: Debug
+ 'tcx
;
1204 type LiftedLiteral
: Debug
+ 'tcx
;
1206 fn lift_ex_clause_to_tcx
<'a
, 'gcx
>(
1207 ex_clause
: &chalk_engine
::ExClause
<Self>,
1208 tcx
: TyCtxt
<'a
, 'gcx
, 'tcx
>,
1209 ) -> Option
<Self::LiftedExClause
>;
1211 fn lift_delayed_literal_to_tcx
<'a
, 'gcx
>(
1212 ex_clause
: &chalk_engine
::DelayedLiteral
<Self>,
1213 tcx
: TyCtxt
<'a
, 'gcx
, 'tcx
>,
1214 ) -> Option
<Self::LiftedDelayedLiteral
>;
1216 fn lift_literal_to_tcx
<'a
, 'gcx
>(
1217 ex_clause
: &chalk_engine
::Literal
<Self>,
1218 tcx
: TyCtxt
<'a
, 'gcx
, 'tcx
>,
1219 ) -> Option
<Self::LiftedLiteral
>;