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