]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/coherence/orphan.rs
88fa09cc9366a39d3f9bc24f94c58f5dafe26577
[rust.git] / src / librustc_typeck / coherence / orphan.rs
1 //! Orphan checker: every impl either implements a trait defined in this
2 //! crate or pertains to a type defined in this crate.
3
4 use rustc::traits;
5 use rustc::ty::{self, TyCtxt};
6 use rustc::hir::itemlikevisit::ItemLikeVisitor;
7 use rustc::hir;
8
9 pub fn check(tcx: TyCtxt<'_>) {
10     let mut orphan = OrphanChecker { tcx };
11     tcx.hir().krate().visit_all_item_likes(&mut orphan);
12 }
13
14 struct OrphanChecker<'tcx> {
15     tcx: TyCtxt<'tcx>,
16 }
17
18 impl ItemLikeVisitor<'v> for OrphanChecker<'tcx> {
19     /// Checks exactly one impl for orphan rules and other such
20     /// restrictions. In this fn, it can happen that multiple errors
21     /// apply to a specific impl, so just return after reporting one
22     /// to prevent inundating the user with a bunch of similar error
23     /// reports.
24     fn visit_item(&mut self, item: &hir::Item) {
25         let def_id = self.tcx.hir().local_def_id(item.hir_id);
26         // "Trait" impl
27         if let hir::ItemKind::Impl(.., generics, Some(tr), impl_ty, _) = &item.kind {
28             debug!("coherence2::orphan check: trait impl {}",
29                    self.tcx.hir().node_to_string(item.hir_id));
30             let trait_ref = self.tcx.impl_trait_ref(def_id).unwrap();
31             let trait_def_id = trait_ref.def_id;
32             let cm = self.tcx.sess.source_map();
33             let sp = cm.def_span(item.span);
34             match traits::orphan_check(self.tcx, def_id) {
35                 Ok(()) => {}
36                 Err(traits::OrphanCheckErr::NonLocalInputType(tys)) => {
37                     let mut err = struct_span_err!(
38                         self.tcx.sess,
39                         sp,
40                         E0117,
41                         "only traits defined in the current crate can be implemented for \
42                          arbitrary types"
43                     );
44                     err.span_label(sp, "impl doesn't use only types from inside the current crate");
45                     for (ty, is_target_ty) in &tys {
46                         let mut ty = *ty;
47                         self.tcx.infer_ctxt().enter(|infcx| {
48                             // Remove the lifetimes unnecessary for this error.
49                             ty = infcx.freshen(ty);
50                         });
51                         ty = match ty.kind {
52                             // Remove the type arguments from the output, as they are not relevant.
53                             // You can think of this as the reverse of `resolve_vars_if_possible`.
54                             // That way if we had `Vec<MyType>`, we will properly attribute the
55                             // problem to `Vec<T>` and avoid confusing the user if they were to see
56                             // `MyType` in the error.
57                             ty::Adt(def, _) => self.tcx.mk_adt(def, ty::List::empty()),
58                             _ => ty,
59                         };
60                         let this = "this".to_string();
61                         let (ty, postfix) = match &ty.kind {
62                             ty::Slice(_) => (this, " because slices are always foreign"),
63                             ty::Array(..) => (this, " because arrays are always foreign"),
64                             ty::Tuple(..) => (this, " because tuples are always foreign"),
65                             _ => (format!("`{}`", ty), ""),
66                         };
67                         let msg = format!("{} is not defined in the current crate{}", ty, postfix);
68                         if *is_target_ty {
69                             // Point at `D<A>` in `impl<A, B> for C<B> in D<A>`
70                             err.span_label(impl_ty.span, &msg);
71                         } else {
72                             // Point at `C<B>` in `impl<A, B> for C<B> in D<A>`
73                             err.span_label(tr.path.span, &msg);
74                         }
75                     }
76                     err.note("define and implement a trait or new type instead");
77                     err.emit();
78                     return;
79                 }
80                 Err(traits::OrphanCheckErr::UncoveredTy(param_ty, local_type)) => {
81                     let mut sp = sp;
82                     for param in &generics.params {
83                         if param.name.ident().to_string() == param_ty.to_string() {
84                             sp = param.span;
85                         }
86                     }
87
88                     match local_type {
89                         Some(local_type) => {
90                             struct_span_err!(
91                                 self.tcx.sess,
92                                 sp,
93                                 E0210,
94                                 "type parameter `{}` must be covered by another type \
95                                 when it appears before the first local type (`{}`)",
96                                 param_ty,
97                                 local_type
98                             ).span_label(sp, format!(
99                                 "type parameter `{}` must be covered by another type \
100                                 when it appears before the first local type (`{}`)",
101                                 param_ty,
102                                 local_type
103                             )).note("implementing a foreign trait is only possible if at \
104                                     least one of the types for which is it implemented is local, \
105                                     and no uncovered type parameters appear before that first \
106                                     local type"
107                             ).note("in this case, 'before' refers to the following order: \
108                                     `impl<..> ForeignTrait<T1, ..., Tn> for T0`, \
109                                     where `T0` is the first and `Tn` is the last"
110                             ).emit();
111                         }
112                         None => {
113                             struct_span_err!(
114                                 self.tcx.sess,
115                                 sp,
116                                 E0210,
117                                 "type parameter `{}` must be used as the type parameter for some \
118                                 local type (e.g., `MyStruct<{}>`)",
119                                 param_ty,
120                                 param_ty
121                             ).span_label(sp, format!(
122                                 "type parameter `{}` must be used as the type parameter for some \
123                                 local type",
124                                 param_ty,
125                             )).note("implementing a foreign trait is only possible if at \
126                                     least one of the types for which is it implemented is local"
127                             ).note("only traits defined in the current crate can be \
128                                     implemented for a type parameter"
129                             ).emit();
130                         }
131                     };
132                     return;
133                 }
134             }
135
136             // In addition to the above rules, we restrict impls of auto traits
137             // so that they can only be implemented on nominal types, such as structs,
138             // enums or foreign types. To see why this restriction exists, consider the
139             // following example (#22978). Imagine that crate A defines an auto trait
140             // `Foo` and a fn that operates on pairs of types:
141             //
142             // ```
143             // // Crate A
144             // auto trait Foo { }
145             // fn two_foos<A:Foo,B:Foo>(..) {
146             //     one_foo::<(A,B)>(..)
147             // }
148             // fn one_foo<T:Foo>(..) { .. }
149             // ```
150             //
151             // This type-checks fine; in particular the fn
152             // `two_foos` is able to conclude that `(A,B):Foo`
153             // because `A:Foo` and `B:Foo`.
154             //
155             // Now imagine that crate B comes along and does the following:
156             //
157             // ```
158             // struct A { }
159             // struct B { }
160             // impl Foo for A { }
161             // impl Foo for B { }
162             // impl !Send for (A, B) { }
163             // ```
164             //
165             // This final impl is legal according to the orpan
166             // rules, but it invalidates the reasoning from
167             // `two_foos` above.
168             debug!("trait_ref={:?} trait_def_id={:?} trait_is_auto={}",
169                    trait_ref,
170                    trait_def_id,
171                    self.tcx.trait_is_auto(trait_def_id));
172             if self.tcx.trait_is_auto(trait_def_id) &&
173                !trait_def_id.is_local() {
174                 let self_ty = trait_ref.self_ty();
175                 let opt_self_def_id = match self_ty.kind {
176                     ty::Adt(self_def, _) => Some(self_def.did),
177                     ty::Foreign(did) => Some(did),
178                     _ => None,
179                 };
180
181                 let msg = match opt_self_def_id {
182                     // We only want to permit nominal types, but not *all* nominal types.
183                     // They must be local to the current crate, so that people
184                     // can't do `unsafe impl Send for Rc<SomethingLocal>` or
185                     // `impl !Send for Box<SomethingLocalAndSend>`.
186                     Some(self_def_id) => {
187                         if self_def_id.is_local() {
188                             None
189                         } else {
190                             Some((
191                                 format!("cross-crate traits with a default impl, like `{}`, \
192                                          can only be implemented for a struct/enum type \
193                                          defined in the current crate",
194                                         self.tcx.def_path_str(trait_def_id)),
195                                 "can't implement cross-crate trait for type in another crate"
196                             ))
197                         }
198                     }
199                     _ => {
200                         Some((format!("cross-crate traits with a default impl, like `{}`, can \
201                                        only be implemented for a struct/enum type, not `{}`",
202                                       self.tcx.def_path_str(trait_def_id),
203                                       self_ty),
204                               "can't implement cross-crate trait with a default impl for \
205                                non-struct/enum type"))
206                     }
207                 };
208
209                 if let Some((msg, label)) = msg {
210                     struct_span_err!(self.tcx.sess, sp, E0321, "{}", msg)
211                         .span_label(sp, label)
212                         .emit();
213                     return;
214                 }
215             }
216         }
217     }
218
219     fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem) {
220     }
221
222     fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem) {
223     }
224 }