]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans_item.rs
ae6e095d1429131a7781a700c0393efb8ffd5f04
[rust.git] / src / librustc_trans / trans_item.rs
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.
4 //
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.
10
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.
16
17 use attributes;
18 use base;
19 use context::{SharedCrateContext, CrateContext};
20 use declare;
21 use glue::DropGlueKind;
22 use llvm;
23 use monomorphize::{self, Instance};
24 use inline;
25 use rustc::hir;
26 use rustc::hir::map as hir_map;
27 use rustc::hir::def_id::DefId;
28 use rustc::ty::{self, Ty, TyCtxt, TypeFoldable};
29 use rustc::ty::subst;
30 use std::hash::{Hash, Hasher};
31 use syntax::ast::{self, NodeId};
32 use syntax::{attr,errors};
33 use syntax::parse::token;
34 use type_of;
35
36
37 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
38 pub enum TransItem<'tcx> {
39     DropGlue(DropGlueKind<'tcx>),
40     Fn(Instance<'tcx>),
41     Static(NodeId)
42 }
43
44 impl<'tcx> Hash for TransItem<'tcx> {
45     fn hash<H: Hasher>(&self, s: &mut H) {
46         match *self {
47             TransItem::DropGlue(t) => {
48                 0u8.hash(s);
49                 t.hash(s);
50             },
51             TransItem::Fn(instance) => {
52                 1u8.hash(s);
53                 instance.def.hash(s);
54                 (instance.substs as *const _ as usize).hash(s);
55             }
56             TransItem::Static(node_id) => {
57                 2u8.hash(s);
58                 node_id.hash(s);
59             }
60         };
61     }
62 }
63
64
65 impl<'a, 'tcx> TransItem<'tcx> {
66
67     pub fn predefine(&self,
68                      ccx: &CrateContext<'a, 'tcx>,
69                      linkage: llvm::Linkage) {
70         match *self {
71             TransItem::Static(node_id) => {
72                 TransItem::predefine_static(ccx, node_id, linkage);
73             }
74             TransItem::Fn(instance) => {
75                 TransItem::predefine_fn(ccx, instance, linkage);
76             }
77             _ => {
78                 // Not yet implemented
79             }
80         }
81     }
82
83     fn predefine_static(ccx: &CrateContext<'a, 'tcx>,
84                         node_id: ast::NodeId,
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);
89
90         match ccx.tcx().map.get(node_id) {
91             hir::map::NodeItem(&hir::Item {
92                 span, node: hir::ItemStatic(..), ..
93             }) => {
94                 let instance = Instance::mono(ccx.shared(), def_id);
95                 let sym = instance.symbol_name(ccx.shared());
96                 debug!("making {}", sym);
97
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))
101                 });
102
103                 llvm::SetLinkage(g, linkage);
104             }
105
106             item => bug!("predefine_static: expected static, found {:?}", item)
107         }
108     }
109
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());
117
118         let instance = inline::maybe_inline_instance(ccx, instance);
119
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);
123
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),
128             || {
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?)",
132                     instance)
133             });
134
135         match map_node {
136             hir_map::NodeItem(&hir::Item {
137                 ref attrs, node: hir::ItemFn(..), ..
138             }) |
139             hir_map::NodeTraitItem(&hir::TraitItem {
140                 ref attrs, node: hir::MethodTraitItem(..), ..
141             }) |
142             hir_map::NodeImplItem(&hir::ImplItem {
143                 ref attrs, node: hir::ImplItemKind::Method(..), ..
144             }) => {
145                 let symbol = instance.symbol_name(ccx.shared());
146                 let lldecl = declare::declare_fn(ccx, &symbol, mono_ty);
147
148                 attributes::from_fn_attrs(ccx, attrs, lldecl);
149                 llvm::SetLinkage(lldecl, linkage);
150                 base::set_link_section(ccx, lldecl, attrs);
151
152                 ccx.instances().borrow_mut().insert(instance, lldecl);
153             }
154             _ => bug!("Invalid item for TransItem::Fn: `{:?}`", map_node)
155         };
156
157     }
158
159
160     pub fn requests_inline(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> bool {
161         match *self {
162             TransItem::Fn(ref instance) => {
163                 let attributes = tcx.get_attrs(instance.def);
164                 attr::requests_inline(&attributes[..])
165             }
166             TransItem::DropGlue(..) => true,
167             TransItem::Static(..)   => false,
168         }
169     }
170
171     pub fn is_from_extern_crate(&self) -> bool {
172         match *self {
173             TransItem::Fn(ref instance) => !instance.def.is_local(),
174             TransItem::DropGlue(..) |
175             TransItem::Static(..)   => false,
176         }
177     }
178
179     pub fn is_lazily_instantiated(&self) -> bool {
180         match *self {
181             TransItem::Fn(ref instance) => !instance.substs.types.is_empty(),
182             TransItem::DropGlue(..) => true,
183             TransItem::Static(..)   => false,
184         }
185     }
186
187     pub fn is_generic_fn(&self) -> bool {
188         match *self {
189             TransItem::Fn(ref instance) => !instance.substs.types.is_empty(),
190             TransItem::DropGlue(..) |
191             TransItem::Static(..)   => false,
192         }
193     }
194
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,
200         };
201
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) {
205                 Some(linkage)
206             } else {
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")
210                 } else {
211                     tcx.sess.fatal(&format!("invalid linkage specified: {}", name))
212                 }
213             }
214         } else {
215             None
216         }
217     }
218
219     pub fn to_string(&self, scx: &SharedCrateContext<'a, 'tcx>) -> String {
220         let tcx = scx.tcx();
221         let hir_map = &tcx.map;
222
223         return match *self {
224             TransItem::DropGlue(dg) => {
225                 let mut s = String::with_capacity(32);
226                 match dg {
227                     DropGlueKind::Ty(_) => s.push_str("drop-glue "),
228                     DropGlueKind::TyContents(_) => s.push_str("drop-glue-contents "),
229                 };
230                 push_unique_type_name(tcx, dg.ty(), &mut s);
231                 s
232             }
233             TransItem::Fn(instance) => {
234                 to_string_internal(tcx, "fn ", instance)
235             },
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)
240             },
241         };
242
243         fn to_string_internal<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
244                                         prefix: &str,
245                                         instance: Instance<'tcx>)
246                                         -> String {
247             let mut result = String::with_capacity(32);
248             result.push_str(prefix);
249             push_instance_as_string(tcx, instance, &mut result);
250             result
251         }
252     }
253
254     pub fn to_raw_string(&self) -> String {
255         match *self {
256             TransItem::DropGlue(dg) => {
257                 format!("DropGlue({})", dg.ty() as *const _ as usize)
258             }
259             TransItem::Fn(instance) => {
260                 format!("Fn({:?}, {})",
261                          instance.def,
262                          instance.substs as *const _ as usize)
263             }
264             TransItem::Static(id) => {
265                 format!("Static({:?})", id)
266             }
267         }
268     }
269 }
270
271
272 //=-----------------------------------------------------------------------------
273 // TransItem String Keys
274 //=-----------------------------------------------------------------------------
275
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.
279 //
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.
283
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>,
287                                        t: ty::Ty<'tcx>,
288                                        output: &mut String) {
289     match t.sty {
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);
309         },
310         ty::TyTuple(component_types) => {
311             output.push('(');
312             for &component_type in component_types {
313                 push_unique_type_name(tcx, component_type, output);
314                 output.push_str(", ");
315             }
316             if !component_types.is_empty() {
317                 output.pop();
318                 output.pop();
319             }
320             output.push(')');
321         },
322         ty::TyBox(inner_type) => {
323             output.push_str("Box<");
324             push_unique_type_name(tcx, inner_type, output);
325             output.push('>');
326         },
327         ty::TyRawPtr(ty::TypeAndMut { ty: inner_type, mutbl } ) => {
328             output.push('*');
329             match mutbl {
330                 hir::MutImmutable => output.push_str("const "),
331                 hir::MutMutable => output.push_str("mut "),
332             }
333
334             push_unique_type_name(tcx, inner_type, output);
335         },
336         ty::TyRef(_, ty::TypeAndMut { ty: inner_type, mutbl }) => {
337             output.push('&');
338             if mutbl == hir::MutMutable {
339                 output.push_str("mut ");
340             }
341
342             push_unique_type_name(tcx, inner_type, output);
343         },
344         ty::TyArray(inner_type, len) => {
345             output.push('[');
346             push_unique_type_name(tcx, inner_type, output);
347             output.push_str(&format!("; {}", len));
348             output.push(']');
349         },
350         ty::TySlice(inner_type) => {
351             output.push('[');
352             push_unique_type_name(tcx, inner_type, output);
353             output.push(']');
354         },
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,
360                              output);
361         },
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 ");
366             }
367
368             if abi != ::abi::Abi::Rust {
369                 output.push_str("extern \"");
370                 output.push_str(abi.name());
371                 output.push_str("\" ");
372             }
373
374             output.push_str("fn(");
375
376             let sig = tcx.erase_late_bound_regions(sig);
377             if !sig.inputs.is_empty() {
378                 for &parameter_type in &sig.inputs {
379                     push_unique_type_name(tcx, parameter_type, output);
380                     output.push_str(", ");
381                 }
382                 output.pop();
383                 output.pop();
384             }
385
386             if sig.variadic {
387                 if !sig.inputs.is_empty() {
388                     output.push_str(", ...");
389                 } else {
390                     output.push_str("...");
391                 }
392             }
393
394             output.push(')');
395
396             match sig.output {
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);
401                 }
402                 ty::FnDiverging => {
403                     output.push_str(" -> !");
404                 }
405             }
406         },
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);
413         }
414         ty::TyError |
415         ty::TyInfer(_) |
416         ty::TyProjection(..) |
417         ty::TyParam(_) => {
418             bug!("debuginfo: Trying to create type name for \
419                   unexpected type: {:?}", t);
420         }
421     }
422 }
423
424 fn push_item_name(tcx: TyCtxt,
425                   def_id: DefId,
426                   output: &mut String) {
427     let def_path = tcx.def_path(def_id);
428
429     // some_crate::
430     output.push_str(&tcx.crate_name(def_path.krate));
431     output.push_str("::");
432
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));
438     }
439
440     // remove final "::"
441     output.pop();
442     output.pop();
443 }
444
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() {
450         return;
451     }
452
453     output.push('<');
454
455     for &type_parameter in types {
456         push_unique_type_name(tcx, type_parameter, output);
457         output.push_str(", ");
458     }
459
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(", ");
467     }
468
469     output.pop();
470     output.pop();
471
472     output.push('>');
473 }
474
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);
480 }
481
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);
485     output
486 }
487
488 pub fn type_to_string<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
489                                 ty: ty::Ty<'tcx>)
490                                 -> String {
491     let mut output = String::new();
492     push_unique_type_name(tcx, ty, &mut output);
493     output
494 }