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::mir::ConstraintCategory;
14 use crate::ty::abstract_const::NotConstEvaluatable;
15 use crate::ty::subst::SubstsRef;
16 use crate::ty::{self, AdtKind, Ty, TyCtxt};
18 use rustc_data_structures::sync::Lrc;
19 use rustc_errors::{Applicability, Diagnostic};
21 use rustc_hir::def_id::DefId;
22 use rustc_span::def_id::{LocalDefId, CRATE_DEF_ID};
23 use rustc_span::symbol::Symbol;
24 use rustc_span::{Span, DUMMY_SP};
25 use smallvec::SmallVec;
28 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
52 /// ```compile_fail,E0308
53 /// #![feature(specialization)]
58 /// impl<T> Assoc for T {
59 /// default type Output = bool;
63 /// let x: <() as Assoc>::Output = true;
67 /// We also do not reveal the hidden type of opaque types during
71 /// At codegen time, all monomorphic projections will succeed.
72 /// Also, `impl Trait` is normalized to the concrete type,
73 /// which has to be already collected by type-checking.
75 /// NOTE: as `impl Trait`'s concrete type should *never*
76 /// be observable directly by the user, `Reveal::All`
77 /// should not be used by checks which may expose
78 /// type equality or type contents to the user.
79 /// There are some exceptions, e.g., around auto traits and
80 /// transmute-checking, which expose some details, but
81 /// not the whole concrete type of the `impl Trait`.
85 /// The reason why we incurred this obligation; used for error reporting.
87 /// Non-misc `ObligationCauseCode`s are stored on the heap. This gives the
88 /// best trade-off between keeping the type small (which makes copies cheaper)
89 /// while not doing too many heap allocations.
91 /// We do not want to intern this as there are a lot of obligation causes which
92 /// only live for a short period of time.
93 #[derive(Clone, Debug, PartialEq, Eq, Lift)]
94 pub struct ObligationCause<'tcx> {
97 /// The ID of the fn body that triggered this obligation. This is
98 /// used for region obligations to determine the precise
99 /// environment in which the region obligation should be evaluated
100 /// (in particular, closures can add new assumptions). See the
101 /// field `region_obligations` of the `FulfillmentContext` for more
103 pub body_id: LocalDefId,
105 code: InternedObligationCauseCode<'tcx>,
108 // This custom hash function speeds up hashing for `Obligation` deduplication
109 // greatly by skipping the `code` field, which can be large and complex. That
110 // shouldn't affect hash quality much since there are several other fields in
111 // `Obligation` which should be unique enough, especially the predicate itself
112 // which is hashed as an interned pointer. See #90996.
113 impl Hash for ObligationCause<'_> {
114 fn hash<H: Hasher>(&self, state: &mut H) {
115 self.body_id.hash(state);
116 self.span.hash(state);
120 impl<'tcx> ObligationCause<'tcx> {
125 code: ObligationCauseCode<'tcx>,
126 ) -> ObligationCause<'tcx> {
127 ObligationCause { span, body_id, code: code.into() }
130 pub fn misc(span: Span, body_id: LocalDefId) -> ObligationCause<'tcx> {
131 ObligationCause::new(span, body_id, MiscObligation)
135 pub fn dummy() -> ObligationCause<'tcx> {
136 ObligationCause::dummy_with_span(DUMMY_SP)
140 pub fn dummy_with_span(span: Span) -> ObligationCause<'tcx> {
141 ObligationCause { span, body_id: CRATE_DEF_ID, code: Default::default() }
144 pub fn span(&self) -> Span {
146 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
155 pub fn code(&self) -> &ObligationCauseCode<'tcx> {
161 f: impl FnOnce(InternedObligationCauseCode<'tcx>) -> ObligationCauseCode<'tcx>,
163 self.code = f(std::mem::take(&mut self.code)).into();
166 pub fn derived_cause(
168 parent_trait_pred: ty::PolyTraitPredicate<'tcx>,
169 variant: impl FnOnce(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
170 ) -> ObligationCause<'tcx> {
172 * Creates a cause for obligations that are derived from
173 * `obligation` by a recursive search (e.g., for a builtin
174 * bound, or eventually a `auto trait Foo`). If `obligation`
175 * is itself a derived obligation, this is just a clone, but
176 * otherwise we create a "derived obligation" cause so as to
177 * keep track of the original root obligation for error
181 // NOTE(flaper87): As of now, it keeps track of the whole error
182 // chain. Ideally, we should have a way to configure this either
183 // by using -Z verbose or just a CLI argument.
185 variant(DerivedObligationCause { parent_trait_pred, parent_code: self.code }).into();
189 pub fn to_constraint_category(&self) -> ConstraintCategory<'tcx> {
191 MatchImpl(cause, _) => cause.to_constraint_category(),
192 AscribeUserTypeProvePredicate(predicate_span) => {
193 ConstraintCategory::Predicate(*predicate_span)
195 _ => ConstraintCategory::BoringNoLocation,
200 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
201 pub struct UnifyReceiverContext<'tcx> {
202 pub assoc_item: ty::AssocItem,
203 pub param_env: ty::ParamEnv<'tcx>,
204 pub substs: SubstsRef<'tcx>,
207 #[derive(Clone, PartialEq, Eq, Hash, Lift, Default)]
208 pub struct InternedObligationCauseCode<'tcx> {
209 /// `None` for `ObligationCauseCode::MiscObligation` (a common case, occurs ~60% of
210 /// the time). `Some` otherwise.
211 code: Option<Lrc<ObligationCauseCode<'tcx>>>,
214 impl<'tcx> std::fmt::Debug for InternedObligationCauseCode<'tcx> {
215 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
216 let cause: &ObligationCauseCode<'_> = self;
221 impl<'tcx> ObligationCauseCode<'tcx> {
223 fn into(self) -> InternedObligationCauseCode<'tcx> {
224 InternedObligationCauseCode {
225 code: if let ObligationCauseCode::MiscObligation = self {
234 impl<'tcx> std::ops::Deref for InternedObligationCauseCode<'tcx> {
235 type Target = ObligationCauseCode<'tcx>;
237 fn deref(&self) -> &Self::Target {
238 self.code.as_deref().unwrap_or(&ObligationCauseCode::MiscObligation)
242 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
243 pub enum ObligationCauseCode<'tcx> {
244 /// Not well classified or should be obvious from the span.
247 /// A slice or array is WF only if `T: Sized`.
250 /// A tuple is WF only if its middle elements are `Sized`.
253 /// This is the trait reference from the given projection.
254 ProjectionWf(ty::AliasTy<'tcx>),
256 /// Must satisfy all of the where-clause predicates of the
258 ItemObligation(DefId),
260 /// Like `ItemObligation`, but carries the span of the
261 /// predicate when it can be identified.
262 BindingObligation(DefId, Span),
264 /// Like `ItemObligation`, but carries the `HirId` of the
265 /// expression that caused the obligation, and the `usize`
266 /// indicates exactly which predicate it is in the list of
267 /// instantiated predicates.
268 ExprItemObligation(DefId, rustc_hir::HirId, usize),
270 /// Combines `ExprItemObligation` and `BindingObligation`.
271 ExprBindingObligation(DefId, Span, rustc_hir::HirId, usize),
273 /// A type like `&'a T` is WF only if `T: 'a`.
274 ReferenceOutlivesReferent(Ty<'tcx>),
276 /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
277 ObjectTypeBound(Ty<'tcx>, ty::Region<'tcx>),
279 /// Obligation incurred due to an object cast.
280 ObjectCastObligation(/* Concrete type */ Ty<'tcx>, /* Object type */ Ty<'tcx>),
282 /// Obligation incurred due to a coercion.
288 /// Various cases where expressions must be `Sized` / `Copy` / etc.
289 /// `L = X` implies that `L` is `Sized`.
291 /// `(x1, .., xn)` must be `Sized`.
292 TupleInitializerSized,
293 /// `S { ... }` must be `Sized`.
294 StructInitializerSized,
295 /// Type of each variable must be `Sized`.
296 VariableType(hir::HirId),
297 /// Argument type must be `Sized`.
298 SizedArgumentType(Option<Span>),
299 /// Return type must be `Sized`.
301 /// Yield type must be `Sized`.
303 /// Box expression result type must be `Sized`.
305 /// Inline asm operand type must be `Sized`.
307 /// `[expr; N]` requires `type_of(expr): Copy`.
309 /// If element is a `const fn` we display a help message suggesting to move the
310 /// function call to a new `const` item while saying that `T` doesn't implement `Copy`.
314 /// Types of fields (other than the last, except for packed structs) in a struct must be sized.
321 /// Constant expressions must be sized.
324 /// `static` items must have `Sync` type.
327 BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
329 ImplDerivedObligation(Box<ImplDerivedObligationCause<'tcx>>),
331 DerivedObligation(DerivedObligationCause<'tcx>),
333 FunctionArgumentObligation {
334 /// The node of the relevant argument in the function call.
335 arg_hir_id: hir::HirId,
336 /// The node of the function call.
337 call_hir_id: hir::HirId,
338 /// The obligation introduced by this argument.
339 parent_code: InternedObligationCauseCode<'tcx>,
342 /// Error derived when matching traits/impls; see ObligationCause for more details
343 CompareImplItemObligation {
344 impl_item_def_id: LocalDefId,
345 trait_item_def_id: DefId,
349 /// Checking that the bounds of a trait's associated type hold for a given impl
350 CheckAssociatedTypeBounds {
351 impl_item_def_id: LocalDefId,
352 trait_item_def_id: DefId,
355 /// Checking that this expression can be assigned to its target.
358 /// Computing common supertype in the arms of a match expression
359 MatchExpressionArm(Box<MatchExpressionArmCause<'tcx>>),
361 /// Type error arising from type checking a pattern against an expected type.
363 /// The span of the scrutinee or type expression which caused the `root_ty` type.
365 /// The root expected type induced by a scrutinee or type expression.
367 /// Whether the `Span` came from an expression or a type expression.
371 /// Constants in patterns must have `Structural` type.
372 ConstPatternStructural,
374 /// Computing common supertype in an if expression
375 IfExpression(Box<IfExpressionCause<'tcx>>),
377 /// Computing common supertype of an if expression with no else counter-part
378 IfExpressionWithNoElse,
380 /// `main` has wrong type
383 /// `start` has wrong type
386 /// Intrinsic has wrong type
389 /// A let else block does not diverge
395 UnifyReceiver(Box<UnifyReceiverContext<'tcx>>),
397 /// `return` with no expression
400 /// `return` with an expression
401 ReturnValue(hir::HirId),
403 /// Return type of this function
406 /// Opaque return type of this function
407 OpaqueReturnType(Option<(Ty<'tcx>, Span)>),
409 /// Block implicit return
410 BlockTailExpression(hir::HirId),
412 /// #[feature(trivial_bounds)] is not enabled
415 /// If `X` is the concrete type of an opaque type `impl Y`, then `X` must implement `Y`
418 AwaitableExpr(Option<hir::HirId>),
424 /// Well-formed checking. If a `WellFormedLoc` is provided,
425 /// then it will be used to perform HIR-based wf checking
426 /// after an error occurs, in order to generate a more precise error span.
427 /// This is purely for diagnostic purposes - it is always
428 /// correct to use `MiscObligation` instead, or to specify
429 /// `WellFormed(None)`
430 WellFormed(Option<WellFormedLoc>),
432 /// From `match_impl`. The cause for us having to match an impl, and the DefId we are matching against.
433 MatchImpl(ObligationCause<'tcx>, DefId),
436 rhs_span: Option<Span>,
438 output_ty: Option<Ty<'tcx>>,
441 AscribeUserTypeProvePredicate(Span),
446 /// The 'location' at which we try to perform HIR-based wf checking.
447 /// This information is used to obtain an `hir::Ty`, which
448 /// we can walk in order to obtain precise spans for any
449 /// 'nested' types (e.g. `Foo` in `Option<Foo>`).
450 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
451 pub enum WellFormedLoc {
452 /// Use the type of the provided definition.
454 /// Use the type of the parameter of the provided function.
455 /// We cannot use `hir::Param`, since the function may
456 /// not have a body (e.g. a trait method definition)
458 /// The function to lookup the parameter in
459 function: LocalDefId,
460 /// The index of the parameter to use.
461 /// Parameters are indexed from 0, with the return type
462 /// being the last 'parameter'
467 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
468 pub struct ImplDerivedObligationCause<'tcx> {
469 pub derived: DerivedObligationCause<'tcx>,
470 pub impl_def_id: DefId,
474 impl<'tcx> ObligationCauseCode<'tcx> {
475 /// Returns the base obligation, ignoring derived obligations.
476 pub fn peel_derives(&self) -> &Self {
477 let mut base_cause = self;
478 while let Some((parent_code, _)) = base_cause.parent() {
479 base_cause = parent_code;
484 pub fn parent(&self) -> Option<(&Self, Option<ty::PolyTraitPredicate<'tcx>>)> {
486 FunctionArgumentObligation { parent_code, .. } => Some((parent_code, None)),
487 BuiltinDerivedObligation(derived)
488 | DerivedObligation(derived)
489 | ImplDerivedObligation(box ImplDerivedObligationCause { derived, .. }) => {
490 Some((&derived.parent_code, Some(derived.parent_trait_pred)))
496 pub fn peel_match_impls(&self) -> &Self {
498 MatchImpl(cause, _) => cause.code(),
504 // `ObligationCauseCode` is used a lot. Make sure it doesn't unintentionally get bigger.
505 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
506 static_assert_size!(ObligationCauseCode<'_>, 48);
508 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
509 pub enum StatementAsExpression {
514 impl<'tcx> ty::Lift<'tcx> for StatementAsExpression {
515 type Lifted = StatementAsExpression;
516 fn lift_to_tcx(self, _tcx: TyCtxt<'tcx>) -> Option<StatementAsExpression> {
521 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
522 pub struct MatchExpressionArmCause<'tcx> {
523 pub arm_block_id: Option<hir::HirId>,
524 pub arm_ty: Ty<'tcx>,
526 pub prior_arm_block_id: Option<hir::HirId>,
527 pub prior_arm_ty: Ty<'tcx>,
528 pub prior_arm_span: Span,
529 pub scrut_span: Span,
530 pub source: hir::MatchSource,
531 pub prior_arms: Vec<Span>,
532 pub scrut_hir_id: hir::HirId,
533 pub opt_suggest_box_span: Option<Span>,
536 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
537 #[derive(Lift, TypeFoldable, TypeVisitable)]
538 pub struct IfExpressionCause<'tcx> {
539 pub then_id: hir::HirId,
540 pub else_id: hir::HirId,
541 pub then_ty: Ty<'tcx>,
542 pub else_ty: Ty<'tcx>,
543 pub outer_span: Option<Span>,
544 pub opt_suggest_box_span: Option<Span>,
547 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
548 pub struct DerivedObligationCause<'tcx> {
549 /// The trait predicate of the parent obligation that led to the
550 /// current obligation. Note that only trait obligations lead to
551 /// derived obligations, so we just store the trait predicate here
553 pub parent_trait_pred: ty::PolyTraitPredicate<'tcx>,
555 /// The parent trait had this cause.
556 pub parent_code: InternedObligationCauseCode<'tcx>,
559 #[derive(Clone, Debug, TypeFoldable, TypeVisitable, Lift)]
560 pub enum SelectionError<'tcx> {
561 /// The trait is not implemented.
563 /// After a closure impl has selected, its "outputs" were evaluated
564 /// (which for closures includes the "input" type params) and they
565 /// didn't resolve. See `confirm_poly_trait_refs` for more.
566 OutputTypeParameterMismatch(
567 ty::PolyTraitRef<'tcx>,
568 ty::PolyTraitRef<'tcx>,
569 ty::error::TypeError<'tcx>,
571 /// The trait pointed by `DefId` is not object safe.
572 TraitNotObjectSafe(DefId),
573 /// A given constant couldn't be evaluated.
574 NotConstEvaluatable(NotConstEvaluatable),
575 /// Exceeded the recursion depth during type projection.
576 Overflow(OverflowError),
577 /// Signaling that an error has already been emitted, to avoid
578 /// multiple errors being shown.
582 /// When performing resolution, it is typically the case that there
583 /// can be one of three outcomes:
585 /// - `Ok(Some(r))`: success occurred with result `r`
586 /// - `Ok(None)`: could not definitely determine anything, usually due
587 /// to inconclusive type inference.
588 /// - `Err(e)`: error `e` occurred
589 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
591 /// Given the successful resolution of an obligation, the `ImplSource`
592 /// indicates where the impl comes from.
594 /// For example, the obligation may be satisfied by a specific impl (case A),
595 /// or it may be relative to some bound that is in scope (case B).
597 /// ```ignore (illustrative)
598 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
599 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
600 /// impl Clone for i32 { ... } // Impl_3
602 /// fn foo<T: Clone>(concrete: Option<Box<i32>>, param: T, mixed: Option<T>) {
603 /// // Case A: ImplSource points at a specific impl. Only possible when
604 /// // type is concretely known. If the impl itself has bounded
605 /// // type parameters, ImplSource will carry resolutions for those as well:
606 /// concrete.clone(); // ImplSource(Impl_1, [ImplSource(Impl_2, [ImplSource(Impl_3)])])
608 /// // Case B: ImplSource must be provided by caller. This applies when
609 /// // type is a type parameter.
610 /// param.clone(); // ImplSource::Param
612 /// // Case C: A mix of cases A and B.
613 /// mixed.clone(); // ImplSource(Impl_1, [ImplSource::Param])
617 /// ### The type parameter `N`
619 /// See explanation on `ImplSourceUserDefinedData`.
620 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
621 #[derive(TypeFoldable, TypeVisitable)]
622 pub enum ImplSource<'tcx, N> {
623 /// ImplSource identifying a particular impl.
624 UserDefined(ImplSourceUserDefinedData<'tcx, N>),
626 /// ImplSource for auto trait implementations.
627 /// This carries the information and nested obligations with regards
628 /// to an auto implementation for a trait `Trait`. The nested obligations
629 /// ensure the trait implementation holds for all the constituent types.
630 AutoImpl(ImplSourceAutoImplData<N>),
632 /// Successful resolution to an obligation provided by the caller
633 /// for some type parameter. The `Vec<N>` represents the
634 /// obligations incurred from normalizing the where-clause (if
636 Param(Vec<N>, ty::BoundConstness),
638 /// Virtual calls through an object.
639 Object(ImplSourceObjectData<'tcx, N>),
641 /// Successful resolution for a builtin trait.
642 Builtin(ImplSourceBuiltinData<N>),
644 /// ImplSource for trait upcasting coercion
645 TraitUpcasting(ImplSourceTraitUpcastingData<'tcx, N>),
647 /// ImplSource automatically generated for a closure. The `DefId` is the ID
648 /// of the closure expression. This is an `ImplSource::UserDefined` in spirit, but the
649 /// impl is generated by the compiler and does not appear in the source.
650 Closure(ImplSourceClosureData<'tcx, N>),
652 /// Same as above, but for a function pointer type with the given signature.
653 FnPointer(ImplSourceFnPointerData<'tcx, N>),
655 /// ImplSource automatically generated for a generator.
656 Generator(ImplSourceGeneratorData<'tcx, N>),
658 /// ImplSource automatically generated for a generator backing an async future.
659 Future(ImplSourceFutureData<'tcx, N>),
661 /// ImplSource for a trait alias.
662 TraitAlias(ImplSourceTraitAliasData<'tcx, N>),
664 /// ImplSource for a `const Drop` implementation.
665 ConstDestruct(ImplSourceConstDestructData<N>),
668 impl<'tcx, N> ImplSource<'tcx, N> {
669 pub fn nested_obligations(self) -> Vec<N> {
671 ImplSource::UserDefined(i) => i.nested,
672 ImplSource::Param(n, _) => n,
673 ImplSource::Builtin(i) => i.nested,
674 ImplSource::AutoImpl(d) => d.nested,
675 ImplSource::Closure(c) => c.nested,
676 ImplSource::Generator(c) => c.nested,
677 ImplSource::Future(c) => c.nested,
678 ImplSource::Object(d) => d.nested,
679 ImplSource::FnPointer(d) => d.nested,
680 ImplSource::TraitAlias(d) => d.nested,
681 ImplSource::TraitUpcasting(d) => d.nested,
682 ImplSource::ConstDestruct(i) => i.nested,
686 pub fn borrow_nested_obligations(&self) -> &[N] {
688 ImplSource::UserDefined(i) => &i.nested[..],
689 ImplSource::Param(n, _) => &n,
690 ImplSource::Builtin(i) => &i.nested,
691 ImplSource::AutoImpl(d) => &d.nested,
692 ImplSource::Closure(c) => &c.nested,
693 ImplSource::Generator(c) => &c.nested,
694 ImplSource::Future(c) => &c.nested,
695 ImplSource::Object(d) => &d.nested,
696 ImplSource::FnPointer(d) => &d.nested,
697 ImplSource::TraitAlias(d) => &d.nested,
698 ImplSource::TraitUpcasting(d) => &d.nested,
699 ImplSource::ConstDestruct(i) => &i.nested,
703 pub fn map<M, F>(self, f: F) -> ImplSource<'tcx, M>
708 ImplSource::UserDefined(i) => ImplSource::UserDefined(ImplSourceUserDefinedData {
709 impl_def_id: i.impl_def_id,
711 nested: i.nested.into_iter().map(f).collect(),
713 ImplSource::Param(n, ct) => ImplSource::Param(n.into_iter().map(f).collect(), ct),
714 ImplSource::Builtin(i) => ImplSource::Builtin(ImplSourceBuiltinData {
715 nested: i.nested.into_iter().map(f).collect(),
717 ImplSource::Object(o) => ImplSource::Object(ImplSourceObjectData {
718 upcast_trait_ref: o.upcast_trait_ref,
719 vtable_base: o.vtable_base,
720 nested: o.nested.into_iter().map(f).collect(),
722 ImplSource::AutoImpl(d) => ImplSource::AutoImpl(ImplSourceAutoImplData {
723 trait_def_id: d.trait_def_id,
724 nested: d.nested.into_iter().map(f).collect(),
726 ImplSource::Closure(c) => ImplSource::Closure(ImplSourceClosureData {
727 closure_def_id: c.closure_def_id,
729 nested: c.nested.into_iter().map(f).collect(),
731 ImplSource::Generator(c) => ImplSource::Generator(ImplSourceGeneratorData {
732 generator_def_id: c.generator_def_id,
734 nested: c.nested.into_iter().map(f).collect(),
736 ImplSource::Future(c) => ImplSource::Future(ImplSourceFutureData {
737 generator_def_id: c.generator_def_id,
739 nested: c.nested.into_iter().map(f).collect(),
741 ImplSource::FnPointer(p) => ImplSource::FnPointer(ImplSourceFnPointerData {
743 nested: p.nested.into_iter().map(f).collect(),
745 ImplSource::TraitAlias(d) => ImplSource::TraitAlias(ImplSourceTraitAliasData {
746 alias_def_id: d.alias_def_id,
748 nested: d.nested.into_iter().map(f).collect(),
750 ImplSource::TraitUpcasting(d) => {
751 ImplSource::TraitUpcasting(ImplSourceTraitUpcastingData {
752 upcast_trait_ref: d.upcast_trait_ref,
753 vtable_vptr_slot: d.vtable_vptr_slot,
754 nested: d.nested.into_iter().map(f).collect(),
757 ImplSource::ConstDestruct(i) => {
758 ImplSource::ConstDestruct(ImplSourceConstDestructData {
759 nested: i.nested.into_iter().map(f).collect(),
766 /// Identifies a particular impl in the source, along with a set of
767 /// substitutions from the impl's type/lifetime parameters. The
768 /// `nested` vector corresponds to the nested obligations attached to
769 /// the impl's type parameters.
771 /// The type parameter `N` indicates the type used for "nested
772 /// obligations" that are required by the impl. During type-check, this
773 /// is `Obligation`, as one might expect. During codegen, however, this
774 /// is `()`, because codegen only requires a shallow resolution of an
775 /// impl, and nested obligations are satisfied later.
776 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
777 #[derive(TypeFoldable, TypeVisitable)]
778 pub struct ImplSourceUserDefinedData<'tcx, N> {
779 pub impl_def_id: DefId,
780 pub substs: SubstsRef<'tcx>,
784 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
785 #[derive(TypeFoldable, TypeVisitable)]
786 pub struct ImplSourceGeneratorData<'tcx, N> {
787 pub generator_def_id: DefId,
788 pub substs: SubstsRef<'tcx>,
789 /// Nested obligations. This can be non-empty if the generator
790 /// signature contains associated types.
794 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
795 #[derive(TypeFoldable, TypeVisitable)]
796 pub struct ImplSourceFutureData<'tcx, N> {
797 pub generator_def_id: DefId,
798 pub substs: SubstsRef<'tcx>,
799 /// Nested obligations. This can be non-empty if the generator
800 /// signature contains associated types.
804 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
805 #[derive(TypeFoldable, TypeVisitable)]
806 pub struct ImplSourceClosureData<'tcx, N> {
807 pub closure_def_id: DefId,
808 pub substs: SubstsRef<'tcx>,
809 /// Nested obligations. This can be non-empty if the closure
810 /// signature contains associated types.
814 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
815 #[derive(TypeFoldable, TypeVisitable)]
816 pub struct ImplSourceAutoImplData<N> {
817 pub trait_def_id: DefId,
821 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
822 #[derive(TypeFoldable, TypeVisitable)]
823 pub struct ImplSourceTraitUpcastingData<'tcx, N> {
824 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
825 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
827 /// The vtable is formed by concatenating together the method lists of
828 /// the base object trait and all supertraits, pointers to supertrait vtable will
829 /// be provided when necessary; this is the position of `upcast_trait_ref`'s vtable
830 /// within that vtable.
831 pub vtable_vptr_slot: Option<usize>,
836 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
837 #[derive(TypeFoldable, TypeVisitable)]
838 pub struct ImplSourceBuiltinData<N> {
842 #[derive(PartialEq, Eq, Clone, TyEncodable, TyDecodable, HashStable, Lift)]
843 #[derive(TypeFoldable, TypeVisitable)]
844 pub struct ImplSourceObjectData<'tcx, N> {
845 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
846 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
848 /// The vtable is formed by concatenating together the method lists of
849 /// the base object trait and all supertraits, pointers to supertrait vtable will
850 /// be provided when necessary; this is the start of `upcast_trait_ref`'s methods
852 pub vtable_base: usize,
857 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
858 #[derive(TypeFoldable, TypeVisitable)]
859 pub struct ImplSourceFnPointerData<'tcx, N> {
864 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
865 #[derive(TypeFoldable, TypeVisitable)]
866 pub struct ImplSourceConstDestructData<N> {
870 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
871 #[derive(TypeFoldable, TypeVisitable)]
872 pub struct ImplSourceTraitAliasData<'tcx, N> {
873 pub alias_def_id: DefId,
874 pub substs: SubstsRef<'tcx>,
878 #[derive(Clone, Debug, PartialEq, Eq, Hash, HashStable, PartialOrd, Ord)]
879 pub enum ObjectSafetyViolation {
880 /// `Self: Sized` declared on the trait.
881 SizedSelf(SmallVec<[Span; 1]>),
883 /// Supertrait reference references `Self` an in illegal location
884 /// (e.g., `trait Foo : Bar<Self>`).
885 SupertraitSelf(SmallVec<[Span; 1]>),
887 /// Method has something illegal.
888 Method(Symbol, MethodViolationCode, Span),
890 /// Associated const.
891 AssocConst(Symbol, Span),
897 impl ObjectSafetyViolation {
898 pub fn error_msg(&self) -> Cow<'static, str> {
900 ObjectSafetyViolation::SizedSelf(_) => "it requires `Self: Sized`".into(),
901 ObjectSafetyViolation::SupertraitSelf(ref spans) => {
902 if spans.iter().any(|sp| *sp != DUMMY_SP) {
903 "it uses `Self` as a type parameter".into()
905 "it cannot use `Self` as a type parameter in a supertrait or `where`-clause"
909 ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod(_), _) => {
910 format!("associated function `{}` has no `self` parameter", name).into()
912 ObjectSafetyViolation::Method(
914 MethodViolationCode::ReferencesSelfInput(_),
916 ) => format!("method `{}` references the `Self` type in its parameters", name).into(),
917 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfInput(_), _) => {
918 format!("method `{}` references the `Self` type in this parameter", name).into()
920 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfOutput, _) => {
921 format!("method `{}` references the `Self` type in its return type", name).into()
923 ObjectSafetyViolation::Method(
925 MethodViolationCode::ReferencesImplTraitInTrait(_),
927 ) => format!("method `{}` references an `impl Trait` type in its return type", name)
929 ObjectSafetyViolation::Method(name, MethodViolationCode::AsyncFn, _) => {
930 format!("method `{}` is `async`", name).into()
932 ObjectSafetyViolation::Method(
934 MethodViolationCode::WhereClauseReferencesSelf,
937 format!("method `{}` references the `Self` type in its `where` clause", name).into()
939 ObjectSafetyViolation::Method(name, MethodViolationCode::Generic, _) => {
940 format!("method `{}` has generic type parameters", name).into()
942 ObjectSafetyViolation::Method(
944 MethodViolationCode::UndispatchableReceiver(_),
946 ) => format!("method `{}`'s `self` parameter cannot be dispatched on", name).into(),
947 ObjectSafetyViolation::AssocConst(name, DUMMY_SP) => {
948 format!("it contains associated `const` `{}`", name).into()
950 ObjectSafetyViolation::AssocConst(..) => "it contains this associated `const`".into(),
951 ObjectSafetyViolation::GAT(name, _) => {
952 format!("it contains the generic associated type `{}`", name).into()
957 pub fn solution(&self, err: &mut Diagnostic) {
959 ObjectSafetyViolation::SizedSelf(_) | ObjectSafetyViolation::SupertraitSelf(_) => {}
960 ObjectSafetyViolation::Method(
962 MethodViolationCode::StaticMethod(Some((add_self_sugg, make_sized_sugg))),
968 "consider turning `{}` into a method by giving it a `&self` argument",
971 add_self_sugg.0.to_string(),
972 Applicability::MaybeIncorrect,
977 "alternatively, consider constraining `{}` so it does not apply to \
981 make_sized_sugg.0.to_string(),
982 Applicability::MaybeIncorrect,
985 ObjectSafetyViolation::Method(
987 MethodViolationCode::UndispatchableReceiver(Some(span)),
993 "consider changing method `{}`'s `self` parameter to be `&self`",
997 Applicability::MachineApplicable,
1000 ObjectSafetyViolation::AssocConst(name, _)
1001 | ObjectSafetyViolation::GAT(name, _)
1002 | ObjectSafetyViolation::Method(name, ..) => {
1003 err.help(&format!("consider moving `{}` to another trait", name));
1008 pub fn spans(&self) -> SmallVec<[Span; 1]> {
1009 // When `span` comes from a separate crate, it'll be `DUMMY_SP`. Treat it as `None` so
1010 // diagnostics use a `note` instead of a `span_label`.
1012 ObjectSafetyViolation::SupertraitSelf(spans)
1013 | ObjectSafetyViolation::SizedSelf(spans) => spans.clone(),
1014 ObjectSafetyViolation::AssocConst(_, span)
1015 | ObjectSafetyViolation::GAT(_, span)
1016 | ObjectSafetyViolation::Method(_, _, span)
1017 if *span != DUMMY_SP =>
1026 /// Reasons a method might not be object-safe.
1027 #[derive(Clone, Debug, PartialEq, Eq, Hash, HashStable, PartialOrd, Ord)]
1028 pub enum MethodViolationCode {
1029 /// e.g., `fn foo()`
1030 StaticMethod(Option<(/* add &self */ (String, Span), /* add Self: Sized */ (String, Span))>),
1032 /// e.g., `fn foo(&self, x: Self)`
1033 ReferencesSelfInput(Option<Span>),
1035 /// e.g., `fn foo(&self) -> Self`
1036 ReferencesSelfOutput,
1038 /// e.g., `fn foo(&self) -> impl Sized`
1039 ReferencesImplTraitInTrait(Span),
1041 /// e.g., `async fn foo(&self)`
1044 /// e.g., `fn foo(&self) where Self: Clone`
1045 WhereClauseReferencesSelf,
1047 /// e.g., `fn foo<A>()`
1050 /// the method's receiver (`self` argument) can't be dispatched on
1051 UndispatchableReceiver(Option<Span>),
1054 /// These are the error cases for `codegen_select_candidate`.
1055 #[derive(Copy, Clone, Debug, Hash, HashStable, Encodable, Decodable)]
1056 pub enum CodegenObligationError {
1057 /// Ambiguity can happen when monomorphizing during trans
1058 /// expands to some humongous type that never occurred
1059 /// statically -- this humongous type can then overflow,
1060 /// leading to an ambiguous result. So report this as an
1061 /// overflow bug, since I believe this is the only case
1062 /// where ambiguity can result.
1064 /// This can trigger when we probe for the source of a `'static` lifetime requirement
1065 /// on a trait object: `impl Foo for dyn Trait {}` has an implicit `'static` bound.
1066 /// This can also trigger when we have a global bound that is not actually satisfied,
1067 /// but was included during typeck due to the trivial_bounds feature.