]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans_item.rs
Fix checking for missing stability annotations
[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 asm;
18 use attributes;
19 use base;
20 use consts;
21 use context::CrateContext;
22 use common;
23 use declare;
24 use llvm;
25 use monomorphize::Instance;
26 use rustc::hir;
27 use rustc::hir::def_id::DefId;
28 use rustc::traits;
29 use rustc::ty::{self, Ty, TyCtxt, TypeFoldable};
30 use rustc::ty::subst::{Subst, Substs};
31 use syntax::ast::{self, NodeId};
32 use syntax::attr;
33 use syntax_pos::Span;
34 use syntax_pos::symbol::Symbol;
35 use type_of;
36 use std::fmt::Write;
37 use std::iter;
38
39 #[derive(PartialEq, Eq, Clone, Copy, Debug, Hash)]
40 pub enum TransItem<'tcx> {
41     Fn(Instance<'tcx>),
42     Static(NodeId),
43     GlobalAsm(NodeId),
44 }
45
46 /// Describes how a translation item will be instantiated in object files.
47 #[derive(PartialEq, Eq, Clone, Copy, Debug, Hash)]
48 pub enum InstantiationMode {
49     /// There will be exactly one instance of the given TransItem. It will have
50     /// external linkage so that it can be linked to from other codegen units.
51     GloballyShared,
52
53     /// Each codegen unit containing a reference to the given TransItem will
54     /// have its own private copy of the function (with internal linkage).
55     LocalCopy,
56 }
57
58 impl<'a, 'tcx> TransItem<'tcx> {
59
60     pub fn define(&self, ccx: &CrateContext<'a, 'tcx>) {
61         debug!("BEGIN IMPLEMENTING '{} ({})' in cgu {}",
62                   self.to_string(ccx.tcx()),
63                   self.to_raw_string(),
64                   ccx.codegen_unit().name());
65
66         match *self {
67             TransItem::Static(node_id) => {
68                 let tcx = ccx.tcx();
69                 let item = tcx.hir.expect_item(node_id);
70                 if let hir::ItemStatic(_, m, _) = item.node {
71                     match consts::trans_static(&ccx, m, item.id, &item.attrs) {
72                         Ok(_) => { /* Cool, everything's alright. */ },
73                         Err(err) => {
74                             err.report(tcx, item.span, "static");
75                         }
76                     };
77                 } else {
78                     span_bug!(item.span, "Mismatch between hir::Item type and TransItem type")
79                 }
80             }
81             TransItem::GlobalAsm(node_id) => {
82                 let item = ccx.tcx().hir.expect_item(node_id);
83                 if let hir::ItemGlobalAsm(ref ga) = item.node {
84                     asm::trans_global_asm(ccx, ga);
85                 } else {
86                     span_bug!(item.span, "Mismatch between hir::Item type and TransItem type")
87                 }
88             }
89             TransItem::Fn(instance) => {
90                 base::trans_instance(&ccx, instance);
91             }
92         }
93
94         debug!("END IMPLEMENTING '{} ({})' in cgu {}",
95                self.to_string(ccx.tcx()),
96                self.to_raw_string(),
97                ccx.codegen_unit().name());
98     }
99
100     pub fn predefine(&self,
101                      ccx: &CrateContext<'a, 'tcx>,
102                      linkage: llvm::Linkage) {
103         debug!("BEGIN PREDEFINING '{} ({})' in cgu {}",
104                self.to_string(ccx.tcx()),
105                self.to_raw_string(),
106                ccx.codegen_unit().name());
107
108         let symbol_name = self.symbol_name(ccx.tcx());
109
110         debug!("symbol {}", &symbol_name);
111
112         match *self {
113             TransItem::Static(node_id) => {
114                 TransItem::predefine_static(ccx, node_id, linkage, &symbol_name);
115             }
116             TransItem::Fn(instance) => {
117                 TransItem::predefine_fn(ccx, instance, linkage, &symbol_name);
118             }
119             TransItem::GlobalAsm(..) => {}
120         }
121
122         debug!("END PREDEFINING '{} ({})' in cgu {}",
123                self.to_string(ccx.tcx()),
124                self.to_raw_string(),
125                ccx.codegen_unit().name());
126     }
127
128     fn predefine_static(ccx: &CrateContext<'a, 'tcx>,
129                         node_id: ast::NodeId,
130                         linkage: llvm::Linkage,
131                         symbol_name: &str) {
132         let def_id = ccx.tcx().hir.local_def_id(node_id);
133         let instance = Instance::mono(ccx.tcx(), def_id);
134         let ty = common::instance_ty(ccx.shared(), &instance);
135         let llty = type_of::type_of(ccx, ty);
136
137         let g = declare::define_global(ccx, symbol_name, llty).unwrap_or_else(|| {
138             ccx.sess().span_fatal(ccx.tcx().hir.span(node_id),
139                 &format!("symbol `{}` is already defined", symbol_name))
140         });
141
142         unsafe { llvm::LLVMRustSetLinkage(g, linkage) };
143
144         ccx.instances().borrow_mut().insert(instance, g);
145         ccx.statics().borrow_mut().insert(g, def_id);
146     }
147
148     fn predefine_fn(ccx: &CrateContext<'a, 'tcx>,
149                     instance: Instance<'tcx>,
150                     linkage: llvm::Linkage,
151                     symbol_name: &str) {
152         assert!(!instance.substs.needs_infer() &&
153                 !instance.substs.has_param_types());
154
155         let mono_ty = common::instance_ty(ccx.shared(), &instance);
156         let attrs = instance.def.attrs(ccx.tcx());
157         let lldecl = declare::declare_fn(ccx, symbol_name, mono_ty);
158         unsafe { llvm::LLVMRustSetLinkage(lldecl, linkage) };
159         base::set_link_section(ccx, lldecl, &attrs);
160         if linkage == llvm::Linkage::LinkOnceODRLinkage ||
161             linkage == llvm::Linkage::WeakODRLinkage {
162             llvm::SetUniqueComdat(ccx.llmod(), lldecl);
163         }
164
165         // If we're compiling the compiler-builtins crate, e.g. the equivalent of
166         // compiler-rt, then we want to implicitly compile everything with hidden
167         // visibility as we're going to link this object all over the place but
168         // don't want the symbols to get exported.
169         if linkage != llvm::Linkage::InternalLinkage &&
170            linkage != llvm::Linkage::PrivateLinkage &&
171            attr::contains_name(ccx.tcx().hir.krate_attrs(), "compiler_builtins") {
172             unsafe {
173                 llvm::LLVMRustSetVisibility(lldecl, llvm::Visibility::Hidden);
174             }
175         }
176
177         debug!("predefine_fn: mono_ty = {:?} instance = {:?}", mono_ty, instance);
178         if common::is_inline_instance(ccx.tcx(), &instance) {
179             attributes::inline(lldecl, attributes::InlineAttr::Hint);
180         }
181         attributes::from_fn_attrs(ccx, &attrs, lldecl);
182
183         ccx.instances().borrow_mut().insert(instance, lldecl);
184     }
185
186     pub fn symbol_name(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> ty::SymbolName {
187         match *self {
188             TransItem::Fn(instance) => tcx.symbol_name(instance),
189             TransItem::Static(node_id) => {
190                 let def_id = tcx.hir.local_def_id(node_id);
191                 tcx.symbol_name(Instance::mono(tcx, def_id))
192             }
193             TransItem::GlobalAsm(node_id) => {
194                 let def_id = tcx.hir.local_def_id(node_id);
195                 ty::SymbolName {
196                     name: Symbol::intern(&format!("global_asm_{:?}", def_id)).as_str()
197                 }
198             }
199         }
200     }
201
202     pub fn local_span(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Option<Span> {
203         match *self {
204             TransItem::Fn(Instance { def, .. }) => {
205                 tcx.hir.as_local_node_id(def.def_id())
206             }
207             TransItem::Static(node_id) |
208             TransItem::GlobalAsm(node_id) => {
209                 Some(node_id)
210             }
211         }.map(|node_id| tcx.hir.span(node_id))
212     }
213
214     pub fn instantiation_mode(&self,
215                               tcx: TyCtxt<'a, 'tcx, 'tcx>)
216                               -> InstantiationMode {
217         match *self {
218             TransItem::Fn(ref instance) => {
219                 if self.explicit_linkage(tcx).is_none() &&
220                     common::requests_inline(tcx, instance)
221                 {
222                     InstantiationMode::LocalCopy
223                 } else {
224                     InstantiationMode::GloballyShared
225                 }
226             }
227             TransItem::Static(..) => InstantiationMode::GloballyShared,
228             TransItem::GlobalAsm(..) => InstantiationMode::GloballyShared,
229         }
230     }
231
232     pub fn is_generic_fn(&self) -> bool {
233         match *self {
234             TransItem::Fn(ref instance) => {
235                 instance.substs.types().next().is_some()
236             }
237             TransItem::Static(..) |
238             TransItem::GlobalAsm(..) => false,
239         }
240     }
241
242     pub fn explicit_linkage(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Option<llvm::Linkage> {
243         let def_id = match *self {
244             TransItem::Fn(ref instance) => instance.def_id(),
245             TransItem::Static(node_id) => tcx.hir.local_def_id(node_id),
246             TransItem::GlobalAsm(..) => return None,
247         };
248
249         let attributes = tcx.get_attrs(def_id);
250         if let Some(name) = attr::first_attr_value_str_by_name(&attributes, "linkage") {
251             if let Some(linkage) = base::llvm_linkage_by_name(&name.as_str()) {
252                 Some(linkage)
253             } else {
254                 let span = tcx.hir.span_if_local(def_id);
255                 if let Some(span) = span {
256                     tcx.sess.span_fatal(span, "invalid linkage specified")
257                 } else {
258                     tcx.sess.fatal(&format!("invalid linkage specified: {}", name))
259                 }
260             }
261         } else {
262             None
263         }
264     }
265
266     /// Returns whether this instance is instantiable - whether it has no unsatisfied
267     /// predicates.
268     ///
269     /// In order to translate an item, all of its predicates must hold, because
270     /// otherwise the item does not make sense. Type-checking ensures that
271     /// the predicates of every item that is *used by* a valid item *do*
272     /// hold, so we can rely on that.
273     ///
274     /// However, we translate collector roots (reachable items) and functions
275     /// in vtables when they are seen, even if they are not used, and so they
276     /// might not be instantiable. For example, a programmer can define this
277     /// public function:
278     ///
279     ///     pub fn foo<'a>(s: &'a mut ()) where &'a mut (): Clone {
280     ///         <&mut () as Clone>::clone(&s);
281     ///     }
282     ///
283     /// That function can't be translated, because the method `<&mut () as Clone>::clone`
284     /// does not exist. Luckily for us, that function can't ever be used,
285     /// because that would require for `&'a mut (): Clone` to hold, so we
286     /// can just not emit any code, or even a linker reference for it.
287     ///
288     /// Similarly, if a vtable method has such a signature, and therefore can't
289     /// be used, we can just not emit it and have a placeholder (a null pointer,
290     /// which will never be accessed) in its place.
291     pub fn is_instantiable(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> bool {
292         debug!("is_instantiable({:?})", self);
293         let (def_id, substs) = match *self {
294             TransItem::Fn(ref instance) => (instance.def_id(), instance.substs),
295             TransItem::Static(node_id) => (tcx.hir.local_def_id(node_id), Substs::empty()),
296             // global asm never has predicates
297             TransItem::GlobalAsm(..) => return true
298         };
299
300         let predicates = tcx.predicates_of(def_id).predicates.subst(tcx, substs);
301         traits::normalize_and_test_predicates(tcx, predicates)
302     }
303
304     pub fn to_string(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> String {
305         let hir_map = &tcx.hir;
306
307         return match *self {
308             TransItem::Fn(instance) => {
309                 to_string_internal(tcx, "fn ", instance)
310             },
311             TransItem::Static(node_id) => {
312                 let def_id = hir_map.local_def_id(node_id);
313                 let instance = Instance::new(def_id, tcx.intern_substs(&[]));
314                 to_string_internal(tcx, "static ", instance)
315             },
316             TransItem::GlobalAsm(..) => {
317                 "global_asm".to_string()
318             }
319         };
320
321         fn to_string_internal<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
322                                         prefix: &str,
323                                         instance: Instance<'tcx>)
324                                         -> String {
325             let mut result = String::with_capacity(32);
326             result.push_str(prefix);
327             let printer = DefPathBasedNames::new(tcx, false, false);
328             printer.push_instance_as_string(instance, &mut result);
329             result
330         }
331     }
332
333     pub fn to_raw_string(&self) -> String {
334         match *self {
335             TransItem::Fn(instance) => {
336                 format!("Fn({:?}, {})",
337                          instance.def,
338                          instance.substs.as_ptr() as usize)
339             }
340             TransItem::Static(id) => {
341                 format!("Static({:?})", id)
342             }
343             TransItem::GlobalAsm(id) => {
344                 format!("GlobalAsm({:?})", id)
345             }
346         }
347     }
348 }
349
350
351 //=-----------------------------------------------------------------------------
352 // TransItem String Keys
353 //=-----------------------------------------------------------------------------
354
355 // The code below allows for producing a unique string key for a trans item.
356 // These keys are used by the handwritten auto-tests, so they need to be
357 // predictable and human-readable.
358 //
359 // Note: A lot of this could looks very similar to what's already in the
360 //       ppaux module. It would be good to refactor things so we only have one
361 //       parameterizable implementation for printing types.
362
363 /// Same as `unique_type_name()` but with the result pushed onto the given
364 /// `output` parameter.
365 pub struct DefPathBasedNames<'a, 'tcx: 'a> {
366     tcx: TyCtxt<'a, 'tcx, 'tcx>,
367     omit_disambiguators: bool,
368     omit_local_crate_name: bool,
369 }
370
371 impl<'a, 'tcx> DefPathBasedNames<'a, 'tcx> {
372     pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>,
373                omit_disambiguators: bool,
374                omit_local_crate_name: bool)
375                -> Self {
376         DefPathBasedNames {
377             tcx: tcx,
378             omit_disambiguators: omit_disambiguators,
379             omit_local_crate_name: omit_local_crate_name,
380         }
381     }
382
383     pub fn push_type_name(&self, t: Ty<'tcx>, output: &mut String) {
384         match t.sty {
385             ty::TyBool              => output.push_str("bool"),
386             ty::TyChar              => output.push_str("char"),
387             ty::TyStr               => output.push_str("str"),
388             ty::TyNever             => output.push_str("!"),
389             ty::TyInt(ast::IntTy::Is)    => output.push_str("isize"),
390             ty::TyInt(ast::IntTy::I8)    => output.push_str("i8"),
391             ty::TyInt(ast::IntTy::I16)   => output.push_str("i16"),
392             ty::TyInt(ast::IntTy::I32)   => output.push_str("i32"),
393             ty::TyInt(ast::IntTy::I64)   => output.push_str("i64"),
394             ty::TyInt(ast::IntTy::I128)   => output.push_str("i128"),
395             ty::TyUint(ast::UintTy::Us)   => output.push_str("usize"),
396             ty::TyUint(ast::UintTy::U8)   => output.push_str("u8"),
397             ty::TyUint(ast::UintTy::U16)  => output.push_str("u16"),
398             ty::TyUint(ast::UintTy::U32)  => output.push_str("u32"),
399             ty::TyUint(ast::UintTy::U64)  => output.push_str("u64"),
400             ty::TyUint(ast::UintTy::U128)  => output.push_str("u128"),
401             ty::TyFloat(ast::FloatTy::F32) => output.push_str("f32"),
402             ty::TyFloat(ast::FloatTy::F64) => output.push_str("f64"),
403             ty::TyAdt(adt_def, substs) => {
404                 self.push_def_path(adt_def.did, output);
405                 self.push_type_params(substs, iter::empty(), output);
406             },
407             ty::TyTuple(component_types, _) => {
408                 output.push('(');
409                 for &component_type in component_types {
410                     self.push_type_name(component_type, output);
411                     output.push_str(", ");
412                 }
413                 if !component_types.is_empty() {
414                     output.pop();
415                     output.pop();
416                 }
417                 output.push(')');
418             },
419             ty::TyRawPtr(ty::TypeAndMut { ty: inner_type, mutbl } ) => {
420                 output.push('*');
421                 match mutbl {
422                     hir::MutImmutable => output.push_str("const "),
423                     hir::MutMutable => output.push_str("mut "),
424                 }
425
426                 self.push_type_name(inner_type, output);
427             },
428             ty::TyRef(_, ty::TypeAndMut { ty: inner_type, mutbl }) => {
429                 output.push('&');
430                 if mutbl == hir::MutMutable {
431                     output.push_str("mut ");
432                 }
433
434                 self.push_type_name(inner_type, output);
435             },
436             ty::TyArray(inner_type, len) => {
437                 output.push('[');
438                 self.push_type_name(inner_type, output);
439                 write!(output, "; {}", len).unwrap();
440                 output.push(']');
441             },
442             ty::TySlice(inner_type) => {
443                 output.push('[');
444                 self.push_type_name(inner_type, output);
445                 output.push(']');
446             },
447             ty::TyDynamic(ref trait_data, ..) => {
448                 if let Some(principal) = trait_data.principal() {
449                     self.push_def_path(principal.def_id(), output);
450                     self.push_type_params(principal.skip_binder().substs,
451                         trait_data.projection_bounds(),
452                         output);
453                 }
454             },
455             ty::TyFnDef(..) |
456             ty::TyFnPtr(_) => {
457                 let sig = t.fn_sig(self.tcx);
458                 if sig.unsafety() == hir::Unsafety::Unsafe {
459                     output.push_str("unsafe ");
460                 }
461
462                 let abi = sig.abi();
463                 if abi != ::abi::Abi::Rust {
464                     output.push_str("extern \"");
465                     output.push_str(abi.name());
466                     output.push_str("\" ");
467                 }
468
469                 output.push_str("fn(");
470
471                 let sig = self.tcx.erase_late_bound_regions_and_normalize(&sig);
472
473                 if !sig.inputs().is_empty() {
474                     for &parameter_type in sig.inputs() {
475                         self.push_type_name(parameter_type, output);
476                         output.push_str(", ");
477                     }
478                     output.pop();
479                     output.pop();
480                 }
481
482                 if sig.variadic {
483                     if !sig.inputs().is_empty() {
484                         output.push_str(", ...");
485                     } else {
486                         output.push_str("...");
487                     }
488                 }
489
490                 output.push(')');
491
492                 if !sig.output().is_nil() {
493                     output.push_str(" -> ");
494                     self.push_type_name(sig.output(), output);
495                 }
496             },
497             ty::TyClosure(def_id, ref closure_substs) => {
498                 self.push_def_path(def_id, output);
499                 let generics = self.tcx.generics_of(self.tcx.closure_base_def_id(def_id));
500                 let substs = closure_substs.substs.truncate_to(self.tcx, generics);
501                 self.push_type_params(substs, iter::empty(), output);
502             }
503             ty::TyError |
504             ty::TyInfer(_) |
505             ty::TyProjection(..) |
506             ty::TyParam(_) |
507             ty::TyAnon(..) => {
508                 bug!("DefPathBasedNames: Trying to create type name for \
509                                          unexpected type: {:?}", t);
510             }
511         }
512     }
513
514     pub fn push_def_path(&self,
515                          def_id: DefId,
516                          output: &mut String) {
517         let def_path = self.tcx.def_path(def_id);
518
519         // some_crate::
520         if !(self.omit_local_crate_name && def_id.is_local()) {
521             output.push_str(&self.tcx.crate_name(def_path.krate).as_str());
522             output.push_str("::");
523         }
524
525         // foo::bar::ItemName::
526         for part in self.tcx.def_path(def_id).data {
527             if self.omit_disambiguators {
528                 write!(output, "{}::", part.data.as_interned_str()).unwrap();
529             } else {
530                 write!(output, "{}[{}]::",
531                        part.data.as_interned_str(),
532                        part.disambiguator).unwrap();
533             }
534         }
535
536         // remove final "::"
537         output.pop();
538         output.pop();
539     }
540
541     fn push_type_params<I>(&self,
542                             substs: &Substs<'tcx>,
543                             projections: I,
544                             output: &mut String)
545         where I: Iterator<Item=ty::PolyExistentialProjection<'tcx>>
546     {
547         let mut projections = projections.peekable();
548         if substs.types().next().is_none() && projections.peek().is_none() {
549             return;
550         }
551
552         output.push('<');
553
554         for type_parameter in substs.types() {
555             self.push_type_name(type_parameter, output);
556             output.push_str(", ");
557         }
558
559         for projection in projections {
560             let projection = projection.skip_binder();
561             let name = &self.tcx.associated_item(projection.item_def_id).name.as_str();
562             output.push_str(name);
563             output.push_str("=");
564             self.push_type_name(projection.ty, output);
565             output.push_str(", ");
566         }
567
568         output.pop();
569         output.pop();
570
571         output.push('>');
572     }
573
574     pub fn push_instance_as_string(&self,
575                                    instance: Instance<'tcx>,
576                                    output: &mut String) {
577         self.push_def_path(instance.def_id(), output);
578         self.push_type_params(instance.substs, iter::empty(), output);
579     }
580 }