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
7 pub mod specialization_graph;
10 use crate::infer::canonical::Canonical;
11 use crate::mir::interpret::ErrorHandled;
12 use crate::ty::fold::{TypeFolder, TypeVisitor};
13 use crate::ty::subst::SubstsRef;
14 use crate::ty::{self, AdtKind, List, Ty, TyCtxt};
18 use rustc_hir::def_id::DefId;
19 use rustc_span::{Span, DUMMY_SP};
20 use smallvec::SmallVec;
26 pub use self::select::{EvaluationCache, EvaluationResult, OverflowError, SelectionCache};
28 pub type ChalkCanonicalGoal<'tcx> = Canonical<'tcx, InEnvironment<'tcx, ty::Predicate<'tcx>>>;
30 pub use self::ObligationCauseCode::*;
31 pub use self::SelectionError::*;
32 pub use self::Vtable::*;
34 /// Depending on the stage of compilation, we want projection to be
35 /// more or less conservative.
36 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, HashStable)]
38 /// At type-checking time, we refuse to project any associated
39 /// type that is marked `default`. Non-`default` ("final") types
40 /// are always projected. This is necessary in general for
41 /// soundness of specialization. However, we *could* allow
42 /// projections in fully-monomorphic cases. We choose not to,
43 /// because we prefer for `default type` to force the type
44 /// definition to be treated abstractly by any consumers of the
45 /// impl. Concretely, that means that the following example will
53 /// impl<T> Assoc for T {
54 /// default type Output = bool;
58 /// let <() as Assoc>::Output = true;
63 /// At codegen time, all monomorphic projections will succeed.
64 /// Also, `impl Trait` is normalized to the concrete type,
65 /// which has to be already collected by type-checking.
67 /// NOTE: as `impl Trait`'s concrete type should *never*
68 /// be observable directly by the user, `Reveal::All`
69 /// should not be used by checks which may expose
70 /// type equality or type contents to the user.
71 /// There are some exceptions, e.g., around OIBITS and
72 /// transmute-checking, which expose some details, but
73 /// not the whole concrete type of the `impl Trait`.
77 /// The reason why we incurred this obligation; used for error reporting.
78 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
79 pub struct ObligationCause<'tcx> {
82 /// The ID of the fn body that triggered this obligation. This is
83 /// used for region obligations to determine the precise
84 /// environment in which the region obligation should be evaluated
85 /// (in particular, closures can add new assumptions). See the
86 /// field `region_obligations` of the `FulfillmentContext` for more
88 pub body_id: hir::HirId,
90 pub code: ObligationCauseCode<'tcx>,
93 impl<'tcx> ObligationCause<'tcx> {
98 code: ObligationCauseCode<'tcx>,
99 ) -> ObligationCause<'tcx> {
100 ObligationCause { span, body_id, code }
103 pub fn misc(span: Span, body_id: hir::HirId) -> ObligationCause<'tcx> {
104 ObligationCause { span, body_id, code: MiscObligation }
107 pub fn dummy() -> ObligationCause<'tcx> {
108 ObligationCause { span: DUMMY_SP, body_id: hir::CRATE_HIR_ID, code: MiscObligation }
111 pub fn span(&self, tcx: TyCtxt<'tcx>) -> Span {
113 ObligationCauseCode::CompareImplMethodObligation { .. }
114 | ObligationCauseCode::MainFunctionType
115 | ObligationCauseCode::StartFunctionType => tcx.sess.source_map().def_span(self.span),
116 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
125 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
126 pub enum ObligationCauseCode<'tcx> {
127 /// Not well classified or should be obvious from the span.
130 /// A slice or array is WF only if `T: Sized`.
133 /// A tuple is WF only if its middle elements are `Sized`.
136 /// This is the trait reference from the given projection.
137 ProjectionWf(ty::ProjectionTy<'tcx>),
139 /// In an impl of trait `X` for type `Y`, type `Y` must
140 /// also implement all supertraits of `X`.
141 ItemObligation(DefId),
143 /// Like `ItemObligation`, but with extra detail on the source of the obligation.
144 BindingObligation(DefId, Span),
146 /// A type like `&'a T` is WF only if `T: 'a`.
147 ReferenceOutlivesReferent(Ty<'tcx>),
149 /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
150 ObjectTypeBound(Ty<'tcx>, ty::Region<'tcx>),
152 /// Obligation incurred due to an object cast.
153 ObjectCastObligation(/* Object type */ Ty<'tcx>),
155 /// Obligation incurred due to a coercion.
161 /// Various cases where expressions must be `Sized` / `Copy` / etc.
162 /// `L = X` implies that `L` is `Sized`.
164 /// `(x1, .., xn)` must be `Sized`.
165 TupleInitializerSized,
166 /// `S { ... }` must be `Sized`.
167 StructInitializerSized,
168 /// Type of each variable must be `Sized`.
169 VariableType(hir::HirId),
170 /// Argument type must be `Sized`.
172 /// Return type must be `Sized`.
174 /// Yield type must be `Sized`.
176 /// `[T, ..n]` implies that `T` must be `Copy`.
177 /// If `true`, suggest `const_in_array_repeat_expressions` feature flag.
180 /// Types of fields (other than the last, except for packed structs) in a struct must be sized.
186 /// Constant expressions must be sized.
189 /// `static` items must have `Sync` type.
192 BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
194 ImplDerivedObligation(DerivedObligationCause<'tcx>),
196 /// Error derived when matching traits/impls; see ObligationCause for more details
197 CompareImplMethodObligation {
198 item_name: ast::Name,
199 impl_item_def_id: DefId,
200 trait_item_def_id: DefId,
203 /// Error derived when matching traits/impls; see ObligationCause for more details
204 CompareImplTypeObligation {
205 item_name: ast::Name,
206 impl_item_def_id: DefId,
207 trait_item_def_id: DefId,
210 /// Checking that this expression can be assigned where it needs to be
211 // FIXME(eddyb) #11161 is the original Expr required?
214 /// Computing common supertype in the arms of a match expression
215 MatchExpressionArm(Box<MatchExpressionArmCause<'tcx>>),
217 /// Type error arising from type checking a pattern against an expected type.
219 /// The span of the scrutinee or type expression which caused the `root_ty` type.
221 /// The root expected type induced by a scrutinee or type expression.
223 /// Whether the `Span` came from an expression or a type expression.
227 /// Constants in patterns must have `Structural` type.
228 ConstPatternStructural,
230 /// Computing common supertype in an if expression
231 IfExpression(Box<IfExpressionCause>),
233 /// Computing common supertype of an if expression with no else counter-part
234 IfExpressionWithNoElse,
236 /// `main` has wrong type
239 /// `start` has wrong type
242 /// Intrinsic has wrong type
248 /// `return` with no expression
251 /// `return` with an expression
252 ReturnValue(hir::HirId),
254 /// Return type of this function
257 /// Block implicit return
258 BlockTailExpression(hir::HirId),
260 /// #[feature(trivial_bounds)] is not enabled
263 AssocTypeBound(Box<AssocTypeBoundData>),
266 impl ObligationCauseCode<'_> {
267 // Return the base obligation, ignoring derived obligations.
268 pub fn peel_derives(&self) -> &Self {
269 let mut base_cause = self;
270 while let BuiltinDerivedObligation(cause) | ImplDerivedObligation(cause) = base_cause {
271 base_cause = &cause.parent_code;
277 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
278 pub struct AssocTypeBoundData {
279 pub impl_span: Option<Span>,
281 pub bounds: Vec<Span>,
284 // `ObligationCauseCode` is used a lot. Make sure it doesn't unintentionally get bigger.
285 #[cfg(target_arch = "x86_64")]
286 static_assert_size!(ObligationCauseCode<'_>, 32);
288 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
289 pub struct MatchExpressionArmCause<'tcx> {
291 pub source: hir::MatchSource,
292 pub prior_arms: Vec<Span>,
293 pub last_ty: Ty<'tcx>,
294 pub scrut_hir_id: hir::HirId,
297 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
298 pub struct IfExpressionCause {
300 pub outer: Option<Span>,
301 pub semicolon: Option<Span>,
304 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
305 pub struct DerivedObligationCause<'tcx> {
306 /// The trait reference of the parent obligation that led to the
307 /// current obligation. Note that only trait obligations lead to
308 /// derived obligations, so we just store the trait reference here
310 pub parent_trait_ref: ty::PolyTraitRef<'tcx>,
312 /// The parent trait had this cause.
313 pub parent_code: Rc<ObligationCauseCode<'tcx>>,
316 /// The following types:
324 /// * `InEnvironment`,
325 /// are used for representing the trait system in the form of
326 /// logic programming clauses. They are part of the interface
327 /// for the chalk SLG solver.
328 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
329 pub enum WhereClause<'tcx> {
330 Implemented(ty::TraitPredicate<'tcx>),
331 ProjectionEq(ty::ProjectionPredicate<'tcx>),
332 RegionOutlives(ty::RegionOutlivesPredicate<'tcx>),
333 TypeOutlives(ty::TypeOutlivesPredicate<'tcx>),
336 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
337 pub enum WellFormed<'tcx> {
338 Trait(ty::TraitPredicate<'tcx>),
342 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
343 pub enum FromEnv<'tcx> {
344 Trait(ty::TraitPredicate<'tcx>),
348 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
349 pub enum DomainGoal<'tcx> {
350 Holds(WhereClause<'tcx>),
351 WellFormed(WellFormed<'tcx>),
352 FromEnv(FromEnv<'tcx>),
353 Normalize(ty::ProjectionPredicate<'tcx>),
356 pub type PolyDomainGoal<'tcx> = ty::Binder<DomainGoal<'tcx>>;
358 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
359 pub enum QuantifierKind {
364 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
365 pub enum GoalKind<'tcx> {
366 Implies(Clauses<'tcx>, Goal<'tcx>),
367 And(Goal<'tcx>, Goal<'tcx>),
369 DomainGoal(DomainGoal<'tcx>),
370 Quantified(QuantifierKind, ty::Binder<Goal<'tcx>>),
371 Subtype(Ty<'tcx>, Ty<'tcx>),
375 pub type Goal<'tcx> = &'tcx GoalKind<'tcx>;
377 pub type Goals<'tcx> = &'tcx List<Goal<'tcx>>;
379 impl<'tcx> DomainGoal<'tcx> {
380 pub fn into_goal(self) -> GoalKind<'tcx> {
381 GoalKind::DomainGoal(self)
384 pub fn into_program_clause(self) -> ProgramClause<'tcx> {
387 hypotheses: ty::List::empty(),
388 category: ProgramClauseCategory::Other,
393 impl<'tcx> GoalKind<'tcx> {
394 pub fn from_poly_domain_goal(
395 domain_goal: PolyDomainGoal<'tcx>,
397 ) -> GoalKind<'tcx> {
398 match domain_goal.no_bound_vars() {
399 Some(p) => p.into_goal(),
400 None => GoalKind::Quantified(
401 QuantifierKind::Universal,
402 domain_goal.map_bound(|p| tcx.mk_goal(p.into_goal())),
408 /// This matches the definition from Page 7 of "A Proof Procedure for the Logic of Hereditary
409 /// Harrop Formulas".
410 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
411 pub enum Clause<'tcx> {
412 Implies(ProgramClause<'tcx>),
413 ForAll(ty::Binder<ProgramClause<'tcx>>),
417 pub fn category(self) -> ProgramClauseCategory {
419 Clause::Implies(clause) => clause.category,
420 Clause::ForAll(clause) => clause.skip_binder().category,
425 /// Multiple clauses.
426 pub type Clauses<'tcx> = &'tcx List<Clause<'tcx>>;
428 /// A "program clause" has the form `D :- G1, ..., Gn`. It is saying
429 /// that the domain goal `D` is true if `G1...Gn` are provable. This
430 /// is equivalent to the implication `G1..Gn => D`; we usually write
431 /// it with the reverse implication operator `:-` to emphasize the way
432 /// that programs are actually solved (via backchaining, which starts
433 /// with the goal to solve and proceeds from there).
434 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
435 pub struct ProgramClause<'tcx> {
436 /// This goal will be considered true ...
437 pub goal: DomainGoal<'tcx>,
439 /// ... if we can prove these hypotheses (there may be no hypotheses at all):
440 pub hypotheses: Goals<'tcx>,
442 /// Useful for filtering clauses.
443 pub category: ProgramClauseCategory,
446 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
447 pub enum ProgramClauseCategory {
453 /// A set of clauses that we assume to be true.
454 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
455 pub struct Environment<'tcx> {
456 pub clauses: Clauses<'tcx>,
459 impl Environment<'tcx> {
460 pub fn with<G>(self, goal: G) -> InEnvironment<'tcx, G> {
461 InEnvironment { environment: self, goal }
465 /// Something (usually a goal), along with an environment.
466 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
467 pub struct InEnvironment<'tcx, G> {
468 pub environment: Environment<'tcx>,
472 #[derive(Clone, Debug, TypeFoldable)]
473 pub enum SelectionError<'tcx> {
475 OutputTypeParameterMismatch(
476 ty::PolyTraitRef<'tcx>,
477 ty::PolyTraitRef<'tcx>,
478 ty::error::TypeError<'tcx>,
480 TraitNotObjectSafe(DefId),
481 ConstEvalFailure(ErrorHandled),
485 /// When performing resolution, it is typically the case that there
486 /// can be one of three outcomes:
488 /// - `Ok(Some(r))`: success occurred with result `r`
489 /// - `Ok(None)`: could not definitely determine anything, usually due
490 /// to inconclusive type inference.
491 /// - `Err(e)`: error `e` occurred
492 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
494 /// Given the successful resolution of an obligation, the `Vtable`
495 /// indicates where the vtable comes from. Note that while we call this
496 /// a "vtable", it does not necessarily indicate dynamic dispatch at
497 /// runtime. `Vtable` instances just tell the compiler where to find
498 /// methods, but in generic code those methods are typically statically
499 /// dispatched -- only when an object is constructed is a `Vtable`
500 /// instance reified into an actual vtable.
502 /// For example, the vtable may be tied to a specific impl (case A),
503 /// or it may be relative to some bound that is in scope (case B).
506 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
507 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
508 /// impl Clone for int { ... } // Impl_3
510 /// fn foo<T:Clone>(concrete: Option<Box<int>>,
512 /// mixed: Option<T>) {
514 /// // Case A: Vtable points at a specific impl. Only possible when
515 /// // type is concretely known. If the impl itself has bounded
516 /// // type parameters, Vtable will carry resolutions for those as well:
517 /// concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
519 /// // Case B: Vtable must be provided by caller. This applies when
520 /// // type is a type parameter.
521 /// param.clone(); // VtableParam
523 /// // Case C: A mix of cases A and B.
524 /// mixed.clone(); // Vtable(Impl_1, [VtableParam])
528 /// ### The type parameter `N`
530 /// See explanation on `VtableImplData`.
531 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
532 pub enum Vtable<'tcx, N> {
533 /// Vtable identifying a particular impl.
534 VtableImpl(VtableImplData<'tcx, N>),
536 /// Vtable for auto trait implementations.
537 /// This carries the information and nested obligations with regards
538 /// to an auto implementation for a trait `Trait`. The nested obligations
539 /// ensure the trait implementation holds for all the constituent types.
540 VtableAutoImpl(VtableAutoImplData<N>),
542 /// Successful resolution to an obligation provided by the caller
543 /// for some type parameter. The `Vec<N>` represents the
544 /// obligations incurred from normalizing the where-clause (if
548 /// Virtual calls through an object.
549 VtableObject(VtableObjectData<'tcx, N>),
551 /// Successful resolution for a builtin trait.
552 VtableBuiltin(VtableBuiltinData<N>),
554 /// Vtable automatically generated for a closure. The `DefId` is the ID
555 /// of the closure expression. This is a `VtableImpl` in spirit, but the
556 /// impl is generated by the compiler and does not appear in the source.
557 VtableClosure(VtableClosureData<'tcx, N>),
559 /// Same as above, but for a function pointer type with the given signature.
560 VtableFnPointer(VtableFnPointerData<'tcx, N>),
562 /// Vtable automatically generated for a generator.
563 VtableGenerator(VtableGeneratorData<'tcx, N>),
565 /// Vtable for a trait alias.
566 VtableTraitAlias(VtableTraitAliasData<'tcx, N>),
569 impl<'tcx, N> Vtable<'tcx, N> {
570 pub fn nested_obligations(self) -> Vec<N> {
572 VtableImpl(i) => i.nested,
574 VtableBuiltin(i) => i.nested,
575 VtableAutoImpl(d) => d.nested,
576 VtableClosure(c) => c.nested,
577 VtableGenerator(c) => c.nested,
578 VtableObject(d) => d.nested,
579 VtableFnPointer(d) => d.nested,
580 VtableTraitAlias(d) => d.nested,
584 pub fn borrow_nested_obligations(&self) -> &[N] {
586 VtableImpl(i) => &i.nested[..],
587 VtableParam(n) => &n[..],
588 VtableBuiltin(i) => &i.nested[..],
589 VtableAutoImpl(d) => &d.nested[..],
590 VtableClosure(c) => &c.nested[..],
591 VtableGenerator(c) => &c.nested[..],
592 VtableObject(d) => &d.nested[..],
593 VtableFnPointer(d) => &d.nested[..],
594 VtableTraitAlias(d) => &d.nested[..],
598 pub fn map<M, F>(self, f: F) -> Vtable<'tcx, M>
603 VtableImpl(i) => VtableImpl(VtableImplData {
604 impl_def_id: i.impl_def_id,
606 nested: i.nested.into_iter().map(f).collect(),
608 VtableParam(n) => VtableParam(n.into_iter().map(f).collect()),
609 VtableBuiltin(i) => {
610 VtableBuiltin(VtableBuiltinData { nested: i.nested.into_iter().map(f).collect() })
612 VtableObject(o) => VtableObject(VtableObjectData {
613 upcast_trait_ref: o.upcast_trait_ref,
614 vtable_base: o.vtable_base,
615 nested: o.nested.into_iter().map(f).collect(),
617 VtableAutoImpl(d) => VtableAutoImpl(VtableAutoImplData {
618 trait_def_id: d.trait_def_id,
619 nested: d.nested.into_iter().map(f).collect(),
621 VtableClosure(c) => VtableClosure(VtableClosureData {
622 closure_def_id: c.closure_def_id,
624 nested: c.nested.into_iter().map(f).collect(),
626 VtableGenerator(c) => VtableGenerator(VtableGeneratorData {
627 generator_def_id: c.generator_def_id,
629 nested: c.nested.into_iter().map(f).collect(),
631 VtableFnPointer(p) => VtableFnPointer(VtableFnPointerData {
633 nested: p.nested.into_iter().map(f).collect(),
635 VtableTraitAlias(d) => VtableTraitAlias(VtableTraitAliasData {
636 alias_def_id: d.alias_def_id,
638 nested: d.nested.into_iter().map(f).collect(),
644 /// Identifies a particular impl in the source, along with a set of
645 /// substitutions from the impl's type/lifetime parameters. The
646 /// `nested` vector corresponds to the nested obligations attached to
647 /// the impl's type parameters.
649 /// The type parameter `N` indicates the type used for "nested
650 /// obligations" that are required by the impl. During type-check, this
651 /// is `Obligation`, as one might expect. During codegen, however, this
652 /// is `()`, because codegen only requires a shallow resolution of an
653 /// impl, and nested obligations are satisfied later.
654 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
655 pub struct VtableImplData<'tcx, N> {
656 pub impl_def_id: DefId,
657 pub substs: SubstsRef<'tcx>,
661 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
662 pub struct VtableGeneratorData<'tcx, N> {
663 pub generator_def_id: DefId,
664 pub substs: SubstsRef<'tcx>,
665 /// Nested obligations. This can be non-empty if the generator
666 /// signature contains associated types.
670 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
671 pub struct VtableClosureData<'tcx, N> {
672 pub closure_def_id: DefId,
673 pub substs: SubstsRef<'tcx>,
674 /// Nested obligations. This can be non-empty if the closure
675 /// signature contains associated types.
679 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
680 pub struct VtableAutoImplData<N> {
681 pub trait_def_id: DefId,
685 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
686 pub struct VtableBuiltinData<N> {
690 /// A vtable for some object-safe trait `Foo` automatically derived
691 /// for the object type `Foo`.
692 #[derive(PartialEq, Eq, Clone, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
693 pub struct VtableObjectData<'tcx, N> {
694 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
695 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
697 /// The vtable is formed by concatenating together the method lists of
698 /// the base object trait and all supertraits; this is the start of
699 /// `upcast_trait_ref`'s methods in that vtable.
700 pub vtable_base: usize,
705 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
706 pub struct VtableFnPointerData<'tcx, N> {
711 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
712 pub struct VtableTraitAliasData<'tcx, N> {
713 pub alias_def_id: DefId,
714 pub substs: SubstsRef<'tcx>,
718 pub trait ExClauseFold<'tcx>
720 Self: chalk_engine::context::Context + Clone,
722 fn fold_ex_clause_with<F: TypeFolder<'tcx>>(
723 ex_clause: &chalk_engine::ExClause<Self>,
725 ) -> chalk_engine::ExClause<Self>;
727 fn visit_ex_clause_with<V: TypeVisitor<'tcx>>(
728 ex_clause: &chalk_engine::ExClause<Self>,
733 pub trait ChalkContextLift<'tcx>
735 Self: chalk_engine::context::Context + Clone,
737 type LiftedExClause: Debug + 'tcx;
738 type LiftedDelayedLiteral: Debug + 'tcx;
739 type LiftedLiteral: Debug + 'tcx;
741 fn lift_ex_clause_to_tcx(
742 ex_clause: &chalk_engine::ExClause<Self>,
744 ) -> Option<Self::LiftedExClause>;
746 fn lift_delayed_literal_to_tcx(
747 ex_clause: &chalk_engine::DelayedLiteral<Self>,
749 ) -> Option<Self::LiftedDelayedLiteral>;
751 fn lift_literal_to_tcx(
752 ex_clause: &chalk_engine::Literal<Self>,
754 ) -> Option<Self::LiftedLiteral>;
757 #[derive(Clone, Debug, PartialEq, Eq, Hash, HashStable)]
758 pub enum ObjectSafetyViolation {
759 /// `Self: Sized` declared on the trait.
760 SizedSelf(SmallVec<[Span; 1]>),
762 /// Supertrait reference references `Self` an in illegal location
763 /// (e.g., `trait Foo : Bar<Self>`).
764 SupertraitSelf(SmallVec<[Span; 1]>),
766 /// Method has something illegal.
767 Method(ast::Name, MethodViolationCode, Span),
769 /// Associated const.
770 AssocConst(ast::Name, Span),
773 impl ObjectSafetyViolation {
774 pub fn error_msg(&self) -> Cow<'static, str> {
776 ObjectSafetyViolation::SizedSelf(_) => "it requires `Self: Sized`".into(),
777 ObjectSafetyViolation::SupertraitSelf(ref spans) => {
778 if spans.iter().any(|sp| *sp != DUMMY_SP) {
779 "it uses `Self` as a type parameter in this".into()
781 "it cannot use `Self` as a type parameter in a supertrait or `where`-clause"
785 ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod(_), _) => {
786 format!("associated function `{}` has no `self` parameter", name).into()
788 ObjectSafetyViolation::Method(
790 MethodViolationCode::ReferencesSelfInput(_),
792 ) => format!("method `{}` references the `Self` type in its parameters", name).into(),
793 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfInput(_), _) => {
794 format!("method `{}` references the `Self` type in this parameter", name).into()
796 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfOutput, _) => {
797 format!("method `{}` references the `Self` type in its return type", name).into()
799 ObjectSafetyViolation::Method(
801 MethodViolationCode::WhereClauseReferencesSelf,
804 format!("method `{}` references the `Self` type in its `where` clause", name).into()
806 ObjectSafetyViolation::Method(name, MethodViolationCode::Generic, _) => {
807 format!("method `{}` has generic type parameters", name).into()
809 ObjectSafetyViolation::Method(name, MethodViolationCode::UndispatchableReceiver, _) => {
810 format!("method `{}`'s `self` parameter cannot be dispatched on", name).into()
812 ObjectSafetyViolation::AssocConst(name, DUMMY_SP) => {
813 format!("it contains associated `const` `{}`", name).into()
815 ObjectSafetyViolation::AssocConst(..) => "it contains this associated `const`".into(),
819 pub fn solution(&self) -> Option<(String, Option<(String, Span)>)> {
821 ObjectSafetyViolation::SizedSelf(_) | ObjectSafetyViolation::SupertraitSelf(_) => {
824 ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod(sugg), _) => (
826 "consider turning `{}` into a method by giving it a `&self` argument or \
827 constraining it so it does not apply to trait objects",
830 sugg.map(|(sugg, sp)| (sugg.to_string(), sp)),
832 ObjectSafetyViolation::Method(
834 MethodViolationCode::UndispatchableReceiver,
837 format!("consider changing method `{}`'s `self` parameter to be `&self`", name),
838 Some(("&Self".to_string(), span)),
840 ObjectSafetyViolation::AssocConst(name, _)
841 | ObjectSafetyViolation::Method(name, ..) => {
842 (format!("consider moving `{}` to another trait", name), None)
847 pub fn spans(&self) -> SmallVec<[Span; 1]> {
848 // When `span` comes from a separate crate, it'll be `DUMMY_SP`. Treat it as `None` so
849 // diagnostics use a `note` instead of a `span_label`.
851 ObjectSafetyViolation::SupertraitSelf(spans)
852 | ObjectSafetyViolation::SizedSelf(spans) => spans.clone(),
853 ObjectSafetyViolation::AssocConst(_, span)
854 | ObjectSafetyViolation::Method(_, _, span)
855 if *span != DUMMY_SP =>
864 /// Reasons a method might not be object-safe.
865 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
866 pub enum MethodViolationCode {
868 StaticMethod(Option<(&'static str, Span)>),
870 /// e.g., `fn foo(&self, x: Self)`
871 ReferencesSelfInput(usize),
873 /// e.g., `fn foo(&self) -> Self`
874 ReferencesSelfOutput,
876 /// e.g., `fn foo(&self) where Self: Clone`
877 WhereClauseReferencesSelf,
879 /// e.g., `fn foo<A>()`
882 /// the method's receiver (`self` argument) can't be dispatched on
883 UndispatchableReceiver,