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