]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_passes/src/lang_items.rs
separate definitions and `HIR` owners
[rust.git] / compiler / rustc_passes / src / lang_items.rs
1 //! Detecting language items.
2 //!
3 //! Language items are items that represent concepts intrinsic to the language
4 //! itself. Examples are:
5 //!
6 //! * Traits that specify "kinds"; e.g., `Sync`, `Send`.
7 //! * Traits that represent operators; e.g., `Add`, `Sub`, `Index`.
8 //! * Functions called by the compiler itself.
9
10 use crate::check_attr::target_from_impl_item;
11 use crate::weak_lang_items;
12
13 use rustc_errors::{pluralize, struct_span_err};
14 use rustc_hir as hir;
15 use rustc_hir::def::DefKind;
16 use rustc_hir::def_id::DefId;
17 use rustc_hir::lang_items::{extract, GenericRequirement, ITEM_REFS};
18 use rustc_hir::{HirId, LangItem, LanguageItems, Target};
19 use rustc_middle::ty::TyCtxt;
20 use rustc_session::cstore::ExternCrate;
21 use rustc_span::Span;
22
23 use rustc_middle::ty::query::Providers;
24
25 struct LanguageItemCollector<'tcx> {
26     items: LanguageItems,
27     tcx: TyCtxt<'tcx>,
28 }
29
30 impl<'tcx> LanguageItemCollector<'tcx> {
31     fn new(tcx: TyCtxt<'tcx>) -> LanguageItemCollector<'tcx> {
32         LanguageItemCollector { tcx, items: LanguageItems::new() }
33     }
34
35     fn check_for_lang(&mut self, actual_target: Target, hir_id: HirId) {
36         let attrs = self.tcx.hir().attrs(hir_id);
37         if let Some((value, span)) = extract(&attrs) {
38             match ITEM_REFS.get(&value).cloned() {
39                 // Known lang item with attribute on correct target.
40                 Some((item_index, expected_target)) if actual_target == expected_target => {
41                     self.collect_item_extended(item_index, hir_id, span);
42                 }
43                 // Known lang item with attribute on incorrect target.
44                 Some((_, expected_target)) => {
45                     struct_span_err!(
46                         self.tcx.sess,
47                         span,
48                         E0718,
49                         "`{}` language item must be applied to a {}",
50                         value,
51                         expected_target,
52                     )
53                     .span_label(
54                         span,
55                         format!(
56                             "attribute should be applied to a {}, not a {}",
57                             expected_target, actual_target,
58                         ),
59                     )
60                     .emit();
61                 }
62                 // Unknown lang item.
63                 _ => {
64                     struct_span_err!(
65                         self.tcx.sess,
66                         span,
67                         E0522,
68                         "definition of an unknown language item: `{}`",
69                         value
70                     )
71                     .span_label(span, format!("definition of unknown language item `{}`", value))
72                     .emit();
73                 }
74             }
75         }
76     }
77
78     fn collect_item(&mut self, item_index: usize, item_def_id: DefId) {
79         // Check for duplicates.
80         if let Some(original_def_id) = self.items.items[item_index] {
81             if original_def_id != item_def_id {
82                 let lang_item = LangItem::from_u32(item_index as u32).unwrap();
83                 let name = lang_item.name();
84                 let mut err = match self.tcx.hir().span_if_local(item_def_id) {
85                     Some(span) => struct_span_err!(
86                         self.tcx.sess,
87                         span,
88                         E0152,
89                         "found duplicate lang item `{}`",
90                         name
91                     ),
92                     None => match self.tcx.extern_crate(item_def_id) {
93                         Some(ExternCrate { dependency_of, .. }) => {
94                             self.tcx.sess.struct_err(&format!(
95                                 "duplicate lang item in crate `{}` (which `{}` depends on): `{}`.",
96                                 self.tcx.crate_name(item_def_id.krate),
97                                 self.tcx.crate_name(*dependency_of),
98                                 name
99                             ))
100                         }
101                         _ => self.tcx.sess.struct_err(&format!(
102                             "duplicate lang item in crate `{}`: `{}`.",
103                             self.tcx.crate_name(item_def_id.krate),
104                             name
105                         )),
106                     },
107                 };
108                 if let Some(span) = self.tcx.hir().span_if_local(original_def_id) {
109                     err.span_note(span, "the lang item is first defined here");
110                 } else {
111                     match self.tcx.extern_crate(original_def_id) {
112                         Some(ExternCrate { dependency_of, .. }) => {
113                             err.note(&format!(
114                                 "the lang item is first defined in crate `{}` (which `{}` depends on)",
115                                 self.tcx.crate_name(original_def_id.krate),
116                                 self.tcx.crate_name(*dependency_of)
117                             ));
118                         }
119                         _ => {
120                             err.note(&format!(
121                                 "the lang item is first defined in crate `{}`.",
122                                 self.tcx.crate_name(original_def_id.krate)
123                             ));
124                         }
125                     }
126                     let mut note_def = |which, def_id: DefId| {
127                         let crate_name = self.tcx.crate_name(def_id.krate);
128                         let note = if def_id.is_local() {
129                             format!("{} definition in the local crate (`{}`)", which, crate_name)
130                         } else {
131                             let paths: Vec<_> = self
132                                 .tcx
133                                 .crate_extern_paths(def_id.krate)
134                                 .iter()
135                                 .map(|p| p.display().to_string())
136                                 .collect();
137                             format!(
138                                 "{} definition in `{}` loaded from {}",
139                                 which,
140                                 crate_name,
141                                 paths.join(", ")
142                             )
143                         };
144                         err.note(&note);
145                     };
146                     note_def("first", original_def_id);
147                     note_def("second", item_def_id);
148                 }
149                 err.emit();
150             }
151         }
152
153         // Matched.
154         self.items.items[item_index] = Some(item_def_id);
155         if let Some(group) = LangItem::from_u32(item_index as u32).unwrap().group() {
156             self.items.groups[group as usize].push(item_def_id);
157         }
158     }
159
160     // Like collect_item() above, but also checks whether the lang item is declared
161     // with the right number of generic arguments.
162     fn collect_item_extended(&mut self, item_index: usize, hir_id: HirId, span: Span) {
163         let item_def_id = self.tcx.hir().local_def_id(hir_id).to_def_id();
164         let lang_item = LangItem::from_u32(item_index as u32).unwrap();
165         let name = lang_item.name();
166
167         // Now check whether the lang_item has the expected number of generic
168         // arguments. Generally speaking, binary and indexing operations have
169         // one (for the RHS/index), unary operations have none, the closure
170         // traits have one for the argument list, generators have one for the
171         // resume argument, and ordering/equality relations have one for the RHS
172         // Some other types like Box and various functions like drop_in_place
173         // have minimum requirements.
174
175         if let hir::Node::Item(hir::Item { kind, span: item_span, .. }) = self.tcx.hir().get(hir_id)
176         {
177             let (actual_num, generics_span) = match kind.generics() {
178                 Some(generics) => (generics.params.len(), generics.span),
179                 None => (0, *item_span),
180             };
181
182             let required = match lang_item.required_generics() {
183                 GenericRequirement::Exact(num) if num != actual_num => {
184                     Some((format!("{}", num), pluralize!(num)))
185                 }
186                 GenericRequirement::Minimum(num) if actual_num < num => {
187                     Some((format!("at least {}", num), pluralize!(num)))
188                 }
189                 // If the number matches, or there is no requirement, handle it normally
190                 _ => None,
191             };
192
193             if let Some((range_str, pluralized)) = required {
194                 // We are issuing E0718 "incorrect target" here, because while the
195                 // item kind of the target is correct, the target is still wrong
196                 // because of the wrong number of generic arguments.
197                 struct_span_err!(
198                     self.tcx.sess,
199                     span,
200                     E0718,
201                     "`{}` language item must be applied to a {} with {} generic argument{}",
202                     name,
203                     kind.descr(),
204                     range_str,
205                     pluralized,
206                 )
207                 .span_label(
208                     generics_span,
209                     format!(
210                         "this {} has {} generic argument{}",
211                         kind.descr(),
212                         actual_num,
213                         pluralize!(actual_num),
214                     ),
215                 )
216                 .emit();
217
218                 // return early to not collect the lang item
219                 return;
220             }
221         }
222
223         self.collect_item(item_index, item_def_id);
224     }
225 }
226
227 /// Traverses and collects all the lang items in all crates.
228 fn get_lang_items(tcx: TyCtxt<'_>, (): ()) -> LanguageItems {
229     // Initialize the collector.
230     let mut collector = LanguageItemCollector::new(tcx);
231
232     // Collect lang items in other crates.
233     for &cnum in tcx.crates(()).iter() {
234         for &(def_id, item_index) in tcx.defined_lang_items(cnum).iter() {
235             collector.collect_item(item_index, def_id);
236         }
237     }
238
239     // Collect lang items in this crate.
240     let crate_items = tcx.hir_crate_items(());
241
242     for id in crate_items.items() {
243         collector.check_for_lang(Target::from_def_kind(tcx.def_kind(id.def_id)), id.hir_id());
244
245         if matches!(tcx.def_kind(id.def_id), DefKind::Enum) {
246             let item = tcx.hir().item(id);
247             if let hir::ItemKind::Enum(def, ..) = &item.kind {
248                 for variant in def.variants {
249                     collector.check_for_lang(Target::Variant, variant.id);
250                 }
251             }
252         }
253     }
254
255     // FIXME: avoid calling trait_item() when possible
256     for id in crate_items.trait_items() {
257         let item = tcx.hir().trait_item(id);
258         collector.check_for_lang(Target::from_trait_item(item), item.hir_id())
259     }
260
261     // FIXME: avoid calling impl_item() when possible
262     for id in crate_items.impl_items() {
263         let item = tcx.hir().impl_item(id);
264         collector.check_for_lang(target_from_impl_item(tcx, item), item.hir_id())
265     }
266
267     // Extract out the found lang items.
268     let LanguageItemCollector { mut items, .. } = collector;
269
270     // Find all required but not-yet-defined lang items.
271     weak_lang_items::check_crate(tcx, &mut items);
272
273     items
274 }
275
276 pub fn provide(providers: &mut Providers) {
277     providers.get_lang_items = get_lang_items;
278 }