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::*;
25 use metadata::csearch::each_lang_item;
26 use middle::def_id::DefId;
28 use middle::weak_lang_items;
29 use util::nodemap::FnvHashMap;
32 use syntax::attr::AttrMetaMethods;
33 use syntax::codemap::{DUMMY_SP, Span};
34 use syntax::parse::token::InternedString;
35 use rustc_front::visit::Visitor;
36 use rustc_front::visit;
39 use std::iter::Enumerate;
42 // The actual lang items defined come at the end of this file in one handy table.
43 // So you probably just want to nip down to the end.
44 macro_rules! lets_do_this {
46 $( $variant:ident, $name:expr, $method:ident; )*
51 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
57 pub struct LanguageItems {
58 pub items: Vec<Option<DefId>>,
59 pub missing: Vec<LangItem>,
63 pub fn new() -> LanguageItems {
64 fn foo(_: LangItem) -> Option<DefId> { None }
67 items: vec!($(foo($variant)),*),
72 pub fn items<'a>(&'a self) -> Enumerate<slice::Iter<'a, Option<DefId>>> {
73 self.items.iter().enumerate()
76 pub fn item_name(index: usize) -> &'static str {
77 let item: Option<LangItem> = LangItem::from_u32(index as u32);
79 $( Some($variant) => $name, )*
84 pub fn require(&self, it: LangItem) -> Result<DefId, String> {
85 match self.items[it as usize] {
88 Err(format!("requires `{}` lang_item",
89 LanguageItems::item_name(it as usize)))
94 pub fn require_owned_box(&self) -> Result<DefId, String> {
95 self.require(OwnedBoxLangItem)
98 pub fn from_builtin_kind(&self, bound: ty::BuiltinBound)
99 -> Result<DefId, String>
102 ty::BoundSend => self.require(SendTraitLangItem),
103 ty::BoundSized => self.require(SizedTraitLangItem),
104 ty::BoundCopy => self.require(CopyTraitLangItem),
105 ty::BoundSync => self.require(SyncTraitLangItem),
109 pub fn to_builtin_kind(&self, id: DefId) -> Option<ty::BuiltinBound> {
110 if Some(id) == self.send_trait() {
112 } else if Some(id) == self.sized_trait() {
114 } else if Some(id) == self.copy_trait() {
116 } else if Some(id) == self.sync_trait() {
123 pub fn fn_trait_kind(&self, id: DefId) -> Option<ty::ClosureKind> {
125 (self.fn_trait(), ty::FnClosureKind),
126 (self.fn_mut_trait(), ty::FnMutClosureKind),
127 (self.fn_once_trait(), ty::FnOnceClosureKind),
130 for &(opt_def_id, kind) in &def_id_kinds {
131 if Some(id) == opt_def_id {
141 pub fn $method(&self) -> Option<DefId> {
142 self.items[$variant as usize]
147 struct LanguageItemCollector<'a> {
148 items: LanguageItems,
150 session: &'a Session,
152 item_refs: FnvHashMap<&'static str, usize>,
155 impl<'a, 'v> Visitor<'v> for LanguageItemCollector<'a> {
156 fn visit_item(&mut self, item: &hir::Item) {
157 if let Some(value) = extract(&item.attrs) {
158 let item_index = self.item_refs.get(&value[..]).cloned();
160 if let Some(item_index) = item_index {
161 self.collect_item(item_index, DefId::local(item.id), item.span)
165 visit::walk_item(self, item);
169 impl<'a> LanguageItemCollector<'a> {
170 pub fn new(session: &'a Session) -> LanguageItemCollector<'a> {
171 let mut item_refs = FnvHashMap();
173 $( item_refs.insert($name, $variant as usize); )*
175 LanguageItemCollector {
177 items: LanguageItems::new(),
182 pub fn collect_item(&mut self, item_index: usize,
183 item_def_id: DefId, span: Span) {
184 // Check for duplicates.
185 match self.items.items[item_index] {
186 Some(original_def_id) if original_def_id != item_def_id => {
187 span_err!(self.session, span, E0152,
188 "duplicate entry for `{}`", LanguageItems::item_name(item_index));
196 self.items.items[item_index] = Some(item_def_id);
199 pub fn collect_local_language_items(&mut self, krate: &hir::Crate) {
200 visit::walk_crate(self, krate);
203 pub fn collect_external_language_items(&mut self) {
204 let crate_store = &self.session.cstore;
205 crate_store.iter_crate_data(|crate_number, _crate_metadata| {
206 each_lang_item(crate_store, crate_number, |node_id, item_index| {
207 let def_id = DefId { krate: crate_number, node: node_id };
208 self.collect_item(item_index, def_id, DUMMY_SP);
214 pub fn collect(&mut self, krate: &hir::Crate) {
215 self.collect_local_language_items(krate);
216 self.collect_external_language_items();
220 pub fn extract(attrs: &[ast::Attribute]) -> Option<InternedString> {
221 for attribute in attrs {
222 match attribute.value_str() {
223 Some(ref value) if attribute.check_name("lang") => {
224 return Some(value.clone());
233 pub fn collect_language_items(krate: &hir::Crate,
234 session: &Session) -> LanguageItems {
235 let mut collector = LanguageItemCollector::new(session);
236 collector.collect(krate);
237 let LanguageItemCollector { mut items, .. } = collector;
238 weak_lang_items::check_crate(krate, session, &mut items);
239 session.abort_if_errors();
248 // Variant name, Name, Method name;
249 CharImplItem, "char", char_impl;
250 StrImplItem, "str", str_impl;
251 SliceImplItem, "slice", slice_impl;
252 ConstPtrImplItem, "const_ptr", const_ptr_impl;
253 MutPtrImplItem, "mut_ptr", mut_ptr_impl;
254 I8ImplItem, "i8", i8_impl;
255 I16ImplItem, "i16", i16_impl;
256 I32ImplItem, "i32", i32_impl;
257 I64ImplItem, "i64", i64_impl;
258 IsizeImplItem, "isize", isize_impl;
259 U8ImplItem, "u8", u8_impl;
260 U16ImplItem, "u16", u16_impl;
261 U32ImplItem, "u32", u32_impl;
262 U64ImplItem, "u64", u64_impl;
263 UsizeImplItem, "usize", usize_impl;
264 F32ImplItem, "f32", f32_impl;
265 F64ImplItem, "f64", f64_impl;
267 SendTraitLangItem, "send", send_trait;
268 SizedTraitLangItem, "sized", sized_trait;
269 UnsizeTraitLangItem, "unsize", unsize_trait;
270 CopyTraitLangItem, "copy", copy_trait;
271 SyncTraitLangItem, "sync", sync_trait;
273 DropTraitLangItem, "drop", drop_trait;
275 CoerceUnsizedTraitLangItem, "coerce_unsized", coerce_unsized_trait;
277 AddTraitLangItem, "add", add_trait;
278 SubTraitLangItem, "sub", sub_trait;
279 MulTraitLangItem, "mul", mul_trait;
280 DivTraitLangItem, "div", div_trait;
281 RemTraitLangItem, "rem", rem_trait;
282 NegTraitLangItem, "neg", neg_trait;
283 NotTraitLangItem, "not", not_trait;
284 BitXorTraitLangItem, "bitxor", bitxor_trait;
285 BitAndTraitLangItem, "bitand", bitand_trait;
286 BitOrTraitLangItem, "bitor", bitor_trait;
287 ShlTraitLangItem, "shl", shl_trait;
288 ShrTraitLangItem, "shr", shr_trait;
289 AddAssignTraitLangItem, "add_assign", add_assign_trait;
290 SubAssignTraitLangItem, "sub_assign", sub_assign_trait;
291 MulAssignTraitLangItem, "mul_assign", mul_assign_trait;
292 DivAssignTraitLangItem, "div_assign", div_assign_trait;
293 RemAssignTraitLangItem, "rem_assign", rem_assign_trait;
294 BitXorAssignTraitLangItem, "bitxor_assign", bitxor_assign_trait;
295 BitAndAssignTraitLangItem, "bitand_assign", bitand_assign_trait;
296 BitOrAssignTraitLangItem, "bitor_assign", bitor_assign_trait;
297 ShlAssignTraitLangItem, "shl_assign", shl_assign_trait;
298 ShrAssignTraitLangItem, "shr_assign", shr_assign_trait;
299 IndexTraitLangItem, "index", index_trait;
300 IndexMutTraitLangItem, "index_mut", index_mut_trait;
301 RangeStructLangItem, "range", range_struct;
302 RangeFromStructLangItem, "range_from", range_from_struct;
303 RangeToStructLangItem, "range_to", range_to_struct;
304 RangeFullStructLangItem, "range_full", range_full_struct;
306 UnsafeCellTypeLangItem, "unsafe_cell", unsafe_cell_type;
308 DerefTraitLangItem, "deref", deref_trait;
309 DerefMutTraitLangItem, "deref_mut", deref_mut_trait;
311 FnTraitLangItem, "fn", fn_trait;
312 FnMutTraitLangItem, "fn_mut", fn_mut_trait;
313 FnOnceTraitLangItem, "fn_once", fn_once_trait;
315 EqTraitLangItem, "eq", eq_trait;
316 OrdTraitLangItem, "ord", ord_trait;
318 StrEqFnLangItem, "str_eq", str_eq_fn;
320 // A number of panic-related lang items. The `panic` item corresponds to
321 // divide-by-zero and various panic cases with `match`. The
322 // `panic_bounds_check` item is for indexing arrays.
324 // The `begin_unwind` lang item has a predefined symbol name and is sort of
325 // a "weak lang item" in the sense that a crate is not required to have it
326 // defined to use it, but a final product is required to define it
327 // somewhere. Additionally, there are restrictions on crates that use a weak
328 // lang item, but do not have it defined.
329 PanicFnLangItem, "panic", panic_fn;
330 PanicBoundsCheckFnLangItem, "panic_bounds_check", panic_bounds_check_fn;
331 PanicFmtLangItem, "panic_fmt", panic_fmt;
333 ExchangeMallocFnLangItem, "exchange_malloc", exchange_malloc_fn;
334 ExchangeFreeFnLangItem, "exchange_free", exchange_free_fn;
335 StrDupUniqFnLangItem, "strdup_uniq", strdup_uniq_fn;
337 StartFnLangItem, "start", start_fn;
339 EhPersonalityLangItem, "eh_personality", eh_personality;
340 EhPersonalityCatchLangItem, "eh_personality_catch", eh_personality_catch;
341 EhUnwindResumeLangItem, "eh_unwind_resume", eh_unwind_resume;
342 MSVCTryFilterLangItem, "msvc_try_filter", msvc_try_filter;
344 ExchangeHeapLangItem, "exchange_heap", exchange_heap;
345 OwnedBoxLangItem, "owned_box", owned_box;
347 PhantomDataItem, "phantom_data", phantom_data;
350 CovariantTypeItem, "covariant_type", covariant_type;
351 ContravariantTypeItem, "contravariant_type", contravariant_type;
352 InvariantTypeItem, "invariant_type", invariant_type;
353 CovariantLifetimeItem, "covariant_lifetime", covariant_lifetime;
354 ContravariantLifetimeItem, "contravariant_lifetime", contravariant_lifetime;
355 InvariantLifetimeItem, "invariant_lifetime", invariant_lifetime;
357 NoCopyItem, "no_copy_bound", no_copy_bound;
359 NonZeroItem, "non_zero", non_zero;
361 DebugTraitLangItem, "debug_trait", debug_trait;