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