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;
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 /// As the happy path does not care about this struct, storing this on the heap
82 /// ends up increasing performance.
84 /// We do not want to intern this as there are a lot of obligation causes which
85 /// only live for a short period of time.
86 #[derive(Clone, PartialEq, Eq, Hash, Lift)]
87 pub struct ObligationCause<'tcx> {
88 /// `None` for `ObligationCause::dummy`, `Some` otherwise.
89 data: Option<Lrc<ObligationCauseData<'tcx>>>,
92 const DUMMY_OBLIGATION_CAUSE_DATA: ObligationCauseData<'static> =
93 ObligationCauseData { span: DUMMY_SP, body_id: hir::CRATE_HIR_ID, code: MiscObligation };
95 // Correctly format `ObligationCause::dummy`.
96 impl<'tcx> fmt::Debug for ObligationCause<'tcx> {
97 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98 ObligationCauseData::fmt(self, f)
102 impl Deref for ObligationCause<'tcx> {
103 type Target = ObligationCauseData<'tcx>;
106 fn deref(&self) -> &Self::Target {
107 self.data.as_deref().unwrap_or(&DUMMY_OBLIGATION_CAUSE_DATA)
111 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
112 pub struct ObligationCauseData<'tcx> {
115 /// The ID of the fn body that triggered this obligation. This is
116 /// used for region obligations to determine the precise
117 /// environment in which the region obligation should be evaluated
118 /// (in particular, closures can add new assumptions). See the
119 /// field `region_obligations` of the `FulfillmentContext` for more
121 pub body_id: hir::HirId,
123 pub code: ObligationCauseCode<'tcx>,
126 impl<'tcx> ObligationCause<'tcx> {
131 code: ObligationCauseCode<'tcx>,
132 ) -> ObligationCause<'tcx> {
133 ObligationCause { data: Some(Lrc::new(ObligationCauseData { span, body_id, code })) }
136 pub fn misc(span: Span, body_id: hir::HirId) -> ObligationCause<'tcx> {
137 ObligationCause::new(span, body_id, MiscObligation)
140 pub fn dummy_with_span(span: Span) -> ObligationCause<'tcx> {
141 ObligationCause::new(span, hir::CRATE_HIR_ID, MiscObligation)
145 pub fn dummy() -> ObligationCause<'tcx> {
146 ObligationCause { data: None }
149 pub fn make_mut(&mut self) -> &mut ObligationCauseData<'tcx> {
150 Lrc::make_mut(self.data.get_or_insert_with(|| Lrc::new(DUMMY_OBLIGATION_CAUSE_DATA)))
153 pub fn span(&self, tcx: TyCtxt<'tcx>) -> Span {
155 ObligationCauseCode::CompareImplMethodObligation { .. }
156 | ObligationCauseCode::MainFunctionType
157 | ObligationCauseCode::StartFunctionType => {
158 tcx.sess.source_map().guess_head_span(self.span)
160 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
169 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
170 pub struct UnifyReceiverContext<'tcx> {
171 pub assoc_item: ty::AssocItem,
172 pub param_env: ty::ParamEnv<'tcx>,
173 pub substs: SubstsRef<'tcx>,
176 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
177 pub enum ObligationCauseCode<'tcx> {
178 /// Not well classified or should be obvious from the span.
181 /// A slice or array is WF only if `T: Sized`.
184 /// A tuple is WF only if its middle elements are `Sized`.
187 /// This is the trait reference from the given projection.
188 ProjectionWf(ty::ProjectionTy<'tcx>),
190 /// In an impl of trait `X` for type `Y`, type `Y` must
191 /// also implement all supertraits of `X`.
192 ItemObligation(DefId),
194 /// Like `ItemObligation`, but with extra detail on the source of the obligation.
195 BindingObligation(DefId, Span),
197 /// A type like `&'a T` is WF only if `T: 'a`.
198 ReferenceOutlivesReferent(Ty<'tcx>),
200 /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
201 ObjectTypeBound(Ty<'tcx>, ty::Region<'tcx>),
203 /// Obligation incurred due to an object cast.
204 ObjectCastObligation(/* Object type */ Ty<'tcx>),
206 /// Obligation incurred due to a coercion.
212 /// Various cases where expressions must be `Sized` / `Copy` / etc.
213 /// `L = X` implies that `L` is `Sized`.
215 /// `(x1, .., xn)` must be `Sized`.
216 TupleInitializerSized,
217 /// `S { ... }` must be `Sized`.
218 StructInitializerSized,
219 /// Type of each variable must be `Sized`.
220 VariableType(hir::HirId),
221 /// Argument type must be `Sized`.
222 SizedArgumentType(Option<Span>),
223 /// Return type must be `Sized`.
225 /// Yield type must be `Sized`.
227 /// Box expression result type must be `Sized`.
229 /// Inline asm operand type must be `Sized`.
231 /// `[T, ..n]` implies that `T` must be `Copy`.
232 /// If the function in the array repeat expression is a `const fn`,
233 /// display a help message suggesting to move the function call to a
234 /// new `const` item while saying that `T` doesn't implement `Copy`.
237 /// Types of fields (other than the last, except for packed structs) in a struct must be sized.
244 /// Constant expressions must be sized.
247 /// `static` items must have `Sync` type.
250 BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
252 ImplDerivedObligation(DerivedObligationCause<'tcx>),
254 DerivedObligation(DerivedObligationCause<'tcx>),
256 FunctionArgumentObligation {
257 /// The node of the relevant argument in the function call.
258 arg_hir_id: hir::HirId,
259 /// The node of the function call.
260 call_hir_id: hir::HirId,
261 /// The obligation introduced by this argument.
262 parent_code: Lrc<ObligationCauseCode<'tcx>>,
265 /// Error derived when matching traits/impls; see ObligationCause for more details
266 CompareImplConstObligation,
268 /// Error derived when matching traits/impls; see ObligationCause for more details
269 CompareImplMethodObligation {
271 impl_item_def_id: DefId,
272 trait_item_def_id: DefId,
275 /// Error derived when matching traits/impls; see ObligationCause for more details
276 CompareImplTypeObligation {
278 impl_item_def_id: DefId,
279 trait_item_def_id: DefId,
282 /// Checking that this expression can be assigned where it needs to be
283 // FIXME(eddyb) #11161 is the original Expr required?
286 /// Computing common supertype in the arms of a match expression
287 MatchExpressionArm(Box<MatchExpressionArmCause<'tcx>>),
289 /// Type error arising from type checking a pattern against an expected type.
291 /// The span of the scrutinee or type expression which caused the `root_ty` type.
293 /// The root expected type induced by a scrutinee or type expression.
295 /// Whether the `Span` came from an expression or a type expression.
299 /// Constants in patterns must have `Structural` type.
300 ConstPatternStructural,
302 /// Computing common supertype in an if expression
303 IfExpression(Box<IfExpressionCause>),
305 /// Computing common supertype of an if expression with no else counter-part
306 IfExpressionWithNoElse,
308 /// `main` has wrong type
311 /// `start` has wrong type
314 /// Intrinsic has wrong type
317 /// A let else block does not diverge
323 UnifyReceiver(Box<UnifyReceiverContext<'tcx>>),
325 /// `return` with no expression
328 /// `return` with an expression
329 ReturnValue(hir::HirId),
331 /// Return type of this function
334 /// Block implicit return
335 BlockTailExpression(hir::HirId),
337 /// #[feature(trivial_bounds)] is not enabled
340 /// If `X` is the concrete type of an opaque type `impl Y`, then `X` must implement `Y`
343 /// Well-formed checking. If a `WellFormedLoc` is provided,
344 /// then it will be used to eprform HIR-based wf checking
345 /// after an error occurs, in order to generate a more precise error span.
346 /// This is purely for diagnostic purposes - it is always
347 /// correct to use `MiscObligation` instead, or to specify
348 /// `WellFormed(None)`
349 WellFormed(Option<WellFormedLoc>),
351 /// From `match_impl`. The cause for us having to match an impl, and the DefId we are matching against.
352 MatchImpl(ObligationCause<'tcx>, DefId),
355 /// The 'location' at which we try to perform HIR-based wf checking.
356 /// This information is used to obtain an `hir::Ty`, which
357 /// we can walk in order to obtain precise spans for any
358 /// 'nested' types (e.g. `Foo` in `Option<Foo>`).
359 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
360 pub enum WellFormedLoc {
361 /// Use the type of the provided definition.
363 /// Use the type of the parameter of the provided function.
364 /// We cannot use `hir::Param`, since the function may
365 /// not have a body (e.g. a trait method definition)
367 /// The function to lookup the parameter in
368 function: LocalDefId,
369 /// The index of the parameter to use.
370 /// Parameters are indexed from 0, with the return type
371 /// being the last 'parameter'
376 impl ObligationCauseCode<'_> {
377 // Return the base obligation, ignoring derived obligations.
378 pub fn peel_derives(&self) -> &Self {
379 let mut base_cause = self;
380 while let BuiltinDerivedObligation(DerivedObligationCause { parent_code, .. })
381 | ImplDerivedObligation(DerivedObligationCause { parent_code, .. })
382 | DerivedObligation(DerivedObligationCause { parent_code, .. })
383 | FunctionArgumentObligation { parent_code, .. } = base_cause
385 base_cause = &parent_code;
391 // `ObligationCauseCode` is used a lot. Make sure it doesn't unintentionally get bigger.
392 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
393 static_assert_size!(ObligationCauseCode<'_>, 40);
395 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
396 pub enum StatementAsExpression {
401 impl<'tcx> ty::Lift<'tcx> for StatementAsExpression {
402 type Lifted = StatementAsExpression;
403 fn lift_to_tcx(self, _tcx: TyCtxt<'tcx>) -> Option<StatementAsExpression> {
408 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
409 pub struct MatchExpressionArmCause<'tcx> {
411 pub scrut_span: Span,
412 pub semi_span: Option<(Span, StatementAsExpression)>,
413 pub source: hir::MatchSource,
414 pub prior_arms: Vec<Span>,
415 pub last_ty: Ty<'tcx>,
416 pub scrut_hir_id: hir::HirId,
417 pub opt_suggest_box_span: Option<Span>,
420 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
421 pub struct IfExpressionCause {
424 pub outer: Option<Span>,
425 pub semicolon: Option<(Span, StatementAsExpression)>,
426 pub opt_suggest_box_span: Option<Span>,
429 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
430 pub struct DerivedObligationCause<'tcx> {
431 /// The trait reference of the parent obligation that led to the
432 /// current obligation. Note that only trait obligations lead to
433 /// derived obligations, so we just store the trait reference here
435 pub parent_trait_ref: ty::PolyTraitRef<'tcx>,
437 /// The parent trait had this cause.
438 pub parent_code: Lrc<ObligationCauseCode<'tcx>>,
441 #[derive(Clone, Debug, TypeFoldable, Lift)]
442 pub enum SelectionError<'tcx> {
443 /// The trait is not implemented.
445 /// After a closure impl has selected, its "outputs" were evaluated
446 /// (which for closures includes the "input" type params) and they
447 /// didn't resolve. See `confirm_poly_trait_refs` for more.
448 OutputTypeParameterMismatch(
449 ty::PolyTraitRef<'tcx>,
450 ty::PolyTraitRef<'tcx>,
451 ty::error::TypeError<'tcx>,
453 /// The trait pointed by `DefId` is not object safe.
454 TraitNotObjectSafe(DefId),
455 /// A given constant couldn't be evaluated.
456 NotConstEvaluatable(NotConstEvaluatable),
457 /// Exceeded the recursion depth during type projection.
459 /// Signaling that an error has already been emitted, to avoid
460 /// multiple errors being shown.
462 /// Multiple applicable `impl`s where found. The `DefId`s correspond to
463 /// all the `impl`s' Items.
464 Ambiguous(Vec<DefId>),
467 /// When performing resolution, it is typically the case that there
468 /// can be one of three outcomes:
470 /// - `Ok(Some(r))`: success occurred with result `r`
471 /// - `Ok(None)`: could not definitely determine anything, usually due
472 /// to inconclusive type inference.
473 /// - `Err(e)`: error `e` occurred
474 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
476 /// Given the successful resolution of an obligation, the `ImplSource`
477 /// indicates where the impl comes from.
479 /// For example, the obligation may be satisfied by a specific impl (case A),
480 /// or it may be relative to some bound that is in scope (case B).
483 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
484 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
485 /// impl Clone for i32 { ... } // Impl_3
487 /// fn foo<T: Clone>(concrete: Option<Box<i32>>, param: T, mixed: Option<T>) {
488 /// // Case A: ImplSource points at a specific impl. Only possible when
489 /// // type is concretely known. If the impl itself has bounded
490 /// // type parameters, ImplSource will carry resolutions for those as well:
491 /// concrete.clone(); // ImpleSource(Impl_1, [ImplSource(Impl_2, [ImplSource(Impl_3)])])
493 /// // Case A: ImplSource points at a specific impl. Only possible when
494 /// // type is concretely known. If the impl itself has bounded
495 /// // type parameters, ImplSource will carry resolutions for those as well:
496 /// concrete.clone(); // ImplSource(Impl_1, [ImplSource(Impl_2, [ImplSource(Impl_3)])])
498 /// // Case B: ImplSource must be provided by caller. This applies when
499 /// // type is a type parameter.
500 /// param.clone(); // ImplSource::Param
502 /// // Case C: A mix of cases A and B.
503 /// mixed.clone(); // ImplSource(Impl_1, [ImplSource::Param])
507 /// ### The type parameter `N`
509 /// See explanation on `ImplSourceUserDefinedData`.
510 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
511 pub enum ImplSource<'tcx, N> {
512 /// ImplSource identifying a particular impl.
513 UserDefined(ImplSourceUserDefinedData<'tcx, N>),
515 /// ImplSource for auto trait implementations.
516 /// This carries the information and nested obligations with regards
517 /// to an auto implementation for a trait `Trait`. The nested obligations
518 /// ensure the trait implementation holds for all the constituent types.
519 AutoImpl(ImplSourceAutoImplData<N>),
521 /// Successful resolution to an obligation provided by the caller
522 /// for some type parameter. The `Vec<N>` represents the
523 /// obligations incurred from normalizing the where-clause (if
525 Param(Vec<N>, ty::BoundConstness),
527 /// Virtual calls through an object.
528 Object(ImplSourceObjectData<'tcx, N>),
530 /// Successful resolution for a builtin trait.
531 Builtin(ImplSourceBuiltinData<N>),
533 /// ImplSource for trait upcasting coercion
534 TraitUpcasting(ImplSourceTraitUpcastingData<'tcx, N>),
536 /// ImplSource automatically generated for a closure. The `DefId` is the ID
537 /// of the closure expression. This is an `ImplSource::UserDefined` in spirit, but the
538 /// impl is generated by the compiler and does not appear in the source.
539 Closure(ImplSourceClosureData<'tcx, N>),
541 /// Same as above, but for a function pointer type with the given signature.
542 FnPointer(ImplSourceFnPointerData<'tcx, N>),
544 /// ImplSource for a builtin `DeterminantKind` trait implementation.
545 DiscriminantKind(ImplSourceDiscriminantKindData),
547 /// ImplSource for a builtin `Pointee` trait implementation.
548 Pointee(ImplSourcePointeeData),
550 /// ImplSource automatically generated for a generator.
551 Generator(ImplSourceGeneratorData<'tcx, N>),
553 /// ImplSource for a trait alias.
554 TraitAlias(ImplSourceTraitAliasData<'tcx, N>),
556 /// ImplSource for a `const Drop` implementation.
557 ConstDrop(ImplSourceConstDropData),
560 impl<'tcx, N> ImplSource<'tcx, N> {
561 pub fn nested_obligations(self) -> Vec<N> {
563 ImplSource::UserDefined(i) => i.nested,
564 ImplSource::Param(n, _) => n,
565 ImplSource::Builtin(i) => i.nested,
566 ImplSource::AutoImpl(d) => d.nested,
567 ImplSource::Closure(c) => c.nested,
568 ImplSource::Generator(c) => c.nested,
569 ImplSource::Object(d) => d.nested,
570 ImplSource::FnPointer(d) => d.nested,
571 ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData)
572 | ImplSource::Pointee(ImplSourcePointeeData)
573 | ImplSource::ConstDrop(ImplSourceConstDropData) => Vec::new(),
574 ImplSource::TraitAlias(d) => d.nested,
575 ImplSource::TraitUpcasting(d) => d.nested,
579 pub fn borrow_nested_obligations(&self) -> &[N] {
581 ImplSource::UserDefined(i) => &i.nested[..],
582 ImplSource::Param(n, _) => &n[..],
583 ImplSource::Builtin(i) => &i.nested[..],
584 ImplSource::AutoImpl(d) => &d.nested[..],
585 ImplSource::Closure(c) => &c.nested[..],
586 ImplSource::Generator(c) => &c.nested[..],
587 ImplSource::Object(d) => &d.nested[..],
588 ImplSource::FnPointer(d) => &d.nested[..],
589 ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData)
590 | ImplSource::Pointee(ImplSourcePointeeData)
591 | ImplSource::ConstDrop(ImplSourceConstDropData) => &[],
592 ImplSource::TraitAlias(d) => &d.nested[..],
593 ImplSource::TraitUpcasting(d) => &d.nested[..],
597 pub fn map<M, F>(self, f: F) -> ImplSource<'tcx, M>
602 ImplSource::UserDefined(i) => ImplSource::UserDefined(ImplSourceUserDefinedData {
603 impl_def_id: i.impl_def_id,
605 nested: i.nested.into_iter().map(f).collect(),
607 ImplSource::Param(n, ct) => ImplSource::Param(n.into_iter().map(f).collect(), ct),
608 ImplSource::Builtin(i) => ImplSource::Builtin(ImplSourceBuiltinData {
609 nested: i.nested.into_iter().map(f).collect(),
611 ImplSource::Object(o) => ImplSource::Object(ImplSourceObjectData {
612 upcast_trait_ref: o.upcast_trait_ref,
613 vtable_base: o.vtable_base,
614 nested: o.nested.into_iter().map(f).collect(),
616 ImplSource::AutoImpl(d) => ImplSource::AutoImpl(ImplSourceAutoImplData {
617 trait_def_id: d.trait_def_id,
618 nested: d.nested.into_iter().map(f).collect(),
620 ImplSource::Closure(c) => ImplSource::Closure(ImplSourceClosureData {
621 closure_def_id: c.closure_def_id,
623 nested: c.nested.into_iter().map(f).collect(),
625 ImplSource::Generator(c) => ImplSource::Generator(ImplSourceGeneratorData {
626 generator_def_id: c.generator_def_id,
628 nested: c.nested.into_iter().map(f).collect(),
630 ImplSource::FnPointer(p) => ImplSource::FnPointer(ImplSourceFnPointerData {
632 nested: p.nested.into_iter().map(f).collect(),
634 ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData) => {
635 ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData)
637 ImplSource::Pointee(ImplSourcePointeeData) => {
638 ImplSource::Pointee(ImplSourcePointeeData)
640 ImplSource::TraitAlias(d) => ImplSource::TraitAlias(ImplSourceTraitAliasData {
641 alias_def_id: d.alias_def_id,
643 nested: d.nested.into_iter().map(f).collect(),
645 ImplSource::TraitUpcasting(d) => {
646 ImplSource::TraitUpcasting(ImplSourceTraitUpcastingData {
647 upcast_trait_ref: d.upcast_trait_ref,
648 vtable_vptr_slot: d.vtable_vptr_slot,
649 nested: d.nested.into_iter().map(f).collect(),
652 ImplSource::ConstDrop(ImplSourceConstDropData) => {
653 ImplSource::ConstDrop(ImplSourceConstDropData)
659 /// Identifies a particular impl in the source, along with a set of
660 /// substitutions from the impl's type/lifetime parameters. The
661 /// `nested` vector corresponds to the nested obligations attached to
662 /// the impl's type parameters.
664 /// The type parameter `N` indicates the type used for "nested
665 /// obligations" that are required by the impl. During type-check, this
666 /// is `Obligation`, as one might expect. During codegen, however, this
667 /// is `()`, because codegen only requires a shallow resolution of an
668 /// impl, and nested obligations are satisfied later.
669 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
670 pub struct ImplSourceUserDefinedData<'tcx, N> {
671 pub impl_def_id: DefId,
672 pub substs: SubstsRef<'tcx>,
676 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
677 pub struct ImplSourceGeneratorData<'tcx, N> {
678 pub generator_def_id: DefId,
679 pub substs: SubstsRef<'tcx>,
680 /// Nested obligations. This can be non-empty if the generator
681 /// signature contains associated types.
685 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
686 pub struct ImplSourceClosureData<'tcx, N> {
687 pub closure_def_id: DefId,
688 pub substs: SubstsRef<'tcx>,
689 /// Nested obligations. This can be non-empty if the closure
690 /// signature contains associated types.
694 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
695 pub struct ImplSourceAutoImplData<N> {
696 pub trait_def_id: DefId,
700 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
701 pub struct ImplSourceTraitUpcastingData<'tcx, N> {
702 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
703 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
705 /// The vtable is formed by concatenating together the method lists of
706 /// the base object trait and all supertraits, pointers to supertrait vtable will
707 /// be provided when necessary; this is the position of `upcast_trait_ref`'s vtable
708 /// within that vtable.
709 pub vtable_vptr_slot: Option<usize>,
714 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
715 pub struct ImplSourceBuiltinData<N> {
719 #[derive(PartialEq, Eq, Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
720 pub struct ImplSourceObjectData<'tcx, N> {
721 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
722 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
724 /// The vtable is formed by concatenating together the method lists of
725 /// the base object trait and all supertraits, pointers to supertrait vtable will
726 /// be provided when necessary; this is the start of `upcast_trait_ref`'s methods
728 pub vtable_base: usize,
733 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
734 pub struct ImplSourceFnPointerData<'tcx, N> {
739 // FIXME(@lcnr): This should be refactored and merged with other builtin vtables.
740 #[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
741 pub struct ImplSourceDiscriminantKindData;
743 #[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
744 pub struct ImplSourcePointeeData;
746 #[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
747 pub struct ImplSourceConstDropData;
749 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
750 pub struct ImplSourceTraitAliasData<'tcx, N> {
751 pub alias_def_id: DefId,
752 pub substs: SubstsRef<'tcx>,
756 #[derive(Clone, Debug, PartialEq, Eq, Hash, HashStable, PartialOrd, Ord)]
757 pub enum ObjectSafetyViolation {
758 /// `Self: Sized` declared on the trait.
759 SizedSelf(SmallVec<[Span; 1]>),
761 /// Supertrait reference references `Self` an in illegal location
762 /// (e.g., `trait Foo : Bar<Self>`).
763 SupertraitSelf(SmallVec<[Span; 1]>),
765 /// Method has something illegal.
766 Method(Symbol, MethodViolationCode, Span),
768 /// Associated const.
769 AssocConst(Symbol, Span),
775 impl ObjectSafetyViolation {
776 pub fn error_msg(&self) -> Cow<'static, str> {
778 ObjectSafetyViolation::SizedSelf(_) => "it requires `Self: Sized`".into(),
779 ObjectSafetyViolation::SupertraitSelf(ref spans) => {
780 if spans.iter().any(|sp| *sp != DUMMY_SP) {
781 "it uses `Self` as a type parameter".into()
783 "it cannot use `Self` as a type parameter in a supertrait or `where`-clause"
787 ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod(_, _, _), _) => {
788 format!("associated function `{}` has no `self` parameter", name).into()
790 ObjectSafetyViolation::Method(
792 MethodViolationCode::ReferencesSelfInput(_),
794 ) => format!("method `{}` references the `Self` type in its parameters", name).into(),
795 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfInput(_), _) => {
796 format!("method `{}` references the `Self` type in this parameter", name).into()
798 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfOutput, _) => {
799 format!("method `{}` references the `Self` type in its return type", name).into()
801 ObjectSafetyViolation::Method(
803 MethodViolationCode::WhereClauseReferencesSelf,
806 format!("method `{}` references the `Self` type in its `where` clause", name).into()
808 ObjectSafetyViolation::Method(name, MethodViolationCode::Generic, _) => {
809 format!("method `{}` has generic type parameters", name).into()
811 ObjectSafetyViolation::Method(name, MethodViolationCode::UndispatchableReceiver, _) => {
812 format!("method `{}`'s `self` parameter cannot be dispatched on", name).into()
814 ObjectSafetyViolation::AssocConst(name, DUMMY_SP) => {
815 format!("it contains associated `const` `{}`", name).into()
817 ObjectSafetyViolation::AssocConst(..) => "it contains this associated `const`".into(),
818 ObjectSafetyViolation::GAT(name, _) => {
819 format!("it contains the generic associated type `{}`", name).into()
824 pub fn solution(&self, err: &mut DiagnosticBuilder<'_>) {
826 ObjectSafetyViolation::SizedSelf(_) | ObjectSafetyViolation::SupertraitSelf(_) => {}
827 ObjectSafetyViolation::Method(
829 MethodViolationCode::StaticMethod(sugg, self_span, has_args),
835 "consider turning `{}` into a method by giving it a `&self` argument",
838 format!("&self{}", if has_args { ", " } else { "" }),
839 Applicability::MaybeIncorrect,
842 Some((sugg, span)) => {
846 "alternatively, consider constraining `{}` so it does not apply to \
851 Applicability::MaybeIncorrect,
856 "consider turning `{}` into a method by giving it a `&self` \
857 argument or constraining it so it does not apply to trait objects",
863 ObjectSafetyViolation::Method(
865 MethodViolationCode::UndispatchableReceiver,
871 "consider changing method `{}`'s `self` parameter to be `&self`",
875 Applicability::MachineApplicable,
878 ObjectSafetyViolation::AssocConst(name, _)
879 | ObjectSafetyViolation::GAT(name, _)
880 | ObjectSafetyViolation::Method(name, ..) => {
881 err.help(&format!("consider moving `{}` to another trait", name));
886 pub fn spans(&self) -> SmallVec<[Span; 1]> {
887 // When `span` comes from a separate crate, it'll be `DUMMY_SP`. Treat it as `None` so
888 // diagnostics use a `note` instead of a `span_label`.
890 ObjectSafetyViolation::SupertraitSelf(spans)
891 | ObjectSafetyViolation::SizedSelf(spans) => spans.clone(),
892 ObjectSafetyViolation::AssocConst(_, span)
893 | ObjectSafetyViolation::GAT(_, span)
894 | ObjectSafetyViolation::Method(_, _, span)
895 if *span != DUMMY_SP =>
904 /// Reasons a method might not be object-safe.
905 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable, PartialOrd, Ord)]
906 pub enum MethodViolationCode {
908 StaticMethod(Option<(&'static str, Span)>, Span, bool /* has args */),
910 /// e.g., `fn foo(&self, x: Self)`
911 ReferencesSelfInput(usize),
913 /// e.g., `fn foo(&self) -> Self`
914 ReferencesSelfOutput,
916 /// e.g., `fn foo(&self) where Self: Clone`
917 WhereClauseReferencesSelf,
919 /// e.g., `fn foo<A>()`
922 /// the method's receiver (`self` argument) can't be dispatched on
923 UndispatchableReceiver,