]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/lang_items.rs
Various minor/cosmetic improvements to code
[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 hir::check_attr::Target;
26 use ty::{self, TyCtxt};
27 use middle::weak_lang_items;
28 use util::nodemap::FxHashMap;
29
30 use syntax::ast;
31 use syntax::symbol::Symbol;
32 use syntax_pos::Span;
33 use hir::itemlikevisit::ItemLikeVisitor;
34 use hir;
35
36 // The actual lang items defined come at the end of this file in one handy table.
37 // So you probably just want to nip down to the end.
38 macro_rules! language_item_table {
39     (
40         $( $variant:ident, $name:expr, $method:ident, $target:path; )*
41     ) => {
42
43 enum_from_u32! {
44     #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
45     pub enum LangItem {
46         $($variant,)*
47     }
48 }
49
50 impl LangItem {
51     fn name(self) -> &'static str {
52         match self {
53             $( $variant => $name, )*
54         }
55     }
56 }
57
58 pub struct LanguageItems {
59     pub items: Vec<Option<DefId>>,
60     pub missing: Vec<LangItem>,
61 }
62
63 impl LanguageItems {
64     pub fn new() -> LanguageItems {
65         fn foo(_: LangItem) -> Option<DefId> { None }
66
67         LanguageItems {
68             items: vec![$(foo($variant)),*],
69             missing: Vec::new(),
70         }
71     }
72
73     pub fn items(&self) -> &[Option<DefId>] {
74         &*self.items
75     }
76
77     pub fn require(&self, it: LangItem) -> Result<DefId, String> {
78         self.items[it as usize].ok_or_else(|| format!("requires `{}` lang_item", it.name()))
79     }
80
81     pub fn fn_trait_kind(&self, id: DefId) -> Option<ty::ClosureKind> {
82         match Some(id) {
83             x if x == self.fn_trait() => Some(ty::ClosureKind::Fn),
84             x if x == self.fn_mut_trait() => Some(ty::ClosureKind::FnMut),
85             x if x == self.fn_once_trait() => Some(ty::ClosureKind::FnOnce),
86             _ => None
87         }
88     }
89
90     $(
91         #[allow(dead_code)]
92         pub fn $method(&self) -> Option<DefId> {
93             self.items[$variant as usize]
94         }
95     )*
96 }
97
98 struct LanguageItemCollector<'a, 'tcx: 'a> {
99     items: LanguageItems,
100     tcx: TyCtxt<'a, 'tcx, 'tcx>,
101     item_refs: FxHashMap<&'static str, (usize, Target)>,
102 }
103
104 impl<'a, 'v, 'tcx> ItemLikeVisitor<'v> for LanguageItemCollector<'a, 'tcx> {
105     fn visit_item(&mut self, item: &hir::Item) {
106         if let Some((value, span)) = extract(&item.attrs) {
107             let actual_target = Target::from_item(item);
108             match self.item_refs.get(&*value.as_str()).cloned() {
109                 // Known lang item with attribute on correct target.
110                 Some((item_index, expected_target)) if actual_target == expected_target => {
111                     let def_id = self.tcx.hir().local_def_id(item.id);
112                     self.collect_item(item_index, def_id);
113                 },
114                 // Known lang item with attribute on incorrect target.
115                 Some((_, expected_target)) => {
116                     let mut err = struct_span_err!(
117                         self.tcx.sess, span, E0718,
118                         "`{}` language item must be applied to a {}",
119                         value, expected_target,
120                     );
121                     err.span_label(
122                         span,
123                         format!(
124                             "attribute should be applied to a {}, not a {}",
125                             expected_target, actual_target,
126                         ),
127                     );
128                     err.emit();
129                 },
130                 // Unknown lang item.
131                 _ => {
132                     let mut err = struct_span_err!(
133                         self.tcx.sess, span, E0522,
134                         "definition of an unknown language item: `{}`",
135                         value
136                     );
137                     err.span_label(
138                         span,
139                         format!("definition of unknown language item `{}`", value)
140                     );
141                     err.emit();
142                 },
143             }
144         }
145     }
146
147     fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem) {
148         // at present, lang items are always items, not trait items
149     }
150
151     fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem) {
152         // at present, lang items are always items, not impl items
153     }
154 }
155
156 impl<'a, 'tcx> LanguageItemCollector<'a, 'tcx> {
157     fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> LanguageItemCollector<'a, 'tcx> {
158         let mut item_refs = FxHashMap::default();
159
160         $( item_refs.insert($name, ($variant as usize, $target)); )*
161
162         LanguageItemCollector {
163             tcx,
164             items: LanguageItems::new(),
165             item_refs,
166         }
167     }
168
169     fn collect_item(&mut self, item_index: usize, item_def_id: DefId) {
170         // Check for duplicates.
171         if let Some(original_def_id) = self.items.items[item_index] {
172             if original_def_id != item_def_id {
173                 let name = LangItem::from_u32(item_index as u32).unwrap().name();
174                 let mut err = match self.tcx.hir().span_if_local(item_def_id) {
175                     Some(span) => struct_span_err!(
176                         self.tcx.sess,
177                         span,
178                         E0152,
179                         "duplicate lang item found: `{}`.",
180                         name),
181                     None => self.tcx.sess.struct_err(&format!(
182                             "duplicate lang item in crate `{}`: `{}`.",
183                             self.tcx.crate_name(item_def_id.krate),
184                             name)),
185                 };
186                 if let Some(span) = self.tcx.hir().span_if_local(original_def_id) {
187                     span_note!(&mut err, span, "first defined here.");
188                 } else {
189                     err.note(&format!("first defined in crate `{}`.",
190                                       self.tcx.crate_name(original_def_id.krate)));
191                 }
192                 err.emit();
193             }
194         }
195
196         // Matched.
197         self.items.items[item_index] = Some(item_def_id);
198     }
199 }
200
201 pub fn extract(attrs: &[ast::Attribute]) -> Option<(Symbol, Span)> {
202     for attribute in attrs {
203         if attribute.check_name("lang") {
204             if let Some(value) = attribute.value_str() {
205                 return Some((value, attribute.span));
206             }
207         } else if attribute.check_name("panic_handler") {
208             return Some((Symbol::intern("panic_impl"), attribute.span))
209         } else if attribute.check_name("alloc_error_handler") {
210             return Some((Symbol::intern("oom"), attribute.span))
211         }
212     }
213
214     None
215 }
216
217 pub fn collect<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> LanguageItems {
218     let mut collector = LanguageItemCollector::new(tcx);
219     for &cnum in tcx.crates().iter() {
220         for &(def_id, item_index) in tcx.defined_lang_items(cnum).iter() {
221             collector.collect_item(item_index, def_id);
222         }
223     }
224     tcx.hir().krate().visit_all_item_likes(&mut collector);
225     let LanguageItemCollector { mut items, .. } = collector;
226     weak_lang_items::check_crate(tcx, &mut items);
227     items
228 }
229
230 // End of the macro
231     }
232 }
233
234 language_item_table! {
235 //  Variant name,                Name,                 Method name,             Target;
236     CharImplItem,                "char",               char_impl,               Target::Impl;
237     StrImplItem,                 "str",                str_impl,                Target::Impl;
238     SliceImplItem,               "slice",              slice_impl,              Target::Impl;
239     SliceU8ImplItem,             "slice_u8",           slice_u8_impl,           Target::Impl;
240     StrAllocImplItem,            "str_alloc",          str_alloc_impl,          Target::Impl;
241     SliceAllocImplItem,          "slice_alloc",        slice_alloc_impl,        Target::Impl;
242     SliceU8AllocImplItem,        "slice_u8_alloc",     slice_u8_alloc_impl,     Target::Impl;
243     ConstPtrImplItem,            "const_ptr",          const_ptr_impl,          Target::Impl;
244     MutPtrImplItem,              "mut_ptr",            mut_ptr_impl,            Target::Impl;
245     I8ImplItem,                  "i8",                 i8_impl,                 Target::Impl;
246     I16ImplItem,                 "i16",                i16_impl,                Target::Impl;
247     I32ImplItem,                 "i32",                i32_impl,                Target::Impl;
248     I64ImplItem,                 "i64",                i64_impl,                Target::Impl;
249     I128ImplItem,                "i128",               i128_impl,               Target::Impl;
250     IsizeImplItem,               "isize",              isize_impl,              Target::Impl;
251     U8ImplItem,                  "u8",                 u8_impl,                 Target::Impl;
252     U16ImplItem,                 "u16",                u16_impl,                Target::Impl;
253     U32ImplItem,                 "u32",                u32_impl,                Target::Impl;
254     U64ImplItem,                 "u64",                u64_impl,                Target::Impl;
255     U128ImplItem,                "u128",               u128_impl,               Target::Impl;
256     UsizeImplItem,               "usize",              usize_impl,              Target::Impl;
257     F32ImplItem,                 "f32",                f32_impl,                Target::Impl;
258     F64ImplItem,                 "f64",                f64_impl,                Target::Impl;
259     F32RuntimeImplItem,          "f32_runtime",        f32_runtime_impl,        Target::Impl;
260     F64RuntimeImplItem,          "f64_runtime",        f64_runtime_impl,        Target::Impl;
261
262     SizedTraitLangItem,          "sized",              sized_trait,             Target::Trait;
263     UnsizeTraitLangItem,         "unsize",             unsize_trait,            Target::Trait;
264     CopyTraitLangItem,           "copy",               copy_trait,              Target::Trait;
265     CloneTraitLangItem,          "clone",              clone_trait,             Target::Trait;
266     SyncTraitLangItem,           "sync",               sync_trait,              Target::Trait;
267     FreezeTraitLangItem,         "freeze",             freeze_trait,            Target::Trait;
268
269     DropTraitLangItem,           "drop",               drop_trait,              Target::Trait;
270
271     CoerceUnsizedTraitLangItem,  "coerce_unsized",     coerce_unsized_trait,    Target::Trait;
272     DispatchFromDynTraitLangItem,"dispatch_from_dyn",  dispatch_from_dyn_trait, Target::Trait;
273
274     AddTraitLangItem,            "add",                add_trait,               Target::Trait;
275     SubTraitLangItem,            "sub",                sub_trait,               Target::Trait;
276     MulTraitLangItem,            "mul",                mul_trait,               Target::Trait;
277     DivTraitLangItem,            "div",                div_trait,               Target::Trait;
278     RemTraitLangItem,            "rem",                rem_trait,               Target::Trait;
279     NegTraitLangItem,            "neg",                neg_trait,               Target::Trait;
280     NotTraitLangItem,            "not",                not_trait,               Target::Trait;
281     BitXorTraitLangItem,         "bitxor",             bitxor_trait,            Target::Trait;
282     BitAndTraitLangItem,         "bitand",             bitand_trait,            Target::Trait;
283     BitOrTraitLangItem,          "bitor",              bitor_trait,             Target::Trait;
284     ShlTraitLangItem,            "shl",                shl_trait,               Target::Trait;
285     ShrTraitLangItem,            "shr",                shr_trait,               Target::Trait;
286     AddAssignTraitLangItem,      "add_assign",         add_assign_trait,        Target::Trait;
287     SubAssignTraitLangItem,      "sub_assign",         sub_assign_trait,        Target::Trait;
288     MulAssignTraitLangItem,      "mul_assign",         mul_assign_trait,        Target::Trait;
289     DivAssignTraitLangItem,      "div_assign",         div_assign_trait,        Target::Trait;
290     RemAssignTraitLangItem,      "rem_assign",         rem_assign_trait,        Target::Trait;
291     BitXorAssignTraitLangItem,   "bitxor_assign",      bitxor_assign_trait,     Target::Trait;
292     BitAndAssignTraitLangItem,   "bitand_assign",      bitand_assign_trait,     Target::Trait;
293     BitOrAssignTraitLangItem,    "bitor_assign",       bitor_assign_trait,      Target::Trait;
294     ShlAssignTraitLangItem,      "shl_assign",         shl_assign_trait,        Target::Trait;
295     ShrAssignTraitLangItem,      "shr_assign",         shr_assign_trait,        Target::Trait;
296     IndexTraitLangItem,          "index",              index_trait,             Target::Trait;
297     IndexMutTraitLangItem,       "index_mut",          index_mut_trait,         Target::Trait;
298
299     UnsafeCellTypeLangItem,      "unsafe_cell",        unsafe_cell_type,        Target::Struct;
300     VaListTypeLangItem,          "va_list",            va_list,                 Target::Struct;
301
302     DerefTraitLangItem,          "deref",              deref_trait,             Target::Trait;
303     DerefMutTraitLangItem,       "deref_mut",          deref_mut_trait,         Target::Trait;
304
305     FnTraitLangItem,             "fn",                 fn_trait,                Target::Trait;
306     FnMutTraitLangItem,          "fn_mut",             fn_mut_trait,            Target::Trait;
307     FnOnceTraitLangItem,         "fn_once",            fn_once_trait,           Target::Trait;
308
309     GeneratorStateLangItem,      "generator_state",    gen_state,               Target::Enum;
310     GeneratorTraitLangItem,      "generator",          gen_trait,               Target::Trait;
311
312     EqTraitLangItem,             "eq",                 eq_trait,                Target::Trait;
313     PartialOrdTraitLangItem,     "partial_ord",        partial_ord_trait,       Target::Trait;
314     OrdTraitLangItem,            "ord",                ord_trait,               Target::Trait;
315
316     // A number of panic-related lang items. The `panic` item corresponds to
317     // divide-by-zero and various panic cases with `match`. The
318     // `panic_bounds_check` item is for indexing arrays.
319     //
320     // The `begin_unwind` lang item has a predefined symbol name and is sort of
321     // a "weak lang item" in the sense that a crate is not required to have it
322     // defined to use it, but a final product is required to define it
323     // somewhere. Additionally, there are restrictions on crates that use a weak
324     // lang item, but do not have it defined.
325     PanicFnLangItem,             "panic",              panic_fn,                Target::Fn;
326     PanicBoundsCheckFnLangItem,  "panic_bounds_check", panic_bounds_check_fn,   Target::Fn;
327     PanicInfoLangItem,           "panic_info",         panic_info,              Target::Struct;
328     PanicImplLangItem,           "panic_impl",         panic_impl,              Target::Fn;
329     // Libstd panic entry point. Necessary for const eval to be able to catch it
330     BeginPanicFnLangItem,        "begin_panic",        begin_panic_fn,          Target::Fn;
331
332     ExchangeMallocFnLangItem,    "exchange_malloc",    exchange_malloc_fn,      Target::Fn;
333     BoxFreeFnLangItem,           "box_free",           box_free_fn,             Target::Fn;
334     DropInPlaceFnLangItem,       "drop_in_place",      drop_in_place_fn,        Target::Fn;
335     OomLangItem,                 "oom",                oom,                     Target::Fn;
336     AllocLayoutLangItem,         "alloc_layout",       alloc_layout,            Target::Struct;
337
338     StartFnLangItem,             "start",              start_fn,                Target::Fn;
339
340     EhPersonalityLangItem,       "eh_personality",     eh_personality,          Target::Fn;
341     EhUnwindResumeLangItem,      "eh_unwind_resume",   eh_unwind_resume,        Target::Fn;
342     MSVCTryFilterLangItem,       "msvc_try_filter",    msvc_try_filter,         Target::Static;
343
344     OwnedBoxLangItem,            "owned_box",          owned_box,               Target::Struct;
345
346     PhantomDataItem,             "phantom_data",       phantom_data,            Target::Struct;
347
348     ManuallyDropItem,            "manually_drop",      manually_drop,           Target::Struct;
349
350     DebugTraitLangItem,          "debug_trait",        debug_trait,             Target::Trait;
351
352     // A lang item for each of the 128-bit operators we can optionally lower.
353     I128AddFnLangItem,           "i128_add",           i128_add_fn,             Target::Fn;
354     U128AddFnLangItem,           "u128_add",           u128_add_fn,             Target::Fn;
355     I128SubFnLangItem,           "i128_sub",           i128_sub_fn,             Target::Fn;
356     U128SubFnLangItem,           "u128_sub",           u128_sub_fn,             Target::Fn;
357     I128MulFnLangItem,           "i128_mul",           i128_mul_fn,             Target::Fn;
358     U128MulFnLangItem,           "u128_mul",           u128_mul_fn,             Target::Fn;
359     I128DivFnLangItem,           "i128_div",           i128_div_fn,             Target::Fn;
360     U128DivFnLangItem,           "u128_div",           u128_div_fn,             Target::Fn;
361     I128RemFnLangItem,           "i128_rem",           i128_rem_fn,             Target::Fn;
362     U128RemFnLangItem,           "u128_rem",           u128_rem_fn,             Target::Fn;
363     I128ShlFnLangItem,           "i128_shl",           i128_shl_fn,             Target::Fn;
364     U128ShlFnLangItem,           "u128_shl",           u128_shl_fn,             Target::Fn;
365     I128ShrFnLangItem,           "i128_shr",           i128_shr_fn,             Target::Fn;
366     U128ShrFnLangItem,           "u128_shr",           u128_shr_fn,             Target::Fn;
367     // And overflow versions for the operators that are checkable.
368     // While MIR calls these Checked*, they return (T,bool), not Option<T>.
369     I128AddoFnLangItem,          "i128_addo",          i128_addo_fn,            Target::Fn;
370     U128AddoFnLangItem,          "u128_addo",          u128_addo_fn,            Target::Fn;
371     I128SuboFnLangItem,          "i128_subo",          i128_subo_fn,            Target::Fn;
372     U128SuboFnLangItem,          "u128_subo",          u128_subo_fn,            Target::Fn;
373     I128MuloFnLangItem,          "i128_mulo",          i128_mulo_fn,            Target::Fn;
374     U128MuloFnLangItem,          "u128_mulo",          u128_mulo_fn,            Target::Fn;
375     I128ShloFnLangItem,          "i128_shlo",          i128_shlo_fn,            Target::Fn;
376     U128ShloFnLangItem,          "u128_shlo",          u128_shlo_fn,            Target::Fn;
377     I128ShroFnLangItem,          "i128_shro",          i128_shro_fn,            Target::Fn;
378     U128ShroFnLangItem,          "u128_shro",          u128_shro_fn,            Target::Fn;
379
380     // Align offset for stride != 1, must not panic.
381     AlignOffsetLangItem,         "align_offset",       align_offset_fn,         Target::Fn;
382
383     TerminationTraitLangItem,    "termination",        termination,             Target::Trait;
384
385     Arc,                         "arc",                arc,                     Target::Struct;
386     Rc,                          "rc",                 rc,                      Target::Struct;
387 }
388
389 impl<'a, 'tcx, 'gcx> TyCtxt<'a, 'tcx, 'gcx> {
390     pub fn require_lang_item(&self, lang_item: LangItem) -> DefId {
391         self.lang_items().require(lang_item).unwrap_or_else(|msg| {
392             self.sess.fatal(&msg)
393         })
394     }
395 }