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
9 pub mod specialization_graph;
13 use crate::infer::canonical::Canonical;
14 use crate::mir::ConstraintCategory;
15 use crate::ty::abstract_const::NotConstEvaluatable;
16 use crate::ty::subst::SubstsRef;
17 use crate::ty::{self, AdtKind, Ty, TyCtxt};
19 use rustc_data_structures::sync::Lrc;
20 use rustc_errors::{Applicability, Diagnostic};
22 use rustc_hir::def_id::DefId;
23 use rustc_span::def_id::{LocalDefId, CRATE_DEF_ID};
24 use rustc_span::symbol::Symbol;
25 use rustc_span::{Span, DUMMY_SP};
26 use smallvec::SmallVec;
29 use std::hash::{Hash, Hasher};
31 pub use self::select::{EvaluationCache, EvaluationResult, OverflowError, SelectionCache};
33 pub type CanonicalChalkEnvironmentAndGoal<'tcx> = Canonical<'tcx, ChalkEnvironmentAndGoal<'tcx>>;
35 pub use self::ObligationCauseCode::*;
37 pub use self::chalk::{ChalkEnvironmentAndGoal, RustInterner as ChalkRustInterner};
39 /// Depending on the stage of compilation, we want projection to be
40 /// more or less conservative.
41 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, HashStable, Encodable, Decodable)]
43 /// At type-checking time, we refuse to project any associated
44 /// type that is marked `default`. Non-`default` ("final") types
45 /// are always projected. This is necessary in general for
46 /// soundness of specialization. However, we *could* allow
47 /// projections in fully-monomorphic cases. We choose not to,
48 /// because we prefer for `default type` to force the type
49 /// definition to be treated abstractly by any consumers of the
50 /// impl. Concretely, that means that the following example will
53 /// ```compile_fail,E0308
54 /// #![feature(specialization)]
59 /// impl<T> Assoc for T {
60 /// default type Output = bool;
64 /// let x: <() as Assoc>::Output = true;
68 /// We also do not reveal the hidden type of opaque types during
72 /// At codegen time, all monomorphic projections will succeed.
73 /// Also, `impl Trait` is normalized to the concrete type,
74 /// which has to be already collected by type-checking.
76 /// NOTE: as `impl Trait`'s concrete type should *never*
77 /// be observable directly by the user, `Reveal::All`
78 /// should not be used by checks which may expose
79 /// type equality or type contents to the user.
80 /// There are some exceptions, e.g., around auto traits and
81 /// transmute-checking, which expose some details, but
82 /// not the whole concrete type of the `impl Trait`.
86 /// The reason why we incurred this obligation; used for error reporting.
88 /// Non-misc `ObligationCauseCode`s are stored on the heap. This gives the
89 /// best trade-off between keeping the type small (which makes copies cheaper)
90 /// while not doing too many heap allocations.
92 /// We do not want to intern this as there are a lot of obligation causes which
93 /// only live for a short period of time.
94 #[derive(Clone, Debug, PartialEq, Eq, Lift, HashStable, TyEncodable, TyDecodable)]
95 #[derive(TypeVisitable, TypeFoldable)]
96 pub struct ObligationCause<'tcx> {
99 /// The ID of the fn body that triggered this obligation. This is
100 /// used for region obligations to determine the precise
101 /// environment in which the region obligation should be evaluated
102 /// (in particular, closures can add new assumptions). See the
103 /// field `region_obligations` of the `FulfillmentContext` for more
105 pub body_id: LocalDefId,
107 code: InternedObligationCauseCode<'tcx>,
110 // This custom hash function speeds up hashing for `Obligation` deduplication
111 // greatly by skipping the `code` field, which can be large and complex. That
112 // shouldn't affect hash quality much since there are several other fields in
113 // `Obligation` which should be unique enough, especially the predicate itself
114 // which is hashed as an interned pointer. See #90996.
115 impl Hash for ObligationCause<'_> {
116 fn hash<H: Hasher>(&self, state: &mut H) {
117 self.body_id.hash(state);
118 self.span.hash(state);
122 impl<'tcx> ObligationCause<'tcx> {
127 code: ObligationCauseCode<'tcx>,
128 ) -> ObligationCause<'tcx> {
129 ObligationCause { span, body_id, code: code.into() }
132 pub fn misc(span: Span, body_id: LocalDefId) -> ObligationCause<'tcx> {
133 ObligationCause::new(span, body_id, MiscObligation)
137 pub fn dummy() -> ObligationCause<'tcx> {
138 ObligationCause::dummy_with_span(DUMMY_SP)
142 pub fn dummy_with_span(span: Span) -> ObligationCause<'tcx> {
143 ObligationCause { span, body_id: CRATE_DEF_ID, code: Default::default() }
146 pub fn span(&self) -> Span {
148 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
157 pub fn code(&self) -> &ObligationCauseCode<'tcx> {
163 f: impl FnOnce(InternedObligationCauseCode<'tcx>) -> ObligationCauseCode<'tcx>,
165 self.code = f(std::mem::take(&mut self.code)).into();
168 pub fn derived_cause(
170 parent_trait_pred: ty::PolyTraitPredicate<'tcx>,
171 variant: impl FnOnce(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
172 ) -> ObligationCause<'tcx> {
174 * Creates a cause for obligations that are derived from
175 * `obligation` by a recursive search (e.g., for a builtin
176 * bound, or eventually a `auto trait Foo`). If `obligation`
177 * is itself a derived obligation, this is just a clone, but
178 * otherwise we create a "derived obligation" cause so as to
179 * keep track of the original root obligation for error
183 // NOTE(flaper87): As of now, it keeps track of the whole error
184 // chain. Ideally, we should have a way to configure this either
185 // by using -Z verbose or just a CLI argument.
187 variant(DerivedObligationCause { parent_trait_pred, parent_code: self.code }).into();
191 pub fn to_constraint_category(&self) -> ConstraintCategory<'tcx> {
193 MatchImpl(cause, _) => cause.to_constraint_category(),
194 AscribeUserTypeProvePredicate(predicate_span) => {
195 ConstraintCategory::Predicate(*predicate_span)
197 _ => ConstraintCategory::BoringNoLocation,
202 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift, HashStable, TyEncodable, TyDecodable)]
203 #[derive(TypeVisitable, TypeFoldable)]
204 pub struct UnifyReceiverContext<'tcx> {
205 pub assoc_item: ty::AssocItem,
206 pub param_env: ty::ParamEnv<'tcx>,
207 pub substs: SubstsRef<'tcx>,
210 #[derive(Clone, PartialEq, Eq, Hash, Lift, Default, HashStable)]
211 #[derive(TypeVisitable, TypeFoldable, TyEncodable, TyDecodable)]
212 pub struct InternedObligationCauseCode<'tcx> {
213 /// `None` for `ObligationCauseCode::MiscObligation` (a common case, occurs ~60% of
214 /// the time). `Some` otherwise.
215 code: Option<Lrc<ObligationCauseCode<'tcx>>>,
218 impl<'tcx> std::fmt::Debug for InternedObligationCauseCode<'tcx> {
219 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
220 let cause: &ObligationCauseCode<'_> = self;
225 impl<'tcx> ObligationCauseCode<'tcx> {
227 fn into(self) -> InternedObligationCauseCode<'tcx> {
228 InternedObligationCauseCode {
229 code: if let ObligationCauseCode::MiscObligation = self {
238 impl<'tcx> std::ops::Deref for InternedObligationCauseCode<'tcx> {
239 type Target = ObligationCauseCode<'tcx>;
241 fn deref(&self) -> &Self::Target {
242 self.code.as_deref().unwrap_or(&ObligationCauseCode::MiscObligation)
246 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift, HashStable, TyEncodable, TyDecodable)]
247 #[derive(TypeVisitable, TypeFoldable)]
248 pub enum ObligationCauseCode<'tcx> {
249 /// Not well classified or should be obvious from the span.
252 /// A slice or array is WF only if `T: Sized`.
255 /// A tuple is WF only if its middle elements are `Sized`.
258 /// This is the trait reference from the given projection.
259 ProjectionWf(ty::AliasTy<'tcx>),
261 /// Must satisfy all of the where-clause predicates of the
263 ItemObligation(DefId),
265 /// Like `ItemObligation`, but carries the span of the
266 /// predicate when it can be identified.
267 BindingObligation(DefId, Span),
269 /// Like `ItemObligation`, but carries the `HirId` of the
270 /// expression that caused the obligation, and the `usize`
271 /// indicates exactly which predicate it is in the list of
272 /// instantiated predicates.
273 ExprItemObligation(DefId, rustc_hir::HirId, usize),
275 /// Combines `ExprItemObligation` and `BindingObligation`.
276 ExprBindingObligation(DefId, Span, rustc_hir::HirId, usize),
278 /// A type like `&'a T` is WF only if `T: 'a`.
279 ReferenceOutlivesReferent(Ty<'tcx>),
281 /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
282 ObjectTypeBound(Ty<'tcx>, ty::Region<'tcx>),
284 /// Obligation incurred due to an object cast.
285 ObjectCastObligation(/* Concrete type */ Ty<'tcx>, /* Object type */ Ty<'tcx>),
287 /// Obligation incurred due to a coercion.
293 /// Various cases where expressions must be `Sized` / `Copy` / etc.
294 /// `L = X` implies that `L` is `Sized`.
296 /// `(x1, .., xn)` must be `Sized`.
297 TupleInitializerSized,
298 /// `S { ... }` must be `Sized`.
299 StructInitializerSized,
300 /// Type of each variable must be `Sized`.
301 VariableType(hir::HirId),
302 /// Argument type must be `Sized`.
303 SizedArgumentType(Option<Span>),
304 /// Return type must be `Sized`.
306 /// Yield type must be `Sized`.
308 /// Box expression result type must be `Sized`.
310 /// Inline asm operand type must be `Sized`.
312 /// `[expr; N]` requires `type_of(expr): Copy`.
314 /// If element is a `const fn` we display a help message suggesting to move the
315 /// function call to a new `const` item while saying that `T` doesn't implement `Copy`.
319 /// Types of fields (other than the last, except for packed structs) in a struct must be sized.
326 /// Constant expressions must be sized.
329 /// `static` items must have `Sync` type.
332 BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
334 ImplDerivedObligation(Box<ImplDerivedObligationCause<'tcx>>),
336 DerivedObligation(DerivedObligationCause<'tcx>),
338 FunctionArgumentObligation {
339 /// The node of the relevant argument in the function call.
340 arg_hir_id: hir::HirId,
341 /// The node of the function call.
342 call_hir_id: hir::HirId,
343 /// The obligation introduced by this argument.
344 parent_code: InternedObligationCauseCode<'tcx>,
347 /// Error derived when matching traits/impls; see ObligationCause for more details
348 CompareImplItemObligation {
349 impl_item_def_id: LocalDefId,
350 trait_item_def_id: DefId,
354 /// Checking that the bounds of a trait's associated type hold for a given impl
355 CheckAssociatedTypeBounds {
356 impl_item_def_id: LocalDefId,
357 trait_item_def_id: DefId,
360 /// Checking that this expression can be assigned to its target.
363 /// Computing common supertype in the arms of a match expression
364 MatchExpressionArm(Box<MatchExpressionArmCause<'tcx>>),
366 /// Type error arising from type checking a pattern against an expected type.
368 /// The span of the scrutinee or type expression which caused the `root_ty` type.
370 /// The root expected type induced by a scrutinee or type expression.
372 /// Whether the `Span` came from an expression or a type expression.
376 /// Constants in patterns must have `Structural` type.
377 ConstPatternStructural,
379 /// Computing common supertype in an if expression
380 IfExpression(Box<IfExpressionCause<'tcx>>),
382 /// Computing common supertype of an if expression with no else counter-part
383 IfExpressionWithNoElse,
385 /// `main` has wrong type
388 /// `start` has wrong type
391 /// Intrinsic has wrong type
394 /// A let else block does not diverge
400 UnifyReceiver(Box<UnifyReceiverContext<'tcx>>),
402 /// `return` with no expression
405 /// `return` with an expression
406 ReturnValue(hir::HirId),
408 /// Return type of this function
411 /// Opaque return type of this function
412 OpaqueReturnType(Option<(Ty<'tcx>, Span)>),
414 /// Block implicit return
415 BlockTailExpression(hir::HirId),
417 /// #[feature(trivial_bounds)] is not enabled
420 /// If `X` is the concrete type of an opaque type `impl Y`, then `X` must implement `Y`
423 AwaitableExpr(Option<hir::HirId>),
429 /// Well-formed checking. If a `WellFormedLoc` is provided,
430 /// then it will be used to perform HIR-based wf checking
431 /// after an error occurs, in order to generate a more precise error span.
432 /// This is purely for diagnostic purposes - it is always
433 /// correct to use `MiscObligation` instead, or to specify
434 /// `WellFormed(None)`
435 WellFormed(Option<WellFormedLoc>),
437 /// From `match_impl`. The cause for us having to match an impl, and the DefId we are matching against.
438 MatchImpl(ObligationCause<'tcx>, DefId),
441 rhs_span: Option<Span>,
443 output_ty: Option<Ty<'tcx>>,
446 AscribeUserTypeProvePredicate(Span),
451 /// The 'location' at which we try to perform HIR-based wf checking.
452 /// This information is used to obtain an `hir::Ty`, which
453 /// we can walk in order to obtain precise spans for any
454 /// 'nested' types (e.g. `Foo` in `Option<Foo>`).
455 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable, Encodable, Decodable)]
456 #[derive(TypeVisitable, TypeFoldable)]
457 pub enum WellFormedLoc {
458 /// Use the type of the provided definition.
460 /// Use the type of the parameter of the provided function.
461 /// We cannot use `hir::Param`, since the function may
462 /// not have a body (e.g. a trait method definition)
464 /// The function to lookup the parameter in
465 function: LocalDefId,
466 /// The index of the parameter to use.
467 /// Parameters are indexed from 0, with the return type
468 /// being the last 'parameter'
473 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift, HashStable, TyEncodable, TyDecodable)]
474 #[derive(TypeVisitable, TypeFoldable)]
475 pub struct ImplDerivedObligationCause<'tcx> {
476 pub derived: DerivedObligationCause<'tcx>,
477 pub impl_def_id: DefId,
481 impl<'tcx> ObligationCauseCode<'tcx> {
482 /// Returns the base obligation, ignoring derived obligations.
483 pub fn peel_derives(&self) -> &Self {
484 let mut base_cause = self;
485 while let Some((parent_code, _)) = base_cause.parent() {
486 base_cause = parent_code;
491 pub fn parent(&self) -> Option<(&Self, Option<ty::PolyTraitPredicate<'tcx>>)> {
493 FunctionArgumentObligation { parent_code, .. } => Some((parent_code, None)),
494 BuiltinDerivedObligation(derived)
495 | DerivedObligation(derived)
496 | ImplDerivedObligation(box ImplDerivedObligationCause { derived, .. }) => {
497 Some((&derived.parent_code, Some(derived.parent_trait_pred)))
503 pub fn peel_match_impls(&self) -> &Self {
505 MatchImpl(cause, _) => cause.code(),
511 // `ObligationCauseCode` is used a lot. Make sure it doesn't unintentionally get bigger.
512 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
513 static_assert_size!(ObligationCauseCode<'_>, 48);
515 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
516 pub enum StatementAsExpression {
521 impl<'tcx> ty::Lift<'tcx> for StatementAsExpression {
522 type Lifted = StatementAsExpression;
523 fn lift_to_tcx(self, _tcx: TyCtxt<'tcx>) -> Option<StatementAsExpression> {
528 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift, HashStable, TyEncodable, TyDecodable)]
529 #[derive(TypeVisitable, TypeFoldable)]
530 pub struct MatchExpressionArmCause<'tcx> {
531 pub arm_block_id: Option<hir::HirId>,
532 pub arm_ty: Ty<'tcx>,
534 pub prior_arm_block_id: Option<hir::HirId>,
535 pub prior_arm_ty: Ty<'tcx>,
536 pub prior_arm_span: Span,
537 pub scrut_span: Span,
538 pub source: hir::MatchSource,
539 pub prior_arms: Vec<Span>,
540 pub scrut_hir_id: hir::HirId,
541 pub opt_suggest_box_span: Option<Span>,
544 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
545 #[derive(Lift, TypeFoldable, TypeVisitable, HashStable, TyEncodable, TyDecodable)]
546 pub struct IfExpressionCause<'tcx> {
547 pub then_id: hir::HirId,
548 pub else_id: hir::HirId,
549 pub then_ty: Ty<'tcx>,
550 pub else_ty: Ty<'tcx>,
551 pub outer_span: Option<Span>,
552 pub opt_suggest_box_span: Option<Span>,
555 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift, HashStable, TyEncodable, TyDecodable)]
556 #[derive(TypeVisitable, TypeFoldable)]
557 pub struct DerivedObligationCause<'tcx> {
558 /// The trait predicate of the parent obligation that led to the
559 /// current obligation. Note that only trait obligations lead to
560 /// derived obligations, so we just store the trait predicate here
562 pub parent_trait_pred: ty::PolyTraitPredicate<'tcx>,
564 /// The parent trait had this cause.
565 pub parent_code: InternedObligationCauseCode<'tcx>,
568 #[derive(Clone, Debug, TypeFoldable, TypeVisitable, Lift)]
569 pub enum SelectionError<'tcx> {
570 /// The trait is not implemented.
572 /// After a closure impl has selected, its "outputs" were evaluated
573 /// (which for closures includes the "input" type params) and they
574 /// didn't resolve. See `confirm_poly_trait_refs` for more.
575 OutputTypeParameterMismatch(
576 ty::PolyTraitRef<'tcx>,
577 ty::PolyTraitRef<'tcx>,
578 ty::error::TypeError<'tcx>,
580 /// The trait pointed by `DefId` is not object safe.
581 TraitNotObjectSafe(DefId),
582 /// A given constant couldn't be evaluated.
583 NotConstEvaluatable(NotConstEvaluatable),
584 /// Exceeded the recursion depth during type projection.
585 Overflow(OverflowError),
586 /// Signaling that an error has already been emitted, to avoid
587 /// multiple errors being shown.
591 /// When performing resolution, it is typically the case that there
592 /// can be one of three outcomes:
594 /// - `Ok(Some(r))`: success occurred with result `r`
595 /// - `Ok(None)`: could not definitely determine anything, usually due
596 /// to inconclusive type inference.
597 /// - `Err(e)`: error `e` occurred
598 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
600 /// Given the successful resolution of an obligation, the `ImplSource`
601 /// indicates where the impl comes from.
603 /// For example, the obligation may be satisfied by a specific impl (case A),
604 /// or it may be relative to some bound that is in scope (case B).
606 /// ```ignore (illustrative)
607 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
608 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
609 /// impl Clone for i32 { ... } // Impl_3
611 /// fn foo<T: Clone>(concrete: Option<Box<i32>>, param: T, mixed: Option<T>) {
612 /// // Case A: ImplSource points at a specific impl. Only possible when
613 /// // type is concretely known. If the impl itself has bounded
614 /// // type parameters, ImplSource will carry resolutions for those as well:
615 /// concrete.clone(); // ImplSource(Impl_1, [ImplSource(Impl_2, [ImplSource(Impl_3)])])
617 /// // Case B: ImplSource must be provided by caller. This applies when
618 /// // type is a type parameter.
619 /// param.clone(); // ImplSource::Param
621 /// // Case C: A mix of cases A and B.
622 /// mixed.clone(); // ImplSource(Impl_1, [ImplSource::Param])
626 /// ### The type parameter `N`
628 /// See explanation on `ImplSourceUserDefinedData`.
629 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
630 #[derive(TypeFoldable, TypeVisitable)]
631 pub enum ImplSource<'tcx, N> {
632 /// ImplSource identifying a particular impl.
633 UserDefined(ImplSourceUserDefinedData<'tcx, N>),
635 /// ImplSource for auto trait implementations.
636 /// This carries the information and nested obligations with regards
637 /// to an auto implementation for a trait `Trait`. The nested obligations
638 /// ensure the trait implementation holds for all the constituent types.
639 AutoImpl(ImplSourceAutoImplData<N>),
641 /// Successful resolution to an obligation provided by the caller
642 /// for some type parameter. The `Vec<N>` represents the
643 /// obligations incurred from normalizing the where-clause (if
645 Param(Vec<N>, ty::BoundConstness),
647 /// Virtual calls through an object.
648 Object(ImplSourceObjectData<'tcx, N>),
650 /// Successful resolution for a builtin trait.
651 Builtin(ImplSourceBuiltinData<N>),
653 /// ImplSource for trait upcasting coercion
654 TraitUpcasting(ImplSourceTraitUpcastingData<'tcx, N>),
656 /// ImplSource automatically generated for a closure. The `DefId` is the ID
657 /// of the closure expression. This is an `ImplSource::UserDefined` in spirit, but the
658 /// impl is generated by the compiler and does not appear in the source.
659 Closure(ImplSourceClosureData<'tcx, N>),
661 /// Same as above, but for a function pointer type with the given signature.
662 FnPointer(ImplSourceFnPointerData<'tcx, N>),
664 /// ImplSource automatically generated for a generator.
665 Generator(ImplSourceGeneratorData<'tcx, N>),
667 /// ImplSource automatically generated for a generator backing an async future.
668 Future(ImplSourceFutureData<'tcx, N>),
670 /// ImplSource for a trait alias.
671 TraitAlias(ImplSourceTraitAliasData<'tcx, N>),
673 /// ImplSource for a `const Drop` implementation.
674 ConstDestruct(ImplSourceConstDestructData<N>),
677 impl<'tcx, N> ImplSource<'tcx, N> {
678 pub fn nested_obligations(self) -> Vec<N> {
680 ImplSource::UserDefined(i) => i.nested,
681 ImplSource::Param(n, _) => n,
682 ImplSource::Builtin(i) => i.nested,
683 ImplSource::AutoImpl(d) => d.nested,
684 ImplSource::Closure(c) => c.nested,
685 ImplSource::Generator(c) => c.nested,
686 ImplSource::Future(c) => c.nested,
687 ImplSource::Object(d) => d.nested,
688 ImplSource::FnPointer(d) => d.nested,
689 ImplSource::TraitAlias(d) => d.nested,
690 ImplSource::TraitUpcasting(d) => d.nested,
691 ImplSource::ConstDestruct(i) => i.nested,
695 pub fn borrow_nested_obligations(&self) -> &[N] {
697 ImplSource::UserDefined(i) => &i.nested[..],
698 ImplSource::Param(n, _) => &n,
699 ImplSource::Builtin(i) => &i.nested,
700 ImplSource::AutoImpl(d) => &d.nested,
701 ImplSource::Closure(c) => &c.nested,
702 ImplSource::Generator(c) => &c.nested,
703 ImplSource::Future(c) => &c.nested,
704 ImplSource::Object(d) => &d.nested,
705 ImplSource::FnPointer(d) => &d.nested,
706 ImplSource::TraitAlias(d) => &d.nested,
707 ImplSource::TraitUpcasting(d) => &d.nested,
708 ImplSource::ConstDestruct(i) => &i.nested,
712 pub fn map<M, F>(self, f: F) -> ImplSource<'tcx, M>
717 ImplSource::UserDefined(i) => ImplSource::UserDefined(ImplSourceUserDefinedData {
718 impl_def_id: i.impl_def_id,
720 nested: i.nested.into_iter().map(f).collect(),
722 ImplSource::Param(n, ct) => ImplSource::Param(n.into_iter().map(f).collect(), ct),
723 ImplSource::Builtin(i) => ImplSource::Builtin(ImplSourceBuiltinData {
724 nested: i.nested.into_iter().map(f).collect(),
726 ImplSource::Object(o) => ImplSource::Object(ImplSourceObjectData {
727 upcast_trait_ref: o.upcast_trait_ref,
728 vtable_base: o.vtable_base,
729 nested: o.nested.into_iter().map(f).collect(),
731 ImplSource::AutoImpl(d) => ImplSource::AutoImpl(ImplSourceAutoImplData {
732 trait_def_id: d.trait_def_id,
733 nested: d.nested.into_iter().map(f).collect(),
735 ImplSource::Closure(c) => ImplSource::Closure(ImplSourceClosureData {
736 closure_def_id: c.closure_def_id,
738 nested: c.nested.into_iter().map(f).collect(),
740 ImplSource::Generator(c) => ImplSource::Generator(ImplSourceGeneratorData {
741 generator_def_id: c.generator_def_id,
743 nested: c.nested.into_iter().map(f).collect(),
745 ImplSource::Future(c) => ImplSource::Future(ImplSourceFutureData {
746 generator_def_id: c.generator_def_id,
748 nested: c.nested.into_iter().map(f).collect(),
750 ImplSource::FnPointer(p) => ImplSource::FnPointer(ImplSourceFnPointerData {
752 nested: p.nested.into_iter().map(f).collect(),
754 ImplSource::TraitAlias(d) => ImplSource::TraitAlias(ImplSourceTraitAliasData {
755 alias_def_id: d.alias_def_id,
757 nested: d.nested.into_iter().map(f).collect(),
759 ImplSource::TraitUpcasting(d) => {
760 ImplSource::TraitUpcasting(ImplSourceTraitUpcastingData {
761 upcast_trait_ref: d.upcast_trait_ref,
762 vtable_vptr_slot: d.vtable_vptr_slot,
763 nested: d.nested.into_iter().map(f).collect(),
766 ImplSource::ConstDestruct(i) => {
767 ImplSource::ConstDestruct(ImplSourceConstDestructData {
768 nested: i.nested.into_iter().map(f).collect(),
775 /// Identifies a particular impl in the source, along with a set of
776 /// substitutions from the impl's type/lifetime parameters. The
777 /// `nested` vector corresponds to the nested obligations attached to
778 /// the impl's type parameters.
780 /// The type parameter `N` indicates the type used for "nested
781 /// obligations" that are required by the impl. During type-check, this
782 /// is `Obligation`, as one might expect. During codegen, however, this
783 /// is `()`, because codegen only requires a shallow resolution of an
784 /// impl, and nested obligations are satisfied later.
785 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
786 #[derive(TypeFoldable, TypeVisitable)]
787 pub struct ImplSourceUserDefinedData<'tcx, N> {
788 pub impl_def_id: DefId,
789 pub substs: SubstsRef<'tcx>,
793 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
794 #[derive(TypeFoldable, TypeVisitable)]
795 pub struct ImplSourceGeneratorData<'tcx, N> {
796 pub generator_def_id: DefId,
797 pub substs: SubstsRef<'tcx>,
798 /// Nested obligations. This can be non-empty if the generator
799 /// signature contains associated types.
803 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
804 #[derive(TypeFoldable, TypeVisitable)]
805 pub struct ImplSourceFutureData<'tcx, N> {
806 pub generator_def_id: DefId,
807 pub substs: SubstsRef<'tcx>,
808 /// Nested obligations. This can be non-empty if the generator
809 /// signature contains associated types.
813 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
814 #[derive(TypeFoldable, TypeVisitable)]
815 pub struct ImplSourceClosureData<'tcx, N> {
816 pub closure_def_id: DefId,
817 pub substs: SubstsRef<'tcx>,
818 /// Nested obligations. This can be non-empty if the closure
819 /// signature contains associated types.
823 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
824 #[derive(TypeFoldable, TypeVisitable)]
825 pub struct ImplSourceAutoImplData<N> {
826 pub trait_def_id: DefId,
830 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
831 #[derive(TypeFoldable, TypeVisitable)]
832 pub struct ImplSourceTraitUpcastingData<'tcx, N> {
833 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
834 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
836 /// The vtable is formed by concatenating together the method lists of
837 /// the base object trait and all supertraits, pointers to supertrait vtable will
838 /// be provided when necessary; this is the position of `upcast_trait_ref`'s vtable
839 /// within that vtable.
840 pub vtable_vptr_slot: Option<usize>,
845 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
846 #[derive(TypeFoldable, TypeVisitable)]
847 pub struct ImplSourceBuiltinData<N> {
851 #[derive(PartialEq, Eq, Clone, TyEncodable, TyDecodable, HashStable, Lift)]
852 #[derive(TypeFoldable, TypeVisitable)]
853 pub struct ImplSourceObjectData<'tcx, N> {
854 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
855 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
857 /// The vtable is formed by concatenating together the method lists of
858 /// the base object trait and all supertraits, pointers to supertrait vtable will
859 /// be provided when necessary; this is the start of `upcast_trait_ref`'s methods
861 pub vtable_base: usize,
866 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
867 #[derive(TypeFoldable, TypeVisitable)]
868 pub struct ImplSourceFnPointerData<'tcx, N> {
873 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
874 #[derive(TypeFoldable, TypeVisitable)]
875 pub struct ImplSourceConstDestructData<N> {
879 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
880 #[derive(TypeFoldable, TypeVisitable)]
881 pub struct ImplSourceTraitAliasData<'tcx, N> {
882 pub alias_def_id: DefId,
883 pub substs: SubstsRef<'tcx>,
887 #[derive(Clone, Debug, PartialEq, Eq, Hash, HashStable, PartialOrd, Ord)]
888 pub enum ObjectSafetyViolation {
889 /// `Self: Sized` declared on the trait.
890 SizedSelf(SmallVec<[Span; 1]>),
892 /// Supertrait reference references `Self` an in illegal location
893 /// (e.g., `trait Foo : Bar<Self>`).
894 SupertraitSelf(SmallVec<[Span; 1]>),
896 /// Method has something illegal.
897 Method(Symbol, MethodViolationCode, Span),
899 /// Associated const.
900 AssocConst(Symbol, Span),
906 impl ObjectSafetyViolation {
907 pub fn error_msg(&self) -> Cow<'static, str> {
909 ObjectSafetyViolation::SizedSelf(_) => "it requires `Self: Sized`".into(),
910 ObjectSafetyViolation::SupertraitSelf(ref spans) => {
911 if spans.iter().any(|sp| *sp != DUMMY_SP) {
912 "it uses `Self` as a type parameter".into()
914 "it cannot use `Self` as a type parameter in a supertrait or `where`-clause"
918 ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod(_), _) => {
919 format!("associated function `{}` has no `self` parameter", name).into()
921 ObjectSafetyViolation::Method(
923 MethodViolationCode::ReferencesSelfInput(_),
925 ) => format!("method `{}` references the `Self` type in its parameters", name).into(),
926 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfInput(_), _) => {
927 format!("method `{}` references the `Self` type in this parameter", name).into()
929 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfOutput, _) => {
930 format!("method `{}` references the `Self` type in its return type", name).into()
932 ObjectSafetyViolation::Method(
934 MethodViolationCode::ReferencesImplTraitInTrait(_),
936 ) => format!("method `{}` references an `impl Trait` type in its return type", name)
938 ObjectSafetyViolation::Method(name, MethodViolationCode::AsyncFn, _) => {
939 format!("method `{}` is `async`", name).into()
941 ObjectSafetyViolation::Method(
943 MethodViolationCode::WhereClauseReferencesSelf,
946 format!("method `{}` references the `Self` type in its `where` clause", name).into()
948 ObjectSafetyViolation::Method(name, MethodViolationCode::Generic, _) => {
949 format!("method `{}` has generic type parameters", name).into()
951 ObjectSafetyViolation::Method(
953 MethodViolationCode::UndispatchableReceiver(_),
955 ) => format!("method `{}`'s `self` parameter cannot be dispatched on", name).into(),
956 ObjectSafetyViolation::AssocConst(name, DUMMY_SP) => {
957 format!("it contains associated `const` `{}`", name).into()
959 ObjectSafetyViolation::AssocConst(..) => "it contains this associated `const`".into(),
960 ObjectSafetyViolation::GAT(name, _) => {
961 format!("it contains the generic associated type `{}`", name).into()
966 pub fn solution(&self, err: &mut Diagnostic) {
968 ObjectSafetyViolation::SizedSelf(_) | ObjectSafetyViolation::SupertraitSelf(_) => {}
969 ObjectSafetyViolation::Method(
971 MethodViolationCode::StaticMethod(Some((add_self_sugg, make_sized_sugg))),
977 "consider turning `{}` into a method by giving it a `&self` argument",
980 add_self_sugg.0.to_string(),
981 Applicability::MaybeIncorrect,
986 "alternatively, consider constraining `{}` so it does not apply to \
990 make_sized_sugg.0.to_string(),
991 Applicability::MaybeIncorrect,
994 ObjectSafetyViolation::Method(
996 MethodViolationCode::UndispatchableReceiver(Some(span)),
1002 "consider changing method `{}`'s `self` parameter to be `&self`",
1006 Applicability::MachineApplicable,
1009 ObjectSafetyViolation::AssocConst(name, _)
1010 | ObjectSafetyViolation::GAT(name, _)
1011 | ObjectSafetyViolation::Method(name, ..) => {
1012 err.help(&format!("consider moving `{}` to another trait", name));
1017 pub fn spans(&self) -> SmallVec<[Span; 1]> {
1018 // When `span` comes from a separate crate, it'll be `DUMMY_SP`. Treat it as `None` so
1019 // diagnostics use a `note` instead of a `span_label`.
1021 ObjectSafetyViolation::SupertraitSelf(spans)
1022 | ObjectSafetyViolation::SizedSelf(spans) => spans.clone(),
1023 ObjectSafetyViolation::AssocConst(_, span)
1024 | ObjectSafetyViolation::GAT(_, span)
1025 | ObjectSafetyViolation::Method(_, _, span)
1026 if *span != DUMMY_SP =>
1035 /// Reasons a method might not be object-safe.
1036 #[derive(Clone, Debug, PartialEq, Eq, Hash, HashStable, PartialOrd, Ord)]
1037 pub enum MethodViolationCode {
1038 /// e.g., `fn foo()`
1039 StaticMethod(Option<(/* add &self */ (String, Span), /* add Self: Sized */ (String, Span))>),
1041 /// e.g., `fn foo(&self, x: Self)`
1042 ReferencesSelfInput(Option<Span>),
1044 /// e.g., `fn foo(&self) -> Self`
1045 ReferencesSelfOutput,
1047 /// e.g., `fn foo(&self) -> impl Sized`
1048 ReferencesImplTraitInTrait(Span),
1050 /// e.g., `async fn foo(&self)`
1053 /// e.g., `fn foo(&self) where Self: Clone`
1054 WhereClauseReferencesSelf,
1056 /// e.g., `fn foo<A>()`
1059 /// the method's receiver (`self` argument) can't be dispatched on
1060 UndispatchableReceiver(Option<Span>),
1063 /// These are the error cases for `codegen_select_candidate`.
1064 #[derive(Copy, Clone, Debug, Hash, HashStable, Encodable, Decodable)]
1065 pub enum CodegenObligationError {
1066 /// Ambiguity can happen when monomorphizing during trans
1067 /// expands to some humongous type that never occurred
1068 /// statically -- this humongous type can then overflow,
1069 /// leading to an ambiguous result. So report this as an
1070 /// overflow bug, since I believe this is the only case
1071 /// where ambiguity can result.
1073 /// This can trigger when we probe for the source of a `'static` lifetime requirement
1074 /// on a trait object: `impl Foo for dyn Trait {}` has an implicit `'static` bound.
1075 /// This can also trigger when we have a global bound that is not actually satisfied,
1076 /// but was included during typeck due to the trivial_bounds feature.