]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/traits/mod.rs
f951e43fbfa3538c163e24eb35447cef734d62f1
[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_data_structures::sync::Lrc;
17 use rustc_errors::{Applicability, DiagnosticBuilder};
18 use rustc_hir as hir;
19 use rustc_hir::def_id::DefId;
20 use rustc_hir::Constness;
21 use rustc_span::symbol::Symbol;
22 use rustc_span::{Span, DUMMY_SP};
23 use smallvec::SmallVec;
24
25 use std::borrow::Cow;
26 use std::fmt;
27 use std::ops::Deref;
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<Lrc<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(Lrc::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         Lrc::make_mut(self.data.get_or_insert_with(|| Lrc::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     /// Well-formed checking. If a `HirId` is provided,
331     /// it is used to perform HIR-based wf checking if an error
332     /// occurs, in order to generate a more precise error message.
333     /// This is purely for diagnostic purposes - it is always
334     /// correct to use `MiscObligation` instead
335     WellFormed(Option<hir::HirId>),
336
337     /// From `match_impl`. The cause for us having to match an impl, and the DefId we are matching against.
338     MatchImpl(Lrc<ObligationCauseCode<'tcx>>, DefId),
339 }
340
341 impl ObligationCauseCode<'_> {
342     // Return the base obligation, ignoring derived obligations.
343     pub fn peel_derives(&self) -> &Self {
344         let mut base_cause = self;
345         while let BuiltinDerivedObligation(cause)
346         | ImplDerivedObligation(cause)
347         | DerivedObligation(cause) = base_cause
348         {
349             base_cause = &cause.parent_code;
350         }
351         base_cause
352     }
353 }
354
355 // `ObligationCauseCode` is used a lot. Make sure it doesn't unintentionally get bigger.
356 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
357 static_assert_size!(ObligationCauseCode<'_>, 40);
358
359 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
360 pub enum StatementAsExpression {
361     CorrectType,
362     NeedsBoxing,
363 }
364
365 impl<'tcx> ty::Lift<'tcx> for StatementAsExpression {
366     type Lifted = StatementAsExpression;
367     fn lift_to_tcx(self, _tcx: TyCtxt<'tcx>) -> Option<StatementAsExpression> {
368         Some(self)
369     }
370 }
371
372 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
373 pub struct MatchExpressionArmCause<'tcx> {
374     pub arm_span: Span,
375     pub scrut_span: Span,
376     pub semi_span: Option<(Span, StatementAsExpression)>,
377     pub source: hir::MatchSource,
378     pub prior_arms: Vec<Span>,
379     pub last_ty: Ty<'tcx>,
380     pub scrut_hir_id: hir::HirId,
381     pub opt_suggest_box_span: Option<Span>,
382 }
383
384 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
385 pub struct IfExpressionCause {
386     pub then: Span,
387     pub else_sp: Span,
388     pub outer: Option<Span>,
389     pub semicolon: Option<(Span, StatementAsExpression)>,
390     pub opt_suggest_box_span: Option<Span>,
391 }
392
393 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
394 pub struct DerivedObligationCause<'tcx> {
395     /// The trait reference of the parent obligation that led to the
396     /// current obligation. Note that only trait obligations lead to
397     /// derived obligations, so we just store the trait reference here
398     /// directly.
399     pub parent_trait_ref: ty::PolyTraitRef<'tcx>,
400
401     /// The parent trait had this cause.
402     pub parent_code: Lrc<ObligationCauseCode<'tcx>>,
403 }
404
405 #[derive(Clone, Debug, TypeFoldable, Lift)]
406 pub enum SelectionError<'tcx> {
407     Unimplemented,
408     OutputTypeParameterMismatch(
409         ty::PolyTraitRef<'tcx>,
410         ty::PolyTraitRef<'tcx>,
411         ty::error::TypeError<'tcx>,
412     ),
413     TraitNotObjectSafe(DefId),
414     NotConstEvaluatable(NotConstEvaluatable),
415     Overflow,
416 }
417
418 /// When performing resolution, it is typically the case that there
419 /// can be one of three outcomes:
420 ///
421 /// - `Ok(Some(r))`: success occurred with result `r`
422 /// - `Ok(None)`: could not definitely determine anything, usually due
423 ///   to inconclusive type inference.
424 /// - `Err(e)`: error `e` occurred
425 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
426
427 /// Given the successful resolution of an obligation, the `ImplSource`
428 /// indicates where the impl comes from.
429 ///
430 /// For example, the obligation may be satisfied by a specific impl (case A),
431 /// or it may be relative to some bound that is in scope (case B).
432 ///
433 /// ```
434 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
435 /// impl<T:Clone> Clone<T> for Box<T> { ... }    // Impl_2
436 /// impl Clone for i32 { ... }                   // Impl_3
437 ///
438 /// fn foo<T: Clone>(concrete: Option<Box<i32>>, param: T, mixed: Option<T>) {
439 ///     // Case A: ImplSource points at a specific impl. Only possible when
440 ///     // type is concretely known. If the impl itself has bounded
441 ///     // type parameters, ImplSource will carry resolutions for those as well:
442 ///     concrete.clone(); // ImpleSource(Impl_1, [ImplSource(Impl_2, [ImplSource(Impl_3)])])
443 ///
444 ///     // Case A: ImplSource points at a specific impl. Only possible when
445 ///     // type is concretely known. If the impl itself has bounded
446 ///     // type parameters, ImplSource will carry resolutions for those as well:
447 ///     concrete.clone(); // ImplSource(Impl_1, [ImplSource(Impl_2, [ImplSource(Impl_3)])])
448 ///
449 ///     // Case B: ImplSource must be provided by caller. This applies when
450 ///     // type is a type parameter.
451 ///     param.clone();    // ImplSource::Param
452 ///
453 ///     // Case C: A mix of cases A and B.
454 ///     mixed.clone();    // ImplSource(Impl_1, [ImplSource::Param])
455 /// }
456 /// ```
457 ///
458 /// ### The type parameter `N`
459 ///
460 /// See explanation on `ImplSourceUserDefinedData`.
461 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
462 pub enum ImplSource<'tcx, N> {
463     /// ImplSource identifying a particular impl.
464     UserDefined(ImplSourceUserDefinedData<'tcx, N>),
465
466     /// ImplSource for auto trait implementations.
467     /// This carries the information and nested obligations with regards
468     /// to an auto implementation for a trait `Trait`. The nested obligations
469     /// ensure the trait implementation holds for all the constituent types.
470     AutoImpl(ImplSourceAutoImplData<N>),
471
472     /// Successful resolution to an obligation provided by the caller
473     /// for some type parameter. The `Vec<N>` represents the
474     /// obligations incurred from normalizing the where-clause (if
475     /// any).
476     Param(Vec<N>, Constness),
477
478     /// Virtual calls through an object.
479     Object(ImplSourceObjectData<'tcx, N>),
480
481     /// Successful resolution for a builtin trait.
482     Builtin(ImplSourceBuiltinData<N>),
483
484     /// ImplSource automatically generated for a closure. The `DefId` is the ID
485     /// of the closure expression. This is a `ImplSource::UserDefined` in spirit, but the
486     /// impl is generated by the compiler and does not appear in the source.
487     Closure(ImplSourceClosureData<'tcx, N>),
488
489     /// Same as above, but for a function pointer type with the given signature.
490     FnPointer(ImplSourceFnPointerData<'tcx, N>),
491
492     /// ImplSource for a builtin `DeterminantKind` trait implementation.
493     DiscriminantKind(ImplSourceDiscriminantKindData),
494
495     /// ImplSource for a builtin `Pointee` trait implementation.
496     Pointee(ImplSourcePointeeData),
497
498     /// ImplSource automatically generated for a generator.
499     Generator(ImplSourceGeneratorData<'tcx, N>),
500
501     /// ImplSource for a trait alias.
502     TraitAlias(ImplSourceTraitAliasData<'tcx, N>),
503 }
504
505 impl<'tcx, N> ImplSource<'tcx, N> {
506     pub fn nested_obligations(self) -> Vec<N> {
507         match self {
508             ImplSource::UserDefined(i) => i.nested,
509             ImplSource::Param(n, _) => n,
510             ImplSource::Builtin(i) => i.nested,
511             ImplSource::AutoImpl(d) => d.nested,
512             ImplSource::Closure(c) => c.nested,
513             ImplSource::Generator(c) => c.nested,
514             ImplSource::Object(d) => d.nested,
515             ImplSource::FnPointer(d) => d.nested,
516             ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData)
517             | ImplSource::Pointee(ImplSourcePointeeData) => Vec::new(),
518             ImplSource::TraitAlias(d) => d.nested,
519         }
520     }
521
522     pub fn borrow_nested_obligations(&self) -> &[N] {
523         match &self {
524             ImplSource::UserDefined(i) => &i.nested[..],
525             ImplSource::Param(n, _) => &n[..],
526             ImplSource::Builtin(i) => &i.nested[..],
527             ImplSource::AutoImpl(d) => &d.nested[..],
528             ImplSource::Closure(c) => &c.nested[..],
529             ImplSource::Generator(c) => &c.nested[..],
530             ImplSource::Object(d) => &d.nested[..],
531             ImplSource::FnPointer(d) => &d.nested[..],
532             ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData)
533             | ImplSource::Pointee(ImplSourcePointeeData) => &[],
534             ImplSource::TraitAlias(d) => &d.nested[..],
535         }
536     }
537
538     pub fn map<M, F>(self, f: F) -> ImplSource<'tcx, M>
539     where
540         F: FnMut(N) -> M,
541     {
542         match self {
543             ImplSource::UserDefined(i) => ImplSource::UserDefined(ImplSourceUserDefinedData {
544                 impl_def_id: i.impl_def_id,
545                 substs: i.substs,
546                 nested: i.nested.into_iter().map(f).collect(),
547             }),
548             ImplSource::Param(n, ct) => ImplSource::Param(n.into_iter().map(f).collect(), ct),
549             ImplSource::Builtin(i) => ImplSource::Builtin(ImplSourceBuiltinData {
550                 nested: i.nested.into_iter().map(f).collect(),
551             }),
552             ImplSource::Object(o) => ImplSource::Object(ImplSourceObjectData {
553                 upcast_trait_ref: o.upcast_trait_ref,
554                 vtable_base: o.vtable_base,
555                 nested: o.nested.into_iter().map(f).collect(),
556             }),
557             ImplSource::AutoImpl(d) => ImplSource::AutoImpl(ImplSourceAutoImplData {
558                 trait_def_id: d.trait_def_id,
559                 nested: d.nested.into_iter().map(f).collect(),
560             }),
561             ImplSource::Closure(c) => ImplSource::Closure(ImplSourceClosureData {
562                 closure_def_id: c.closure_def_id,
563                 substs: c.substs,
564                 nested: c.nested.into_iter().map(f).collect(),
565             }),
566             ImplSource::Generator(c) => ImplSource::Generator(ImplSourceGeneratorData {
567                 generator_def_id: c.generator_def_id,
568                 substs: c.substs,
569                 nested: c.nested.into_iter().map(f).collect(),
570             }),
571             ImplSource::FnPointer(p) => ImplSource::FnPointer(ImplSourceFnPointerData {
572                 fn_ty: p.fn_ty,
573                 nested: p.nested.into_iter().map(f).collect(),
574             }),
575             ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData) => {
576                 ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData)
577             }
578             ImplSource::Pointee(ImplSourcePointeeData) => {
579                 ImplSource::Pointee(ImplSourcePointeeData)
580             }
581             ImplSource::TraitAlias(d) => ImplSource::TraitAlias(ImplSourceTraitAliasData {
582                 alias_def_id: d.alias_def_id,
583                 substs: d.substs,
584                 nested: d.nested.into_iter().map(f).collect(),
585             }),
586         }
587     }
588 }
589
590 /// Identifies a particular impl in the source, along with a set of
591 /// substitutions from the impl's type/lifetime parameters. The
592 /// `nested` vector corresponds to the nested obligations attached to
593 /// the impl's type parameters.
594 ///
595 /// The type parameter `N` indicates the type used for "nested
596 /// obligations" that are required by the impl. During type-check, this
597 /// is `Obligation`, as one might expect. During codegen, however, this
598 /// is `()`, because codegen only requires a shallow resolution of an
599 /// impl, and nested obligations are satisfied later.
600 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
601 pub struct ImplSourceUserDefinedData<'tcx, N> {
602     pub impl_def_id: DefId,
603     pub substs: SubstsRef<'tcx>,
604     pub nested: Vec<N>,
605 }
606
607 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
608 pub struct ImplSourceGeneratorData<'tcx, N> {
609     pub generator_def_id: DefId,
610     pub substs: SubstsRef<'tcx>,
611     /// Nested obligations. This can be non-empty if the generator
612     /// signature contains associated types.
613     pub nested: Vec<N>,
614 }
615
616 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
617 pub struct ImplSourceClosureData<'tcx, N> {
618     pub closure_def_id: DefId,
619     pub substs: SubstsRef<'tcx>,
620     /// Nested obligations. This can be non-empty if the closure
621     /// signature contains associated types.
622     pub nested: Vec<N>,
623 }
624
625 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
626 pub struct ImplSourceAutoImplData<N> {
627     pub trait_def_id: DefId,
628     pub nested: Vec<N>,
629 }
630
631 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
632 pub struct ImplSourceBuiltinData<N> {
633     pub nested: Vec<N>,
634 }
635
636 #[derive(PartialEq, Eq, Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
637 pub struct ImplSourceObjectData<'tcx, N> {
638     /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
639     pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
640
641     /// The vtable is formed by concatenating together the method lists of
642     /// the base object trait and all supertraits; this is the start of
643     /// `upcast_trait_ref`'s methods in that vtable.
644     pub vtable_base: usize,
645
646     pub nested: Vec<N>,
647 }
648
649 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
650 pub struct ImplSourceFnPointerData<'tcx, N> {
651     pub fn_ty: Ty<'tcx>,
652     pub nested: Vec<N>,
653 }
654
655 // FIXME(@lcnr): This should be  refactored and merged with other builtin vtables.
656 #[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
657 pub struct ImplSourceDiscriminantKindData;
658
659 #[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
660 pub struct ImplSourcePointeeData;
661
662 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
663 pub struct ImplSourceTraitAliasData<'tcx, N> {
664     pub alias_def_id: DefId,
665     pub substs: SubstsRef<'tcx>,
666     pub nested: Vec<N>,
667 }
668
669 #[derive(Clone, Debug, PartialEq, Eq, Hash, HashStable)]
670 pub enum ObjectSafetyViolation {
671     /// `Self: Sized` declared on the trait.
672     SizedSelf(SmallVec<[Span; 1]>),
673
674     /// Supertrait reference references `Self` an in illegal location
675     /// (e.g., `trait Foo : Bar<Self>`).
676     SupertraitSelf(SmallVec<[Span; 1]>),
677
678     /// Method has something illegal.
679     Method(Symbol, MethodViolationCode, Span),
680
681     /// Associated const.
682     AssocConst(Symbol, Span),
683
684     /// GAT
685     GAT(Symbol, Span),
686 }
687
688 impl ObjectSafetyViolation {
689     pub fn error_msg(&self) -> Cow<'static, str> {
690         match *self {
691             ObjectSafetyViolation::SizedSelf(_) => "it requires `Self: Sized`".into(),
692             ObjectSafetyViolation::SupertraitSelf(ref spans) => {
693                 if spans.iter().any(|sp| *sp != DUMMY_SP) {
694                     "it uses `Self` as a type parameter".into()
695                 } else {
696                     "it cannot use `Self` as a type parameter in a supertrait or `where`-clause"
697                         .into()
698                 }
699             }
700             ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod(_, _, _), _) => {
701                 format!("associated function `{}` has no `self` parameter", name).into()
702             }
703             ObjectSafetyViolation::Method(
704                 name,
705                 MethodViolationCode::ReferencesSelfInput(_),
706                 DUMMY_SP,
707             ) => format!("method `{}` references the `Self` type in its parameters", name).into(),
708             ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfInput(_), _) => {
709                 format!("method `{}` references the `Self` type in this parameter", name).into()
710             }
711             ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfOutput, _) => {
712                 format!("method `{}` references the `Self` type in its return type", name).into()
713             }
714             ObjectSafetyViolation::Method(
715                 name,
716                 MethodViolationCode::WhereClauseReferencesSelf,
717                 _,
718             ) => {
719                 format!("method `{}` references the `Self` type in its `where` clause", name).into()
720             }
721             ObjectSafetyViolation::Method(name, MethodViolationCode::Generic, _) => {
722                 format!("method `{}` has generic type parameters", name).into()
723             }
724             ObjectSafetyViolation::Method(name, MethodViolationCode::UndispatchableReceiver, _) => {
725                 format!("method `{}`'s `self` parameter cannot be dispatched on", name).into()
726             }
727             ObjectSafetyViolation::AssocConst(name, DUMMY_SP) => {
728                 format!("it contains associated `const` `{}`", name).into()
729             }
730             ObjectSafetyViolation::AssocConst(..) => "it contains this associated `const`".into(),
731             ObjectSafetyViolation::GAT(name, _) => {
732                 format!("it contains the generic associated type `{}`", name).into()
733             }
734         }
735     }
736
737     pub fn solution(&self, err: &mut DiagnosticBuilder<'_>) {
738         match *self {
739             ObjectSafetyViolation::SizedSelf(_) | ObjectSafetyViolation::SupertraitSelf(_) => {}
740             ObjectSafetyViolation::Method(
741                 name,
742                 MethodViolationCode::StaticMethod(sugg, self_span, has_args),
743                 _,
744             ) => {
745                 err.span_suggestion(
746                     self_span,
747                     &format!(
748                         "consider turning `{}` into a method by giving it a `&self` argument",
749                         name
750                     ),
751                     format!("&self{}", if has_args { ", " } else { "" }),
752                     Applicability::MaybeIncorrect,
753                 );
754                 match sugg {
755                     Some((sugg, span)) => {
756                         err.span_suggestion(
757                             span,
758                             &format!(
759                                 "alternatively, consider constraining `{}` so it does not apply to \
760                                  trait objects",
761                                 name
762                             ),
763                             sugg.to_string(),
764                             Applicability::MaybeIncorrect,
765                         );
766                     }
767                     None => {
768                         err.help(&format!(
769                             "consider turning `{}` into a method by giving it a `&self` \
770                              argument or constraining it so it does not apply to trait objects",
771                             name
772                         ));
773                     }
774                 }
775             }
776             ObjectSafetyViolation::Method(
777                 name,
778                 MethodViolationCode::UndispatchableReceiver,
779                 span,
780             ) => {
781                 err.span_suggestion(
782                     span,
783                     &format!(
784                         "consider changing method `{}`'s `self` parameter to be `&self`",
785                         name
786                     ),
787                     "&Self".to_string(),
788                     Applicability::MachineApplicable,
789                 );
790             }
791             ObjectSafetyViolation::AssocConst(name, _)
792             | ObjectSafetyViolation::GAT(name, _)
793             | ObjectSafetyViolation::Method(name, ..) => {
794                 err.help(&format!("consider moving `{}` to another trait", name));
795             }
796         }
797     }
798
799     pub fn spans(&self) -> SmallVec<[Span; 1]> {
800         // When `span` comes from a separate crate, it'll be `DUMMY_SP`. Treat it as `None` so
801         // diagnostics use a `note` instead of a `span_label`.
802         match self {
803             ObjectSafetyViolation::SupertraitSelf(spans)
804             | ObjectSafetyViolation::SizedSelf(spans) => spans.clone(),
805             ObjectSafetyViolation::AssocConst(_, span)
806             | ObjectSafetyViolation::GAT(_, span)
807             | ObjectSafetyViolation::Method(_, _, span)
808                 if *span != DUMMY_SP =>
809             {
810                 smallvec![*span]
811             }
812             _ => smallvec![],
813         }
814     }
815 }
816
817 /// Reasons a method might not be object-safe.
818 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
819 pub enum MethodViolationCode {
820     /// e.g., `fn foo()`
821     StaticMethod(Option<(&'static str, Span)>, Span, bool /* has args */),
822
823     /// e.g., `fn foo(&self, x: Self)`
824     ReferencesSelfInput(usize),
825
826     /// e.g., `fn foo(&self) -> Self`
827     ReferencesSelfOutput,
828
829     /// e.g., `fn foo(&self) where Self: Clone`
830     WhereClauseReferencesSelf,
831
832     /// e.g., `fn foo<A>()`
833     Generic,
834
835     /// the method's receiver (`self` argument) can't be dispatched on
836     UndispatchableReceiver,
837 }