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 require_owned_box(&self) -> Result<DefId, String> {
87 self.require(OwnedBoxLangItem)
90 pub fn fn_trait_kind(&self, id: DefId) -> Option<ty::ClosureKind> {
92 (self.fn_trait(), ty::ClosureKind::Fn),
93 (self.fn_mut_trait(), ty::ClosureKind::FnMut),
94 (self.fn_once_trait(), ty::ClosureKind::FnOnce),
97 for &(opt_def_id, kind) in &def_id_kinds {
98 if Some(id) == opt_def_id {
108 pub fn $method(&self) -> Option<DefId> {
109 self.items[$variant as usize]
114 struct LanguageItemCollector<'a, 'tcx: 'a> {
115 items: LanguageItems,
117 tcx: TyCtxt<'a, 'tcx, 'tcx>,
119 item_refs: FxHashMap<&'static str, usize>,
122 impl<'a, 'v, 'tcx> ItemLikeVisitor<'v> for LanguageItemCollector<'a, 'tcx> {
123 fn visit_item(&mut self, item: &hir::Item) {
124 if let Some(value) = extract(&item.attrs) {
125 let item_index = self.item_refs.get(&*value.as_str()).cloned();
127 if let Some(item_index) = item_index {
128 let def_id = self.tcx.hir.local_def_id(item.id);
129 self.collect_item(item_index, def_id);
131 let span = self.tcx.hir.span(item.id);
132 span_err!(self.tcx.sess, span, E0522,
133 "definition of an unknown language item: `{}`.",
139 fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem) {
140 // at present, lang items are always items, not trait items
143 fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem) {
144 // at present, lang items are always items, not impl items
148 impl<'a, 'tcx> LanguageItemCollector<'a, 'tcx> {
149 fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> LanguageItemCollector<'a, 'tcx> {
150 let mut item_refs = FxHashMap();
152 $( item_refs.insert($name, $variant as usize); )*
154 LanguageItemCollector {
156 items: LanguageItems::new(),
161 fn collect_item(&mut self, item_index: usize, item_def_id: DefId) {
162 // Check for duplicates.
163 match self.items.items[item_index] {
164 Some(original_def_id) if original_def_id != item_def_id => {
165 let name = LanguageItems::item_name(item_index);
166 let mut err = match self.tcx.hir.span_if_local(item_def_id) {
167 Some(span) => struct_span_err!(
171 "duplicate lang item found: `{}`.",
173 None => self.tcx.sess.struct_err(&format!(
174 "duplicate lang item in crate `{}`: `{}`.",
175 self.tcx.crate_name(item_def_id.krate),
178 if let Some(span) = self.tcx.hir.span_if_local(original_def_id) {
179 span_note!(&mut err, span,
180 "first defined here.");
182 err.note(&format!("first defined in crate `{}`.",
183 self.tcx.crate_name(original_def_id.krate)));
193 self.items.items[item_index] = Some(item_def_id);
197 pub fn extract(attrs: &[ast::Attribute]) -> Option<Symbol> {
198 for attribute in attrs {
199 if attribute.check_name("lang") {
200 if let Some(value) = attribute.value_str() {
209 pub fn collect<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> LanguageItems {
210 let mut collector = LanguageItemCollector::new(tcx);
211 for &cnum in tcx.crates().iter() {
212 for &(index, item_index) in tcx.defined_lang_items(cnum).iter() {
213 let def_id = DefId { krate: cnum, index: index };
214 collector.collect_item(item_index, def_id);
217 tcx.hir.krate().visit_all_item_likes(&mut collector);
218 let LanguageItemCollector { mut items, .. } = collector;
219 weak_lang_items::check_crate(tcx, &mut items);
227 language_item_table! {
228 // Variant name, Name, Method name;
229 CharImplItem, "char", char_impl;
230 StrImplItem, "str", str_impl;
231 SliceImplItem, "slice", slice_impl;
232 ConstPtrImplItem, "const_ptr", const_ptr_impl;
233 MutPtrImplItem, "mut_ptr", mut_ptr_impl;
234 I8ImplItem, "i8", i8_impl;
235 I16ImplItem, "i16", i16_impl;
236 I32ImplItem, "i32", i32_impl;
237 I64ImplItem, "i64", i64_impl;
238 I128ImplItem, "i128", i128_impl;
239 IsizeImplItem, "isize", isize_impl;
240 U8ImplItem, "u8", u8_impl;
241 U16ImplItem, "u16", u16_impl;
242 U32ImplItem, "u32", u32_impl;
243 U64ImplItem, "u64", u64_impl;
244 U128ImplItem, "u128", u128_impl;
245 UsizeImplItem, "usize", usize_impl;
246 F32ImplItem, "f32", f32_impl;
247 F64ImplItem, "f64", f64_impl;
249 SendTraitLangItem, "send", send_trait;
250 SizedTraitLangItem, "sized", sized_trait;
251 UnsizeTraitLangItem, "unsize", unsize_trait;
252 CopyTraitLangItem, "copy", copy_trait;
253 CloneTraitLangItem, "clone", clone_trait;
254 SyncTraitLangItem, "sync", sync_trait;
255 FreezeTraitLangItem, "freeze", freeze_trait;
257 DropTraitLangItem, "drop", drop_trait;
259 CoerceUnsizedTraitLangItem, "coerce_unsized", coerce_unsized_trait;
261 AddTraitLangItem, "add", add_trait;
262 SubTraitLangItem, "sub", sub_trait;
263 MulTraitLangItem, "mul", mul_trait;
264 DivTraitLangItem, "div", div_trait;
265 RemTraitLangItem, "rem", rem_trait;
266 NegTraitLangItem, "neg", neg_trait;
267 NotTraitLangItem, "not", not_trait;
268 BitXorTraitLangItem, "bitxor", bitxor_trait;
269 BitAndTraitLangItem, "bitand", bitand_trait;
270 BitOrTraitLangItem, "bitor", bitor_trait;
271 ShlTraitLangItem, "shl", shl_trait;
272 ShrTraitLangItem, "shr", shr_trait;
273 AddAssignTraitLangItem, "add_assign", add_assign_trait;
274 SubAssignTraitLangItem, "sub_assign", sub_assign_trait;
275 MulAssignTraitLangItem, "mul_assign", mul_assign_trait;
276 DivAssignTraitLangItem, "div_assign", div_assign_trait;
277 RemAssignTraitLangItem, "rem_assign", rem_assign_trait;
278 BitXorAssignTraitLangItem, "bitxor_assign", bitxor_assign_trait;
279 BitAndAssignTraitLangItem, "bitand_assign", bitand_assign_trait;
280 BitOrAssignTraitLangItem, "bitor_assign", bitor_assign_trait;
281 ShlAssignTraitLangItem, "shl_assign", shl_assign_trait;
282 ShrAssignTraitLangItem, "shr_assign", shr_assign_trait;
283 IndexTraitLangItem, "index", index_trait;
284 IndexMutTraitLangItem, "index_mut", index_mut_trait;
286 UnsafeCellTypeLangItem, "unsafe_cell", unsafe_cell_type;
288 DerefTraitLangItem, "deref", deref_trait;
289 DerefMutTraitLangItem, "deref_mut", deref_mut_trait;
291 FnTraitLangItem, "fn", fn_trait;
292 FnMutTraitLangItem, "fn_mut", fn_mut_trait;
293 FnOnceTraitLangItem, "fn_once", fn_once_trait;
295 GeneratorStateLangItem, "generator_state", gen_state;
296 GeneratorTraitLangItem, "generator", gen_trait;
298 EqTraitLangItem, "eq", eq_trait;
299 OrdTraitLangItem, "ord", ord_trait;
301 StrEqFnLangItem, "str_eq", str_eq_fn;
303 // A number of panic-related lang items. The `panic` item corresponds to
304 // divide-by-zero and various panic cases with `match`. The
305 // `panic_bounds_check` item is for indexing arrays.
307 // The `begin_unwind` lang item has a predefined symbol name and is sort of
308 // a "weak lang item" in the sense that a crate is not required to have it
309 // defined to use it, but a final product is required to define it
310 // somewhere. Additionally, there are restrictions on crates that use a weak
311 // lang item, but do not have it defined.
312 PanicFnLangItem, "panic", panic_fn;
313 PanicBoundsCheckFnLangItem, "panic_bounds_check", panic_bounds_check_fn;
314 PanicFmtLangItem, "panic_fmt", panic_fmt;
316 ExchangeMallocFnLangItem, "exchange_malloc", exchange_malloc_fn;
317 BoxFreeFnLangItem, "box_free", box_free_fn;
318 DropInPlaceFnLangItem, "drop_in_place", drop_in_place_fn;
320 StartFnLangItem, "start", start_fn;
322 EhPersonalityLangItem, "eh_personality", eh_personality;
323 EhUnwindResumeLangItem, "eh_unwind_resume", eh_unwind_resume;
324 MSVCTryFilterLangItem, "msvc_try_filter", msvc_try_filter;
326 OwnedBoxLangItem, "owned_box", owned_box;
328 PhantomDataItem, "phantom_data", phantom_data;
331 CovariantTypeItem, "covariant_type", covariant_type;
332 ContravariantTypeItem, "contravariant_type", contravariant_type;
333 InvariantTypeItem, "invariant_type", invariant_type;
334 CovariantLifetimeItem, "covariant_lifetime", covariant_lifetime;
335 ContravariantLifetimeItem, "contravariant_lifetime", contravariant_lifetime;
336 InvariantLifetimeItem, "invariant_lifetime", invariant_lifetime;
338 NonZeroItem, "non_zero", non_zero;
340 DebugTraitLangItem, "debug_trait", debug_trait;
343 impl<'a, 'tcx, 'gcx> ty::TyCtxt<'a, 'tcx, 'gcx> {
344 pub fn require_lang_item(&self, lang_item: LangItem) -> DefId {
345 self.lang_items().require(lang_item).unwrap_or_else(|msg| {
346 self.sess.fatal(&msg)