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