1 // Copyright 2016 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 //! Walks the crate looking for items/impl-items/trait-items that have
12 //! either a `rustc_symbol_name` or `rustc_item_path` attribute and
13 //! generates an error giving, respectively, the symbol name or
14 //! item-path. This is used for unit testing the code that generates
15 //! paths etc in all kinds of annoying scenarios.
19 use context::{SharedCrateContext, CrateContext};
21 use glue::DropGlueKind;
23 use monomorphize::{self, Instance};
26 use rustc::hir::map as hir_map;
27 use rustc::hir::def_id::DefId;
28 use rustc::ty::{self, Ty, TyCtxt, TypeFoldable};
30 use std::hash::{Hash, Hasher};
31 use syntax::ast::{self, NodeId};
32 use syntax::{attr,errors};
33 use syntax::parse::token;
37 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
38 pub enum TransItem<'tcx> {
39 DropGlue(DropGlueKind<'tcx>),
44 impl<'tcx> Hash for TransItem<'tcx> {
45 fn hash<H: Hasher>(&self, s: &mut H) {
47 TransItem::DropGlue(t) => {
51 TransItem::Fn(instance) => {
54 (instance.substs as *const _ as usize).hash(s);
56 TransItem::Static(node_id) => {
65 impl<'a, 'tcx> TransItem<'tcx> {
67 pub fn predefine(&self,
68 ccx: &CrateContext<'a, 'tcx>,
69 linkage: llvm::Linkage) {
71 TransItem::Static(node_id) => {
72 TransItem::predefine_static(ccx, node_id, linkage);
74 TransItem::Fn(instance) => {
75 TransItem::predefine_fn(ccx, instance, linkage);
78 // Not yet implemented
83 fn predefine_static(ccx: &CrateContext<'a, 'tcx>,
85 linkage: llvm::Linkage) {
86 let def_id = ccx.tcx().map.local_def_id(node_id);
87 let ty = ccx.tcx().lookup_item_type(def_id).ty;
88 let llty = type_of::type_of(ccx, ty);
90 match ccx.tcx().map.get(node_id) {
91 hir::map::NodeItem(&hir::Item {
92 span, node: hir::ItemStatic(..), ..
94 let instance = Instance::mono(ccx.shared(), def_id);
95 let sym = instance.symbol_name(ccx.shared());
96 debug!("making {}", sym);
98 let g = declare::define_global(ccx, &sym, llty).unwrap_or_else(|| {
99 ccx.sess().span_fatal(span,
100 &format!("symbol `{}` is already defined", sym))
103 llvm::SetLinkage(g, linkage);
106 item => bug!("predefine_static: expected static, found {:?}", item)
110 fn predefine_fn(ccx: &CrateContext<'a, 'tcx>,
111 instance: Instance<'tcx>,
112 linkage: llvm::Linkage) {
113 let unit = ccx.codegen_unit();
114 debug!("predefine_fn[cg={}](instance={:?})", &unit.name[..], instance);
115 assert!(!instance.substs.types.needs_infer() &&
116 !instance.substs.types.has_param_types());
118 let instance = inline::maybe_inline_instance(ccx, instance);
120 let item_ty = ccx.tcx().lookup_item_type(instance.def).ty;
121 let item_ty = ccx.tcx().erase_regions(&item_ty);
122 let mono_ty = monomorphize::apply_param_substs(ccx.tcx(), instance.substs, &item_ty);
124 let fn_node_id = ccx.tcx().map.as_local_node_id(instance.def).unwrap();
125 let map_node = errors::expect(
126 ccx.sess().diagnostic(),
127 ccx.tcx().map.find(fn_node_id),
129 format!("while instantiating `{}`, couldn't find it in \
130 the item map (may have attempted to monomorphize \
131 an item defined in a different crate?)",
136 hir_map::NodeItem(&hir::Item {
137 ref attrs, node: hir::ItemFn(..), ..
139 hir_map::NodeTraitItem(&hir::TraitItem {
140 ref attrs, node: hir::MethodTraitItem(..), ..
142 hir_map::NodeImplItem(&hir::ImplItem {
143 ref attrs, node: hir::ImplItemKind::Method(..), ..
145 let symbol = instance.symbol_name(ccx.shared());
146 let lldecl = declare::declare_fn(ccx, &symbol, mono_ty);
148 attributes::from_fn_attrs(ccx, attrs, lldecl);
149 llvm::SetLinkage(lldecl, linkage);
150 base::set_link_section(ccx, lldecl, attrs);
152 ccx.instances().borrow_mut().insert(instance, lldecl);
154 _ => bug!("Invalid item for TransItem::Fn: `{:?}`", map_node)
160 pub fn requests_inline(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> bool {
162 TransItem::Fn(ref instance) => {
163 let attributes = tcx.get_attrs(instance.def);
164 attr::requests_inline(&attributes[..])
166 TransItem::DropGlue(..) => true,
167 TransItem::Static(..) => false,
171 pub fn is_from_extern_crate(&self) -> bool {
173 TransItem::Fn(ref instance) => !instance.def.is_local(),
174 TransItem::DropGlue(..) |
175 TransItem::Static(..) => false,
179 pub fn is_lazily_instantiated(&self) -> bool {
181 TransItem::Fn(ref instance) => !instance.substs.types.is_empty(),
182 TransItem::DropGlue(..) => true,
183 TransItem::Static(..) => false,
187 pub fn is_generic_fn(&self) -> bool {
189 TransItem::Fn(ref instance) => !instance.substs.types.is_empty(),
190 TransItem::DropGlue(..) |
191 TransItem::Static(..) => false,
195 pub fn explicit_linkage(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Option<llvm::Linkage> {
196 let def_id = match *self {
197 TransItem::Fn(ref instance) => instance.def,
198 TransItem::Static(node_id) => tcx.map.local_def_id(node_id),
199 TransItem::DropGlue(..) => return None,
202 let attributes = tcx.get_attrs(def_id);
203 if let Some(name) = attr::first_attr_value_str_by_name(&attributes, "linkage") {
204 if let Some(linkage) = base::llvm_linkage_by_name(&name) {
207 let span = tcx.map.span_if_local(def_id);
208 if let Some(span) = span {
209 tcx.sess.span_fatal(span, "invalid linkage specified")
211 tcx.sess.fatal(&format!("invalid linkage specified: {}", name))
219 pub fn to_string(&self, scx: &SharedCrateContext<'a, 'tcx>) -> String {
221 let hir_map = &tcx.map;
224 TransItem::DropGlue(dg) => {
225 let mut s = String::with_capacity(32);
227 DropGlueKind::Ty(_) => s.push_str("drop-glue "),
228 DropGlueKind::TyContents(_) => s.push_str("drop-glue-contents "),
230 push_unique_type_name(tcx, dg.ty(), &mut s);
233 TransItem::Fn(instance) => {
234 to_string_internal(tcx, "fn ", instance)
236 TransItem::Static(node_id) => {
237 let def_id = hir_map.local_def_id(node_id);
238 let instance = Instance::mono(scx, def_id);
239 to_string_internal(tcx, "static ", instance)
243 fn to_string_internal<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
245 instance: Instance<'tcx>)
247 let mut result = String::with_capacity(32);
248 result.push_str(prefix);
249 push_instance_as_string(tcx, instance, &mut result);
254 pub fn to_raw_string(&self) -> String {
256 TransItem::DropGlue(dg) => {
257 format!("DropGlue({})", dg.ty() as *const _ as usize)
259 TransItem::Fn(instance) => {
260 format!("Fn({:?}, {})",
262 instance.substs as *const _ as usize)
264 TransItem::Static(id) => {
265 format!("Static({:?})", id)
272 //=-----------------------------------------------------------------------------
273 // TransItem String Keys
274 //=-----------------------------------------------------------------------------
276 // The code below allows for producing a unique string key for a trans item.
277 // These keys are used by the handwritten auto-tests, so they need to be
278 // predictable and human-readable.
280 // Note: A lot of this could looks very similar to what's already in the
281 // ppaux module. It would be good to refactor things so we only have one
282 // parameterizable implementation for printing types.
284 /// Same as `unique_type_name()` but with the result pushed onto the given
285 /// `output` parameter.
286 pub fn push_unique_type_name<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
288 output: &mut String) {
290 ty::TyBool => output.push_str("bool"),
291 ty::TyChar => output.push_str("char"),
292 ty::TyStr => output.push_str("str"),
293 ty::TyInt(ast::IntTy::Is) => output.push_str("isize"),
294 ty::TyInt(ast::IntTy::I8) => output.push_str("i8"),
295 ty::TyInt(ast::IntTy::I16) => output.push_str("i16"),
296 ty::TyInt(ast::IntTy::I32) => output.push_str("i32"),
297 ty::TyInt(ast::IntTy::I64) => output.push_str("i64"),
298 ty::TyUint(ast::UintTy::Us) => output.push_str("usize"),
299 ty::TyUint(ast::UintTy::U8) => output.push_str("u8"),
300 ty::TyUint(ast::UintTy::U16) => output.push_str("u16"),
301 ty::TyUint(ast::UintTy::U32) => output.push_str("u32"),
302 ty::TyUint(ast::UintTy::U64) => output.push_str("u64"),
303 ty::TyFloat(ast::FloatTy::F32) => output.push_str("f32"),
304 ty::TyFloat(ast::FloatTy::F64) => output.push_str("f64"),
305 ty::TyStruct(adt_def, substs) |
306 ty::TyEnum(adt_def, substs) => {
307 push_item_name(tcx, adt_def.did, output);
308 push_type_params(tcx, &substs.types, &[], output);
310 ty::TyTuple(component_types) => {
312 for &component_type in component_types {
313 push_unique_type_name(tcx, component_type, output);
314 output.push_str(", ");
316 if !component_types.is_empty() {
322 ty::TyBox(inner_type) => {
323 output.push_str("Box<");
324 push_unique_type_name(tcx, inner_type, output);
327 ty::TyRawPtr(ty::TypeAndMut { ty: inner_type, mutbl } ) => {
330 hir::MutImmutable => output.push_str("const "),
331 hir::MutMutable => output.push_str("mut "),
334 push_unique_type_name(tcx, inner_type, output);
336 ty::TyRef(_, ty::TypeAndMut { ty: inner_type, mutbl }) => {
338 if mutbl == hir::MutMutable {
339 output.push_str("mut ");
342 push_unique_type_name(tcx, inner_type, output);
344 ty::TyArray(inner_type, len) => {
346 push_unique_type_name(tcx, inner_type, output);
347 output.push_str(&format!("; {}", len));
350 ty::TySlice(inner_type) => {
352 push_unique_type_name(tcx, inner_type, output);
355 ty::TyTrait(ref trait_data) => {
356 push_item_name(tcx, trait_data.principal.skip_binder().def_id, output);
357 push_type_params(tcx,
358 &trait_data.principal.skip_binder().substs.types,
359 &trait_data.bounds.projection_bounds,
362 ty::TyFnDef(_, _, &ty::BareFnTy{ unsafety, abi, ref sig } ) |
363 ty::TyFnPtr(&ty::BareFnTy{ unsafety, abi, ref sig } ) => {
364 if unsafety == hir::Unsafety::Unsafe {
365 output.push_str("unsafe ");
368 if abi != ::abi::Abi::Rust {
369 output.push_str("extern \"");
370 output.push_str(abi.name());
371 output.push_str("\" ");
374 output.push_str("fn(");
376 let sig = tcx.erase_late_bound_regions(sig);
377 if !sig.inputs.is_empty() {
378 for ¶meter_type in &sig.inputs {
379 push_unique_type_name(tcx, parameter_type, output);
380 output.push_str(", ");
387 if !sig.inputs.is_empty() {
388 output.push_str(", ...");
390 output.push_str("...");
397 ty::FnConverging(result_type) if result_type.is_nil() => {}
398 ty::FnConverging(result_type) => {
399 output.push_str(" -> ");
400 push_unique_type_name(tcx, result_type, output);
403 output.push_str(" -> !");
407 ty::TyClosure(def_id, ref closure_substs) => {
408 push_item_name(tcx, def_id, output);
409 output.push_str("{");
410 output.push_str(&format!("{}:{}", def_id.krate, def_id.index.as_usize()));
411 output.push_str("}");
412 push_type_params(tcx, &closure_substs.func_substs.types, &[], output);
416 ty::TyProjection(..) |
418 bug!("debuginfo: Trying to create type name for \
419 unexpected type: {:?}", t);
424 fn push_item_name(tcx: TyCtxt,
426 output: &mut String) {
427 let def_path = tcx.def_path(def_id);
430 output.push_str(&tcx.crate_name(def_path.krate));
431 output.push_str("::");
433 // foo::bar::ItemName::
434 for part in tcx.def_path(def_id).data {
435 output.push_str(&format!("{}[{}]::",
436 part.data.as_interned_str(),
437 part.disambiguator));
445 fn push_type_params<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
446 types: &'tcx subst::VecPerParamSpace<Ty<'tcx>>,
447 projections: &[ty::PolyProjectionPredicate<'tcx>],
448 output: &mut String) {
449 if types.is_empty() && projections.is_empty() {
455 for &type_parameter in types {
456 push_unique_type_name(tcx, type_parameter, output);
457 output.push_str(", ");
460 for projection in projections {
461 let projection = projection.skip_binder();
462 let name = token::get_ident_interner().get(projection.projection_ty.item_name);
463 output.push_str(&name[..]);
464 output.push_str("=");
465 push_unique_type_name(tcx, projection.ty, output);
466 output.push_str(", ");
475 fn push_instance_as_string<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
476 instance: Instance<'tcx>,
477 output: &mut String) {
478 push_item_name(tcx, instance.def, output);
479 push_type_params(tcx, &instance.substs.types, &[], output);
482 pub fn def_id_to_string(tcx: TyCtxt, def_id: DefId) -> String {
483 let mut output = String::new();
484 push_item_name(tcx, def_id, &mut output);
488 pub fn type_to_string<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
491 let mut output = String::new();
492 push_unique_type_name(tcx, ty, &mut output);