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