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