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