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, Encodable, Decodable)]
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, HashStable, TyEncodable, TyDecodable)]
94 #[derive(TypeVisitable, TypeFoldable)]
95 pub struct ObligationCause<'tcx> {
98 /// The ID of the fn body that triggered this obligation. This is
99 /// used for region obligations to determine the precise
100 /// environment in which the region obligation should be evaluated
101 /// (in particular, closures can add new assumptions). See the
102 /// field `region_obligations` of the `FulfillmentContext` for more
104 pub body_id: LocalDefId,
106 code: InternedObligationCauseCode<'tcx>,
109 // This custom hash function speeds up hashing for `Obligation` deduplication
110 // greatly by skipping the `code` field, which can be large and complex. That
111 // shouldn't affect hash quality much since there are several other fields in
112 // `Obligation` which should be unique enough, especially the predicate itself
113 // which is hashed as an interned pointer. See #90996.
114 impl Hash for ObligationCause<'_> {
115 fn hash<H: Hasher>(&self, state: &mut H) {
116 self.body_id.hash(state);
117 self.span.hash(state);
121 impl<'tcx> ObligationCause<'tcx> {
126 code: ObligationCauseCode<'tcx>,
127 ) -> ObligationCause<'tcx> {
128 ObligationCause { span, body_id, code: code.into() }
131 pub fn misc(span: Span, body_id: LocalDefId) -> ObligationCause<'tcx> {
132 ObligationCause::new(span, body_id, MiscObligation)
136 pub fn dummy() -> ObligationCause<'tcx> {
137 ObligationCause::dummy_with_span(DUMMY_SP)
141 pub fn dummy_with_span(span: Span) -> ObligationCause<'tcx> {
142 ObligationCause { span, body_id: CRATE_DEF_ID, code: Default::default() }
145 pub fn span(&self) -> Span {
147 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
156 pub fn code(&self) -> &ObligationCauseCode<'tcx> {
162 f: impl FnOnce(InternedObligationCauseCode<'tcx>) -> ObligationCauseCode<'tcx>,
164 self.code = f(std::mem::take(&mut self.code)).into();
167 pub fn derived_cause(
169 parent_trait_pred: ty::PolyTraitPredicate<'tcx>,
170 variant: impl FnOnce(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
171 ) -> ObligationCause<'tcx> {
173 * Creates a cause for obligations that are derived from
174 * `obligation` by a recursive search (e.g., for a builtin
175 * bound, or eventually a `auto trait Foo`). If `obligation`
176 * is itself a derived obligation, this is just a clone, but
177 * otherwise we create a "derived obligation" cause so as to
178 * keep track of the original root obligation for error
182 // NOTE(flaper87): As of now, it keeps track of the whole error
183 // chain. Ideally, we should have a way to configure this either
184 // by using -Z verbose or just a CLI argument.
186 variant(DerivedObligationCause { parent_trait_pred, parent_code: self.code }).into();
190 pub fn to_constraint_category(&self) -> ConstraintCategory<'tcx> {
192 MatchImpl(cause, _) => cause.to_constraint_category(),
193 AscribeUserTypeProvePredicate(predicate_span) => {
194 ConstraintCategory::Predicate(*predicate_span)
196 _ => ConstraintCategory::BoringNoLocation,
201 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift, HashStable, TyEncodable, TyDecodable)]
202 #[derive(TypeVisitable, TypeFoldable)]
203 pub struct UnifyReceiverContext<'tcx> {
204 pub assoc_item: ty::AssocItem,
205 pub param_env: ty::ParamEnv<'tcx>,
206 pub substs: SubstsRef<'tcx>,
209 #[derive(Clone, PartialEq, Eq, Hash, Lift, Default, HashStable)]
210 #[derive(TypeVisitable, TypeFoldable, TyEncodable, TyDecodable)]
211 pub struct InternedObligationCauseCode<'tcx> {
212 /// `None` for `ObligationCauseCode::MiscObligation` (a common case, occurs ~60% of
213 /// the time). `Some` otherwise.
214 code: Option<Lrc<ObligationCauseCode<'tcx>>>,
217 impl<'tcx> std::fmt::Debug for InternedObligationCauseCode<'tcx> {
218 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
219 let cause: &ObligationCauseCode<'_> = self;
224 impl<'tcx> ObligationCauseCode<'tcx> {
226 fn into(self) -> InternedObligationCauseCode<'tcx> {
227 InternedObligationCauseCode {
228 code: if let ObligationCauseCode::MiscObligation = self {
237 impl<'tcx> std::ops::Deref for InternedObligationCauseCode<'tcx> {
238 type Target = ObligationCauseCode<'tcx>;
240 fn deref(&self) -> &Self::Target {
241 self.code.as_deref().unwrap_or(&ObligationCauseCode::MiscObligation)
245 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift, HashStable, TyEncodable, TyDecodable)]
246 #[derive(TypeVisitable, TypeFoldable)]
247 pub enum ObligationCauseCode<'tcx> {
248 /// Not well classified or should be obvious from the span.
251 /// A slice or array is WF only if `T: Sized`.
254 /// A tuple is WF only if its middle elements are `Sized`.
257 /// This is the trait reference from the given projection.
258 ProjectionWf(ty::AliasTy<'tcx>),
260 /// Must satisfy all of the where-clause predicates of the
262 ItemObligation(DefId),
264 /// Like `ItemObligation`, but carries the span of the
265 /// predicate when it can be identified.
266 BindingObligation(DefId, Span),
268 /// Like `ItemObligation`, but carries the `HirId` of the
269 /// expression that caused the obligation, and the `usize`
270 /// indicates exactly which predicate it is in the list of
271 /// instantiated predicates.
272 ExprItemObligation(DefId, rustc_hir::HirId, usize),
274 /// Combines `ExprItemObligation` and `BindingObligation`.
275 ExprBindingObligation(DefId, Span, rustc_hir::HirId, usize),
277 /// A type like `&'a T` is WF only if `T: 'a`.
278 ReferenceOutlivesReferent(Ty<'tcx>),
280 /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
281 ObjectTypeBound(Ty<'tcx>, ty::Region<'tcx>),
283 /// Obligation incurred due to an object cast.
284 ObjectCastObligation(/* Concrete type */ Ty<'tcx>, /* Object type */ Ty<'tcx>),
286 /// Obligation incurred due to a coercion.
292 /// Various cases where expressions must be `Sized` / `Copy` / etc.
293 /// `L = X` implies that `L` is `Sized`.
295 /// `(x1, .., xn)` must be `Sized`.
296 TupleInitializerSized,
297 /// `S { ... }` must be `Sized`.
298 StructInitializerSized,
299 /// Type of each variable must be `Sized`.
300 VariableType(hir::HirId),
301 /// Argument type must be `Sized`.
302 SizedArgumentType(Option<Span>),
303 /// Return type must be `Sized`.
305 /// Yield type must be `Sized`.
307 /// Box expression result type must be `Sized`.
309 /// Inline asm operand type must be `Sized`.
311 /// `[expr; N]` requires `type_of(expr): Copy`.
313 /// If element is a `const fn` we display a help message suggesting to move the
314 /// function call to a new `const` item while saying that `T` doesn't implement `Copy`.
318 /// Types of fields (other than the last, except for packed structs) in a struct must be sized.
325 /// Constant expressions must be sized.
328 /// `static` items must have `Sync` type.
331 BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
333 ImplDerivedObligation(Box<ImplDerivedObligationCause<'tcx>>),
335 DerivedObligation(DerivedObligationCause<'tcx>),
337 FunctionArgumentObligation {
338 /// The node of the relevant argument in the function call.
339 arg_hir_id: hir::HirId,
340 /// The node of the function call.
341 call_hir_id: hir::HirId,
342 /// The obligation introduced by this argument.
343 parent_code: InternedObligationCauseCode<'tcx>,
346 /// Error derived when matching traits/impls; see ObligationCause for more details
347 CompareImplItemObligation {
348 impl_item_def_id: LocalDefId,
349 trait_item_def_id: DefId,
353 /// Checking that the bounds of a trait's associated type hold for a given impl
354 CheckAssociatedTypeBounds {
355 impl_item_def_id: LocalDefId,
356 trait_item_def_id: DefId,
359 /// Checking that this expression can be assigned to its target.
362 /// Computing common supertype in the arms of a match expression
363 MatchExpressionArm(Box<MatchExpressionArmCause<'tcx>>),
365 /// Type error arising from type checking a pattern against an expected type.
367 /// The span of the scrutinee or type expression which caused the `root_ty` type.
369 /// The root expected type induced by a scrutinee or type expression.
371 /// Whether the `Span` came from an expression or a type expression.
375 /// Constants in patterns must have `Structural` type.
376 ConstPatternStructural,
378 /// Computing common supertype in an if expression
379 IfExpression(Box<IfExpressionCause<'tcx>>),
381 /// Computing common supertype of an if expression with no else counter-part
382 IfExpressionWithNoElse,
384 /// `main` has wrong type
387 /// `start` has wrong type
390 /// Intrinsic has wrong type
393 /// A let else block does not diverge
399 UnifyReceiver(Box<UnifyReceiverContext<'tcx>>),
401 /// `return` with no expression
404 /// `return` with an expression
405 ReturnValue(hir::HirId),
407 /// Return type of this function
410 /// Opaque return type of this function
411 OpaqueReturnType(Option<(Ty<'tcx>, Span)>),
413 /// Block implicit return
414 BlockTailExpression(hir::HirId),
416 /// #[feature(trivial_bounds)] is not enabled
419 /// If `X` is the concrete type of an opaque type `impl Y`, then `X` must implement `Y`
422 AwaitableExpr(Option<hir::HirId>),
428 /// Well-formed checking. If a `WellFormedLoc` is provided,
429 /// then it will be used to perform HIR-based wf checking
430 /// after an error occurs, in order to generate a more precise error span.
431 /// This is purely for diagnostic purposes - it is always
432 /// correct to use `MiscObligation` instead, or to specify
433 /// `WellFormed(None)`
434 WellFormed(Option<WellFormedLoc>),
436 /// From `match_impl`. The cause for us having to match an impl, and the DefId we are matching against.
437 MatchImpl(ObligationCause<'tcx>, DefId),
440 rhs_span: Option<Span>,
442 output_ty: Option<Ty<'tcx>>,
445 AscribeUserTypeProvePredicate(Span),
450 /// The 'location' at which we try to perform HIR-based wf checking.
451 /// This information is used to obtain an `hir::Ty`, which
452 /// we can walk in order to obtain precise spans for any
453 /// 'nested' types (e.g. `Foo` in `Option<Foo>`).
454 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable, Encodable, Decodable)]
455 #[derive(TypeVisitable, TypeFoldable)]
456 pub enum WellFormedLoc {
457 /// Use the type of the provided definition.
459 /// Use the type of the parameter of the provided function.
460 /// We cannot use `hir::Param`, since the function may
461 /// not have a body (e.g. a trait method definition)
463 /// The function to lookup the parameter in
464 function: LocalDefId,
465 /// The index of the parameter to use.
466 /// Parameters are indexed from 0, with the return type
467 /// being the last 'parameter'
472 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift, HashStable, TyEncodable, TyDecodable)]
473 #[derive(TypeVisitable, TypeFoldable)]
474 pub struct ImplDerivedObligationCause<'tcx> {
475 pub derived: DerivedObligationCause<'tcx>,
476 pub impl_def_id: DefId,
480 impl<'tcx> ObligationCauseCode<'tcx> {
481 /// Returns the base obligation, ignoring derived obligations.
482 pub fn peel_derives(&self) -> &Self {
483 let mut base_cause = self;
484 while let Some((parent_code, _)) = base_cause.parent() {
485 base_cause = parent_code;
490 pub fn parent(&self) -> Option<(&Self, Option<ty::PolyTraitPredicate<'tcx>>)> {
492 FunctionArgumentObligation { parent_code, .. } => Some((parent_code, None)),
493 BuiltinDerivedObligation(derived)
494 | DerivedObligation(derived)
495 | ImplDerivedObligation(box ImplDerivedObligationCause { derived, .. }) => {
496 Some((&derived.parent_code, Some(derived.parent_trait_pred)))
502 pub fn peel_match_impls(&self) -> &Self {
504 MatchImpl(cause, _) => cause.code(),
510 // `ObligationCauseCode` is used a lot. Make sure it doesn't unintentionally get bigger.
511 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
512 static_assert_size!(ObligationCauseCode<'_>, 48);
514 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
515 pub enum StatementAsExpression {
520 impl<'tcx> ty::Lift<'tcx> for StatementAsExpression {
521 type Lifted = StatementAsExpression;
522 fn lift_to_tcx(self, _tcx: TyCtxt<'tcx>) -> Option<StatementAsExpression> {
527 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift, HashStable, TyEncodable, TyDecodable)]
528 #[derive(TypeVisitable, TypeFoldable)]
529 pub struct MatchExpressionArmCause<'tcx> {
530 pub arm_block_id: Option<hir::HirId>,
531 pub arm_ty: Ty<'tcx>,
533 pub prior_arm_block_id: Option<hir::HirId>,
534 pub prior_arm_ty: Ty<'tcx>,
535 pub prior_arm_span: Span,
536 pub scrut_span: Span,
537 pub source: hir::MatchSource,
538 pub prior_arms: Vec<Span>,
539 pub scrut_hir_id: hir::HirId,
540 pub opt_suggest_box_span: Option<Span>,
543 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
544 #[derive(Lift, TypeFoldable, TypeVisitable, HashStable, TyEncodable, TyDecodable)]
545 pub struct IfExpressionCause<'tcx> {
546 pub then_id: hir::HirId,
547 pub else_id: hir::HirId,
548 pub then_ty: Ty<'tcx>,
549 pub else_ty: Ty<'tcx>,
550 pub outer_span: Option<Span>,
551 pub opt_suggest_box_span: Option<Span>,
554 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift, HashStable, TyEncodable, TyDecodable)]
555 #[derive(TypeVisitable, TypeFoldable)]
556 pub struct DerivedObligationCause<'tcx> {
557 /// The trait predicate of the parent obligation that led to the
558 /// current obligation. Note that only trait obligations lead to
559 /// derived obligations, so we just store the trait predicate here
561 pub parent_trait_pred: ty::PolyTraitPredicate<'tcx>,
563 /// The parent trait had this cause.
564 pub parent_code: InternedObligationCauseCode<'tcx>,
567 #[derive(Clone, Debug, TypeFoldable, TypeVisitable, Lift)]
568 pub enum SelectionError<'tcx> {
569 /// The trait is not implemented.
571 /// After a closure impl has selected, its "outputs" were evaluated
572 /// (which for closures includes the "input" type params) and they
573 /// didn't resolve. See `confirm_poly_trait_refs` for more.
574 OutputTypeParameterMismatch(
575 ty::PolyTraitRef<'tcx>,
576 ty::PolyTraitRef<'tcx>,
577 ty::error::TypeError<'tcx>,
579 /// The trait pointed by `DefId` is not object safe.
580 TraitNotObjectSafe(DefId),
581 /// A given constant couldn't be evaluated.
582 NotConstEvaluatable(NotConstEvaluatable),
583 /// Exceeded the recursion depth during type projection.
584 Overflow(OverflowError),
585 /// Signaling that an error has already been emitted, to avoid
586 /// multiple errors being shown.
590 /// When performing resolution, it is typically the case that there
591 /// can be one of three outcomes:
593 /// - `Ok(Some(r))`: success occurred with result `r`
594 /// - `Ok(None)`: could not definitely determine anything, usually due
595 /// to inconclusive type inference.
596 /// - `Err(e)`: error `e` occurred
597 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
599 /// Given the successful resolution of an obligation, the `ImplSource`
600 /// indicates where the impl comes from.
602 /// For example, the obligation may be satisfied by a specific impl (case A),
603 /// or it may be relative to some bound that is in scope (case B).
605 /// ```ignore (illustrative)
606 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
607 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
608 /// impl Clone for i32 { ... } // Impl_3
610 /// fn foo<T: Clone>(concrete: Option<Box<i32>>, param: T, mixed: Option<T>) {
611 /// // Case A: ImplSource points at a specific impl. Only possible when
612 /// // type is concretely known. If the impl itself has bounded
613 /// // type parameters, ImplSource will carry resolutions for those as well:
614 /// concrete.clone(); // ImplSource(Impl_1, [ImplSource(Impl_2, [ImplSource(Impl_3)])])
616 /// // Case B: ImplSource must be provided by caller. This applies when
617 /// // type is a type parameter.
618 /// param.clone(); // ImplSource::Param
620 /// // Case C: A mix of cases A and B.
621 /// mixed.clone(); // ImplSource(Impl_1, [ImplSource::Param])
625 /// ### The type parameter `N`
627 /// See explanation on `ImplSourceUserDefinedData`.
628 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
629 #[derive(TypeFoldable, TypeVisitable)]
630 pub enum ImplSource<'tcx, N> {
631 /// ImplSource identifying a particular impl.
632 UserDefined(ImplSourceUserDefinedData<'tcx, N>),
634 /// ImplSource for auto trait implementations.
635 /// This carries the information and nested obligations with regards
636 /// to an auto implementation for a trait `Trait`. The nested obligations
637 /// ensure the trait implementation holds for all the constituent types.
638 AutoImpl(ImplSourceAutoImplData<N>),
640 /// Successful resolution to an obligation provided by the caller
641 /// for some type parameter. The `Vec<N>` represents the
642 /// obligations incurred from normalizing the where-clause (if
644 Param(Vec<N>, ty::BoundConstness),
646 /// Virtual calls through an object.
647 Object(ImplSourceObjectData<'tcx, N>),
649 /// Successful resolution for a builtin trait.
650 Builtin(ImplSourceBuiltinData<N>),
652 /// ImplSource for trait upcasting coercion
653 TraitUpcasting(ImplSourceTraitUpcastingData<'tcx, N>),
655 /// ImplSource automatically generated for a closure. The `DefId` is the ID
656 /// of the closure expression. This is an `ImplSource::UserDefined` in spirit, but the
657 /// impl is generated by the compiler and does not appear in the source.
658 Closure(ImplSourceClosureData<'tcx, N>),
660 /// Same as above, but for a function pointer type with the given signature.
661 FnPointer(ImplSourceFnPointerData<'tcx, N>),
663 /// ImplSource automatically generated for a generator.
664 Generator(ImplSourceGeneratorData<'tcx, N>),
666 /// ImplSource automatically generated for a generator backing an async future.
667 Future(ImplSourceFutureData<'tcx, N>),
669 /// ImplSource for a trait alias.
670 TraitAlias(ImplSourceTraitAliasData<'tcx, N>),
672 /// ImplSource for a `const Drop` implementation.
673 ConstDestruct(ImplSourceConstDestructData<N>),
676 impl<'tcx, N> ImplSource<'tcx, N> {
677 pub fn nested_obligations(self) -> Vec<N> {
679 ImplSource::UserDefined(i) => i.nested,
680 ImplSource::Param(n, _) => n,
681 ImplSource::Builtin(i) => i.nested,
682 ImplSource::AutoImpl(d) => d.nested,
683 ImplSource::Closure(c) => c.nested,
684 ImplSource::Generator(c) => c.nested,
685 ImplSource::Future(c) => c.nested,
686 ImplSource::Object(d) => d.nested,
687 ImplSource::FnPointer(d) => d.nested,
688 ImplSource::TraitAlias(d) => d.nested,
689 ImplSource::TraitUpcasting(d) => d.nested,
690 ImplSource::ConstDestruct(i) => i.nested,
694 pub fn borrow_nested_obligations(&self) -> &[N] {
696 ImplSource::UserDefined(i) => &i.nested[..],
697 ImplSource::Param(n, _) => &n,
698 ImplSource::Builtin(i) => &i.nested,
699 ImplSource::AutoImpl(d) => &d.nested,
700 ImplSource::Closure(c) => &c.nested,
701 ImplSource::Generator(c) => &c.nested,
702 ImplSource::Future(c) => &c.nested,
703 ImplSource::Object(d) => &d.nested,
704 ImplSource::FnPointer(d) => &d.nested,
705 ImplSource::TraitAlias(d) => &d.nested,
706 ImplSource::TraitUpcasting(d) => &d.nested,
707 ImplSource::ConstDestruct(i) => &i.nested,
711 pub fn map<M, F>(self, f: F) -> ImplSource<'tcx, M>
716 ImplSource::UserDefined(i) => ImplSource::UserDefined(ImplSourceUserDefinedData {
717 impl_def_id: i.impl_def_id,
719 nested: i.nested.into_iter().map(f).collect(),
721 ImplSource::Param(n, ct) => ImplSource::Param(n.into_iter().map(f).collect(), ct),
722 ImplSource::Builtin(i) => ImplSource::Builtin(ImplSourceBuiltinData {
723 nested: i.nested.into_iter().map(f).collect(),
725 ImplSource::Object(o) => ImplSource::Object(ImplSourceObjectData {
726 upcast_trait_ref: o.upcast_trait_ref,
727 vtable_base: o.vtable_base,
728 nested: o.nested.into_iter().map(f).collect(),
730 ImplSource::AutoImpl(d) => ImplSource::AutoImpl(ImplSourceAutoImplData {
731 trait_def_id: d.trait_def_id,
732 nested: d.nested.into_iter().map(f).collect(),
734 ImplSource::Closure(c) => ImplSource::Closure(ImplSourceClosureData {
735 closure_def_id: c.closure_def_id,
737 nested: c.nested.into_iter().map(f).collect(),
739 ImplSource::Generator(c) => ImplSource::Generator(ImplSourceGeneratorData {
740 generator_def_id: c.generator_def_id,
742 nested: c.nested.into_iter().map(f).collect(),
744 ImplSource::Future(c) => ImplSource::Future(ImplSourceFutureData {
745 generator_def_id: c.generator_def_id,
747 nested: c.nested.into_iter().map(f).collect(),
749 ImplSource::FnPointer(p) => ImplSource::FnPointer(ImplSourceFnPointerData {
751 nested: p.nested.into_iter().map(f).collect(),
753 ImplSource::TraitAlias(d) => ImplSource::TraitAlias(ImplSourceTraitAliasData {
754 alias_def_id: d.alias_def_id,
756 nested: d.nested.into_iter().map(f).collect(),
758 ImplSource::TraitUpcasting(d) => {
759 ImplSource::TraitUpcasting(ImplSourceTraitUpcastingData {
760 upcast_trait_ref: d.upcast_trait_ref,
761 vtable_vptr_slot: d.vtable_vptr_slot,
762 nested: d.nested.into_iter().map(f).collect(),
765 ImplSource::ConstDestruct(i) => {
766 ImplSource::ConstDestruct(ImplSourceConstDestructData {
767 nested: i.nested.into_iter().map(f).collect(),
774 /// Identifies a particular impl in the source, along with a set of
775 /// substitutions from the impl's type/lifetime parameters. The
776 /// `nested` vector corresponds to the nested obligations attached to
777 /// the impl's type parameters.
779 /// The type parameter `N` indicates the type used for "nested
780 /// obligations" that are required by the impl. During type-check, this
781 /// is `Obligation`, as one might expect. During codegen, however, this
782 /// is `()`, because codegen only requires a shallow resolution of an
783 /// impl, and nested obligations are satisfied later.
784 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
785 #[derive(TypeFoldable, TypeVisitable)]
786 pub struct ImplSourceUserDefinedData<'tcx, N> {
787 pub impl_def_id: DefId,
788 pub substs: SubstsRef<'tcx>,
792 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
793 #[derive(TypeFoldable, TypeVisitable)]
794 pub struct ImplSourceGeneratorData<'tcx, N> {
795 pub generator_def_id: DefId,
796 pub substs: SubstsRef<'tcx>,
797 /// Nested obligations. This can be non-empty if the generator
798 /// signature contains associated types.
802 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
803 #[derive(TypeFoldable, TypeVisitable)]
804 pub struct ImplSourceFutureData<'tcx, N> {
805 pub generator_def_id: DefId,
806 pub substs: SubstsRef<'tcx>,
807 /// Nested obligations. This can be non-empty if the generator
808 /// signature contains associated types.
812 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
813 #[derive(TypeFoldable, TypeVisitable)]
814 pub struct ImplSourceClosureData<'tcx, N> {
815 pub closure_def_id: DefId,
816 pub substs: SubstsRef<'tcx>,
817 /// Nested obligations. This can be non-empty if the closure
818 /// signature contains associated types.
822 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
823 #[derive(TypeFoldable, TypeVisitable)]
824 pub struct ImplSourceAutoImplData<N> {
825 pub trait_def_id: DefId,
829 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
830 #[derive(TypeFoldable, TypeVisitable)]
831 pub struct ImplSourceTraitUpcastingData<'tcx, N> {
832 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
833 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
835 /// The vtable is formed by concatenating together the method lists of
836 /// the base object trait and all supertraits, pointers to supertrait vtable will
837 /// be provided when necessary; this is the position of `upcast_trait_ref`'s vtable
838 /// within that vtable.
839 pub vtable_vptr_slot: Option<usize>,
844 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
845 #[derive(TypeFoldable, TypeVisitable)]
846 pub struct ImplSourceBuiltinData<N> {
850 #[derive(PartialEq, Eq, Clone, TyEncodable, TyDecodable, HashStable, Lift)]
851 #[derive(TypeFoldable, TypeVisitable)]
852 pub struct ImplSourceObjectData<'tcx, N> {
853 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
854 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
856 /// The vtable is formed by concatenating together the method lists of
857 /// the base object trait and all supertraits, pointers to supertrait vtable will
858 /// be provided when necessary; this is the start of `upcast_trait_ref`'s methods
860 pub vtable_base: usize,
865 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
866 #[derive(TypeFoldable, TypeVisitable)]
867 pub struct ImplSourceFnPointerData<'tcx, N> {
872 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
873 #[derive(TypeFoldable, TypeVisitable)]
874 pub struct ImplSourceConstDestructData<N> {
878 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
879 #[derive(TypeFoldable, TypeVisitable)]
880 pub struct ImplSourceTraitAliasData<'tcx, N> {
881 pub alias_def_id: DefId,
882 pub substs: SubstsRef<'tcx>,
886 #[derive(Clone, Debug, PartialEq, Eq, Hash, HashStable, PartialOrd, Ord)]
887 pub enum ObjectSafetyViolation {
888 /// `Self: Sized` declared on the trait.
889 SizedSelf(SmallVec<[Span; 1]>),
891 /// Supertrait reference references `Self` an in illegal location
892 /// (e.g., `trait Foo : Bar<Self>`).
893 SupertraitSelf(SmallVec<[Span; 1]>),
895 /// Method has something illegal.
896 Method(Symbol, MethodViolationCode, Span),
898 /// Associated const.
899 AssocConst(Symbol, Span),
905 impl ObjectSafetyViolation {
906 pub fn error_msg(&self) -> Cow<'static, str> {
908 ObjectSafetyViolation::SizedSelf(_) => "it requires `Self: Sized`".into(),
909 ObjectSafetyViolation::SupertraitSelf(ref spans) => {
910 if spans.iter().any(|sp| *sp != DUMMY_SP) {
911 "it uses `Self` as a type parameter".into()
913 "it cannot use `Self` as a type parameter in a supertrait or `where`-clause"
917 ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod(_), _) => {
918 format!("associated function `{}` has no `self` parameter", name).into()
920 ObjectSafetyViolation::Method(
922 MethodViolationCode::ReferencesSelfInput(_),
924 ) => format!("method `{}` references the `Self` type in its parameters", name).into(),
925 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfInput(_), _) => {
926 format!("method `{}` references the `Self` type in this parameter", name).into()
928 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfOutput, _) => {
929 format!("method `{}` references the `Self` type in its return type", name).into()
931 ObjectSafetyViolation::Method(
933 MethodViolationCode::ReferencesImplTraitInTrait(_),
935 ) => format!("method `{}` references an `impl Trait` type in its return type", name)
937 ObjectSafetyViolation::Method(name, MethodViolationCode::AsyncFn, _) => {
938 format!("method `{}` is `async`", name).into()
940 ObjectSafetyViolation::Method(
942 MethodViolationCode::WhereClauseReferencesSelf,
945 format!("method `{}` references the `Self` type in its `where` clause", name).into()
947 ObjectSafetyViolation::Method(name, MethodViolationCode::Generic, _) => {
948 format!("method `{}` has generic type parameters", name).into()
950 ObjectSafetyViolation::Method(
952 MethodViolationCode::UndispatchableReceiver(_),
954 ) => format!("method `{}`'s `self` parameter cannot be dispatched on", name).into(),
955 ObjectSafetyViolation::AssocConst(name, DUMMY_SP) => {
956 format!("it contains associated `const` `{}`", name).into()
958 ObjectSafetyViolation::AssocConst(..) => "it contains this associated `const`".into(),
959 ObjectSafetyViolation::GAT(name, _) => {
960 format!("it contains the generic associated type `{}`", name).into()
965 pub fn solution(&self, err: &mut Diagnostic) {
967 ObjectSafetyViolation::SizedSelf(_) | ObjectSafetyViolation::SupertraitSelf(_) => {}
968 ObjectSafetyViolation::Method(
970 MethodViolationCode::StaticMethod(Some((add_self_sugg, make_sized_sugg))),
976 "consider turning `{}` into a method by giving it a `&self` argument",
979 add_self_sugg.0.to_string(),
980 Applicability::MaybeIncorrect,
985 "alternatively, consider constraining `{}` so it does not apply to \
989 make_sized_sugg.0.to_string(),
990 Applicability::MaybeIncorrect,
993 ObjectSafetyViolation::Method(
995 MethodViolationCode::UndispatchableReceiver(Some(span)),
1001 "consider changing method `{}`'s `self` parameter to be `&self`",
1005 Applicability::MachineApplicable,
1008 ObjectSafetyViolation::AssocConst(name, _)
1009 | ObjectSafetyViolation::GAT(name, _)
1010 | ObjectSafetyViolation::Method(name, ..) => {
1011 err.help(&format!("consider moving `{}` to another trait", name));
1016 pub fn spans(&self) -> SmallVec<[Span; 1]> {
1017 // When `span` comes from a separate crate, it'll be `DUMMY_SP`. Treat it as `None` so
1018 // diagnostics use a `note` instead of a `span_label`.
1020 ObjectSafetyViolation::SupertraitSelf(spans)
1021 | ObjectSafetyViolation::SizedSelf(spans) => spans.clone(),
1022 ObjectSafetyViolation::AssocConst(_, span)
1023 | ObjectSafetyViolation::GAT(_, span)
1024 | ObjectSafetyViolation::Method(_, _, span)
1025 if *span != DUMMY_SP =>
1034 /// Reasons a method might not be object-safe.
1035 #[derive(Clone, Debug, PartialEq, Eq, Hash, HashStable, PartialOrd, Ord)]
1036 pub enum MethodViolationCode {
1037 /// e.g., `fn foo()`
1038 StaticMethod(Option<(/* add &self */ (String, Span), /* add Self: Sized */ (String, Span))>),
1040 /// e.g., `fn foo(&self, x: Self)`
1041 ReferencesSelfInput(Option<Span>),
1043 /// e.g., `fn foo(&self) -> Self`
1044 ReferencesSelfOutput,
1046 /// e.g., `fn foo(&self) -> impl Sized`
1047 ReferencesImplTraitInTrait(Span),
1049 /// e.g., `async fn foo(&self)`
1052 /// e.g., `fn foo(&self) where Self: Clone`
1053 WhereClauseReferencesSelf,
1055 /// e.g., `fn foo<A>()`
1058 /// the method's receiver (`self` argument) can't be dispatched on
1059 UndispatchableReceiver(Option<Span>),
1062 /// These are the error cases for `codegen_select_candidate`.
1063 #[derive(Copy, Clone, Debug, Hash, HashStable, Encodable, Decodable)]
1064 pub enum CodegenObligationError {
1065 /// Ambiguity can happen when monomorphizing during trans
1066 /// expands to some humongous type that never occurred
1067 /// statically -- this humongous type can then overflow,
1068 /// leading to an ambiguous result. So report this as an
1069 /// overflow bug, since I believe this is the only case
1070 /// where ambiguity can result.
1072 /// This can trigger when we probe for the source of a `'static` lifetime requirement
1073 /// on a trait object: `impl Foo for dyn Trait {}` has an implicit `'static` bound.
1074 /// This can also trigger when we have a global bound that is not actually satisfied,
1075 /// but was included during typeck due to the trivial_bounds feature.