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.
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.
11 // Detecting language items.
13 // Language items are items that represent concepts intrinsic to the language
14 // itself. Examples are:
16 // * Traits that specify "kinds"; e.g. "Sync", "Send".
18 // * Traits that represent operators; e.g. "Add", "Sub", "Index".
20 // * Functions called by the compiler itself.
22 pub use self::LangItem::*;
24 use front::map as hir_map;
26 use metadata::csearch::each_lang_item;
27 use middle::def_id::DefId;
29 use middle::weak_lang_items;
30 use util::nodemap::FnvHashMap;
33 use syntax::attr::AttrMetaMethods;
34 use syntax::codemap::{DUMMY_SP, Span};
35 use syntax::parse::token::InternedString;
36 use rustc_front::visit::Visitor;
37 use rustc_front::visit;
40 use std::iter::Enumerate;
43 // The actual lang items defined come at the end of this file in one handy table.
44 // So you probably just want to nip down to the end.
45 macro_rules! lets_do_this {
47 $( $variant:ident, $name:expr, $method:ident; )*
52 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
58 pub struct LanguageItems {
59 pub items: Vec<Option<DefId>>,
60 pub missing: Vec<LangItem>,
64 pub fn new() -> LanguageItems {
65 fn foo(_: LangItem) -> Option<DefId> { None }
68 items: vec!($(foo($variant)),*),
73 pub fn items<'a>(&'a self) -> Enumerate<slice::Iter<'a, Option<DefId>>> {
74 self.items.iter().enumerate()
77 pub fn item_name(index: usize) -> &'static str {
78 let item: Option<LangItem> = LangItem::from_u32(index as u32);
80 $( Some($variant) => $name, )*
85 pub fn require(&self, it: LangItem) -> Result<DefId, String> {
86 match self.items[it as usize] {
89 Err(format!("requires `{}` lang_item",
90 LanguageItems::item_name(it as usize)))
95 pub fn require_owned_box(&self) -> Result<DefId, String> {
96 self.require(OwnedBoxLangItem)
99 pub fn from_builtin_kind(&self, bound: ty::BuiltinBound)
100 -> Result<DefId, String>
103 ty::BoundSend => self.require(SendTraitLangItem),
104 ty::BoundSized => self.require(SizedTraitLangItem),
105 ty::BoundCopy => self.require(CopyTraitLangItem),
106 ty::BoundSync => self.require(SyncTraitLangItem),
110 pub fn to_builtin_kind(&self, id: DefId) -> Option<ty::BuiltinBound> {
111 if Some(id) == self.send_trait() {
113 } else if Some(id) == self.sized_trait() {
115 } else if Some(id) == self.copy_trait() {
117 } else if Some(id) == self.sync_trait() {
124 pub fn fn_trait_kind(&self, id: DefId) -> Option<ty::ClosureKind> {
126 (self.fn_trait(), ty::FnClosureKind),
127 (self.fn_mut_trait(), ty::FnMutClosureKind),
128 (self.fn_once_trait(), ty::FnOnceClosureKind),
131 for &(opt_def_id, kind) in &def_id_kinds {
132 if Some(id) == opt_def_id {
142 pub fn $method(&self) -> Option<DefId> {
143 self.items[$variant as usize]
148 struct LanguageItemCollector<'a, 'tcx: 'a> {
149 items: LanguageItems,
151 ast_map: &'a hir_map::Map<'tcx>,
153 session: &'a Session,
155 item_refs: FnvHashMap<&'static str, usize>,
158 impl<'a, 'v, 'tcx> Visitor<'v> for LanguageItemCollector<'a, 'tcx> {
159 fn visit_item(&mut self, item: &hir::Item) {
160 if let Some(value) = extract(&item.attrs) {
161 let item_index = self.item_refs.get(&value[..]).cloned();
163 if let Some(item_index) = item_index {
164 self.collect_item(item_index, self.ast_map.local_def_id(item.id), item.span)
168 visit::walk_item(self, item);
172 impl<'a, 'tcx> LanguageItemCollector<'a, 'tcx> {
173 pub fn new(session: &'a Session, ast_map: &'a hir_map::Map<'tcx>)
174 -> LanguageItemCollector<'a, 'tcx> {
175 let mut item_refs = FnvHashMap();
177 $( item_refs.insert($name, $variant as usize); )*
179 LanguageItemCollector {
182 items: LanguageItems::new(),
183 item_refs: item_refs,
187 pub fn collect_item(&mut self, item_index: usize,
188 item_def_id: DefId, span: Span) {
189 // Check for duplicates.
190 match self.items.items[item_index] {
191 Some(original_def_id) if original_def_id != item_def_id => {
192 span_err!(self.session, span, E0152,
193 "duplicate entry for `{}`", LanguageItems::item_name(item_index));
201 self.items.items[item_index] = Some(item_def_id);
204 pub fn collect_local_language_items(&mut self, krate: &hir::Crate) {
205 visit::walk_crate(self, krate);
208 pub fn collect_external_language_items(&mut self) {
209 let crate_store = &self.session.cstore;
210 crate_store.iter_crate_data(|crate_number, _crate_metadata| {
211 each_lang_item(crate_store, crate_number, |node_id, item_index| {
212 let def_id = DefId { krate: crate_number, node: node_id };
213 self.collect_item(item_index, def_id, DUMMY_SP);
219 pub fn collect(&mut self, krate: &hir::Crate) {
220 self.collect_local_language_items(krate);
221 self.collect_external_language_items();
225 pub fn extract(attrs: &[ast::Attribute]) -> Option<InternedString> {
226 for attribute in attrs {
227 match attribute.value_str() {
228 Some(ref value) if attribute.check_name("lang") => {
229 return Some(value.clone());
238 pub fn collect_language_items(session: &Session,
241 let krate: &hir::Crate = map.krate();
242 let mut collector = LanguageItemCollector::new(session, map);
243 collector.collect(krate);
244 let LanguageItemCollector { mut items, .. } = collector;
245 weak_lang_items::check_crate(krate, session, &mut items);
246 session.abort_if_errors();
255 // Variant name, Name, Method name;
256 CharImplItem, "char", char_impl;
257 StrImplItem, "str", str_impl;
258 SliceImplItem, "slice", slice_impl;
259 ConstPtrImplItem, "const_ptr", const_ptr_impl;
260 MutPtrImplItem, "mut_ptr", mut_ptr_impl;
261 I8ImplItem, "i8", i8_impl;
262 I16ImplItem, "i16", i16_impl;
263 I32ImplItem, "i32", i32_impl;
264 I64ImplItem, "i64", i64_impl;
265 IsizeImplItem, "isize", isize_impl;
266 U8ImplItem, "u8", u8_impl;
267 U16ImplItem, "u16", u16_impl;
268 U32ImplItem, "u32", u32_impl;
269 U64ImplItem, "u64", u64_impl;
270 UsizeImplItem, "usize", usize_impl;
271 F32ImplItem, "f32", f32_impl;
272 F64ImplItem, "f64", f64_impl;
274 SendTraitLangItem, "send", send_trait;
275 SizedTraitLangItem, "sized", sized_trait;
276 UnsizeTraitLangItem, "unsize", unsize_trait;
277 CopyTraitLangItem, "copy", copy_trait;
278 SyncTraitLangItem, "sync", sync_trait;
280 DropTraitLangItem, "drop", drop_trait;
282 CoerceUnsizedTraitLangItem, "coerce_unsized", coerce_unsized_trait;
284 AddTraitLangItem, "add", add_trait;
285 SubTraitLangItem, "sub", sub_trait;
286 MulTraitLangItem, "mul", mul_trait;
287 DivTraitLangItem, "div", div_trait;
288 RemTraitLangItem, "rem", rem_trait;
289 NegTraitLangItem, "neg", neg_trait;
290 NotTraitLangItem, "not", not_trait;
291 BitXorTraitLangItem, "bitxor", bitxor_trait;
292 BitAndTraitLangItem, "bitand", bitand_trait;
293 BitOrTraitLangItem, "bitor", bitor_trait;
294 ShlTraitLangItem, "shl", shl_trait;
295 ShrTraitLangItem, "shr", shr_trait;
296 AddAssignTraitLangItem, "add_assign", add_assign_trait;
297 SubAssignTraitLangItem, "sub_assign", sub_assign_trait;
298 MulAssignTraitLangItem, "mul_assign", mul_assign_trait;
299 DivAssignTraitLangItem, "div_assign", div_assign_trait;
300 RemAssignTraitLangItem, "rem_assign", rem_assign_trait;
301 BitXorAssignTraitLangItem, "bitxor_assign", bitxor_assign_trait;
302 BitAndAssignTraitLangItem, "bitand_assign", bitand_assign_trait;
303 BitOrAssignTraitLangItem, "bitor_assign", bitor_assign_trait;
304 ShlAssignTraitLangItem, "shl_assign", shl_assign_trait;
305 ShrAssignTraitLangItem, "shr_assign", shr_assign_trait;
306 IndexTraitLangItem, "index", index_trait;
307 IndexMutTraitLangItem, "index_mut", index_mut_trait;
308 RangeStructLangItem, "range", range_struct;
309 RangeFromStructLangItem, "range_from", range_from_struct;
310 RangeToStructLangItem, "range_to", range_to_struct;
311 RangeFullStructLangItem, "range_full", range_full_struct;
313 UnsafeCellTypeLangItem, "unsafe_cell", unsafe_cell_type;
315 DerefTraitLangItem, "deref", deref_trait;
316 DerefMutTraitLangItem, "deref_mut", deref_mut_trait;
318 FnTraitLangItem, "fn", fn_trait;
319 FnMutTraitLangItem, "fn_mut", fn_mut_trait;
320 FnOnceTraitLangItem, "fn_once", fn_once_trait;
322 EqTraitLangItem, "eq", eq_trait;
323 OrdTraitLangItem, "ord", ord_trait;
325 StrEqFnLangItem, "str_eq", str_eq_fn;
327 // A number of panic-related lang items. The `panic` item corresponds to
328 // divide-by-zero and various panic cases with `match`. The
329 // `panic_bounds_check` item is for indexing arrays.
331 // The `begin_unwind` lang item has a predefined symbol name and is sort of
332 // a "weak lang item" in the sense that a crate is not required to have it
333 // defined to use it, but a final product is required to define it
334 // somewhere. Additionally, there are restrictions on crates that use a weak
335 // lang item, but do not have it defined.
336 PanicFnLangItem, "panic", panic_fn;
337 PanicBoundsCheckFnLangItem, "panic_bounds_check", panic_bounds_check_fn;
338 PanicFmtLangItem, "panic_fmt", panic_fmt;
340 ExchangeMallocFnLangItem, "exchange_malloc", exchange_malloc_fn;
341 ExchangeFreeFnLangItem, "exchange_free", exchange_free_fn;
342 StrDupUniqFnLangItem, "strdup_uniq", strdup_uniq_fn;
344 StartFnLangItem, "start", start_fn;
346 EhPersonalityLangItem, "eh_personality", eh_personality;
347 EhPersonalityCatchLangItem, "eh_personality_catch", eh_personality_catch;
348 EhUnwindResumeLangItem, "eh_unwind_resume", eh_unwind_resume;
349 MSVCTryFilterLangItem, "msvc_try_filter", msvc_try_filter;
351 OwnedBoxLangItem, "owned_box", owned_box;
353 PhantomDataItem, "phantom_data", phantom_data;
356 CovariantTypeItem, "covariant_type", covariant_type;
357 ContravariantTypeItem, "contravariant_type", contravariant_type;
358 InvariantTypeItem, "invariant_type", invariant_type;
359 CovariantLifetimeItem, "covariant_lifetime", covariant_lifetime;
360 ContravariantLifetimeItem, "contravariant_lifetime", contravariant_lifetime;
361 InvariantLifetimeItem, "invariant_lifetime", invariant_lifetime;
363 NoCopyItem, "no_copy_bound", no_copy_bound;
365 NonZeroItem, "non_zero", non_zero;
367 DebugTraitLangItem, "debug_trait", debug_trait;