]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_passes/src/lang_items.rs
Rollup merge of #103124 - ldm0:nohard_tests, r=Mark-Simulacrum
[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::errors::{
12     DuplicateLangItem, IncorrectTarget, LangItemOnIncorrectTarget, UnknownLangItem,
13 };
14 use crate::weak_lang_items;
15
16 use rustc_hir as hir;
17 use rustc_hir::def::DefKind;
18 use rustc_hir::def_id::DefId;
19 use rustc_hir::lang_items::{extract, GenericRequirement, ITEM_REFS};
20 use rustc_hir::{HirId, LangItem, LanguageItems, Target};
21 use rustc_middle::ty::TyCtxt;
22 use rustc_session::cstore::ExternCrate;
23 use rustc_span::{symbol::kw::Empty, Span};
24
25 use rustc_middle::ty::query::Providers;
26
27 pub(crate) enum Duplicate {
28     Plain,
29     Crate,
30     CrateDepends,
31 }
32
33 struct LanguageItemCollector<'tcx> {
34     items: LanguageItems,
35     tcx: TyCtxt<'tcx>,
36 }
37
38 impl<'tcx> LanguageItemCollector<'tcx> {
39     fn new(tcx: TyCtxt<'tcx>) -> LanguageItemCollector<'tcx> {
40         LanguageItemCollector { tcx, items: LanguageItems::new() }
41     }
42
43     fn check_for_lang(&mut self, actual_target: Target, hir_id: HirId) {
44         let attrs = self.tcx.hir().attrs(hir_id);
45         if let Some((name, span)) = extract(&attrs) {
46             match ITEM_REFS.get(&name).cloned() {
47                 // Known lang item with attribute on correct target.
48                 Some((item_index, expected_target)) if actual_target == expected_target => {
49                     self.collect_item_extended(item_index, hir_id, span);
50                 }
51                 // Known lang item with attribute on incorrect target.
52                 Some((_, expected_target)) => {
53                     self.tcx.sess.emit_err(LangItemOnIncorrectTarget {
54                         span,
55                         name,
56                         expected_target,
57                         actual_target,
58                     });
59                 }
60                 // Unknown lang item.
61                 _ => {
62                     self.tcx.sess.emit_err(UnknownLangItem { span, name });
63                 }
64             }
65         }
66     }
67
68     fn collect_item(&mut self, item_index: usize, item_def_id: DefId) {
69         // Check for duplicates.
70         if let Some(original_def_id) = self.items.items[item_index] {
71             if original_def_id != item_def_id {
72                 let local_span = self.tcx.hir().span_if_local(item_def_id);
73                 let lang_item_name = LangItem::from_u32(item_index as u32).unwrap().name();
74                 let crate_name = self.tcx.crate_name(item_def_id.krate);
75                 let mut dependency_of = Empty;
76                 let is_local = item_def_id.is_local();
77                 let path = if is_local {
78                     String::new()
79                 } else {
80                     self.tcx
81                         .crate_extern_paths(item_def_id.krate)
82                         .iter()
83                         .map(|p| p.display().to_string())
84                         .collect::<Vec<_>>()
85                         .join(", ")
86                         .into()
87                 };
88                 let first_defined_span = self.tcx.hir().span_if_local(original_def_id);
89                 let mut orig_crate_name = Empty;
90                 let mut orig_dependency_of = Empty;
91                 let orig_is_local = original_def_id.is_local();
92                 let orig_path = if orig_is_local {
93                     String::new()
94                 } else {
95                     self.tcx
96                         .crate_extern_paths(original_def_id.krate)
97                         .iter()
98                         .map(|p| p.display().to_string())
99                         .collect::<Vec<_>>()
100                         .join(", ")
101                         .into()
102                 };
103                 if first_defined_span.is_none() {
104                     orig_crate_name = self.tcx.crate_name(original_def_id.krate);
105                     if let Some(ExternCrate { dependency_of: inner_dependency_of, .. }) =
106                         self.tcx.extern_crate(original_def_id)
107                     {
108                         orig_dependency_of = self.tcx.crate_name(*inner_dependency_of);
109                     }
110                 }
111
112                 let duplicate = if local_span.is_some() {
113                     Duplicate::Plain
114                 } else {
115                     match self.tcx.extern_crate(item_def_id) {
116                         Some(ExternCrate { dependency_of: inner_dependency_of, .. }) => {
117                             dependency_of = self.tcx.crate_name(*inner_dependency_of);
118                             Duplicate::CrateDepends
119                         }
120                         _ => Duplicate::Crate,
121                     }
122                 };
123
124                 self.tcx.sess.emit_err(DuplicateLangItem {
125                     local_span,
126                     lang_item_name,
127                     crate_name,
128                     dependency_of,
129                     is_local,
130                     path,
131                     first_defined_span,
132                     orig_crate_name,
133                     orig_dependency_of,
134                     orig_is_local,
135                     orig_path,
136                     duplicate,
137                 });
138             }
139         }
140
141         // Matched.
142         self.items.items[item_index] = Some(item_def_id);
143         if let Some(group) = LangItem::from_u32(item_index as u32).unwrap().group() {
144             self.items.groups[group as usize].push(item_def_id);
145         }
146     }
147
148     // Like collect_item() above, but also checks whether the lang item is declared
149     // with the right number of generic arguments.
150     fn collect_item_extended(&mut self, item_index: usize, hir_id: HirId, span: Span) {
151         let item_def_id = self.tcx.hir().local_def_id(hir_id).to_def_id();
152         let lang_item = LangItem::from_u32(item_index as u32).unwrap();
153         let name = lang_item.name();
154
155         // Now check whether the lang_item has the expected number of generic
156         // arguments. Generally speaking, binary and indexing operations have
157         // one (for the RHS/index), unary operations have none, the closure
158         // traits have one for the argument list, generators have one for the
159         // resume argument, and ordering/equality relations have one for the RHS
160         // Some other types like Box and various functions like drop_in_place
161         // have minimum requirements.
162
163         if let hir::Node::Item(hir::Item { kind, span: item_span, .. }) = self.tcx.hir().get(hir_id)
164         {
165             let (actual_num, generics_span) = match kind.generics() {
166                 Some(generics) => (generics.params.len(), generics.span),
167                 None => (0, *item_span),
168             };
169
170             let mut at_least = false;
171             let required = match lang_item.required_generics() {
172                 GenericRequirement::Exact(num) if num != actual_num => Some(num),
173                 GenericRequirement::Minimum(num) if actual_num < num => {
174                     at_least = true;
175                     Some(num)}
176                 ,
177                 // If the number matches, or there is no requirement, handle it normally
178                 _ => None,
179             };
180
181             if let Some(num) = required {
182                 // We are issuing E0718 "incorrect target" here, because while the
183                 // item kind of the target is correct, the target is still wrong
184                 // because of the wrong number of generic arguments.
185                 self.tcx.sess.emit_err(IncorrectTarget {
186                     span,
187                     generics_span,
188                     name: name.as_str(),
189                     kind: kind.descr(),
190                     num,
191                     actual_num,
192                     at_least,
193                 });
194
195                 // return early to not collect the lang item
196                 return;
197             }
198         }
199
200         self.collect_item(item_index, item_def_id);
201     }
202 }
203
204 /// Traverses and collects all the lang items in all crates.
205 fn get_lang_items(tcx: TyCtxt<'_>, (): ()) -> LanguageItems {
206     // Initialize the collector.
207     let mut collector = LanguageItemCollector::new(tcx);
208
209     // Collect lang items in other crates.
210     for &cnum in tcx.crates(()).iter() {
211         for &(def_id, item_index) in tcx.defined_lang_items(cnum).iter() {
212             collector.collect_item(item_index, def_id);
213         }
214     }
215
216     // Collect lang items in this crate.
217     let crate_items = tcx.hir_crate_items(());
218
219     for id in crate_items.items() {
220         collector.check_for_lang(Target::from_def_kind(tcx.def_kind(id.owner_id)), id.hir_id());
221
222         if matches!(tcx.def_kind(id.owner_id), DefKind::Enum) {
223             let item = tcx.hir().item(id);
224             if let hir::ItemKind::Enum(def, ..) = &item.kind {
225                 for variant in def.variants {
226                     collector.check_for_lang(Target::Variant, variant.id);
227                 }
228             }
229         }
230     }
231
232     // FIXME: avoid calling trait_item() when possible
233     for id in crate_items.trait_items() {
234         let item = tcx.hir().trait_item(id);
235         collector.check_for_lang(Target::from_trait_item(item), item.hir_id())
236     }
237
238     // FIXME: avoid calling impl_item() when possible
239     for id in crate_items.impl_items() {
240         let item = tcx.hir().impl_item(id);
241         collector.check_for_lang(target_from_impl_item(tcx, item), item.hir_id())
242     }
243
244     // Extract out the found lang items.
245     let LanguageItemCollector { mut items, .. } = collector;
246
247     // Find all required but not-yet-defined lang items.
248     weak_lang_items::check_crate(tcx, &mut items);
249
250     items
251 }
252
253 pub fn provide(providers: &mut Providers) {
254     providers.get_lang_items = get_lang_items;
255 }