]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/lang_items.rs
librustc: Add NonZero lang item and use it if possible for nullable pointer enum...
[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::ty;
27 use middle::weak_lang_items;
28 use util::nodemap::FnvHashMap;
29
30 use syntax::ast;
31 use syntax::ast_util::local_def;
32 use syntax::attr::AttrMetaMethods;
33 use syntax::codemap::{DUMMY_SP, Span};
34 use syntax::parse::token::InternedString;
35 use syntax::visit::Visitor;
36 use syntax::visit;
37
38 use std::iter::Enumerate;
39 use std::slice;
40
41 // The actual lang items defined come at the end of this file in one handy table.
42 // So you probably just want to nip down to the end.
43 macro_rules! lets_do_this {
44     (
45         $( $variant:ident, $name:expr, $method:ident; )*
46     ) => {
47
48 #[deriving(Copy, FromPrimitive, PartialEq, Eq, Hash)]
49 pub enum LangItem {
50     $($variant),*
51 }
52
53 pub struct LanguageItems {
54     pub items: Vec<Option<ast::DefId>>,
55     pub missing: Vec<LangItem>,
56 }
57
58 impl LanguageItems {
59     pub fn new() -> LanguageItems {
60         fn foo(_: LangItem) -> Option<ast::DefId> { None }
61
62         LanguageItems {
63             items: vec!($(foo($variant)),*),
64             missing: Vec::new(),
65         }
66     }
67
68     pub fn items<'a>(&'a self) -> Enumerate<slice::Iter<'a, Option<ast::DefId>>> {
69         self.items.iter().enumerate()
70     }
71
72     pub fn item_name(index: uint) -> &'static str {
73         let item: Option<LangItem> = FromPrimitive::from_uint(index);
74         match item {
75             $( Some($variant) => $name, )*
76             None => "???"
77         }
78     }
79
80     pub fn require(&self, it: LangItem) -> Result<ast::DefId, String> {
81         match self.items[it as uint] {
82             Some(id) => Ok(id),
83             None => {
84                 Err(format!("requires `{}` lang_item",
85                             LanguageItems::item_name(it as uint)))
86             }
87         }
88     }
89
90     pub fn from_builtin_kind(&self, bound: ty::BuiltinBound)
91                              -> Result<ast::DefId, String>
92     {
93         match bound {
94             ty::BoundSend => self.require(SendTraitLangItem),
95             ty::BoundSized => self.require(SizedTraitLangItem),
96             ty::BoundCopy => self.require(CopyTraitLangItem),
97             ty::BoundSync => self.require(SyncTraitLangItem),
98         }
99     }
100
101     pub fn to_builtin_kind(&self, id: ast::DefId) -> Option<ty::BuiltinBound> {
102         if Some(id) == self.send_trait() {
103             Some(ty::BoundSend)
104         } else if Some(id) == self.sized_trait() {
105             Some(ty::BoundSized)
106         } else if Some(id) == self.copy_trait() {
107             Some(ty::BoundCopy)
108         } else if Some(id) == self.sync_trait() {
109             Some(ty::BoundSync)
110         } else {
111             None
112         }
113     }
114
115     pub fn fn_trait_kind(&self, id: ast::DefId) -> Option<ty::UnboxedClosureKind> {
116         let def_id_kinds = [
117             (self.fn_trait(), ty::FnUnboxedClosureKind),
118             (self.fn_mut_trait(), ty::FnMutUnboxedClosureKind),
119             (self.fn_once_trait(), ty::FnOnceUnboxedClosureKind),
120             ];
121
122         for &(opt_def_id, kind) in def_id_kinds.iter() {
123             if Some(id) == opt_def_id {
124                 return Some(kind);
125             }
126         }
127
128         None
129     }
130
131     $(
132         #[allow(dead_code)]
133         pub fn $method(&self) -> Option<ast::DefId> {
134             self.items[$variant as uint]
135         }
136     )*
137 }
138
139 struct LanguageItemCollector<'a> {
140     items: LanguageItems,
141
142     session: &'a Session,
143
144     item_refs: FnvHashMap<&'static str, uint>,
145 }
146
147 impl<'a, 'v> Visitor<'v> for LanguageItemCollector<'a> {
148     fn visit_item(&mut self, item: &ast::Item) {
149         match extract(item.attrs.as_slice()) {
150             Some(value) => {
151                 let item_index = self.item_refs.get(value.get()).map(|x| *x);
152
153                 match item_index {
154                     Some(item_index) => {
155                         self.collect_item(item_index, local_def(item.id), item.span)
156                     }
157                     None => {}
158                 }
159             }
160             None => {}
161         }
162
163         visit::walk_item(self, item);
164     }
165 }
166
167 impl<'a> LanguageItemCollector<'a> {
168     pub fn new(session: &'a Session) -> LanguageItemCollector<'a> {
169         let mut item_refs = FnvHashMap::new();
170
171         $( item_refs.insert($name, $variant as uint); )*
172
173         LanguageItemCollector {
174             session: session,
175             items: LanguageItems::new(),
176             item_refs: item_refs
177         }
178     }
179
180     pub fn collect_item(&mut self, item_index: uint,
181                         item_def_id: ast::DefId, span: Span) {
182         // Check for duplicates.
183         match self.items.items[item_index] {
184             Some(original_def_id) if original_def_id != item_def_id => {
185                 span_err!(self.session, span, E0152,
186                     "duplicate entry for `{}`", LanguageItems::item_name(item_index));
187             }
188             Some(_) | None => {
189                 // OK.
190             }
191         }
192
193         // Matched.
194         self.items.items[item_index] = Some(item_def_id);
195     }
196
197     pub fn collect_local_language_items(&mut self, krate: &ast::Crate) {
198         visit::walk_crate(self, krate);
199     }
200
201     pub fn collect_external_language_items(&mut self) {
202         let crate_store = &self.session.cstore;
203         crate_store.iter_crate_data(|crate_number, _crate_metadata| {
204             each_lang_item(crate_store, crate_number, |node_id, item_index| {
205                 let def_id = ast::DefId { krate: crate_number, node: node_id };
206                 self.collect_item(item_index, def_id, DUMMY_SP);
207                 true
208             });
209         })
210     }
211
212     pub fn collect(&mut self, krate: &ast::Crate) {
213         self.collect_local_language_items(krate);
214         self.collect_external_language_items();
215     }
216 }
217
218 pub fn extract(attrs: &[ast::Attribute]) -> Option<InternedString> {
219     for attribute in attrs.iter() {
220         match attribute.value_str() {
221             Some(ref value) if attribute.check_name("lang") => {
222                 return Some(value.clone());
223             }
224             _ => {}
225         }
226     }
227
228     return None;
229 }
230
231 pub fn collect_language_items(krate: &ast::Crate,
232                               session: &Session) -> LanguageItems {
233     let mut collector = LanguageItemCollector::new(session);
234     collector.collect(krate);
235     let LanguageItemCollector { mut items, .. } = collector;
236     weak_lang_items::check_crate(krate, session, &mut items);
237     session.abort_if_errors();
238     items
239 }
240
241 // End of the macro
242     }
243 }
244
245 lets_do_this! {
246 //  Variant name,                    Name,                      Method name;
247     SendTraitLangItem,               "send",                    send_trait;
248     SizedTraitLangItem,              "sized",                   sized_trait;
249     CopyTraitLangItem,               "copy",                    copy_trait;
250     SyncTraitLangItem,               "sync",                    sync_trait;
251
252     DropTraitLangItem,               "drop",                    drop_trait;
253
254     AddTraitLangItem,                "add",                     add_trait;
255     SubTraitLangItem,                "sub",                     sub_trait;
256     MulTraitLangItem,                "mul",                     mul_trait;
257     DivTraitLangItem,                "div",                     div_trait;
258     RemTraitLangItem,                "rem",                     rem_trait;
259     NegTraitLangItem,                "neg",                     neg_trait;
260     NotTraitLangItem,                "not",                     not_trait;
261     BitXorTraitLangItem,             "bitxor",                  bitxor_trait;
262     BitAndTraitLangItem,             "bitand",                  bitand_trait;
263     BitOrTraitLangItem,              "bitor",                   bitor_trait;
264     ShlTraitLangItem,                "shl",                     shl_trait;
265     ShrTraitLangItem,                "shr",                     shr_trait;
266     IndexTraitLangItem,              "index",                   index_trait;
267     IndexMutTraitLangItem,           "index_mut",               index_mut_trait;
268     SliceTraitLangItem,              "slice",                   slice_trait;
269     SliceMutTraitLangItem,           "slice_mut",               slice_mut_trait;
270     RangeStructLangItem,             "range",                   range_struct;
271     RangeFromStructLangItem,         "range_from",              range_from_struct;
272     FullRangeStructLangItem,         "full_range",              full_range_struct;
273
274     UnsafeTypeLangItem,              "unsafe",                  unsafe_type;
275
276     DerefTraitLangItem,              "deref",                   deref_trait;
277     DerefMutTraitLangItem,           "deref_mut",               deref_mut_trait;
278
279     FnTraitLangItem,                 "fn",                      fn_trait;
280     FnMutTraitLangItem,              "fn_mut",                  fn_mut_trait;
281     FnOnceTraitLangItem,             "fn_once",                 fn_once_trait;
282
283     EqTraitLangItem,                 "eq",                      eq_trait;
284     OrdTraitLangItem,                "ord",                     ord_trait;
285
286     StrEqFnLangItem,                 "str_eq",                  str_eq_fn;
287
288     // A number of panic-related lang items. The `panic` item corresponds to
289     // divide-by-zero and various panic cases with `match`. The
290     // `panic_bounds_check` item is for indexing arrays.
291     //
292     // The `begin_unwind` lang item has a predefined symbol name and is sort of
293     // a "weak lang item" in the sense that a crate is not required to have it
294     // defined to use it, but a final product is required to define it
295     // somewhere. Additionally, there are restrictions on crates that use a weak
296     // lang item, but do not have it defined.
297     PanicFnLangItem,                 "panic",                   panic_fn;
298     PanicBoundsCheckFnLangItem,      "panic_bounds_check",      panic_bounds_check_fn;
299     PanicFmtLangItem,                "panic_fmt",               panic_fmt;
300
301     ExchangeMallocFnLangItem,        "exchange_malloc",         exchange_malloc_fn;
302     ExchangeFreeFnLangItem,          "exchange_free",           exchange_free_fn;
303     StrDupUniqFnLangItem,            "strdup_uniq",             strdup_uniq_fn;
304
305     StartFnLangItem,                 "start",                   start_fn;
306
307     TyDescStructLangItem,            "ty_desc",                 ty_desc;
308     OpaqueStructLangItem,            "opaque",                  opaque;
309
310     TypeIdLangItem,                  "type_id",                 type_id;
311
312     EhPersonalityLangItem,           "eh_personality",          eh_personality;
313
314     ExchangeHeapLangItem,            "exchange_heap",           exchange_heap;
315     OwnedBoxLangItem,                "owned_box",               owned_box;
316
317     CovariantTypeItem,               "covariant_type",          covariant_type;
318     ContravariantTypeItem,           "contravariant_type",      contravariant_type;
319     InvariantTypeItem,               "invariant_type",          invariant_type;
320
321     CovariantLifetimeItem,           "covariant_lifetime",      covariant_lifetime;
322     ContravariantLifetimeItem,       "contravariant_lifetime",  contravariant_lifetime;
323     InvariantLifetimeItem,           "invariant_lifetime",      invariant_lifetime;
324
325     NoSendItem,                      "no_send_bound",           no_send_bound;
326     NoCopyItem,                      "no_copy_bound",           no_copy_bound;
327     NoSyncItem,                      "no_sync_bound",           no_sync_bound;
328     ManagedItem,                     "managed_bound",           managed_bound;
329
330     NonZeroItem,                     "non_zero",                non_zero;
331
332     IteratorItem,                    "iterator",                iterator;
333
334     StackExhaustedLangItem,          "stack_exhausted",         stack_exhausted;
335 }