]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/lang_items.rs
Auto merge of #28539 - rkruppe:shuffle-num-internals, r=alexcrichton
[rust.git] / src / librustc / middle / lang_items.rs
1 // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 // Detecting language items.
12 //
13 // Language items are items that represent concepts intrinsic to the language
14 // itself. Examples are:
15 //
16 // * Traits that specify "kinds"; e.g. "Sync", "Send".
17 //
18 // * Traits that represent operators; e.g. "Add", "Sub", "Index".
19 //
20 // * Functions called by the compiler itself.
21
22 pub use self::LangItem::*;
23
24 use session::Session;
25 use metadata::csearch::each_lang_item;
26 use middle::def_id::DefId;
27 use middle::ty;
28 use middle::weak_lang_items;
29 use util::nodemap::FnvHashMap;
30
31 use syntax::ast;
32 use syntax::attr::AttrMetaMethods;
33 use syntax::codemap::{DUMMY_SP, Span};
34 use syntax::parse::token::InternedString;
35 use rustc_front::visit::Visitor;
36 use rustc_front::visit;
37 use rustc_front::hir;
38
39 use std::iter::Enumerate;
40 use std::slice;
41
42 // The actual lang items defined come at the end of this file in one handy table.
43 // So you probably just want to nip down to the end.
44 macro_rules! lets_do_this {
45     (
46         $( $variant:ident, $name:expr, $method:ident; )*
47     ) => {
48
49
50 enum_from_u32! {
51     #[derive(Copy, Clone, PartialEq, Eq, Hash)]
52     pub enum LangItem {
53         $($variant,)*
54     }
55 }
56
57 pub struct LanguageItems {
58     pub items: Vec<Option<DefId>>,
59     pub missing: Vec<LangItem>,
60 }
61
62 impl LanguageItems {
63     pub fn new() -> LanguageItems {
64         fn foo(_: LangItem) -> Option<DefId> { None }
65
66         LanguageItems {
67             items: vec!($(foo($variant)),*),
68             missing: Vec::new(),
69         }
70     }
71
72     pub fn items<'a>(&'a self) -> Enumerate<slice::Iter<'a, Option<DefId>>> {
73         self.items.iter().enumerate()
74     }
75
76     pub fn item_name(index: usize) -> &'static str {
77         let item: Option<LangItem> = LangItem::from_u32(index as u32);
78         match item {
79             $( Some($variant) => $name, )*
80             None => "???"
81         }
82     }
83
84     pub fn require(&self, it: LangItem) -> Result<DefId, String> {
85         match self.items[it as usize] {
86             Some(id) => Ok(id),
87             None => {
88                 Err(format!("requires `{}` lang_item",
89                             LanguageItems::item_name(it as usize)))
90             }
91         }
92     }
93
94     pub fn require_owned_box(&self) -> Result<DefId, String> {
95         self.require(OwnedBoxLangItem)
96     }
97
98     pub fn from_builtin_kind(&self, bound: ty::BuiltinBound)
99                              -> Result<DefId, String>
100     {
101         match bound {
102             ty::BoundSend => self.require(SendTraitLangItem),
103             ty::BoundSized => self.require(SizedTraitLangItem),
104             ty::BoundCopy => self.require(CopyTraitLangItem),
105             ty::BoundSync => self.require(SyncTraitLangItem),
106         }
107     }
108
109     pub fn to_builtin_kind(&self, id: DefId) -> Option<ty::BuiltinBound> {
110         if Some(id) == self.send_trait() {
111             Some(ty::BoundSend)
112         } else if Some(id) == self.sized_trait() {
113             Some(ty::BoundSized)
114         } else if Some(id) == self.copy_trait() {
115             Some(ty::BoundCopy)
116         } else if Some(id) == self.sync_trait() {
117             Some(ty::BoundSync)
118         } else {
119             None
120         }
121     }
122
123     pub fn fn_trait_kind(&self, id: DefId) -> Option<ty::ClosureKind> {
124         let def_id_kinds = [
125             (self.fn_trait(), ty::FnClosureKind),
126             (self.fn_mut_trait(), ty::FnMutClosureKind),
127             (self.fn_once_trait(), ty::FnOnceClosureKind),
128             ];
129
130         for &(opt_def_id, kind) in &def_id_kinds {
131             if Some(id) == opt_def_id {
132                 return Some(kind);
133             }
134         }
135
136         None
137     }
138
139     $(
140         #[allow(dead_code)]
141         pub fn $method(&self) -> Option<DefId> {
142             self.items[$variant as usize]
143         }
144     )*
145 }
146
147 struct LanguageItemCollector<'a> {
148     items: LanguageItems,
149
150     session: &'a Session,
151
152     item_refs: FnvHashMap<&'static str, usize>,
153 }
154
155 impl<'a, 'v> Visitor<'v> for LanguageItemCollector<'a> {
156     fn visit_item(&mut self, item: &hir::Item) {
157         if let Some(value) = extract(&item.attrs) {
158             let item_index = self.item_refs.get(&value[..]).cloned();
159
160             if let Some(item_index) = item_index {
161                 self.collect_item(item_index, DefId::local(item.id), item.span)
162             }
163         }
164
165         visit::walk_item(self, item);
166     }
167 }
168
169 impl<'a> LanguageItemCollector<'a> {
170     pub fn new(session: &'a Session) -> LanguageItemCollector<'a> {
171         let mut item_refs = FnvHashMap();
172
173         $( item_refs.insert($name, $variant as usize); )*
174
175         LanguageItemCollector {
176             session: session,
177             items: LanguageItems::new(),
178             item_refs: item_refs
179         }
180     }
181
182     pub fn collect_item(&mut self, item_index: usize,
183                         item_def_id: DefId, span: Span) {
184         // Check for duplicates.
185         match self.items.items[item_index] {
186             Some(original_def_id) if original_def_id != item_def_id => {
187                 span_err!(self.session, span, E0152,
188                     "duplicate entry for `{}`", LanguageItems::item_name(item_index));
189             }
190             Some(_) | None => {
191                 // OK.
192             }
193         }
194
195         // Matched.
196         self.items.items[item_index] = Some(item_def_id);
197     }
198
199     pub fn collect_local_language_items(&mut self, krate: &hir::Crate) {
200         visit::walk_crate(self, krate);
201     }
202
203     pub fn collect_external_language_items(&mut self) {
204         let crate_store = &self.session.cstore;
205         crate_store.iter_crate_data(|crate_number, _crate_metadata| {
206             each_lang_item(crate_store, crate_number, |node_id, item_index| {
207                 let def_id = DefId { krate: crate_number, node: node_id };
208                 self.collect_item(item_index, def_id, DUMMY_SP);
209                 true
210             });
211         })
212     }
213
214     pub fn collect(&mut self, krate: &hir::Crate) {
215         self.collect_local_language_items(krate);
216         self.collect_external_language_items();
217     }
218 }
219
220 pub fn extract(attrs: &[ast::Attribute]) -> Option<InternedString> {
221     for attribute in attrs {
222         match attribute.value_str() {
223             Some(ref value) if attribute.check_name("lang") => {
224                 return Some(value.clone());
225             }
226             _ => {}
227         }
228     }
229
230     return None;
231 }
232
233 pub fn collect_language_items(krate: &hir::Crate,
234                               session: &Session) -> LanguageItems {
235     let mut collector = LanguageItemCollector::new(session);
236     collector.collect(krate);
237     let LanguageItemCollector { mut items, .. } = collector;
238     weak_lang_items::check_crate(krate, session, &mut items);
239     session.abort_if_errors();
240     items
241 }
242
243 // End of the macro
244     }
245 }
246
247 lets_do_this! {
248 //  Variant name,                    Name,                      Method name;
249     CharImplItem,                    "char",                    char_impl;
250     StrImplItem,                     "str",                     str_impl;
251     SliceImplItem,                   "slice",                   slice_impl;
252     ConstPtrImplItem,                "const_ptr",               const_ptr_impl;
253     MutPtrImplItem,                  "mut_ptr",                 mut_ptr_impl;
254     I8ImplItem,                      "i8",                      i8_impl;
255     I16ImplItem,                     "i16",                     i16_impl;
256     I32ImplItem,                     "i32",                     i32_impl;
257     I64ImplItem,                     "i64",                     i64_impl;
258     IsizeImplItem,                   "isize",                   isize_impl;
259     U8ImplItem,                      "u8",                      u8_impl;
260     U16ImplItem,                     "u16",                     u16_impl;
261     U32ImplItem,                     "u32",                     u32_impl;
262     U64ImplItem,                     "u64",                     u64_impl;
263     UsizeImplItem,                   "usize",                   usize_impl;
264     F32ImplItem,                     "f32",                     f32_impl;
265     F64ImplItem,                     "f64",                     f64_impl;
266
267     SendTraitLangItem,               "send",                    send_trait;
268     SizedTraitLangItem,              "sized",                   sized_trait;
269     UnsizeTraitLangItem,             "unsize",                  unsize_trait;
270     CopyTraitLangItem,               "copy",                    copy_trait;
271     SyncTraitLangItem,               "sync",                    sync_trait;
272
273     DropTraitLangItem,               "drop",                    drop_trait;
274
275     CoerceUnsizedTraitLangItem,      "coerce_unsized",          coerce_unsized_trait;
276
277     AddTraitLangItem,                "add",                     add_trait;
278     SubTraitLangItem,                "sub",                     sub_trait;
279     MulTraitLangItem,                "mul",                     mul_trait;
280     DivTraitLangItem,                "div",                     div_trait;
281     RemTraitLangItem,                "rem",                     rem_trait;
282     NegTraitLangItem,                "neg",                     neg_trait;
283     NotTraitLangItem,                "not",                     not_trait;
284     BitXorTraitLangItem,             "bitxor",                  bitxor_trait;
285     BitAndTraitLangItem,             "bitand",                  bitand_trait;
286     BitOrTraitLangItem,              "bitor",                   bitor_trait;
287     ShlTraitLangItem,                "shl",                     shl_trait;
288     ShrTraitLangItem,                "shr",                     shr_trait;
289     AddAssignTraitLangItem,          "add_assign",              add_assign_trait;
290     SubAssignTraitLangItem,          "sub_assign",              sub_assign_trait;
291     MulAssignTraitLangItem,          "mul_assign",              mul_assign_trait;
292     DivAssignTraitLangItem,          "div_assign",              div_assign_trait;
293     RemAssignTraitLangItem,          "rem_assign",              rem_assign_trait;
294     BitXorAssignTraitLangItem,       "bitxor_assign",           bitxor_assign_trait;
295     BitAndAssignTraitLangItem,       "bitand_assign",           bitand_assign_trait;
296     BitOrAssignTraitLangItem,        "bitor_assign",            bitor_assign_trait;
297     ShlAssignTraitLangItem,          "shl_assign",              shl_assign_trait;
298     ShrAssignTraitLangItem,          "shr_assign",              shr_assign_trait;
299     IndexTraitLangItem,              "index",                   index_trait;
300     IndexMutTraitLangItem,           "index_mut",               index_mut_trait;
301     RangeStructLangItem,             "range",                   range_struct;
302     RangeFromStructLangItem,         "range_from",              range_from_struct;
303     RangeToStructLangItem,           "range_to",                range_to_struct;
304     RangeFullStructLangItem,         "range_full",              range_full_struct;
305
306     UnsafeCellTypeLangItem,          "unsafe_cell",             unsafe_cell_type;
307
308     DerefTraitLangItem,              "deref",                   deref_trait;
309     DerefMutTraitLangItem,           "deref_mut",               deref_mut_trait;
310
311     FnTraitLangItem,                 "fn",                      fn_trait;
312     FnMutTraitLangItem,              "fn_mut",                  fn_mut_trait;
313     FnOnceTraitLangItem,             "fn_once",                 fn_once_trait;
314
315     EqTraitLangItem,                 "eq",                      eq_trait;
316     OrdTraitLangItem,                "ord",                     ord_trait;
317
318     StrEqFnLangItem,                 "str_eq",                  str_eq_fn;
319
320     // A number of panic-related lang items. The `panic` item corresponds to
321     // divide-by-zero and various panic cases with `match`. The
322     // `panic_bounds_check` item is for indexing arrays.
323     //
324     // The `begin_unwind` lang item has a predefined symbol name and is sort of
325     // a "weak lang item" in the sense that a crate is not required to have it
326     // defined to use it, but a final product is required to define it
327     // somewhere. Additionally, there are restrictions on crates that use a weak
328     // lang item, but do not have it defined.
329     PanicFnLangItem,                 "panic",                   panic_fn;
330     PanicBoundsCheckFnLangItem,      "panic_bounds_check",      panic_bounds_check_fn;
331     PanicFmtLangItem,                "panic_fmt",               panic_fmt;
332
333     ExchangeMallocFnLangItem,        "exchange_malloc",         exchange_malloc_fn;
334     ExchangeFreeFnLangItem,          "exchange_free",           exchange_free_fn;
335     StrDupUniqFnLangItem,            "strdup_uniq",             strdup_uniq_fn;
336
337     StartFnLangItem,                 "start",                   start_fn;
338
339     EhPersonalityLangItem,           "eh_personality",          eh_personality;
340     EhPersonalityCatchLangItem,      "eh_personality_catch",    eh_personality_catch;
341     EhUnwindResumeLangItem,          "eh_unwind_resume",        eh_unwind_resume;
342     MSVCTryFilterLangItem,           "msvc_try_filter",         msvc_try_filter;
343
344     ExchangeHeapLangItem,            "exchange_heap",           exchange_heap;
345     OwnedBoxLangItem,                "owned_box",               owned_box;
346
347     PhantomDataItem,                 "phantom_data",            phantom_data;
348
349     // Deprecated:
350     CovariantTypeItem,               "covariant_type",          covariant_type;
351     ContravariantTypeItem,           "contravariant_type",      contravariant_type;
352     InvariantTypeItem,               "invariant_type",          invariant_type;
353     CovariantLifetimeItem,           "covariant_lifetime",      covariant_lifetime;
354     ContravariantLifetimeItem,       "contravariant_lifetime",  contravariant_lifetime;
355     InvariantLifetimeItem,           "invariant_lifetime",      invariant_lifetime;
356
357     NoCopyItem,                      "no_copy_bound",           no_copy_bound;
358
359     NonZeroItem,                     "non_zero",                non_zero;
360
361     DebugTraitLangItem,              "debug_trait",             debug_trait;
362 }