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;
11 use crate::infer::canonical::Canonical;
12 use crate::thir::abstract_const::NotConstEvaluatable;
13 use crate::ty::subst::SubstsRef;
14 use crate::ty::{self, AdtKind, Ty, TyCtxt};
16 use rustc_data_structures::sync::Lrc;
17 use rustc_errors::{Applicability, DiagnosticBuilder};
19 use rustc_hir::def_id::{DefId, LocalDefId};
20 use rustc_span::symbol::Symbol;
21 use rustc_span::{Span, DUMMY_SP};
22 use smallvec::SmallVec;
26 use std::hash::{Hash, Hasher};
29 pub use self::select::{EvaluationCache, EvaluationResult, OverflowError, SelectionCache};
31 pub type CanonicalChalkEnvironmentAndGoal<'tcx> = Canonical<'tcx, ChalkEnvironmentAndGoal<'tcx>>;
33 pub use self::ObligationCauseCode::*;
35 pub use self::chalk::{ChalkEnvironmentAndGoal, RustInterner as ChalkRustInterner};
37 /// Depending on the stage of compilation, we want projection to be
38 /// more or less conservative.
39 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, HashStable)]
41 /// At type-checking time, we refuse to project any associated
42 /// type that is marked `default`. Non-`default` ("final") types
43 /// are always projected. This is necessary in general for
44 /// soundness of specialization. However, we *could* allow
45 /// projections in fully-monomorphic cases. We choose not to,
46 /// because we prefer for `default type` to force the type
47 /// definition to be treated abstractly by any consumers of the
48 /// impl. Concretely, that means that the following example will
56 /// impl<T> Assoc for T {
57 /// default type Output = bool;
61 /// let <() as Assoc>::Output = true;
66 /// At codegen time, all monomorphic projections will succeed.
67 /// Also, `impl Trait` is normalized to the concrete type,
68 /// which has to be already collected by type-checking.
70 /// NOTE: as `impl Trait`'s concrete type should *never*
71 /// be observable directly by the user, `Reveal::All`
72 /// should not be used by checks which may expose
73 /// type equality or type contents to the user.
74 /// There are some exceptions, e.g., around auto traits and
75 /// transmute-checking, which expose some details, but
76 /// not the whole concrete type of the `impl Trait`.
80 /// The reason why we incurred this obligation; used for error reporting.
82 /// As the happy path does not care about this struct, storing this on the heap
83 /// ends up increasing performance.
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, PartialEq, Eq, Hash, Lift)]
88 pub struct ObligationCause<'tcx> {
89 /// `None` for `ObligationCause::dummy`, `Some` otherwise.
90 data: Option<Lrc<ObligationCauseData<'tcx>>>,
93 const DUMMY_OBLIGATION_CAUSE_DATA: ObligationCauseData<'static> =
94 ObligationCauseData { span: DUMMY_SP, body_id: hir::CRATE_HIR_ID, code: MiscObligation };
96 // Correctly format `ObligationCause::dummy`.
97 impl<'tcx> fmt::Debug for ObligationCause<'tcx> {
98 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99 ObligationCauseData::fmt(self, f)
103 impl Deref for ObligationCause<'tcx> {
104 type Target = ObligationCauseData<'tcx>;
107 fn deref(&self) -> &Self::Target {
108 self.data.as_deref().unwrap_or(&DUMMY_OBLIGATION_CAUSE_DATA)
112 #[derive(Clone, Debug, PartialEq, Eq, Lift)]
113 pub struct ObligationCauseData<'tcx> {
116 /// The ID of the fn body that triggered this obligation. This is
117 /// used for region obligations to determine the precise
118 /// environment in which the region obligation should be evaluated
119 /// (in particular, closures can add new assumptions). See the
120 /// field `region_obligations` of the `FulfillmentContext` for more
122 pub body_id: hir::HirId,
124 pub code: ObligationCauseCode<'tcx>,
127 impl Hash for ObligationCauseData<'_> {
128 fn hash<H: Hasher>(&self, state: &mut H) {
129 self.body_id.hash(state);
130 self.span.hash(state);
131 std::mem::discriminant(&self.code).hash(state);
135 impl<'tcx> ObligationCause<'tcx> {
140 code: ObligationCauseCode<'tcx>,
141 ) -> ObligationCause<'tcx> {
142 ObligationCause { data: Some(Lrc::new(ObligationCauseData { span, body_id, code })) }
145 pub fn misc(span: Span, body_id: hir::HirId) -> ObligationCause<'tcx> {
146 ObligationCause::new(span, body_id, MiscObligation)
149 pub fn dummy_with_span(span: Span) -> ObligationCause<'tcx> {
150 ObligationCause::new(span, hir::CRATE_HIR_ID, MiscObligation)
154 pub fn dummy() -> ObligationCause<'tcx> {
155 ObligationCause { data: None }
158 pub fn make_mut(&mut self) -> &mut ObligationCauseData<'tcx> {
159 Lrc::make_mut(self.data.get_or_insert_with(|| Lrc::new(DUMMY_OBLIGATION_CAUSE_DATA)))
162 pub fn span(&self, tcx: TyCtxt<'tcx>) -> Span {
164 ObligationCauseCode::CompareImplMethodObligation { .. }
165 | ObligationCauseCode::MainFunctionType
166 | ObligationCauseCode::StartFunctionType => {
167 tcx.sess.source_map().guess_head_span(self.span)
169 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
178 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
179 pub struct UnifyReceiverContext<'tcx> {
180 pub assoc_item: ty::AssocItem,
181 pub param_env: ty::ParamEnv<'tcx>,
182 pub substs: SubstsRef<'tcx>,
185 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
186 pub enum ObligationCauseCode<'tcx> {
187 /// Not well classified or should be obvious from the span.
190 /// A slice or array is WF only if `T: Sized`.
193 /// A tuple is WF only if its middle elements are `Sized`.
196 /// This is the trait reference from the given projection.
197 ProjectionWf(ty::ProjectionTy<'tcx>),
199 /// In an impl of trait `X` for type `Y`, type `Y` must
200 /// also implement all supertraits of `X`.
201 ItemObligation(DefId),
203 /// Like `ItemObligation`, but with extra detail on the source of the obligation.
204 BindingObligation(DefId, Span),
206 /// A type like `&'a T` is WF only if `T: 'a`.
207 ReferenceOutlivesReferent(Ty<'tcx>),
209 /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
210 ObjectTypeBound(Ty<'tcx>, ty::Region<'tcx>),
212 /// Obligation incurred due to an object cast.
213 ObjectCastObligation(/* Object type */ Ty<'tcx>),
215 /// Obligation incurred due to a coercion.
221 /// Various cases where expressions must be `Sized` / `Copy` / etc.
222 /// `L = X` implies that `L` is `Sized`.
224 /// `(x1, .., xn)` must be `Sized`.
225 TupleInitializerSized,
226 /// `S { ... }` must be `Sized`.
227 StructInitializerSized,
228 /// Type of each variable must be `Sized`.
229 VariableType(hir::HirId),
230 /// Argument type must be `Sized`.
231 SizedArgumentType(Option<Span>),
232 /// Return type must be `Sized`.
234 /// Yield type must be `Sized`.
236 /// Box expression result type must be `Sized`.
238 /// Inline asm operand type must be `Sized`.
240 /// `[T, ..n]` implies that `T` must be `Copy`.
241 /// If the function in the array repeat expression is a `const fn`,
242 /// display a help message suggesting to move the function call to a
243 /// new `const` item while saying that `T` doesn't implement `Copy`.
246 /// Types of fields (other than the last, except for packed structs) in a struct must be sized.
253 /// Constant expressions must be sized.
256 /// `static` items must have `Sync` type.
259 BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
261 ImplDerivedObligation(DerivedObligationCause<'tcx>),
263 DerivedObligation(DerivedObligationCause<'tcx>),
265 FunctionArgumentObligation {
266 /// The node of the relevant argument in the function call.
267 arg_hir_id: hir::HirId,
268 /// The node of the function call.
269 call_hir_id: hir::HirId,
270 /// The obligation introduced by this argument.
271 parent_code: Lrc<ObligationCauseCode<'tcx>>,
274 /// Error derived when matching traits/impls; see ObligationCause for more details
275 CompareImplConstObligation,
277 /// Error derived when matching traits/impls; see ObligationCause for more details
278 CompareImplMethodObligation {
279 impl_item_def_id: DefId,
280 trait_item_def_id: DefId,
283 /// Error derived when matching traits/impls; see ObligationCause for more details
284 CompareImplTypeObligation {
285 impl_item_def_id: DefId,
286 trait_item_def_id: DefId,
289 /// Checking that this expression can be assigned where it needs to be
290 // FIXME(eddyb) #11161 is the original Expr required?
293 /// Computing common supertype in the arms of a match expression
294 MatchExpressionArm(Box<MatchExpressionArmCause<'tcx>>),
296 /// Type error arising from type checking a pattern against an expected type.
298 /// The span of the scrutinee or type expression which caused the `root_ty` type.
300 /// The root expected type induced by a scrutinee or type expression.
302 /// Whether the `Span` came from an expression or a type expression.
306 /// Constants in patterns must have `Structural` type.
307 ConstPatternStructural,
309 /// Computing common supertype in an if expression
310 IfExpression(Box<IfExpressionCause>),
312 /// Computing common supertype of an if expression with no else counter-part
313 IfExpressionWithNoElse,
315 /// `main` has wrong type
318 /// `start` has wrong type
321 /// Intrinsic has wrong type
324 /// A let else block does not diverge
330 UnifyReceiver(Box<UnifyReceiverContext<'tcx>>),
332 /// `return` with no expression
335 /// `return` with an expression
336 ReturnValue(hir::HirId),
338 /// Return type of this function
341 /// Block implicit return
342 BlockTailExpression(hir::HirId),
344 /// #[feature(trivial_bounds)] is not enabled
347 /// If `X` is the concrete type of an opaque type `impl Y`, then `X` must implement `Y`
350 /// Well-formed checking. If a `WellFormedLoc` is provided,
351 /// then it will be used to eprform HIR-based wf checking
352 /// after an error occurs, in order to generate a more precise error span.
353 /// This is purely for diagnostic purposes - it is always
354 /// correct to use `MiscObligation` instead, or to specify
355 /// `WellFormed(None)`
356 WellFormed(Option<WellFormedLoc>),
358 /// From `match_impl`. The cause for us having to match an impl, and the DefId we are matching against.
359 MatchImpl(ObligationCause<'tcx>, DefId),
362 /// The 'location' at which we try to perform HIR-based wf checking.
363 /// This information is used to obtain an `hir::Ty`, which
364 /// we can walk in order to obtain precise spans for any
365 /// 'nested' types (e.g. `Foo` in `Option<Foo>`).
366 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
367 pub enum WellFormedLoc {
368 /// Use the type of the provided definition.
370 /// Use the type of the parameter of the provided function.
371 /// We cannot use `hir::Param`, since the function may
372 /// not have a body (e.g. a trait method definition)
374 /// The function to lookup the parameter in
375 function: LocalDefId,
376 /// The index of the parameter to use.
377 /// Parameters are indexed from 0, with the return type
378 /// being the last 'parameter'
383 impl ObligationCauseCode<'_> {
384 // Return the base obligation, ignoring derived obligations.
385 pub fn peel_derives(&self) -> &Self {
386 let mut base_cause = self;
387 while let BuiltinDerivedObligation(DerivedObligationCause { parent_code, .. })
388 | ImplDerivedObligation(DerivedObligationCause { parent_code, .. })
389 | DerivedObligation(DerivedObligationCause { parent_code, .. })
390 | FunctionArgumentObligation { parent_code, .. } = base_cause
392 base_cause = &parent_code;
398 // `ObligationCauseCode` is used a lot. Make sure it doesn't unintentionally get bigger.
399 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
400 static_assert_size!(ObligationCauseCode<'_>, 40);
402 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
403 pub enum StatementAsExpression {
408 impl<'tcx> ty::Lift<'tcx> for StatementAsExpression {
409 type Lifted = StatementAsExpression;
410 fn lift_to_tcx(self, _tcx: TyCtxt<'tcx>) -> Option<StatementAsExpression> {
415 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
416 pub struct MatchExpressionArmCause<'tcx> {
418 pub scrut_span: Span,
419 pub semi_span: Option<(Span, StatementAsExpression)>,
420 pub source: hir::MatchSource,
421 pub prior_arms: Vec<Span>,
422 pub last_ty: Ty<'tcx>,
423 pub scrut_hir_id: hir::HirId,
424 pub opt_suggest_box_span: Option<Span>,
427 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
428 pub struct IfExpressionCause {
431 pub outer: Option<Span>,
432 pub semicolon: Option<(Span, StatementAsExpression)>,
433 pub opt_suggest_box_span: Option<Span>,
436 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
437 pub struct DerivedObligationCause<'tcx> {
438 /// The trait reference of the parent obligation that led to the
439 /// current obligation. Note that only trait obligations lead to
440 /// derived obligations, so we just store the trait reference here
442 pub parent_trait_ref: ty::PolyTraitRef<'tcx>,
444 /// The parent trait had this cause.
445 pub parent_code: Lrc<ObligationCauseCode<'tcx>>,
448 #[derive(Clone, Debug, TypeFoldable, Lift)]
449 pub enum SelectionError<'tcx> {
450 /// The trait is not implemented.
452 /// After a closure impl has selected, its "outputs" were evaluated
453 /// (which for closures includes the "input" type params) and they
454 /// didn't resolve. See `confirm_poly_trait_refs` for more.
455 OutputTypeParameterMismatch(
456 ty::PolyTraitRef<'tcx>,
457 ty::PolyTraitRef<'tcx>,
458 ty::error::TypeError<'tcx>,
460 /// The trait pointed by `DefId` is not object safe.
461 TraitNotObjectSafe(DefId),
462 /// A given constant couldn't be evaluated.
463 NotConstEvaluatable(NotConstEvaluatable),
464 /// Exceeded the recursion depth during type projection.
466 /// Signaling that an error has already been emitted, to avoid
467 /// multiple errors being shown.
469 /// Multiple applicable `impl`s where found. The `DefId`s correspond to
470 /// all the `impl`s' Items.
471 Ambiguous(Vec<DefId>),
474 /// When performing resolution, it is typically the case that there
475 /// can be one of three outcomes:
477 /// - `Ok(Some(r))`: success occurred with result `r`
478 /// - `Ok(None)`: could not definitely determine anything, usually due
479 /// to inconclusive type inference.
480 /// - `Err(e)`: error `e` occurred
481 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
483 /// Given the successful resolution of an obligation, the `ImplSource`
484 /// indicates where the impl comes from.
486 /// For example, the obligation may be satisfied by a specific impl (case A),
487 /// or it may be relative to some bound that is in scope (case B).
490 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
491 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
492 /// impl Clone for i32 { ... } // Impl_3
494 /// fn foo<T: Clone>(concrete: Option<Box<i32>>, param: T, mixed: Option<T>) {
495 /// // Case A: ImplSource points at a specific impl. Only possible when
496 /// // type is concretely known. If the impl itself has bounded
497 /// // type parameters, ImplSource will carry resolutions for those as well:
498 /// concrete.clone(); // ImpleSource(Impl_1, [ImplSource(Impl_2, [ImplSource(Impl_3)])])
500 /// // Case A: ImplSource points at a specific impl. Only possible when
501 /// // type is concretely known. If the impl itself has bounded
502 /// // type parameters, ImplSource will carry resolutions for those as well:
503 /// concrete.clone(); // ImplSource(Impl_1, [ImplSource(Impl_2, [ImplSource(Impl_3)])])
505 /// // Case B: ImplSource must be provided by caller. This applies when
506 /// // type is a type parameter.
507 /// param.clone(); // ImplSource::Param
509 /// // Case C: A mix of cases A and B.
510 /// mixed.clone(); // ImplSource(Impl_1, [ImplSource::Param])
514 /// ### The type parameter `N`
516 /// See explanation on `ImplSourceUserDefinedData`.
517 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
518 pub enum ImplSource<'tcx, N> {
519 /// ImplSource identifying a particular impl.
520 UserDefined(ImplSourceUserDefinedData<'tcx, N>),
522 /// ImplSource for auto trait implementations.
523 /// This carries the information and nested obligations with regards
524 /// to an auto implementation for a trait `Trait`. The nested obligations
525 /// ensure the trait implementation holds for all the constituent types.
526 AutoImpl(ImplSourceAutoImplData<N>),
528 /// Successful resolution to an obligation provided by the caller
529 /// for some type parameter. The `Vec<N>` represents the
530 /// obligations incurred from normalizing the where-clause (if
532 Param(Vec<N>, ty::BoundConstness),
534 /// Virtual calls through an object.
535 Object(ImplSourceObjectData<'tcx, N>),
537 /// Successful resolution for a builtin trait.
538 Builtin(ImplSourceBuiltinData<N>),
540 /// ImplSource for trait upcasting coercion
541 TraitUpcasting(ImplSourceTraitUpcastingData<'tcx, N>),
543 /// ImplSource automatically generated for a closure. The `DefId` is the ID
544 /// of the closure expression. This is an `ImplSource::UserDefined` in spirit, but the
545 /// impl is generated by the compiler and does not appear in the source.
546 Closure(ImplSourceClosureData<'tcx, N>),
548 /// Same as above, but for a function pointer type with the given signature.
549 FnPointer(ImplSourceFnPointerData<'tcx, N>),
551 /// ImplSource for a builtin `DeterminantKind` trait implementation.
552 DiscriminantKind(ImplSourceDiscriminantKindData),
554 /// ImplSource for a builtin `Pointee` trait implementation.
555 Pointee(ImplSourcePointeeData),
557 /// ImplSource automatically generated for a generator.
558 Generator(ImplSourceGeneratorData<'tcx, N>),
560 /// ImplSource for a trait alias.
561 TraitAlias(ImplSourceTraitAliasData<'tcx, N>),
563 /// ImplSource for a `const Drop` implementation.
564 ConstDrop(ImplSourceConstDropData),
567 impl<'tcx, N> ImplSource<'tcx, N> {
568 pub fn nested_obligations(self) -> Vec<N> {
570 ImplSource::UserDefined(i) => i.nested,
571 ImplSource::Param(n, _) => n,
572 ImplSource::Builtin(i) => i.nested,
573 ImplSource::AutoImpl(d) => d.nested,
574 ImplSource::Closure(c) => c.nested,
575 ImplSource::Generator(c) => c.nested,
576 ImplSource::Object(d) => d.nested,
577 ImplSource::FnPointer(d) => d.nested,
578 ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData)
579 | ImplSource::Pointee(ImplSourcePointeeData)
580 | ImplSource::ConstDrop(ImplSourceConstDropData) => Vec::new(),
581 ImplSource::TraitAlias(d) => d.nested,
582 ImplSource::TraitUpcasting(d) => d.nested,
586 pub fn borrow_nested_obligations(&self) -> &[N] {
588 ImplSource::UserDefined(i) => &i.nested[..],
589 ImplSource::Param(n, _) => &n[..],
590 ImplSource::Builtin(i) => &i.nested[..],
591 ImplSource::AutoImpl(d) => &d.nested[..],
592 ImplSource::Closure(c) => &c.nested[..],
593 ImplSource::Generator(c) => &c.nested[..],
594 ImplSource::Object(d) => &d.nested[..],
595 ImplSource::FnPointer(d) => &d.nested[..],
596 ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData)
597 | ImplSource::Pointee(ImplSourcePointeeData)
598 | ImplSource::ConstDrop(ImplSourceConstDropData) => &[],
599 ImplSource::TraitAlias(d) => &d.nested[..],
600 ImplSource::TraitUpcasting(d) => &d.nested[..],
604 pub fn map<M, F>(self, f: F) -> ImplSource<'tcx, M>
609 ImplSource::UserDefined(i) => ImplSource::UserDefined(ImplSourceUserDefinedData {
610 impl_def_id: i.impl_def_id,
612 nested: i.nested.into_iter().map(f).collect(),
614 ImplSource::Param(n, ct) => ImplSource::Param(n.into_iter().map(f).collect(), ct),
615 ImplSource::Builtin(i) => ImplSource::Builtin(ImplSourceBuiltinData {
616 nested: i.nested.into_iter().map(f).collect(),
618 ImplSource::Object(o) => ImplSource::Object(ImplSourceObjectData {
619 upcast_trait_ref: o.upcast_trait_ref,
620 vtable_base: o.vtable_base,
621 nested: o.nested.into_iter().map(f).collect(),
623 ImplSource::AutoImpl(d) => ImplSource::AutoImpl(ImplSourceAutoImplData {
624 trait_def_id: d.trait_def_id,
625 nested: d.nested.into_iter().map(f).collect(),
627 ImplSource::Closure(c) => ImplSource::Closure(ImplSourceClosureData {
628 closure_def_id: c.closure_def_id,
630 nested: c.nested.into_iter().map(f).collect(),
632 ImplSource::Generator(c) => ImplSource::Generator(ImplSourceGeneratorData {
633 generator_def_id: c.generator_def_id,
635 nested: c.nested.into_iter().map(f).collect(),
637 ImplSource::FnPointer(p) => ImplSource::FnPointer(ImplSourceFnPointerData {
639 nested: p.nested.into_iter().map(f).collect(),
641 ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData) => {
642 ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData)
644 ImplSource::Pointee(ImplSourcePointeeData) => {
645 ImplSource::Pointee(ImplSourcePointeeData)
647 ImplSource::TraitAlias(d) => ImplSource::TraitAlias(ImplSourceTraitAliasData {
648 alias_def_id: d.alias_def_id,
650 nested: d.nested.into_iter().map(f).collect(),
652 ImplSource::TraitUpcasting(d) => {
653 ImplSource::TraitUpcasting(ImplSourceTraitUpcastingData {
654 upcast_trait_ref: d.upcast_trait_ref,
655 vtable_vptr_slot: d.vtable_vptr_slot,
656 nested: d.nested.into_iter().map(f).collect(),
659 ImplSource::ConstDrop(ImplSourceConstDropData) => {
660 ImplSource::ConstDrop(ImplSourceConstDropData)
666 /// Identifies a particular impl in the source, along with a set of
667 /// substitutions from the impl's type/lifetime parameters. The
668 /// `nested` vector corresponds to the nested obligations attached to
669 /// the impl's type parameters.
671 /// The type parameter `N` indicates the type used for "nested
672 /// obligations" that are required by the impl. During type-check, this
673 /// is `Obligation`, as one might expect. During codegen, however, this
674 /// is `()`, because codegen only requires a shallow resolution of an
675 /// impl, and nested obligations are satisfied later.
676 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
677 pub struct ImplSourceUserDefinedData<'tcx, N> {
678 pub impl_def_id: DefId,
679 pub substs: SubstsRef<'tcx>,
683 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
684 pub struct ImplSourceGeneratorData<'tcx, N> {
685 pub generator_def_id: DefId,
686 pub substs: SubstsRef<'tcx>,
687 /// Nested obligations. This can be non-empty if the generator
688 /// signature contains associated types.
692 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
693 pub struct ImplSourceClosureData<'tcx, N> {
694 pub closure_def_id: DefId,
695 pub substs: SubstsRef<'tcx>,
696 /// Nested obligations. This can be non-empty if the closure
697 /// signature contains associated types.
701 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
702 pub struct ImplSourceAutoImplData<N> {
703 pub trait_def_id: DefId,
707 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
708 pub struct ImplSourceTraitUpcastingData<'tcx, N> {
709 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
710 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
712 /// The vtable is formed by concatenating together the method lists of
713 /// the base object trait and all supertraits, pointers to supertrait vtable will
714 /// be provided when necessary; this is the position of `upcast_trait_ref`'s vtable
715 /// within that vtable.
716 pub vtable_vptr_slot: Option<usize>,
721 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
722 pub struct ImplSourceBuiltinData<N> {
726 #[derive(PartialEq, Eq, Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
727 pub struct ImplSourceObjectData<'tcx, N> {
728 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
729 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
731 /// The vtable is formed by concatenating together the method lists of
732 /// the base object trait and all supertraits, pointers to supertrait vtable will
733 /// be provided when necessary; this is the start of `upcast_trait_ref`'s methods
735 pub vtable_base: usize,
740 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
741 pub struct ImplSourceFnPointerData<'tcx, N> {
746 // FIXME(@lcnr): This should be refactored and merged with other builtin vtables.
747 #[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
748 pub struct ImplSourceDiscriminantKindData;
750 #[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
751 pub struct ImplSourcePointeeData;
753 #[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
754 pub struct ImplSourceConstDropData;
756 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
757 pub struct ImplSourceTraitAliasData<'tcx, N> {
758 pub alias_def_id: DefId,
759 pub substs: SubstsRef<'tcx>,
763 #[derive(Clone, Debug, PartialEq, Eq, Hash, HashStable, PartialOrd, Ord)]
764 pub enum ObjectSafetyViolation {
765 /// `Self: Sized` declared on the trait.
766 SizedSelf(SmallVec<[Span; 1]>),
768 /// Supertrait reference references `Self` an in illegal location
769 /// (e.g., `trait Foo : Bar<Self>`).
770 SupertraitSelf(SmallVec<[Span; 1]>),
772 /// Method has something illegal.
773 Method(Symbol, MethodViolationCode, Span),
775 /// Associated const.
776 AssocConst(Symbol, Span),
782 impl ObjectSafetyViolation {
783 pub fn error_msg(&self) -> Cow<'static, str> {
785 ObjectSafetyViolation::SizedSelf(_) => "it requires `Self: Sized`".into(),
786 ObjectSafetyViolation::SupertraitSelf(ref spans) => {
787 if spans.iter().any(|sp| *sp != DUMMY_SP) {
788 "it uses `Self` as a type parameter".into()
790 "it cannot use `Self` as a type parameter in a supertrait or `where`-clause"
794 ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod(_, _, _), _) => {
795 format!("associated function `{}` has no `self` parameter", name).into()
797 ObjectSafetyViolation::Method(
799 MethodViolationCode::ReferencesSelfInput(_),
801 ) => format!("method `{}` references the `Self` type in its parameters", name).into(),
802 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfInput(_), _) => {
803 format!("method `{}` references the `Self` type in this parameter", name).into()
805 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfOutput, _) => {
806 format!("method `{}` references the `Self` type in its return type", name).into()
808 ObjectSafetyViolation::Method(
810 MethodViolationCode::WhereClauseReferencesSelf,
813 format!("method `{}` references the `Self` type in its `where` clause", name).into()
815 ObjectSafetyViolation::Method(name, MethodViolationCode::Generic, _) => {
816 format!("method `{}` has generic type parameters", name).into()
818 ObjectSafetyViolation::Method(name, MethodViolationCode::UndispatchableReceiver, _) => {
819 format!("method `{}`'s `self` parameter cannot be dispatched on", name).into()
821 ObjectSafetyViolation::AssocConst(name, DUMMY_SP) => {
822 format!("it contains associated `const` `{}`", name).into()
824 ObjectSafetyViolation::AssocConst(..) => "it contains this associated `const`".into(),
825 ObjectSafetyViolation::GAT(name, _) => {
826 format!("it contains the generic associated type `{}`", name).into()
831 pub fn solution(&self, err: &mut DiagnosticBuilder<'_>) {
833 ObjectSafetyViolation::SizedSelf(_) | ObjectSafetyViolation::SupertraitSelf(_) => {}
834 ObjectSafetyViolation::Method(
836 MethodViolationCode::StaticMethod(sugg, self_span, has_args),
842 "consider turning `{}` into a method by giving it a `&self` argument",
845 format!("&self{}", if has_args { ", " } else { "" }),
846 Applicability::MaybeIncorrect,
849 Some((sugg, span)) => {
853 "alternatively, consider constraining `{}` so it does not apply to \
858 Applicability::MaybeIncorrect,
863 "consider turning `{}` into a method by giving it a `&self` \
864 argument or constraining it so it does not apply to trait objects",
870 ObjectSafetyViolation::Method(
872 MethodViolationCode::UndispatchableReceiver,
878 "consider changing method `{}`'s `self` parameter to be `&self`",
882 Applicability::MachineApplicable,
885 ObjectSafetyViolation::AssocConst(name, _)
886 | ObjectSafetyViolation::GAT(name, _)
887 | ObjectSafetyViolation::Method(name, ..) => {
888 err.help(&format!("consider moving `{}` to another trait", name));
893 pub fn spans(&self) -> SmallVec<[Span; 1]> {
894 // When `span` comes from a separate crate, it'll be `DUMMY_SP`. Treat it as `None` so
895 // diagnostics use a `note` instead of a `span_label`.
897 ObjectSafetyViolation::SupertraitSelf(spans)
898 | ObjectSafetyViolation::SizedSelf(spans) => spans.clone(),
899 ObjectSafetyViolation::AssocConst(_, span)
900 | ObjectSafetyViolation::GAT(_, span)
901 | ObjectSafetyViolation::Method(_, _, span)
902 if *span != DUMMY_SP =>
911 /// Reasons a method might not be object-safe.
912 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable, PartialOrd, Ord)]
913 pub enum MethodViolationCode {
915 StaticMethod(Option<(&'static str, Span)>, Span, bool /* has args */),
917 /// e.g., `fn foo(&self, x: Self)`
918 ReferencesSelfInput(usize),
920 /// e.g., `fn foo(&self) -> Self`
921 ReferencesSelfOutput,
923 /// e.g., `fn foo(&self) where Self: Clone`
924 WhereClauseReferencesSelf,
926 /// e.g., `fn foo<A>()`
929 /// the method's receiver (`self` argument) can't be dispatched on
930 UndispatchableReceiver,