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