]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/traits/mod.rs
cf3dce48064923a0b582c25ca028827c673eecdf
[rust.git] / compiler / rustc_middle / src / 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
5 mod chalk;
6 pub mod query;
7 pub mod select;
8 pub mod specialization_graph;
9 mod structural_impls;
10 pub mod util;
11
12 use crate::infer::canonical::Canonical;
13 use crate::mir::ConstraintCategory;
14 use crate::ty::abstract_const::NotConstEvaluatable;
15 use crate::ty::subst::SubstsRef;
16 use crate::ty::{self, AdtKind, Ty, TyCtxt};
17
18 use rustc_data_structures::sync::Lrc;
19 use rustc_errors::{Applicability, Diagnostic};
20 use rustc_hir as hir;
21 use rustc_hir::def_id::DefId;
22 use rustc_span::def_id::{LocalDefId, CRATE_DEF_ID};
23 use rustc_span::symbol::Symbol;
24 use rustc_span::{Span, DUMMY_SP};
25 use smallvec::SmallVec;
26
27 use std::borrow::Cow;
28 use std::hash::{Hash, Hasher};
29
30 pub use self::select::{EvaluationCache, EvaluationResult, OverflowError, SelectionCache};
31
32 pub type CanonicalChalkEnvironmentAndGoal<'tcx> = Canonical<'tcx, ChalkEnvironmentAndGoal<'tcx>>;
33
34 pub use self::ObligationCauseCode::*;
35
36 pub use self::chalk::{ChalkEnvironmentAndGoal, RustInterner as ChalkRustInterner};
37
38 /// Depending on the stage of compilation, we want projection to be
39 /// more or less conservative.
40 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, HashStable, Encodable, Decodable)]
41 pub enum Reveal {
42     /// At type-checking time, we refuse to project any associated
43     /// type that is marked `default`. Non-`default` ("final") types
44     /// are always projected. This is necessary in general for
45     /// soundness of specialization. However, we *could* allow
46     /// projections in fully-monomorphic cases. We choose not to,
47     /// because we prefer for `default type` to force the type
48     /// definition to be treated abstractly by any consumers of the
49     /// impl. Concretely, that means that the following example will
50     /// fail to compile:
51     ///
52     /// ```compile_fail,E0308
53     /// #![feature(specialization)]
54     /// trait Assoc {
55     ///     type Output;
56     /// }
57     ///
58     /// impl<T> Assoc for T {
59     ///     default type Output = bool;
60     /// }
61     ///
62     /// fn main() {
63     ///     let x: <() as Assoc>::Output = true;
64     /// }
65     /// ```
66     ///
67     /// We also do not reveal the hidden type of opaque types during
68     /// type-checking.
69     UserFacing,
70
71     /// At codegen time, all monomorphic projections will succeed.
72     /// Also, `impl Trait` is normalized to the concrete type,
73     /// which has to be already collected by type-checking.
74     ///
75     /// NOTE: as `impl Trait`'s concrete type should *never*
76     /// be observable directly by the user, `Reveal::All`
77     /// should not be used by checks which may expose
78     /// type equality or type contents to the user.
79     /// There are some exceptions, e.g., around auto traits and
80     /// transmute-checking, which expose some details, but
81     /// not the whole concrete type of the `impl Trait`.
82     All,
83 }
84
85 /// The reason why we incurred this obligation; used for error reporting.
86 ///
87 /// Non-misc `ObligationCauseCode`s are stored on the heap. This gives the
88 /// best trade-off between keeping the type small (which makes copies cheaper)
89 /// while not doing too many heap allocations.
90 ///
91 /// We do not want to intern this as there are a lot of obligation causes which
92 /// only live for a short period of time.
93 #[derive(Clone, Debug, PartialEq, Eq, Lift, HashStable, TyEncodable, TyDecodable)]
94 #[derive(TypeVisitable, TypeFoldable)]
95 pub struct ObligationCause<'tcx> {
96     pub span: Span,
97
98     /// The ID of the fn body that triggered this obligation. This is
99     /// used for region obligations to determine the precise
100     /// environment in which the region obligation should be evaluated
101     /// (in particular, closures can add new assumptions). See the
102     /// field `region_obligations` of the `FulfillmentContext` for more
103     /// information.
104     pub body_id: LocalDefId,
105
106     code: InternedObligationCauseCode<'tcx>,
107 }
108
109 // This custom hash function speeds up hashing for `Obligation` deduplication
110 // greatly by skipping the `code` field, which can be large and complex. That
111 // shouldn't affect hash quality much since there are several other fields in
112 // `Obligation` which should be unique enough, especially the predicate itself
113 // which is hashed as an interned pointer. See #90996.
114 impl Hash for ObligationCause<'_> {
115     fn hash<H: Hasher>(&self, state: &mut H) {
116         self.body_id.hash(state);
117         self.span.hash(state);
118     }
119 }
120
121 impl<'tcx> ObligationCause<'tcx> {
122     #[inline]
123     pub fn new(
124         span: Span,
125         body_id: LocalDefId,
126         code: ObligationCauseCode<'tcx>,
127     ) -> ObligationCause<'tcx> {
128         ObligationCause { span, body_id, code: code.into() }
129     }
130
131     pub fn misc(span: Span, body_id: LocalDefId) -> ObligationCause<'tcx> {
132         ObligationCause::new(span, body_id, MiscObligation)
133     }
134
135     #[inline(always)]
136     pub fn dummy() -> ObligationCause<'tcx> {
137         ObligationCause::dummy_with_span(DUMMY_SP)
138     }
139
140     #[inline(always)]
141     pub fn dummy_with_span(span: Span) -> ObligationCause<'tcx> {
142         ObligationCause { span, body_id: CRATE_DEF_ID, code: Default::default() }
143     }
144
145     pub fn span(&self) -> Span {
146         match *self.code() {
147             ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
148                 arm_span,
149                 ..
150             }) => arm_span,
151             _ => self.span,
152         }
153     }
154
155     #[inline]
156     pub fn code(&self) -> &ObligationCauseCode<'tcx> {
157         &self.code
158     }
159
160     pub fn map_code(
161         &mut self,
162         f: impl FnOnce(InternedObligationCauseCode<'tcx>) -> ObligationCauseCode<'tcx>,
163     ) {
164         self.code = f(std::mem::take(&mut self.code)).into();
165     }
166
167     pub fn derived_cause(
168         mut self,
169         parent_trait_pred: ty::PolyTraitPredicate<'tcx>,
170         variant: impl FnOnce(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
171     ) -> ObligationCause<'tcx> {
172         /*!
173          * Creates a cause for obligations that are derived from
174          * `obligation` by a recursive search (e.g., for a builtin
175          * bound, or eventually a `auto trait Foo`). If `obligation`
176          * is itself a derived obligation, this is just a clone, but
177          * otherwise we create a "derived obligation" cause so as to
178          * keep track of the original root obligation for error
179          * reporting.
180          */
181
182         // NOTE(flaper87): As of now, it keeps track of the whole error
183         // chain. Ideally, we should have a way to configure this either
184         // by using -Z verbose or just a CLI argument.
185         self.code =
186             variant(DerivedObligationCause { parent_trait_pred, parent_code: self.code }).into();
187         self
188     }
189
190     pub fn to_constraint_category(&self) -> ConstraintCategory<'tcx> {
191         match self.code() {
192             MatchImpl(cause, _) => cause.to_constraint_category(),
193             AscribeUserTypeProvePredicate(predicate_span) => {
194                 ConstraintCategory::Predicate(*predicate_span)
195             }
196             _ => ConstraintCategory::BoringNoLocation,
197         }
198     }
199 }
200
201 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift, HashStable, TyEncodable, TyDecodable)]
202 #[derive(TypeVisitable, TypeFoldable)]
203 pub struct UnifyReceiverContext<'tcx> {
204     pub assoc_item: ty::AssocItem,
205     pub param_env: ty::ParamEnv<'tcx>,
206     pub substs: SubstsRef<'tcx>,
207 }
208
209 #[derive(Clone, PartialEq, Eq, Hash, Lift, Default, HashStable)]
210 #[derive(TypeVisitable, TypeFoldable, TyEncodable, TyDecodable)]
211 pub struct InternedObligationCauseCode<'tcx> {
212     /// `None` for `ObligationCauseCode::MiscObligation` (a common case, occurs ~60% of
213     /// the time). `Some` otherwise.
214     code: Option<Lrc<ObligationCauseCode<'tcx>>>,
215 }
216
217 impl<'tcx> std::fmt::Debug for InternedObligationCauseCode<'tcx> {
218     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
219         let cause: &ObligationCauseCode<'_> = self;
220         cause.fmt(f)
221     }
222 }
223
224 impl<'tcx> ObligationCauseCode<'tcx> {
225     #[inline(always)]
226     fn into(self) -> InternedObligationCauseCode<'tcx> {
227         InternedObligationCauseCode {
228             code: if let ObligationCauseCode::MiscObligation = self {
229                 None
230             } else {
231                 Some(Lrc::new(self))
232             },
233         }
234     }
235 }
236
237 impl<'tcx> std::ops::Deref for InternedObligationCauseCode<'tcx> {
238     type Target = ObligationCauseCode<'tcx>;
239
240     fn deref(&self) -> &Self::Target {
241         self.code.as_deref().unwrap_or(&ObligationCauseCode::MiscObligation)
242     }
243 }
244
245 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift, HashStable, TyEncodable, TyDecodable)]
246 #[derive(TypeVisitable, TypeFoldable)]
247 pub enum ObligationCauseCode<'tcx> {
248     /// Not well classified or should be obvious from the span.
249     MiscObligation,
250
251     /// A slice or array is WF only if `T: Sized`.
252     SliceOrArrayElem,
253
254     /// A tuple is WF only if its middle elements are `Sized`.
255     TupleElem,
256
257     /// This is the trait reference from the given projection.
258     ProjectionWf(ty::AliasTy<'tcx>),
259
260     /// Must satisfy all of the where-clause predicates of the
261     /// given item.
262     ItemObligation(DefId),
263
264     /// Like `ItemObligation`, but carries the span of the
265     /// predicate when it can be identified.
266     BindingObligation(DefId, Span),
267
268     /// Like `ItemObligation`, but carries the `HirId` of the
269     /// expression that caused the obligation, and the `usize`
270     /// indicates exactly which predicate it is in the list of
271     /// instantiated predicates.
272     ExprItemObligation(DefId, rustc_hir::HirId, usize),
273
274     /// Combines `ExprItemObligation` and `BindingObligation`.
275     ExprBindingObligation(DefId, Span, rustc_hir::HirId, usize),
276
277     /// A type like `&'a T` is WF only if `T: 'a`.
278     ReferenceOutlivesReferent(Ty<'tcx>),
279
280     /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
281     ObjectTypeBound(Ty<'tcx>, ty::Region<'tcx>),
282
283     /// Obligation incurred due to an object cast.
284     ObjectCastObligation(/* Concrete type */ Ty<'tcx>, /* Object type */ Ty<'tcx>),
285
286     /// Obligation incurred due to a coercion.
287     Coercion {
288         source: Ty<'tcx>,
289         target: Ty<'tcx>,
290     },
291
292     /// Various cases where expressions must be `Sized` / `Copy` / etc.
293     /// `L = X` implies that `L` is `Sized`.
294     AssignmentLhsSized,
295     /// `(x1, .., xn)` must be `Sized`.
296     TupleInitializerSized,
297     /// `S { ... }` must be `Sized`.
298     StructInitializerSized,
299     /// Type of each variable must be `Sized`.
300     VariableType(hir::HirId),
301     /// Argument type must be `Sized`.
302     SizedArgumentType(Option<Span>),
303     /// Return type must be `Sized`.
304     SizedReturnType,
305     /// Yield type must be `Sized`.
306     SizedYieldType,
307     /// Box expression result type must be `Sized`.
308     SizedBoxType,
309     /// Inline asm operand type must be `Sized`.
310     InlineAsmSized,
311     /// `[expr; N]` requires `type_of(expr): Copy`.
312     RepeatElementCopy {
313         /// If element is a `const fn` we display a help message suggesting to move the
314         /// function call to a new `const` item while saying that `T` doesn't implement `Copy`.
315         is_const_fn: bool,
316     },
317
318     /// Types of fields (other than the last, except for packed structs) in a struct must be sized.
319     FieldSized {
320         adt_kind: AdtKind,
321         span: Span,
322         last: bool,
323     },
324
325     /// Constant expressions must be sized.
326     ConstSized,
327
328     /// `static` items must have `Sync` type.
329     SharedStatic,
330
331     BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
332
333     ImplDerivedObligation(Box<ImplDerivedObligationCause<'tcx>>),
334
335     DerivedObligation(DerivedObligationCause<'tcx>),
336
337     FunctionArgumentObligation {
338         /// The node of the relevant argument in the function call.
339         arg_hir_id: hir::HirId,
340         /// The node of the function call.
341         call_hir_id: hir::HirId,
342         /// The obligation introduced by this argument.
343         parent_code: InternedObligationCauseCode<'tcx>,
344     },
345
346     /// Error derived when matching traits/impls; see ObligationCause for more details
347     CompareImplItemObligation {
348         impl_item_def_id: LocalDefId,
349         trait_item_def_id: DefId,
350         kind: ty::AssocKind,
351     },
352
353     /// Checking that the bounds of a trait's associated type hold for a given impl
354     CheckAssociatedTypeBounds {
355         impl_item_def_id: LocalDefId,
356         trait_item_def_id: DefId,
357     },
358
359     /// Checking that this expression can be assigned to its target.
360     ExprAssignable,
361
362     /// Computing common supertype in the arms of a match expression
363     MatchExpressionArm(Box<MatchExpressionArmCause<'tcx>>),
364
365     /// Type error arising from type checking a pattern against an expected type.
366     Pattern {
367         /// The span of the scrutinee or type expression which caused the `root_ty` type.
368         span: Option<Span>,
369         /// The root expected type induced by a scrutinee or type expression.
370         root_ty: Ty<'tcx>,
371         /// Whether the `Span` came from an expression or a type expression.
372         origin_expr: bool,
373     },
374
375     /// Constants in patterns must have `Structural` type.
376     ConstPatternStructural,
377
378     /// Computing common supertype in an if expression
379     IfExpression(Box<IfExpressionCause<'tcx>>),
380
381     /// Computing common supertype of an if expression with no else counter-part
382     IfExpressionWithNoElse,
383
384     /// `main` has wrong type
385     MainFunctionType,
386
387     /// `start` has wrong type
388     StartFunctionType,
389
390     /// Intrinsic has wrong type
391     IntrinsicType,
392
393     /// A let else block does not diverge
394     LetElse,
395
396     /// Method receiver
397     MethodReceiver,
398
399     UnifyReceiver(Box<UnifyReceiverContext<'tcx>>),
400
401     /// `return` with no expression
402     ReturnNoExpression,
403
404     /// `return` with an expression
405     ReturnValue(hir::HirId),
406
407     /// Return type of this function
408     ReturnType,
409
410     /// Opaque return type of this function
411     OpaqueReturnType(Option<(Ty<'tcx>, Span)>),
412
413     /// Block implicit return
414     BlockTailExpression(hir::HirId),
415
416     /// #[feature(trivial_bounds)] is not enabled
417     TrivialBound,
418
419     /// If `X` is the concrete type of an opaque type `impl Y`, then `X` must implement `Y`
420     OpaqueType,
421
422     AwaitableExpr(Option<hir::HirId>),
423
424     ForLoopIterator,
425
426     QuestionMark,
427
428     /// Well-formed checking. If a `WellFormedLoc` is provided,
429     /// then it will be used to perform HIR-based wf checking
430     /// after an error occurs, in order to generate a more precise error span.
431     /// This is purely for diagnostic purposes - it is always
432     /// correct to use `MiscObligation` instead, or to specify
433     /// `WellFormed(None)`
434     WellFormed(Option<WellFormedLoc>),
435
436     /// From `match_impl`. The cause for us having to match an impl, and the DefId we are matching against.
437     MatchImpl(ObligationCause<'tcx>, DefId),
438
439     BinOp {
440         rhs_span: Option<Span>,
441         is_lit: bool,
442         output_ty: Option<Ty<'tcx>>,
443     },
444
445     AscribeUserTypeProvePredicate(Span),
446
447     RustCall,
448 }
449
450 /// The 'location' at which we try to perform HIR-based wf checking.
451 /// This information is used to obtain an `hir::Ty`, which
452 /// we can walk in order to obtain precise spans for any
453 /// 'nested' types (e.g. `Foo` in `Option<Foo>`).
454 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable, Encodable, Decodable)]
455 #[derive(TypeVisitable, TypeFoldable)]
456 pub enum WellFormedLoc {
457     /// Use the type of the provided definition.
458     Ty(LocalDefId),
459     /// Use the type of the parameter of the provided function.
460     /// We cannot use `hir::Param`, since the function may
461     /// not have a body (e.g. a trait method definition)
462     Param {
463         /// The function to lookup the parameter in
464         function: LocalDefId,
465         /// The index of the parameter to use.
466         /// Parameters are indexed from 0, with the return type
467         /// being the last 'parameter'
468         param_idx: u16,
469     },
470 }
471
472 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift, HashStable, TyEncodable, TyDecodable)]
473 #[derive(TypeVisitable, TypeFoldable)]
474 pub struct ImplDerivedObligationCause<'tcx> {
475     pub derived: DerivedObligationCause<'tcx>,
476     pub impl_def_id: DefId,
477     pub span: Span,
478 }
479
480 impl<'tcx> ObligationCauseCode<'tcx> {
481     /// Returns the base obligation, ignoring derived obligations.
482     pub fn peel_derives(&self) -> &Self {
483         let mut base_cause = self;
484         while let Some((parent_code, _)) = base_cause.parent() {
485             base_cause = parent_code;
486         }
487         base_cause
488     }
489
490     pub fn parent(&self) -> Option<(&Self, Option<ty::PolyTraitPredicate<'tcx>>)> {
491         match self {
492             FunctionArgumentObligation { parent_code, .. } => Some((parent_code, None)),
493             BuiltinDerivedObligation(derived)
494             | DerivedObligation(derived)
495             | ImplDerivedObligation(box ImplDerivedObligationCause { derived, .. }) => {
496                 Some((&derived.parent_code, Some(derived.parent_trait_pred)))
497             }
498             _ => None,
499         }
500     }
501
502     pub fn peel_match_impls(&self) -> &Self {
503         match self {
504             MatchImpl(cause, _) => cause.code(),
505             _ => self,
506         }
507     }
508 }
509
510 // `ObligationCauseCode` is used a lot. Make sure it doesn't unintentionally get bigger.
511 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
512 static_assert_size!(ObligationCauseCode<'_>, 48);
513
514 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
515 pub enum StatementAsExpression {
516     CorrectType,
517     NeedsBoxing,
518 }
519
520 impl<'tcx> ty::Lift<'tcx> for StatementAsExpression {
521     type Lifted = StatementAsExpression;
522     fn lift_to_tcx(self, _tcx: TyCtxt<'tcx>) -> Option<StatementAsExpression> {
523         Some(self)
524     }
525 }
526
527 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift, HashStable, TyEncodable, TyDecodable)]
528 #[derive(TypeVisitable, TypeFoldable)]
529 pub struct MatchExpressionArmCause<'tcx> {
530     pub arm_block_id: Option<hir::HirId>,
531     pub arm_ty: Ty<'tcx>,
532     pub arm_span: Span,
533     pub prior_arm_block_id: Option<hir::HirId>,
534     pub prior_arm_ty: Ty<'tcx>,
535     pub prior_arm_span: Span,
536     pub scrut_span: Span,
537     pub source: hir::MatchSource,
538     pub prior_arms: Vec<Span>,
539     pub scrut_hir_id: hir::HirId,
540     pub opt_suggest_box_span: Option<Span>,
541 }
542
543 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
544 #[derive(Lift, TypeFoldable, TypeVisitable, HashStable, TyEncodable, TyDecodable)]
545 pub struct IfExpressionCause<'tcx> {
546     pub then_id: hir::HirId,
547     pub else_id: hir::HirId,
548     pub then_ty: Ty<'tcx>,
549     pub else_ty: Ty<'tcx>,
550     pub outer_span: Option<Span>,
551     pub opt_suggest_box_span: Option<Span>,
552 }
553
554 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift, HashStable, TyEncodable, TyDecodable)]
555 #[derive(TypeVisitable, TypeFoldable)]
556 pub struct DerivedObligationCause<'tcx> {
557     /// The trait predicate of the parent obligation that led to the
558     /// current obligation. Note that only trait obligations lead to
559     /// derived obligations, so we just store the trait predicate here
560     /// directly.
561     pub parent_trait_pred: ty::PolyTraitPredicate<'tcx>,
562
563     /// The parent trait had this cause.
564     pub parent_code: InternedObligationCauseCode<'tcx>,
565 }
566
567 #[derive(Clone, Debug, TypeFoldable, TypeVisitable, Lift)]
568 pub enum SelectionError<'tcx> {
569     /// The trait is not implemented.
570     Unimplemented,
571     /// After a closure impl has selected, its "outputs" were evaluated
572     /// (which for closures includes the "input" type params) and they
573     /// didn't resolve. See `confirm_poly_trait_refs` for more.
574     OutputTypeParameterMismatch(
575         ty::PolyTraitRef<'tcx>,
576         ty::PolyTraitRef<'tcx>,
577         ty::error::TypeError<'tcx>,
578     ),
579     /// The trait pointed by `DefId` is not object safe.
580     TraitNotObjectSafe(DefId),
581     /// A given constant couldn't be evaluated.
582     NotConstEvaluatable(NotConstEvaluatable),
583     /// Exceeded the recursion depth during type projection.
584     Overflow(OverflowError),
585     /// Signaling that an error has already been emitted, to avoid
586     /// multiple errors being shown.
587     ErrorReporting,
588 }
589
590 /// When performing resolution, it is typically the case that there
591 /// can be one of three outcomes:
592 ///
593 /// - `Ok(Some(r))`: success occurred with result `r`
594 /// - `Ok(None)`: could not definitely determine anything, usually due
595 ///   to inconclusive type inference.
596 /// - `Err(e)`: error `e` occurred
597 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
598
599 /// Given the successful resolution of an obligation, the `ImplSource`
600 /// indicates where the impl comes from.
601 ///
602 /// For example, the obligation may be satisfied by a specific impl (case A),
603 /// or it may be relative to some bound that is in scope (case B).
604 ///
605 /// ```ignore (illustrative)
606 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
607 /// impl<T:Clone> Clone<T> for Box<T> { ... }    // Impl_2
608 /// impl Clone for i32 { ... }                   // Impl_3
609 ///
610 /// fn foo<T: Clone>(concrete: Option<Box<i32>>, param: T, mixed: Option<T>) {
611 ///     // Case A: ImplSource points at a specific impl. Only possible when
612 ///     // type is concretely known. If the impl itself has bounded
613 ///     // type parameters, ImplSource will carry resolutions for those as well:
614 ///     concrete.clone(); // ImplSource(Impl_1, [ImplSource(Impl_2, [ImplSource(Impl_3)])])
615 ///
616 ///     // Case B: ImplSource must be provided by caller. This applies when
617 ///     // type is a type parameter.
618 ///     param.clone();    // ImplSource::Param
619 ///
620 ///     // Case C: A mix of cases A and B.
621 ///     mixed.clone();    // ImplSource(Impl_1, [ImplSource::Param])
622 /// }
623 /// ```
624 ///
625 /// ### The type parameter `N`
626 ///
627 /// See explanation on `ImplSourceUserDefinedData`.
628 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
629 #[derive(TypeFoldable, TypeVisitable)]
630 pub enum ImplSource<'tcx, N> {
631     /// ImplSource identifying a particular impl.
632     UserDefined(ImplSourceUserDefinedData<'tcx, N>),
633
634     /// ImplSource for auto trait implementations.
635     /// This carries the information and nested obligations with regards
636     /// to an auto implementation for a trait `Trait`. The nested obligations
637     /// ensure the trait implementation holds for all the constituent types.
638     AutoImpl(ImplSourceAutoImplData<N>),
639
640     /// Successful resolution to an obligation provided by the caller
641     /// for some type parameter. The `Vec<N>` represents the
642     /// obligations incurred from normalizing the where-clause (if
643     /// any).
644     Param(Vec<N>, ty::BoundConstness),
645
646     /// Virtual calls through an object.
647     Object(ImplSourceObjectData<'tcx, N>),
648
649     /// Successful resolution for a builtin trait.
650     Builtin(ImplSourceBuiltinData<N>),
651
652     /// ImplSource for trait upcasting coercion
653     TraitUpcasting(ImplSourceTraitUpcastingData<'tcx, N>),
654
655     /// ImplSource automatically generated for a closure. The `DefId` is the ID
656     /// of the closure expression. This is an `ImplSource::UserDefined` in spirit, but the
657     /// impl is generated by the compiler and does not appear in the source.
658     Closure(ImplSourceClosureData<'tcx, N>),
659
660     /// Same as above, but for a function pointer type with the given signature.
661     FnPointer(ImplSourceFnPointerData<'tcx, N>),
662
663     /// ImplSource automatically generated for a generator.
664     Generator(ImplSourceGeneratorData<'tcx, N>),
665
666     /// ImplSource automatically generated for a generator backing an async future.
667     Future(ImplSourceFutureData<'tcx, N>),
668
669     /// ImplSource for a trait alias.
670     TraitAlias(ImplSourceTraitAliasData<'tcx, N>),
671
672     /// ImplSource for a `const Drop` implementation.
673     ConstDestruct(ImplSourceConstDestructData<N>),
674 }
675
676 impl<'tcx, N> ImplSource<'tcx, N> {
677     pub fn nested_obligations(self) -> Vec<N> {
678         match self {
679             ImplSource::UserDefined(i) => i.nested,
680             ImplSource::Param(n, _) => n,
681             ImplSource::Builtin(i) => i.nested,
682             ImplSource::AutoImpl(d) => d.nested,
683             ImplSource::Closure(c) => c.nested,
684             ImplSource::Generator(c) => c.nested,
685             ImplSource::Future(c) => c.nested,
686             ImplSource::Object(d) => d.nested,
687             ImplSource::FnPointer(d) => d.nested,
688             ImplSource::TraitAlias(d) => d.nested,
689             ImplSource::TraitUpcasting(d) => d.nested,
690             ImplSource::ConstDestruct(i) => i.nested,
691         }
692     }
693
694     pub fn borrow_nested_obligations(&self) -> &[N] {
695         match &self {
696             ImplSource::UserDefined(i) => &i.nested[..],
697             ImplSource::Param(n, _) => &n,
698             ImplSource::Builtin(i) => &i.nested,
699             ImplSource::AutoImpl(d) => &d.nested,
700             ImplSource::Closure(c) => &c.nested,
701             ImplSource::Generator(c) => &c.nested,
702             ImplSource::Future(c) => &c.nested,
703             ImplSource::Object(d) => &d.nested,
704             ImplSource::FnPointer(d) => &d.nested,
705             ImplSource::TraitAlias(d) => &d.nested,
706             ImplSource::TraitUpcasting(d) => &d.nested,
707             ImplSource::ConstDestruct(i) => &i.nested,
708         }
709     }
710
711     pub fn map<M, F>(self, f: F) -> ImplSource<'tcx, M>
712     where
713         F: FnMut(N) -> M,
714     {
715         match self {
716             ImplSource::UserDefined(i) => ImplSource::UserDefined(ImplSourceUserDefinedData {
717                 impl_def_id: i.impl_def_id,
718                 substs: i.substs,
719                 nested: i.nested.into_iter().map(f).collect(),
720             }),
721             ImplSource::Param(n, ct) => ImplSource::Param(n.into_iter().map(f).collect(), ct),
722             ImplSource::Builtin(i) => ImplSource::Builtin(ImplSourceBuiltinData {
723                 nested: i.nested.into_iter().map(f).collect(),
724             }),
725             ImplSource::Object(o) => ImplSource::Object(ImplSourceObjectData {
726                 upcast_trait_ref: o.upcast_trait_ref,
727                 vtable_base: o.vtable_base,
728                 nested: o.nested.into_iter().map(f).collect(),
729             }),
730             ImplSource::AutoImpl(d) => ImplSource::AutoImpl(ImplSourceAutoImplData {
731                 trait_def_id: d.trait_def_id,
732                 nested: d.nested.into_iter().map(f).collect(),
733             }),
734             ImplSource::Closure(c) => ImplSource::Closure(ImplSourceClosureData {
735                 closure_def_id: c.closure_def_id,
736                 substs: c.substs,
737                 nested: c.nested.into_iter().map(f).collect(),
738             }),
739             ImplSource::Generator(c) => ImplSource::Generator(ImplSourceGeneratorData {
740                 generator_def_id: c.generator_def_id,
741                 substs: c.substs,
742                 nested: c.nested.into_iter().map(f).collect(),
743             }),
744             ImplSource::Future(c) => ImplSource::Future(ImplSourceFutureData {
745                 generator_def_id: c.generator_def_id,
746                 substs: c.substs,
747                 nested: c.nested.into_iter().map(f).collect(),
748             }),
749             ImplSource::FnPointer(p) => ImplSource::FnPointer(ImplSourceFnPointerData {
750                 fn_ty: p.fn_ty,
751                 nested: p.nested.into_iter().map(f).collect(),
752             }),
753             ImplSource::TraitAlias(d) => ImplSource::TraitAlias(ImplSourceTraitAliasData {
754                 alias_def_id: d.alias_def_id,
755                 substs: d.substs,
756                 nested: d.nested.into_iter().map(f).collect(),
757             }),
758             ImplSource::TraitUpcasting(d) => {
759                 ImplSource::TraitUpcasting(ImplSourceTraitUpcastingData {
760                     upcast_trait_ref: d.upcast_trait_ref,
761                     vtable_vptr_slot: d.vtable_vptr_slot,
762                     nested: d.nested.into_iter().map(f).collect(),
763                 })
764             }
765             ImplSource::ConstDestruct(i) => {
766                 ImplSource::ConstDestruct(ImplSourceConstDestructData {
767                     nested: i.nested.into_iter().map(f).collect(),
768                 })
769             }
770         }
771     }
772 }
773
774 /// Identifies a particular impl in the source, along with a set of
775 /// substitutions from the impl's type/lifetime parameters. The
776 /// `nested` vector corresponds to the nested obligations attached to
777 /// the impl's type parameters.
778 ///
779 /// The type parameter `N` indicates the type used for "nested
780 /// obligations" that are required by the impl. During type-check, this
781 /// is `Obligation`, as one might expect. During codegen, however, this
782 /// is `()`, because codegen only requires a shallow resolution of an
783 /// impl, and nested obligations are satisfied later.
784 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
785 #[derive(TypeFoldable, TypeVisitable)]
786 pub struct ImplSourceUserDefinedData<'tcx, N> {
787     pub impl_def_id: DefId,
788     pub substs: SubstsRef<'tcx>,
789     pub nested: Vec<N>,
790 }
791
792 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
793 #[derive(TypeFoldable, TypeVisitable)]
794 pub struct ImplSourceGeneratorData<'tcx, N> {
795     pub generator_def_id: DefId,
796     pub substs: SubstsRef<'tcx>,
797     /// Nested obligations. This can be non-empty if the generator
798     /// signature contains associated types.
799     pub nested: Vec<N>,
800 }
801
802 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
803 #[derive(TypeFoldable, TypeVisitable)]
804 pub struct ImplSourceFutureData<'tcx, N> {
805     pub generator_def_id: DefId,
806     pub substs: SubstsRef<'tcx>,
807     /// Nested obligations. This can be non-empty if the generator
808     /// signature contains associated types.
809     pub nested: Vec<N>,
810 }
811
812 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
813 #[derive(TypeFoldable, TypeVisitable)]
814 pub struct ImplSourceClosureData<'tcx, N> {
815     pub closure_def_id: DefId,
816     pub substs: SubstsRef<'tcx>,
817     /// Nested obligations. This can be non-empty if the closure
818     /// signature contains associated types.
819     pub nested: Vec<N>,
820 }
821
822 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
823 #[derive(TypeFoldable, TypeVisitable)]
824 pub struct ImplSourceAutoImplData<N> {
825     pub trait_def_id: DefId,
826     pub nested: Vec<N>,
827 }
828
829 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
830 #[derive(TypeFoldable, TypeVisitable)]
831 pub struct ImplSourceTraitUpcastingData<'tcx, N> {
832     /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
833     pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
834
835     /// The vtable is formed by concatenating together the method lists of
836     /// the base object trait and all supertraits, pointers to supertrait vtable will
837     /// be provided when necessary; this is the position of `upcast_trait_ref`'s vtable
838     /// within that vtable.
839     pub vtable_vptr_slot: Option<usize>,
840
841     pub nested: Vec<N>,
842 }
843
844 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
845 #[derive(TypeFoldable, TypeVisitable)]
846 pub struct ImplSourceBuiltinData<N> {
847     pub nested: Vec<N>,
848 }
849
850 #[derive(PartialEq, Eq, Clone, TyEncodable, TyDecodable, HashStable, Lift)]
851 #[derive(TypeFoldable, TypeVisitable)]
852 pub struct ImplSourceObjectData<'tcx, N> {
853     /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
854     pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
855
856     /// The vtable is formed by concatenating together the method lists of
857     /// the base object trait and all supertraits, pointers to supertrait vtable will
858     /// be provided when necessary; this is the start of `upcast_trait_ref`'s methods
859     /// in that vtable.
860     pub vtable_base: usize,
861
862     pub nested: Vec<N>,
863 }
864
865 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
866 #[derive(TypeFoldable, TypeVisitable)]
867 pub struct ImplSourceFnPointerData<'tcx, N> {
868     pub fn_ty: Ty<'tcx>,
869     pub nested: Vec<N>,
870 }
871
872 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
873 #[derive(TypeFoldable, TypeVisitable)]
874 pub struct ImplSourceConstDestructData<N> {
875     pub nested: Vec<N>,
876 }
877
878 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, Lift)]
879 #[derive(TypeFoldable, TypeVisitable)]
880 pub struct ImplSourceTraitAliasData<'tcx, N> {
881     pub alias_def_id: DefId,
882     pub substs: SubstsRef<'tcx>,
883     pub nested: Vec<N>,
884 }
885
886 #[derive(Clone, Debug, PartialEq, Eq, Hash, HashStable, PartialOrd, Ord)]
887 pub enum ObjectSafetyViolation {
888     /// `Self: Sized` declared on the trait.
889     SizedSelf(SmallVec<[Span; 1]>),
890
891     /// Supertrait reference references `Self` an in illegal location
892     /// (e.g., `trait Foo : Bar<Self>`).
893     SupertraitSelf(SmallVec<[Span; 1]>),
894
895     /// Method has something illegal.
896     Method(Symbol, MethodViolationCode, Span),
897
898     /// Associated const.
899     AssocConst(Symbol, Span),
900
901     /// GAT
902     GAT(Symbol, Span),
903 }
904
905 impl ObjectSafetyViolation {
906     pub fn error_msg(&self) -> Cow<'static, str> {
907         match self {
908             ObjectSafetyViolation::SizedSelf(_) => "it requires `Self: Sized`".into(),
909             ObjectSafetyViolation::SupertraitSelf(ref spans) => {
910                 if spans.iter().any(|sp| *sp != DUMMY_SP) {
911                     "it uses `Self` as a type parameter".into()
912                 } else {
913                     "it cannot use `Self` as a type parameter in a supertrait or `where`-clause"
914                         .into()
915                 }
916             }
917             ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod(_), _) => {
918                 format!("associated function `{}` has no `self` parameter", name).into()
919             }
920             ObjectSafetyViolation::Method(
921                 name,
922                 MethodViolationCode::ReferencesSelfInput(_),
923                 DUMMY_SP,
924             ) => format!("method `{}` references the `Self` type in its parameters", name).into(),
925             ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfInput(_), _) => {
926                 format!("method `{}` references the `Self` type in this parameter", name).into()
927             }
928             ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfOutput, _) => {
929                 format!("method `{}` references the `Self` type in its return type", name).into()
930             }
931             ObjectSafetyViolation::Method(
932                 name,
933                 MethodViolationCode::ReferencesImplTraitInTrait(_),
934                 _,
935             ) => format!("method `{}` references an `impl Trait` type in its return type", name)
936                 .into(),
937             ObjectSafetyViolation::Method(name, MethodViolationCode::AsyncFn, _) => {
938                 format!("method `{}` is `async`", name).into()
939             }
940             ObjectSafetyViolation::Method(
941                 name,
942                 MethodViolationCode::WhereClauseReferencesSelf,
943                 _,
944             ) => {
945                 format!("method `{}` references the `Self` type in its `where` clause", name).into()
946             }
947             ObjectSafetyViolation::Method(name, MethodViolationCode::Generic, _) => {
948                 format!("method `{}` has generic type parameters", name).into()
949             }
950             ObjectSafetyViolation::Method(
951                 name,
952                 MethodViolationCode::UndispatchableReceiver(_),
953                 _,
954             ) => format!("method `{}`'s `self` parameter cannot be dispatched on", name).into(),
955             ObjectSafetyViolation::AssocConst(name, DUMMY_SP) => {
956                 format!("it contains associated `const` `{}`", name).into()
957             }
958             ObjectSafetyViolation::AssocConst(..) => "it contains this associated `const`".into(),
959             ObjectSafetyViolation::GAT(name, _) => {
960                 format!("it contains the generic associated type `{}`", name).into()
961             }
962         }
963     }
964
965     pub fn solution(&self, err: &mut Diagnostic) {
966         match self {
967             ObjectSafetyViolation::SizedSelf(_) | ObjectSafetyViolation::SupertraitSelf(_) => {}
968             ObjectSafetyViolation::Method(
969                 name,
970                 MethodViolationCode::StaticMethod(Some((add_self_sugg, make_sized_sugg))),
971                 _,
972             ) => {
973                 err.span_suggestion(
974                     add_self_sugg.1,
975                     format!(
976                         "consider turning `{}` into a method by giving it a `&self` argument",
977                         name
978                     ),
979                     add_self_sugg.0.to_string(),
980                     Applicability::MaybeIncorrect,
981                 );
982                 err.span_suggestion(
983                     make_sized_sugg.1,
984                     format!(
985                         "alternatively, consider constraining `{}` so it does not apply to \
986                              trait objects",
987                         name
988                     ),
989                     make_sized_sugg.0.to_string(),
990                     Applicability::MaybeIncorrect,
991                 );
992             }
993             ObjectSafetyViolation::Method(
994                 name,
995                 MethodViolationCode::UndispatchableReceiver(Some(span)),
996                 _,
997             ) => {
998                 err.span_suggestion(
999                     *span,
1000                     &format!(
1001                         "consider changing method `{}`'s `self` parameter to be `&self`",
1002                         name
1003                     ),
1004                     "&Self",
1005                     Applicability::MachineApplicable,
1006                 );
1007             }
1008             ObjectSafetyViolation::AssocConst(name, _)
1009             | ObjectSafetyViolation::GAT(name, _)
1010             | ObjectSafetyViolation::Method(name, ..) => {
1011                 err.help(&format!("consider moving `{}` to another trait", name));
1012             }
1013         }
1014     }
1015
1016     pub fn spans(&self) -> SmallVec<[Span; 1]> {
1017         // When `span` comes from a separate crate, it'll be `DUMMY_SP`. Treat it as `None` so
1018         // diagnostics use a `note` instead of a `span_label`.
1019         match self {
1020             ObjectSafetyViolation::SupertraitSelf(spans)
1021             | ObjectSafetyViolation::SizedSelf(spans) => spans.clone(),
1022             ObjectSafetyViolation::AssocConst(_, span)
1023             | ObjectSafetyViolation::GAT(_, span)
1024             | ObjectSafetyViolation::Method(_, _, span)
1025                 if *span != DUMMY_SP =>
1026             {
1027                 smallvec![*span]
1028             }
1029             _ => smallvec![],
1030         }
1031     }
1032 }
1033
1034 /// Reasons a method might not be object-safe.
1035 #[derive(Clone, Debug, PartialEq, Eq, Hash, HashStable, PartialOrd, Ord)]
1036 pub enum MethodViolationCode {
1037     /// e.g., `fn foo()`
1038     StaticMethod(Option<(/* add &self */ (String, Span), /* add Self: Sized */ (String, Span))>),
1039
1040     /// e.g., `fn foo(&self, x: Self)`
1041     ReferencesSelfInput(Option<Span>),
1042
1043     /// e.g., `fn foo(&self) -> Self`
1044     ReferencesSelfOutput,
1045
1046     /// e.g., `fn foo(&self) -> impl Sized`
1047     ReferencesImplTraitInTrait(Span),
1048
1049     /// e.g., `async fn foo(&self)`
1050     AsyncFn,
1051
1052     /// e.g., `fn foo(&self) where Self: Clone`
1053     WhereClauseReferencesSelf,
1054
1055     /// e.g., `fn foo<A>()`
1056     Generic,
1057
1058     /// the method's receiver (`self` argument) can't be dispatched on
1059     UndispatchableReceiver(Option<Span>),
1060 }
1061
1062 /// These are the error cases for `codegen_select_candidate`.
1063 #[derive(Copy, Clone, Debug, Hash, HashStable, Encodable, Decodable)]
1064 pub enum CodegenObligationError {
1065     /// Ambiguity can happen when monomorphizing during trans
1066     /// expands to some humongous type that never occurred
1067     /// statically -- this humongous type can then overflow,
1068     /// leading to an ambiguous result. So report this as an
1069     /// overflow bug, since I believe this is the only case
1070     /// where ambiguity can result.
1071     Ambiguity,
1072     /// This can trigger when we probe for the source of a `'static` lifetime requirement
1073     /// on a trait object: `impl Foo for dyn Trait {}` has an implicit `'static` bound.
1074     /// This can also trigger when we have a global bound that is not actually satisfied,
1075     /// but was included during typeck due to the trivial_bounds feature.
1076     Unimplemented,
1077     FulfillmentError,
1078 }