]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_middle/src/traits/mod.rs
New upstream version 1.49.0~beta.4+dfsg1
[rustc.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
11 use crate::infer::canonical::Canonical;
12 use crate::mir::interpret::ErrorHandled;
13 use crate::ty::subst::SubstsRef;
14 use crate::ty::{self, AdtKind, Ty, TyCtxt};
15
16 use rustc_errors::{Applicability, DiagnosticBuilder};
17 use rustc_hir as hir;
18 use rustc_hir::def_id::DefId;
19 use rustc_span::symbol::Symbol;
20 use rustc_span::{Span, DUMMY_SP};
21 use smallvec::SmallVec;
22
23 use std::borrow::Cow;
24 use std::fmt;
25 use std::ops::Deref;
26 use std::rc::Rc;
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 OIBITS 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 /// As the happy path does not care about this struct, storing this on the heap
82 /// ends up increasing performance.
83 ///
84 /// We do not want to intern this as there are a lot of obligation causes which
85 /// only live for a short period of time.
86 #[derive(Clone, PartialEq, Eq, Hash, Lift)]
87 pub struct ObligationCause<'tcx> {
88 /// `None` for `ObligationCause::dummy`, `Some` otherwise.
89 data: Option<Rc<ObligationCauseData<'tcx>>>,
90 }
91
92 const DUMMY_OBLIGATION_CAUSE_DATA: ObligationCauseData<'static> =
93 ObligationCauseData { span: DUMMY_SP, body_id: hir::CRATE_HIR_ID, code: MiscObligation };
94
95 // Correctly format `ObligationCause::dummy`.
96 impl<'tcx> fmt::Debug for ObligationCause<'tcx> {
97 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98 ObligationCauseData::fmt(self, f)
99 }
100 }
101
102 impl Deref for ObligationCause<'tcx> {
103 type Target = ObligationCauseData<'tcx>;
104
105 #[inline(always)]
106 fn deref(&self) -> &Self::Target {
107 self.data.as_deref().unwrap_or(&DUMMY_OBLIGATION_CAUSE_DATA)
108 }
109 }
110
111 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
112 pub struct ObligationCauseData<'tcx> {
113 pub span: Span,
114
115 /// The ID of the fn body that triggered this obligation. This is
116 /// used for region obligations to determine the precise
117 /// environment in which the region obligation should be evaluated
118 /// (in particular, closures can add new assumptions). See the
119 /// field `region_obligations` of the `FulfillmentContext` for more
120 /// information.
121 pub body_id: hir::HirId,
122
123 pub code: ObligationCauseCode<'tcx>,
124 }
125
126 impl<'tcx> ObligationCause<'tcx> {
127 #[inline]
128 pub fn new(
129 span: Span,
130 body_id: hir::HirId,
131 code: ObligationCauseCode<'tcx>,
132 ) -> ObligationCause<'tcx> {
133 ObligationCause { data: Some(Rc::new(ObligationCauseData { span, body_id, code })) }
134 }
135
136 pub fn misc(span: Span, body_id: hir::HirId) -> ObligationCause<'tcx> {
137 ObligationCause::new(span, body_id, MiscObligation)
138 }
139
140 pub fn dummy_with_span(span: Span) -> ObligationCause<'tcx> {
141 ObligationCause::new(span, hir::CRATE_HIR_ID, MiscObligation)
142 }
143
144 #[inline(always)]
145 pub fn dummy() -> ObligationCause<'tcx> {
146 ObligationCause { data: None }
147 }
148
149 pub fn make_mut(&mut self) -> &mut ObligationCauseData<'tcx> {
150 Rc::make_mut(self.data.get_or_insert_with(|| Rc::new(DUMMY_OBLIGATION_CAUSE_DATA)))
151 }
152
153 pub fn span(&self, tcx: TyCtxt<'tcx>) -> Span {
154 match self.code {
155 ObligationCauseCode::CompareImplMethodObligation { .. }
156 | ObligationCauseCode::MainFunctionType
157 | ObligationCauseCode::StartFunctionType => {
158 tcx.sess.source_map().guess_head_span(self.span)
159 }
160 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
161 arm_span,
162 ..
163 }) => arm_span,
164 _ => self.span,
165 }
166 }
167 }
168
169 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
170 pub struct UnifyReceiverContext<'tcx> {
171 pub assoc_item: ty::AssocItem,
172 pub param_env: ty::ParamEnv<'tcx>,
173 pub substs: SubstsRef<'tcx>,
174 }
175
176 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
177 pub enum ObligationCauseCode<'tcx> {
178 /// Not well classified or should be obvious from the span.
179 MiscObligation,
180
181 /// A slice or array is WF only if `T: Sized`.
182 SliceOrArrayElem,
183
184 /// A tuple is WF only if its middle elements are `Sized`.
185 TupleElem,
186
187 /// This is the trait reference from the given projection.
188 ProjectionWf(ty::ProjectionTy<'tcx>),
189
190 /// In an impl of trait `X` for type `Y`, type `Y` must
191 /// also implement all supertraits of `X`.
192 ItemObligation(DefId),
193
194 /// Like `ItemObligation`, but with extra detail on the source of the obligation.
195 BindingObligation(DefId, Span),
196
197 /// A type like `&'a T` is WF only if `T: 'a`.
198 ReferenceOutlivesReferent(Ty<'tcx>),
199
200 /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
201 ObjectTypeBound(Ty<'tcx>, ty::Region<'tcx>),
202
203 /// Obligation incurred due to an object cast.
204 ObjectCastObligation(/* Object type */ Ty<'tcx>),
205
206 /// Obligation incurred due to a coercion.
207 Coercion {
208 source: Ty<'tcx>,
209 target: Ty<'tcx>,
210 },
211
212 /// Various cases where expressions must be `Sized` / `Copy` / etc.
213 /// `L = X` implies that `L` is `Sized`.
214 AssignmentLhsSized,
215 /// `(x1, .., xn)` must be `Sized`.
216 TupleInitializerSized,
217 /// `S { ... }` must be `Sized`.
218 StructInitializerSized,
219 /// Type of each variable must be `Sized`.
220 VariableType(hir::HirId),
221 /// Argument type must be `Sized`.
222 SizedArgumentType(Option<Span>),
223 /// Return type must be `Sized`.
224 SizedReturnType,
225 /// Yield type must be `Sized`.
226 SizedYieldType,
227 /// Inline asm operand type must be `Sized`.
228 InlineAsmSized,
229 /// `[T, ..n]` implies that `T` must be `Copy`.
230 /// If `true`, suggest `const_in_array_repeat_expressions` feature flag.
231 RepeatVec(bool),
232
233 /// Types of fields (other than the last, except for packed structs) in a struct must be sized.
234 FieldSized {
235 adt_kind: AdtKind,
236 span: Span,
237 last: bool,
238 },
239
240 /// Constant expressions must be sized.
241 ConstSized,
242
243 /// `static` items must have `Sync` type.
244 SharedStatic,
245
246 BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
247
248 ImplDerivedObligation(DerivedObligationCause<'tcx>),
249
250 DerivedObligation(DerivedObligationCause<'tcx>),
251
252 /// Error derived when matching traits/impls; see ObligationCause for more details
253 CompareImplConstObligation,
254
255 /// Error derived when matching traits/impls; see ObligationCause for more details
256 CompareImplMethodObligation {
257 item_name: Symbol,
258 impl_item_def_id: DefId,
259 trait_item_def_id: DefId,
260 },
261
262 /// Error derived when matching traits/impls; see ObligationCause for more details
263 CompareImplTypeObligation {
264 item_name: Symbol,
265 impl_item_def_id: DefId,
266 trait_item_def_id: DefId,
267 },
268
269 /// Checking that this expression can be assigned where it needs to be
270 // FIXME(eddyb) #11161 is the original Expr required?
271 ExprAssignable,
272
273 /// Computing common supertype in the arms of a match expression
274 MatchExpressionArm(Box<MatchExpressionArmCause<'tcx>>),
275
276 /// Type error arising from type checking a pattern against an expected type.
277 Pattern {
278 /// The span of the scrutinee or type expression which caused the `root_ty` type.
279 span: Option<Span>,
280 /// The root expected type induced by a scrutinee or type expression.
281 root_ty: Ty<'tcx>,
282 /// Whether the `Span` came from an expression or a type expression.
283 origin_expr: bool,
284 },
285
286 /// Constants in patterns must have `Structural` type.
287 ConstPatternStructural,
288
289 /// Computing common supertype in an if expression
290 IfExpression(Box<IfExpressionCause>),
291
292 /// Computing common supertype of an if expression with no else counter-part
293 IfExpressionWithNoElse,
294
295 /// `main` has wrong type
296 MainFunctionType,
297
298 /// `start` has wrong type
299 StartFunctionType,
300
301 /// Intrinsic has wrong type
302 IntrinsicType,
303
304 /// Method receiver
305 MethodReceiver,
306
307 UnifyReceiver(Box<UnifyReceiverContext<'tcx>>),
308
309 /// `return` with no expression
310 ReturnNoExpression,
311
312 /// `return` with an expression
313 ReturnValue(hir::HirId),
314
315 /// Return type of this function
316 ReturnType,
317
318 /// Block implicit return
319 BlockTailExpression(hir::HirId),
320
321 /// #[feature(trivial_bounds)] is not enabled
322 TrivialBound,
323 }
324
325 impl ObligationCauseCode<'_> {
326 // Return the base obligation, ignoring derived obligations.
327 pub fn peel_derives(&self) -> &Self {
328 let mut base_cause = self;
329 while let BuiltinDerivedObligation(cause)
330 | ImplDerivedObligation(cause)
331 | DerivedObligation(cause) = base_cause
332 {
333 base_cause = &cause.parent_code;
334 }
335 base_cause
336 }
337 }
338
339 // `ObligationCauseCode` is used a lot. Make sure it doesn't unintentionally get bigger.
340 #[cfg(target_arch = "x86_64")]
341 static_assert_size!(ObligationCauseCode<'_>, 32);
342
343 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
344 pub enum StatementAsExpression {
345 CorrectType,
346 NeedsBoxing,
347 }
348
349 impl<'tcx> ty::Lift<'tcx> for StatementAsExpression {
350 type Lifted = StatementAsExpression;
351 fn lift_to_tcx(self, _tcx: TyCtxt<'tcx>) -> Option<StatementAsExpression> {
352 Some(self)
353 }
354 }
355
356 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
357 pub struct MatchExpressionArmCause<'tcx> {
358 pub arm_span: Span,
359 pub scrut_span: Span,
360 pub semi_span: Option<(Span, StatementAsExpression)>,
361 pub source: hir::MatchSource,
362 pub prior_arms: Vec<Span>,
363 pub last_ty: Ty<'tcx>,
364 pub scrut_hir_id: hir::HirId,
365 pub opt_suggest_box_span: Option<Span>,
366 }
367
368 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
369 pub struct IfExpressionCause {
370 pub then: Span,
371 pub else_sp: Span,
372 pub outer: Option<Span>,
373 pub semicolon: Option<(Span, StatementAsExpression)>,
374 pub opt_suggest_box_span: Option<Span>,
375 }
376
377 #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
378 pub struct DerivedObligationCause<'tcx> {
379 /// The trait reference of the parent obligation that led to the
380 /// current obligation. Note that only trait obligations lead to
381 /// derived obligations, so we just store the trait reference here
382 /// directly.
383 pub parent_trait_ref: ty::PolyTraitRef<'tcx>,
384
385 /// The parent trait had this cause.
386 pub parent_code: Rc<ObligationCauseCode<'tcx>>,
387 }
388
389 #[derive(Clone, Debug, TypeFoldable, Lift)]
390 pub enum SelectionError<'tcx> {
391 Unimplemented,
392 OutputTypeParameterMismatch(
393 ty::PolyTraitRef<'tcx>,
394 ty::PolyTraitRef<'tcx>,
395 ty::error::TypeError<'tcx>,
396 ),
397 TraitNotObjectSafe(DefId),
398 ConstEvalFailure(ErrorHandled),
399 Overflow,
400 }
401
402 /// When performing resolution, it is typically the case that there
403 /// can be one of three outcomes:
404 ///
405 /// - `Ok(Some(r))`: success occurred with result `r`
406 /// - `Ok(None)`: could not definitely determine anything, usually due
407 /// to inconclusive type inference.
408 /// - `Err(e)`: error `e` occurred
409 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
410
411 /// Given the successful resolution of an obligation, the `ImplSource`
412 /// indicates where the impl comes from.
413 ///
414 /// For example, the obligation may be satisfied by a specific impl (case A),
415 /// or it may be relative to some bound that is in scope (case B).
416 ///
417 /// ```
418 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
419 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
420 /// impl Clone for i32 { ... } // Impl_3
421 ///
422 /// fn foo<T: Clone>(concrete: Option<Box<i32>>, param: T, mixed: Option<T>) {
423 /// // Case A: Vtable points at a specific impl. Only possible when
424 /// // type is concretely known. If the impl itself has bounded
425 /// // type parameters, Vtable will carry resolutions for those as well:
426 /// concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
427 ///
428 /// // Case A: ImplSource points at a specific impl. Only possible when
429 /// // type is concretely known. If the impl itself has bounded
430 /// // type parameters, ImplSource will carry resolutions for those as well:
431 /// concrete.clone(); // ImplSource(Impl_1, [ImplSource(Impl_2, [ImplSource(Impl_3)])])
432 ///
433 /// // Case B: ImplSource must be provided by caller. This applies when
434 /// // type is a type parameter.
435 /// param.clone(); // ImplSource::Param
436 ///
437 /// // Case C: A mix of cases A and B.
438 /// mixed.clone(); // ImplSource(Impl_1, [ImplSource::Param])
439 /// }
440 /// ```
441 ///
442 /// ### The type parameter `N`
443 ///
444 /// See explanation on `ImplSourceUserDefinedData`.
445 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
446 pub enum ImplSource<'tcx, N> {
447 /// ImplSource identifying a particular impl.
448 UserDefined(ImplSourceUserDefinedData<'tcx, N>),
449
450 /// ImplSource for auto trait implementations.
451 /// This carries the information and nested obligations with regards
452 /// to an auto implementation for a trait `Trait`. The nested obligations
453 /// ensure the trait implementation holds for all the constituent types.
454 AutoImpl(ImplSourceAutoImplData<N>),
455
456 /// Successful resolution to an obligation provided by the caller
457 /// for some type parameter. The `Vec<N>` represents the
458 /// obligations incurred from normalizing the where-clause (if
459 /// any).
460 Param(Vec<N>),
461
462 /// Virtual calls through an object.
463 Object(ImplSourceObjectData<'tcx, N>),
464
465 /// Successful resolution for a builtin trait.
466 Builtin(ImplSourceBuiltinData<N>),
467
468 /// ImplSource automatically generated for a closure. The `DefId` is the ID
469 /// of the closure expression. This is a `ImplSource::UserDefined` in spirit, but the
470 /// impl is generated by the compiler and does not appear in the source.
471 Closure(ImplSourceClosureData<'tcx, N>),
472
473 /// Same as above, but for a function pointer type with the given signature.
474 FnPointer(ImplSourceFnPointerData<'tcx, N>),
475
476 /// ImplSource for a builtin `DeterminantKind` trait implementation.
477 DiscriminantKind(ImplSourceDiscriminantKindData),
478
479 /// ImplSource automatically generated for a generator.
480 Generator(ImplSourceGeneratorData<'tcx, N>),
481
482 /// ImplSource for a trait alias.
483 TraitAlias(ImplSourceTraitAliasData<'tcx, N>),
484 }
485
486 impl<'tcx, N> ImplSource<'tcx, N> {
487 pub fn nested_obligations(self) -> Vec<N> {
488 match self {
489 ImplSource::UserDefined(i) => i.nested,
490 ImplSource::Param(n) => n,
491 ImplSource::Builtin(i) => i.nested,
492 ImplSource::AutoImpl(d) => d.nested,
493 ImplSource::Closure(c) => c.nested,
494 ImplSource::Generator(c) => c.nested,
495 ImplSource::Object(d) => d.nested,
496 ImplSource::FnPointer(d) => d.nested,
497 ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData) => Vec::new(),
498 ImplSource::TraitAlias(d) => d.nested,
499 }
500 }
501
502 pub fn borrow_nested_obligations(&self) -> &[N] {
503 match &self {
504 ImplSource::UserDefined(i) => &i.nested[..],
505 ImplSource::Param(n) => &n[..],
506 ImplSource::Builtin(i) => &i.nested[..],
507 ImplSource::AutoImpl(d) => &d.nested[..],
508 ImplSource::Closure(c) => &c.nested[..],
509 ImplSource::Generator(c) => &c.nested[..],
510 ImplSource::Object(d) => &d.nested[..],
511 ImplSource::FnPointer(d) => &d.nested[..],
512 ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData) => &[],
513 ImplSource::TraitAlias(d) => &d.nested[..],
514 }
515 }
516
517 pub fn map<M, F>(self, f: F) -> ImplSource<'tcx, M>
518 where
519 F: FnMut(N) -> M,
520 {
521 match self {
522 ImplSource::UserDefined(i) => ImplSource::UserDefined(ImplSourceUserDefinedData {
523 impl_def_id: i.impl_def_id,
524 substs: i.substs,
525 nested: i.nested.into_iter().map(f).collect(),
526 }),
527 ImplSource::Param(n) => ImplSource::Param(n.into_iter().map(f).collect()),
528 ImplSource::Builtin(i) => ImplSource::Builtin(ImplSourceBuiltinData {
529 nested: i.nested.into_iter().map(f).collect(),
530 }),
531 ImplSource::Object(o) => ImplSource::Object(ImplSourceObjectData {
532 upcast_trait_ref: o.upcast_trait_ref,
533 vtable_base: o.vtable_base,
534 nested: o.nested.into_iter().map(f).collect(),
535 }),
536 ImplSource::AutoImpl(d) => ImplSource::AutoImpl(ImplSourceAutoImplData {
537 trait_def_id: d.trait_def_id,
538 nested: d.nested.into_iter().map(f).collect(),
539 }),
540 ImplSource::Closure(c) => ImplSource::Closure(ImplSourceClosureData {
541 closure_def_id: c.closure_def_id,
542 substs: c.substs,
543 nested: c.nested.into_iter().map(f).collect(),
544 }),
545 ImplSource::Generator(c) => ImplSource::Generator(ImplSourceGeneratorData {
546 generator_def_id: c.generator_def_id,
547 substs: c.substs,
548 nested: c.nested.into_iter().map(f).collect(),
549 }),
550 ImplSource::FnPointer(p) => ImplSource::FnPointer(ImplSourceFnPointerData {
551 fn_ty: p.fn_ty,
552 nested: p.nested.into_iter().map(f).collect(),
553 }),
554 ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData) => {
555 ImplSource::DiscriminantKind(ImplSourceDiscriminantKindData)
556 }
557 ImplSource::TraitAlias(d) => ImplSource::TraitAlias(ImplSourceTraitAliasData {
558 alias_def_id: d.alias_def_id,
559 substs: d.substs,
560 nested: d.nested.into_iter().map(f).collect(),
561 }),
562 }
563 }
564 }
565
566 /// Identifies a particular impl in the source, along with a set of
567 /// substitutions from the impl's type/lifetime parameters. The
568 /// `nested` vector corresponds to the nested obligations attached to
569 /// the impl's type parameters.
570 ///
571 /// The type parameter `N` indicates the type used for "nested
572 /// obligations" that are required by the impl. During type-check, this
573 /// is `Obligation`, as one might expect. During codegen, however, this
574 /// is `()`, because codegen only requires a shallow resolution of an
575 /// impl, and nested obligations are satisfied later.
576 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
577 pub struct ImplSourceUserDefinedData<'tcx, N> {
578 pub impl_def_id: DefId,
579 pub substs: SubstsRef<'tcx>,
580 pub nested: Vec<N>,
581 }
582
583 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
584 pub struct ImplSourceGeneratorData<'tcx, N> {
585 pub generator_def_id: DefId,
586 pub substs: SubstsRef<'tcx>,
587 /// Nested obligations. This can be non-empty if the generator
588 /// signature contains associated types.
589 pub nested: Vec<N>,
590 }
591
592 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
593 pub struct ImplSourceClosureData<'tcx, N> {
594 pub closure_def_id: DefId,
595 pub substs: SubstsRef<'tcx>,
596 /// Nested obligations. This can be non-empty if the closure
597 /// signature contains associated types.
598 pub nested: Vec<N>,
599 }
600
601 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
602 pub struct ImplSourceAutoImplData<N> {
603 pub trait_def_id: DefId,
604 pub nested: Vec<N>,
605 }
606
607 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
608 pub struct ImplSourceBuiltinData<N> {
609 pub nested: Vec<N>,
610 }
611
612 #[derive(PartialEq, Eq, Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
613 pub struct ImplSourceObjectData<'tcx, N> {
614 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
615 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
616
617 /// The vtable is formed by concatenating together the method lists of
618 /// the base object trait and all supertraits; this is the start of
619 /// `upcast_trait_ref`'s methods in that vtable.
620 pub vtable_base: usize,
621
622 pub nested: Vec<N>,
623 }
624
625 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
626 pub struct ImplSourceFnPointerData<'tcx, N> {
627 pub fn_ty: Ty<'tcx>,
628 pub nested: Vec<N>,
629 }
630
631 // FIXME(@lcnr): This should be refactored and merged with other builtin vtables.
632 #[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
633 pub struct ImplSourceDiscriminantKindData;
634
635 #[derive(Clone, PartialEq, Eq, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)]
636 pub struct ImplSourceTraitAliasData<'tcx, N> {
637 pub alias_def_id: DefId,
638 pub substs: SubstsRef<'tcx>,
639 pub nested: Vec<N>,
640 }
641
642 #[derive(Clone, Debug, PartialEq, Eq, Hash, HashStable)]
643 pub enum ObjectSafetyViolation {
644 /// `Self: Sized` declared on the trait.
645 SizedSelf(SmallVec<[Span; 1]>),
646
647 /// Supertrait reference references `Self` an in illegal location
648 /// (e.g., `trait Foo : Bar<Self>`).
649 SupertraitSelf(SmallVec<[Span; 1]>),
650
651 /// Method has something illegal.
652 Method(Symbol, MethodViolationCode, Span),
653
654 /// Associated const.
655 AssocConst(Symbol, Span),
656 }
657
658 impl ObjectSafetyViolation {
659 pub fn error_msg(&self) -> Cow<'static, str> {
660 match *self {
661 ObjectSafetyViolation::SizedSelf(_) => "it requires `Self: Sized`".into(),
662 ObjectSafetyViolation::SupertraitSelf(ref spans) => {
663 if spans.iter().any(|sp| *sp != DUMMY_SP) {
664 "it uses `Self` as a type parameter".into()
665 } else {
666 "it cannot use `Self` as a type parameter in a supertrait or `where`-clause"
667 .into()
668 }
669 }
670 ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod(_, _, _), _) => {
671 format!("associated function `{}` has no `self` parameter", name).into()
672 }
673 ObjectSafetyViolation::Method(
674 name,
675 MethodViolationCode::ReferencesSelfInput(_),
676 DUMMY_SP,
677 ) => format!("method `{}` references the `Self` type in its parameters", name).into(),
678 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfInput(_), _) => {
679 format!("method `{}` references the `Self` type in this parameter", name).into()
680 }
681 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfOutput, _) => {
682 format!("method `{}` references the `Self` type in its return type", name).into()
683 }
684 ObjectSafetyViolation::Method(
685 name,
686 MethodViolationCode::WhereClauseReferencesSelf,
687 _,
688 ) => {
689 format!("method `{}` references the `Self` type in its `where` clause", name).into()
690 }
691 ObjectSafetyViolation::Method(name, MethodViolationCode::Generic, _) => {
692 format!("method `{}` has generic type parameters", name).into()
693 }
694 ObjectSafetyViolation::Method(name, MethodViolationCode::UndispatchableReceiver, _) => {
695 format!("method `{}`'s `self` parameter cannot be dispatched on", name).into()
696 }
697 ObjectSafetyViolation::AssocConst(name, DUMMY_SP) => {
698 format!("it contains associated `const` `{}`", name).into()
699 }
700 ObjectSafetyViolation::AssocConst(..) => "it contains this associated `const`".into(),
701 }
702 }
703
704 pub fn solution(&self, err: &mut DiagnosticBuilder<'_>) {
705 match *self {
706 ObjectSafetyViolation::SizedSelf(_) | ObjectSafetyViolation::SupertraitSelf(_) => {}
707 ObjectSafetyViolation::Method(
708 name,
709 MethodViolationCode::StaticMethod(sugg, self_span, has_args),
710 _,
711 ) => {
712 err.span_suggestion(
713 self_span,
714 &format!(
715 "consider turning `{}` into a method by giving it a `&self` argument",
716 name
717 ),
718 format!("&self{}", if has_args { ", " } else { "" }),
719 Applicability::MaybeIncorrect,
720 );
721 match sugg {
722 Some((sugg, span)) => {
723 err.span_suggestion(
724 span,
725 &format!(
726 "alternatively, consider constraining `{}` so it does not apply to \
727 trait objects",
728 name
729 ),
730 sugg.to_string(),
731 Applicability::MaybeIncorrect,
732 );
733 }
734 None => {
735 err.help(&format!(
736 "consider turning `{}` into a method by giving it a `&self` \
737 argument or constraining it so it does not apply to trait objects",
738 name
739 ));
740 }
741 }
742 }
743 ObjectSafetyViolation::Method(
744 name,
745 MethodViolationCode::UndispatchableReceiver,
746 span,
747 ) => {
748 err.span_suggestion(
749 span,
750 &format!(
751 "consider changing method `{}`'s `self` parameter to be `&self`",
752 name
753 ),
754 "&Self".to_string(),
755 Applicability::MachineApplicable,
756 );
757 }
758 ObjectSafetyViolation::AssocConst(name, _)
759 | ObjectSafetyViolation::Method(name, ..) => {
760 err.help(&format!("consider moving `{}` to another trait", name));
761 }
762 }
763 }
764
765 pub fn spans(&self) -> SmallVec<[Span; 1]> {
766 // When `span` comes from a separate crate, it'll be `DUMMY_SP`. Treat it as `None` so
767 // diagnostics use a `note` instead of a `span_label`.
768 match self {
769 ObjectSafetyViolation::SupertraitSelf(spans)
770 | ObjectSafetyViolation::SizedSelf(spans) => spans.clone(),
771 ObjectSafetyViolation::AssocConst(_, span)
772 | ObjectSafetyViolation::Method(_, _, span)
773 if *span != DUMMY_SP =>
774 {
775 smallvec![*span]
776 }
777 _ => smallvec![],
778 }
779 }
780 }
781
782 /// Reasons a method might not be object-safe.
783 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
784 pub enum MethodViolationCode {
785 /// e.g., `fn foo()`
786 StaticMethod(Option<(&'static str, Span)>, Span, bool /* has args */),
787
788 /// e.g., `fn foo(&self, x: Self)`
789 ReferencesSelfInput(usize),
790
791 /// e.g., `fn foo(&self) -> Self`
792 ReferencesSelfOutput,
793
794 /// e.g., `fn foo(&self) where Self: Clone`
795 WhereClauseReferencesSelf,
796
797 /// e.g., `fn foo<A>()`
798 Generic,
799
800 /// the method's receiver (`self` argument) can't be dispatched on
801 UndispatchableReceiver,
802 }