]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/lang_items.rs
645da2475c62767f62e96c5a69a97208c41c1a90
[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 hir::def_id::DefId;
25 use ty::{self, TyCtxt};
26 use middle::weak_lang_items;
27 use util::nodemap::FxHashMap;
28
29 use syntax::ast;
30 use syntax::symbol::Symbol;
31 use hir::itemlikevisit::ItemLikeVisitor;
32 use hir;
33
34 // The actual lang items defined come at the end of this file in one handy table.
35 // So you probably just want to nip down to the end.
36 macro_rules! language_item_table {
37     (
38         $( $variant:ident, $name:expr, $method:ident; )*
39     ) => {
40
41
42 enum_from_u32! {
43     #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
44     pub enum LangItem {
45         $($variant,)*
46     }
47 }
48
49 pub struct LanguageItems {
50     pub items: Vec<Option<DefId>>,
51     pub missing: Vec<LangItem>,
52 }
53
54 impl LanguageItems {
55     pub fn new() -> LanguageItems {
56         fn foo(_: LangItem) -> Option<DefId> { None }
57
58         LanguageItems {
59             items: vec![$(foo($variant)),*],
60             missing: Vec::new(),
61         }
62     }
63
64     pub fn items(&self) -> &[Option<DefId>] {
65         &*self.items
66     }
67
68     pub fn item_name(index: usize) -> &'static str {
69         let item: Option<LangItem> = LangItem::from_u32(index as u32);
70         match item {
71             $( Some($variant) => $name, )*
72             None => "???"
73         }
74     }
75
76     pub fn require(&self, it: LangItem) -> Result<DefId, String> {
77         match self.items[it as usize] {
78             Some(id) => Ok(id),
79             None => {
80                 Err(format!("requires `{}` lang_item",
81                             LanguageItems::item_name(it as usize)))
82             }
83         }
84     }
85
86     pub fn fn_trait_kind(&self, id: DefId) -> Option<ty::ClosureKind> {
87         let def_id_kinds = [
88             (self.fn_trait(), ty::ClosureKind::Fn),
89             (self.fn_mut_trait(), ty::ClosureKind::FnMut),
90             (self.fn_once_trait(), ty::ClosureKind::FnOnce),
91             ];
92
93         for &(opt_def_id, kind) in &def_id_kinds {
94             if Some(id) == opt_def_id {
95                 return Some(kind);
96             }
97         }
98
99         None
100     }
101
102     $(
103         #[allow(dead_code)]
104         pub fn $method(&self) -> Option<DefId> {
105             self.items[$variant as usize]
106         }
107     )*
108 }
109
110 struct LanguageItemCollector<'a, 'tcx: 'a> {
111     items: LanguageItems,
112
113     tcx: TyCtxt<'a, 'tcx, 'tcx>,
114
115     item_refs: FxHashMap<&'static str, usize>,
116 }
117
118 impl<'a, 'v, 'tcx> ItemLikeVisitor<'v> for LanguageItemCollector<'a, 'tcx> {
119     fn visit_item(&mut self, item: &hir::Item) {
120         if let Some(value) = extract(&item.attrs) {
121             let item_index = self.item_refs.get(&*value.as_str()).cloned();
122
123             if let Some(item_index) = item_index {
124                 let def_id = self.tcx.hir.local_def_id(item.id);
125                 self.collect_item(item_index, def_id);
126             } else {
127                 let span = self.tcx.hir.span(item.id);
128                 span_err!(self.tcx.sess, span, E0522,
129                           "definition of an unknown language item: `{}`.",
130                           value);
131             }
132         }
133     }
134
135     fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem) {
136         // at present, lang items are always items, not trait items
137     }
138
139     fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem) {
140         // at present, lang items are always items, not impl items
141     }
142 }
143
144 impl<'a, 'tcx> LanguageItemCollector<'a, 'tcx> {
145     fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> LanguageItemCollector<'a, 'tcx> {
146         let mut item_refs = FxHashMap();
147
148         $( item_refs.insert($name, $variant as usize); )*
149
150         LanguageItemCollector {
151             tcx,
152             items: LanguageItems::new(),
153             item_refs,
154         }
155     }
156
157     fn collect_item(&mut self, item_index: usize, item_def_id: DefId) {
158         // Check for duplicates.
159         match self.items.items[item_index] {
160             Some(original_def_id) if original_def_id != item_def_id => {
161                 let name = LanguageItems::item_name(item_index);
162                 let mut err = match self.tcx.hir.span_if_local(item_def_id) {
163                     Some(span) => struct_span_err!(
164                         self.tcx.sess,
165                         span,
166                         E0152,
167                         "duplicate lang item found: `{}`.",
168                         name),
169                     None => self.tcx.sess.struct_err(&format!(
170                             "duplicate lang item in crate `{}`: `{}`.",
171                             self.tcx.crate_name(item_def_id.krate),
172                             name)),
173                 };
174                 if let Some(span) = self.tcx.hir.span_if_local(original_def_id) {
175                     span_note!(&mut err, span,
176                                "first defined here.");
177                 } else {
178                     err.note(&format!("first defined in crate `{}`.",
179                                       self.tcx.crate_name(original_def_id.krate)));
180                 }
181                 err.emit();
182             }
183             _ => {
184                 // OK.
185             }
186         }
187
188         // Matched.
189         self.items.items[item_index] = Some(item_def_id);
190     }
191 }
192
193 pub fn extract(attrs: &[ast::Attribute]) -> Option<Symbol> {
194     for attribute in attrs {
195         if attribute.check_name("lang") {
196             if let Some(value) = attribute.value_str() {
197                 return Some(value)
198             }
199         }
200     }
201
202     return None;
203 }
204
205 pub fn collect<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> LanguageItems {
206     let mut collector = LanguageItemCollector::new(tcx);
207     for &cnum in tcx.crates().iter() {
208         for &(index, item_index) in tcx.defined_lang_items(cnum).iter() {
209             let def_id = DefId { krate: cnum, index: index };
210             collector.collect_item(item_index, def_id);
211         }
212     }
213     tcx.hir.krate().visit_all_item_likes(&mut collector);
214     let LanguageItemCollector { mut items, .. } = collector;
215     weak_lang_items::check_crate(tcx, &mut items);
216     items
217 }
218
219 // End of the macro
220     }
221 }
222
223 language_item_table! {
224 //  Variant name,                    Name,                      Method name;
225     CharImplItem,                    "char",                    char_impl;
226     StrImplItem,                     "str",                     str_impl;
227     SliceImplItem,                   "slice",                   slice_impl;
228     ConstPtrImplItem,                "const_ptr",               const_ptr_impl;
229     MutPtrImplItem,                  "mut_ptr",                 mut_ptr_impl;
230     I8ImplItem,                      "i8",                      i8_impl;
231     I16ImplItem,                     "i16",                     i16_impl;
232     I32ImplItem,                     "i32",                     i32_impl;
233     I64ImplItem,                     "i64",                     i64_impl;
234     I128ImplItem,                     "i128",                   i128_impl;
235     IsizeImplItem,                   "isize",                   isize_impl;
236     U8ImplItem,                      "u8",                      u8_impl;
237     U16ImplItem,                     "u16",                     u16_impl;
238     U32ImplItem,                     "u32",                     u32_impl;
239     U64ImplItem,                     "u64",                     u64_impl;
240     U128ImplItem,                    "u128",                    u128_impl;
241     UsizeImplItem,                   "usize",                   usize_impl;
242     F32ImplItem,                     "f32",                     f32_impl;
243     F64ImplItem,                     "f64",                     f64_impl;
244
245     SendTraitLangItem,               "send",                    send_trait;
246     SizedTraitLangItem,              "sized",                   sized_trait;
247     UnsizeTraitLangItem,             "unsize",                  unsize_trait;
248     CopyTraitLangItem,               "copy",                    copy_trait;
249     CloneTraitLangItem,              "clone",                   clone_trait;
250     SyncTraitLangItem,               "sync",                    sync_trait;
251     FreezeTraitLangItem,             "freeze",                  freeze_trait;
252
253     DropTraitLangItem,               "drop",                    drop_trait;
254
255     CoerceUnsizedTraitLangItem,      "coerce_unsized",          coerce_unsized_trait;
256
257     AddTraitLangItem,                "add",                     add_trait;
258     SubTraitLangItem,                "sub",                     sub_trait;
259     MulTraitLangItem,                "mul",                     mul_trait;
260     DivTraitLangItem,                "div",                     div_trait;
261     RemTraitLangItem,                "rem",                     rem_trait;
262     NegTraitLangItem,                "neg",                     neg_trait;
263     NotTraitLangItem,                "not",                     not_trait;
264     BitXorTraitLangItem,             "bitxor",                  bitxor_trait;
265     BitAndTraitLangItem,             "bitand",                  bitand_trait;
266     BitOrTraitLangItem,              "bitor",                   bitor_trait;
267     ShlTraitLangItem,                "shl",                     shl_trait;
268     ShrTraitLangItem,                "shr",                     shr_trait;
269     AddAssignTraitLangItem,          "add_assign",              add_assign_trait;
270     SubAssignTraitLangItem,          "sub_assign",              sub_assign_trait;
271     MulAssignTraitLangItem,          "mul_assign",              mul_assign_trait;
272     DivAssignTraitLangItem,          "div_assign",              div_assign_trait;
273     RemAssignTraitLangItem,          "rem_assign",              rem_assign_trait;
274     BitXorAssignTraitLangItem,       "bitxor_assign",           bitxor_assign_trait;
275     BitAndAssignTraitLangItem,       "bitand_assign",           bitand_assign_trait;
276     BitOrAssignTraitLangItem,        "bitor_assign",            bitor_assign_trait;
277     ShlAssignTraitLangItem,          "shl_assign",              shl_assign_trait;
278     ShrAssignTraitLangItem,          "shr_assign",              shr_assign_trait;
279     IndexTraitLangItem,              "index",                   index_trait;
280     IndexMutTraitLangItem,           "index_mut",               index_mut_trait;
281
282     UnsafeCellTypeLangItem,          "unsafe_cell",             unsafe_cell_type;
283
284     DerefTraitLangItem,              "deref",                   deref_trait;
285     DerefMutTraitLangItem,           "deref_mut",               deref_mut_trait;
286
287     FnTraitLangItem,                 "fn",                      fn_trait;
288     FnMutTraitLangItem,              "fn_mut",                  fn_mut_trait;
289     FnOnceTraitLangItem,             "fn_once",                 fn_once_trait;
290
291     GeneratorStateLangItem,          "generator_state",         gen_state;
292     GeneratorTraitLangItem,          "generator",               gen_trait;
293
294     EqTraitLangItem,                 "eq",                      eq_trait;
295     OrdTraitLangItem,                "ord",                     ord_trait;
296
297     StrEqFnLangItem,                 "str_eq",                  str_eq_fn;
298
299     // A number of panic-related lang items. The `panic` item corresponds to
300     // divide-by-zero and various panic cases with `match`. The
301     // `panic_bounds_check` item is for indexing arrays.
302     //
303     // The `begin_unwind` lang item has a predefined symbol name and is sort of
304     // a "weak lang item" in the sense that a crate is not required to have it
305     // defined to use it, but a final product is required to define it
306     // somewhere. Additionally, there are restrictions on crates that use a weak
307     // lang item, but do not have it defined.
308     PanicFnLangItem,                 "panic",                   panic_fn;
309     PanicBoundsCheckFnLangItem,      "panic_bounds_check",      panic_bounds_check_fn;
310     PanicFmtLangItem,                "panic_fmt",               panic_fmt;
311
312     ExchangeMallocFnLangItem,        "exchange_malloc",         exchange_malloc_fn;
313     BoxFreeFnLangItem,               "box_free",                box_free_fn;
314     DropInPlaceFnLangItem,             "drop_in_place",           drop_in_place_fn;
315
316     StartFnLangItem,                 "start",                   start_fn;
317
318     EhPersonalityLangItem,           "eh_personality",          eh_personality;
319     EhUnwindResumeLangItem,          "eh_unwind_resume",        eh_unwind_resume;
320     MSVCTryFilterLangItem,           "msvc_try_filter",         msvc_try_filter;
321
322     OwnedBoxLangItem,                "owned_box",               owned_box;
323
324     PhantomDataItem,                 "phantom_data",            phantom_data;
325
326     NonZeroItem,                     "non_zero",                non_zero;
327
328     DebugTraitLangItem,              "debug_trait",             debug_trait;
329 }
330
331 impl<'a, 'tcx, 'gcx> ty::TyCtxt<'a, 'tcx, 'gcx> {
332     pub fn require_lang_item(&self, lang_item: LangItem) -> DefId {
333         self.lang_items().require(lang_item).unwrap_or_else(|msg| {
334             self.sess.fatal(&msg)
335         })
336     }
337 }