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