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