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