]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/traits/mod.rs
Rollup merge of #87028 - aDotInTheVoid:patch-1, r=petrochenkov
[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
11 use crate::infer::canonical::Canonical;
12 use crate::mir::abstract_const::NotConstEvaluatable;
13 use crate::ty::subst::SubstsRef;
14 use crate::ty::{self, AdtKind, Ty, TyCtxt};
15
16 use rustc_errors::{Applicability, DiagnosticBuilder};
17 use rustc_hir as hir;
18 use rustc_hir::def_id::DefId;
19 use rustc_hir::Constness;
20 use rustc_span::symbol::Symbol;
21 use rustc_span::{Span, DUMMY_SP};
22 use smallvec::SmallVec;
23
24 use std::borrow::Cow;
25 use std::fmt;
26 use std::ops::Deref;
27 use std::rc::Rc;
28
29 pub use self::select::{EvaluationCache, EvaluationResult, OverflowError, SelectionCache};
30
31 pub type CanonicalChalkEnvironmentAndGoal<'tcx> = Canonical<'tcx, ChalkEnvironmentAndGoal<'tcx>>;
32
33 pub use self::ObligationCauseCode::*;
34
35 pub use self::chalk::{ChalkEnvironmentAndGoal, RustInterner as ChalkRustInterner};
36
37 /// Depending on the stage of compilation, we want projection to be
38 /// more or less conservative.
39 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, HashStable)]
40 pub enum Reveal {
41     /// At type-checking time, we refuse to project any associated
42     /// type that is marked `default`. Non-`default` ("final") types
43     /// are always projected. This is necessary in general for
44     /// soundness of specialization. However, we *could* allow
45     /// projections in fully-monomorphic cases. We choose not to,
46     /// because we prefer for `default type` to force the type
47     /// definition to be treated abstractly by any consumers of the
48     /// impl. Concretely, that means that the following example will
49     /// fail to compile:
50     ///
51     /// ```
52     /// trait Assoc {
53     ///     type Output;
54     /// }
55     ///
56     /// impl<T> Assoc for T {
57     ///     default type Output = bool;
58     /// }
59     ///
60     /// fn main() {
61     ///     let <() as Assoc>::Output = true;
62     /// }
63     /// ```
64     UserFacing,
65
66     /// At codegen time, all monomorphic projections will succeed.
67     /// Also, `impl Trait` is normalized to the concrete type,
68     /// which has to be already collected by type-checking.
69     ///
70     /// NOTE: as `impl Trait`'s concrete type should *never*
71     /// be observable directly by the user, `Reveal::All`
72     /// should not be used by checks which may expose
73     /// type equality or type contents to the user.
74     /// There are some exceptions, e.g., around auto traits and
75     /// transmute-checking, which expose some details, but
76     /// not the whole concrete type of the `impl Trait`.
77     All,
78 }
79
80 /// The reason why we incurred this obligation; used for error reporting.
81 ///
82 /// As the happy path does not care about this struct, storing this on the heap
83 /// ends up increasing performance.
84 ///
85 /// We do not want to intern this as there are a lot of obligation causes which
86 /// only live for a short period of time.
87 #[derive(Clone, PartialEq, Eq, Hash, Lift)]
88 pub struct ObligationCause<'tcx> {
89     /// `None` for `ObligationCause::dummy`, `Some` otherwise.
90     data: Option<Rc<ObligationCauseData<'tcx>>>,
91 }
92
93 const DUMMY_OBLIGATION_CAUSE_DATA: ObligationCauseData<'static> =
94     ObligationCauseData { span: DUMMY_SP, body_id: hir::CRATE_HIR_ID, code: MiscObligation };
95
96 // Correctly format `ObligationCause::dummy`.
97 impl<'tcx> fmt::Debug for ObligationCause<'tcx> {
98     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99         ObligationCauseData::fmt(self, f)
100     }
101 }
102
103 impl Deref for ObligationCause<'tcx> {
104     type Target = ObligationCauseData<'tcx>;
105
106     #[inline(always)]
107     fn deref(&self) -> &Self::Target {
108         self.data.as_deref().unwrap_or(&DUMMY_OBLIGATION_CAUSE_DATA)
109     }
110 }
111
112 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
113 pub struct ObligationCauseData<'tcx> {
114     pub span: Span,
115
116     /// The ID of the fn body that triggered this obligation. This is
117     /// used for region obligations to determine the precise
118     /// environment in which the region obligation should be evaluated
119     /// (in particular, closures can add new assumptions). See the
120     /// field `region_obligations` of the `FulfillmentContext` for more
121     /// information.
122     pub body_id: hir::HirId,
123
124     pub code: ObligationCauseCode<'tcx>,
125 }
126
127 impl<'tcx> ObligationCause<'tcx> {
128     #[inline]
129     pub fn new(
130         span: Span,
131         body_id: hir::HirId,
132         code: ObligationCauseCode<'tcx>,
133     ) -> ObligationCause<'tcx> {
134         ObligationCause { data: Some(Rc::new(ObligationCauseData { span, body_id, code })) }
135     }
136
137     pub fn misc(span: Span, body_id: hir::HirId) -> ObligationCause<'tcx> {
138         ObligationCause::new(span, body_id, MiscObligation)
139     }
140
141     pub fn dummy_with_span(span: Span) -> ObligationCause<'tcx> {
142         ObligationCause::new(span, hir::CRATE_HIR_ID, MiscObligation)
143     }
144
145     #[inline(always)]
146     pub fn dummy() -> ObligationCause<'tcx> {
147         ObligationCause { data: None }
148     }
149
150     pub fn make_mut(&mut self) -> &mut ObligationCauseData<'tcx> {
151         Rc::make_mut(self.data.get_or_insert_with(|| Rc::new(DUMMY_OBLIGATION_CAUSE_DATA)))
152     }
153
154     pub fn span(&self, tcx: TyCtxt<'tcx>) -> Span {
155         match self.code {
156             ObligationCauseCode::CompareImplMethodObligation { .. }
157             | ObligationCauseCode::MainFunctionType
158             | ObligationCauseCode::StartFunctionType => {
159                 tcx.sess.source_map().guess_head_span(self.span)
160             }
161             ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
162                 arm_span,
163                 ..
164             }) => arm_span,
165             _ => self.span,
166         }
167     }
168 }
169
170 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
171 pub struct UnifyReceiverContext<'tcx> {
172     pub assoc_item: ty::AssocItem,
173     pub param_env: ty::ParamEnv<'tcx>,
174     pub substs: SubstsRef<'tcx>,
175 }
176
177 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
178 pub enum ObligationCauseCode<'tcx> {
179     /// Not well classified or should be obvious from the span.
180     MiscObligation,
181
182     /// A slice or array is WF only if `T: Sized`.
183     SliceOrArrayElem,
184
185     /// A tuple is WF only if its middle elements are `Sized`.
186     TupleElem,
187
188     /// This is the trait reference from the given projection.
189     ProjectionWf(ty::ProjectionTy<'tcx>),
190
191     /// In an impl of trait `X` for type `Y`, type `Y` must
192     /// also implement all supertraits of `X`.
193     ItemObligation(DefId),
194
195     /// Like `ItemObligation`, but with extra detail on the source of the obligation.
196     BindingObligation(DefId, Span),
197
198     /// A type like `&'a T` is WF only if `T: 'a`.
199     ReferenceOutlivesReferent(Ty<'tcx>),
200
201     /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
202     ObjectTypeBound(Ty<'tcx>, ty::Region<'tcx>),
203
204     /// Obligation incurred due to an object cast.
205     ObjectCastObligation(/* Object type */ Ty<'tcx>),
206
207     /// Obligation incurred due to a coercion.
208     Coercion {
209         source: Ty<'tcx>,
210         target: Ty<'tcx>,
211     },
212
213     /// Various cases where expressions must be `Sized` / `Copy` / etc.
214     /// `L = X` implies that `L` is `Sized`.
215     AssignmentLhsSized,
216     /// `(x1, .., xn)` must be `Sized`.
217     TupleInitializerSized,
218     /// `S { ... }` must be `Sized`.
219     StructInitializerSized,
220     /// Type of each variable must be `Sized`.
221     VariableType(hir::HirId),
222     /// Argument type must be `Sized`.
223     SizedArgumentType(Option<Span>),
224     /// Return type must be `Sized`.
225     SizedReturnType,
226     /// Yield type must be `Sized`.
227     SizedYieldType,
228     /// Inline asm operand type must be `Sized`.
229     InlineAsmSized,
230     /// `[T, ..n]` implies that `T` must be `Copy`.
231     /// If the function in the array repeat expression is a `const fn`,
232     /// display a help message suggesting to move the function call to a
233     /// new `const` item while saying that `T` doesn't implement `Copy`.
234     RepeatVec(bool),
235
236     /// Types of fields (other than the last, except for packed structs) in a struct must be sized.
237     FieldSized {
238         adt_kind: AdtKind,
239         span: Span,
240         last: bool,
241     },
242
243     /// Constant expressions must be sized.
244     ConstSized,
245
246     /// `static` items must have `Sync` type.
247     SharedStatic,
248
249     BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
250
251     ImplDerivedObligation(DerivedObligationCause<'tcx>),
252
253     DerivedObligation(DerivedObligationCause<'tcx>),
254
255     /// Error derived when matching traits/impls; see ObligationCause for more details
256     CompareImplConstObligation,
257
258     /// Error derived when matching traits/impls; see ObligationCause for more details
259     CompareImplMethodObligation {
260         item_name: Symbol,
261         impl_item_def_id: DefId,
262         trait_item_def_id: DefId,
263     },
264
265     /// Error derived when matching traits/impls; see ObligationCause for more details
266     CompareImplTypeObligation {
267         item_name: Symbol,
268         impl_item_def_id: DefId,
269         trait_item_def_id: DefId,
270     },
271
272     /// Checking that this expression can be assigned where it needs to be
273     // FIXME(eddyb) #11161 is the original Expr required?
274     ExprAssignable,
275
276     /// Computing common supertype in the arms of a match expression
277     MatchExpressionArm(Box<MatchExpressionArmCause<'tcx>>),
278
279     /// Type error arising from type checking a pattern against an expected type.
280     Pattern {
281         /// The span of the scrutinee or type expression which caused the `root_ty` type.
282         span: Option<Span>,
283         /// The root expected type induced by a scrutinee or type expression.
284         root_ty: Ty<'tcx>,
285         /// Whether the `Span` came from an expression or a type expression.
286         origin_expr: bool,
287     },
288
289     /// Constants in patterns must have `Structural` type.
290     ConstPatternStructural,
291
292     /// Computing common supertype in an if expression
293     IfExpression(Box<IfExpressionCause>),
294
295     /// Computing common supertype of an if expression with no else counter-part
296     IfExpressionWithNoElse,
297
298     /// `main` has wrong type
299     MainFunctionType,
300
301     /// `start` has wrong type
302     StartFunctionType,
303
304     /// Intrinsic has wrong type
305     IntrinsicType,
306
307     /// Method receiver
308     MethodReceiver,
309
310     UnifyReceiver(Box<UnifyReceiverContext<'tcx>>),
311
312     /// `return` with no expression
313     ReturnNoExpression,
314
315     /// `return` with an expression
316     ReturnValue(hir::HirId),
317
318     /// Return type of this function
319     ReturnType,
320
321     /// Block implicit return
322     BlockTailExpression(hir::HirId),
323
324     /// #[feature(trivial_bounds)] is not enabled
325     TrivialBound,
326
327     /// If `X` is the concrete type of an opaque type `impl Y`, then `X` must implement `Y`
328     OpaqueType,
329 }
330
331 impl ObligationCauseCode<'_> {
332     // Return the base obligation, ignoring derived obligations.
333     pub fn peel_derives(&self) -> &Self {
334         let mut base_cause = self;
335         while let BuiltinDerivedObligation(cause)
336         | ImplDerivedObligation(cause)
337         | DerivedObligation(cause) = base_cause
338         {
339             base_cause = &cause.parent_code;
340         }
341         base_cause
342     }
343 }
344
345 // `ObligationCauseCode` is used a lot. Make sure it doesn't unintentionally get bigger.
346 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
347 static_assert_size!(ObligationCauseCode<'_>, 40);
348
349 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
350 pub enum StatementAsExpression {
351     CorrectType,
352     NeedsBoxing,
353 }
354
355 impl<'tcx> ty::Lift<'tcx> for StatementAsExpression {
356     type Lifted = StatementAsExpression;
357     fn lift_to_tcx(self, _tcx: TyCtxt<'tcx>) -> Option<StatementAsExpression> {
358         Some(self)
359     }
360 }
361
362 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
363 pub struct MatchExpressionArmCause<'tcx> {
364     pub arm_span: Span,
365     pub scrut_span: Span,
366     pub semi_span: Option<(Span, StatementAsExpression)>,
367     pub source: hir::MatchSource,
368     pub prior_arms: Vec<Span>,
369     pub last_ty: Ty<'tcx>,
370     pub scrut_hir_id: hir::HirId,
371     pub opt_suggest_box_span: Option<Span>,
372 }
373
374 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
375 pub struct IfExpressionCause {
376     pub then: Span,
377     pub else_sp: Span,
378     pub outer: Option<Span>,
379     pub semicolon: Option<(Span, StatementAsExpression)>,
380     pub opt_suggest_box_span: Option<Span>,
381 }
382
383 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
384 pub struct DerivedObligationCause<'tcx> {
385     /// The trait reference of the parent obligation that led to the
386     /// current obligation. Note that only trait obligations lead to
387     /// derived obligations, so we just store the trait reference here
388     /// directly.
389     pub parent_trait_ref: ty::PolyTraitRef<'tcx>,
390
391     /// The parent trait had this cause.
392     pub parent_code: Rc<ObligationCauseCode<'tcx>>,
393 }
394
395 #[derive(Clone, Debug, TypeFoldable, Lift)]
396 pub enum SelectionError<'tcx> {
397     Unimplemented,
398     OutputTypeParameterMismatch(
399         ty::PolyTraitRef<'tcx>,
400         ty::PolyTraitRef<'tcx>,
401         ty::error::TypeError<'tcx>,
402     ),
403     TraitNotObjectSafe(DefId),
404     NotConstEvaluatable(NotConstEvaluatable),
405     Overflow,
406 }
407
408 /// When performing resolution, it is typically the case that there
409 /// can be one of three outcomes:
410 ///
411 /// - `Ok(Some(r))`: success occurred with result `r`
412 /// - `Ok(None)`: could not definitely determine anything, usually due
413 ///   to inconclusive type inference.
414 /// - `Err(e)`: error `e` occurred
415 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
416
417 /// Given the successful resolution of an obligation, the `ImplSource`
418 /// indicates where the impl comes from.
419 ///
420 /// For example, the obligation may be satisfied by a specific impl (case A),
421 /// or it may be relative to some bound that is in scope (case B).
422 ///
423 /// ```
424 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
425 /// impl<T:Clone> Clone<T> for Box<T> { ... }    // Impl_2
426 /// impl Clone for i32 { ... }                   // Impl_3
427 ///
428 /// fn foo<T: Clone>(concrete: Option<Box<i32>>, param: T, mixed: Option<T>) {
429 ///     // Case A: ImplSource points at a specific impl. Only possible when
430 ///     // type is concretely known. If the impl itself has bounded
431 ///     // type parameters, ImplSource will carry resolutions for those as well:
432 ///     concrete.clone(); // ImpleSource(Impl_1, [ImplSource(Impl_2, [ImplSource(Impl_3)])])
433 ///
434 ///     // Case A: ImplSource points at a specific impl. Only possible when
435 ///     // type is concretely known. If the impl itself has bounded
436 ///     // type parameters, ImplSource will carry resolutions for those as well:
437 ///     concrete.clone(); // ImplSource(Impl_1, [ImplSource(Impl_2, [ImplSource(Impl_3)])])
438 ///
439 ///     // Case B: ImplSource must be provided by caller. This applies when
440 ///     // type is a type parameter.
441 ///     param.clone();    // ImplSource::Param
442 ///
443 ///     // Case C: A mix of cases A and B.
444 ///     mixed.clone();    // ImplSource(Impl_1, [ImplSource::Param])
445 /// }
446 /// ```
447 ///
448 /// ### The type parameter `N`
449 ///
450 /// See explanation on `ImplSourceUserDefinedData`.
451 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
452 pub enum ImplSource<'tcx, N> {
453     /// ImplSource identifying a particular impl.
454     UserDefined(ImplSourceUserDefinedData<'tcx, N>),
455
456     /// ImplSource for auto trait implementations.
457     /// This carries the information and nested obligations with regards
458     /// to an auto implementation for a trait `Trait`. The nested obligations
459     /// ensure the trait implementation holds for all the constituent types.
460     AutoImpl(ImplSourceAutoImplData<N>),
461
462     /// Successful resolution to an obligation provided by the caller
463     /// for some type parameter. The `Vec<N>` represents the
464     /// obligations incurred from normalizing the where-clause (if
465     /// any).
466     Param(Vec<N>, Constness),
467
468     /// Virtual calls through an object.
469     Object(ImplSourceObjectData<'tcx, N>),
470
471     /// Successful resolution for a builtin trait.
472     Builtin(ImplSourceBuiltinData<N>),
473
474     /// ImplSource automatically generated for a closure. The `DefId` is the ID
475     /// of the closure expression. This is a `ImplSource::UserDefined` in spirit, but the
476     /// impl is generated by the compiler and does not appear in the source.
477     Closure(ImplSourceClosureData<'tcx, N>),
478
479     /// Same as above, but for a function pointer type with the given signature.
480     FnPointer(ImplSourceFnPointerData<'tcx, N>),
481
482     /// ImplSource for a builtin `DeterminantKind` trait implementation.
483     DiscriminantKind(ImplSourceDiscriminantKindData),
484
485     /// ImplSource for a builtin `Pointee` trait implementation.
486     Pointee(ImplSourcePointeeData),
487
488     /// ImplSource automatically generated for a generator.
489     Generator(ImplSourceGeneratorData<'tcx, N>),
490
491     /// ImplSource for a trait alias.
492     TraitAlias(ImplSourceTraitAliasData<'tcx, N>),
493 }
494
495 impl<'tcx, N> ImplSource<'tcx, N> {
496     pub fn nested_obligations(self) -> Vec<N> {
497         match self {
498             ImplSource::UserDefined(i) => i.nested,
499             ImplSource::Param(n, _) => n,
500             ImplSource::Builtin(i) => i.nested,
501             ImplSource::AutoImpl(d) => d.nested,
502             ImplSource::Closure(c) => c.nested,
503             ImplSource::Generator(c) => c.nested,
504             ImplSource::Object(d) => d.nested,
505             ImplSource::FnPointer(d) => d.nested,
506             ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData)
507             | ImplSource::Pointee(ImplSourcePointeeData) => Vec::new(),
508             ImplSource::TraitAlias(d) => d.nested,
509         }
510     }
511
512     pub fn borrow_nested_obligations(&self) -> &[N] {
513         match &self {
514             ImplSource::UserDefined(i) => &i.nested[..],
515             ImplSource::Param(n, _) => &n[..],
516             ImplSource::Builtin(i) => &i.nested[..],
517             ImplSource::AutoImpl(d) => &d.nested[..],
518             ImplSource::Closure(c) => &c.nested[..],
519             ImplSource::Generator(c) => &c.nested[..],
520             ImplSource::Object(d) => &d.nested[..],
521             ImplSource::FnPointer(d) => &d.nested[..],
522             ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData)
523             | ImplSource::Pointee(ImplSourcePointeeData) => &[],
524             ImplSource::TraitAlias(d) => &d.nested[..],
525         }
526     }
527
528     pub fn map<M, F>(self, f: F) -> ImplSource<'tcx, M>
529     where
530         F: FnMut(N) -> M,
531     {
532         match self {
533             ImplSource::UserDefined(i) => ImplSource::UserDefined(ImplSourceUserDefinedData {
534                 impl_def_id: i.impl_def_id,
535                 substs: i.substs,
536                 nested: i.nested.into_iter().map(f).collect(),
537             }),
538             ImplSource::Param(n, ct) => ImplSource::Param(n.into_iter().map(f).collect(), ct),
539             ImplSource::Builtin(i) => ImplSource::Builtin(ImplSourceBuiltinData {
540                 nested: i.nested.into_iter().map(f).collect(),
541             }),
542             ImplSource::Object(o) => ImplSource::Object(ImplSourceObjectData {
543                 upcast_trait_ref: o.upcast_trait_ref,
544                 vtable_base: o.vtable_base,
545                 nested: o.nested.into_iter().map(f).collect(),
546             }),
547             ImplSource::AutoImpl(d) => ImplSource::AutoImpl(ImplSourceAutoImplData {
548                 trait_def_id: d.trait_def_id,
549                 nested: d.nested.into_iter().map(f).collect(),
550             }),
551             ImplSource::Closure(c) => ImplSource::Closure(ImplSourceClosureData {
552                 closure_def_id: c.closure_def_id,
553                 substs: c.substs,
554                 nested: c.nested.into_iter().map(f).collect(),
555             }),
556             ImplSource::Generator(c) => ImplSource::Generator(ImplSourceGeneratorData {
557                 generator_def_id: c.generator_def_id,
558                 substs: c.substs,
559                 nested: c.nested.into_iter().map(f).collect(),
560             }),
561             ImplSource::FnPointer(p) => ImplSource::FnPointer(ImplSourceFnPointerData {
562                 fn_ty: p.fn_ty,
563                 nested: p.nested.into_iter().map(f).collect(),
564             }),
565             ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData) => {
566                 ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData)
567             }
568             ImplSource::Pointee(ImplSourcePointeeData) => {
569                 ImplSource::Pointee(ImplSourcePointeeData)
570             }
571             ImplSource::TraitAlias(d) => ImplSource::TraitAlias(ImplSourceTraitAliasData {
572                 alias_def_id: d.alias_def_id,
573                 substs: d.substs,
574                 nested: d.nested.into_iter().map(f).collect(),
575             }),
576         }
577     }
578 }
579
580 /// Identifies a particular impl in the source, along with a set of
581 /// substitutions from the impl's type/lifetime parameters. The
582 /// `nested` vector corresponds to the nested obligations attached to
583 /// the impl's type parameters.
584 ///
585 /// The type parameter `N` indicates the type used for "nested
586 /// obligations" that are required by the impl. During type-check, this
587 /// is `Obligation`, as one might expect. During codegen, however, this
588 /// is `()`, because codegen only requires a shallow resolution of an
589 /// impl, and nested obligations are satisfied later.
590 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
591 pub struct ImplSourceUserDefinedData<'tcx, N> {
592     pub impl_def_id: DefId,
593     pub substs: SubstsRef<'tcx>,
594     pub nested: Vec<N>,
595 }
596
597 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
598 pub struct ImplSourceGeneratorData<'tcx, N> {
599     pub generator_def_id: DefId,
600     pub substs: SubstsRef<'tcx>,
601     /// Nested obligations. This can be non-empty if the generator
602     /// signature contains associated types.
603     pub nested: Vec<N>,
604 }
605
606 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
607 pub struct ImplSourceClosureData<'tcx, N> {
608     pub closure_def_id: DefId,
609     pub substs: SubstsRef<'tcx>,
610     /// Nested obligations. This can be non-empty if the closure
611     /// signature contains associated types.
612     pub nested: Vec<N>,
613 }
614
615 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
616 pub struct ImplSourceAutoImplData<N> {
617     pub trait_def_id: DefId,
618     pub nested: Vec<N>,
619 }
620
621 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
622 pub struct ImplSourceBuiltinData<N> {
623     pub nested: Vec<N>,
624 }
625
626 #[derive(PartialEq, Eq, Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
627 pub struct ImplSourceObjectData<'tcx, N> {
628     /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
629     pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
630
631     /// The vtable is formed by concatenating together the method lists of
632     /// the base object trait and all supertraits; this is the start of
633     /// `upcast_trait_ref`'s methods in that vtable.
634     pub vtable_base: usize,
635
636     pub nested: Vec<N>,
637 }
638
639 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
640 pub struct ImplSourceFnPointerData<'tcx, N> {
641     pub fn_ty: Ty<'tcx>,
642     pub nested: Vec<N>,
643 }
644
645 // FIXME(@lcnr): This should be  refactored and merged with other builtin vtables.
646 #[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
647 pub struct ImplSourceDiscriminantKindData;
648
649 #[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
650 pub struct ImplSourcePointeeData;
651
652 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
653 pub struct ImplSourceTraitAliasData<'tcx, N> {
654     pub alias_def_id: DefId,
655     pub substs: SubstsRef<'tcx>,
656     pub nested: Vec<N>,
657 }
658
659 #[derive(Clone, Debug, PartialEq, Eq, Hash, HashStable)]
660 pub enum ObjectSafetyViolation {
661     /// `Self: Sized` declared on the trait.
662     SizedSelf(SmallVec<[Span; 1]>),
663
664     /// Supertrait reference references `Self` an in illegal location
665     /// (e.g., `trait Foo : Bar<Self>`).
666     SupertraitSelf(SmallVec<[Span; 1]>),
667
668     /// Method has something illegal.
669     Method(Symbol, MethodViolationCode, Span),
670
671     /// Associated const.
672     AssocConst(Symbol, Span),
673
674     /// GAT
675     GAT(Symbol, Span),
676 }
677
678 impl ObjectSafetyViolation {
679     pub fn error_msg(&self) -> Cow<'static, str> {
680         match *self {
681             ObjectSafetyViolation::SizedSelf(_) => "it requires `Self: Sized`".into(),
682             ObjectSafetyViolation::SupertraitSelf(ref spans) => {
683                 if spans.iter().any(|sp| *sp != DUMMY_SP) {
684                     "it uses `Self` as a type parameter".into()
685                 } else {
686                     "it cannot use `Self` as a type parameter in a supertrait or `where`-clause"
687                         .into()
688                 }
689             }
690             ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod(_, _, _), _) => {
691                 format!("associated function `{}` has no `self` parameter", name).into()
692             }
693             ObjectSafetyViolation::Method(
694                 name,
695                 MethodViolationCode::ReferencesSelfInput(_),
696                 DUMMY_SP,
697             ) => format!("method `{}` references the `Self` type in its parameters", name).into(),
698             ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfInput(_), _) => {
699                 format!("method `{}` references the `Self` type in this parameter", name).into()
700             }
701             ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfOutput, _) => {
702                 format!("method `{}` references the `Self` type in its return type", name).into()
703             }
704             ObjectSafetyViolation::Method(
705                 name,
706                 MethodViolationCode::WhereClauseReferencesSelf,
707                 _,
708             ) => {
709                 format!("method `{}` references the `Self` type in its `where` clause", name).into()
710             }
711             ObjectSafetyViolation::Method(name, MethodViolationCode::Generic, _) => {
712                 format!("method `{}` has generic type parameters", name).into()
713             }
714             ObjectSafetyViolation::Method(name, MethodViolationCode::UndispatchableReceiver, _) => {
715                 format!("method `{}`'s `self` parameter cannot be dispatched on", name).into()
716             }
717             ObjectSafetyViolation::AssocConst(name, DUMMY_SP) => {
718                 format!("it contains associated `const` `{}`", name).into()
719             }
720             ObjectSafetyViolation::AssocConst(..) => "it contains this associated `const`".into(),
721             ObjectSafetyViolation::GAT(name, _) => {
722                 format!("it contains the generic associated type `{}`", name).into()
723             }
724         }
725     }
726
727     pub fn solution(&self, err: &mut DiagnosticBuilder<'_>) {
728         match *self {
729             ObjectSafetyViolation::SizedSelf(_) | ObjectSafetyViolation::SupertraitSelf(_) => {}
730             ObjectSafetyViolation::Method(
731                 name,
732                 MethodViolationCode::StaticMethod(sugg, self_span, has_args),
733                 _,
734             ) => {
735                 err.span_suggestion(
736                     self_span,
737                     &format!(
738                         "consider turning `{}` into a method by giving it a `&self` argument",
739                         name
740                     ),
741                     format!("&self{}", if has_args { ", " } else { "" }),
742                     Applicability::MaybeIncorrect,
743                 );
744                 match sugg {
745                     Some((sugg, span)) => {
746                         err.span_suggestion(
747                             span,
748                             &format!(
749                                 "alternatively, consider constraining `{}` so it does not apply to \
750                                  trait objects",
751                                 name
752                             ),
753                             sugg.to_string(),
754                             Applicability::MaybeIncorrect,
755                         );
756                     }
757                     None => {
758                         err.help(&format!(
759                             "consider turning `{}` into a method by giving it a `&self` \
760                              argument or constraining it so it does not apply to trait objects",
761                             name
762                         ));
763                     }
764                 }
765             }
766             ObjectSafetyViolation::Method(
767                 name,
768                 MethodViolationCode::UndispatchableReceiver,
769                 span,
770             ) => {
771                 err.span_suggestion(
772                     span,
773                     &format!(
774                         "consider changing method `{}`'s `self` parameter to be `&self`",
775                         name
776                     ),
777                     "&Self".to_string(),
778                     Applicability::MachineApplicable,
779                 );
780             }
781             ObjectSafetyViolation::AssocConst(name, _)
782             | ObjectSafetyViolation::GAT(name, _)
783             | ObjectSafetyViolation::Method(name, ..) => {
784                 err.help(&format!("consider moving `{}` to another trait", name));
785             }
786         }
787     }
788
789     pub fn spans(&self) -> SmallVec<[Span; 1]> {
790         // When `span` comes from a separate crate, it'll be `DUMMY_SP`. Treat it as `None` so
791         // diagnostics use a `note` instead of a `span_label`.
792         match self {
793             ObjectSafetyViolation::SupertraitSelf(spans)
794             | ObjectSafetyViolation::SizedSelf(spans) => spans.clone(),
795             ObjectSafetyViolation::AssocConst(_, span)
796             | ObjectSafetyViolation::GAT(_, span)
797             | ObjectSafetyViolation::Method(_, _, span)
798                 if *span != DUMMY_SP =>
799             {
800                 smallvec![*span]
801             }
802             _ => smallvec![],
803         }
804     }
805 }
806
807 /// Reasons a method might not be object-safe.
808 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
809 pub enum MethodViolationCode {
810     /// e.g., `fn foo()`
811     StaticMethod(Option<(&'static str, Span)>, Span, bool /* has args */),
812
813     /// e.g., `fn foo(&self, x: Self)`
814     ReferencesSelfInput(usize),
815
816     /// e.g., `fn foo(&self) -> Self`
817     ReferencesSelfOutput,
818
819     /// e.g., `fn foo(&self) where Self: Clone`
820     WhereClauseReferencesSelf,
821
822     /// e.g., `fn foo<A>()`
823     Generic,
824
825     /// the method's receiver (`self` argument) can't be dispatched on
826     UndispatchableReceiver,
827 }