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.
23 use driver::session::Session;
24 use metadata::csearch::each_lang_item;
26 use middle::weak_lang_items;
28 use syntax::ast_util::local_def;
29 use syntax::attr::AttrMetaMethods;
30 use syntax::codemap::{DUMMY_SP, Span};
31 use syntax::parse::token::InternedString;
32 use syntax::visit::Visitor;
35 use std::collections::HashMap;
36 use std::iter::Enumerate;
39 // The actual lang items defined come at the end of this file in one handy table.
40 // So you probably just want to nip down to the end.
41 macro_rules! lets_do_this {
43 $( $variant:ident, $name:expr, $method:ident; )*
46 #[deriving(FromPrimitive, PartialEq, Eq, Hash)]
51 pub struct LanguageItems {
52 pub items: Vec<Option<ast::DefId>>,
53 pub missing: Vec<LangItem>,
57 pub fn new() -> LanguageItems {
58 fn foo(_: LangItem) -> Option<ast::DefId> { None }
61 items: vec!($(foo($variant)),*),
66 pub fn items<'a>(&'a self) -> Enumerate<slice::Items<'a, Option<ast::DefId>>> {
67 self.items.iter().enumerate()
70 pub fn item_name(index: uint) -> &'static str {
71 let item: Option<LangItem> = FromPrimitive::from_uint(index);
73 $( Some($variant) => $name, )*
78 pub fn require(&self, it: LangItem) -> Result<ast::DefId, String> {
79 match self.items.get(it as uint) {
82 Err(format!("requires `{}` lang_item",
83 LanguageItems::item_name(it as uint)))
88 pub fn to_builtin_kind(&self, id: ast::DefId) -> Option<ty::BuiltinBound> {
89 if Some(id) == self.send_trait() {
91 } else if Some(id) == self.sized_trait() {
93 } else if Some(id) == self.copy_trait() {
95 } else if Some(id) == self.sync_trait() {
104 pub fn $method(&self) -> Option<ast::DefId> {
105 *self.items.get($variant as uint)
110 struct LanguageItemCollector<'a> {
111 items: LanguageItems,
113 session: &'a Session,
115 item_refs: HashMap<&'static str, uint>,
118 impl<'a, 'v> Visitor<'v> for LanguageItemCollector<'a> {
119 fn visit_item(&mut self, item: &ast::Item) {
120 match extract(item.attrs.as_slice()) {
122 let item_index = self.item_refs.find_equiv(&value).map(|x| *x);
125 Some(item_index) => {
126 self.collect_item(item_index, local_def(item.id), item.span)
134 visit::walk_item(self, item);
138 impl<'a> LanguageItemCollector<'a> {
139 pub fn new(session: &'a Session) -> LanguageItemCollector<'a> {
140 let mut item_refs = HashMap::new();
142 $( item_refs.insert($name, $variant as uint); )*
144 LanguageItemCollector {
146 items: LanguageItems::new(),
151 pub fn collect_item(&mut self, item_index: uint,
152 item_def_id: ast::DefId, span: Span) {
153 // Check for duplicates.
154 match self.items.items.get(item_index) {
155 &Some(original_def_id) if original_def_id != item_def_id => {
156 span_err!(self.session, span, E0152,
157 "duplicate entry for `{}`", LanguageItems::item_name(item_index));
159 &Some(_) | &None => {
165 *self.items.items.get_mut(item_index) = Some(item_def_id);
168 pub fn collect_local_language_items(&mut self, krate: &ast::Crate) {
169 visit::walk_crate(self, krate);
172 pub fn collect_external_language_items(&mut self) {
173 let crate_store = &self.session.cstore;
174 crate_store.iter_crate_data(|crate_number, _crate_metadata| {
175 each_lang_item(crate_store, crate_number, |node_id, item_index| {
176 let def_id = ast::DefId { krate: crate_number, node: node_id };
177 self.collect_item(item_index, def_id, DUMMY_SP);
183 pub fn collect(&mut self, krate: &ast::Crate) {
184 self.collect_local_language_items(krate);
185 self.collect_external_language_items();
189 pub fn extract(attrs: &[ast::Attribute]) -> Option<InternedString> {
190 for attribute in attrs.iter() {
191 match attribute.value_str() {
192 Some(ref value) if attribute.check_name("lang") => {
193 return Some(value.clone());
202 pub fn collect_language_items(krate: &ast::Crate,
203 session: &Session) -> LanguageItems {
204 let mut collector = LanguageItemCollector::new(session);
205 collector.collect(krate);
206 let LanguageItemCollector { mut items, .. } = collector;
207 weak_lang_items::check_crate(krate, session, &mut items);
208 session.abort_if_errors();
217 // Variant name, Name, Method name;
218 SendTraitLangItem, "send", send_trait;
219 SizedTraitLangItem, "sized", sized_trait;
220 CopyTraitLangItem, "copy", copy_trait;
221 SyncTraitLangItem, "sync", sync_trait;
223 DropTraitLangItem, "drop", drop_trait;
225 AddTraitLangItem, "add", add_trait;
226 SubTraitLangItem, "sub", sub_trait;
227 MulTraitLangItem, "mul", mul_trait;
228 DivTraitLangItem, "div", div_trait;
229 RemTraitLangItem, "rem", rem_trait;
230 NegTraitLangItem, "neg", neg_trait;
231 NotTraitLangItem, "not", not_trait;
232 BitXorTraitLangItem, "bitxor", bitxor_trait;
233 BitAndTraitLangItem, "bitand", bitand_trait;
234 BitOrTraitLangItem, "bitor", bitor_trait;
235 ShlTraitLangItem, "shl", shl_trait;
236 ShrTraitLangItem, "shr", shr_trait;
237 IndexTraitLangItem, "index", index_trait;
238 IndexMutTraitLangItem, "index_mut", index_mut_trait;
240 UnsafeTypeLangItem, "unsafe", unsafe_type;
242 DerefTraitLangItem, "deref", deref_trait;
243 DerefMutTraitLangItem, "deref_mut", deref_mut_trait;
245 FnTraitLangItem, "fn", fn_trait;
246 FnMutTraitLangItem, "fn_mut", fn_mut_trait;
247 FnOnceTraitLangItem, "fn_once", fn_once_trait;
249 EqTraitLangItem, "eq", eq_trait;
250 OrdTraitLangItem, "ord", ord_trait;
252 StrEqFnLangItem, "str_eq", str_eq_fn;
254 // A number of failure-related lang items. The `fail_` item corresponds to
255 // divide-by-zero and various failure cases with `match`. The
256 // `fail_bounds_check` item is for indexing arrays.
258 // The `begin_unwind` lang item has a predefined symbol name and is sort of
259 // a "weak lang item" in the sense that a crate is not required to have it
260 // defined to use it, but a final product is required to define it
261 // somewhere. Additionally, there are restrictions on crates that use a weak
262 // lang item, but do not have it defined.
263 FailFnLangItem, "fail_", fail_fn;
264 FailBoundsCheckFnLangItem, "fail_bounds_check", fail_bounds_check_fn;
265 BeginUnwindLangItem, "begin_unwind", begin_unwind;
267 ExchangeMallocFnLangItem, "exchange_malloc", exchange_malloc_fn;
268 ClosureExchangeMallocFnLangItem, "closure_exchange_malloc", closure_exchange_malloc_fn;
269 ExchangeFreeFnLangItem, "exchange_free", exchange_free_fn;
270 MallocFnLangItem, "malloc", malloc_fn;
271 FreeFnLangItem, "free", free_fn;
272 StrDupUniqFnLangItem, "strdup_uniq", strdup_uniq_fn;
274 StartFnLangItem, "start", start_fn;
276 TyDescStructLangItem, "ty_desc", ty_desc;
277 TyVisitorTraitLangItem, "ty_visitor", ty_visitor;
278 OpaqueStructLangItem, "opaque", opaque;
280 TypeIdLangItem, "type_id", type_id;
282 EhPersonalityLangItem, "eh_personality", eh_personality;
284 ManagedHeapLangItem, "managed_heap", managed_heap;
285 ExchangeHeapLangItem, "exchange_heap", exchange_heap;
286 GcLangItem, "gc", gc;
287 OwnedBoxLangItem, "owned_box", owned_box;
289 CovariantTypeItem, "covariant_type", covariant_type;
290 ContravariantTypeItem, "contravariant_type", contravariant_type;
291 InvariantTypeItem, "invariant_type", invariant_type;
293 CovariantLifetimeItem, "covariant_lifetime", covariant_lifetime;
294 ContravariantLifetimeItem, "contravariant_lifetime", contravariant_lifetime;
295 InvariantLifetimeItem, "invariant_lifetime", invariant_lifetime;
297 NoSendItem, "no_send_bound", no_send_bound;
298 NoCopyItem, "no_copy_bound", no_copy_bound;
299 NoSyncItem, "no_sync_bound", no_sync_bound;
300 ManagedItem, "managed_bound", managed_bound;
302 IteratorItem, "iterator", iterator;
304 StackExhaustedLangItem, "stack_exhausted", stack_exhausted;