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, DiagnosticBuilder};
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;
27 use std::hash::{Hash, Hasher};
30 pub use self::select::{EvaluationCache, EvaluationResult, OverflowError, SelectionCache};
32 pub type CanonicalChalkEnvironmentAndGoal<'tcx> = Canonical<'tcx, ChalkEnvironmentAndGoal<'tcx>>;
34 pub use self::ObligationCauseCode::*;
36 pub use self::chalk::{ChalkEnvironmentAndGoal, RustInterner as ChalkRustInterner};
38 /// Depending on the stage of compilation, we want projection to be
39 /// more or less conservative.
40 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, HashStable)]
42 /// At type-checking time, we refuse to project any associated
43 /// type that is marked `default`. Non-`default` ("final") types
44 /// are always projected. This is necessary in general for
45 /// soundness of specialization. However, we *could* allow
46 /// projections in fully-monomorphic cases. We choose not to,
47 /// because we prefer for `default type` to force the type
48 /// definition to be treated abstractly by any consumers of the
49 /// impl. Concretely, that means that the following example will
57 /// impl<T> Assoc for T {
58 /// default type Output = bool;
62 /// let <() as Assoc>::Output = true;
67 /// At codegen time, all monomorphic projections will succeed.
68 /// Also, `impl Trait` is normalized to the concrete type,
69 /// which has to be already collected by type-checking.
71 /// NOTE: as `impl Trait`'s concrete type should *never*
72 /// be observable directly by the user, `Reveal::All`
73 /// should not be used by checks which may expose
74 /// type equality or type contents to the user.
75 /// There are some exceptions, e.g., around auto traits and
76 /// transmute-checking, which expose some details, but
77 /// not the whole concrete type of the `impl Trait`.
81 /// The reason why we incurred this obligation; used for error reporting.
83 /// As the happy path does not care about this struct, storing this on the heap
84 /// ends up increasing performance.
86 /// We do not want to intern this as there are a lot of obligation causes which
87 /// only live for a short period of time.
88 #[derive(Clone, PartialEq, Eq, Hash, Lift)]
89 pub struct ObligationCause<'tcx> {
90 /// `None` for `ObligationCause::dummy`, `Some` otherwise.
91 data: Option<Lrc<ObligationCauseData<'tcx>>>,
94 const DUMMY_OBLIGATION_CAUSE_DATA: ObligationCauseData<'static> =
95 ObligationCauseData { span: DUMMY_SP, body_id: hir::CRATE_HIR_ID, code: MiscObligation };
97 // Correctly format `ObligationCause::dummy`.
98 impl<'tcx> fmt::Debug for ObligationCause<'tcx> {
99 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100 ObligationCauseData::fmt(self, f)
104 impl<'tcx> Deref for ObligationCause<'tcx> {
105 type Target = ObligationCauseData<'tcx>;
108 fn deref(&self) -> &Self::Target {
109 self.data.as_deref().unwrap_or(&DUMMY_OBLIGATION_CAUSE_DATA)
113 #[derive(Clone, Debug, PartialEq, Eq, Lift)]
114 pub struct ObligationCauseData<'tcx> {
117 /// The ID of the fn body that triggered this obligation. This is
118 /// used for region obligations to determine the precise
119 /// environment in which the region obligation should be evaluated
120 /// (in particular, closures can add new assumptions). See the
121 /// field `region_obligations` of the `FulfillmentContext` for more
123 pub body_id: hir::HirId,
125 pub code: ObligationCauseCode<'tcx>,
128 impl Hash for ObligationCauseData<'_> {
129 fn hash<H: Hasher>(&self, state: &mut H) {
130 self.body_id.hash(state);
131 self.span.hash(state);
132 std::mem::discriminant(&self.code).hash(state);
136 impl<'tcx> ObligationCause<'tcx> {
141 code: ObligationCauseCode<'tcx>,
142 ) -> ObligationCause<'tcx> {
143 ObligationCause { data: Some(Lrc::new(ObligationCauseData { span, body_id, code })) }
146 pub fn misc(span: Span, body_id: hir::HirId) -> ObligationCause<'tcx> {
147 ObligationCause::new(span, body_id, MiscObligation)
150 pub fn dummy_with_span(span: Span) -> ObligationCause<'tcx> {
151 ObligationCause::new(span, hir::CRATE_HIR_ID, MiscObligation)
155 pub fn dummy() -> ObligationCause<'tcx> {
156 ObligationCause { data: None }
159 pub fn make_mut(&mut self) -> &mut ObligationCauseData<'tcx> {
160 Lrc::make_mut(self.data.get_or_insert_with(|| Lrc::new(DUMMY_OBLIGATION_CAUSE_DATA)))
163 pub fn span(&self, tcx: TyCtxt<'tcx>) -> Span {
165 ObligationCauseCode::CompareImplMethodObligation { .. }
166 | ObligationCauseCode::MainFunctionType
167 | ObligationCauseCode::StartFunctionType => {
168 tcx.sess.source_map().guess_head_span(self.span)
170 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
179 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
180 pub struct UnifyReceiverContext<'tcx> {
181 pub assoc_item: ty::AssocItem,
182 pub param_env: ty::ParamEnv<'tcx>,
183 pub substs: SubstsRef<'tcx>,
186 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
187 pub enum ObligationCauseCode<'tcx> {
188 /// Not well classified or should be obvious from the span.
191 /// A slice or array is WF only if `T: Sized`.
194 /// A tuple is WF only if its middle elements are `Sized`.
197 /// This is the trait reference from the given projection.
198 ProjectionWf(ty::ProjectionTy<'tcx>),
200 /// In an impl of trait `X` for type `Y`, type `Y` must
201 /// also implement all supertraits of `X`.
202 ItemObligation(DefId),
204 /// Like `ItemObligation`, but with extra detail on the source of the obligation.
205 BindingObligation(DefId, Span),
207 /// A type like `&'a T` is WF only if `T: 'a`.
208 ReferenceOutlivesReferent(Ty<'tcx>),
210 /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
211 ObjectTypeBound(Ty<'tcx>, ty::Region<'tcx>),
213 /// Obligation incurred due to an object cast.
214 ObjectCastObligation(/* Object type */ Ty<'tcx>),
216 /// Obligation incurred due to a coercion.
222 /// Various cases where expressions must be `Sized` / `Copy` / etc.
223 /// `L = X` implies that `L` is `Sized`.
225 /// `(x1, .., xn)` must be `Sized`.
226 TupleInitializerSized,
227 /// `S { ... }` must be `Sized`.
228 StructInitializerSized,
229 /// Type of each variable must be `Sized`.
230 VariableType(hir::HirId),
231 /// Argument type must be `Sized`.
232 SizedArgumentType(Option<Span>),
233 /// Return type must be `Sized`.
235 /// Yield type must be `Sized`.
237 /// Box expression result type must be `Sized`.
239 /// Inline asm operand type must be `Sized`.
241 /// `[T, ..n]` implies that `T` must be `Copy`.
242 /// If the function in the array repeat expression is a `const fn`,
243 /// display a help message suggesting to move the function call to a
244 /// new `const` item while saying that `T` doesn't implement `Copy`.
247 /// Types of fields (other than the last, except for packed structs) in a struct must be sized.
254 /// Constant expressions must be sized.
257 /// `static` items must have `Sync` type.
260 BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
262 ImplDerivedObligation(DerivedObligationCause<'tcx>),
264 DerivedObligation(DerivedObligationCause<'tcx>),
266 FunctionArgumentObligation {
267 /// The node of the relevant argument in the function call.
268 arg_hir_id: hir::HirId,
269 /// The node of the function call.
270 call_hir_id: hir::HirId,
271 /// The obligation introduced by this argument.
272 parent_code: Lrc<ObligationCauseCode<'tcx>>,
275 /// Error derived when matching traits/impls; see ObligationCause for more details
276 CompareImplConstObligation,
278 /// Error derived when matching traits/impls; see ObligationCause for more details
279 CompareImplMethodObligation {
280 impl_item_def_id: DefId,
281 trait_item_def_id: DefId,
284 /// Error derived when matching traits/impls; see ObligationCause for more details
285 CompareImplTypeObligation {
286 impl_item_def_id: DefId,
287 trait_item_def_id: DefId,
290 /// Checking that this expression can be assigned where it needs to be
291 // FIXME(eddyb) #11161 is the original Expr required?
294 /// Computing common supertype in the arms of a match expression
295 MatchExpressionArm(Box<MatchExpressionArmCause<'tcx>>),
297 /// Type error arising from type checking a pattern against an expected type.
299 /// The span of the scrutinee or type expression which caused the `root_ty` type.
301 /// The root expected type induced by a scrutinee or type expression.
303 /// Whether the `Span` came from an expression or a type expression.
307 /// Constants in patterns must have `Structural` type.
308 ConstPatternStructural,
310 /// Computing common supertype in an if expression
311 IfExpression(Box<IfExpressionCause>),
313 /// Computing common supertype of an if expression with no else counter-part
314 IfExpressionWithNoElse,
316 /// `main` has wrong type
319 /// `start` has wrong type
322 /// Intrinsic has wrong type
325 /// A let else block does not diverge
331 UnifyReceiver(Box<UnifyReceiverContext<'tcx>>),
333 /// `return` with no expression
336 /// `return` with an expression
337 ReturnValue(hir::HirId),
339 /// Return type of this function
342 /// Block implicit return
343 BlockTailExpression(hir::HirId),
345 /// #[feature(trivial_bounds)] is not enabled
348 /// If `X` is the concrete type of an opaque type `impl Y`, then `X` must implement `Y`
351 AwaitableExpr(Option<hir::HirId>),
357 /// Well-formed checking. If a `WellFormedLoc` is provided,
358 /// then it will be used to eprform HIR-based wf checking
359 /// after an error occurs, in order to generate a more precise error span.
360 /// This is purely for diagnostic purposes - it is always
361 /// correct to use `MiscObligation` instead, or to specify
362 /// `WellFormed(None)`
363 WellFormed(Option<WellFormedLoc>),
365 /// From `match_impl`. The cause for us having to match an impl, and the DefId we are matching against.
366 MatchImpl(ObligationCause<'tcx>, DefId),
369 /// The 'location' at which we try to perform HIR-based wf checking.
370 /// This information is used to obtain an `hir::Ty`, which
371 /// we can walk in order to obtain precise spans for any
372 /// 'nested' types (e.g. `Foo` in `Option<Foo>`).
373 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
374 pub enum WellFormedLoc {
375 /// Use the type of the provided definition.
377 /// Use the type of the parameter of the provided function.
378 /// We cannot use `hir::Param`, since the function may
379 /// not have a body (e.g. a trait method definition)
381 /// The function to lookup the parameter in
382 function: LocalDefId,
383 /// The index of the parameter to use.
384 /// Parameters are indexed from 0, with the return type
385 /// being the last 'parameter'
390 impl ObligationCauseCode<'_> {
391 // Return the base obligation, ignoring derived obligations.
392 pub fn peel_derives(&self) -> &Self {
393 let mut base_cause = self;
394 while let BuiltinDerivedObligation(DerivedObligationCause { parent_code, .. })
395 | ImplDerivedObligation(DerivedObligationCause { parent_code, .. })
396 | DerivedObligation(DerivedObligationCause { parent_code, .. })
397 | FunctionArgumentObligation { parent_code, .. } = base_cause
399 base_cause = &parent_code;
405 // `ObligationCauseCode` is used a lot. Make sure it doesn't unintentionally get bigger.
406 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
407 static_assert_size!(ObligationCauseCode<'_>, 40);
409 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
410 pub enum StatementAsExpression {
415 impl<'tcx> ty::Lift<'tcx> for StatementAsExpression {
416 type Lifted = StatementAsExpression;
417 fn lift_to_tcx(self, _tcx: TyCtxt<'tcx>) -> Option<StatementAsExpression> {
422 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
423 pub struct MatchExpressionArmCause<'tcx> {
425 pub scrut_span: Span,
426 pub semi_span: Option<(Span, StatementAsExpression)>,
427 pub source: hir::MatchSource,
428 pub prior_arms: Vec<Span>,
429 pub last_ty: Ty<'tcx>,
430 pub scrut_hir_id: hir::HirId,
431 pub opt_suggest_box_span: Option<Span>,
434 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
435 pub struct IfExpressionCause {
438 pub outer: Option<Span>,
439 pub semicolon: Option<(Span, StatementAsExpression)>,
440 pub opt_suggest_box_span: Option<Span>,
443 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
444 pub struct DerivedObligationCause<'tcx> {
445 /// The trait reference of the parent obligation that led to the
446 /// current obligation. Note that only trait obligations lead to
447 /// derived obligations, so we just store the trait reference here
449 pub parent_trait_ref: ty::PolyTraitRef<'tcx>,
451 /// The parent trait had this cause.
452 pub parent_code: Lrc<ObligationCauseCode<'tcx>>,
455 #[derive(Clone, Debug, TypeFoldable, Lift)]
456 pub enum SelectionError<'tcx> {
457 /// The trait is not implemented.
459 /// After a closure impl has selected, its "outputs" were evaluated
460 /// (which for closures includes the "input" type params) and they
461 /// didn't resolve. See `confirm_poly_trait_refs` for more.
462 OutputTypeParameterMismatch(
463 ty::PolyTraitRef<'tcx>,
464 ty::PolyTraitRef<'tcx>,
465 ty::error::TypeError<'tcx>,
467 /// The trait pointed by `DefId` is not object safe.
468 TraitNotObjectSafe(DefId),
469 /// A given constant couldn't be evaluated.
470 NotConstEvaluatable(NotConstEvaluatable),
471 /// Exceeded the recursion depth during type projection.
473 /// Signaling that an error has already been emitted, to avoid
474 /// multiple errors being shown.
476 /// Multiple applicable `impl`s where found. The `DefId`s correspond to
477 /// all the `impl`s' Items.
478 Ambiguous(Vec<DefId>),
481 /// When performing resolution, it is typically the case that there
482 /// can be one of three outcomes:
484 /// - `Ok(Some(r))`: success occurred with result `r`
485 /// - `Ok(None)`: could not definitely determine anything, usually due
486 /// to inconclusive type inference.
487 /// - `Err(e)`: error `e` occurred
488 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
490 /// Given the successful resolution of an obligation, the `ImplSource`
491 /// indicates where the impl comes from.
493 /// For example, the obligation may be satisfied by a specific impl (case A),
494 /// or it may be relative to some bound that is in scope (case B).
497 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
498 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
499 /// impl Clone for i32 { ... } // Impl_3
501 /// fn foo<T: Clone>(concrete: Option<Box<i32>>, param: T, mixed: Option<T>) {
502 /// // Case A: ImplSource points at a specific impl. Only possible when
503 /// // type is concretely known. If the impl itself has bounded
504 /// // type parameters, ImplSource will carry resolutions for those as well:
505 /// concrete.clone(); // ImpleSource(Impl_1, [ImplSource(Impl_2, [ImplSource(Impl_3)])])
507 /// // Case A: ImplSource points at a specific impl. Only possible when
508 /// // type is concretely known. If the impl itself has bounded
509 /// // type parameters, ImplSource will carry resolutions for those as well:
510 /// concrete.clone(); // ImplSource(Impl_1, [ImplSource(Impl_2, [ImplSource(Impl_3)])])
512 /// // Case B: ImplSource must be provided by caller. This applies when
513 /// // type is a type parameter.
514 /// param.clone(); // ImplSource::Param
516 /// // Case C: A mix of cases A and B.
517 /// mixed.clone(); // ImplSource(Impl_1, [ImplSource::Param])
521 /// ### The type parameter `N`
523 /// See explanation on `ImplSourceUserDefinedData`.
524 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
525 pub enum ImplSource<'tcx, N> {
526 /// ImplSource identifying a particular impl.
527 UserDefined(ImplSourceUserDefinedData<'tcx, N>),
529 /// ImplSource for auto trait implementations.
530 /// This carries the information and nested obligations with regards
531 /// to an auto implementation for a trait `Trait`. The nested obligations
532 /// ensure the trait implementation holds for all the constituent types.
533 AutoImpl(ImplSourceAutoImplData<N>),
535 /// Successful resolution to an obligation provided by the caller
536 /// for some type parameter. The `Vec<N>` represents the
537 /// obligations incurred from normalizing the where-clause (if
539 Param(Vec<N>, ty::BoundConstness),
541 /// Virtual calls through an object.
542 Object(ImplSourceObjectData<'tcx, N>),
544 /// Successful resolution for a builtin trait.
545 Builtin(ImplSourceBuiltinData<N>),
547 /// ImplSource for trait upcasting coercion
548 TraitUpcasting(ImplSourceTraitUpcastingData<'tcx, N>),
550 /// ImplSource automatically generated for a closure. The `DefId` is the ID
551 /// of the closure expression. This is an `ImplSource::UserDefined` in spirit, but the
552 /// impl is generated by the compiler and does not appear in the source.
553 Closure(ImplSourceClosureData<'tcx, N>),
555 /// Same as above, but for a function pointer type with the given signature.
556 FnPointer(ImplSourceFnPointerData<'tcx, N>),
558 /// ImplSource for a builtin `DeterminantKind` trait implementation.
559 DiscriminantKind(ImplSourceDiscriminantKindData),
561 /// ImplSource for a builtin `Pointee` trait implementation.
562 Pointee(ImplSourcePointeeData),
564 /// ImplSource automatically generated for a generator.
565 Generator(ImplSourceGeneratorData<'tcx, N>),
567 /// ImplSource for a trait alias.
568 TraitAlias(ImplSourceTraitAliasData<'tcx, N>),
570 /// ImplSource for a `const Drop` implementation.
571 ConstDrop(ImplSourceConstDropData),
574 impl<'tcx, N> ImplSource<'tcx, N> {
575 pub fn nested_obligations(self) -> Vec<N> {
577 ImplSource::UserDefined(i) => i.nested,
578 ImplSource::Param(n, _) => n,
579 ImplSource::Builtin(i) => i.nested,
580 ImplSource::AutoImpl(d) => d.nested,
581 ImplSource::Closure(c) => c.nested,
582 ImplSource::Generator(c) => c.nested,
583 ImplSource::Object(d) => d.nested,
584 ImplSource::FnPointer(d) => d.nested,
585 ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData)
586 | ImplSource::Pointee(ImplSourcePointeeData)
587 | ImplSource::ConstDrop(ImplSourceConstDropData) => Vec::new(),
588 ImplSource::TraitAlias(d) => d.nested,
589 ImplSource::TraitUpcasting(d) => d.nested,
593 pub fn borrow_nested_obligations(&self) -> &[N] {
595 ImplSource::UserDefined(i) => &i.nested[..],
596 ImplSource::Param(n, _) => &n,
597 ImplSource::Builtin(i) => &i.nested,
598 ImplSource::AutoImpl(d) => &d.nested,
599 ImplSource::Closure(c) => &c.nested,
600 ImplSource::Generator(c) => &c.nested,
601 ImplSource::Object(d) => &d.nested,
602 ImplSource::FnPointer(d) => &d.nested,
603 ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData)
604 | ImplSource::Pointee(ImplSourcePointeeData)
605 | ImplSource::ConstDrop(ImplSourceConstDropData) => &[],
606 ImplSource::TraitAlias(d) => &d.nested,
607 ImplSource::TraitUpcasting(d) => &d.nested,
611 pub fn map<M, F>(self, f: F) -> ImplSource<'tcx, M>
616 ImplSource::UserDefined(i) => ImplSource::UserDefined(ImplSourceUserDefinedData {
617 impl_def_id: i.impl_def_id,
619 nested: i.nested.into_iter().map(f).collect(),
621 ImplSource::Param(n, ct) => ImplSource::Param(n.into_iter().map(f).collect(), ct),
622 ImplSource::Builtin(i) => ImplSource::Builtin(ImplSourceBuiltinData {
623 nested: i.nested.into_iter().map(f).collect(),
625 ImplSource::Object(o) => ImplSource::Object(ImplSourceObjectData {
626 upcast_trait_ref: o.upcast_trait_ref,
627 vtable_base: o.vtable_base,
628 nested: o.nested.into_iter().map(f).collect(),
630 ImplSource::AutoImpl(d) => ImplSource::AutoImpl(ImplSourceAutoImplData {
631 trait_def_id: d.trait_def_id,
632 nested: d.nested.into_iter().map(f).collect(),
634 ImplSource::Closure(c) => ImplSource::Closure(ImplSourceClosureData {
635 closure_def_id: c.closure_def_id,
637 nested: c.nested.into_iter().map(f).collect(),
639 ImplSource::Generator(c) => ImplSource::Generator(ImplSourceGeneratorData {
640 generator_def_id: c.generator_def_id,
642 nested: c.nested.into_iter().map(f).collect(),
644 ImplSource::FnPointer(p) => ImplSource::FnPointer(ImplSourceFnPointerData {
646 nested: p.nested.into_iter().map(f).collect(),
648 ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData) => {
649 ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData)
651 ImplSource::Pointee(ImplSourcePointeeData) => {
652 ImplSource::Pointee(ImplSourcePointeeData)
654 ImplSource::TraitAlias(d) => ImplSource::TraitAlias(ImplSourceTraitAliasData {
655 alias_def_id: d.alias_def_id,
657 nested: d.nested.into_iter().map(f).collect(),
659 ImplSource::TraitUpcasting(d) => {
660 ImplSource::TraitUpcasting(ImplSourceTraitUpcastingData {
661 upcast_trait_ref: d.upcast_trait_ref,
662 vtable_vptr_slot: d.vtable_vptr_slot,
663 nested: d.nested.into_iter().map(f).collect(),
666 ImplSource::ConstDrop(ImplSourceConstDropData) => {
667 ImplSource::ConstDrop(ImplSourceConstDropData)
673 /// Identifies a particular impl in the source, along with a set of
674 /// substitutions from the impl's type/lifetime parameters. The
675 /// `nested` vector corresponds to the nested obligations attached to
676 /// the impl's type parameters.
678 /// The type parameter `N` indicates the type used for "nested
679 /// obligations" that are required by the impl. During type-check, this
680 /// is `Obligation`, as one might expect. During codegen, however, this
681 /// is `()`, because codegen only requires a shallow resolution of an
682 /// impl, and nested obligations are satisfied later.
683 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
684 pub struct ImplSourceUserDefinedData<'tcx, N> {
685 pub impl_def_id: DefId,
686 pub substs: SubstsRef<'tcx>,
690 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
691 pub struct ImplSourceGeneratorData<'tcx, N> {
692 pub generator_def_id: DefId,
693 pub substs: SubstsRef<'tcx>,
694 /// Nested obligations. This can be non-empty if the generator
695 /// signature contains associated types.
699 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
700 pub struct ImplSourceClosureData<'tcx, N> {
701 pub closure_def_id: DefId,
702 pub substs: SubstsRef<'tcx>,
703 /// Nested obligations. This can be non-empty if the closure
704 /// signature contains associated types.
708 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
709 pub struct ImplSourceAutoImplData<N> {
710 pub trait_def_id: DefId,
714 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
715 pub struct ImplSourceTraitUpcastingData<'tcx, N> {
716 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
717 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
719 /// The vtable is formed by concatenating together the method lists of
720 /// the base object trait and all supertraits, pointers to supertrait vtable will
721 /// be provided when necessary; this is the position of `upcast_trait_ref`'s vtable
722 /// within that vtable.
723 pub vtable_vptr_slot: Option<usize>,
728 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
729 pub struct ImplSourceBuiltinData<N> {
733 #[derive(PartialEq, Eq, Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
734 pub struct ImplSourceObjectData<'tcx, N> {
735 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
736 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
738 /// The vtable is formed by concatenating together the method lists of
739 /// the base object trait and all supertraits, pointers to supertrait vtable will
740 /// be provided when necessary; this is the start of `upcast_trait_ref`'s methods
742 pub vtable_base: usize,
747 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
748 pub struct ImplSourceFnPointerData<'tcx, N> {
753 // FIXME(@lcnr): This should be refactored and merged with other builtin vtables.
754 #[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
755 pub struct ImplSourceDiscriminantKindData;
757 #[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
758 pub struct ImplSourcePointeeData;
760 #[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
761 pub struct ImplSourceConstDropData;
763 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
764 pub struct ImplSourceTraitAliasData<'tcx, N> {
765 pub alias_def_id: DefId,
766 pub substs: SubstsRef<'tcx>,
770 #[derive(Clone, Debug, PartialEq, Eq, Hash, HashStable, PartialOrd, Ord)]
771 pub enum ObjectSafetyViolation {
772 /// `Self: Sized` declared on the trait.
773 SizedSelf(SmallVec<[Span; 1]>),
775 /// Supertrait reference references `Self` an in illegal location
776 /// (e.g., `trait Foo : Bar<Self>`).
777 SupertraitSelf(SmallVec<[Span; 1]>),
779 /// Method has something illegal.
780 Method(Symbol, MethodViolationCode, Span),
782 /// Associated const.
783 AssocConst(Symbol, Span),
789 impl ObjectSafetyViolation {
790 pub fn error_msg(&self) -> Cow<'static, str> {
792 ObjectSafetyViolation::SizedSelf(_) => "it requires `Self: Sized`".into(),
793 ObjectSafetyViolation::SupertraitSelf(ref spans) => {
794 if spans.iter().any(|sp| *sp != DUMMY_SP) {
795 "it uses `Self` as a type parameter".into()
797 "it cannot use `Self` as a type parameter in a supertrait or `where`-clause"
801 ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod(_, _, _), _) => {
802 format!("associated function `{}` has no `self` parameter", name).into()
804 ObjectSafetyViolation::Method(
806 MethodViolationCode::ReferencesSelfInput(_),
808 ) => format!("method `{}` references the `Self` type in its parameters", name).into(),
809 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfInput(_), _) => {
810 format!("method `{}` references the `Self` type in this parameter", name).into()
812 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfOutput, _) => {
813 format!("method `{}` references the `Self` type in its return type", name).into()
815 ObjectSafetyViolation::Method(
817 MethodViolationCode::WhereClauseReferencesSelf,
820 format!("method `{}` references the `Self` type in its `where` clause", name).into()
822 ObjectSafetyViolation::Method(name, MethodViolationCode::Generic, _) => {
823 format!("method `{}` has generic type parameters", name).into()
825 ObjectSafetyViolation::Method(name, MethodViolationCode::UndispatchableReceiver, _) => {
826 format!("method `{}`'s `self` parameter cannot be dispatched on", name).into()
828 ObjectSafetyViolation::AssocConst(name, DUMMY_SP) => {
829 format!("it contains associated `const` `{}`", name).into()
831 ObjectSafetyViolation::AssocConst(..) => "it contains this associated `const`".into(),
832 ObjectSafetyViolation::GAT(name, _) => {
833 format!("it contains the generic associated type `{}`", name).into()
838 pub fn solution(&self, err: &mut DiagnosticBuilder<'_>) {
840 ObjectSafetyViolation::SizedSelf(_) | ObjectSafetyViolation::SupertraitSelf(_) => {}
841 ObjectSafetyViolation::Method(
843 MethodViolationCode::StaticMethod(sugg, self_span, has_args),
849 "consider turning `{}` into a method by giving it a `&self` argument",
852 format!("&self{}", if has_args { ", " } else { "" }),
853 Applicability::MaybeIncorrect,
856 Some((sugg, span)) => {
860 "alternatively, consider constraining `{}` so it does not apply to \
865 Applicability::MaybeIncorrect,
870 "consider turning `{}` into a method by giving it a `&self` \
871 argument or constraining it so it does not apply to trait objects",
877 ObjectSafetyViolation::Method(
879 MethodViolationCode::UndispatchableReceiver,
885 "consider changing method `{}`'s `self` parameter to be `&self`",
889 Applicability::MachineApplicable,
892 ObjectSafetyViolation::AssocConst(name, _)
893 | ObjectSafetyViolation::GAT(name, _)
894 | ObjectSafetyViolation::Method(name, ..) => {
895 err.help(&format!("consider moving `{}` to another trait", name));
900 pub fn spans(&self) -> SmallVec<[Span; 1]> {
901 // When `span` comes from a separate crate, it'll be `DUMMY_SP`. Treat it as `None` so
902 // diagnostics use a `note` instead of a `span_label`.
904 ObjectSafetyViolation::SupertraitSelf(spans)
905 | ObjectSafetyViolation::SizedSelf(spans) => spans.clone(),
906 ObjectSafetyViolation::AssocConst(_, span)
907 | ObjectSafetyViolation::GAT(_, span)
908 | ObjectSafetyViolation::Method(_, _, span)
909 if *span != DUMMY_SP =>
918 /// Reasons a method might not be object-safe.
919 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable, PartialOrd, Ord)]
920 pub enum MethodViolationCode {
922 StaticMethod(Option<(&'static str, Span)>, Span, bool /* has args */),
924 /// e.g., `fn foo(&self, x: Self)`
925 ReferencesSelfInput(usize),
927 /// e.g., `fn foo(&self) -> Self`
928 ReferencesSelfOutput,
930 /// e.g., `fn foo(&self) where Self: Clone`
931 WhereClauseReferencesSelf,
933 /// e.g., `fn foo<A>()`
936 /// the method's receiver (`self` argument) can't be dispatched on
937 UndispatchableReceiver,