]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/lang_items.rs
Auto merge of #22517 - brson:relnotes, r=Gankro
[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::num::FromPrimitive;
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 #[derive(Copy, FromPrimitive, PartialEq, Eq, Hash)]
50 pub enum LangItem {
51     $($variant),*
52 }
53
54 pub struct LanguageItems {
55     pub items: Vec<Option<ast::DefId>>,
56     pub missing: Vec<LangItem>,
57 }
58
59 impl LanguageItems {
60     pub fn new() -> LanguageItems {
61         fn foo(_: LangItem) -> Option<ast::DefId> { None }
62
63         LanguageItems {
64             items: vec!($(foo($variant)),*),
65             missing: Vec::new(),
66         }
67     }
68
69     pub fn items<'a>(&'a self) -> Enumerate<slice::Iter<'a, Option<ast::DefId>>> {
70         self.items.iter().enumerate()
71     }
72
73     pub fn item_name(index: uint) -> &'static str {
74         let item: Option<LangItem> = FromPrimitive::from_uint(index);
75         match item {
76             $( Some($variant) => $name, )*
77             None => "???"
78         }
79     }
80
81     pub fn require(&self, it: LangItem) -> Result<ast::DefId, String> {
82         match self.items[it as uint] {
83             Some(id) => Ok(id),
84             None => {
85                 Err(format!("requires `{}` lang_item",
86                             LanguageItems::item_name(it as uint)))
87             }
88         }
89     }
90
91     pub fn from_builtin_kind(&self, bound: ty::BuiltinBound)
92                              -> Result<ast::DefId, String>
93     {
94         match bound {
95             ty::BoundSend => self.require(SendTraitLangItem),
96             ty::BoundSized => self.require(SizedTraitLangItem),
97             ty::BoundCopy => self.require(CopyTraitLangItem),
98             ty::BoundSync => self.require(SyncTraitLangItem),
99         }
100     }
101
102     pub fn to_builtin_kind(&self, id: ast::DefId) -> Option<ty::BuiltinBound> {
103         if Some(id) == self.send_trait() {
104             Some(ty::BoundSend)
105         } else if Some(id) == self.sized_trait() {
106             Some(ty::BoundSized)
107         } else if Some(id) == self.copy_trait() {
108             Some(ty::BoundCopy)
109         } else if Some(id) == self.sync_trait() {
110             Some(ty::BoundSync)
111         } else {
112             None
113         }
114     }
115
116     pub fn fn_trait_kind(&self, id: ast::DefId) -> Option<ty::ClosureKind> {
117         let def_id_kinds = [
118             (self.fn_trait(), ty::FnClosureKind),
119             (self.fn_mut_trait(), ty::FnMutClosureKind),
120             (self.fn_once_trait(), ty::FnOnceClosureKind),
121             ];
122
123         for &(opt_def_id, kind) in &def_id_kinds {
124             if Some(id) == opt_def_id {
125                 return Some(kind);
126             }
127         }
128
129         None
130     }
131
132     $(
133         #[allow(dead_code)]
134         pub fn $method(&self) -> Option<ast::DefId> {
135             self.items[$variant as uint]
136         }
137     )*
138 }
139
140 struct LanguageItemCollector<'a> {
141     items: LanguageItems,
142
143     session: &'a Session,
144
145     item_refs: FnvHashMap<&'static str, uint>,
146 }
147
148 impl<'a, 'v> Visitor<'v> for LanguageItemCollector<'a> {
149     fn visit_item(&mut self, item: &ast::Item) {
150         match extract(&item.attrs) {
151             Some(value) => {
152                 let item_index = self.item_refs.get(&value[]).map(|x| *x);
153
154                 match item_index {
155                     Some(item_index) => {
156                         self.collect_item(item_index, local_def(item.id), item.span)
157                     }
158                     None => {}
159                 }
160             }
161             None => {}
162         }
163
164         visit::walk_item(self, item);
165     }
166 }
167
168 impl<'a> LanguageItemCollector<'a> {
169     pub fn new(session: &'a Session) -> LanguageItemCollector<'a> {
170         let mut item_refs = FnvHashMap();
171
172         $( item_refs.insert($name, $variant as uint); )*
173
174         LanguageItemCollector {
175             session: session,
176             items: LanguageItems::new(),
177             item_refs: item_refs
178         }
179     }
180
181     pub fn collect_item(&mut self, item_index: uint,
182                         item_def_id: ast::DefId, span: Span) {
183         // Check for duplicates.
184         match self.items.items[item_index] {
185             Some(original_def_id) if original_def_id != item_def_id => {
186                 span_err!(self.session, span, E0152,
187                     "duplicate entry for `{}`", LanguageItems::item_name(item_index));
188             }
189             Some(_) | None => {
190                 // OK.
191             }
192         }
193
194         // Matched.
195         self.items.items[item_index] = Some(item_def_id);
196     }
197
198     pub fn collect_local_language_items(&mut self, krate: &ast::Crate) {
199         visit::walk_crate(self, krate);
200     }
201
202     pub fn collect_external_language_items(&mut self) {
203         let crate_store = &self.session.cstore;
204         crate_store.iter_crate_data(|crate_number, _crate_metadata| {
205             each_lang_item(crate_store, crate_number, |node_id, item_index| {
206                 let def_id = ast::DefId { krate: crate_number, node: node_id };
207                 self.collect_item(item_index, def_id, DUMMY_SP);
208                 true
209             });
210         })
211     }
212
213     pub fn collect(&mut self, krate: &ast::Crate) {
214         self.collect_local_language_items(krate);
215         self.collect_external_language_items();
216     }
217 }
218
219 pub fn extract(attrs: &[ast::Attribute]) -> Option<InternedString> {
220     for attribute in attrs {
221         match attribute.value_str() {
222             Some(ref value) if attribute.check_name("lang") => {
223                 return Some(value.clone());
224             }
225             _ => {}
226         }
227     }
228
229     return None;
230 }
231
232 pub fn collect_language_items(krate: &ast::Crate,
233                               session: &Session) -> LanguageItems {
234     let mut collector = LanguageItemCollector::new(session);
235     collector.collect(krate);
236     let LanguageItemCollector { mut items, .. } = collector;
237     weak_lang_items::check_crate(krate, session, &mut items);
238     session.abort_if_errors();
239     items
240 }
241
242 // End of the macro
243     }
244 }
245
246 lets_do_this! {
247 //  Variant name,                    Name,                      Method name;
248     SendTraitLangItem,               "send",                    send_trait;
249     SizedTraitLangItem,              "sized",                   sized_trait;
250     CopyTraitLangItem,               "copy",                    copy_trait;
251     SyncTraitLangItem,               "sync",                    sync_trait;
252
253     DropTraitLangItem,               "drop",                    drop_trait;
254
255     AddTraitLangItem,                "add",                     add_trait;
256     SubTraitLangItem,                "sub",                     sub_trait;
257     MulTraitLangItem,                "mul",                     mul_trait;
258     DivTraitLangItem,                "div",                     div_trait;
259     RemTraitLangItem,                "rem",                     rem_trait;
260     NegTraitLangItem,                "neg",                     neg_trait;
261     NotTraitLangItem,                "not",                     not_trait;
262     BitXorTraitLangItem,             "bitxor",                  bitxor_trait;
263     BitAndTraitLangItem,             "bitand",                  bitand_trait;
264     BitOrTraitLangItem,              "bitor",                   bitor_trait;
265     ShlTraitLangItem,                "shl",                     shl_trait;
266     ShrTraitLangItem,                "shr",                     shr_trait;
267     IndexTraitLangItem,              "index",                   index_trait;
268     IndexMutTraitLangItem,           "index_mut",               index_mut_trait;
269     RangeStructLangItem,             "range",                   range_struct;
270     RangeFromStructLangItem,         "range_from",              range_from_struct;
271     RangeToStructLangItem,           "range_to",                range_to_struct;
272     RangeFullStructLangItem,         "range_full",              range_full_struct;
273
274     UnsafeCellTypeLangItem,          "unsafe_cell",             unsafe_cell_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     EhPersonalityLangItem,           "eh_personality",          eh_personality;
311
312     ExchangeHeapLangItem,            "exchange_heap",           exchange_heap;
313     OwnedBoxLangItem,                "owned_box",               owned_box;
314
315     PhantomDataItem,                 "phantom_data",            phantom_data;
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     NoCopyItem,                      "no_copy_bound",           no_copy_bound;
326     ManagedItem,                     "managed_bound",           managed_bound;
327
328     NonZeroItem,                     "non_zero",                non_zero;
329
330     StackExhaustedLangItem,          "stack_exhausted",         stack_exhausted;
331
332     DebugTraitLangItem,              "debug_trait",             debug_trait;
333 }