]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/lang_items.rs
librustc: Implement overloading for the call operator behind a feature
[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. "Share", "Send".
17 //
18 // * Traits that represent operators; e.g. "Add", "Sub", "Index".
19 //
20 // * Functions called by the compiler itself.
21
22
23 use driver::session::Session;
24 use metadata::csearch::each_lang_item;
25 use middle::ty;
26 use middle::weak_lang_items;
27 use syntax::ast;
28 use syntax::ast_util::local_def;
29 use syntax::attr::AttrMetaMethods;
30 use syntax::parse::token::InternedString;
31 use syntax::visit::Visitor;
32 use syntax::visit;
33
34 use std::collections::HashMap;
35 use std::iter::Enumerate;
36 use std::slice;
37
38 // The actual lang items defined come at the end of this file in one handy table.
39 // So you probably just want to nip down to the end.
40 macro_rules! lets_do_this {
41     (
42         $( $variant:ident, $name:expr, $method:ident; )*
43     ) => {
44
45 #[deriving(FromPrimitive, PartialEq, Eq, Hash)]
46 pub enum LangItem {
47     $($variant),*
48 }
49
50 pub struct LanguageItems {
51     pub items: Vec<Option<ast::DefId>>,
52     pub missing: Vec<LangItem>,
53 }
54
55 impl LanguageItems {
56     pub fn new() -> LanguageItems {
57         fn foo(_: LangItem) -> Option<ast::DefId> { None }
58
59         LanguageItems {
60             items: vec!($(foo($variant)),*),
61             missing: Vec::new(),
62         }
63     }
64
65     pub fn items<'a>(&'a self) -> Enumerate<slice::Items<'a, Option<ast::DefId>>> {
66         self.items.iter().enumerate()
67     }
68
69     pub fn item_name(index: uint) -> &'static str {
70         let item: Option<LangItem> = FromPrimitive::from_uint(index);
71         match item {
72             $( Some($variant) => $name, )*
73             None => "???"
74         }
75     }
76
77     pub fn require(&self, it: LangItem) -> Result<ast::DefId, String> {
78         match self.items.get(it as uint) {
79             &Some(id) => Ok(id),
80             &None => {
81                 Err(format!("requires `{}` lang_item",
82                             LanguageItems::item_name(it as uint)))
83             }
84         }
85     }
86
87     pub fn to_builtin_kind(&self, id: ast::DefId) -> Option<ty::BuiltinBound> {
88         if Some(id) == self.send_trait() {
89             Some(ty::BoundSend)
90         } else if Some(id) == self.sized_trait() {
91             Some(ty::BoundSized)
92         } else if Some(id) == self.copy_trait() {
93             Some(ty::BoundCopy)
94         } else if Some(id) == self.share_trait() {
95             Some(ty::BoundShare)
96         } else {
97             None
98         }
99     }
100
101     $(
102         #[allow(dead_code)]
103         pub fn $method(&self) -> Option<ast::DefId> {
104             *self.items.get($variant as uint)
105         }
106     )*
107 }
108
109 struct LanguageItemCollector<'a> {
110     items: LanguageItems,
111
112     session: &'a Session,
113
114     item_refs: HashMap<&'static str, uint>,
115 }
116
117 impl<'a> Visitor<()> for LanguageItemCollector<'a> {
118     fn visit_item(&mut self, item: &ast::Item, _: ()) {
119         match extract(item.attrs.as_slice()) {
120             Some(value) => {
121                 let item_index = self.item_refs.find_equiv(&value).map(|x| *x);
122
123                 match item_index {
124                     Some(item_index) => {
125                         self.collect_item(item_index, local_def(item.id))
126                     }
127                     None => {}
128                 }
129             }
130             None => {}
131         }
132
133         visit::walk_item(self, item, ());
134     }
135 }
136
137 impl<'a> LanguageItemCollector<'a> {
138     pub fn new(session: &'a Session) -> LanguageItemCollector<'a> {
139         let mut item_refs = HashMap::new();
140
141         $( item_refs.insert($name, $variant as uint); )*
142
143         LanguageItemCollector {
144             session: session,
145             items: LanguageItems::new(),
146             item_refs: item_refs
147         }
148     }
149
150     pub fn collect_item(&mut self, item_index: uint, item_def_id: ast::DefId) {
151         // Check for duplicates.
152         match self.items.items.get(item_index) {
153             &Some(original_def_id) if original_def_id != item_def_id => {
154                 self.session.err(format!("duplicate entry for `{}`",
155                                          LanguageItems::item_name(
156                                              item_index)).as_slice());
157             }
158             &Some(_) | &None => {
159                 // OK.
160             }
161         }
162
163         // Matched.
164         *self.items.items.get_mut(item_index) = Some(item_def_id);
165     }
166
167     pub fn collect_local_language_items(&mut self, krate: &ast::Crate) {
168         visit::walk_crate(self, krate, ());
169     }
170
171     pub fn collect_external_language_items(&mut self) {
172         let crate_store = &self.session.cstore;
173         crate_store.iter_crate_data(|crate_number, _crate_metadata| {
174             each_lang_item(crate_store, crate_number, |node_id, item_index| {
175                 let def_id = ast::DefId { krate: crate_number, node: node_id };
176                 self.collect_item(item_index, def_id);
177                 true
178             });
179         })
180     }
181
182     pub fn collect(&mut self, krate: &ast::Crate) {
183         self.collect_local_language_items(krate);
184         self.collect_external_language_items();
185     }
186 }
187
188 pub fn extract(attrs: &[ast::Attribute]) -> Option<InternedString> {
189     for attribute in attrs.iter() {
190         match attribute.value_str() {
191             Some(ref value) if attribute.check_name("lang") => {
192                 return Some(value.clone());
193             }
194             _ => {}
195         }
196     }
197
198     return None;
199 }
200
201 pub fn collect_language_items(krate: &ast::Crate,
202                               session: &Session) -> LanguageItems {
203     let mut collector = LanguageItemCollector::new(session);
204     collector.collect(krate);
205     let LanguageItemCollector { mut items, .. } = collector;
206     weak_lang_items::check_crate(krate, session, &mut items);
207     session.abort_if_errors();
208     items
209 }
210
211 // End of the macro
212     }
213 }
214
215 lets_do_this! {
216 //  Variant name,                    Name,                      Method name;
217     SendTraitLangItem,               "send",                    send_trait;
218     SizedTraitLangItem,              "sized",                   sized_trait;
219     CopyTraitLangItem,               "copy",                    copy_trait;
220     ShareTraitLangItem,              "share",                   share_trait;
221
222     DropTraitLangItem,               "drop",                    drop_trait;
223
224     AddTraitLangItem,                "add",                     add_trait;
225     SubTraitLangItem,                "sub",                     sub_trait;
226     MulTraitLangItem,                "mul",                     mul_trait;
227     DivTraitLangItem,                "div",                     div_trait;
228     RemTraitLangItem,                "rem",                     rem_trait;
229     NegTraitLangItem,                "neg",                     neg_trait;
230     NotTraitLangItem,                "not",                     not_trait;
231     BitXorTraitLangItem,             "bitxor",                  bitxor_trait;
232     BitAndTraitLangItem,             "bitand",                  bitand_trait;
233     BitOrTraitLangItem,              "bitor",                   bitor_trait;
234     ShlTraitLangItem,                "shl",                     shl_trait;
235     ShrTraitLangItem,                "shr",                     shr_trait;
236     IndexTraitLangItem,              "index",                   index_trait;
237
238     UnsafeTypeLangItem,              "unsafe",                  unsafe_type;
239
240     DerefTraitLangItem,              "deref",                   deref_trait;
241     DerefMutTraitLangItem,           "deref_mut",               deref_mut_trait;
242
243     FnTraitLangItem,                 "fn",                      fn_trait;
244     FnMutTraitLangItem,              "fn_mut",                  fn_mut_trait;
245     FnOnceTraitLangItem,             "fn_once",                 fn_once_trait;
246
247     EqTraitLangItem,                 "eq",                      eq_trait;
248     OrdTraitLangItem,                "ord",                     ord_trait;
249
250     StrEqFnLangItem,                 "str_eq",                  str_eq_fn;
251     UniqStrEqFnLangItem,             "uniq_str_eq",             uniq_str_eq_fn;
252
253     // A number of failure-related lang items. The `fail_` item corresponds to
254     // divide-by-zero and various failure cases with `match`. The
255     // `fail_bounds_check` item is for indexing arrays.
256     //
257     // The `begin_unwind` lang item has a predefined symbol name and is sort of
258     // a "weak lang item" in the sense that a crate is not required to have it
259     // defined to use it, but a final product is required to define it
260     // somewhere. Additionally, there are restrictions on crates that use a weak
261     // lang item, but do not have it defined.
262     FailFnLangItem,                  "fail_",                   fail_fn;
263     FailBoundsCheckFnLangItem,       "fail_bounds_check",       fail_bounds_check_fn;
264     BeginUnwindLangItem,             "begin_unwind",            begin_unwind;
265
266     ExchangeMallocFnLangItem,        "exchange_malloc",         exchange_malloc_fn;
267     ClosureExchangeMallocFnLangItem, "closure_exchange_malloc", closure_exchange_malloc_fn;
268     ExchangeFreeFnLangItem,          "exchange_free",           exchange_free_fn;
269     MallocFnLangItem,                "malloc",                  malloc_fn;
270     FreeFnLangItem,                  "free",                    free_fn;
271     StrDupUniqFnLangItem,            "strdup_uniq",             strdup_uniq_fn;
272
273     StartFnLangItem,                 "start",                   start_fn;
274
275     TyDescStructLangItem,            "ty_desc",                 ty_desc;
276     TyVisitorTraitLangItem,          "ty_visitor",              ty_visitor;
277     OpaqueStructLangItem,            "opaque",                  opaque;
278
279     TypeIdLangItem,                  "type_id",                 type_id;
280
281     EhPersonalityLangItem,           "eh_personality",          eh_personality;
282
283     ManagedHeapLangItem,             "managed_heap",            managed_heap;
284     ExchangeHeapLangItem,            "exchange_heap",           exchange_heap;
285     GcLangItem,                      "gc",                      gc;
286     OwnedBoxLangItem,                "owned_box",               owned_box;
287
288     CovariantTypeItem,               "covariant_type",          covariant_type;
289     ContravariantTypeItem,           "contravariant_type",      contravariant_type;
290     InvariantTypeItem,               "invariant_type",          invariant_type;
291
292     CovariantLifetimeItem,           "covariant_lifetime",      covariant_lifetime;
293     ContravariantLifetimeItem,       "contravariant_lifetime",  contravariant_lifetime;
294     InvariantLifetimeItem,           "invariant_lifetime",      invariant_lifetime;
295
296     NoSendItem,                      "no_send_bound",           no_send_bound;
297     NoCopyItem,                      "no_copy_bound",           no_copy_bound;
298     NoShareItem,                     "no_share_bound",          no_share_bound;
299     ManagedItem,                     "managed_bound",           managed_bound;
300
301     StackExhaustedLangItem,          "stack_exhausted",         stack_exhausted;
302 }