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,
478 /// The index of the derived predicate in the parent impl's predicates.
479 pub impl_def_predicate_index: Option<usize>,
483 impl<'tcx> ObligationCauseCode<'tcx> {
484 /// Returns the base obligation, ignoring derived obligations.
485 pub fn peel_derives(&self) -> &Self {
486 let mut base_cause = self;
487 while let Some((parent_code, _)) = base_cause.parent() {
488 base_cause = parent_code;
493 pub fn parent(&self) -> Option<(&Self, Option<ty::PolyTraitPredicate<'tcx>>)> {
495 FunctionArgumentObligation { parent_code, .. } => Some((parent_code, None)),
496 BuiltinDerivedObligation(derived)
497 | DerivedObligation(derived)
498 | ImplDerivedObligation(box ImplDerivedObligationCause { derived, .. }) => {
499 Some((&derived.parent_code, Some(derived.parent_trait_pred)))
505 pub fn peel_match_impls(&self) -> &Self {
507 MatchImpl(cause, _) => cause.code(),
513 // `ObligationCauseCode` is used a lot. Make sure it doesn't unintentionally get bigger.
514 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
515 static_assert_size!(ObligationCauseCode<'_>, 48);
517 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
518 pub enum StatementAsExpression {
523 impl<'tcx> ty::Lift<'tcx> for StatementAsExpression {
524 type Lifted = StatementAsExpression;
525 fn lift_to_tcx(self, _tcx: TyCtxt<'tcx>) -> Option<StatementAsExpression> {
530 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift, HashStable, TyEncodable, TyDecodable)]
531 #[derive(TypeVisitable, TypeFoldable)]
532 pub struct MatchExpressionArmCause<'tcx> {
533 pub arm_block_id: Option<hir::HirId>,
534 pub arm_ty: Ty<'tcx>,
536 pub prior_arm_block_id: Option<hir::HirId>,
537 pub prior_arm_ty: Ty<'tcx>,
538 pub prior_arm_span: Span,
539 pub scrut_span: Span,
540 pub source: hir::MatchSource,
541 pub prior_arms: Vec<Span>,
542 pub scrut_hir_id: hir::HirId,
543 pub opt_suggest_box_span: Option<Span>,
546 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
547 #[derive(Lift, TypeFoldable, TypeVisitable, HashStable, TyEncodable, TyDecodable)]
548 pub struct IfExpressionCause<'tcx> {
549 pub then_id: hir::HirId,
550 pub else_id: hir::HirId,
551 pub then_ty: Ty<'tcx>,
552 pub else_ty: Ty<'tcx>,
553 pub outer_span: Option<Span>,
554 pub opt_suggest_box_span: Option<Span>,
557 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift, HashStable, TyEncodable, TyDecodable)]
558 #[derive(TypeVisitable, TypeFoldable)]
559 pub struct DerivedObligationCause<'tcx> {
560 /// The trait predicate of the parent obligation that led to the
561 /// current obligation. Note that only trait obligations lead to
562 /// derived obligations, so we just store the trait predicate here
564 pub parent_trait_pred: ty::PolyTraitPredicate<'tcx>,
566 /// The parent trait had this cause.
567 pub parent_code: InternedObligationCauseCode<'tcx>,
570 #[derive(Clone, Debug, TypeFoldable, TypeVisitable, Lift)]
571 pub enum SelectionError<'tcx> {
572 /// The trait is not implemented.
574 /// After a closure impl has selected, its "outputs" were evaluated
575 /// (which for closures includes the "input" type params) and they
576 /// didn't resolve. See `confirm_poly_trait_refs` for more.
577 OutputTypeParameterMismatch(
578 ty::PolyTraitRef<'tcx>,
579 ty::PolyTraitRef<'tcx>,
580 ty::error::TypeError<'tcx>,
582 /// The trait pointed by `DefId` is not object safe.
583 TraitNotObjectSafe(DefId),
584 /// A given constant couldn't be evaluated.
585 NotConstEvaluatable(NotConstEvaluatable),
586 /// Exceeded the recursion depth during type projection.
587 Overflow(OverflowError),
588 /// Signaling that an error has already been emitted, to avoid
589 /// multiple errors being shown.
593 /// When performing resolution, it is typically the case that there
594 /// can be one of three outcomes:
596 /// - `Ok(Some(r))`: success occurred with result `r`
597 /// - `Ok(None)`: could not definitely determine anything, usually due
598 /// to inconclusive type inference.
599 /// - `Err(e)`: error `e` occurred
600 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
602 /// Given the successful resolution of an obligation, the `ImplSource`
603 /// indicates where the impl comes from.
605 /// For example, the obligation may be satisfied by a specific impl (case A),
606 /// or it may be relative to some bound that is in scope (case B).
608 /// ```ignore (illustrative)
609 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
610 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
611 /// impl Clone for i32 { ... } // Impl_3
613 /// fn foo<T: Clone>(concrete: Option<Box<i32>>, param: T, mixed: Option<T>) {
614 /// // Case A: ImplSource points at a specific impl. Only possible when
615 /// // type is concretely known. If the impl itself has bounded
616 /// // type parameters, ImplSource will carry resolutions for those as well:
617 /// concrete.clone(); // ImplSource(Impl_1, [ImplSource(Impl_2, [ImplSource(Impl_3)])])
619 /// // Case B: ImplSource must be provided by caller. This applies when
620 /// // type is a type parameter.
621 /// param.clone(); // ImplSource::Param
623 /// // Case C: A mix of cases A and B.
624 /// mixed.clone(); // ImplSource(Impl_1, [ImplSource::Param])
628 /// ### The type parameter `N`
630 /// See explanation on `ImplSourceUserDefinedData`.
631 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
632 #[derive(TypeFoldable, TypeVisitable)]
633 pub enum ImplSource<'tcx, N> {
634 /// ImplSource identifying a particular impl.
635 UserDefined(ImplSourceUserDefinedData<'tcx, N>),
637 /// ImplSource for auto trait implementations.
638 /// This carries the information and nested obligations with regards
639 /// to an auto implementation for a trait `Trait`. The nested obligations
640 /// ensure the trait implementation holds for all the constituent types.
641 AutoImpl(ImplSourceAutoImplData<N>),
643 /// Successful resolution to an obligation provided by the caller
644 /// for some type parameter. The `Vec<N>` represents the
645 /// obligations incurred from normalizing the where-clause (if
647 Param(Vec<N>, ty::BoundConstness),
649 /// Virtual calls through an object.
650 Object(ImplSourceObjectData<'tcx, N>),
652 /// Successful resolution for a builtin trait.
653 Builtin(ImplSourceBuiltinData<N>),
655 /// ImplSource for trait upcasting coercion
656 TraitUpcasting(ImplSourceTraitUpcastingData<'tcx, N>),
658 /// ImplSource automatically generated for a closure. The `DefId` is the ID
659 /// of the closure expression. This is an `ImplSource::UserDefined` in spirit, but the
660 /// impl is generated by the compiler and does not appear in the source.
661 Closure(ImplSourceClosureData<'tcx, N>),
663 /// Same as above, but for a function pointer type with the given signature.
664 FnPointer(ImplSourceFnPointerData<'tcx, N>),
666 /// ImplSource automatically generated for a generator.
667 Generator(ImplSourceGeneratorData<'tcx, N>),
669 /// ImplSource automatically generated for a generator backing an async future.
670 Future(ImplSourceFutureData<'tcx, N>),
672 /// ImplSource for a trait alias.
673 TraitAlias(ImplSourceTraitAliasData<'tcx, N>),
675 /// ImplSource for a `const Drop` implementation.
676 ConstDestruct(ImplSourceConstDestructData<N>),
679 impl<'tcx, N> ImplSource<'tcx, N> {
680 pub fn nested_obligations(self) -> Vec<N> {
682 ImplSource::UserDefined(i) => i.nested,
683 ImplSource::Param(n, _) => n,
684 ImplSource::Builtin(i) => i.nested,
685 ImplSource::AutoImpl(d) => d.nested,
686 ImplSource::Closure(c) => c.nested,
687 ImplSource::Generator(c) => c.nested,
688 ImplSource::Future(c) => c.nested,
689 ImplSource::Object(d) => d.nested,
690 ImplSource::FnPointer(d) => d.nested,
691 ImplSource::TraitAlias(d) => d.nested,
692 ImplSource::TraitUpcasting(d) => d.nested,
693 ImplSource::ConstDestruct(i) => i.nested,
697 pub fn borrow_nested_obligations(&self) -> &[N] {
699 ImplSource::UserDefined(i) => &i.nested[..],
700 ImplSource::Param(n, _) => &n,
701 ImplSource::Builtin(i) => &i.nested,
702 ImplSource::AutoImpl(d) => &d.nested,
703 ImplSource::Closure(c) => &c.nested,
704 ImplSource::Generator(c) => &c.nested,
705 ImplSource::Future(c) => &c.nested,
706 ImplSource::Object(d) => &d.nested,
707 ImplSource::FnPointer(d) => &d.nested,
708 ImplSource::TraitAlias(d) => &d.nested,
709 ImplSource::TraitUpcasting(d) => &d.nested,
710 ImplSource::ConstDestruct(i) => &i.nested,
714 pub fn map<M, F>(self, f: F) -> ImplSource<'tcx, M>
719 ImplSource::UserDefined(i) => ImplSource::UserDefined(ImplSourceUserDefinedData {
720 impl_def_id: i.impl_def_id,
722 nested: i.nested.into_iter().map(f).collect(),
724 ImplSource::Param(n, ct) => ImplSource::Param(n.into_iter().map(f).collect(), ct),
725 ImplSource::Builtin(i) => ImplSource::Builtin(ImplSourceBuiltinData {
726 nested: i.nested.into_iter().map(f).collect(),
728 ImplSource::Object(o) => ImplSource::Object(ImplSourceObjectData {
729 upcast_trait_ref: o.upcast_trait_ref,
730 vtable_base: o.vtable_base,
731 nested: o.nested.into_iter().map(f).collect(),
733 ImplSource::AutoImpl(d) => ImplSource::AutoImpl(ImplSourceAutoImplData {
734 trait_def_id: d.trait_def_id,
735 nested: d.nested.into_iter().map(f).collect(),
737 ImplSource::Closure(c) => ImplSource::Closure(ImplSourceClosureData {
738 closure_def_id: c.closure_def_id,
740 nested: c.nested.into_iter().map(f).collect(),
742 ImplSource::Generator(c) => ImplSource::Generator(ImplSourceGeneratorData {
743 generator_def_id: c.generator_def_id,
745 nested: c.nested.into_iter().map(f).collect(),
747 ImplSource::Future(c) => ImplSource::Future(ImplSourceFutureData {
748 generator_def_id: c.generator_def_id,
750 nested: c.nested.into_iter().map(f).collect(),
752 ImplSource::FnPointer(p) => ImplSource::FnPointer(ImplSourceFnPointerData {
754 nested: p.nested.into_iter().map(f).collect(),
756 ImplSource::TraitAlias(d) => ImplSource::TraitAlias(ImplSourceTraitAliasData {
757 alias_def_id: d.alias_def_id,
759 nested: d.nested.into_iter().map(f).collect(),
761 ImplSource::TraitUpcasting(d) => {
762 ImplSource::TraitUpcasting(ImplSourceTraitUpcastingData {
763 upcast_trait_ref: d.upcast_trait_ref,
764 vtable_vptr_slot: d.vtable_vptr_slot,
765 nested: d.nested.into_iter().map(f).collect(),
768 ImplSource::ConstDestruct(i) => {
769 ImplSource::ConstDestruct(ImplSourceConstDestructData {
770 nested: i.nested.into_iter().map(f).collect(),
777 /// Identifies a particular impl in the source, along with a set of
778 /// substitutions from the impl's type/lifetime parameters. The
779 /// `nested` vector corresponds to the nested obligations attached to
780 /// the impl's type parameters.
782 /// The type parameter `N` indicates the type used for "nested
783 /// obligations" that are required by the impl. During type-check, this
784 /// is `Obligation`, as one might expect. During codegen, however, this
785 /// is `()`, because codegen only requires a shallow resolution of an
786 /// impl, and nested obligations are satisfied later.
787 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
788 #[derive(TypeFoldable, TypeVisitable)]
789 pub struct ImplSourceUserDefinedData<'tcx, N> {
790 pub impl_def_id: DefId,
791 pub substs: SubstsRef<'tcx>,
795 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
796 #[derive(TypeFoldable, TypeVisitable)]
797 pub struct ImplSourceGeneratorData<'tcx, N> {
798 pub generator_def_id: DefId,
799 pub substs: SubstsRef<'tcx>,
800 /// Nested obligations. This can be non-empty if the generator
801 /// signature contains associated types.
805 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
806 #[derive(TypeFoldable, TypeVisitable)]
807 pub struct ImplSourceFutureData<'tcx, N> {
808 pub generator_def_id: DefId,
809 pub substs: SubstsRef<'tcx>,
810 /// Nested obligations. This can be non-empty if the generator
811 /// signature contains associated types.
815 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
816 #[derive(TypeFoldable, TypeVisitable)]
817 pub struct ImplSourceClosureData<'tcx, N> {
818 pub closure_def_id: DefId,
819 pub substs: SubstsRef<'tcx>,
820 /// Nested obligations. This can be non-empty if the closure
821 /// signature contains associated types.
825 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
826 #[derive(TypeFoldable, TypeVisitable)]
827 pub struct ImplSourceAutoImplData<N> {
828 pub trait_def_id: DefId,
832 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
833 #[derive(TypeFoldable, TypeVisitable)]
834 pub struct ImplSourceTraitUpcastingData<'tcx, N> {
835 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
836 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
838 /// The vtable is formed by concatenating together the method lists of
839 /// the base object trait and all supertraits, pointers to supertrait vtable will
840 /// be provided when necessary; this is the position of `upcast_trait_ref`'s vtable
841 /// within that vtable.
842 pub vtable_vptr_slot: Option<usize>,
847 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
848 #[derive(TypeFoldable, TypeVisitable)]
849 pub struct ImplSourceBuiltinData<N> {
853 #[derive(PartialEq, Eq, Clone, TyEncodable, TyDecodable, HashStable, Lift)]
854 #[derive(TypeFoldable, TypeVisitable)]
855 pub struct ImplSourceObjectData<'tcx, N> {
856 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
857 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
859 /// The vtable is formed by concatenating together the method lists of
860 /// the base object trait and all supertraits, pointers to supertrait vtable will
861 /// be provided when necessary; this is the start of `upcast_trait_ref`'s methods
863 pub vtable_base: usize,
868 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
869 #[derive(TypeFoldable, TypeVisitable)]
870 pub struct ImplSourceFnPointerData<'tcx, N> {
875 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
876 #[derive(TypeFoldable, TypeVisitable)]
877 pub struct ImplSourceConstDestructData<N> {
881 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
882 #[derive(TypeFoldable, TypeVisitable)]
883 pub struct ImplSourceTraitAliasData<'tcx, N> {
884 pub alias_def_id: DefId,
885 pub substs: SubstsRef<'tcx>,
889 #[derive(Clone, Debug, PartialEq, Eq, Hash, HashStable, PartialOrd, Ord)]
890 pub enum ObjectSafetyViolation {
891 /// `Self: Sized` declared on the trait.
892 SizedSelf(SmallVec<[Span; 1]>),
894 /// Supertrait reference references `Self` an in illegal location
895 /// (e.g., `trait Foo : Bar<Self>`).
896 SupertraitSelf(SmallVec<[Span; 1]>),
898 /// Method has something illegal.
899 Method(Symbol, MethodViolationCode, Span),
901 /// Associated const.
902 AssocConst(Symbol, Span),
908 impl ObjectSafetyViolation {
909 pub fn error_msg(&self) -> Cow<'static, str> {
911 ObjectSafetyViolation::SizedSelf(_) => "it requires `Self: Sized`".into(),
912 ObjectSafetyViolation::SupertraitSelf(ref spans) => {
913 if spans.iter().any(|sp| *sp != DUMMY_SP) {
914 "it uses `Self` as a type parameter".into()
916 "it cannot use `Self` as a type parameter in a supertrait or `where`-clause"
920 ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod(_), _) => {
921 format!("associated function `{}` has no `self` parameter", name).into()
923 ObjectSafetyViolation::Method(
925 MethodViolationCode::ReferencesSelfInput(_),
927 ) => format!("method `{}` references the `Self` type in its parameters", name).into(),
928 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfInput(_), _) => {
929 format!("method `{}` references the `Self` type in this parameter", name).into()
931 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfOutput, _) => {
932 format!("method `{}` references the `Self` type in its return type", name).into()
934 ObjectSafetyViolation::Method(
936 MethodViolationCode::ReferencesImplTraitInTrait(_),
938 ) => format!("method `{}` references an `impl Trait` type in its return type", name)
940 ObjectSafetyViolation::Method(name, MethodViolationCode::AsyncFn, _) => {
941 format!("method `{}` is `async`", name).into()
943 ObjectSafetyViolation::Method(
945 MethodViolationCode::WhereClauseReferencesSelf,
948 format!("method `{}` references the `Self` type in its `where` clause", name).into()
950 ObjectSafetyViolation::Method(name, MethodViolationCode::Generic, _) => {
951 format!("method `{}` has generic type parameters", name).into()
953 ObjectSafetyViolation::Method(
955 MethodViolationCode::UndispatchableReceiver(_),
957 ) => format!("method `{}`'s `self` parameter cannot be dispatched on", name).into(),
958 ObjectSafetyViolation::AssocConst(name, DUMMY_SP) => {
959 format!("it contains associated `const` `{}`", name).into()
961 ObjectSafetyViolation::AssocConst(..) => "it contains this associated `const`".into(),
962 ObjectSafetyViolation::GAT(name, _) => {
963 format!("it contains the generic associated type `{}`", name).into()
968 pub fn solution(&self, err: &mut Diagnostic) {
970 ObjectSafetyViolation::SizedSelf(_) | ObjectSafetyViolation::SupertraitSelf(_) => {}
971 ObjectSafetyViolation::Method(
973 MethodViolationCode::StaticMethod(Some((add_self_sugg, make_sized_sugg))),
979 "consider turning `{}` into a method by giving it a `&self` argument",
982 add_self_sugg.0.to_string(),
983 Applicability::MaybeIncorrect,
988 "alternatively, consider constraining `{}` so it does not apply to \
992 make_sized_sugg.0.to_string(),
993 Applicability::MaybeIncorrect,
996 ObjectSafetyViolation::Method(
998 MethodViolationCode::UndispatchableReceiver(Some(span)),
1001 err.span_suggestion(
1004 "consider changing method `{}`'s `self` parameter to be `&self`",
1008 Applicability::MachineApplicable,
1011 ObjectSafetyViolation::AssocConst(name, _)
1012 | ObjectSafetyViolation::GAT(name, _)
1013 | ObjectSafetyViolation::Method(name, ..) => {
1014 err.help(&format!("consider moving `{}` to another trait", name));
1019 pub fn spans(&self) -> SmallVec<[Span; 1]> {
1020 // When `span` comes from a separate crate, it'll be `DUMMY_SP`. Treat it as `None` so
1021 // diagnostics use a `note` instead of a `span_label`.
1023 ObjectSafetyViolation::SupertraitSelf(spans)
1024 | ObjectSafetyViolation::SizedSelf(spans) => spans.clone(),
1025 ObjectSafetyViolation::AssocConst(_, span)
1026 | ObjectSafetyViolation::GAT(_, span)
1027 | ObjectSafetyViolation::Method(_, _, span)
1028 if *span != DUMMY_SP =>
1037 /// Reasons a method might not be object-safe.
1038 #[derive(Clone, Debug, PartialEq, Eq, Hash, HashStable, PartialOrd, Ord)]
1039 pub enum MethodViolationCode {
1040 /// e.g., `fn foo()`
1041 StaticMethod(Option<(/* add &self */ (String, Span), /* add Self: Sized */ (String, Span))>),
1043 /// e.g., `fn foo(&self, x: Self)`
1044 ReferencesSelfInput(Option<Span>),
1046 /// e.g., `fn foo(&self) -> Self`
1047 ReferencesSelfOutput,
1049 /// e.g., `fn foo(&self) -> impl Sized`
1050 ReferencesImplTraitInTrait(Span),
1052 /// e.g., `async fn foo(&self)`
1055 /// e.g., `fn foo(&self) where Self: Clone`
1056 WhereClauseReferencesSelf,
1058 /// e.g., `fn foo<A>()`
1061 /// the method's receiver (`self` argument) can't be dispatched on
1062 UndispatchableReceiver(Option<Span>),
1065 /// These are the error cases for `codegen_select_candidate`.
1066 #[derive(Copy, Clone, Debug, Hash, HashStable, Encodable, Decodable)]
1067 pub enum CodegenObligationError {
1068 /// Ambiguity can happen when monomorphizing during trans
1069 /// expands to some humongous type that never occurred
1070 /// statically -- this humongous type can then overflow,
1071 /// leading to an ambiguous result. So report this as an
1072 /// overflow bug, since I believe this is the only case
1073 /// where ambiguity can result.
1075 /// This can trigger when we probe for the source of a `'static` lifetime requirement
1076 /// on a trait object: `impl Foo for dyn Trait {}` has an implicit `'static` bound.
1077 /// This can also trigger when we have a global bound that is not actually satisfied,
1078 /// but was included during typeck due to the trivial_bounds feature.