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;
27 use middle::weak_lang_items;
28 use util::nodemap::FnvHashMap;
31 use syntax::ast_util::local_def;
32 use syntax::attr::AttrMetaMethods;
33 use syntax::codemap::{DUMMY_SP, Span};
34 use syntax::parse::token::InternedString;
35 use syntax::visit::Visitor;
38 use std::iter::Enumerate;
39 use std::num::FromPrimitive;
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; )*
49 #[deriving(Copy, FromPrimitive, PartialEq, Eq, Hash)]
54 pub struct LanguageItems {
55 pub items: Vec<Option<ast::DefId>>,
56 pub missing: Vec<LangItem>,
60 pub fn new() -> LanguageItems {
61 fn foo(_: LangItem) -> Option<ast::DefId> { None }
64 items: vec!($(foo($variant)),*),
69 pub fn items<'a>(&'a self) -> Enumerate<slice::Iter<'a, Option<ast::DefId>>> {
70 self.items.iter().enumerate()
73 pub fn item_name(index: uint) -> &'static str {
74 let item: Option<LangItem> = FromPrimitive::from_uint(index);
76 $( Some($variant) => $name, )*
81 pub fn require(&self, it: LangItem) -> Result<ast::DefId, String> {
82 match self.items[it as uint] {
85 Err(format!("requires `{}` lang_item",
86 LanguageItems::item_name(it as uint)))
91 pub fn from_builtin_kind(&self, bound: ty::BuiltinBound)
92 -> Result<ast::DefId, String>
95 ty::BoundSend => self.require(SendTraitLangItem),
96 ty::BoundSized => self.require(SizedTraitLangItem),
97 ty::BoundCopy => self.require(CopyTraitLangItem),
98 ty::BoundSync => self.require(SyncTraitLangItem),
102 pub fn to_builtin_kind(&self, id: ast::DefId) -> Option<ty::BuiltinBound> {
103 if Some(id) == self.send_trait() {
105 } else if Some(id) == self.sized_trait() {
107 } else if Some(id) == self.copy_trait() {
109 } else if Some(id) == self.sync_trait() {
116 pub fn fn_trait_kind(&self, id: ast::DefId) -> Option<ty::UnboxedClosureKind> {
118 (self.fn_trait(), ty::FnUnboxedClosureKind),
119 (self.fn_mut_trait(), ty::FnMutUnboxedClosureKind),
120 (self.fn_once_trait(), ty::FnOnceUnboxedClosureKind),
123 for &(opt_def_id, kind) in def_id_kinds.iter() {
124 if Some(id) == opt_def_id {
134 pub fn $method(&self) -> Option<ast::DefId> {
135 self.items[$variant as uint]
140 struct LanguageItemCollector<'a> {
141 items: LanguageItems,
143 session: &'a Session,
145 item_refs: FnvHashMap<&'static str, uint>,
148 impl<'a, 'v> Visitor<'v> for LanguageItemCollector<'a> {
149 fn visit_item(&mut self, item: &ast::Item) {
150 match extract(item.attrs.as_slice()) {
152 let item_index = self.item_refs.get(value.get()).map(|x| *x);
155 Some(item_index) => {
156 self.collect_item(item_index, local_def(item.id), item.span)
164 visit::walk_item(self, item);
168 impl<'a> LanguageItemCollector<'a> {
169 pub fn new(session: &'a Session) -> LanguageItemCollector<'a> {
170 let mut item_refs = FnvHashMap::new();
172 $( item_refs.insert($name, $variant as uint); )*
174 LanguageItemCollector {
176 items: LanguageItems::new(),
181 pub fn collect_item(&mut self, item_index: uint,
182 item_def_id: ast::DefId, span: Span) {
183 // Check for duplicates.
184 match self.items.items[item_index] {
185 Some(original_def_id) if original_def_id != item_def_id => {
186 span_err!(self.session, span, E0152,
187 "duplicate entry for `{}`", LanguageItems::item_name(item_index));
195 self.items.items[item_index] = Some(item_def_id);
198 pub fn collect_local_language_items(&mut self, krate: &ast::Crate) {
199 visit::walk_crate(self, krate);
202 pub fn collect_external_language_items(&mut self) {
203 let crate_store = &self.session.cstore;
204 crate_store.iter_crate_data(|crate_number, _crate_metadata| {
205 each_lang_item(crate_store, crate_number, |node_id, item_index| {
206 let def_id = ast::DefId { krate: crate_number, node: node_id };
207 self.collect_item(item_index, def_id, DUMMY_SP);
213 pub fn collect(&mut self, krate: &ast::Crate) {
214 self.collect_local_language_items(krate);
215 self.collect_external_language_items();
219 pub fn extract(attrs: &[ast::Attribute]) -> Option<InternedString> {
220 for attribute in attrs.iter() {
221 match attribute.value_str() {
222 Some(ref value) if attribute.check_name("lang") => {
223 return Some(value.clone());
232 pub fn collect_language_items(krate: &ast::Crate,
233 session: &Session) -> LanguageItems {
234 let mut collector = LanguageItemCollector::new(session);
235 collector.collect(krate);
236 let LanguageItemCollector { mut items, .. } = collector;
237 weak_lang_items::check_crate(krate, session, &mut items);
238 session.abort_if_errors();
247 // Variant name, Name, Method name;
248 SendTraitLangItem, "send", send_trait;
249 SizedTraitLangItem, "sized", sized_trait;
250 CopyTraitLangItem, "copy", copy_trait;
251 SyncTraitLangItem, "sync", sync_trait;
253 DropTraitLangItem, "drop", drop_trait;
255 AddTraitLangItem, "add", add_trait;
256 SubTraitLangItem, "sub", sub_trait;
257 MulTraitLangItem, "mul", mul_trait;
258 DivTraitLangItem, "div", div_trait;
259 RemTraitLangItem, "rem", rem_trait;
260 NegTraitLangItem, "neg", neg_trait;
261 NotTraitLangItem, "not", not_trait;
262 BitXorTraitLangItem, "bitxor", bitxor_trait;
263 BitAndTraitLangItem, "bitand", bitand_trait;
264 BitOrTraitLangItem, "bitor", bitor_trait;
265 ShlTraitLangItem, "shl", shl_trait;
266 ShrTraitLangItem, "shr", shr_trait;
267 IndexTraitLangItem, "index", index_trait;
268 IndexMutTraitLangItem, "index_mut", index_mut_trait;
269 SliceTraitLangItem, "slice", slice_trait;
270 SliceMutTraitLangItem, "slice_mut", slice_mut_trait;
271 RangeStructLangItem, "range", range_struct;
272 RangeFromStructLangItem, "range_from", range_from_struct;
273 RangeToStructLangItem, "range_to", range_to_struct;
274 FullRangeStructLangItem, "full_range", full_range_struct;
276 UnsafeTypeLangItem, "unsafe", unsafe_type;
278 DerefTraitLangItem, "deref", deref_trait;
279 DerefMutTraitLangItem, "deref_mut", deref_mut_trait;
281 FnTraitLangItem, "fn", fn_trait;
282 FnMutTraitLangItem, "fn_mut", fn_mut_trait;
283 FnOnceTraitLangItem, "fn_once", fn_once_trait;
285 EqTraitLangItem, "eq", eq_trait;
286 OrdTraitLangItem, "ord", ord_trait;
288 StrEqFnLangItem, "str_eq", str_eq_fn;
290 // A number of panic-related lang items. The `panic` item corresponds to
291 // divide-by-zero and various panic cases with `match`. The
292 // `panic_bounds_check` item is for indexing arrays.
294 // The `begin_unwind` lang item has a predefined symbol name and is sort of
295 // a "weak lang item" in the sense that a crate is not required to have it
296 // defined to use it, but a final product is required to define it
297 // somewhere. Additionally, there are restrictions on crates that use a weak
298 // lang item, but do not have it defined.
299 PanicFnLangItem, "panic", panic_fn;
300 PanicBoundsCheckFnLangItem, "panic_bounds_check", panic_bounds_check_fn;
301 PanicFmtLangItem, "panic_fmt", panic_fmt;
303 ExchangeMallocFnLangItem, "exchange_malloc", exchange_malloc_fn;
304 ExchangeFreeFnLangItem, "exchange_free", exchange_free_fn;
305 StrDupUniqFnLangItem, "strdup_uniq", strdup_uniq_fn;
307 StartFnLangItem, "start", start_fn;
309 TyDescStructLangItem, "ty_desc", ty_desc;
310 OpaqueStructLangItem, "opaque", opaque;
312 TypeIdLangItem, "type_id", type_id;
314 EhPersonalityLangItem, "eh_personality", eh_personality;
316 ExchangeHeapLangItem, "exchange_heap", exchange_heap;
317 OwnedBoxLangItem, "owned_box", owned_box;
319 CovariantTypeItem, "covariant_type", covariant_type;
320 ContravariantTypeItem, "contravariant_type", contravariant_type;
321 InvariantTypeItem, "invariant_type", invariant_type;
323 CovariantLifetimeItem, "covariant_lifetime", covariant_lifetime;
324 ContravariantLifetimeItem, "contravariant_lifetime", contravariant_lifetime;
325 InvariantLifetimeItem, "invariant_lifetime", invariant_lifetime;
327 NoSendItem, "no_send_bound", no_send_bound;
328 NoCopyItem, "no_copy_bound", no_copy_bound;
329 NoSyncItem, "no_sync_bound", no_sync_bound;
330 ManagedItem, "managed_bound", managed_bound;
332 NonZeroItem, "non_zero", non_zero;
334 IteratorItem, "iterator", iterator;
336 StackExhaustedLangItem, "stack_exhausted", stack_exhausted;