]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_symbol_mangling/src/test.rs
New upstream version 1.48.0~beta.8+dfsg1
[rustc.git] / compiler / rustc_symbol_mangling / src / test.rs
1 //! Walks the crate looking for items/impl-items/trait-items that have
2 //! either a `rustc_symbol_name` or `rustc_def_path` attribute and
3 //! generates an error giving, respectively, the symbol name or
4 //! def-path. This is used for unit testing the code that generates
5 //! paths etc in all kinds of annoying scenarios.
6
7 use rustc_hir as hir;
8 use rustc_middle::ty::{Instance, TyCtxt};
9 use rustc_span::symbol::{sym, Symbol};
10
11 const SYMBOL_NAME: Symbol = sym::rustc_symbol_name;
12 const DEF_PATH: Symbol = sym::rustc_def_path;
13
14 pub fn report_symbol_names(tcx: TyCtxt<'_>) {
15 // if the `rustc_attrs` feature is not enabled, then the
16 // attributes we are interested in cannot be present anyway, so
17 // skip the walk.
18 if !tcx.features().rustc_attrs {
19 return;
20 }
21
22 tcx.dep_graph.with_ignore(|| {
23 let mut visitor = SymbolNamesTest { tcx };
24 tcx.hir().krate().visit_all_item_likes(&mut visitor);
25 })
26 }
27
28 struct SymbolNamesTest<'tcx> {
29 tcx: TyCtxt<'tcx>,
30 }
31
32 impl SymbolNamesTest<'tcx> {
33 fn process_attrs(&mut self, hir_id: hir::HirId) {
34 let tcx = self.tcx;
35 let def_id = tcx.hir().local_def_id(hir_id);
36 for attr in tcx.get_attrs(def_id.to_def_id()).iter() {
37 if tcx.sess.check_name(attr, SYMBOL_NAME) {
38 // for now, can only use on monomorphic names
39 let instance = Instance::mono(tcx, def_id.to_def_id());
40 let mangled = tcx.symbol_name(instance);
41 tcx.sess.span_err(attr.span, &format!("symbol-name({})", mangled));
42 if let Ok(demangling) = rustc_demangle::try_demangle(mangled.name) {
43 tcx.sess.span_err(attr.span, &format!("demangling({})", demangling));
44 tcx.sess.span_err(attr.span, &format!("demangling-alt({:#})", demangling));
45 }
46 } else if tcx.sess.check_name(attr, DEF_PATH) {
47 let path = tcx.def_path_str(def_id.to_def_id());
48 tcx.sess.span_err(attr.span, &format!("def-path({})", path));
49 }
50
51 // (*) The formatting of `tag({})` is chosen so that tests can elect
52 // to test the entirety of the string, if they choose, or else just
53 // some subset.
54 }
55 }
56 }
57
58 impl hir::itemlikevisit::ItemLikeVisitor<'tcx> for SymbolNamesTest<'tcx> {
59 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
60 self.process_attrs(item.hir_id);
61 }
62
63 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
64 self.process_attrs(trait_item.hir_id);
65 }
66
67 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
68 self.process_attrs(impl_item.hir_id);
69 }
70 }