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 hir::def_id::DefId;
25 use ty::{self, TyCtxt};
26 use middle::weak_lang_items;
27 use util::nodemap::FxHashMap;
30 use syntax::symbol::Symbol;
31 use hir::itemlikevisit::ItemLikeVisitor;
34 // The actual lang items defined come at the end of this file in one handy table.
35 // So you probably just want to nip down to the end.
36 macro_rules! language_item_table {
38 $( $variant:ident, $name:expr, $method:ident; )*
43 #[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
49 pub struct LanguageItems {
50 pub items: Vec<Option<DefId>>,
51 pub missing: Vec<LangItem>,
55 pub fn new() -> LanguageItems {
56 fn foo(_: LangItem) -> Option<DefId> { None }
59 items: vec![$(foo($variant)),*],
64 pub fn items(&self) -> &[Option<DefId>] {
68 pub fn item_name(index: usize) -> &'static str {
69 let item: Option<LangItem> = LangItem::from_u32(index as u32);
71 $( Some($variant) => $name, )*
76 pub fn require(&self, it: LangItem) -> Result<DefId, String> {
77 match self.items[it as usize] {
80 Err(format!("requires `{}` lang_item",
81 LanguageItems::item_name(it as usize)))
86 pub fn fn_trait_kind(&self, id: DefId) -> Option<ty::ClosureKind> {
88 (self.fn_trait(), ty::ClosureKind::Fn),
89 (self.fn_mut_trait(), ty::ClosureKind::FnMut),
90 (self.fn_once_trait(), ty::ClosureKind::FnOnce),
93 for &(opt_def_id, kind) in &def_id_kinds {
94 if Some(id) == opt_def_id {
104 pub fn $method(&self) -> Option<DefId> {
105 self.items[$variant as usize]
110 struct LanguageItemCollector<'a, 'tcx: 'a> {
111 items: LanguageItems,
113 tcx: TyCtxt<'a, 'tcx, 'tcx>,
115 item_refs: FxHashMap<&'static str, usize>,
118 impl<'a, 'v, 'tcx> ItemLikeVisitor<'v> for LanguageItemCollector<'a, 'tcx> {
119 fn visit_item(&mut self, item: &hir::Item) {
120 if let Some(value) = extract(&item.attrs) {
121 let item_index = self.item_refs.get(&*value.as_str()).cloned();
123 if let Some(item_index) = item_index {
124 let def_id = self.tcx.hir.local_def_id(item.id);
125 self.collect_item(item_index, def_id);
127 let span = self.tcx.hir.span(item.id);
128 span_err!(self.tcx.sess, span, E0522,
129 "definition of an unknown language item: `{}`.",
135 fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem) {
136 // at present, lang items are always items, not trait items
139 fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem) {
140 // at present, lang items are always items, not impl items
144 impl<'a, 'tcx> LanguageItemCollector<'a, 'tcx> {
145 fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> LanguageItemCollector<'a, 'tcx> {
146 let mut item_refs = FxHashMap();
148 $( item_refs.insert($name, $variant as usize); )*
150 LanguageItemCollector {
152 items: LanguageItems::new(),
157 fn collect_item(&mut self, item_index: usize, item_def_id: DefId) {
158 // Check for duplicates.
159 match self.items.items[item_index] {
160 Some(original_def_id) if original_def_id != item_def_id => {
161 let name = LanguageItems::item_name(item_index);
162 let mut err = match self.tcx.hir.span_if_local(item_def_id) {
163 Some(span) => struct_span_err!(
167 "duplicate lang item found: `{}`.",
169 None => self.tcx.sess.struct_err(&format!(
170 "duplicate lang item in crate `{}`: `{}`.",
171 self.tcx.crate_name(item_def_id.krate),
174 if let Some(span) = self.tcx.hir.span_if_local(original_def_id) {
175 span_note!(&mut err, span,
176 "first defined here.");
178 err.note(&format!("first defined in crate `{}`.",
179 self.tcx.crate_name(original_def_id.krate)));
189 self.items.items[item_index] = Some(item_def_id);
193 pub fn extract(attrs: &[ast::Attribute]) -> Option<Symbol> {
194 for attribute in attrs {
195 if attribute.check_name("lang") {
196 if let Some(value) = attribute.value_str() {
205 pub fn collect<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> LanguageItems {
206 let mut collector = LanguageItemCollector::new(tcx);
207 for &cnum in tcx.crates().iter() {
208 for &(index, item_index) in tcx.defined_lang_items(cnum).iter() {
209 let def_id = DefId { krate: cnum, index: index };
210 collector.collect_item(item_index, def_id);
213 tcx.hir.krate().visit_all_item_likes(&mut collector);
214 let LanguageItemCollector { mut items, .. } = collector;
215 weak_lang_items::check_crate(tcx, &mut items);
223 language_item_table! {
224 // Variant name, Name, Method name;
225 CharImplItem, "char", char_impl;
226 StrImplItem, "str", str_impl;
227 SliceImplItem, "slice", slice_impl;
228 ConstPtrImplItem, "const_ptr", const_ptr_impl;
229 MutPtrImplItem, "mut_ptr", mut_ptr_impl;
230 I8ImplItem, "i8", i8_impl;
231 I16ImplItem, "i16", i16_impl;
232 I32ImplItem, "i32", i32_impl;
233 I64ImplItem, "i64", i64_impl;
234 I128ImplItem, "i128", i128_impl;
235 IsizeImplItem, "isize", isize_impl;
236 U8ImplItem, "u8", u8_impl;
237 U16ImplItem, "u16", u16_impl;
238 U32ImplItem, "u32", u32_impl;
239 U64ImplItem, "u64", u64_impl;
240 U128ImplItem, "u128", u128_impl;
241 UsizeImplItem, "usize", usize_impl;
242 F32ImplItem, "f32", f32_impl;
243 F64ImplItem, "f64", f64_impl;
245 SendTraitLangItem, "send", send_trait;
246 SizedTraitLangItem, "sized", sized_trait;
247 UnsizeTraitLangItem, "unsize", unsize_trait;
248 CopyTraitLangItem, "copy", copy_trait;
249 CloneTraitLangItem, "clone", clone_trait;
250 SyncTraitLangItem, "sync", sync_trait;
251 FreezeTraitLangItem, "freeze", freeze_trait;
253 DropTraitLangItem, "drop", drop_trait;
255 CoerceUnsizedTraitLangItem, "coerce_unsized", coerce_unsized_trait;
257 AddTraitLangItem, "add", add_trait;
258 SubTraitLangItem, "sub", sub_trait;
259 MulTraitLangItem, "mul", mul_trait;
260 DivTraitLangItem, "div", div_trait;
261 RemTraitLangItem, "rem", rem_trait;
262 NegTraitLangItem, "neg", neg_trait;
263 NotTraitLangItem, "not", not_trait;
264 BitXorTraitLangItem, "bitxor", bitxor_trait;
265 BitAndTraitLangItem, "bitand", bitand_trait;
266 BitOrTraitLangItem, "bitor", bitor_trait;
267 ShlTraitLangItem, "shl", shl_trait;
268 ShrTraitLangItem, "shr", shr_trait;
269 AddAssignTraitLangItem, "add_assign", add_assign_trait;
270 SubAssignTraitLangItem, "sub_assign", sub_assign_trait;
271 MulAssignTraitLangItem, "mul_assign", mul_assign_trait;
272 DivAssignTraitLangItem, "div_assign", div_assign_trait;
273 RemAssignTraitLangItem, "rem_assign", rem_assign_trait;
274 BitXorAssignTraitLangItem, "bitxor_assign", bitxor_assign_trait;
275 BitAndAssignTraitLangItem, "bitand_assign", bitand_assign_trait;
276 BitOrAssignTraitLangItem, "bitor_assign", bitor_assign_trait;
277 ShlAssignTraitLangItem, "shl_assign", shl_assign_trait;
278 ShrAssignTraitLangItem, "shr_assign", shr_assign_trait;
279 IndexTraitLangItem, "index", index_trait;
280 IndexMutTraitLangItem, "index_mut", index_mut_trait;
282 UnsafeCellTypeLangItem, "unsafe_cell", unsafe_cell_type;
284 DerefTraitLangItem, "deref", deref_trait;
285 DerefMutTraitLangItem, "deref_mut", deref_mut_trait;
287 FnTraitLangItem, "fn", fn_trait;
288 FnMutTraitLangItem, "fn_mut", fn_mut_trait;
289 FnOnceTraitLangItem, "fn_once", fn_once_trait;
291 GeneratorStateLangItem, "generator_state", gen_state;
292 GeneratorTraitLangItem, "generator", gen_trait;
294 EqTraitLangItem, "eq", eq_trait;
295 OrdTraitLangItem, "ord", ord_trait;
297 StrEqFnLangItem, "str_eq", str_eq_fn;
299 // A number of panic-related lang items. The `panic` item corresponds to
300 // divide-by-zero and various panic cases with `match`. The
301 // `panic_bounds_check` item is for indexing arrays.
303 // The `begin_unwind` lang item has a predefined symbol name and is sort of
304 // a "weak lang item" in the sense that a crate is not required to have it
305 // defined to use it, but a final product is required to define it
306 // somewhere. Additionally, there are restrictions on crates that use a weak
307 // lang item, but do not have it defined.
308 PanicFnLangItem, "panic", panic_fn;
309 PanicBoundsCheckFnLangItem, "panic_bounds_check", panic_bounds_check_fn;
310 PanicFmtLangItem, "panic_fmt", panic_fmt;
312 ExchangeMallocFnLangItem, "exchange_malloc", exchange_malloc_fn;
313 BoxFreeFnLangItem, "box_free", box_free_fn;
314 DropInPlaceFnLangItem, "drop_in_place", drop_in_place_fn;
316 StartFnLangItem, "start", start_fn;
318 EhPersonalityLangItem, "eh_personality", eh_personality;
319 EhUnwindResumeLangItem, "eh_unwind_resume", eh_unwind_resume;
320 MSVCTryFilterLangItem, "msvc_try_filter", msvc_try_filter;
322 OwnedBoxLangItem, "owned_box", owned_box;
324 PhantomDataItem, "phantom_data", phantom_data;
326 NonZeroItem, "non_zero", non_zero;
328 DebugTraitLangItem, "debug_trait", debug_trait;
331 impl<'a, 'tcx, 'gcx> ty::TyCtxt<'a, 'tcx, 'gcx> {
332 pub fn require_lang_item(&self, lang_item: LangItem) -> DefId {
333 self.lang_items().require(lang_item).unwrap_or_else(|msg| {
334 self.sess.fatal(&msg)