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