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 #[derive(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::ClosureKind> {
118 (self.fn_trait(), ty::FnClosureKind),
119 (self.fn_mut_trait(), ty::FnMutClosureKind),
120 (self.fn_once_trait(), ty::FnOnceClosureKind),
123 for &(opt_def_id, kind) in &def_id_kinds {
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 if let Some(value) = extract(&item.attrs) {
151 let item_index = self.item_refs.get(&value[..]).cloned();
153 if let Some(item_index) = item_index {
154 self.collect_item(item_index, local_def(item.id), item.span)
158 visit::walk_item(self, item);
162 impl<'a> LanguageItemCollector<'a> {
163 pub fn new(session: &'a Session) -> LanguageItemCollector<'a> {
164 let mut item_refs = FnvHashMap();
166 $( item_refs.insert($name, $variant as uint); )*
168 LanguageItemCollector {
170 items: LanguageItems::new(),
175 pub fn collect_item(&mut self, item_index: uint,
176 item_def_id: ast::DefId, span: Span) {
177 // Check for duplicates.
178 match self.items.items[item_index] {
179 Some(original_def_id) if original_def_id != item_def_id => {
180 span_err!(self.session, span, E0152,
181 "duplicate entry for `{}`", LanguageItems::item_name(item_index));
189 self.items.items[item_index] = Some(item_def_id);
192 pub fn collect_local_language_items(&mut self, krate: &ast::Crate) {
193 visit::walk_crate(self, krate);
196 pub fn collect_external_language_items(&mut self) {
197 let crate_store = &self.session.cstore;
198 crate_store.iter_crate_data(|crate_number, _crate_metadata| {
199 each_lang_item(crate_store, crate_number, |node_id, item_index| {
200 let def_id = ast::DefId { krate: crate_number, node: node_id };
201 self.collect_item(item_index, def_id, DUMMY_SP);
207 pub fn collect(&mut self, krate: &ast::Crate) {
208 self.collect_local_language_items(krate);
209 self.collect_external_language_items();
213 pub fn extract(attrs: &[ast::Attribute]) -> Option<InternedString> {
214 for attribute in attrs {
215 match attribute.value_str() {
216 Some(ref value) if attribute.check_name("lang") => {
217 return Some(value.clone());
226 pub fn collect_language_items(krate: &ast::Crate,
227 session: &Session) -> LanguageItems {
228 let mut collector = LanguageItemCollector::new(session);
229 collector.collect(krate);
230 let LanguageItemCollector { mut items, .. } = collector;
231 weak_lang_items::check_crate(krate, session, &mut items);
232 session.abort_if_errors();
241 // Variant name, Name, Method name;
242 SendTraitLangItem, "send", send_trait;
243 SizedTraitLangItem, "sized", sized_trait;
244 CopyTraitLangItem, "copy", copy_trait;
245 SyncTraitLangItem, "sync", sync_trait;
247 DropTraitLangItem, "drop", drop_trait;
249 AddTraitLangItem, "add", add_trait;
250 SubTraitLangItem, "sub", sub_trait;
251 MulTraitLangItem, "mul", mul_trait;
252 DivTraitLangItem, "div", div_trait;
253 RemTraitLangItem, "rem", rem_trait;
254 NegTraitLangItem, "neg", neg_trait;
255 NotTraitLangItem, "not", not_trait;
256 BitXorTraitLangItem, "bitxor", bitxor_trait;
257 BitAndTraitLangItem, "bitand", bitand_trait;
258 BitOrTraitLangItem, "bitor", bitor_trait;
259 ShlTraitLangItem, "shl", shl_trait;
260 ShrTraitLangItem, "shr", shr_trait;
261 IndexTraitLangItem, "index", index_trait;
262 IndexMutTraitLangItem, "index_mut", index_mut_trait;
263 RangeStructLangItem, "range", range_struct;
264 RangeFromStructLangItem, "range_from", range_from_struct;
265 RangeToStructLangItem, "range_to", range_to_struct;
266 RangeFullStructLangItem, "range_full", range_full_struct;
268 UnsafeCellTypeLangItem, "unsafe_cell", unsafe_cell_type;
270 DerefTraitLangItem, "deref", deref_trait;
271 DerefMutTraitLangItem, "deref_mut", deref_mut_trait;
273 FnTraitLangItem, "fn", fn_trait;
274 FnMutTraitLangItem, "fn_mut", fn_mut_trait;
275 FnOnceTraitLangItem, "fn_once", fn_once_trait;
277 EqTraitLangItem, "eq", eq_trait;
278 OrdTraitLangItem, "ord", ord_trait;
280 StrEqFnLangItem, "str_eq", str_eq_fn;
282 // A number of panic-related lang items. The `panic` item corresponds to
283 // divide-by-zero and various panic cases with `match`. The
284 // `panic_bounds_check` item is for indexing arrays.
286 // The `begin_unwind` lang item has a predefined symbol name and is sort of
287 // a "weak lang item" in the sense that a crate is not required to have it
288 // defined to use it, but a final product is required to define it
289 // somewhere. Additionally, there are restrictions on crates that use a weak
290 // lang item, but do not have it defined.
291 PanicFnLangItem, "panic", panic_fn;
292 PanicBoundsCheckFnLangItem, "panic_bounds_check", panic_bounds_check_fn;
293 PanicFmtLangItem, "panic_fmt", panic_fmt;
295 ExchangeMallocFnLangItem, "exchange_malloc", exchange_malloc_fn;
296 ExchangeFreeFnLangItem, "exchange_free", exchange_free_fn;
297 StrDupUniqFnLangItem, "strdup_uniq", strdup_uniq_fn;
299 StartFnLangItem, "start", start_fn;
301 TyDescStructLangItem, "ty_desc", ty_desc;
302 OpaqueStructLangItem, "opaque", opaque;
304 EhPersonalityLangItem, "eh_personality", eh_personality;
306 ExchangeHeapLangItem, "exchange_heap", exchange_heap;
307 OwnedBoxLangItem, "owned_box", owned_box;
309 PhantomFnItem, "phantom_fn", phantom_fn;
310 PhantomDataItem, "phantom_data", phantom_data;
313 CovariantTypeItem, "covariant_type", covariant_type;
314 ContravariantTypeItem, "contravariant_type", contravariant_type;
315 InvariantTypeItem, "invariant_type", invariant_type;
316 CovariantLifetimeItem, "covariant_lifetime", covariant_lifetime;
317 ContravariantLifetimeItem, "contravariant_lifetime", contravariant_lifetime;
318 InvariantLifetimeItem, "invariant_lifetime", invariant_lifetime;
320 NoCopyItem, "no_copy_bound", no_copy_bound;
321 ManagedItem, "managed_bound", managed_bound;
323 NonZeroItem, "non_zero", non_zero;
325 StackExhaustedLangItem, "stack_exhausted", stack_exhausted;
327 DebugTraitLangItem, "debug_trait", debug_trait;