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