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::ty::abstract_const::NotConstEvaluatable;
14 use crate::ty::subst::SubstsRef;
15 use crate::ty::{self, AdtKind, Predicate, Ty, TyCtxt};
17 use rustc_data_structures::sync::Lrc;
18 use rustc_errors::{Applicability, Diagnostic};
20 use rustc_hir::def_id::{DefId, LocalDefId};
21 use rustc_span::symbol::Symbol;
22 use rustc_span::{Span, DUMMY_SP};
23 use smallvec::SmallVec;
26 use std::hash::{Hash, Hasher};
28 pub use self::select::{EvaluationCache, EvaluationResult, OverflowError, SelectionCache};
30 pub type CanonicalChalkEnvironmentAndGoal<'tcx> = Canonical<'tcx, ChalkEnvironmentAndGoal<'tcx>>;
32 pub use self::ObligationCauseCode::*;
34 pub use self::chalk::{ChalkEnvironmentAndGoal, RustInterner as ChalkRustInterner};
36 /// Depending on the stage of compilation, we want projection to be
37 /// more or less conservative.
38 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, HashStable)]
40 /// At type-checking time, we refuse to project any associated
41 /// type that is marked `default`. Non-`default` ("final") types
42 /// are always projected. This is necessary in general for
43 /// soundness of specialization. However, we *could* allow
44 /// projections in fully-monomorphic cases. We choose not to,
45 /// because we prefer for `default type` to force the type
46 /// definition to be treated abstractly by any consumers of the
47 /// impl. Concretely, that means that the following example will
50 /// ```compile_fail,E0308
51 /// #![feature(specialization)]
56 /// impl<T> Assoc for T {
57 /// default type Output = bool;
61 /// let x: <() as Assoc>::Output = true;
65 /// We also do not reveal the hidden type of opaque types during
69 /// At codegen time, all monomorphic projections will succeed.
70 /// Also, `impl Trait` is normalized to the concrete type,
71 /// which has to be already collected by type-checking.
73 /// NOTE: as `impl Trait`'s concrete type should *never*
74 /// be observable directly by the user, `Reveal::All`
75 /// should not be used by checks which may expose
76 /// type equality or type contents to the user.
77 /// There are some exceptions, e.g., around auto traits and
78 /// transmute-checking, which expose some details, but
79 /// not the whole concrete type of the `impl Trait`.
83 /// The reason why we incurred this obligation; used for error reporting.
85 /// Non-misc `ObligationCauseCode`s are stored on the heap. This gives the
86 /// best trade-off between keeping the type small (which makes copies cheaper)
87 /// while not doing too many heap allocations.
89 /// We do not want to intern this as there are a lot of obligation causes which
90 /// only live for a short period of time.
91 #[derive(Clone, Debug, PartialEq, Eq, Lift)]
92 pub struct ObligationCause<'tcx> {
95 /// The ID of the fn body that triggered this obligation. This is
96 /// used for region obligations to determine the precise
97 /// environment in which the region obligation should be evaluated
98 /// (in particular, closures can add new assumptions). See the
99 /// field `region_obligations` of the `FulfillmentContext` for more
101 pub body_id: hir::HirId,
103 code: InternedObligationCauseCode<'tcx>,
106 // This custom hash function speeds up hashing for `Obligation` deduplication
107 // greatly by skipping the `code` field, which can be large and complex. That
108 // shouldn't affect hash quality much since there are several other fields in
109 // `Obligation` which should be unique enough, especially the predicate itself
110 // which is hashed as an interned pointer. See #90996.
111 impl Hash for ObligationCause<'_> {
112 fn hash<H: Hasher>(&self, state: &mut H) {
113 self.body_id.hash(state);
114 self.span.hash(state);
118 impl<'tcx> ObligationCause<'tcx> {
123 code: ObligationCauseCode<'tcx>,
124 ) -> ObligationCause<'tcx> {
125 ObligationCause { span, body_id, code: code.into() }
128 pub fn misc(span: Span, body_id: hir::HirId) -> ObligationCause<'tcx> {
129 ObligationCause::new(span, body_id, MiscObligation)
133 pub fn dummy() -> ObligationCause<'tcx> {
134 ObligationCause::dummy_with_span(DUMMY_SP)
138 pub fn dummy_with_span(span: Span) -> ObligationCause<'tcx> {
139 ObligationCause { span, body_id: hir::CRATE_HIR_ID, code: Default::default() }
142 pub fn span(&self) -> Span {
144 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
153 pub fn code(&self) -> &ObligationCauseCode<'tcx> {
159 f: impl FnOnce(InternedObligationCauseCode<'tcx>) -> ObligationCauseCode<'tcx>,
161 self.code = f(std::mem::take(&mut self.code)).into();
164 pub fn derived_cause(
166 parent_trait_pred: ty::PolyTraitPredicate<'tcx>,
167 variant: impl FnOnce(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
168 ) -> ObligationCause<'tcx> {
170 * Creates a cause for obligations that are derived from
171 * `obligation` by a recursive search (e.g., for a builtin
172 * bound, or eventually a `auto trait Foo`). If `obligation`
173 * is itself a derived obligation, this is just a clone, but
174 * otherwise we create a "derived obligation" cause so as to
175 * keep track of the original root obligation for error
179 // NOTE(flaper87): As of now, it keeps track of the whole error
180 // chain. Ideally, we should have a way to configure this either
181 // by using -Z verbose or just a CLI argument.
183 variant(DerivedObligationCause { parent_trait_pred, parent_code: self.code }).into();
188 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
189 pub struct UnifyReceiverContext<'tcx> {
190 pub assoc_item: ty::AssocItem,
191 pub param_env: ty::ParamEnv<'tcx>,
192 pub substs: SubstsRef<'tcx>,
195 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift, Default)]
196 pub struct InternedObligationCauseCode<'tcx> {
197 /// `None` for `ObligationCauseCode::MiscObligation` (a common case, occurs ~60% of
198 /// the time). `Some` otherwise.
199 code: Option<Lrc<ObligationCauseCode<'tcx>>>,
202 impl<'tcx> ObligationCauseCode<'tcx> {
204 fn into(self) -> InternedObligationCauseCode<'tcx> {
205 InternedObligationCauseCode {
206 code: if let ObligationCauseCode::MiscObligation = self {
215 impl<'tcx> std::ops::Deref for InternedObligationCauseCode<'tcx> {
216 type Target = ObligationCauseCode<'tcx>;
218 fn deref(&self) -> &Self::Target {
219 self.code.as_deref().unwrap_or(&ObligationCauseCode::MiscObligation)
223 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
224 pub enum ObligationCauseCode<'tcx> {
225 /// Not well classified or should be obvious from the span.
228 /// A slice or array is WF only if `T: Sized`.
231 /// A tuple is WF only if its middle elements are `Sized`.
234 /// This is the trait reference from the given projection.
235 ProjectionWf(ty::ProjectionTy<'tcx>),
237 /// In an impl of trait `X` for type `Y`, type `Y` must
238 /// also implement all supertraits of `X`.
239 ItemObligation(DefId),
241 /// Like `ItemObligation`, but with extra detail on the source of the obligation.
242 BindingObligation(DefId, Span),
244 /// A type like `&'a T` is WF only if `T: 'a`.
245 ReferenceOutlivesReferent(Ty<'tcx>),
247 /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
248 ObjectTypeBound(Ty<'tcx>, ty::Region<'tcx>),
250 /// Obligation incurred due to an object cast.
251 ObjectCastObligation(/* Concrete type */ Ty<'tcx>, /* Object type */ Ty<'tcx>),
253 /// Obligation incurred due to a coercion.
259 /// Various cases where expressions must be `Sized` / `Copy` / etc.
260 /// `L = X` implies that `L` is `Sized`.
262 /// `(x1, .., xn)` must be `Sized`.
263 TupleInitializerSized,
264 /// `S { ... }` must be `Sized`.
265 StructInitializerSized,
266 /// Type of each variable must be `Sized`.
267 VariableType(hir::HirId),
268 /// Argument type must be `Sized`.
269 SizedArgumentType(Option<Span>),
270 /// Return type must be `Sized`.
272 /// Yield type must be `Sized`.
274 /// Box expression result type must be `Sized`.
276 /// Inline asm operand type must be `Sized`.
278 /// `[expr; N]` requires `type_of(expr): Copy`.
280 /// If element is a `const fn` we display a help message suggesting to move the
281 /// function call to a new `const` item while saying that `T` doesn't implement `Copy`.
285 /// Types of fields (other than the last, except for packed structs) in a struct must be sized.
292 /// Constant expressions must be sized.
295 /// `static` items must have `Sync` type.
298 BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
300 ImplDerivedObligation(Box<ImplDerivedObligationCause<'tcx>>),
302 DerivedObligation(DerivedObligationCause<'tcx>),
304 FunctionArgumentObligation {
305 /// The node of the relevant argument in the function call.
306 arg_hir_id: hir::HirId,
307 /// The node of the function call.
308 call_hir_id: hir::HirId,
309 /// The obligation introduced by this argument.
310 parent_code: InternedObligationCauseCode<'tcx>,
313 /// Error derived when matching traits/impls; see ObligationCause for more details
314 CompareImplItemObligation {
315 impl_item_def_id: LocalDefId,
316 trait_item_def_id: DefId,
320 /// Checking that the bounds of a trait's associated type hold for a given impl
321 CheckAssociatedTypeBounds {
322 impl_item_def_id: LocalDefId,
323 trait_item_def_id: DefId,
326 /// Checking that this expression can be assigned to its target.
329 /// Computing common supertype in the arms of a match expression
330 MatchExpressionArm(Box<MatchExpressionArmCause<'tcx>>),
332 /// Type error arising from type checking a pattern against an expected type.
334 /// The span of the scrutinee or type expression which caused the `root_ty` type.
336 /// The root expected type induced by a scrutinee or type expression.
338 /// Whether the `Span` came from an expression or a type expression.
342 /// Constants in patterns must have `Structural` type.
343 ConstPatternStructural,
345 /// Computing common supertype in an if expression
346 IfExpression(Box<IfExpressionCause<'tcx>>),
348 /// Computing common supertype of an if expression with no else counter-part
349 IfExpressionWithNoElse,
351 /// `main` has wrong type
354 /// `start` has wrong type
357 /// Intrinsic has wrong type
360 /// A let else block does not diverge
366 UnifyReceiver(Box<UnifyReceiverContext<'tcx>>),
368 /// `return` with no expression
371 /// `return` with an expression
372 ReturnValue(hir::HirId),
374 /// Return type of this function
377 /// Opaque return type of this function
378 OpaqueReturnType(Option<(Ty<'tcx>, Span)>),
380 /// Block implicit return
381 BlockTailExpression(hir::HirId),
383 /// #[feature(trivial_bounds)] is not enabled
386 /// If `X` is the concrete type of an opaque type `impl Y`, then `X` must implement `Y`
389 AwaitableExpr(Option<hir::HirId>),
395 /// Well-formed checking. If a `WellFormedLoc` is provided,
396 /// then it will be used to perform HIR-based wf checking
397 /// after an error occurs, in order to generate a more precise error span.
398 /// This is purely for diagnostic purposes - it is always
399 /// correct to use `MiscObligation` instead, or to specify
400 /// `WellFormed(None)`
401 WellFormed(Option<WellFormedLoc>),
403 /// From `match_impl`. The cause for us having to match an impl, and the DefId we are matching against.
404 MatchImpl(ObligationCause<'tcx>, DefId),
407 rhs_span: Option<Span>,
409 output_pred: Option<Predicate<'tcx>>,
413 /// The 'location' at which we try to perform HIR-based wf checking.
414 /// This information is used to obtain an `hir::Ty`, which
415 /// we can walk in order to obtain precise spans for any
416 /// 'nested' types (e.g. `Foo` in `Option<Foo>`).
417 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
418 pub enum WellFormedLoc {
419 /// Use the type of the provided definition.
421 /// Use the type of the parameter of the provided function.
422 /// We cannot use `hir::Param`, since the function may
423 /// not have a body (e.g. a trait method definition)
425 /// The function to lookup the parameter in
426 function: LocalDefId,
427 /// The index of the parameter to use.
428 /// Parameters are indexed from 0, with the return type
429 /// being the last 'parameter'
434 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
435 pub struct ImplDerivedObligationCause<'tcx> {
436 pub derived: DerivedObligationCause<'tcx>,
437 pub impl_def_id: DefId,
441 impl<'tcx> ObligationCauseCode<'tcx> {
442 // Return the base obligation, ignoring derived obligations.
443 pub fn peel_derives(&self) -> &Self {
444 let mut base_cause = self;
445 while let Some((parent_code, _)) = base_cause.parent() {
446 base_cause = parent_code;
451 pub fn parent(&self) -> Option<(&Self, Option<ty::PolyTraitPredicate<'tcx>>)> {
453 FunctionArgumentObligation { parent_code, .. } => Some((parent_code, None)),
454 BuiltinDerivedObligation(derived)
455 | DerivedObligation(derived)
456 | ImplDerivedObligation(box ImplDerivedObligationCause { derived, .. }) => {
457 Some((&derived.parent_code, Some(derived.parent_trait_pred)))
464 // `ObligationCauseCode` is used a lot. Make sure it doesn't unintentionally get bigger.
465 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
466 static_assert_size!(ObligationCauseCode<'_>, 48);
468 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
469 pub enum StatementAsExpression {
474 impl<'tcx> ty::Lift<'tcx> for StatementAsExpression {
475 type Lifted = StatementAsExpression;
476 fn lift_to_tcx(self, _tcx: TyCtxt<'tcx>) -> Option<StatementAsExpression> {
481 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
482 pub struct MatchExpressionArmCause<'tcx> {
483 pub arm_block_id: Option<hir::HirId>,
484 pub arm_ty: Ty<'tcx>,
486 pub prior_arm_block_id: Option<hir::HirId>,
487 pub prior_arm_ty: Ty<'tcx>,
488 pub prior_arm_span: Span,
489 pub scrut_span: Span,
490 pub source: hir::MatchSource,
491 pub prior_arms: Vec<Span>,
492 pub scrut_hir_id: hir::HirId,
493 pub opt_suggest_box_span: Option<Span>,
496 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
497 #[derive(Lift, TypeFoldable, TypeVisitable)]
498 pub struct IfExpressionCause<'tcx> {
499 pub then_id: hir::HirId,
500 pub else_id: hir::HirId,
501 pub then_ty: Ty<'tcx>,
502 pub else_ty: Ty<'tcx>,
503 pub outer_span: Option<Span>,
504 pub opt_suggest_box_span: Option<Span>,
507 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
508 pub struct DerivedObligationCause<'tcx> {
509 /// The trait predicate of the parent obligation that led to the
510 /// current obligation. Note that only trait obligations lead to
511 /// derived obligations, so we just store the trait predicate here
513 pub parent_trait_pred: ty::PolyTraitPredicate<'tcx>,
515 /// The parent trait had this cause.
516 pub parent_code: InternedObligationCauseCode<'tcx>,
519 #[derive(Clone, Debug, TypeFoldable, TypeVisitable, Lift)]
520 pub enum SelectionError<'tcx> {
521 /// The trait is not implemented.
523 /// After a closure impl has selected, its "outputs" were evaluated
524 /// (which for closures includes the "input" type params) and they
525 /// didn't resolve. See `confirm_poly_trait_refs` for more.
526 OutputTypeParameterMismatch(
527 ty::PolyTraitRef<'tcx>,
528 ty::PolyTraitRef<'tcx>,
529 ty::error::TypeError<'tcx>,
531 /// The trait pointed by `DefId` is not object safe.
532 TraitNotObjectSafe(DefId),
533 /// A given constant couldn't be evaluated.
534 NotConstEvaluatable(NotConstEvaluatable),
535 /// Exceeded the recursion depth during type projection.
536 Overflow(OverflowError),
537 /// Signaling that an error has already been emitted, to avoid
538 /// multiple errors being shown.
540 /// Multiple applicable `impl`s where found. The `DefId`s correspond to
541 /// all the `impl`s' Items.
542 Ambiguous(Vec<DefId>),
545 /// When performing resolution, it is typically the case that there
546 /// can be one of three outcomes:
548 /// - `Ok(Some(r))`: success occurred with result `r`
549 /// - `Ok(None)`: could not definitely determine anything, usually due
550 /// to inconclusive type inference.
551 /// - `Err(e)`: error `e` occurred
552 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
554 /// Given the successful resolution of an obligation, the `ImplSource`
555 /// indicates where the impl comes from.
557 /// For example, the obligation may be satisfied by a specific impl (case A),
558 /// or it may be relative to some bound that is in scope (case B).
560 /// ```ignore (illustrative)
561 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
562 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
563 /// impl Clone for i32 { ... } // Impl_3
565 /// fn foo<T: Clone>(concrete: Option<Box<i32>>, param: T, mixed: Option<T>) {
566 /// // Case A: ImplSource points at a specific impl. Only possible when
567 /// // type is concretely known. If the impl itself has bounded
568 /// // type parameters, ImplSource will carry resolutions for those as well:
569 /// concrete.clone(); // ImplSource(Impl_1, [ImplSource(Impl_2, [ImplSource(Impl_3)])])
571 /// // Case A: ImplSource points at a specific impl. Only possible when
572 /// // type is concretely known. If the impl itself has bounded
573 /// // type parameters, ImplSource will carry resolutions for those as well:
574 /// concrete.clone(); // ImplSource(Impl_1, [ImplSource(Impl_2, [ImplSource(Impl_3)])])
576 /// // Case B: ImplSource must be provided by caller. This applies when
577 /// // type is a type parameter.
578 /// param.clone(); // ImplSource::Param
580 /// // Case C: A mix of cases A and B.
581 /// mixed.clone(); // ImplSource(Impl_1, [ImplSource::Param])
585 /// ### The type parameter `N`
587 /// See explanation on `ImplSourceUserDefinedData`.
588 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
589 #[derive(TypeFoldable, TypeVisitable)]
590 pub enum ImplSource<'tcx, N> {
591 /// ImplSource identifying a particular impl.
592 UserDefined(ImplSourceUserDefinedData<'tcx, N>),
594 /// ImplSource for auto trait implementations.
595 /// This carries the information and nested obligations with regards
596 /// to an auto implementation for a trait `Trait`. The nested obligations
597 /// ensure the trait implementation holds for all the constituent types.
598 AutoImpl(ImplSourceAutoImplData<N>),
600 /// Successful resolution to an obligation provided by the caller
601 /// for some type parameter. The `Vec<N>` represents the
602 /// obligations incurred from normalizing the where-clause (if
604 Param(Vec<N>, ty::BoundConstness),
606 /// Virtual calls through an object.
607 Object(ImplSourceObjectData<'tcx, N>),
609 /// Successful resolution for a builtin trait.
610 Builtin(ImplSourceBuiltinData<N>),
612 /// ImplSource for trait upcasting coercion
613 TraitUpcasting(ImplSourceTraitUpcastingData<'tcx, N>),
615 /// ImplSource automatically generated for a closure. The `DefId` is the ID
616 /// of the closure expression. This is an `ImplSource::UserDefined` in spirit, but the
617 /// impl is generated by the compiler and does not appear in the source.
618 Closure(ImplSourceClosureData<'tcx, N>),
620 /// Same as above, but for a function pointer type with the given signature.
621 FnPointer(ImplSourceFnPointerData<'tcx, N>),
623 /// ImplSource for a builtin `DeterminantKind` trait implementation.
624 DiscriminantKind(ImplSourceDiscriminantKindData),
626 /// ImplSource for a builtin `Pointee` trait implementation.
627 Pointee(ImplSourcePointeeData),
629 /// ImplSource automatically generated for a generator.
630 Generator(ImplSourceGeneratorData<'tcx, N>),
632 /// ImplSource for a trait alias.
633 TraitAlias(ImplSourceTraitAliasData<'tcx, N>),
635 /// ImplSource for a `const Drop` implementation.
636 ConstDestruct(ImplSourceConstDestructData<N>),
638 /// ImplSource for a `std::marker::Tuple` implementation.
639 /// This has no nested predicates ever, so no data.
643 impl<'tcx, N> ImplSource<'tcx, N> {
644 pub fn nested_obligations(self) -> Vec<N> {
646 ImplSource::UserDefined(i) => i.nested,
647 ImplSource::Param(n, _) => n,
648 ImplSource::Builtin(i) => i.nested,
649 ImplSource::AutoImpl(d) => d.nested,
650 ImplSource::Closure(c) => c.nested,
651 ImplSource::Generator(c) => c.nested,
652 ImplSource::Object(d) => d.nested,
653 ImplSource::FnPointer(d) => d.nested,
654 ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData)
655 | ImplSource::Pointee(ImplSourcePointeeData)
656 | ImplSource::Tuple => Vec::new(),
657 ImplSource::TraitAlias(d) => d.nested,
658 ImplSource::TraitUpcasting(d) => d.nested,
659 ImplSource::ConstDestruct(i) => i.nested,
663 pub fn borrow_nested_obligations(&self) -> &[N] {
665 ImplSource::UserDefined(i) => &i.nested[..],
666 ImplSource::Param(n, _) => &n,
667 ImplSource::Builtin(i) => &i.nested,
668 ImplSource::AutoImpl(d) => &d.nested,
669 ImplSource::Closure(c) => &c.nested,
670 ImplSource::Generator(c) => &c.nested,
671 ImplSource::Object(d) => &d.nested,
672 ImplSource::FnPointer(d) => &d.nested,
673 ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData)
674 | ImplSource::Pointee(ImplSourcePointeeData)
675 | ImplSource::Tuple => &[],
676 ImplSource::TraitAlias(d) => &d.nested,
677 ImplSource::TraitUpcasting(d) => &d.nested,
678 ImplSource::ConstDestruct(i) => &i.nested,
682 pub fn map<M, F>(self, f: F) -> ImplSource<'tcx, M>
687 ImplSource::UserDefined(i) => ImplSource::UserDefined(ImplSourceUserDefinedData {
688 impl_def_id: i.impl_def_id,
690 nested: i.nested.into_iter().map(f).collect(),
692 ImplSource::Param(n, ct) => ImplSource::Param(n.into_iter().map(f).collect(), ct),
693 ImplSource::Builtin(i) => ImplSource::Builtin(ImplSourceBuiltinData {
694 nested: i.nested.into_iter().map(f).collect(),
696 ImplSource::Object(o) => ImplSource::Object(ImplSourceObjectData {
697 upcast_trait_ref: o.upcast_trait_ref,
698 vtable_base: o.vtable_base,
699 nested: o.nested.into_iter().map(f).collect(),
701 ImplSource::AutoImpl(d) => ImplSource::AutoImpl(ImplSourceAutoImplData {
702 trait_def_id: d.trait_def_id,
703 nested: d.nested.into_iter().map(f).collect(),
705 ImplSource::Closure(c) => ImplSource::Closure(ImplSourceClosureData {
706 closure_def_id: c.closure_def_id,
708 nested: c.nested.into_iter().map(f).collect(),
710 ImplSource::Generator(c) => ImplSource::Generator(ImplSourceGeneratorData {
711 generator_def_id: c.generator_def_id,
713 nested: c.nested.into_iter().map(f).collect(),
715 ImplSource::FnPointer(p) => ImplSource::FnPointer(ImplSourceFnPointerData {
717 nested: p.nested.into_iter().map(f).collect(),
719 ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData) => {
720 ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData)
722 ImplSource::Pointee(ImplSourcePointeeData) => {
723 ImplSource::Pointee(ImplSourcePointeeData)
725 ImplSource::TraitAlias(d) => ImplSource::TraitAlias(ImplSourceTraitAliasData {
726 alias_def_id: d.alias_def_id,
728 nested: d.nested.into_iter().map(f).collect(),
730 ImplSource::TraitUpcasting(d) => {
731 ImplSource::TraitUpcasting(ImplSourceTraitUpcastingData {
732 upcast_trait_ref: d.upcast_trait_ref,
733 vtable_vptr_slot: d.vtable_vptr_slot,
734 nested: d.nested.into_iter().map(f).collect(),
737 ImplSource::ConstDestruct(i) => {
738 ImplSource::ConstDestruct(ImplSourceConstDestructData {
739 nested: i.nested.into_iter().map(f).collect(),
742 ImplSource::Tuple => ImplSource::Tuple,
747 /// Identifies a particular impl in the source, along with a set of
748 /// substitutions from the impl's type/lifetime parameters. The
749 /// `nested` vector corresponds to the nested obligations attached to
750 /// the impl's type parameters.
752 /// The type parameter `N` indicates the type used for "nested
753 /// obligations" that are required by the impl. During type-check, this
754 /// is `Obligation`, as one might expect. During codegen, however, this
755 /// is `()`, because codegen only requires a shallow resolution of an
756 /// impl, and nested obligations are satisfied later.
757 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
758 #[derive(TypeFoldable, TypeVisitable)]
759 pub struct ImplSourceUserDefinedData<'tcx, N> {
760 pub impl_def_id: DefId,
761 pub substs: SubstsRef<'tcx>,
765 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
766 #[derive(TypeFoldable, TypeVisitable)]
767 pub struct ImplSourceGeneratorData<'tcx, N> {
768 pub generator_def_id: DefId,
769 pub substs: SubstsRef<'tcx>,
770 /// Nested obligations. This can be non-empty if the generator
771 /// signature contains associated types.
775 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
776 #[derive(TypeFoldable, TypeVisitable)]
777 pub struct ImplSourceClosureData<'tcx, N> {
778 pub closure_def_id: DefId,
779 pub substs: SubstsRef<'tcx>,
780 /// Nested obligations. This can be non-empty if the closure
781 /// signature contains associated types.
785 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
786 #[derive(TypeFoldable, TypeVisitable)]
787 pub struct ImplSourceAutoImplData<N> {
788 pub trait_def_id: DefId,
792 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
793 #[derive(TypeFoldable, TypeVisitable)]
794 pub struct ImplSourceTraitUpcastingData<'tcx, N> {
795 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
796 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
798 /// The vtable is formed by concatenating together the method lists of
799 /// the base object trait and all supertraits, pointers to supertrait vtable will
800 /// be provided when necessary; this is the position of `upcast_trait_ref`'s vtable
801 /// within that vtable.
802 pub vtable_vptr_slot: Option<usize>,
807 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
808 #[derive(TypeFoldable, TypeVisitable)]
809 pub struct ImplSourceBuiltinData<N> {
813 #[derive(PartialEq, Eq, Clone, TyEncodable, TyDecodable, HashStable, Lift)]
814 #[derive(TypeFoldable, TypeVisitable)]
815 pub struct ImplSourceObjectData<'tcx, N> {
816 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
817 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
819 /// The vtable is formed by concatenating together the method lists of
820 /// the base object trait and all supertraits, pointers to supertrait vtable will
821 /// be provided when necessary; this is the start of `upcast_trait_ref`'s methods
823 pub vtable_base: usize,
828 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
829 #[derive(TypeFoldable, TypeVisitable)]
830 pub struct ImplSourceFnPointerData<'tcx, N> {
835 // FIXME(@lcnr): This should be refactored and merged with other builtin vtables.
836 #[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
837 pub struct ImplSourceDiscriminantKindData;
839 #[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
840 pub struct ImplSourcePointeeData;
842 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
843 #[derive(TypeFoldable, TypeVisitable)]
844 pub struct ImplSourceConstDestructData<N> {
848 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
849 #[derive(TypeFoldable, TypeVisitable)]
850 pub struct ImplSourceTraitAliasData<'tcx, N> {
851 pub alias_def_id: DefId,
852 pub substs: SubstsRef<'tcx>,
856 #[derive(Clone, Debug, PartialEq, Eq, Hash, HashStable, PartialOrd, Ord)]
857 pub enum ObjectSafetyViolation {
858 /// `Self: Sized` declared on the trait.
859 SizedSelf(SmallVec<[Span; 1]>),
861 /// Supertrait reference references `Self` an in illegal location
862 /// (e.g., `trait Foo : Bar<Self>`).
863 SupertraitSelf(SmallVec<[Span; 1]>),
865 /// Method has something illegal.
866 Method(Symbol, MethodViolationCode, Span),
868 /// Associated const.
869 AssocConst(Symbol, Span),
875 impl ObjectSafetyViolation {
876 pub fn error_msg(&self) -> Cow<'static, str> {
878 ObjectSafetyViolation::SizedSelf(_) => "it requires `Self: Sized`".into(),
879 ObjectSafetyViolation::SupertraitSelf(ref spans) => {
880 if spans.iter().any(|sp| *sp != DUMMY_SP) {
881 "it uses `Self` as a type parameter".into()
883 "it cannot use `Self` as a type parameter in a supertrait or `where`-clause"
887 ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod(_), _) => {
888 format!("associated function `{}` has no `self` parameter", name).into()
890 ObjectSafetyViolation::Method(
892 MethodViolationCode::ReferencesSelfInput(_),
894 ) => format!("method `{}` references the `Self` type in its parameters", name).into(),
895 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfInput(_), _) => {
896 format!("method `{}` references the `Self` type in this parameter", name).into()
898 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfOutput, _) => {
899 format!("method `{}` references the `Self` type in its return type", name).into()
901 ObjectSafetyViolation::Method(
903 MethodViolationCode::WhereClauseReferencesSelf,
906 format!("method `{}` references the `Self` type in its `where` clause", name).into()
908 ObjectSafetyViolation::Method(name, MethodViolationCode::Generic, _) => {
909 format!("method `{}` has generic type parameters", name).into()
911 ObjectSafetyViolation::Method(
913 MethodViolationCode::UndispatchableReceiver(_),
915 ) => format!("method `{}`'s `self` parameter cannot be dispatched on", name).into(),
916 ObjectSafetyViolation::AssocConst(name, DUMMY_SP) => {
917 format!("it contains associated `const` `{}`", name).into()
919 ObjectSafetyViolation::AssocConst(..) => "it contains this associated `const`".into(),
920 ObjectSafetyViolation::GAT(name, _) => {
921 format!("it contains the generic associated type `{}`", name).into()
926 pub fn solution(&self, err: &mut Diagnostic) {
928 ObjectSafetyViolation::SizedSelf(_) | ObjectSafetyViolation::SupertraitSelf(_) => {}
929 ObjectSafetyViolation::Method(
931 MethodViolationCode::StaticMethod(Some((add_self_sugg, make_sized_sugg))),
937 "consider turning `{}` into a method by giving it a `&self` argument",
940 add_self_sugg.0.to_string(),
941 Applicability::MaybeIncorrect,
946 "alternatively, consider constraining `{}` so it does not apply to \
950 make_sized_sugg.0.to_string(),
951 Applicability::MaybeIncorrect,
954 ObjectSafetyViolation::Method(
956 MethodViolationCode::UndispatchableReceiver(Some(span)),
962 "consider changing method `{}`'s `self` parameter to be `&self`",
966 Applicability::MachineApplicable,
969 ObjectSafetyViolation::AssocConst(name, _)
970 | ObjectSafetyViolation::GAT(name, _)
971 | ObjectSafetyViolation::Method(name, ..) => {
972 err.help(&format!("consider moving `{}` to another trait", name));
977 pub fn spans(&self) -> SmallVec<[Span; 1]> {
978 // When `span` comes from a separate crate, it'll be `DUMMY_SP`. Treat it as `None` so
979 // diagnostics use a `note` instead of a `span_label`.
981 ObjectSafetyViolation::SupertraitSelf(spans)
982 | ObjectSafetyViolation::SizedSelf(spans) => spans.clone(),
983 ObjectSafetyViolation::AssocConst(_, span)
984 | ObjectSafetyViolation::GAT(_, span)
985 | ObjectSafetyViolation::Method(_, _, span)
986 if *span != DUMMY_SP =>
995 /// Reasons a method might not be object-safe.
996 #[derive(Clone, Debug, PartialEq, Eq, Hash, HashStable, PartialOrd, Ord)]
997 pub enum MethodViolationCode {
999 StaticMethod(Option<(/* add &self */ (String, Span), /* add Self: Sized */ (String, Span))>),
1001 /// e.g., `fn foo(&self, x: Self)`
1002 ReferencesSelfInput(Option<Span>),
1004 /// e.g., `fn foo(&self) -> Self`
1005 ReferencesSelfOutput,
1007 /// e.g., `fn foo(&self) where Self: Clone`
1008 WhereClauseReferencesSelf,
1010 /// e.g., `fn foo<A>()`
1013 /// the method's receiver (`self` argument) can't be dispatched on
1014 UndispatchableReceiver(Option<Span>),
1017 /// These are the error cases for `codegen_fulfill_obligation`.
1018 #[derive(Copy, Clone, Debug, Hash, HashStable, Encodable, Decodable)]
1019 pub enum CodegenObligationError {
1020 /// Ambiguity can happen when monomorphizing during trans
1021 /// expands to some humongous type that never occurred
1022 /// statically -- this humongous type can then overflow,
1023 /// leading to an ambiguous result. So report this as an
1024 /// overflow bug, since I believe this is the only case
1025 /// where ambiguity can result.
1027 /// This can trigger when we probe for the source of a `'static` lifetime requirement
1028 /// on a trait object: `impl Foo for dyn Trait {}` has an implicit `'static` bound.
1029 /// This can also trigger when we have a global bound that is not actually satisfied,
1030 /// but was included during typeck due to the trivial_bounds feature.