]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/traits/mod.rs
Rollup merge of #85766 - workingjubilee:file-options, r=yaahc
[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::thir::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     FunctionArgumentObligation {
257         /// The node of the relevant argument in the function call.
258         arg_hir_id: hir::HirId,
259         /// The node of the function call.
260         call_hir_id: hir::HirId,
261         /// The obligation introduced by this argument.
262         parent_code: Lrc<ObligationCauseCode<'tcx>>,
263     },
264
265     /// Error derived when matching traits/impls; see ObligationCause for more details
266     CompareImplConstObligation,
267
268     /// Error derived when matching traits/impls; see ObligationCause for more details
269     CompareImplMethodObligation {
270         impl_item_def_id: DefId,
271         trait_item_def_id: DefId,
272     },
273
274     /// Error derived when matching traits/impls; see ObligationCause for more details
275     CompareImplTypeObligation {
276         impl_item_def_id: DefId,
277         trait_item_def_id: DefId,
278     },
279
280     /// Checking that this expression can be assigned where it needs to be
281     // FIXME(eddyb) #11161 is the original Expr required?
282     ExprAssignable,
283
284     /// Computing common supertype in the arms of a match expression
285     MatchExpressionArm(Box<MatchExpressionArmCause<'tcx>>),
286
287     /// Type error arising from type checking a pattern against an expected type.
288     Pattern {
289         /// The span of the scrutinee or type expression which caused the `root_ty` type.
290         span: Option<Span>,
291         /// The root expected type induced by a scrutinee or type expression.
292         root_ty: Ty<'tcx>,
293         /// Whether the `Span` came from an expression or a type expression.
294         origin_expr: bool,
295     },
296
297     /// Constants in patterns must have `Structural` type.
298     ConstPatternStructural,
299
300     /// Computing common supertype in an if expression
301     IfExpression(Box<IfExpressionCause>),
302
303     /// Computing common supertype of an if expression with no else counter-part
304     IfExpressionWithNoElse,
305
306     /// `main` has wrong type
307     MainFunctionType,
308
309     /// `start` has wrong type
310     StartFunctionType,
311
312     /// Intrinsic has wrong type
313     IntrinsicType,
314
315     /// A let else block does not diverge
316     LetElse,
317
318     /// Method receiver
319     MethodReceiver,
320
321     UnifyReceiver(Box<UnifyReceiverContext<'tcx>>),
322
323     /// `return` with no expression
324     ReturnNoExpression,
325
326     /// `return` with an expression
327     ReturnValue(hir::HirId),
328
329     /// Return type of this function
330     ReturnType,
331
332     /// Block implicit return
333     BlockTailExpression(hir::HirId),
334
335     /// #[feature(trivial_bounds)] is not enabled
336     TrivialBound,
337
338     /// If `X` is the concrete type of an opaque type `impl Y`, then `X` must implement `Y`
339     OpaqueType,
340
341     /// Well-formed checking. If a `WellFormedLoc` is provided,
342     /// then it will be used to eprform HIR-based wf checking
343     /// after an error occurs, in order to generate a more precise error span.
344     /// This is purely for diagnostic purposes - it is always
345     /// correct to use `MiscObligation` instead, or to specify
346     /// `WellFormed(None)`
347     WellFormed(Option<WellFormedLoc>),
348
349     /// From `match_impl`. The cause for us having to match an impl, and the DefId we are matching against.
350     MatchImpl(ObligationCause<'tcx>, DefId),
351 }
352
353 /// The 'location' at which we try to perform HIR-based wf checking.
354 /// This information is used to obtain an `hir::Ty`, which
355 /// we can walk in order to obtain precise spans for any
356 /// 'nested' types (e.g. `Foo` in `Option<Foo>`).
357 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
358 pub enum WellFormedLoc {
359     /// Use the type of the provided definition.
360     Ty(LocalDefId),
361     /// Use the type of the parameter of the provided function.
362     /// We cannot use `hir::Param`, since the function may
363     /// not have a body (e.g. a trait method definition)
364     Param {
365         /// The function to lookup the parameter in
366         function: LocalDefId,
367         /// The index of the parameter to use.
368         /// Parameters are indexed from 0, with the return type
369         /// being the last 'parameter'
370         param_idx: u16,
371     },
372 }
373
374 impl ObligationCauseCode<'_> {
375     // Return the base obligation, ignoring derived obligations.
376     pub fn peel_derives(&self) -> &Self {
377         let mut base_cause = self;
378         while let BuiltinDerivedObligation(DerivedObligationCause { parent_code, .. })
379         | ImplDerivedObligation(DerivedObligationCause { parent_code, .. })
380         | DerivedObligation(DerivedObligationCause { parent_code, .. })
381         | FunctionArgumentObligation { parent_code, .. } = base_cause
382         {
383             base_cause = &parent_code;
384         }
385         base_cause
386     }
387 }
388
389 // `ObligationCauseCode` is used a lot. Make sure it doesn't unintentionally get bigger.
390 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
391 static_assert_size!(ObligationCauseCode<'_>, 40);
392
393 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
394 pub enum StatementAsExpression {
395     CorrectType,
396     NeedsBoxing,
397 }
398
399 impl<'tcx> ty::Lift<'tcx> for StatementAsExpression {
400     type Lifted = StatementAsExpression;
401     fn lift_to_tcx(self, _tcx: TyCtxt<'tcx>) -> Option<StatementAsExpression> {
402         Some(self)
403     }
404 }
405
406 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
407 pub struct MatchExpressionArmCause<'tcx> {
408     pub arm_span: Span,
409     pub scrut_span: Span,
410     pub semi_span: Option<(Span, StatementAsExpression)>,
411     pub source: hir::MatchSource,
412     pub prior_arms: Vec<Span>,
413     pub last_ty: Ty<'tcx>,
414     pub scrut_hir_id: hir::HirId,
415     pub opt_suggest_box_span: Option<Span>,
416 }
417
418 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
419 pub struct IfExpressionCause {
420     pub then: Span,
421     pub else_sp: Span,
422     pub outer: Option<Span>,
423     pub semicolon: Option<(Span, StatementAsExpression)>,
424     pub opt_suggest_box_span: Option<Span>,
425 }
426
427 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
428 pub struct DerivedObligationCause<'tcx> {
429     /// The trait reference of the parent obligation that led to the
430     /// current obligation. Note that only trait obligations lead to
431     /// derived obligations, so we just store the trait reference here
432     /// directly.
433     pub parent_trait_ref: ty::PolyTraitRef<'tcx>,
434
435     /// The parent trait had this cause.
436     pub parent_code: Lrc<ObligationCauseCode<'tcx>>,
437 }
438
439 #[derive(Clone, Debug, TypeFoldable, Lift)]
440 pub enum SelectionError<'tcx> {
441     /// The trait is not implemented.
442     Unimplemented,
443     /// After a closure impl has selected, its "outputs" were evaluated
444     /// (which for closures includes the "input" type params) and they
445     /// didn't resolve. See `confirm_poly_trait_refs` for more.
446     OutputTypeParameterMismatch(
447         ty::PolyTraitRef<'tcx>,
448         ty::PolyTraitRef<'tcx>,
449         ty::error::TypeError<'tcx>,
450     ),
451     /// The trait pointed by `DefId` is not object safe.
452     TraitNotObjectSafe(DefId),
453     /// A given constant couldn't be evaluated.
454     NotConstEvaluatable(NotConstEvaluatable),
455     /// Exceeded the recursion depth during type projection.
456     Overflow,
457     /// Signaling that an error has already been emitted, to avoid
458     /// multiple errors being shown.
459     ErrorReporting,
460     /// Multiple applicable `impl`s where found. The `DefId`s correspond to
461     /// all the `impl`s' Items.
462     Ambiguous(Vec<DefId>),
463 }
464
465 /// When performing resolution, it is typically the case that there
466 /// can be one of three outcomes:
467 ///
468 /// - `Ok(Some(r))`: success occurred with result `r`
469 /// - `Ok(None)`: could not definitely determine anything, usually due
470 ///   to inconclusive type inference.
471 /// - `Err(e)`: error `e` occurred
472 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
473
474 /// Given the successful resolution of an obligation, the `ImplSource`
475 /// indicates where the impl comes from.
476 ///
477 /// For example, the obligation may be satisfied by a specific impl (case A),
478 /// or it may be relative to some bound that is in scope (case B).
479 ///
480 /// ```
481 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
482 /// impl<T:Clone> Clone<T> for Box<T> { ... }    // Impl_2
483 /// impl Clone for i32 { ... }                   // Impl_3
484 ///
485 /// fn foo<T: Clone>(concrete: Option<Box<i32>>, param: T, mixed: Option<T>) {
486 ///     // Case A: ImplSource points at a specific impl. Only possible when
487 ///     // type is concretely known. If the impl itself has bounded
488 ///     // type parameters, ImplSource will carry resolutions for those as well:
489 ///     concrete.clone(); // ImpleSource(Impl_1, [ImplSource(Impl_2, [ImplSource(Impl_3)])])
490 ///
491 ///     // Case A: ImplSource points at a specific impl. Only possible when
492 ///     // type is concretely known. If the impl itself has bounded
493 ///     // type parameters, ImplSource will carry resolutions for those as well:
494 ///     concrete.clone(); // ImplSource(Impl_1, [ImplSource(Impl_2, [ImplSource(Impl_3)])])
495 ///
496 ///     // Case B: ImplSource must be provided by caller. This applies when
497 ///     // type is a type parameter.
498 ///     param.clone();    // ImplSource::Param
499 ///
500 ///     // Case C: A mix of cases A and B.
501 ///     mixed.clone();    // ImplSource(Impl_1, [ImplSource::Param])
502 /// }
503 /// ```
504 ///
505 /// ### The type parameter `N`
506 ///
507 /// See explanation on `ImplSourceUserDefinedData`.
508 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
509 pub enum ImplSource<'tcx, N> {
510     /// ImplSource identifying a particular impl.
511     UserDefined(ImplSourceUserDefinedData<'tcx, N>),
512
513     /// ImplSource for auto trait implementations.
514     /// This carries the information and nested obligations with regards
515     /// to an auto implementation for a trait `Trait`. The nested obligations
516     /// ensure the trait implementation holds for all the constituent types.
517     AutoImpl(ImplSourceAutoImplData<N>),
518
519     /// Successful resolution to an obligation provided by the caller
520     /// for some type parameter. The `Vec<N>` represents the
521     /// obligations incurred from normalizing the where-clause (if
522     /// any).
523     Param(Vec<N>, ty::BoundConstness),
524
525     /// Virtual calls through an object.
526     Object(ImplSourceObjectData<'tcx, N>),
527
528     /// Successful resolution for a builtin trait.
529     Builtin(ImplSourceBuiltinData<N>),
530
531     /// ImplSource for trait upcasting coercion
532     TraitUpcasting(ImplSourceTraitUpcastingData<'tcx, N>),
533
534     /// ImplSource automatically generated for a closure. The `DefId` is the ID
535     /// of the closure expression. This is an `ImplSource::UserDefined` in spirit, but the
536     /// impl is generated by the compiler and does not appear in the source.
537     Closure(ImplSourceClosureData<'tcx, N>),
538
539     /// Same as above, but for a function pointer type with the given signature.
540     FnPointer(ImplSourceFnPointerData<'tcx, N>),
541
542     /// ImplSource for a builtin `DeterminantKind` trait implementation.
543     DiscriminantKind(ImplSourceDiscriminantKindData),
544
545     /// ImplSource for a builtin `Pointee` trait implementation.
546     Pointee(ImplSourcePointeeData),
547
548     /// ImplSource automatically generated for a generator.
549     Generator(ImplSourceGeneratorData<'tcx, N>),
550
551     /// ImplSource for a trait alias.
552     TraitAlias(ImplSourceTraitAliasData<'tcx, N>),
553
554     /// ImplSource for a `const Drop` implementation.
555     ConstDrop(ImplSourceConstDropData),
556 }
557
558 impl<'tcx, N> ImplSource<'tcx, N> {
559     pub fn nested_obligations(self) -> Vec<N> {
560         match self {
561             ImplSource::UserDefined(i) => i.nested,
562             ImplSource::Param(n, _) => n,
563             ImplSource::Builtin(i) => i.nested,
564             ImplSource::AutoImpl(d) => d.nested,
565             ImplSource::Closure(c) => c.nested,
566             ImplSource::Generator(c) => c.nested,
567             ImplSource::Object(d) => d.nested,
568             ImplSource::FnPointer(d) => d.nested,
569             ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData)
570             | ImplSource::Pointee(ImplSourcePointeeData)
571             | ImplSource::ConstDrop(ImplSourceConstDropData) => Vec::new(),
572             ImplSource::TraitAlias(d) => d.nested,
573             ImplSource::TraitUpcasting(d) => d.nested,
574         }
575     }
576
577     pub fn borrow_nested_obligations(&self) -> &[N] {
578         match &self {
579             ImplSource::UserDefined(i) => &i.nested[..],
580             ImplSource::Param(n, _) => &n[..],
581             ImplSource::Builtin(i) => &i.nested[..],
582             ImplSource::AutoImpl(d) => &d.nested[..],
583             ImplSource::Closure(c) => &c.nested[..],
584             ImplSource::Generator(c) => &c.nested[..],
585             ImplSource::Object(d) => &d.nested[..],
586             ImplSource::FnPointer(d) => &d.nested[..],
587             ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData)
588             | ImplSource::Pointee(ImplSourcePointeeData)
589             | ImplSource::ConstDrop(ImplSourceConstDropData) => &[],
590             ImplSource::TraitAlias(d) => &d.nested[..],
591             ImplSource::TraitUpcasting(d) => &d.nested[..],
592         }
593     }
594
595     pub fn map<M, F>(self, f: F) -> ImplSource<'tcx, M>
596     where
597         F: FnMut(N) -> M,
598     {
599         match self {
600             ImplSource::UserDefined(i) => ImplSource::UserDefined(ImplSourceUserDefinedData {
601                 impl_def_id: i.impl_def_id,
602                 substs: i.substs,
603                 nested: i.nested.into_iter().map(f).collect(),
604             }),
605             ImplSource::Param(n, ct) => ImplSource::Param(n.into_iter().map(f).collect(), ct),
606             ImplSource::Builtin(i) => ImplSource::Builtin(ImplSourceBuiltinData {
607                 nested: i.nested.into_iter().map(f).collect(),
608             }),
609             ImplSource::Object(o) => ImplSource::Object(ImplSourceObjectData {
610                 upcast_trait_ref: o.upcast_trait_ref,
611                 vtable_base: o.vtable_base,
612                 nested: o.nested.into_iter().map(f).collect(),
613             }),
614             ImplSource::AutoImpl(d) => ImplSource::AutoImpl(ImplSourceAutoImplData {
615                 trait_def_id: d.trait_def_id,
616                 nested: d.nested.into_iter().map(f).collect(),
617             }),
618             ImplSource::Closure(c) => ImplSource::Closure(ImplSourceClosureData {
619                 closure_def_id: c.closure_def_id,
620                 substs: c.substs,
621                 nested: c.nested.into_iter().map(f).collect(),
622             }),
623             ImplSource::Generator(c) => ImplSource::Generator(ImplSourceGeneratorData {
624                 generator_def_id: c.generator_def_id,
625                 substs: c.substs,
626                 nested: c.nested.into_iter().map(f).collect(),
627             }),
628             ImplSource::FnPointer(p) => ImplSource::FnPointer(ImplSourceFnPointerData {
629                 fn_ty: p.fn_ty,
630                 nested: p.nested.into_iter().map(f).collect(),
631             }),
632             ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData) => {
633                 ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData)
634             }
635             ImplSource::Pointee(ImplSourcePointeeData) => {
636                 ImplSource::Pointee(ImplSourcePointeeData)
637             }
638             ImplSource::TraitAlias(d) => ImplSource::TraitAlias(ImplSourceTraitAliasData {
639                 alias_def_id: d.alias_def_id,
640                 substs: d.substs,
641                 nested: d.nested.into_iter().map(f).collect(),
642             }),
643             ImplSource::TraitUpcasting(d) => {
644                 ImplSource::TraitUpcasting(ImplSourceTraitUpcastingData {
645                     upcast_trait_ref: d.upcast_trait_ref,
646                     vtable_vptr_slot: d.vtable_vptr_slot,
647                     nested: d.nested.into_iter().map(f).collect(),
648                 })
649             }
650             ImplSource::ConstDrop(ImplSourceConstDropData) => {
651                 ImplSource::ConstDrop(ImplSourceConstDropData)
652             }
653         }
654     }
655 }
656
657 /// Identifies a particular impl in the source, along with a set of
658 /// substitutions from the impl's type/lifetime parameters. The
659 /// `nested` vector corresponds to the nested obligations attached to
660 /// the impl's type parameters.
661 ///
662 /// The type parameter `N` indicates the type used for "nested
663 /// obligations" that are required by the impl. During type-check, this
664 /// is `Obligation`, as one might expect. During codegen, however, this
665 /// is `()`, because codegen only requires a shallow resolution of an
666 /// impl, and nested obligations are satisfied later.
667 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
668 pub struct ImplSourceUserDefinedData<'tcx, N> {
669     pub impl_def_id: DefId,
670     pub substs: SubstsRef<'tcx>,
671     pub nested: Vec<N>,
672 }
673
674 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
675 pub struct ImplSourceGeneratorData<'tcx, N> {
676     pub generator_def_id: DefId,
677     pub substs: SubstsRef<'tcx>,
678     /// Nested obligations. This can be non-empty if the generator
679     /// signature contains associated types.
680     pub nested: Vec<N>,
681 }
682
683 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
684 pub struct ImplSourceClosureData<'tcx, N> {
685     pub closure_def_id: DefId,
686     pub substs: SubstsRef<'tcx>,
687     /// Nested obligations. This can be non-empty if the closure
688     /// signature contains associated types.
689     pub nested: Vec<N>,
690 }
691
692 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
693 pub struct ImplSourceAutoImplData<N> {
694     pub trait_def_id: DefId,
695     pub nested: Vec<N>,
696 }
697
698 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
699 pub struct ImplSourceTraitUpcastingData<'tcx, N> {
700     /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
701     pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
702
703     /// The vtable is formed by concatenating together the method lists of
704     /// the base object trait and all supertraits, pointers to supertrait vtable will
705     /// be provided when necessary; this is the position of `upcast_trait_ref`'s vtable
706     /// within that vtable.
707     pub vtable_vptr_slot: Option<usize>,
708
709     pub nested: Vec<N>,
710 }
711
712 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
713 pub struct ImplSourceBuiltinData<N> {
714     pub nested: Vec<N>,
715 }
716
717 #[derive(PartialEq, Eq, Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
718 pub struct ImplSourceObjectData<'tcx, N> {
719     /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
720     pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
721
722     /// The vtable is formed by concatenating together the method lists of
723     /// the base object trait and all supertraits, pointers to supertrait vtable will
724     /// be provided when necessary; this is the start of `upcast_trait_ref`'s methods
725     /// in that vtable.
726     pub vtable_base: usize,
727
728     pub nested: Vec<N>,
729 }
730
731 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
732 pub struct ImplSourceFnPointerData<'tcx, N> {
733     pub fn_ty: Ty<'tcx>,
734     pub nested: Vec<N>,
735 }
736
737 // FIXME(@lcnr): This should be  refactored and merged with other builtin vtables.
738 #[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
739 pub struct ImplSourceDiscriminantKindData;
740
741 #[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
742 pub struct ImplSourcePointeeData;
743
744 #[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
745 pub struct ImplSourceConstDropData;
746
747 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
748 pub struct ImplSourceTraitAliasData<'tcx, N> {
749     pub alias_def_id: DefId,
750     pub substs: SubstsRef<'tcx>,
751     pub nested: Vec<N>,
752 }
753
754 #[derive(Clone, Debug, PartialEq, Eq, Hash, HashStable, PartialOrd, Ord)]
755 pub enum ObjectSafetyViolation {
756     /// `Self: Sized` declared on the trait.
757     SizedSelf(SmallVec<[Span; 1]>),
758
759     /// Supertrait reference references `Self` an in illegal location
760     /// (e.g., `trait Foo : Bar<Self>`).
761     SupertraitSelf(SmallVec<[Span; 1]>),
762
763     /// Method has something illegal.
764     Method(Symbol, MethodViolationCode, Span),
765
766     /// Associated const.
767     AssocConst(Symbol, Span),
768
769     /// GAT
770     GAT(Symbol, Span),
771 }
772
773 impl ObjectSafetyViolation {
774     pub fn error_msg(&self) -> Cow<'static, str> {
775         match *self {
776             ObjectSafetyViolation::SizedSelf(_) => "it requires `Self: Sized`".into(),
777             ObjectSafetyViolation::SupertraitSelf(ref spans) => {
778                 if spans.iter().any(|sp| *sp != DUMMY_SP) {
779                     "it uses `Self` as a type parameter".into()
780                 } else {
781                     "it cannot use `Self` as a type parameter in a supertrait or `where`-clause"
782                         .into()
783                 }
784             }
785             ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod(_, _, _), _) => {
786                 format!("associated function `{}` has no `self` parameter", name).into()
787             }
788             ObjectSafetyViolation::Method(
789                 name,
790                 MethodViolationCode::ReferencesSelfInput(_),
791                 DUMMY_SP,
792             ) => format!("method `{}` references the `Self` type in its parameters", name).into(),
793             ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfInput(_), _) => {
794                 format!("method `{}` references the `Self` type in this parameter", name).into()
795             }
796             ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfOutput, _) => {
797                 format!("method `{}` references the `Self` type in its return type", name).into()
798             }
799             ObjectSafetyViolation::Method(
800                 name,
801                 MethodViolationCode::WhereClauseReferencesSelf,
802                 _,
803             ) => {
804                 format!("method `{}` references the `Self` type in its `where` clause", name).into()
805             }
806             ObjectSafetyViolation::Method(name, MethodViolationCode::Generic, _) => {
807                 format!("method `{}` has generic type parameters", name).into()
808             }
809             ObjectSafetyViolation::Method(name, MethodViolationCode::UndispatchableReceiver, _) => {
810                 format!("method `{}`'s `self` parameter cannot be dispatched on", name).into()
811             }
812             ObjectSafetyViolation::AssocConst(name, DUMMY_SP) => {
813                 format!("it contains associated `const` `{}`", name).into()
814             }
815             ObjectSafetyViolation::AssocConst(..) => "it contains this associated `const`".into(),
816             ObjectSafetyViolation::GAT(name, _) => {
817                 format!("it contains the generic associated type `{}`", name).into()
818             }
819         }
820     }
821
822     pub fn solution(&self, err: &mut DiagnosticBuilder<'_>) {
823         match *self {
824             ObjectSafetyViolation::SizedSelf(_) | ObjectSafetyViolation::SupertraitSelf(_) => {}
825             ObjectSafetyViolation::Method(
826                 name,
827                 MethodViolationCode::StaticMethod(sugg, self_span, has_args),
828                 _,
829             ) => {
830                 err.span_suggestion(
831                     self_span,
832                     &format!(
833                         "consider turning `{}` into a method by giving it a `&self` argument",
834                         name
835                     ),
836                     format!("&self{}", if has_args { ", " } else { "" }),
837                     Applicability::MaybeIncorrect,
838                 );
839                 match sugg {
840                     Some((sugg, span)) => {
841                         err.span_suggestion(
842                             span,
843                             &format!(
844                                 "alternatively, consider constraining `{}` so it does not apply to \
845                                  trait objects",
846                                 name
847                             ),
848                             sugg.to_string(),
849                             Applicability::MaybeIncorrect,
850                         );
851                     }
852                     None => {
853                         err.help(&format!(
854                             "consider turning `{}` into a method by giving it a `&self` \
855                              argument or constraining it so it does not apply to trait objects",
856                             name
857                         ));
858                     }
859                 }
860             }
861             ObjectSafetyViolation::Method(
862                 name,
863                 MethodViolationCode::UndispatchableReceiver,
864                 span,
865             ) => {
866                 err.span_suggestion(
867                     span,
868                     &format!(
869                         "consider changing method `{}`'s `self` parameter to be `&self`",
870                         name
871                     ),
872                     "&Self".to_string(),
873                     Applicability::MachineApplicable,
874                 );
875             }
876             ObjectSafetyViolation::AssocConst(name, _)
877             | ObjectSafetyViolation::GAT(name, _)
878             | ObjectSafetyViolation::Method(name, ..) => {
879                 err.help(&format!("consider moving `{}` to another trait", name));
880             }
881         }
882     }
883
884     pub fn spans(&self) -> SmallVec<[Span; 1]> {
885         // When `span` comes from a separate crate, it'll be `DUMMY_SP`. Treat it as `None` so
886         // diagnostics use a `note` instead of a `span_label`.
887         match self {
888             ObjectSafetyViolation::SupertraitSelf(spans)
889             | ObjectSafetyViolation::SizedSelf(spans) => spans.clone(),
890             ObjectSafetyViolation::AssocConst(_, span)
891             | ObjectSafetyViolation::GAT(_, span)
892             | ObjectSafetyViolation::Method(_, _, span)
893                 if *span != DUMMY_SP =>
894             {
895                 smallvec![*span]
896             }
897             _ => smallvec![],
898         }
899     }
900 }
901
902 /// Reasons a method might not be object-safe.
903 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable, PartialOrd, Ord)]
904 pub enum MethodViolationCode {
905     /// e.g., `fn foo()`
906     StaticMethod(Option<(&'static str, Span)>, Span, bool /* has args */),
907
908     /// e.g., `fn foo(&self, x: Self)`
909     ReferencesSelfInput(usize),
910
911     /// e.g., `fn foo(&self) -> Self`
912     ReferencesSelfOutput,
913
914     /// e.g., `fn foo(&self) where Self: Clone`
915     WhereClauseReferencesSelf,
916
917     /// e.g., `fn foo<A>()`
918     Generic,
919
920     /// the method's receiver (`self` argument) can't be dispatched on
921     UndispatchableReceiver,
922 }