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