rustc_middle/traits/
mod.rs

1//! Trait Resolution. See the [rustc dev guide] for more information on how this works.
2//!
3//! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html
4
5pub mod query;
6pub mod select;
7pub mod solve;
8pub mod specialization_graph;
9mod structural_impls;
10
11use std::borrow::Cow;
12use std::hash::{Hash, Hasher};
13use std::sync::Arc;
14
15use rustc_errors::{Applicability, Diag, EmissionGuarantee, ErrorGuaranteed};
16use rustc_hir as hir;
17use rustc_hir::HirId;
18use rustc_hir::def_id::DefId;
19use rustc_macros::{
20    Decodable, Encodable, HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable,
21};
22use rustc_span::def_id::{CRATE_DEF_ID, LocalDefId};
23use rustc_span::{DUMMY_SP, Span, Symbol};
24use smallvec::{SmallVec, smallvec};
25use thin_vec::ThinVec;
26
27pub use self::select::{EvaluationCache, EvaluationResult, OverflowError, SelectionCache};
28use crate::mir::ConstraintCategory;
29pub use crate::traits::solve::BuiltinImplSource;
30use crate::ty::abstract_const::NotConstEvaluatable;
31use crate::ty::{self, AdtKind, GenericArgsRef, Ty};
32
33/// The reason why we incurred this obligation; used for error reporting.
34///
35/// Non-misc `ObligationCauseCode`s are stored on the heap. This gives the
36/// best trade-off between keeping the type small (which makes copies cheaper)
37/// while not doing too many heap allocations.
38///
39/// We do not want to intern this as there are a lot of obligation causes which
40/// only live for a short period of time.
41#[derive(Clone, Debug, PartialEq, Eq, HashStable, TyEncodable, TyDecodable)]
42#[derive(TypeVisitable, TypeFoldable)]
43pub struct ObligationCause<'tcx> {
44    pub span: Span,
45
46    /// The ID of the fn body that triggered this obligation. This is
47    /// used for region obligations to determine the precise
48    /// environment in which the region obligation should be evaluated
49    /// (in particular, closures can add new assumptions). See the
50    /// field `region_obligations` of the `FulfillmentContext` for more
51    /// information.
52    pub body_id: LocalDefId,
53
54    code: ObligationCauseCodeHandle<'tcx>,
55}
56
57// This custom hash function speeds up hashing for `Obligation` deduplication
58// greatly by skipping the `code` field, which can be large and complex. That
59// shouldn't affect hash quality much since there are several other fields in
60// `Obligation` which should be unique enough, especially the predicate itself
61// which is hashed as an interned pointer. See #90996.
62impl Hash for ObligationCause<'_> {
63    fn hash<H: Hasher>(&self, state: &mut H) {
64        self.body_id.hash(state);
65        self.span.hash(state);
66    }
67}
68
69impl<'tcx> ObligationCause<'tcx> {
70    #[inline]
71    pub fn new(
72        span: Span,
73        body_id: LocalDefId,
74        code: ObligationCauseCode<'tcx>,
75    ) -> ObligationCause<'tcx> {
76        ObligationCause { span, body_id, code: code.into() }
77    }
78
79    pub fn misc(span: Span, body_id: LocalDefId) -> ObligationCause<'tcx> {
80        ObligationCause::new(span, body_id, ObligationCauseCode::Misc)
81    }
82
83    #[inline(always)]
84    pub fn dummy() -> ObligationCause<'tcx> {
85        ObligationCause::dummy_with_span(DUMMY_SP)
86    }
87
88    #[inline(always)]
89    pub fn dummy_with_span(span: Span) -> ObligationCause<'tcx> {
90        ObligationCause { span, body_id: CRATE_DEF_ID, code: Default::default() }
91    }
92
93    #[inline]
94    pub fn code(&self) -> &ObligationCauseCode<'tcx> {
95        &self.code
96    }
97
98    pub fn map_code(
99        &mut self,
100        f: impl FnOnce(ObligationCauseCodeHandle<'tcx>) -> ObligationCauseCode<'tcx>,
101    ) {
102        self.code = f(std::mem::take(&mut self.code)).into();
103    }
104
105    pub fn derived_cause(
106        mut self,
107        parent_trait_pred: ty::PolyTraitPredicate<'tcx>,
108        variant: impl FnOnce(DerivedCause<'tcx>) -> ObligationCauseCode<'tcx>,
109    ) -> ObligationCause<'tcx> {
110        /*!
111         * Creates a cause for obligations that are derived from
112         * `obligation` by a recursive search (e.g., for a builtin
113         * bound, or eventually a `auto trait Foo`). If `obligation`
114         * is itself a derived obligation, this is just a clone, but
115         * otherwise we create a "derived obligation" cause so as to
116         * keep track of the original root obligation for error
117         * reporting.
118         */
119
120        // NOTE(flaper87): As of now, it keeps track of the whole error
121        // chain. Ideally, we should have a way to configure this either
122        // by using -Z verbose-internals or just a CLI argument.
123        self.code = variant(DerivedCause { parent_trait_pred, parent_code: self.code }).into();
124        self
125    }
126
127    pub fn derived_host_cause(
128        mut self,
129        parent_host_pred: ty::Binder<'tcx, ty::HostEffectPredicate<'tcx>>,
130        variant: impl FnOnce(DerivedHostCause<'tcx>) -> ObligationCauseCode<'tcx>,
131    ) -> ObligationCause<'tcx> {
132        self.code = variant(DerivedHostCause { parent_host_pred, parent_code: self.code }).into();
133        self
134    }
135
136    pub fn to_constraint_category(&self) -> ConstraintCategory<'tcx> {
137        match self.code() {
138            ObligationCauseCode::MatchImpl(cause, _) => cause.to_constraint_category(),
139            ObligationCauseCode::AscribeUserTypeProvePredicate(predicate_span) => {
140                ConstraintCategory::Predicate(*predicate_span)
141            }
142            _ => ConstraintCategory::BoringNoLocation,
143        }
144    }
145}
146
147/// A compact form of `ObligationCauseCode`.
148#[derive(Clone, PartialEq, Eq, Default, HashStable)]
149#[derive(TypeVisitable, TypeFoldable, TyEncodable, TyDecodable)]
150pub struct ObligationCauseCodeHandle<'tcx> {
151    /// `None` for `ObligationCauseCode::Misc` (a common case, occurs ~60% of
152    /// the time). `Some` otherwise.
153    code: Option<Arc<ObligationCauseCode<'tcx>>>,
154}
155
156impl<'tcx> std::fmt::Debug for ObligationCauseCodeHandle<'tcx> {
157    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
158        let cause: &ObligationCauseCode<'_> = self;
159        cause.fmt(f)
160    }
161}
162
163impl<'tcx> ObligationCauseCode<'tcx> {
164    #[inline(always)]
165    fn into(self) -> ObligationCauseCodeHandle<'tcx> {
166        ObligationCauseCodeHandle {
167            code: if let ObligationCauseCode::Misc = self { None } else { Some(Arc::new(self)) },
168        }
169    }
170}
171
172impl<'tcx> std::ops::Deref for ObligationCauseCodeHandle<'tcx> {
173    type Target = ObligationCauseCode<'tcx>;
174
175    fn deref(&self) -> &Self::Target {
176        self.code.as_deref().unwrap_or(&ObligationCauseCode::Misc)
177    }
178}
179
180#[derive(Clone, Debug, PartialEq, Eq, HashStable, TyEncodable, TyDecodable)]
181#[derive(TypeVisitable, TypeFoldable)]
182pub enum ObligationCauseCode<'tcx> {
183    /// Not well classified or should be obvious from the span.
184    Misc,
185
186    /// A slice or array is WF only if `T: Sized`.
187    SliceOrArrayElem,
188
189    /// An array `[T; N]` can only be indexed (and is only well-formed if) `N` has type usize.
190    ArrayLen(Ty<'tcx>),
191
192    /// A tuple is WF only if its middle elements are `Sized`.
193    TupleElem,
194
195    /// Represents a clause that comes from a specific item.
196    /// The span corresponds to the clause.
197    WhereClause(DefId, Span),
198
199    /// Represents a bound for an opaque we are checking the well-formedness of.
200    /// The def-id corresponds to a specific definition site that we found the
201    /// hidden type from, if any.
202    OpaqueTypeBound(Span, Option<LocalDefId>),
203
204    /// Like `WhereClause`, but also identifies the expression
205    /// which requires the `where` clause to be proven, and also
206    /// identifies the index of the predicate in the `predicates_of`
207    /// list of the item.
208    WhereClauseInExpr(DefId, Span, HirId, usize),
209
210    /// Like `WhereClauseinExpr`, but indexes into the `const_conditions`
211    /// rather than the `predicates_of`.
212    HostEffectInExpr(DefId, Span, HirId, usize),
213
214    /// A type like `&'a T` is WF only if `T: 'a`.
215    ReferenceOutlivesReferent(Ty<'tcx>),
216
217    /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
218    ObjectTypeBound(Ty<'tcx>, ty::Region<'tcx>),
219
220    /// Obligation incurred due to a coercion.
221    Coercion {
222        source: Ty<'tcx>,
223        target: Ty<'tcx>,
224    },
225
226    /// Various cases where expressions must be `Sized` / `Copy` / etc.
227    /// `L = X` implies that `L` is `Sized`.
228    AssignmentLhsSized,
229    /// `(x1, .., xn)` must be `Sized`.
230    TupleInitializerSized,
231    /// `S { ... }` must be `Sized`.
232    StructInitializerSized,
233    /// Type of each variable must be `Sized`.
234    VariableType(HirId),
235    /// Argument type must be `Sized`.
236    SizedArgumentType(Option<HirId>),
237    /// Return type must be `Sized`.
238    SizedReturnType,
239    /// Return type of a call expression must be `Sized`.
240    SizedCallReturnType,
241    /// Yield type must be `Sized`.
242    SizedYieldType,
243    /// Inline asm operand type must be `Sized`.
244    InlineAsmSized,
245    /// Captured closure type must be `Sized`.
246    SizedClosureCapture(LocalDefId),
247    /// Types live across coroutine yields must be `Sized`.
248    SizedCoroutineInterior(LocalDefId),
249    /// `[expr; N]` requires `type_of(expr): Copy`.
250    RepeatElementCopy {
251        /// If element is a `const fn` or const ctor we display a help message suggesting
252        /// to move it to a new `const` item while saying that `T` doesn't implement `Copy`.
253        is_constable: IsConstable,
254
255        /// Span of the repeat element.
256        ///
257        /// This is used to suggest wrapping it in a `const { ... }` block.
258        elt_span: Span,
259    },
260
261    /// Types of fields (other than the last, except for packed structs) in a struct must be sized.
262    FieldSized {
263        adt_kind: AdtKind,
264        span: Span,
265        last: bool,
266    },
267
268    /// Constant expressions must be sized.
269    SizedConstOrStatic,
270
271    /// `static` items must have `Sync` type.
272    SharedStatic,
273
274    /// Derived obligation (i.e. theoretical `where` clause) on a built-in
275    /// implementation like `Copy` or `Sized`.
276    BuiltinDerived(DerivedCause<'tcx>),
277
278    /// Derived obligation (i.e. `where` clause) on an user-provided impl
279    /// or a trait alias.
280    ImplDerived(Box<ImplDerivedCause<'tcx>>),
281
282    /// Derived obligation for WF goals.
283    WellFormedDerived(DerivedCause<'tcx>),
284
285    /// Derived obligation (i.e. `where` clause) on an user-provided impl
286    /// or a trait alias.
287    ImplDerivedHost(Box<ImplDerivedHostCause<'tcx>>),
288
289    /// Derived obligation (i.e. `where` clause) on an user-provided impl
290    /// or a trait alias.
291    BuiltinDerivedHost(DerivedHostCause<'tcx>),
292
293    /// Derived obligation refined to point at a specific argument in
294    /// a call or method expression.
295    FunctionArg {
296        /// The node of the relevant argument in the function call.
297        arg_hir_id: HirId,
298        /// The node of the function call.
299        call_hir_id: HirId,
300        /// The obligation introduced by this argument.
301        parent_code: ObligationCauseCodeHandle<'tcx>,
302    },
303
304    /// Error derived when checking an impl item is compatible with
305    /// its corresponding trait item's definition
306    CompareImplItem {
307        impl_item_def_id: LocalDefId,
308        trait_item_def_id: DefId,
309        kind: ty::AssocKind,
310    },
311
312    /// Checking that the bounds of a trait's associated type hold for a given impl
313    CheckAssociatedTypeBounds {
314        impl_item_def_id: LocalDefId,
315        trait_item_def_id: DefId,
316    },
317
318    /// Checking that this expression can be assigned to its target.
319    ExprAssignable,
320
321    /// Computing common supertype in the arms of a match expression
322    MatchExpressionArm(Box<MatchExpressionArmCause<'tcx>>),
323
324    /// Type error arising from type checking a pattern against an expected type.
325    Pattern {
326        /// The span of the scrutinee or type expression which caused the `root_ty` type.
327        span: Option<Span>,
328        /// The root expected type induced by a scrutinee or type expression.
329        root_ty: Ty<'tcx>,
330        /// Information about the `Span`, if it came from an expression, otherwise `None`.
331        origin_expr: Option<PatternOriginExpr>,
332    },
333
334    /// Computing common supertype in an if expression
335    IfExpression(Box<IfExpressionCause<'tcx>>),
336
337    /// Computing common supertype of an if expression with no else counter-part
338    IfExpressionWithNoElse,
339
340    /// `main` has wrong type
341    MainFunctionType,
342
343    /// language function has wrong type
344    LangFunctionType(Symbol),
345
346    /// Intrinsic has wrong type
347    IntrinsicType,
348
349    /// A let else block does not diverge
350    LetElse,
351
352    /// Method receiver
353    MethodReceiver,
354
355    /// `return` with no expression
356    ReturnNoExpression,
357
358    /// `return` with an expression
359    ReturnValue(HirId),
360
361    /// Opaque return type of this function
362    OpaqueReturnType(Option<(Ty<'tcx>, HirId)>),
363
364    /// Block implicit return
365    BlockTailExpression(HirId, hir::MatchSource),
366
367    /// #[feature(trivial_bounds)] is not enabled
368    TrivialBound,
369
370    AwaitableExpr(HirId),
371
372    ForLoopIterator,
373
374    QuestionMark,
375
376    /// Well-formed checking. If a `WellFormedLoc` is provided,
377    /// then it will be used to perform HIR-based wf checking
378    /// after an error occurs, in order to generate a more precise error span.
379    /// This is purely for diagnostic purposes - it is always
380    /// correct to use `Misc` instead, or to specify
381    /// `WellFormed(None)`.
382    WellFormed(Option<WellFormedLoc>),
383
384    /// From `match_impl`. The cause for us having to match an impl, and the DefId we are matching
385    /// against.
386    MatchImpl(ObligationCause<'tcx>, DefId),
387
388    BinOp {
389        lhs_hir_id: HirId,
390        rhs_hir_id: Option<HirId>,
391        rhs_span: Option<Span>,
392        rhs_is_lit: bool,
393        output_ty: Option<Ty<'tcx>>,
394    },
395
396    AscribeUserTypeProvePredicate(Span),
397
398    RustCall,
399
400    DynCompatible(Span),
401
402    /// Obligations to prove that a `Drop` or negative auto trait impl is not stronger than
403    /// the ADT it's being implemented for.
404    AlwaysApplicableImpl,
405
406    /// Requirement for a `const N: Ty` to implement `Ty: ConstParamTy`
407    ConstParam(Ty<'tcx>),
408
409    /// Obligations emitted during the normalization of a free type alias.
410    TypeAlias(ObligationCauseCodeHandle<'tcx>, Span, DefId),
411}
412
413/// Whether a value can be extracted into a const.
414/// Used for diagnostics around array repeat expressions.
415#[derive(Copy, Clone, Debug, PartialEq, Eq, HashStable, TyEncodable, TyDecodable)]
416pub enum IsConstable {
417    No,
418    /// Call to a const fn
419    Fn,
420    /// Use of a const ctor
421    Ctor,
422}
423
424/// The 'location' at which we try to perform HIR-based wf checking.
425/// This information is used to obtain an `hir::Ty`, which
426/// we can walk in order to obtain precise spans for any
427/// 'nested' types (e.g. `Foo` in `Option<Foo>`).
428#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable, Encodable, Decodable)]
429#[derive(TypeVisitable, TypeFoldable)]
430pub enum WellFormedLoc {
431    /// Use the type of the provided definition.
432    Ty(LocalDefId),
433    /// Use the type of the parameter of the provided function.
434    /// We cannot use `hir::Param`, since the function may
435    /// not have a body (e.g. a trait method definition)
436    Param {
437        /// The function to lookup the parameter in
438        function: LocalDefId,
439        /// The index of the parameter to use.
440        /// Parameters are indexed from 0, with the return type
441        /// being the last 'parameter'
442        param_idx: usize,
443    },
444}
445
446impl<'tcx> ObligationCauseCode<'tcx> {
447    /// Returns the base obligation, ignoring derived obligations.
448    pub fn peel_derives(&self) -> &Self {
449        let mut base_cause = self;
450        while let Some(parent_code) = base_cause.parent() {
451            base_cause = parent_code;
452        }
453        base_cause
454    }
455
456    pub fn parent(&self) -> Option<&Self> {
457        match self {
458            ObligationCauseCode::FunctionArg { parent_code, .. } => Some(parent_code),
459            ObligationCauseCode::BuiltinDerived(derived)
460            | ObligationCauseCode::WellFormedDerived(derived)
461            | ObligationCauseCode::ImplDerived(box ImplDerivedCause { derived, .. }) => {
462                Some(&derived.parent_code)
463            }
464            ObligationCauseCode::BuiltinDerivedHost(derived)
465            | ObligationCauseCode::ImplDerivedHost(box ImplDerivedHostCause { derived, .. }) => {
466                Some(&derived.parent_code)
467            }
468            _ => None,
469        }
470    }
471
472    /// Returns the base obligation and the base trait predicate, if any, ignoring
473    /// derived obligations.
474    pub fn peel_derives_with_predicate(&self) -> (&Self, Option<ty::PolyTraitPredicate<'tcx>>) {
475        let mut base_cause = self;
476        let mut base_trait_pred = None;
477        while let Some((parent_code, parent_pred)) = base_cause.parent_with_predicate() {
478            base_cause = parent_code;
479            if let Some(parent_pred) = parent_pred {
480                base_trait_pred = Some(parent_pred);
481            }
482        }
483
484        (base_cause, base_trait_pred)
485    }
486
487    pub fn parent_with_predicate(&self) -> Option<(&Self, Option<ty::PolyTraitPredicate<'tcx>>)> {
488        match self {
489            ObligationCauseCode::FunctionArg { parent_code, .. } => Some((parent_code, None)),
490            ObligationCauseCode::BuiltinDerived(derived)
491            | ObligationCauseCode::WellFormedDerived(derived)
492            | ObligationCauseCode::ImplDerived(box ImplDerivedCause { derived, .. }) => {
493                Some((&derived.parent_code, Some(derived.parent_trait_pred)))
494            }
495            _ => None,
496        }
497    }
498
499    pub fn peel_match_impls(&self) -> &Self {
500        match self {
501            ObligationCauseCode::MatchImpl(cause, _) => cause.code(),
502            _ => self,
503        }
504    }
505}
506
507// `ObligationCauseCode` is used a lot. Make sure it doesn't unintentionally get bigger.
508#[cfg(target_pointer_width = "64")]
509rustc_data_structures::static_assert_size!(ObligationCauseCode<'_>, 48);
510
511#[derive(Clone, Debug, PartialEq, Eq, HashStable, TyEncodable, TyDecodable)]
512#[derive(TypeVisitable, TypeFoldable)]
513pub struct MatchExpressionArmCause<'tcx> {
514    pub arm_block_id: Option<HirId>,
515    pub arm_ty: Ty<'tcx>,
516    pub arm_span: Span,
517    pub prior_arm_block_id: Option<HirId>,
518    pub prior_arm_ty: Ty<'tcx>,
519    pub prior_arm_span: Span,
520    /// Span of the scrutinee of the match (the matched value).
521    pub scrut_span: Span,
522    /// Source of the match, i.e. `match` or a desugaring.
523    pub source: hir::MatchSource,
524    /// Span of the *whole* match expr.
525    pub expr_span: Span,
526    /// Spans of the previous arms except for those that diverge (i.e. evaluate to `!`).
527    ///
528    /// These are used for pointing out errors that may affect several arms.
529    pub prior_non_diverging_arms: Vec<Span>,
530    /// Is the expectation of this match expression an RPIT?
531    pub tail_defines_return_position_impl_trait: Option<LocalDefId>,
532}
533
534/// Information about the origin expression of a pattern, relevant to diagnostics.
535/// Fields here refer to the scrutinee of a pattern.
536/// If the scrutinee isn't given in the diagnostic, then this won't exist.
537#[derive(Copy, Clone, Debug, PartialEq, Eq)]
538#[derive(TypeFoldable, TypeVisitable, HashStable, TyEncodable, TyDecodable)]
539pub struct PatternOriginExpr {
540    /// A span representing the scrutinee expression, with all leading references
541    /// peeled from the expression.
542    /// Only references in the expression are peeled - if the expression refers to a variable
543    /// whose type is a reference, then that reference is kept because it wasn't created
544    /// in the expression.
545    pub peeled_span: Span,
546    /// The number of references that were peeled to produce `peeled_span`.
547    pub peeled_count: usize,
548    /// Does the peeled expression need to be wrapped in parentheses for
549    /// a prefix suggestion (i.e., dereference) to be valid.
550    pub peeled_prefix_suggestion_parentheses: bool,
551}
552
553#[derive(Copy, Clone, Debug, PartialEq, Eq)]
554#[derive(TypeFoldable, TypeVisitable, HashStable, TyEncodable, TyDecodable)]
555pub struct IfExpressionCause<'tcx> {
556    pub then_id: HirId,
557    pub else_id: HirId,
558    pub then_ty: Ty<'tcx>,
559    pub else_ty: Ty<'tcx>,
560    pub outer_span: Option<Span>,
561    // Is the expectation of this match expression an RPIT?
562    pub tail_defines_return_position_impl_trait: Option<LocalDefId>,
563}
564
565#[derive(Clone, Debug, PartialEq, Eq, HashStable, TyEncodable, TyDecodable)]
566#[derive(TypeVisitable, TypeFoldable)]
567pub struct DerivedCause<'tcx> {
568    /// The trait predicate of the parent obligation that led to the
569    /// current obligation. Note that only trait obligations lead to
570    /// derived obligations, so we just store the trait predicate here
571    /// directly.
572    pub parent_trait_pred: ty::PolyTraitPredicate<'tcx>,
573
574    /// The parent trait had this cause.
575    pub parent_code: ObligationCauseCodeHandle<'tcx>,
576}
577
578#[derive(Clone, Debug, PartialEq, Eq, HashStable, TyEncodable, TyDecodable)]
579#[derive(TypeVisitable, TypeFoldable)]
580pub struct ImplDerivedCause<'tcx> {
581    pub derived: DerivedCause<'tcx>,
582    /// The `DefId` of the `impl` that gave rise to the `derived` obligation.
583    /// If the `derived` obligation arose from a trait alias, which conceptually has a synthetic
584    /// impl, then this will be the `DefId` of that trait alias. Care should therefore be taken to
585    /// handle that exceptional case where appropriate.
586    pub impl_or_alias_def_id: DefId,
587    /// The index of the derived predicate in the parent impl's predicates.
588    pub impl_def_predicate_index: Option<usize>,
589    pub span: Span,
590}
591
592#[derive(Clone, Debug, PartialEq, Eq, HashStable, TyEncodable, TyDecodable)]
593#[derive(TypeVisitable, TypeFoldable)]
594pub struct DerivedHostCause<'tcx> {
595    /// The trait predicate of the parent obligation that led to the
596    /// current obligation. Note that only trait obligations lead to
597    /// derived obligations, so we just store the trait predicate here
598    /// directly.
599    pub parent_host_pred: ty::Binder<'tcx, ty::HostEffectPredicate<'tcx>>,
600
601    /// The parent trait had this cause.
602    pub parent_code: ObligationCauseCodeHandle<'tcx>,
603}
604
605#[derive(Clone, Debug, PartialEq, Eq, HashStable, TyEncodable, TyDecodable)]
606#[derive(TypeVisitable, TypeFoldable)]
607pub struct ImplDerivedHostCause<'tcx> {
608    pub derived: DerivedHostCause<'tcx>,
609    /// The `DefId` of the `impl` that gave rise to the `derived` obligation.
610    pub impl_def_id: DefId,
611    pub span: Span,
612}
613
614#[derive(Clone, Debug, PartialEq, Eq, TypeVisitable)]
615pub enum SelectionError<'tcx> {
616    /// The trait is not implemented.
617    Unimplemented,
618    /// After a closure impl has selected, its "outputs" were evaluated
619    /// (which for closures includes the "input" type params) and they
620    /// didn't resolve. See `confirm_poly_trait_refs` for more.
621    SignatureMismatch(Box<SignatureMismatchData<'tcx>>),
622    /// The trait pointed by `DefId` is dyn-incompatible.
623    TraitDynIncompatible(DefId),
624    /// A given constant couldn't be evaluated.
625    NotConstEvaluatable(NotConstEvaluatable),
626    /// Exceeded the recursion depth during type projection.
627    Overflow(OverflowError),
628    /// Computing an opaque type's hidden type caused an error (e.g. a cycle error).
629    /// We can thus not know whether the hidden type implements an auto trait, so
630    /// we should not presume anything about it.
631    OpaqueTypeAutoTraitLeakageUnknown(DefId),
632    /// Error for a `ConstArgHasType` goal
633    ConstArgHasWrongType { ct: ty::Const<'tcx>, ct_ty: Ty<'tcx>, expected_ty: Ty<'tcx> },
634}
635
636#[derive(Clone, Debug, PartialEq, Eq, TypeVisitable)]
637pub struct SignatureMismatchData<'tcx> {
638    pub found_trait_ref: ty::TraitRef<'tcx>,
639    pub expected_trait_ref: ty::TraitRef<'tcx>,
640    pub terr: ty::error::TypeError<'tcx>,
641}
642
643/// When performing resolution, it is typically the case that there
644/// can be one of three outcomes:
645///
646/// - `Ok(Some(r))`: success occurred with result `r`
647/// - `Ok(None)`: could not definitely determine anything, usually due
648///   to inconclusive type inference.
649/// - `Err(e)`: error `e` occurred
650pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
651
652/// Given the successful resolution of an obligation, the `ImplSource`
653/// indicates where the impl comes from.
654///
655/// For example, the obligation may be satisfied by a specific impl (case A),
656/// or it may be relative to some bound that is in scope (case B).
657///
658/// ```ignore (illustrative)
659/// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
660/// impl<T:Clone> Clone<T> for Box<T> { ... }    // Impl_2
661/// impl Clone for i32 { ... }                   // Impl_3
662///
663/// fn foo<T: Clone>(concrete: Option<Box<i32>>, param: T, mixed: Option<T>) {
664///     // Case A: ImplSource points at a specific impl. Only possible when
665///     // type is concretely known. If the impl itself has bounded
666///     // type parameters, ImplSource will carry resolutions for those as well:
667///     concrete.clone(); // ImplSource(Impl_1, [ImplSource(Impl_2, [ImplSource(Impl_3)])])
668///
669///     // Case B: ImplSource must be provided by caller. This applies when
670///     // type is a type parameter.
671///     param.clone();    // ImplSource::Param
672///
673///     // Case C: A mix of cases A and B.
674///     mixed.clone();    // ImplSource(Impl_1, [ImplSource::Param])
675/// }
676/// ```
677///
678/// ### The type parameter `N`
679///
680/// See explanation on `ImplSourceUserDefinedData`.
681#[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
682#[derive(TypeFoldable, TypeVisitable)]
683pub enum ImplSource<'tcx, N> {
684    /// ImplSource identifying a particular impl.
685    UserDefined(ImplSourceUserDefinedData<'tcx, N>),
686
687    /// Successful resolution to an obligation provided by the caller
688    /// for some type parameter. The `Vec<N>` represents the
689    /// obligations incurred from normalizing the where-clause (if
690    /// any).
691    Param(ThinVec<N>),
692
693    /// Successful resolution for a builtin impl.
694    Builtin(BuiltinImplSource, ThinVec<N>),
695}
696
697impl<'tcx, N> ImplSource<'tcx, N> {
698    pub fn nested_obligations(self) -> ThinVec<N> {
699        match self {
700            ImplSource::UserDefined(i) => i.nested,
701            ImplSource::Param(n) | ImplSource::Builtin(_, n) => n,
702        }
703    }
704
705    pub fn borrow_nested_obligations(&self) -> &[N] {
706        match self {
707            ImplSource::UserDefined(i) => &i.nested,
708            ImplSource::Param(n) | ImplSource::Builtin(_, n) => n,
709        }
710    }
711
712    pub fn borrow_nested_obligations_mut(&mut self) -> &mut [N] {
713        match self {
714            ImplSource::UserDefined(i) => &mut i.nested,
715            ImplSource::Param(n) | ImplSource::Builtin(_, n) => n,
716        }
717    }
718
719    pub fn map<M, F>(self, f: F) -> ImplSource<'tcx, M>
720    where
721        F: FnMut(N) -> M,
722    {
723        match self {
724            ImplSource::UserDefined(i) => ImplSource::UserDefined(ImplSourceUserDefinedData {
725                impl_def_id: i.impl_def_id,
726                args: i.args,
727                nested: i.nested.into_iter().map(f).collect(),
728            }),
729            ImplSource::Param(n) => ImplSource::Param(n.into_iter().map(f).collect()),
730            ImplSource::Builtin(source, n) => {
731                ImplSource::Builtin(source, n.into_iter().map(f).collect())
732            }
733        }
734    }
735}
736
737/// Identifies a particular impl in the source, along with a set of
738/// generic parameters from the impl's type/lifetime parameters. The
739/// `nested` vector corresponds to the nested obligations attached to
740/// the impl's type parameters.
741///
742/// The type parameter `N` indicates the type used for "nested
743/// obligations" that are required by the impl. During type-check, this
744/// is `Obligation`, as one might expect. During codegen, however, this
745/// is `()`, because codegen only requires a shallow resolution of an
746/// impl, and nested obligations are satisfied later.
747#[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
748#[derive(TypeFoldable, TypeVisitable)]
749pub struct ImplSourceUserDefinedData<'tcx, N> {
750    pub impl_def_id: DefId,
751    pub args: GenericArgsRef<'tcx>,
752    pub nested: ThinVec<N>,
753}
754
755#[derive(Clone, Debug, PartialEq, Eq, Hash, HashStable, PartialOrd, Ord)]
756pub enum DynCompatibilityViolation {
757    /// `Self: Sized` declared on the trait.
758    SizedSelf(SmallVec<[Span; 1]>),
759
760    /// Supertrait reference references `Self` an in illegal location
761    /// (e.g., `trait Foo : Bar<Self>`).
762    SupertraitSelf(SmallVec<[Span; 1]>),
763
764    // Supertrait has a non-lifetime `for<T>` binder.
765    SupertraitNonLifetimeBinder(SmallVec<[Span; 1]>),
766
767    /// Method has something illegal.
768    Method(Symbol, MethodViolationCode, Span),
769
770    /// Associated const.
771    AssocConst(Symbol, Span),
772
773    /// GAT
774    GAT(Symbol, Span),
775}
776
777impl DynCompatibilityViolation {
778    pub fn error_msg(&self) -> Cow<'static, str> {
779        match self {
780            DynCompatibilityViolation::SizedSelf(_) => "it requires `Self: Sized`".into(),
781            DynCompatibilityViolation::SupertraitSelf(spans) => {
782                if spans.iter().any(|sp| *sp != DUMMY_SP) {
783                    "it uses `Self` as a type parameter".into()
784                } else {
785                    "it cannot use `Self` as a type parameter in a supertrait or `where`-clause"
786                        .into()
787                }
788            }
789            DynCompatibilityViolation::SupertraitNonLifetimeBinder(_) => {
790                "where clause cannot reference non-lifetime `for<...>` variables".into()
791            }
792            DynCompatibilityViolation::Method(name, MethodViolationCode::StaticMethod(_), _) => {
793                format!("associated function `{name}` has no `self` parameter").into()
794            }
795            DynCompatibilityViolation::Method(
796                name,
797                MethodViolationCode::ReferencesSelfInput(_),
798                DUMMY_SP,
799            ) => format!("method `{name}` references the `Self` type in its parameters").into(),
800            DynCompatibilityViolation::Method(
801                name,
802                MethodViolationCode::ReferencesSelfInput(_),
803                _,
804            ) => format!("method `{name}` references the `Self` type in this parameter").into(),
805            DynCompatibilityViolation::Method(
806                name,
807                MethodViolationCode::ReferencesSelfOutput,
808                _,
809            ) => format!("method `{name}` references the `Self` type in its return type").into(),
810            DynCompatibilityViolation::Method(
811                name,
812                MethodViolationCode::ReferencesImplTraitInTrait(_),
813                _,
814            ) => {
815                format!("method `{name}` references an `impl Trait` type in its return type").into()
816            }
817            DynCompatibilityViolation::Method(name, MethodViolationCode::AsyncFn, _) => {
818                format!("method `{name}` is `async`").into()
819            }
820            DynCompatibilityViolation::Method(
821                name,
822                MethodViolationCode::WhereClauseReferencesSelf,
823                _,
824            ) => format!("method `{name}` references the `Self` type in its `where` clause").into(),
825            DynCompatibilityViolation::Method(name, MethodViolationCode::Generic, _) => {
826                format!("method `{name}` has generic type parameters").into()
827            }
828            DynCompatibilityViolation::Method(
829                name,
830                MethodViolationCode::UndispatchableReceiver(_),
831                _,
832            ) => format!("method `{name}`'s `self` parameter cannot be dispatched on").into(),
833            DynCompatibilityViolation::AssocConst(name, DUMMY_SP) => {
834                format!("it contains associated `const` `{name}`").into()
835            }
836            DynCompatibilityViolation::AssocConst(..) => {
837                "it contains this associated `const`".into()
838            }
839            DynCompatibilityViolation::GAT(name, _) => {
840                format!("it contains the generic associated type `{name}`").into()
841            }
842        }
843    }
844
845    pub fn solution(&self) -> DynCompatibilityViolationSolution {
846        match self {
847            DynCompatibilityViolation::SizedSelf(_)
848            | DynCompatibilityViolation::SupertraitSelf(_)
849            | DynCompatibilityViolation::SupertraitNonLifetimeBinder(..) => {
850                DynCompatibilityViolationSolution::None
851            }
852            DynCompatibilityViolation::Method(
853                name,
854                MethodViolationCode::StaticMethod(Some((add_self_sugg, make_sized_sugg))),
855                _,
856            ) => DynCompatibilityViolationSolution::AddSelfOrMakeSized {
857                name: *name,
858                add_self_sugg: add_self_sugg.clone(),
859                make_sized_sugg: make_sized_sugg.clone(),
860            },
861            DynCompatibilityViolation::Method(
862                name,
863                MethodViolationCode::UndispatchableReceiver(Some(span)),
864                _,
865            ) => DynCompatibilityViolationSolution::ChangeToRefSelf(*name, *span),
866            DynCompatibilityViolation::AssocConst(name, _)
867            | DynCompatibilityViolation::GAT(name, _)
868            | DynCompatibilityViolation::Method(name, ..) => {
869                DynCompatibilityViolationSolution::MoveToAnotherTrait(*name)
870            }
871        }
872    }
873
874    pub fn spans(&self) -> SmallVec<[Span; 1]> {
875        // When `span` comes from a separate crate, it'll be `DUMMY_SP`. Treat it as `None` so
876        // diagnostics use a `note` instead of a `span_label`.
877        match self {
878            DynCompatibilityViolation::SupertraitSelf(spans)
879            | DynCompatibilityViolation::SizedSelf(spans)
880            | DynCompatibilityViolation::SupertraitNonLifetimeBinder(spans) => spans.clone(),
881            DynCompatibilityViolation::AssocConst(_, span)
882            | DynCompatibilityViolation::GAT(_, span)
883            | DynCompatibilityViolation::Method(_, _, span)
884                if *span != DUMMY_SP =>
885            {
886                smallvec![*span]
887            }
888            _ => smallvec![],
889        }
890    }
891}
892
893#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
894pub enum DynCompatibilityViolationSolution {
895    None,
896    AddSelfOrMakeSized {
897        name: Symbol,
898        add_self_sugg: (String, Span),
899        make_sized_sugg: (String, Span),
900    },
901    ChangeToRefSelf(Symbol, Span),
902    MoveToAnotherTrait(Symbol),
903}
904
905impl DynCompatibilityViolationSolution {
906    pub fn add_to<G: EmissionGuarantee>(self, err: &mut Diag<'_, G>) {
907        match self {
908            DynCompatibilityViolationSolution::None => {}
909            DynCompatibilityViolationSolution::AddSelfOrMakeSized {
910                name,
911                add_self_sugg,
912                make_sized_sugg,
913            } => {
914                err.span_suggestion(
915                    add_self_sugg.1,
916                    format!(
917                        "consider turning `{name}` into a method by giving it a `&self` argument"
918                    ),
919                    add_self_sugg.0,
920                    Applicability::MaybeIncorrect,
921                );
922                err.span_suggestion(
923                    make_sized_sugg.1,
924                    format!(
925                        "alternatively, consider constraining `{name}` so it does not apply to \
926                             trait objects"
927                    ),
928                    make_sized_sugg.0,
929                    Applicability::MaybeIncorrect,
930                );
931            }
932            DynCompatibilityViolationSolution::ChangeToRefSelf(name, span) => {
933                err.span_suggestion(
934                    span,
935                    format!("consider changing method `{name}`'s `self` parameter to be `&self`"),
936                    "&Self",
937                    Applicability::MachineApplicable,
938                );
939            }
940            DynCompatibilityViolationSolution::MoveToAnotherTrait(name) => {
941                err.help(format!("consider moving `{name}` to another trait"));
942            }
943        }
944    }
945}
946
947/// Reasons a method might not be dyn-compatible.
948#[derive(Clone, Debug, PartialEq, Eq, Hash, HashStable, PartialOrd, Ord)]
949pub enum MethodViolationCode {
950    /// e.g., `fn foo()`
951    StaticMethod(Option<(/* add &self */ (String, Span), /* add Self: Sized */ (String, Span))>),
952
953    /// e.g., `fn foo(&self, x: Self)`
954    ReferencesSelfInput(Option<Span>),
955
956    /// e.g., `fn foo(&self) -> Self`
957    ReferencesSelfOutput,
958
959    /// e.g., `fn foo(&self) -> impl Sized`
960    ReferencesImplTraitInTrait(Span),
961
962    /// e.g., `async fn foo(&self)`
963    AsyncFn,
964
965    /// e.g., `fn foo(&self) where Self: Clone`
966    WhereClauseReferencesSelf,
967
968    /// e.g., `fn foo<A>()`
969    Generic,
970
971    /// the method's receiver (`self` argument) can't be dispatched on
972    UndispatchableReceiver(Option<Span>),
973}
974
975/// These are the error cases for `codegen_select_candidate`.
976#[derive(Copy, Clone, Debug, Hash, HashStable, Encodable, Decodable)]
977pub enum CodegenObligationError {
978    /// Ambiguity can happen when monomorphizing during trans
979    /// expands to some humongous type that never occurred
980    /// statically -- this humongous type can then overflow,
981    /// leading to an ambiguous result. So report this as an
982    /// overflow bug, since I believe this is the only case
983    /// where ambiguity can result.
984    Ambiguity,
985    /// This can trigger when we have a global bound that is not actually satisfied
986    /// due to trivial bounds.
987    Unimplemented,
988    /// The selected impl has unconstrained generic parameters. This will emit an error
989    /// during impl WF checking.
990    UnconstrainedParam(ErrorGuaranteed),
991}