1 //! Trait Resolution. See the [rustc dev guide] for more information on how this works.
3 //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html
8 pub mod specialization_graph;
12 use crate::infer::canonical::Canonical;
13 use crate::thir::abstract_const::NotConstEvaluatable;
14 use crate::ty::subst::SubstsRef;
15 use crate::ty::{self, AdtKind, Ty, TyCtxt};
17 use rustc_data_structures::sync::Lrc;
18 use rustc_errors::{Applicability, Diagnostic};
20 use rustc_hir::def_id::{DefId, LocalDefId};
21 use rustc_span::symbol::Symbol;
22 use rustc_span::{Span, DUMMY_SP};
23 use smallvec::SmallVec;
26 use std::hash::{Hash, Hasher};
28 pub use self::select::{EvaluationCache, EvaluationResult, OverflowError, SelectionCache};
30 pub type CanonicalChalkEnvironmentAndGoal<'tcx> = Canonical<'tcx, ChalkEnvironmentAndGoal<'tcx>>;
32 pub use self::ObligationCauseCode::*;
34 pub use self::chalk::{ChalkEnvironmentAndGoal, RustInterner as ChalkRustInterner};
36 /// Depending on the stage of compilation, we want projection to be
37 /// more or less conservative.
38 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, HashStable)]
40 /// At type-checking time, we refuse to project any associated
41 /// type that is marked `default`. Non-`default` ("final") types
42 /// are always projected. This is necessary in general for
43 /// soundness of specialization. However, we *could* allow
44 /// projections in fully-monomorphic cases. We choose not to,
45 /// because we prefer for `default type` to force the type
46 /// definition to be treated abstractly by any consumers of the
47 /// impl. Concretely, that means that the following example will
55 /// impl<T> Assoc for T {
56 /// default type Output = bool;
60 /// let <() as Assoc>::Output = true;
65 /// At codegen time, all monomorphic projections will succeed.
66 /// Also, `impl Trait` is normalized to the concrete type,
67 /// which has to be already collected by type-checking.
69 /// NOTE: as `impl Trait`'s concrete type should *never*
70 /// be observable directly by the user, `Reveal::All`
71 /// should not be used by checks which may expose
72 /// type equality or type contents to the user.
73 /// There are some exceptions, e.g., around auto traits and
74 /// transmute-checking, which expose some details, but
75 /// not the whole concrete type of the `impl Trait`.
79 /// The reason why we incurred this obligation; used for error reporting.
81 /// Non-misc `ObligationCauseCode`s are stored on the heap. This gives the
82 /// best trade-off between keeping the type small (which makes copies cheaper)
83 /// while not doing too many heap allocations.
85 /// We do not want to intern this as there are a lot of obligation causes which
86 /// only live for a short period of time.
87 #[derive(Clone, Debug, PartialEq, Eq, Lift)]
88 pub struct ObligationCause<'tcx> {
91 /// The ID of the fn body that triggered this obligation. This is
92 /// used for region obligations to determine the precise
93 /// environment in which the region obligation should be evaluated
94 /// (in particular, closures can add new assumptions). See the
95 /// field `region_obligations` of the `FulfillmentContext` for more
97 pub body_id: hir::HirId,
99 /// `None` for `MISC_OBLIGATION_CAUSE_CODE` (a common case, occurs ~60% of
100 /// the time). `Some` otherwise.
101 code: Option<Lrc<ObligationCauseCode<'tcx>>>,
104 // This custom hash function speeds up hashing for `Obligation` deduplication
105 // greatly by skipping the `code` field, which can be large and complex. That
106 // shouldn't affect hash quality much since there are several other fields in
107 // `Obligation` which should be unique enough, especially the predicate itself
108 // which is hashed as an interned pointer. See #90996.
109 impl Hash for ObligationCause<'_> {
110 fn hash<H: Hasher>(&self, state: &mut H) {
111 self.body_id.hash(state);
112 self.span.hash(state);
116 const MISC_OBLIGATION_CAUSE_CODE: ObligationCauseCode<'static> = MiscObligation;
118 impl<'tcx> ObligationCause<'tcx> {
123 code: ObligationCauseCode<'tcx>,
124 ) -> ObligationCause<'tcx> {
128 code: if code == MISC_OBLIGATION_CAUSE_CODE { None } else { Some(Lrc::new(code)) },
132 pub fn misc(span: Span, body_id: hir::HirId) -> ObligationCause<'tcx> {
133 ObligationCause::new(span, body_id, MiscObligation)
137 pub fn dummy() -> ObligationCause<'tcx> {
138 ObligationCause { span: DUMMY_SP, body_id: hir::CRATE_HIR_ID, code: None }
141 pub fn dummy_with_span(span: Span) -> ObligationCause<'tcx> {
142 ObligationCause { span, body_id: hir::CRATE_HIR_ID, code: None }
145 pub fn make_mut_code(&mut self) -> &mut ObligationCauseCode<'tcx> {
146 Lrc::make_mut(self.code.get_or_insert_with(|| Lrc::new(MISC_OBLIGATION_CAUSE_CODE)))
149 pub fn span(&self, tcx: TyCtxt<'tcx>) -> Span {
151 ObligationCauseCode::CompareImplMethodObligation { .. }
152 | ObligationCauseCode::MainFunctionType
153 | ObligationCauseCode::StartFunctionType => {
154 tcx.sess.source_map().guess_head_span(self.span)
156 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
165 pub fn code(&self) -> &ObligationCauseCode<'tcx> {
166 self.code.as_deref().unwrap_or(&MISC_OBLIGATION_CAUSE_CODE)
169 pub fn clone_code(&self) -> Lrc<ObligationCauseCode<'tcx>> {
171 Some(code) => code.clone(),
172 None => Lrc::new(MISC_OBLIGATION_CAUSE_CODE),
177 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
178 pub struct UnifyReceiverContext<'tcx> {
179 pub assoc_item: ty::AssocItem,
180 pub param_env: ty::ParamEnv<'tcx>,
181 pub substs: SubstsRef<'tcx>,
184 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
185 pub enum ObligationCauseCode<'tcx> {
186 /// Not well classified or should be obvious from the span.
189 /// A slice or array is WF only if `T: Sized`.
192 /// A tuple is WF only if its middle elements are `Sized`.
195 /// This is the trait reference from the given projection.
196 ProjectionWf(ty::ProjectionTy<'tcx>),
198 /// In an impl of trait `X` for type `Y`, type `Y` must
199 /// also implement all supertraits of `X`.
200 ItemObligation(DefId),
202 /// Like `ItemObligation`, but with extra detail on the source of the obligation.
203 BindingObligation(DefId, Span),
205 /// A type like `&'a T` is WF only if `T: 'a`.
206 ReferenceOutlivesReferent(Ty<'tcx>),
208 /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
209 ObjectTypeBound(Ty<'tcx>, ty::Region<'tcx>),
211 /// Obligation incurred due to an object cast.
212 ObjectCastObligation(/* Object type */ Ty<'tcx>),
214 /// Obligation incurred due to a coercion.
220 /// Various cases where expressions must be `Sized` / `Copy` / etc.
221 /// `L = X` implies that `L` is `Sized`.
223 /// `(x1, .., xn)` must be `Sized`.
224 TupleInitializerSized,
225 /// `S { ... }` must be `Sized`.
226 StructInitializerSized,
227 /// Type of each variable must be `Sized`.
228 VariableType(hir::HirId),
229 /// Argument type must be `Sized`.
230 SizedArgumentType(Option<Span>),
231 /// Return type must be `Sized`.
233 /// Yield type must be `Sized`.
235 /// Box expression result type must be `Sized`.
237 /// Inline asm operand type must be `Sized`.
239 /// `[T, ..n]` implies that `T` must be `Copy`.
240 /// If the function in the array repeat expression is a `const fn`,
241 /// display a help message suggesting to move the function call to a
242 /// new `const` item while saying that `T` doesn't implement `Copy`.
245 /// Types of fields (other than the last, except for packed structs) in a struct must be sized.
252 /// Constant expressions must be sized.
255 /// `static` items must have `Sync` type.
258 BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
260 ImplDerivedObligation(DerivedObligationCause<'tcx>),
262 DerivedObligation(DerivedObligationCause<'tcx>),
264 FunctionArgumentObligation {
265 /// The node of the relevant argument in the function call.
266 arg_hir_id: hir::HirId,
267 /// The node of the function call.
268 call_hir_id: hir::HirId,
269 /// The obligation introduced by this argument.
270 parent_code: Lrc<ObligationCauseCode<'tcx>>,
273 /// Error derived when matching traits/impls; see ObligationCause for more details
274 CompareImplConstObligation,
276 /// Error derived when matching traits/impls; see ObligationCause for more details
277 CompareImplMethodObligation {
278 impl_item_def_id: DefId,
279 trait_item_def_id: DefId,
282 /// Error derived when matching traits/impls; see ObligationCause for more details
283 CompareImplTypeObligation {
284 impl_item_def_id: DefId,
285 trait_item_def_id: DefId,
288 /// Checking that the bounds of a trait's associated type hold for a given impl
289 CheckAssociatedTypeBounds {
290 impl_item_def_id: DefId,
291 trait_item_def_id: DefId,
294 /// Checking that this expression can be assigned where it needs to be
295 // FIXME(eddyb) #11161 is the original Expr required?
298 /// Computing common supertype in the arms of a match expression
299 MatchExpressionArm(Box<MatchExpressionArmCause<'tcx>>),
301 /// Type error arising from type checking a pattern against an expected type.
303 /// The span of the scrutinee or type expression which caused the `root_ty` type.
305 /// The root expected type induced by a scrutinee or type expression.
307 /// Whether the `Span` came from an expression or a type expression.
311 /// Constants in patterns must have `Structural` type.
312 ConstPatternStructural,
314 /// Computing common supertype in an if expression
315 IfExpression(Box<IfExpressionCause>),
317 /// Computing common supertype of an if expression with no else counter-part
318 IfExpressionWithNoElse,
320 /// `main` has wrong type
323 /// `start` has wrong type
326 /// Intrinsic has wrong type
329 /// A let else block does not diverge
335 UnifyReceiver(Box<UnifyReceiverContext<'tcx>>),
337 /// `return` with no expression
340 /// `return` with an expression
341 ReturnValue(hir::HirId),
343 /// Return type of this function
346 /// Block implicit return
347 BlockTailExpression(hir::HirId),
349 /// #[feature(trivial_bounds)] is not enabled
352 /// If `X` is the concrete type of an opaque type `impl Y`, then `X` must implement `Y`
355 AwaitableExpr(Option<hir::HirId>),
361 /// Well-formed checking. If a `WellFormedLoc` is provided,
362 /// then it will be used to eprform HIR-based wf checking
363 /// after an error occurs, in order to generate a more precise error span.
364 /// This is purely for diagnostic purposes - it is always
365 /// correct to use `MiscObligation` instead, or to specify
366 /// `WellFormed(None)`
367 WellFormed(Option<WellFormedLoc>),
369 /// From `match_impl`. The cause for us having to match an impl, and the DefId we are matching against.
370 MatchImpl(ObligationCause<'tcx>, DefId),
373 rhs_span: Option<Span>,
378 /// The 'location' at which we try to perform HIR-based wf checking.
379 /// This information is used to obtain an `hir::Ty`, which
380 /// we can walk in order to obtain precise spans for any
381 /// 'nested' types (e.g. `Foo` in `Option<Foo>`).
382 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
383 pub enum WellFormedLoc {
384 /// Use the type of the provided definition.
386 /// Use the type of the parameter of the provided function.
387 /// We cannot use `hir::Param`, since the function may
388 /// not have a body (e.g. a trait method definition)
390 /// The function to lookup the parameter in
391 function: LocalDefId,
392 /// The index of the parameter to use.
393 /// Parameters are indexed from 0, with the return type
394 /// being the last 'parameter'
399 impl ObligationCauseCode<'_> {
400 // Return the base obligation, ignoring derived obligations.
401 pub fn peel_derives(&self) -> &Self {
402 let mut base_cause = self;
403 while let BuiltinDerivedObligation(DerivedObligationCause { parent_code, .. })
404 | ImplDerivedObligation(DerivedObligationCause { parent_code, .. })
405 | DerivedObligation(DerivedObligationCause { parent_code, .. })
406 | FunctionArgumentObligation { parent_code, .. } = base_cause
408 base_cause = &parent_code;
414 // `ObligationCauseCode` is used a lot. Make sure it doesn't unintentionally get bigger.
415 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
416 static_assert_size!(ObligationCauseCode<'_>, 48);
418 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
419 pub enum StatementAsExpression {
424 impl<'tcx> ty::Lift<'tcx> for StatementAsExpression {
425 type Lifted = StatementAsExpression;
426 fn lift_to_tcx(self, _tcx: TyCtxt<'tcx>) -> Option<StatementAsExpression> {
431 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
432 pub struct MatchExpressionArmCause<'tcx> {
434 pub scrut_span: Span,
435 pub semi_span: Option<(Span, StatementAsExpression)>,
436 pub source: hir::MatchSource,
437 pub prior_arms: Vec<Span>,
438 pub last_ty: Ty<'tcx>,
439 pub scrut_hir_id: hir::HirId,
440 pub opt_suggest_box_span: Option<Span>,
443 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
444 pub struct IfExpressionCause {
447 pub outer: Option<Span>,
448 pub semicolon: Option<(Span, StatementAsExpression)>,
449 pub opt_suggest_box_span: Option<Span>,
452 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
453 pub struct DerivedObligationCause<'tcx> {
454 /// The trait predicate of the parent obligation that led to the
455 /// current obligation. Note that only trait obligations lead to
456 /// derived obligations, so we just store the trait predicate here
458 pub parent_trait_pred: ty::PolyTraitPredicate<'tcx>,
460 /// The parent trait had this cause.
461 pub parent_code: Lrc<ObligationCauseCode<'tcx>>,
464 #[derive(Clone, Debug, TypeFoldable, Lift)]
465 pub enum SelectionError<'tcx> {
466 /// The trait is not implemented.
468 /// After a closure impl has selected, its "outputs" were evaluated
469 /// (which for closures includes the "input" type params) and they
470 /// didn't resolve. See `confirm_poly_trait_refs` for more.
471 OutputTypeParameterMismatch(
472 ty::PolyTraitRef<'tcx>,
473 ty::PolyTraitRef<'tcx>,
474 ty::error::TypeError<'tcx>,
476 /// The trait pointed by `DefId` is not object safe.
477 TraitNotObjectSafe(DefId),
478 /// A given constant couldn't be evaluated.
479 NotConstEvaluatable(NotConstEvaluatable),
480 /// Exceeded the recursion depth during type projection.
482 /// Signaling that an error has already been emitted, to avoid
483 /// multiple errors being shown.
485 /// Multiple applicable `impl`s where found. The `DefId`s correspond to
486 /// all the `impl`s' Items.
487 Ambiguous(Vec<DefId>),
490 /// When performing resolution, it is typically the case that there
491 /// can be one of three outcomes:
493 /// - `Ok(Some(r))`: success occurred with result `r`
494 /// - `Ok(None)`: could not definitely determine anything, usually due
495 /// to inconclusive type inference.
496 /// - `Err(e)`: error `e` occurred
497 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
499 /// Given the successful resolution of an obligation, the `ImplSource`
500 /// indicates where the impl comes from.
502 /// For example, the obligation may be satisfied by 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 i32 { ... } // Impl_3
510 /// fn foo<T: Clone>(concrete: Option<Box<i32>>, param: T, mixed: Option<T>) {
511 /// // Case A: ImplSource points at a specific impl. Only possible when
512 /// // type is concretely known. If the impl itself has bounded
513 /// // type parameters, ImplSource will carry resolutions for those as well:
514 /// concrete.clone(); // ImpleSource(Impl_1, [ImplSource(Impl_2, [ImplSource(Impl_3)])])
516 /// // Case A: ImplSource points at a specific impl. Only possible when
517 /// // type is concretely known. If the impl itself has bounded
518 /// // type parameters, ImplSource will carry resolutions for those as well:
519 /// concrete.clone(); // ImplSource(Impl_1, [ImplSource(Impl_2, [ImplSource(Impl_3)])])
521 /// // Case B: ImplSource must be provided by caller. This applies when
522 /// // type is a type parameter.
523 /// param.clone(); // ImplSource::Param
525 /// // Case C: A mix of cases A and B.
526 /// mixed.clone(); // ImplSource(Impl_1, [ImplSource::Param])
530 /// ### The type parameter `N`
532 /// See explanation on `ImplSourceUserDefinedData`.
533 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
534 pub enum ImplSource<'tcx, N> {
535 /// ImplSource identifying a particular impl.
536 UserDefined(ImplSourceUserDefinedData<'tcx, N>),
538 /// ImplSource for auto trait implementations.
539 /// This carries the information and nested obligations with regards
540 /// to an auto implementation for a trait `Trait`. The nested obligations
541 /// ensure the trait implementation holds for all the constituent types.
542 AutoImpl(ImplSourceAutoImplData<N>),
544 /// Successful resolution to an obligation provided by the caller
545 /// for some type parameter. The `Vec<N>` represents the
546 /// obligations incurred from normalizing the where-clause (if
548 Param(Vec<N>, ty::BoundConstness),
550 /// Virtual calls through an object.
551 Object(ImplSourceObjectData<'tcx, N>),
553 /// Successful resolution for a builtin trait.
554 Builtin(ImplSourceBuiltinData<N>),
556 /// ImplSource for trait upcasting coercion
557 TraitUpcasting(ImplSourceTraitUpcastingData<'tcx, N>),
559 /// ImplSource automatically generated for a closure. The `DefId` is the ID
560 /// of the closure expression. This is an `ImplSource::UserDefined` in spirit, but the
561 /// impl is generated by the compiler and does not appear in the source.
562 Closure(ImplSourceClosureData<'tcx, N>),
564 /// Same as above, but for a function pointer type with the given signature.
565 FnPointer(ImplSourceFnPointerData<'tcx, N>),
567 /// ImplSource for a builtin `DeterminantKind` trait implementation.
568 DiscriminantKind(ImplSourceDiscriminantKindData),
570 /// ImplSource for a builtin `Pointee` trait implementation.
571 Pointee(ImplSourcePointeeData),
573 /// ImplSource automatically generated for a generator.
574 Generator(ImplSourceGeneratorData<'tcx, N>),
576 /// ImplSource for a trait alias.
577 TraitAlias(ImplSourceTraitAliasData<'tcx, N>),
579 /// ImplSource for a `const Drop` implementation.
580 ConstDestruct(ImplSourceConstDestructData<N>),
583 impl<'tcx, N> ImplSource<'tcx, N> {
584 pub fn nested_obligations(self) -> Vec<N> {
586 ImplSource::UserDefined(i) => i.nested,
587 ImplSource::Param(n, _) => n,
588 ImplSource::Builtin(i) => i.nested,
589 ImplSource::AutoImpl(d) => d.nested,
590 ImplSource::Closure(c) => c.nested,
591 ImplSource::Generator(c) => c.nested,
592 ImplSource::Object(d) => d.nested,
593 ImplSource::FnPointer(d) => d.nested,
594 ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData)
595 | ImplSource::Pointee(ImplSourcePointeeData) => Vec::new(),
596 ImplSource::TraitAlias(d) => d.nested,
597 ImplSource::TraitUpcasting(d) => d.nested,
598 ImplSource::ConstDestruct(i) => i.nested,
602 pub fn borrow_nested_obligations(&self) -> &[N] {
604 ImplSource::UserDefined(i) => &i.nested[..],
605 ImplSource::Param(n, _) => &n,
606 ImplSource::Builtin(i) => &i.nested,
607 ImplSource::AutoImpl(d) => &d.nested,
608 ImplSource::Closure(c) => &c.nested,
609 ImplSource::Generator(c) => &c.nested,
610 ImplSource::Object(d) => &d.nested,
611 ImplSource::FnPointer(d) => &d.nested,
612 ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData)
613 | ImplSource::Pointee(ImplSourcePointeeData) => &[],
614 ImplSource::TraitAlias(d) => &d.nested,
615 ImplSource::TraitUpcasting(d) => &d.nested,
616 ImplSource::ConstDestruct(i) => &i.nested,
620 pub fn map<M, F>(self, f: F) -> ImplSource<'tcx, M>
625 ImplSource::UserDefined(i) => ImplSource::UserDefined(ImplSourceUserDefinedData {
626 impl_def_id: i.impl_def_id,
628 nested: i.nested.into_iter().map(f).collect(),
630 ImplSource::Param(n, ct) => ImplSource::Param(n.into_iter().map(f).collect(), ct),
631 ImplSource::Builtin(i) => ImplSource::Builtin(ImplSourceBuiltinData {
632 nested: i.nested.into_iter().map(f).collect(),
634 ImplSource::Object(o) => ImplSource::Object(ImplSourceObjectData {
635 upcast_trait_ref: o.upcast_trait_ref,
636 vtable_base: o.vtable_base,
637 nested: o.nested.into_iter().map(f).collect(),
639 ImplSource::AutoImpl(d) => ImplSource::AutoImpl(ImplSourceAutoImplData {
640 trait_def_id: d.trait_def_id,
641 nested: d.nested.into_iter().map(f).collect(),
643 ImplSource::Closure(c) => ImplSource::Closure(ImplSourceClosureData {
644 closure_def_id: c.closure_def_id,
646 nested: c.nested.into_iter().map(f).collect(),
648 ImplSource::Generator(c) => ImplSource::Generator(ImplSourceGeneratorData {
649 generator_def_id: c.generator_def_id,
651 nested: c.nested.into_iter().map(f).collect(),
653 ImplSource::FnPointer(p) => ImplSource::FnPointer(ImplSourceFnPointerData {
655 nested: p.nested.into_iter().map(f).collect(),
657 ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData) => {
658 ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData)
660 ImplSource::Pointee(ImplSourcePointeeData) => {
661 ImplSource::Pointee(ImplSourcePointeeData)
663 ImplSource::TraitAlias(d) => ImplSource::TraitAlias(ImplSourceTraitAliasData {
664 alias_def_id: d.alias_def_id,
666 nested: d.nested.into_iter().map(f).collect(),
668 ImplSource::TraitUpcasting(d) => {
669 ImplSource::TraitUpcasting(ImplSourceTraitUpcastingData {
670 upcast_trait_ref: d.upcast_trait_ref,
671 vtable_vptr_slot: d.vtable_vptr_slot,
672 nested: d.nested.into_iter().map(f).collect(),
675 ImplSource::ConstDestruct(i) => {
676 ImplSource::ConstDestruct(ImplSourceConstDestructData {
677 nested: i.nested.into_iter().map(f).collect(),
684 /// Identifies a particular impl in the source, along with a set of
685 /// substitutions from the impl's type/lifetime parameters. The
686 /// `nested` vector corresponds to the nested obligations attached to
687 /// the impl's type parameters.
689 /// The type parameter `N` indicates the type used for "nested
690 /// obligations" that are required by the impl. During type-check, this
691 /// is `Obligation`, as one might expect. During codegen, however, this
692 /// is `()`, because codegen only requires a shallow resolution of an
693 /// impl, and nested obligations are satisfied later.
694 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
695 pub struct ImplSourceUserDefinedData<'tcx, N> {
696 pub impl_def_id: DefId,
697 pub substs: SubstsRef<'tcx>,
701 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
702 pub struct ImplSourceGeneratorData<'tcx, N> {
703 pub generator_def_id: DefId,
704 pub substs: SubstsRef<'tcx>,
705 /// Nested obligations. This can be non-empty if the generator
706 /// signature contains associated types.
710 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
711 pub struct ImplSourceClosureData<'tcx, N> {
712 pub closure_def_id: DefId,
713 pub substs: SubstsRef<'tcx>,
714 /// Nested obligations. This can be non-empty if the closure
715 /// signature contains associated types.
719 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
720 pub struct ImplSourceAutoImplData<N> {
721 pub trait_def_id: DefId,
725 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
726 pub struct ImplSourceTraitUpcastingData<'tcx, N> {
727 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
728 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
730 /// The vtable is formed by concatenating together the method lists of
731 /// the base object trait and all supertraits, pointers to supertrait vtable will
732 /// be provided when necessary; this is the position of `upcast_trait_ref`'s vtable
733 /// within that vtable.
734 pub vtable_vptr_slot: Option<usize>,
739 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
740 pub struct ImplSourceBuiltinData<N> {
744 #[derive(PartialEq, Eq, Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
745 pub struct ImplSourceObjectData<'tcx, N> {
746 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
747 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
749 /// The vtable is formed by concatenating together the method lists of
750 /// the base object trait and all supertraits, pointers to supertrait vtable will
751 /// be provided when necessary; this is the start of `upcast_trait_ref`'s methods
753 pub vtable_base: usize,
758 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
759 pub struct ImplSourceFnPointerData<'tcx, N> {
764 // FIXME(@lcnr): This should be refactored and merged with other builtin vtables.
765 #[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
766 pub struct ImplSourceDiscriminantKindData;
768 #[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
769 pub struct ImplSourcePointeeData;
771 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
772 pub struct ImplSourceConstDestructData<N> {
776 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
777 pub struct ImplSourceTraitAliasData<'tcx, N> {
778 pub alias_def_id: DefId,
779 pub substs: SubstsRef<'tcx>,
783 #[derive(Clone, Debug, PartialEq, Eq, Hash, HashStable, PartialOrd, Ord)]
784 pub enum ObjectSafetyViolation {
785 /// `Self: Sized` declared on the trait.
786 SizedSelf(SmallVec<[Span; 1]>),
788 /// Supertrait reference references `Self` an in illegal location
789 /// (e.g., `trait Foo : Bar<Self>`).
790 SupertraitSelf(SmallVec<[Span; 1]>),
792 /// Method has something illegal.
793 Method(Symbol, MethodViolationCode, Span),
795 /// Associated const.
796 AssocConst(Symbol, Span),
802 impl ObjectSafetyViolation {
803 pub fn error_msg(&self) -> Cow<'static, str> {
805 ObjectSafetyViolation::SizedSelf(_) => "it requires `Self: Sized`".into(),
806 ObjectSafetyViolation::SupertraitSelf(ref spans) => {
807 if spans.iter().any(|sp| *sp != DUMMY_SP) {
808 "it uses `Self` as a type parameter".into()
810 "it cannot use `Self` as a type parameter in a supertrait or `where`-clause"
814 ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod(_, _, _), _) => {
815 format!("associated function `{}` has no `self` parameter", name).into()
817 ObjectSafetyViolation::Method(
819 MethodViolationCode::ReferencesSelfInput(_),
821 ) => format!("method `{}` references the `Self` type in its parameters", name).into(),
822 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfInput(_), _) => {
823 format!("method `{}` references the `Self` type in this parameter", name).into()
825 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfOutput, _) => {
826 format!("method `{}` references the `Self` type in its return type", name).into()
828 ObjectSafetyViolation::Method(
830 MethodViolationCode::WhereClauseReferencesSelf,
833 format!("method `{}` references the `Self` type in its `where` clause", name).into()
835 ObjectSafetyViolation::Method(name, MethodViolationCode::Generic, _) => {
836 format!("method `{}` has generic type parameters", name).into()
838 ObjectSafetyViolation::Method(name, MethodViolationCode::UndispatchableReceiver, _) => {
839 format!("method `{}`'s `self` parameter cannot be dispatched on", name).into()
841 ObjectSafetyViolation::AssocConst(name, DUMMY_SP) => {
842 format!("it contains associated `const` `{}`", name).into()
844 ObjectSafetyViolation::AssocConst(..) => "it contains this associated `const`".into(),
845 ObjectSafetyViolation::GAT(name, _) => {
846 format!("it contains the generic associated type `{}`", name).into()
851 pub fn solution(&self, err: &mut Diagnostic) {
853 ObjectSafetyViolation::SizedSelf(_) | ObjectSafetyViolation::SupertraitSelf(_) => {}
854 ObjectSafetyViolation::Method(
856 MethodViolationCode::StaticMethod(sugg, self_span, has_args),
862 "consider turning `{}` into a method by giving it a `&self` argument",
865 format!("&self{}", if has_args { ", " } else { "" }),
866 Applicability::MaybeIncorrect,
869 Some((sugg, span)) => {
873 "alternatively, consider constraining `{}` so it does not apply to \
878 Applicability::MaybeIncorrect,
883 "consider turning `{}` into a method by giving it a `&self` \
884 argument or constraining it so it does not apply to trait objects",
890 ObjectSafetyViolation::Method(
892 MethodViolationCode::UndispatchableReceiver,
898 "consider changing method `{}`'s `self` parameter to be `&self`",
902 Applicability::MachineApplicable,
905 ObjectSafetyViolation::AssocConst(name, _)
906 | ObjectSafetyViolation::GAT(name, _)
907 | ObjectSafetyViolation::Method(name, ..) => {
908 err.help(&format!("consider moving `{}` to another trait", name));
913 pub fn spans(&self) -> SmallVec<[Span; 1]> {
914 // When `span` comes from a separate crate, it'll be `DUMMY_SP`. Treat it as `None` so
915 // diagnostics use a `note` instead of a `span_label`.
917 ObjectSafetyViolation::SupertraitSelf(spans)
918 | ObjectSafetyViolation::SizedSelf(spans) => spans.clone(),
919 ObjectSafetyViolation::AssocConst(_, span)
920 | ObjectSafetyViolation::GAT(_, span)
921 | ObjectSafetyViolation::Method(_, _, span)
922 if *span != DUMMY_SP =>
931 /// Reasons a method might not be object-safe.
932 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable, PartialOrd, Ord)]
933 pub enum MethodViolationCode {
935 StaticMethod(Option<(&'static str, Span)>, Span, bool /* has args */),
937 /// e.g., `fn foo(&self, x: Self)`
938 ReferencesSelfInput(usize),
940 /// e.g., `fn foo(&self) -> Self`
941 ReferencesSelfOutput,
943 /// e.g., `fn foo(&self) where Self: Clone`
944 WhereClauseReferencesSelf,
946 /// e.g., `fn foo<A>()`
949 /// the method's receiver (`self` argument) can't be dispatched on
950 UndispatchableReceiver,