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