]> git.proxmox.com Git - rustc.git/blob - src/librustc_middle/traits/mod.rs
New upstream version 1.44.1+dfsg1
[rustc.git] / src / librustc_middle / 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 pub mod query;
6 pub mod select;
7 pub mod specialization_graph;
8 mod structural_impls;
9
10 use crate::mir::interpret::ErrorHandled;
11 use crate::ty::subst::SubstsRef;
12 use crate::ty::{self, AdtKind, List, Ty, TyCtxt};
13
14 use rustc_ast::ast;
15 use rustc_hir as hir;
16 use rustc_hir::def_id::DefId;
17 use rustc_span::{Span, DUMMY_SP};
18 use smallvec::SmallVec;
19
20 use std::borrow::Cow;
21 use std::fmt::Debug;
22 use std::rc::Rc;
23
24 pub use self::select::{EvaluationCache, EvaluationResult, OverflowError, SelectionCache};
25
26 pub use self::ObligationCauseCode::*;
27 pub use self::SelectionError::*;
28 pub use self::Vtable::*;
29
30 /// Depending on the stage of compilation, we want projection to be
31 /// more or less conservative.
32 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, HashStable)]
33 pub enum Reveal {
34 /// At type-checking time, we refuse to project any associated
35 /// type that is marked `default`. Non-`default` ("final") types
36 /// are always projected. This is necessary in general for
37 /// soundness of specialization. However, we *could* allow
38 /// projections in fully-monomorphic cases. We choose not to,
39 /// because we prefer for `default type` to force the type
40 /// definition to be treated abstractly by any consumers of the
41 /// impl. Concretely, that means that the following example will
42 /// fail to compile:
43 ///
44 /// ```
45 /// trait Assoc {
46 /// type Output;
47 /// }
48 ///
49 /// impl<T> Assoc for T {
50 /// default type Output = bool;
51 /// }
52 ///
53 /// fn main() {
54 /// let <() as Assoc>::Output = true;
55 /// }
56 /// ```
57 UserFacing,
58
59 /// At codegen time, all monomorphic projections will succeed.
60 /// Also, `impl Trait` is normalized to the concrete type,
61 /// which has to be already collected by type-checking.
62 ///
63 /// NOTE: as `impl Trait`'s concrete type should *never*
64 /// be observable directly by the user, `Reveal::All`
65 /// should not be used by checks which may expose
66 /// type equality or type contents to the user.
67 /// There are some exceptions, e.g., around OIBITS and
68 /// transmute-checking, which expose some details, but
69 /// not the whole concrete type of the `impl Trait`.
70 All,
71 }
72
73 /// The reason why we incurred this obligation; used for error reporting.
74 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
75 pub struct ObligationCause<'tcx> {
76 pub span: Span,
77
78 /// The ID of the fn body that triggered this obligation. This is
79 /// used for region obligations to determine the precise
80 /// environment in which the region obligation should be evaluated
81 /// (in particular, closures can add new assumptions). See the
82 /// field `region_obligations` of the `FulfillmentContext` for more
83 /// information.
84 pub body_id: hir::HirId,
85
86 pub code: ObligationCauseCode<'tcx>,
87 }
88
89 impl<'tcx> ObligationCause<'tcx> {
90 #[inline]
91 pub fn new(
92 span: Span,
93 body_id: hir::HirId,
94 code: ObligationCauseCode<'tcx>,
95 ) -> ObligationCause<'tcx> {
96 ObligationCause { span, body_id, code }
97 }
98
99 pub fn misc(span: Span, body_id: hir::HirId) -> ObligationCause<'tcx> {
100 ObligationCause { span, body_id, code: MiscObligation }
101 }
102
103 pub fn dummy() -> ObligationCause<'tcx> {
104 ObligationCause { span: DUMMY_SP, body_id: hir::CRATE_HIR_ID, code: MiscObligation }
105 }
106
107 pub fn span(&self, tcx: TyCtxt<'tcx>) -> Span {
108 match self.code {
109 ObligationCauseCode::CompareImplMethodObligation { .. }
110 | ObligationCauseCode::MainFunctionType
111 | ObligationCauseCode::StartFunctionType => {
112 tcx.sess.source_map().guess_head_span(self.span)
113 }
114 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
115 arm_span,
116 ..
117 }) => arm_span,
118 _ => self.span,
119 }
120 }
121 }
122
123 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
124 pub enum ObligationCauseCode<'tcx> {
125 /// Not well classified or should be obvious from the span.
126 MiscObligation,
127
128 /// A slice or array is WF only if `T: Sized`.
129 SliceOrArrayElem,
130
131 /// A tuple is WF only if its middle elements are `Sized`.
132 TupleElem,
133
134 /// This is the trait reference from the given projection.
135 ProjectionWf(ty::ProjectionTy<'tcx>),
136
137 /// In an impl of trait `X` for type `Y`, type `Y` must
138 /// also implement all supertraits of `X`.
139 ItemObligation(DefId),
140
141 /// Like `ItemObligation`, but with extra detail on the source of the obligation.
142 BindingObligation(DefId, Span),
143
144 /// A type like `&'a T` is WF only if `T: 'a`.
145 ReferenceOutlivesReferent(Ty<'tcx>),
146
147 /// A type like `Box<Foo<'a> + 'b>` is WF only if `'b: 'a`.
148 ObjectTypeBound(Ty<'tcx>, ty::Region<'tcx>),
149
150 /// Obligation incurred due to an object cast.
151 ObjectCastObligation(/* Object type */ Ty<'tcx>),
152
153 /// Obligation incurred due to a coercion.
154 Coercion {
155 source: Ty<'tcx>,
156 target: Ty<'tcx>,
157 },
158
159 /// Various cases where expressions must be `Sized` / `Copy` / etc.
160 /// `L = X` implies that `L` is `Sized`.
161 AssignmentLhsSized,
162 /// `(x1, .., xn)` must be `Sized`.
163 TupleInitializerSized,
164 /// `S { ... }` must be `Sized`.
165 StructInitializerSized,
166 /// Type of each variable must be `Sized`.
167 VariableType(hir::HirId),
168 /// Argument type must be `Sized`.
169 SizedArgumentType,
170 /// Return type must be `Sized`.
171 SizedReturnType,
172 /// Yield type must be `Sized`.
173 SizedYieldType,
174 /// `[T, ..n]` implies that `T` must be `Copy`.
175 /// If `true`, suggest `const_in_array_repeat_expressions` feature flag.
176 RepeatVec(bool),
177
178 /// Types of fields (other than the last, except for packed structs) in a struct must be sized.
179 FieldSized {
180 adt_kind: AdtKind,
181 last: bool,
182 },
183
184 /// Constant expressions must be sized.
185 ConstSized,
186
187 /// `static` items must have `Sync` type.
188 SharedStatic,
189
190 BuiltinDerivedObligation(DerivedObligationCause<'tcx>),
191
192 ImplDerivedObligation(DerivedObligationCause<'tcx>),
193
194 DerivedObligation(DerivedObligationCause<'tcx>),
195
196 /// Error derived when matching traits/impls; see ObligationCause for more details
197 CompareImplMethodObligation {
198 item_name: ast::Name,
199 impl_item_def_id: DefId,
200 trait_item_def_id: DefId,
201 },
202
203 /// Error derived when matching traits/impls; see ObligationCause for more details
204 CompareImplTypeObligation {
205 item_name: ast::Name,
206 impl_item_def_id: DefId,
207 trait_item_def_id: DefId,
208 },
209
210 /// Checking that this expression can be assigned where it needs to be
211 // FIXME(eddyb) #11161 is the original Expr required?
212 ExprAssignable,
213
214 /// Computing common supertype in the arms of a match expression
215 MatchExpressionArm(Box<MatchExpressionArmCause<'tcx>>),
216
217 /// Type error arising from type checking a pattern against an expected type.
218 Pattern {
219 /// The span of the scrutinee or type expression which caused the `root_ty` type.
220 span: Option<Span>,
221 /// The root expected type induced by a scrutinee or type expression.
222 root_ty: Ty<'tcx>,
223 /// Whether the `Span` came from an expression or a type expression.
224 origin_expr: bool,
225 },
226
227 /// Constants in patterns must have `Structural` type.
228 ConstPatternStructural,
229
230 /// Computing common supertype in an if expression
231 IfExpression(Box<IfExpressionCause>),
232
233 /// Computing common supertype of an if expression with no else counter-part
234 IfExpressionWithNoElse,
235
236 /// `main` has wrong type
237 MainFunctionType,
238
239 /// `start` has wrong type
240 StartFunctionType,
241
242 /// Intrinsic has wrong type
243 IntrinsicType,
244
245 /// Method receiver
246 MethodReceiver,
247
248 /// `return` with no expression
249 ReturnNoExpression,
250
251 /// `return` with an expression
252 ReturnValue(hir::HirId),
253
254 /// Return type of this function
255 ReturnType,
256
257 /// Block implicit return
258 BlockTailExpression(hir::HirId),
259
260 /// #[feature(trivial_bounds)] is not enabled
261 TrivialBound,
262 }
263
264 impl ObligationCauseCode<'_> {
265 // Return the base obligation, ignoring derived obligations.
266 pub fn peel_derives(&self) -> &Self {
267 let mut base_cause = self;
268 while let BuiltinDerivedObligation(cause)
269 | ImplDerivedObligation(cause)
270 | DerivedObligation(cause) = base_cause
271 {
272 base_cause = &cause.parent_code;
273 }
274 base_cause
275 }
276 }
277
278 // `ObligationCauseCode` is used a lot. Make sure it doesn't unintentionally get bigger.
279 #[cfg(target_arch = "x86_64")]
280 static_assert_size!(ObligationCauseCode<'_>, 32);
281
282 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
283 pub struct MatchExpressionArmCause<'tcx> {
284 pub arm_span: Span,
285 pub source: hir::MatchSource,
286 pub prior_arms: Vec<Span>,
287 pub last_ty: Ty<'tcx>,
288 pub scrut_hir_id: hir::HirId,
289 }
290
291 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
292 pub struct IfExpressionCause {
293 pub then: Span,
294 pub outer: Option<Span>,
295 pub semicolon: Option<Span>,
296 }
297
298 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
299 pub struct DerivedObligationCause<'tcx> {
300 /// The trait reference of the parent obligation that led to the
301 /// current obligation. Note that only trait obligations lead to
302 /// derived obligations, so we just store the trait reference here
303 /// directly.
304 pub parent_trait_ref: ty::PolyTraitRef<'tcx>,
305
306 /// The parent trait had this cause.
307 pub parent_code: Rc<ObligationCauseCode<'tcx>>,
308 }
309
310 /// The following types:
311 /// * `WhereClause`,
312 /// * `WellFormed`,
313 /// * `FromEnv`,
314 /// * `DomainGoal`,
315 /// * `Goal`,
316 /// * `Clause`,
317 /// * `Environment`,
318 /// * `InEnvironment`,
319 /// are used for representing the trait system in the form of
320 /// logic programming clauses. They are part of the interface
321 /// for the chalk SLG solver.
322 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
323 pub enum WhereClause<'tcx> {
324 Implemented(ty::TraitPredicate<'tcx>),
325 ProjectionEq(ty::ProjectionPredicate<'tcx>),
326 RegionOutlives(ty::RegionOutlivesPredicate<'tcx>),
327 TypeOutlives(ty::TypeOutlivesPredicate<'tcx>),
328 }
329
330 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
331 pub enum WellFormed<'tcx> {
332 Trait(ty::TraitPredicate<'tcx>),
333 Ty(Ty<'tcx>),
334 }
335
336 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
337 pub enum FromEnv<'tcx> {
338 Trait(ty::TraitPredicate<'tcx>),
339 Ty(Ty<'tcx>),
340 }
341
342 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
343 pub enum DomainGoal<'tcx> {
344 Holds(WhereClause<'tcx>),
345 WellFormed(WellFormed<'tcx>),
346 FromEnv(FromEnv<'tcx>),
347 Normalize(ty::ProjectionPredicate<'tcx>),
348 }
349
350 pub type PolyDomainGoal<'tcx> = ty::Binder<DomainGoal<'tcx>>;
351
352 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
353 pub enum QuantifierKind {
354 Universal,
355 Existential,
356 }
357
358 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable, Lift)]
359 pub enum GoalKind<'tcx> {
360 Implies(Clauses<'tcx>, Goal<'tcx>),
361 And(Goal<'tcx>, Goal<'tcx>),
362 Not(Goal<'tcx>),
363 DomainGoal(DomainGoal<'tcx>),
364 Quantified(QuantifierKind, ty::Binder<Goal<'tcx>>),
365 Subtype(Ty<'tcx>, Ty<'tcx>),
366 CannotProve,
367 }
368
369 pub type Goal<'tcx> = &'tcx GoalKind<'tcx>;
370
371 pub type Goals<'tcx> = &'tcx List<Goal<'tcx>>;
372
373 impl<'tcx> DomainGoal<'tcx> {
374 pub fn into_goal(self) -> GoalKind<'tcx> {
375 GoalKind::DomainGoal(self)
376 }
377
378 pub fn into_program_clause(self) -> ProgramClause<'tcx> {
379 ProgramClause {
380 goal: self,
381 hypotheses: ty::List::empty(),
382 category: ProgramClauseCategory::Other,
383 }
384 }
385 }
386
387 impl<'tcx> GoalKind<'tcx> {
388 pub fn from_poly_domain_goal(
389 domain_goal: PolyDomainGoal<'tcx>,
390 tcx: TyCtxt<'tcx>,
391 ) -> GoalKind<'tcx> {
392 match domain_goal.no_bound_vars() {
393 Some(p) => p.into_goal(),
394 None => GoalKind::Quantified(
395 QuantifierKind::Universal,
396 domain_goal.map_bound(|p| tcx.mk_goal(p.into_goal())),
397 ),
398 }
399 }
400 }
401
402 /// This matches the definition from Page 7 of "A Proof Procedure for the Logic of Hereditary
403 /// Harrop Formulas".
404 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
405 pub enum Clause<'tcx> {
406 Implies(ProgramClause<'tcx>),
407 ForAll(ty::Binder<ProgramClause<'tcx>>),
408 }
409
410 impl Clause<'tcx> {
411 pub fn category(self) -> ProgramClauseCategory {
412 match self {
413 Clause::Implies(clause) => clause.category,
414 Clause::ForAll(clause) => clause.skip_binder().category,
415 }
416 }
417 }
418
419 /// Multiple clauses.
420 pub type Clauses<'tcx> = &'tcx List<Clause<'tcx>>;
421
422 /// A "program clause" has the form `D :- G1, ..., Gn`. It is saying
423 /// that the domain goal `D` is true if `G1...Gn` are provable. This
424 /// is equivalent to the implication `G1..Gn => D`; we usually write
425 /// it with the reverse implication operator `:-` to emphasize the way
426 /// that programs are actually solved (via backchaining, which starts
427 /// with the goal to solve and proceeds from there).
428 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
429 pub struct ProgramClause<'tcx> {
430 /// This goal will be considered true ...
431 pub goal: DomainGoal<'tcx>,
432
433 /// ... if we can prove these hypotheses (there may be no hypotheses at all):
434 pub hypotheses: Goals<'tcx>,
435
436 /// Useful for filtering clauses.
437 pub category: ProgramClauseCategory,
438 }
439
440 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable)]
441 pub enum ProgramClauseCategory {
442 ImpliedBound,
443 WellFormed,
444 Other,
445 }
446
447 /// A set of clauses that we assume to be true.
448 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
449 pub struct Environment<'tcx> {
450 pub clauses: Clauses<'tcx>,
451 }
452
453 impl Environment<'tcx> {
454 pub fn with<G>(self, goal: G) -> InEnvironment<'tcx, G> {
455 InEnvironment { environment: self, goal }
456 }
457 }
458
459 /// Something (usually a goal), along with an environment.
460 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)]
461 pub struct InEnvironment<'tcx, G> {
462 pub environment: Environment<'tcx>,
463 pub goal: G,
464 }
465
466 #[derive(Clone, Debug, TypeFoldable)]
467 pub enum SelectionError<'tcx> {
468 Unimplemented,
469 OutputTypeParameterMismatch(
470 ty::PolyTraitRef<'tcx>,
471 ty::PolyTraitRef<'tcx>,
472 ty::error::TypeError<'tcx>,
473 ),
474 TraitNotObjectSafe(DefId),
475 ConstEvalFailure(ErrorHandled),
476 Overflow,
477 }
478
479 /// When performing resolution, it is typically the case that there
480 /// can be one of three outcomes:
481 ///
482 /// - `Ok(Some(r))`: success occurred with result `r`
483 /// - `Ok(None)`: could not definitely determine anything, usually due
484 /// to inconclusive type inference.
485 /// - `Err(e)`: error `e` occurred
486 pub type SelectionResult<'tcx, T> = Result<Option<T>, SelectionError<'tcx>>;
487
488 /// Given the successful resolution of an obligation, the `Vtable`
489 /// indicates where the vtable comes from. Note that while we call this
490 /// a "vtable", it does not necessarily indicate dynamic dispatch at
491 /// runtime. `Vtable` instances just tell the compiler where to find
492 /// methods, but in generic code those methods are typically statically
493 /// dispatched -- only when an object is constructed is a `Vtable`
494 /// instance reified into an actual vtable.
495 ///
496 /// For example, the vtable may be tied to a specific impl (case A),
497 /// or it may be relative to some bound that is in scope (case B).
498 ///
499 /// ```
500 /// impl<T:Clone> Clone<T> for Option<T> { ... } // Impl_1
501 /// impl<T:Clone> Clone<T> for Box<T> { ... } // Impl_2
502 /// impl Clone for int { ... } // Impl_3
503 ///
504 /// fn foo<T:Clone>(concrete: Option<Box<int>>,
505 /// param: T,
506 /// mixed: Option<T>) {
507 ///
508 /// // Case A: Vtable points at a specific impl. Only possible when
509 /// // type is concretely known. If the impl itself has bounded
510 /// // type parameters, Vtable will carry resolutions for those as well:
511 /// concrete.clone(); // Vtable(Impl_1, [Vtable(Impl_2, [Vtable(Impl_3)])])
512 ///
513 /// // Case B: Vtable must be provided by caller. This applies when
514 /// // type is a type parameter.
515 /// param.clone(); // VtableParam
516 ///
517 /// // Case C: A mix of cases A and B.
518 /// mixed.clone(); // Vtable(Impl_1, [VtableParam])
519 /// }
520 /// ```
521 ///
522 /// ### The type parameter `N`
523 ///
524 /// See explanation on `VtableImplData`.
525 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
526 pub enum Vtable<'tcx, N> {
527 /// Vtable identifying a particular impl.
528 VtableImpl(VtableImplData<'tcx, N>),
529
530 /// Vtable for auto trait implementations.
531 /// This carries the information and nested obligations with regards
532 /// to an auto implementation for a trait `Trait`. The nested obligations
533 /// ensure the trait implementation holds for all the constituent types.
534 VtableAutoImpl(VtableAutoImplData<N>),
535
536 /// Successful resolution to an obligation provided by the caller
537 /// for some type parameter. The `Vec<N>` represents the
538 /// obligations incurred from normalizing the where-clause (if
539 /// any).
540 VtableParam(Vec<N>),
541
542 /// Virtual calls through an object.
543 VtableObject(VtableObjectData<'tcx, N>),
544
545 /// Successful resolution for a builtin trait.
546 VtableBuiltin(VtableBuiltinData<N>),
547
548 /// Vtable automatically generated for a closure. The `DefId` is the ID
549 /// of the closure expression. This is a `VtableImpl` in spirit, but the
550 /// impl is generated by the compiler and does not appear in the source.
551 VtableClosure(VtableClosureData<'tcx, N>),
552
553 /// Same as above, but for a function pointer type with the given signature.
554 VtableFnPointer(VtableFnPointerData<'tcx, N>),
555
556 /// Vtable automatically generated for a generator.
557 VtableGenerator(VtableGeneratorData<'tcx, N>),
558
559 /// Vtable for a trait alias.
560 VtableTraitAlias(VtableTraitAliasData<'tcx, N>),
561 }
562
563 impl<'tcx, N> Vtable<'tcx, N> {
564 pub fn nested_obligations(self) -> Vec<N> {
565 match self {
566 VtableImpl(i) => i.nested,
567 VtableParam(n) => n,
568 VtableBuiltin(i) => i.nested,
569 VtableAutoImpl(d) => d.nested,
570 VtableClosure(c) => c.nested,
571 VtableGenerator(c) => c.nested,
572 VtableObject(d) => d.nested,
573 VtableFnPointer(d) => d.nested,
574 VtableTraitAlias(d) => d.nested,
575 }
576 }
577
578 pub fn borrow_nested_obligations(&self) -> &[N] {
579 match &self {
580 VtableImpl(i) => &i.nested[..],
581 VtableParam(n) => &n[..],
582 VtableBuiltin(i) => &i.nested[..],
583 VtableAutoImpl(d) => &d.nested[..],
584 VtableClosure(c) => &c.nested[..],
585 VtableGenerator(c) => &c.nested[..],
586 VtableObject(d) => &d.nested[..],
587 VtableFnPointer(d) => &d.nested[..],
588 VtableTraitAlias(d) => &d.nested[..],
589 }
590 }
591
592 pub fn map<M, F>(self, f: F) -> Vtable<'tcx, M>
593 where
594 F: FnMut(N) -> M,
595 {
596 match self {
597 VtableImpl(i) => VtableImpl(VtableImplData {
598 impl_def_id: i.impl_def_id,
599 substs: i.substs,
600 nested: i.nested.into_iter().map(f).collect(),
601 }),
602 VtableParam(n) => VtableParam(n.into_iter().map(f).collect()),
603 VtableBuiltin(i) => {
604 VtableBuiltin(VtableBuiltinData { nested: i.nested.into_iter().map(f).collect() })
605 }
606 VtableObject(o) => VtableObject(VtableObjectData {
607 upcast_trait_ref: o.upcast_trait_ref,
608 vtable_base: o.vtable_base,
609 nested: o.nested.into_iter().map(f).collect(),
610 }),
611 VtableAutoImpl(d) => VtableAutoImpl(VtableAutoImplData {
612 trait_def_id: d.trait_def_id,
613 nested: d.nested.into_iter().map(f).collect(),
614 }),
615 VtableClosure(c) => VtableClosure(VtableClosureData {
616 closure_def_id: c.closure_def_id,
617 substs: c.substs,
618 nested: c.nested.into_iter().map(f).collect(),
619 }),
620 VtableGenerator(c) => VtableGenerator(VtableGeneratorData {
621 generator_def_id: c.generator_def_id,
622 substs: c.substs,
623 nested: c.nested.into_iter().map(f).collect(),
624 }),
625 VtableFnPointer(p) => VtableFnPointer(VtableFnPointerData {
626 fn_ty: p.fn_ty,
627 nested: p.nested.into_iter().map(f).collect(),
628 }),
629 VtableTraitAlias(d) => VtableTraitAlias(VtableTraitAliasData {
630 alias_def_id: d.alias_def_id,
631 substs: d.substs,
632 nested: d.nested.into_iter().map(f).collect(),
633 }),
634 }
635 }
636 }
637
638 /// Identifies a particular impl in the source, along with a set of
639 /// substitutions from the impl's type/lifetime parameters. The
640 /// `nested` vector corresponds to the nested obligations attached to
641 /// the impl's type parameters.
642 ///
643 /// The type parameter `N` indicates the type used for "nested
644 /// obligations" that are required by the impl. During type-check, this
645 /// is `Obligation`, as one might expect. During codegen, however, this
646 /// is `()`, because codegen only requires a shallow resolution of an
647 /// impl, and nested obligations are satisfied later.
648 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
649 pub struct VtableImplData<'tcx, N> {
650 pub impl_def_id: DefId,
651 pub substs: SubstsRef<'tcx>,
652 pub nested: Vec<N>,
653 }
654
655 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
656 pub struct VtableGeneratorData<'tcx, N> {
657 pub generator_def_id: DefId,
658 pub substs: SubstsRef<'tcx>,
659 /// Nested obligations. This can be non-empty if the generator
660 /// signature contains associated types.
661 pub nested: Vec<N>,
662 }
663
664 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
665 pub struct VtableClosureData<'tcx, N> {
666 pub closure_def_id: DefId,
667 pub substs: SubstsRef<'tcx>,
668 /// Nested obligations. This can be non-empty if the closure
669 /// signature contains associated types.
670 pub nested: Vec<N>,
671 }
672
673 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
674 pub struct VtableAutoImplData<N> {
675 pub trait_def_id: DefId,
676 pub nested: Vec<N>,
677 }
678
679 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
680 pub struct VtableBuiltinData<N> {
681 pub nested: Vec<N>,
682 }
683
684 /// A vtable for some object-safe trait `Foo` automatically derived
685 /// for the object type `Foo`.
686 #[derive(PartialEq, Eq, Clone, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
687 pub struct VtableObjectData<'tcx, N> {
688 /// `Foo` upcast to the obligation trait. This will be some supertrait of `Foo`.
689 pub upcast_trait_ref: ty::PolyTraitRef<'tcx>,
690
691 /// The vtable is formed by concatenating together the method lists of
692 /// the base object trait and all supertraits; this is the start of
693 /// `upcast_trait_ref`'s methods in that vtable.
694 pub vtable_base: usize,
695
696 pub nested: Vec<N>,
697 }
698
699 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
700 pub struct VtableFnPointerData<'tcx, N> {
701 pub fn_ty: Ty<'tcx>,
702 pub nested: Vec<N>,
703 }
704
705 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
706 pub struct VtableTraitAliasData<'tcx, N> {
707 pub alias_def_id: DefId,
708 pub substs: SubstsRef<'tcx>,
709 pub nested: Vec<N>,
710 }
711
712 #[derive(Clone, Debug, PartialEq, Eq, Hash, HashStable)]
713 pub enum ObjectSafetyViolation {
714 /// `Self: Sized` declared on the trait.
715 SizedSelf(SmallVec<[Span; 1]>),
716
717 /// Supertrait reference references `Self` an in illegal location
718 /// (e.g., `trait Foo : Bar<Self>`).
719 SupertraitSelf(SmallVec<[Span; 1]>),
720
721 /// Method has something illegal.
722 Method(ast::Name, MethodViolationCode, Span),
723
724 /// Associated const.
725 AssocConst(ast::Name, Span),
726 }
727
728 impl ObjectSafetyViolation {
729 pub fn error_msg(&self) -> Cow<'static, str> {
730 match *self {
731 ObjectSafetyViolation::SizedSelf(_) => "it requires `Self: Sized`".into(),
732 ObjectSafetyViolation::SupertraitSelf(ref spans) => {
733 if spans.iter().any(|sp| *sp != DUMMY_SP) {
734 "it uses `Self` as a type parameter in this".into()
735 } else {
736 "it cannot use `Self` as a type parameter in a supertrait or `where`-clause"
737 .into()
738 }
739 }
740 ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod(_), _) => {
741 format!("associated function `{}` has no `self` parameter", name).into()
742 }
743 ObjectSafetyViolation::Method(
744 name,
745 MethodViolationCode::ReferencesSelfInput(_),
746 DUMMY_SP,
747 ) => format!("method `{}` references the `Self` type in its parameters", name).into(),
748 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfInput(_), _) => {
749 format!("method `{}` references the `Self` type in this parameter", name).into()
750 }
751 ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfOutput, _) => {
752 format!("method `{}` references the `Self` type in its return type", name).into()
753 }
754 ObjectSafetyViolation::Method(
755 name,
756 MethodViolationCode::WhereClauseReferencesSelf,
757 _,
758 ) => {
759 format!("method `{}` references the `Self` type in its `where` clause", name).into()
760 }
761 ObjectSafetyViolation::Method(name, MethodViolationCode::Generic, _) => {
762 format!("method `{}` has generic type parameters", name).into()
763 }
764 ObjectSafetyViolation::Method(name, MethodViolationCode::UndispatchableReceiver, _) => {
765 format!("method `{}`'s `self` parameter cannot be dispatched on", name).into()
766 }
767 ObjectSafetyViolation::AssocConst(name, DUMMY_SP) => {
768 format!("it contains associated `const` `{}`", name).into()
769 }
770 ObjectSafetyViolation::AssocConst(..) => "it contains this associated `const`".into(),
771 }
772 }
773
774 pub fn solution(&self) -> Option<(String, Option<(String, Span)>)> {
775 Some(match *self {
776 ObjectSafetyViolation::SizedSelf(_) | ObjectSafetyViolation::SupertraitSelf(_) => {
777 return None;
778 }
779 ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod(sugg), _) => (
780 format!(
781 "consider turning `{}` into a method by giving it a `&self` argument or \
782 constraining it so it does not apply to trait objects",
783 name
784 ),
785 sugg.map(|(sugg, sp)| (sugg.to_string(), sp)),
786 ),
787 ObjectSafetyViolation::Method(
788 name,
789 MethodViolationCode::UndispatchableReceiver,
790 span,
791 ) => (
792 format!("consider changing method `{}`'s `self` parameter to be `&self`", name),
793 Some(("&Self".to_string(), span)),
794 ),
795 ObjectSafetyViolation::AssocConst(name, _)
796 | ObjectSafetyViolation::Method(name, ..) => {
797 (format!("consider moving `{}` to another trait", name), None)
798 }
799 })
800 }
801
802 pub fn spans(&self) -> SmallVec<[Span; 1]> {
803 // When `span` comes from a separate crate, it'll be `DUMMY_SP`. Treat it as `None` so
804 // diagnostics use a `note` instead of a `span_label`.
805 match self {
806 ObjectSafetyViolation::SupertraitSelf(spans)
807 | ObjectSafetyViolation::SizedSelf(spans) => spans.clone(),
808 ObjectSafetyViolation::AssocConst(_, span)
809 | ObjectSafetyViolation::Method(_, _, span)
810 if *span != DUMMY_SP =>
811 {
812 smallvec![*span]
813 }
814 _ => smallvec![],
815 }
816 }
817 }
818
819 /// Reasons a method might not be object-safe.
820 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
821 pub enum MethodViolationCode {
822 /// e.g., `fn foo()`
823 StaticMethod(Option<(&'static str, Span)>),
824
825 /// e.g., `fn foo(&self, x: Self)`
826 ReferencesSelfInput(usize),
827
828 /// e.g., `fn foo(&self) -> Self`
829 ReferencesSelfOutput,
830
831 /// e.g., `fn foo(&self) where Self: Clone`
832 WhereClauseReferencesSelf,
833
834 /// e.g., `fn foo<A>()`
835 Generic,
836
837 /// the method's receiver (`self` argument) can't be dispatched on
838 UndispatchableReceiver,
839 }