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