]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/traits/mod.rs
Auto merge of #79342 - CDirkx:ipaddr-const, r=oli-obk
[rust.git] / compiler / rustc_middle / src / traits / mod.rs
1 //! Trait Resolution. See the [rustc dev guide] for more information on how this works.
2 //!
3 //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html
4
5 mod chalk;
6 pub mod query;
7 pub mod select;
8 pub mod specialization_graph;
9 mod structural_impls;
10
11 use crate::infer::canonical::Canonical;
12 use crate::mir::interpret::ErrorHandled;
13 use crate::ty::subst::SubstsRef;
14 use crate::ty::{self, AdtKind, Ty, TyCtxt};
15
16 use rustc_errors::{Applicability, DiagnosticBuilder};
17 use rustc_hir as hir;
18 use rustc_hir::def_id::DefId;
19 use rustc_hir::Constness;
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 use std::rc::Rc;
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<Rc<ObligationCauseData<'tcx>>>,
91 }
92
93 const DUMMY_OBLIGATION_CAUSE_DATA: ObligationCauseData<'static> =
94     ObligationCauseData { span: DUMMY_SP, body_id: hir::CRATE_HIR_ID, code: MiscObligation };
95
96 // Correctly format `ObligationCause::dummy`.
97 impl<'tcx> fmt::Debug for ObligationCause<'tcx> {
98     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99         ObligationCauseData::fmt(self, f)
100     }
101 }
102
103 impl Deref for ObligationCause<'tcx> {
104     type Target = ObligationCauseData<'tcx>;
105
106     #[inline(always)]
107     fn deref(&self) -> &Self::Target {
108         self.data.as_deref().unwrap_or(&DUMMY_OBLIGATION_CAUSE_DATA)
109     }
110 }
111
112 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
113 pub struct ObligationCauseData<'tcx> {
114     pub span: Span,
115
116     /// The ID of the fn body that triggered this obligation. This is
117     /// used for region obligations to determine the precise
118     /// environment in which the region obligation should be evaluated
119     /// (in particular, closures can add new assumptions). See the
120     /// field `region_obligations` of the `FulfillmentContext` for more
121     /// information.
122     pub body_id: hir::HirId,
123
124     pub code: ObligationCauseCode<'tcx>,
125 }
126
127 impl<'tcx> ObligationCause<'tcx> {
128     #[inline]
129     pub fn new(
130         span: Span,
131         body_id: hir::HirId,
132         code: ObligationCauseCode<'tcx>,
133     ) -> ObligationCause<'tcx> {
134         ObligationCause { data: Some(Rc::new(ObligationCauseData { span, body_id, code })) }
135     }
136
137     pub fn misc(span: Span, body_id: hir::HirId) -> ObligationCause<'tcx> {
138         ObligationCause::new(span, body_id, MiscObligation)
139     }
140
141     pub fn dummy_with_span(span: Span) -> ObligationCause<'tcx> {
142         ObligationCause::new(span, hir::CRATE_HIR_ID, MiscObligation)
143     }
144
145     #[inline(always)]
146     pub fn dummy() -> ObligationCause<'tcx> {
147         ObligationCause { data: None }
148     }
149
150     pub fn make_mut(&mut self) -> &mut ObligationCauseData<'tcx> {
151         Rc::make_mut(self.data.get_or_insert_with(|| Rc::new(DUMMY_OBLIGATION_CAUSE_DATA)))
152     }
153
154     pub fn span(&self, tcx: TyCtxt<'tcx>) -> Span {
155         match self.code {
156             ObligationCauseCode::CompareImplMethodObligation { .. }
157             | ObligationCauseCode::MainFunctionType
158             | ObligationCauseCode::StartFunctionType => {
159                 tcx.sess.source_map().guess_head_span(self.span)
160             }
161             ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
162                 arm_span,
163                 ..
164             }) => arm_span,
165             _ => self.span,
166         }
167     }
168 }
169
170 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
171 pub struct UnifyReceiverContext<'tcx> {
172     pub assoc_item: ty::AssocItem,
173     pub param_env: ty::ParamEnv<'tcx>,
174     pub substs: SubstsRef<'tcx>,
175 }
176
177 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
178 pub enum ObligationCauseCode<'tcx> {
179     /// Not well classified or should be obvious from the span.
180     MiscObligation,
181
182     /// A slice or array is WF only if `T: Sized`.
183     SliceOrArrayElem,
184
185     /// A tuple is WF only if its middle elements are `Sized`.
186     TupleElem,
187
188     /// This is the trait reference from the given projection.
189     ProjectionWf(ty::ProjectionTy<'tcx>),
190
191     /// In an impl of trait `X` for type `Y`, type `Y` must
192     /// also implement all supertraits of `X`.
193     ItemObligation(DefId),
194
195     /// Like `ItemObligation`, but with extra detail on the source of the obligation.
196     BindingObligation(DefId, Span),
197
198     /// A type like `&'a T` is WF only if `T: 'a`.
199     ReferenceOutlivesReferent(Ty<'tcx>),
200
201     /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
202     ObjectTypeBound(Ty<'tcx>, ty::Region<'tcx>),
203
204     /// Obligation incurred due to an object cast.
205     ObjectCastObligation(/* Object type */ Ty<'tcx>),
206
207     /// Obligation incurred due to a coercion.
208     Coercion {
209         source: Ty<'tcx>,
210         target: Ty<'tcx>,
211     },
212
213     /// Various cases where expressions must be `Sized` / `Copy` / etc.
214     /// `L = X` implies that `L` is `Sized`.
215     AssignmentLhsSized,
216     /// `(x1, .., xn)` must be `Sized`.
217     TupleInitializerSized,
218     /// `S { ... }` must be `Sized`.
219     StructInitializerSized,
220     /// Type of each variable must be `Sized`.
221     VariableType(hir::HirId),
222     /// Argument type must be `Sized`.
223     SizedArgumentType(Option<Span>),
224     /// Return type must be `Sized`.
225     SizedReturnType,
226     /// Yield type must be `Sized`.
227     SizedYieldType,
228     /// Inline asm operand type must be `Sized`.
229     InlineAsmSized,
230     /// `[T, ..n]` implies that `T` must be `Copy`.
231     /// If `true`, suggest `const_in_array_repeat_expressions` feature flag.
232     RepeatVec(bool),
233
234     /// Types of fields (other than the last, except for packed structs) in a struct must be sized.
235     FieldSized {
236         adt_kind: AdtKind,
237         span: Span,
238         last: bool,
239     },
240
241     /// Constant expressions must be sized.
242     ConstSized,
243
244     /// `static` items must have `Sync` type.
245     SharedStatic,
246
247     BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
248
249     ImplDerivedObligation(DerivedObligationCause<'tcx>),
250
251     DerivedObligation(DerivedObligationCause<'tcx>),
252
253     /// Error derived when matching traits/impls; see ObligationCause for more details
254     CompareImplConstObligation,
255
256     /// Error derived when matching traits/impls; see ObligationCause for more details
257     CompareImplMethodObligation {
258         item_name: Symbol,
259         impl_item_def_id: DefId,
260         trait_item_def_id: DefId,
261     },
262
263     /// Error derived when matching traits/impls; see ObligationCause for more details
264     CompareImplTypeObligation {
265         item_name: Symbol,
266         impl_item_def_id: DefId,
267         trait_item_def_id: DefId,
268     },
269
270     /// Checking that this expression can be assigned where it needs to be
271     // FIXME(eddyb) #11161 is the original Expr required?
272     ExprAssignable,
273
274     /// Computing common supertype in the arms of a match expression
275     MatchExpressionArm(Box<MatchExpressionArmCause<'tcx>>),
276
277     /// Type error arising from type checking a pattern against an expected type.
278     Pattern {
279         /// The span of the scrutinee or type expression which caused the `root_ty` type.
280         span: Option<Span>,
281         /// The root expected type induced by a scrutinee or type expression.
282         root_ty: Ty<'tcx>,
283         /// Whether the `Span` came from an expression or a type expression.
284         origin_expr: bool,
285     },
286
287     /// Constants in patterns must have `Structural` type.
288     ConstPatternStructural,
289
290     /// Computing common supertype in an if expression
291     IfExpression(Box<IfExpressionCause>),
292
293     /// Computing common supertype of an if expression with no else counter-part
294     IfExpressionWithNoElse,
295
296     /// `main` has wrong type
297     MainFunctionType,
298
299     /// `start` has wrong type
300     StartFunctionType,
301
302     /// Intrinsic has wrong type
303     IntrinsicType,
304
305     /// Method receiver
306     MethodReceiver,
307
308     UnifyReceiver(Box<UnifyReceiverContext<'tcx>>),
309
310     /// `return` with no expression
311     ReturnNoExpression,
312
313     /// `return` with an expression
314     ReturnValue(hir::HirId),
315
316     /// Return type of this function
317     ReturnType,
318
319     /// Block implicit return
320     BlockTailExpression(hir::HirId),
321
322     /// #[feature(trivial_bounds)] is not enabled
323     TrivialBound,
324 }
325
326 impl ObligationCauseCode<'_> {
327     // Return the base obligation, ignoring derived obligations.
328     pub fn peel_derives(&self) -> &Self {
329         let mut base_cause = self;
330         while let BuiltinDerivedObligation(cause)
331         | ImplDerivedObligation(cause)
332         | DerivedObligation(cause) = base_cause
333         {
334             base_cause = &cause.parent_code;
335         }
336         base_cause
337     }
338 }
339
340 // `ObligationCauseCode` is used a lot. Make sure it doesn't unintentionally get bigger.
341 #[cfg(target_arch = "x86_64")]
342 static_assert_size!(ObligationCauseCode<'_>, 32);
343
344 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
345 pub enum StatementAsExpression {
346     CorrectType,
347     NeedsBoxing,
348 }
349
350 impl<'tcx> ty::Lift<'tcx> for StatementAsExpression {
351     type Lifted = StatementAsExpression;
352     fn lift_to_tcx(self, _tcx: TyCtxt<'tcx>) -> Option<StatementAsExpression> {
353         Some(self)
354     }
355 }
356
357 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
358 pub struct MatchExpressionArmCause<'tcx> {
359     pub arm_span: Span,
360     pub scrut_span: Span,
361     pub semi_span: Option<(Span, StatementAsExpression)>,
362     pub source: hir::MatchSource,
363     pub prior_arms: Vec<Span>,
364     pub last_ty: Ty<'tcx>,
365     pub scrut_hir_id: hir::HirId,
366     pub opt_suggest_box_span: Option<Span>,
367 }
368
369 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
370 pub struct IfExpressionCause {
371     pub then: Span,
372     pub else_sp: Span,
373     pub outer: Option<Span>,
374     pub semicolon: Option<(Span, StatementAsExpression)>,
375     pub opt_suggest_box_span: Option<Span>,
376 }
377
378 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
379 pub struct DerivedObligationCause<'tcx> {
380     /// The trait reference of the parent obligation that led to the
381     /// current obligation. Note that only trait obligations lead to
382     /// derived obligations, so we just store the trait reference here
383     /// directly.
384     pub parent_trait_ref: ty::PolyTraitRef<'tcx>,
385
386     /// The parent trait had this cause.
387     pub parent_code: Rc<ObligationCauseCode<'tcx>>,
388 }
389
390 #[derive(Clone, Debug, TypeFoldable, Lift)]
391 pub enum SelectionError<'tcx> {
392     Unimplemented,
393     OutputTypeParameterMismatch(
394         ty::PolyTraitRef<'tcx>,
395         ty::PolyTraitRef<'tcx>,
396         ty::error::TypeError<'tcx>,
397     ),
398     TraitNotObjectSafe(DefId),
399     ConstEvalFailure(ErrorHandled),
400     Overflow,
401 }
402
403 /// When performing resolution, it is typically the case that there
404 /// can be one of three outcomes:
405 ///
406 /// - `Ok(Some(r))`: success occurred with result `r`
407 /// - `Ok(None)`: could not definitely determine anything, usually due
408 ///   to inconclusive type inference.
409 /// - `Err(e)`: error `e` occurred
410 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
411
412 /// Given the successful resolution of an obligation, the `ImplSource`
413 /// indicates where the impl comes from.
414 ///
415 /// For example, the obligation may be satisfied by a specific impl (case A),
416 /// or it may be relative to some bound that is in scope (case B).
417 ///
418 /// ```
419 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
420 /// impl<T:Clone> Clone<T> for Box<T> { ... }    // Impl_2
421 /// impl Clone for i32 { ... }                   // Impl_3
422 ///
423 /// fn foo<T: Clone>(concrete: Option<Box<i32>>, param: T, mixed: Option<T>) {
424 ///     // Case A: Vtable points at a specific impl. Only possible when
425 ///     // type is concretely known. If the impl itself has bounded
426 ///     // type parameters, Vtable will carry resolutions for those as well:
427 ///     concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
428 ///
429 ///     // Case A: ImplSource points at a specific impl. Only possible when
430 ///     // type is concretely known. If the impl itself has bounded
431 ///     // type parameters, ImplSource will carry resolutions for those as well:
432 ///     concrete.clone(); // ImplSource(Impl_1, [ImplSource(Impl_2, [ImplSource(Impl_3)])])
433 ///
434 ///     // Case B: ImplSource must be provided by caller. This applies when
435 ///     // type is a type parameter.
436 ///     param.clone();    // ImplSource::Param
437 ///
438 ///     // Case C: A mix of cases A and B.
439 ///     mixed.clone();    // ImplSource(Impl_1, [ImplSource::Param])
440 /// }
441 /// ```
442 ///
443 /// ### The type parameter `N`
444 ///
445 /// See explanation on `ImplSourceUserDefinedData`.
446 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
447 pub enum ImplSource<'tcx, N> {
448     /// ImplSource identifying a particular impl.
449     UserDefined(ImplSourceUserDefinedData<'tcx, N>),
450
451     /// ImplSource for auto trait implementations.
452     /// This carries the information and nested obligations with regards
453     /// to an auto implementation for a trait `Trait`. The nested obligations
454     /// ensure the trait implementation holds for all the constituent types.
455     AutoImpl(ImplSourceAutoImplData<N>),
456
457     /// Successful resolution to an obligation provided by the caller
458     /// for some type parameter. The `Vec<N>` represents the
459     /// obligations incurred from normalizing the where-clause (if
460     /// any).
461     Param(Vec<N>, Constness),
462
463     /// Virtual calls through an object.
464     Object(ImplSourceObjectData<'tcx, N>),
465
466     /// Successful resolution for a builtin trait.
467     Builtin(ImplSourceBuiltinData<N>),
468
469     /// ImplSource automatically generated for a closure. The `DefId` is the ID
470     /// of the closure expression. This is a `ImplSource::UserDefined` in spirit, but the
471     /// impl is generated by the compiler and does not appear in the source.
472     Closure(ImplSourceClosureData<'tcx, N>),
473
474     /// Same as above, but for a function pointer type with the given signature.
475     FnPointer(ImplSourceFnPointerData<'tcx, N>),
476
477     /// ImplSource for a builtin `DeterminantKind` trait implementation.
478     DiscriminantKind(ImplSourceDiscriminantKindData),
479
480     /// ImplSource automatically generated for a generator.
481     Generator(ImplSourceGeneratorData<'tcx, N>),
482
483     /// ImplSource for a trait alias.
484     TraitAlias(ImplSourceTraitAliasData<'tcx, N>),
485 }
486
487 impl<'tcx, N> ImplSource<'tcx, N> {
488     pub fn nested_obligations(self) -> Vec<N> {
489         match self {
490             ImplSource::UserDefined(i) => i.nested,
491             ImplSource::Param(n, _) => n,
492             ImplSource::Builtin(i) => i.nested,
493             ImplSource::AutoImpl(d) => d.nested,
494             ImplSource::Closure(c) => c.nested,
495             ImplSource::Generator(c) => c.nested,
496             ImplSource::Object(d) => d.nested,
497             ImplSource::FnPointer(d) => d.nested,
498             ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData) => Vec::new(),
499             ImplSource::TraitAlias(d) => d.nested,
500         }
501     }
502
503     pub fn borrow_nested_obligations(&self) -> &[N] {
504         match &self {
505             ImplSource::UserDefined(i) => &i.nested[..],
506             ImplSource::Param(n, _) => &n[..],
507             ImplSource::Builtin(i) => &i.nested[..],
508             ImplSource::AutoImpl(d) => &d.nested[..],
509             ImplSource::Closure(c) => &c.nested[..],
510             ImplSource::Generator(c) => &c.nested[..],
511             ImplSource::Object(d) => &d.nested[..],
512             ImplSource::FnPointer(d) => &d.nested[..],
513             ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData) => &[],
514             ImplSource::TraitAlias(d) => &d.nested[..],
515         }
516     }
517
518     pub fn map<M, F>(self, f: F) -> ImplSource<'tcx, M>
519     where
520         F: FnMut(N) -> M,
521     {
522         match self {
523             ImplSource::UserDefined(i) => ImplSource::UserDefined(ImplSourceUserDefinedData {
524                 impl_def_id: i.impl_def_id,
525                 substs: i.substs,
526                 nested: i.nested.into_iter().map(f).collect(),
527             }),
528             ImplSource::Param(n, ct) => ImplSource::Param(n.into_iter().map(f).collect(), ct),
529             ImplSource::Builtin(i) => ImplSource::Builtin(ImplSourceBuiltinData {
530                 nested: i.nested.into_iter().map(f).collect(),
531             }),
532             ImplSource::Object(o) => ImplSource::Object(ImplSourceObjectData {
533                 upcast_trait_ref: o.upcast_trait_ref,
534                 vtable_base: o.vtable_base,
535                 nested: o.nested.into_iter().map(f).collect(),
536             }),
537             ImplSource::AutoImpl(d) => ImplSource::AutoImpl(ImplSourceAutoImplData {
538                 trait_def_id: d.trait_def_id,
539                 nested: d.nested.into_iter().map(f).collect(),
540             }),
541             ImplSource::Closure(c) => ImplSource::Closure(ImplSourceClosureData {
542                 closure_def_id: c.closure_def_id,
543                 substs: c.substs,
544                 nested: c.nested.into_iter().map(f).collect(),
545             }),
546             ImplSource::Generator(c) => ImplSource::Generator(ImplSourceGeneratorData {
547                 generator_def_id: c.generator_def_id,
548                 substs: c.substs,
549                 nested: c.nested.into_iter().map(f).collect(),
550             }),
551             ImplSource::FnPointer(p) => ImplSource::FnPointer(ImplSourceFnPointerData {
552                 fn_ty: p.fn_ty,
553                 nested: p.nested.into_iter().map(f).collect(),
554             }),
555             ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData) => {
556                 ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData)
557             }
558             ImplSource::TraitAlias(d) => ImplSource::TraitAlias(ImplSourceTraitAliasData {
559                 alias_def_id: d.alias_def_id,
560                 substs: d.substs,
561                 nested: d.nested.into_iter().map(f).collect(),
562             }),
563         }
564     }
565 }
566
567 /// Identifies a particular impl in the source, along with a set of
568 /// substitutions from the impl's type/lifetime parameters. The
569 /// `nested` vector corresponds to the nested obligations attached to
570 /// the impl's type parameters.
571 ///
572 /// The type parameter `N` indicates the type used for "nested
573 /// obligations" that are required by the impl. During type-check, this
574 /// is `Obligation`, as one might expect. During codegen, however, this
575 /// is `()`, because codegen only requires a shallow resolution of an
576 /// impl, and nested obligations are satisfied later.
577 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
578 pub struct ImplSourceUserDefinedData<'tcx, N> {
579     pub impl_def_id: DefId,
580     pub substs: SubstsRef<'tcx>,
581     pub nested: Vec<N>,
582 }
583
584 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
585 pub struct ImplSourceGeneratorData<'tcx, N> {
586     pub generator_def_id: DefId,
587     pub substs: SubstsRef<'tcx>,
588     /// Nested obligations. This can be non-empty if the generator
589     /// signature contains associated types.
590     pub nested: Vec<N>,
591 }
592
593 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
594 pub struct ImplSourceClosureData<'tcx, N> {
595     pub closure_def_id: DefId,
596     pub substs: SubstsRef<'tcx>,
597     /// Nested obligations. This can be non-empty if the closure
598     /// signature contains associated types.
599     pub nested: Vec<N>,
600 }
601
602 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
603 pub struct ImplSourceAutoImplData<N> {
604     pub trait_def_id: DefId,
605     pub nested: Vec<N>,
606 }
607
608 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
609 pub struct ImplSourceBuiltinData<N> {
610     pub nested: Vec<N>,
611 }
612
613 #[derive(PartialEq, Eq, Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
614 pub struct ImplSourceObjectData<'tcx, N> {
615     /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
616     pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
617
618     /// The vtable is formed by concatenating together the method lists of
619     /// the base object trait and all supertraits; this is the start of
620     /// `upcast_trait_ref`'s methods in that vtable.
621     pub vtable_base: usize,
622
623     pub nested: Vec<N>,
624 }
625
626 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
627 pub struct ImplSourceFnPointerData<'tcx, N> {
628     pub fn_ty: Ty<'tcx>,
629     pub nested: Vec<N>,
630 }
631
632 // FIXME(@lcnr): This should be  refactored and merged with other builtin vtables.
633 #[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
634 pub struct ImplSourceDiscriminantKindData;
635
636 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
637 pub struct ImplSourceTraitAliasData<'tcx, N> {
638     pub alias_def_id: DefId,
639     pub substs: SubstsRef<'tcx>,
640     pub nested: Vec<N>,
641 }
642
643 #[derive(Clone, Debug, PartialEq, Eq, Hash, HashStable)]
644 pub enum ObjectSafetyViolation {
645     /// `Self: Sized` declared on the trait.
646     SizedSelf(SmallVec<[Span; 1]>),
647
648     /// Supertrait reference references `Self` an in illegal location
649     /// (e.g., `trait Foo : Bar<Self>`).
650     SupertraitSelf(SmallVec<[Span; 1]>),
651
652     /// Method has something illegal.
653     Method(Symbol, MethodViolationCode, Span),
654
655     /// Associated const.
656     AssocConst(Symbol, Span),
657 }
658
659 impl ObjectSafetyViolation {
660     pub fn error_msg(&self) -> Cow<'static, str> {
661         match *self {
662             ObjectSafetyViolation::SizedSelf(_) => "it requires `Self: Sized`".into(),
663             ObjectSafetyViolation::SupertraitSelf(ref spans) => {
664                 if spans.iter().any(|sp| *sp != DUMMY_SP) {
665                     "it uses `Self` as a type parameter".into()
666                 } else {
667                     "it cannot use `Self` as a type parameter in a supertrait or `where`-clause"
668                         .into()
669                 }
670             }
671             ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod(_, _, _), _) => {
672                 format!("associated function `{}` has no `self` parameter", name).into()
673             }
674             ObjectSafetyViolation::Method(
675                 name,
676                 MethodViolationCode::ReferencesSelfInput(_),
677                 DUMMY_SP,
678             ) => format!("method `{}` references the `Self` type in its parameters", name).into(),
679             ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfInput(_), _) => {
680                 format!("method `{}` references the `Self` type in this parameter", name).into()
681             }
682             ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfOutput, _) => {
683                 format!("method `{}` references the `Self` type in its return type", name).into()
684             }
685             ObjectSafetyViolation::Method(
686                 name,
687                 MethodViolationCode::WhereClauseReferencesSelf,
688                 _,
689             ) => {
690                 format!("method `{}` references the `Self` type in its `where` clause", name).into()
691             }
692             ObjectSafetyViolation::Method(name, MethodViolationCode::Generic, _) => {
693                 format!("method `{}` has generic type parameters", name).into()
694             }
695             ObjectSafetyViolation::Method(name, MethodViolationCode::UndispatchableReceiver, _) => {
696                 format!("method `{}`'s `self` parameter cannot be dispatched on", name).into()
697             }
698             ObjectSafetyViolation::AssocConst(name, DUMMY_SP) => {
699                 format!("it contains associated `const` `{}`", name).into()
700             }
701             ObjectSafetyViolation::AssocConst(..) => "it contains this associated `const`".into(),
702         }
703     }
704
705     pub fn solution(&self, err: &mut DiagnosticBuilder<'_>) {
706         match *self {
707             ObjectSafetyViolation::SizedSelf(_) | ObjectSafetyViolation::SupertraitSelf(_) => {}
708             ObjectSafetyViolation::Method(
709                 name,
710                 MethodViolationCode::StaticMethod(sugg, self_span, has_args),
711                 _,
712             ) => {
713                 err.span_suggestion(
714                     self_span,
715                     &format!(
716                         "consider turning `{}` into a method by giving it a `&self` argument",
717                         name
718                     ),
719                     format!("&self{}", if has_args { ", " } else { "" }),
720                     Applicability::MaybeIncorrect,
721                 );
722                 match sugg {
723                     Some((sugg, span)) => {
724                         err.span_suggestion(
725                             span,
726                             &format!(
727                                 "alternatively, consider constraining `{}` so it does not apply to \
728                                  trait objects",
729                                 name
730                             ),
731                             sugg.to_string(),
732                             Applicability::MaybeIncorrect,
733                         );
734                     }
735                     None => {
736                         err.help(&format!(
737                             "consider turning `{}` into a method by giving it a `&self` \
738                              argument or constraining it so it does not apply to trait objects",
739                             name
740                         ));
741                     }
742                 }
743             }
744             ObjectSafetyViolation::Method(
745                 name,
746                 MethodViolationCode::UndispatchableReceiver,
747                 span,
748             ) => {
749                 err.span_suggestion(
750                     span,
751                     &format!(
752                         "consider changing method `{}`'s `self` parameter to be `&self`",
753                         name
754                     ),
755                     "&Self".to_string(),
756                     Applicability::MachineApplicable,
757                 );
758             }
759             ObjectSafetyViolation::AssocConst(name, _)
760             | ObjectSafetyViolation::Method(name, ..) => {
761                 err.help(&format!("consider moving `{}` to another trait", name));
762             }
763         }
764     }
765
766     pub fn spans(&self) -> SmallVec<[Span; 1]> {
767         // When `span` comes from a separate crate, it'll be `DUMMY_SP`. Treat it as `None` so
768         // diagnostics use a `note` instead of a `span_label`.
769         match self {
770             ObjectSafetyViolation::SupertraitSelf(spans)
771             | ObjectSafetyViolation::SizedSelf(spans) => spans.clone(),
772             ObjectSafetyViolation::AssocConst(_, span)
773             | ObjectSafetyViolation::Method(_, _, span)
774                 if *span != DUMMY_SP =>
775             {
776                 smallvec![*span]
777             }
778             _ => smallvec![],
779         }
780     }
781 }
782
783 /// Reasons a method might not be object-safe.
784 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
785 pub enum MethodViolationCode {
786     /// e.g., `fn foo()`
787     StaticMethod(Option<(&'static str, Span)>, Span, bool /* has args */),
788
789     /// e.g., `fn foo(&self, x: Self)`
790     ReferencesSelfInput(usize),
791
792     /// e.g., `fn foo(&self) -> Self`
793     ReferencesSelfOutput,
794
795     /// e.g., `fn foo(&self) where Self: Clone`
796     WhereClauseReferencesSelf,
797
798     /// e.g., `fn foo<A>()`
799     Generic,
800
801     /// the method's receiver (`self` argument) can't be dispatched on
802     UndispatchableReceiver,
803 }