]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/lang_items.rs
Auto merge of #54813 - petrochenkov:uilocale, r=alexcrichton
[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 syntax_pos::Span;
32 use hir::itemlikevisit::ItemLikeVisitor;
33 use hir;
34
35 // The actual lang items defined come at the end of this file in one handy table.
36 // So you probably just want to nip down to the end.
37 macro_rules! language_item_table {
38     (
39         $( $variant:ident, $name:expr, $method:ident; )*
40     ) => {
41
42 enum_from_u32! {
43     #[derive(Debug, 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_else(|| format!("requires `{}` lang_item", it.name()))
78     }
79
80     pub fn fn_trait_kind(&self, id: DefId) -> Option<ty::ClosureKind> {
81         match Some(id) {
82             x if x == self.fn_trait() => Some(ty::ClosureKind::Fn),
83             x if x == self.fn_mut_trait() => Some(ty::ClosureKind::FnMut),
84             x if x == self.fn_once_trait() => Some(ty::ClosureKind::FnOnce),
85             _ => None
86         }
87     }
88
89     $(
90         #[allow(dead_code)]
91         pub fn $method(&self) -> Option<DefId> {
92             self.items[$variant as usize]
93         }
94     )*
95 }
96
97 struct LanguageItemCollector<'a, 'tcx: 'a> {
98     items: LanguageItems,
99
100     tcx: TyCtxt<'a, 'tcx, 'tcx>,
101
102     item_refs: FxHashMap<&'static str, usize>,
103 }
104
105 impl<'a, 'v, 'tcx> ItemLikeVisitor<'v> for LanguageItemCollector<'a, 'tcx> {
106     fn visit_item(&mut self, item: &hir::Item) {
107         if let Some((value, span)) = extract(&item.attrs) {
108             let item_index = self.item_refs.get(&*value.as_str()).cloned();
109
110             if let Some(item_index) = item_index {
111                 let def_id = self.tcx.hir.local_def_id(item.id);
112                 self.collect_item(item_index, def_id);
113             } else {
114                 let mut err = struct_span_err!(self.tcx.sess, span, E0522,
115                                                "definition of an unknown language item: `{}`",
116                                                value);
117                 err.span_label(span, format!("definition of unknown language item `{}`", value));
118                 err.emit();
119             }
120         }
121     }
122
123     fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem) {
124         // at present, lang items are always items, not trait items
125     }
126
127     fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem) {
128         // at present, lang items are always items, not impl items
129     }
130 }
131
132 impl<'a, 'tcx> LanguageItemCollector<'a, 'tcx> {
133     fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> LanguageItemCollector<'a, 'tcx> {
134         let mut item_refs = FxHashMap();
135
136         $( item_refs.insert($name, $variant as usize); )*
137
138         LanguageItemCollector {
139             tcx,
140             items: LanguageItems::new(),
141             item_refs,
142         }
143     }
144
145     fn collect_item(&mut self, item_index: usize, item_def_id: DefId) {
146         // Check for duplicates.
147         if let Some(original_def_id) = self.items.items[item_index] {
148             if original_def_id != item_def_id {
149                 let name = LangItem::from_u32(item_index as u32).unwrap().name();
150                 let mut err = match self.tcx.hir.span_if_local(item_def_id) {
151                     Some(span) => struct_span_err!(
152                         self.tcx.sess,
153                         span,
154                         E0152,
155                         "duplicate lang item found: `{}`.",
156                         name),
157                     None => self.tcx.sess.struct_err(&format!(
158                             "duplicate lang item in crate `{}`: `{}`.",
159                             self.tcx.crate_name(item_def_id.krate),
160                             name)),
161                 };
162                 if let Some(span) = self.tcx.hir.span_if_local(original_def_id) {
163                     span_note!(&mut err, span, "first defined here.");
164                 } else {
165                     err.note(&format!("first defined in crate `{}`.",
166                                       self.tcx.crate_name(original_def_id.krate)));
167                 }
168                 err.emit();
169             }
170         }
171
172         // Matched.
173         self.items.items[item_index] = Some(item_def_id);
174     }
175 }
176
177 pub fn extract(attrs: &[ast::Attribute]) -> Option<(Symbol, Span)> {
178     for attribute in attrs {
179         if attribute.check_name("lang") {
180             if let Some(value) = attribute.value_str() {
181                 return Some((value, attribute.span));
182             }
183         } else if attribute.check_name("panic_implementation") ||
184             attribute.check_name("panic_handler")
185         {
186             return Some((Symbol::intern("panic_impl"), attribute.span))
187         } else if attribute.check_name("alloc_error_handler") {
188             return Some((Symbol::intern("oom"), attribute.span))
189         }
190     }
191
192     None
193 }
194
195 pub fn collect<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> LanguageItems {
196     let mut collector = LanguageItemCollector::new(tcx);
197     for &cnum in tcx.crates().iter() {
198         for &(def_id, item_index) in tcx.defined_lang_items(cnum).iter() {
199             collector.collect_item(item_index, def_id);
200         }
201     }
202     tcx.hir.krate().visit_all_item_likes(&mut collector);
203     let LanguageItemCollector { mut items, .. } = collector;
204     weak_lang_items::check_crate(tcx, &mut items);
205     items
206 }
207
208 // End of the macro
209     }
210 }
211
212 language_item_table! {
213 //  Variant name,                    Name,                      Method name;
214     CharImplItem,                    "char",                    char_impl;
215     StrImplItem,                     "str",                     str_impl;
216     SliceImplItem,                   "slice",                   slice_impl;
217     SliceU8ImplItem,                 "slice_u8",                slice_u8_impl;
218     StrAllocImplItem,                "str_alloc",               str_alloc_impl;
219     SliceAllocImplItem,              "slice_alloc",             slice_alloc_impl;
220     SliceU8AllocImplItem,            "slice_u8_alloc",          slice_u8_alloc_impl;
221     ConstPtrImplItem,                "const_ptr",               const_ptr_impl;
222     MutPtrImplItem,                  "mut_ptr",                 mut_ptr_impl;
223     I8ImplItem,                      "i8",                      i8_impl;
224     I16ImplItem,                     "i16",                     i16_impl;
225     I32ImplItem,                     "i32",                     i32_impl;
226     I64ImplItem,                     "i64",                     i64_impl;
227     I128ImplItem,                     "i128",                   i128_impl;
228     IsizeImplItem,                   "isize",                   isize_impl;
229     U8ImplItem,                      "u8",                      u8_impl;
230     U16ImplItem,                     "u16",                     u16_impl;
231     U32ImplItem,                     "u32",                     u32_impl;
232     U64ImplItem,                     "u64",                     u64_impl;
233     U128ImplItem,                    "u128",                    u128_impl;
234     UsizeImplItem,                   "usize",                   usize_impl;
235     F32ImplItem,                     "f32",                     f32_impl;
236     F64ImplItem,                     "f64",                     f64_impl;
237     F32RuntimeImplItem,              "f32_runtime",             f32_runtime_impl;
238     F64RuntimeImplItem,              "f64_runtime",             f64_runtime_impl;
239
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     PartialOrdTraitLangItem,         "partial_ord",             partial_ord_trait;
290     OrdTraitLangItem,                "ord",                     ord_trait;
291
292     // A number of panic-related lang items. The `panic` item corresponds to
293     // divide-by-zero and various panic cases with `match`. The
294     // `panic_bounds_check` item is for indexing arrays.
295     //
296     // The `begin_unwind` lang item has a predefined symbol name and is sort of
297     // a "weak lang item" in the sense that a crate is not required to have it
298     // defined to use it, but a final product is required to define it
299     // somewhere. Additionally, there are restrictions on crates that use a weak
300     // lang item, but do not have it defined.
301     PanicFnLangItem,                 "panic",                   panic_fn;
302     PanicBoundsCheckFnLangItem,      "panic_bounds_check",      panic_bounds_check_fn;
303     PanicInfoLangItem,               "panic_info",              panic_info;
304     PanicImplLangItem,               "panic_impl",              panic_impl;
305     // Libstd panic entry point. Necessary for const eval to be able to catch it
306     BeginPanicFnLangItem,            "begin_panic",             begin_panic_fn;
307
308     ExchangeMallocFnLangItem,        "exchange_malloc",         exchange_malloc_fn;
309     BoxFreeFnLangItem,               "box_free",                box_free_fn;
310     DropInPlaceFnLangItem,           "drop_in_place",           drop_in_place_fn;
311     OomLangItem,                     "oom",                     oom;
312     AllocLayoutLangItem,             "alloc_layout",            alloc_layout;
313
314     StartFnLangItem,                 "start",                   start_fn;
315
316     EhPersonalityLangItem,           "eh_personality",          eh_personality;
317     EhUnwindResumeLangItem,          "eh_unwind_resume",        eh_unwind_resume;
318     MSVCTryFilterLangItem,           "msvc_try_filter",         msvc_try_filter;
319
320     OwnedBoxLangItem,                "owned_box",               owned_box;
321
322     PhantomDataItem,                 "phantom_data",            phantom_data;
323
324     ManuallyDropItem,                "manually_drop",           manually_drop;
325
326     DebugTraitLangItem,              "debug_trait",             debug_trait;
327
328     // A lang item for each of the 128-bit operators we can optionally lower.
329     I128AddFnLangItem,               "i128_add",                i128_add_fn;
330     U128AddFnLangItem,               "u128_add",                u128_add_fn;
331     I128SubFnLangItem,               "i128_sub",                i128_sub_fn;
332     U128SubFnLangItem,               "u128_sub",                u128_sub_fn;
333     I128MulFnLangItem,               "i128_mul",                i128_mul_fn;
334     U128MulFnLangItem,               "u128_mul",                u128_mul_fn;
335     I128DivFnLangItem,               "i128_div",                i128_div_fn;
336     U128DivFnLangItem,               "u128_div",                u128_div_fn;
337     I128RemFnLangItem,               "i128_rem",                i128_rem_fn;
338     U128RemFnLangItem,               "u128_rem",                u128_rem_fn;
339     I128ShlFnLangItem,               "i128_shl",                i128_shl_fn;
340     U128ShlFnLangItem,               "u128_shl",                u128_shl_fn;
341     I128ShrFnLangItem,               "i128_shr",                i128_shr_fn;
342     U128ShrFnLangItem,               "u128_shr",                u128_shr_fn;
343     // And overflow versions for the operators that are checkable.
344     // While MIR calls these Checked*, they return (T,bool), not Option<T>.
345     I128AddoFnLangItem,              "i128_addo",               i128_addo_fn;
346     U128AddoFnLangItem,              "u128_addo",               u128_addo_fn;
347     I128SuboFnLangItem,              "i128_subo",               i128_subo_fn;
348     U128SuboFnLangItem,              "u128_subo",               u128_subo_fn;
349     I128MuloFnLangItem,              "i128_mulo",               i128_mulo_fn;
350     U128MuloFnLangItem,              "u128_mulo",               u128_mulo_fn;
351     I128ShloFnLangItem,              "i128_shlo",               i128_shlo_fn;
352     U128ShloFnLangItem,              "u128_shlo",               u128_shlo_fn;
353     I128ShroFnLangItem,              "i128_shro",               i128_shro_fn;
354     U128ShroFnLangItem,              "u128_shro",               u128_shro_fn;
355
356     // Align offset for stride != 1, must not panic.
357     AlignOffsetLangItem,             "align_offset",            align_offset_fn;
358
359     TerminationTraitLangItem,        "termination",             termination;
360
361     Arc,                             "arc",                     arc;
362     Rc,                              "rc",                      rc;
363 }
364
365 impl<'a, 'tcx, 'gcx> TyCtxt<'a, 'tcx, 'gcx> {
366     pub fn require_lang_item(&self, lang_item: LangItem) -> DefId {
367         self.lang_items().require(lang_item).unwrap_or_else(|msg| {
368             self.sess.fatal(&msg)
369         })
370     }
371 }