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