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