]> git.lizzy.rs Git - rust.git/blob - src/librustc_incremental/assert_module_sources.rs
Move cgu_reuse_tracker to librustc_session
[rust.git] / src / librustc_incremental / assert_module_sources.rs
1 //! This pass is only used for UNIT TESTS related to incremental
2 //! compilation. It tests whether a particular `.o` file will be re-used
3 //! from a previous compilation or whether it must be regenerated.
4 //!
5 //! The user adds annotations to the crate of the following form:
6 //!
7 //! ```
8 //! #![rustc_partition_reused(module="spike", cfg="rpass2")]
9 //! #![rustc_partition_codegened(module="spike-x", cfg="rpass2")]
10 //! ```
11 //!
12 //! The first indicates (in the cfg `rpass2`) that `spike.o` will be
13 //! reused, the second that `spike-x.o` will be recreated. If these
14 //! annotations are inaccurate, errors are reported.
15 //!
16 //! The reason that we use `cfg=...` and not `#[cfg_attr]` is so that
17 //! the HIR doesn't change as a result of the annotations, which might
18 //! perturb the reuse results.
19 //!
20 //! `#![rustc_expected_cgu_reuse(module="spike", cfg="rpass2", kind="post-lto")]
21 //! allows for doing a more fine-grained check to see if pre- or post-lto data
22 //! was re-used.
23
24 use rustc::hir::def_id::LOCAL_CRATE;
25 use rustc_session::cgu_reuse_tracker::*;
26 use rustc::mir::mono::CodegenUnitNameBuilder;
27 use rustc::ty::TyCtxt;
28 use std::collections::BTreeSet;
29 use syntax::ast;
30 use syntax::symbol::{Symbol, sym};
31 use rustc::ich::{ATTR_PARTITION_REUSED, ATTR_PARTITION_CODEGENED,
32                  ATTR_EXPECTED_CGU_REUSE};
33
34 pub fn assert_module_sources(tcx: TyCtxt<'_>) {
35     tcx.dep_graph.with_ignore(|| {
36         if tcx.sess.opts.incremental.is_none() {
37             return;
38         }
39
40         let available_cgus = tcx
41             .collect_and_partition_mono_items(LOCAL_CRATE)
42             .1
43             .iter()
44             .map(|cgu| cgu.name())
45             .collect::<BTreeSet<Symbol>>();
46
47         let ams = AssertModuleSource {
48             tcx,
49             available_cgus
50         };
51
52         for attr in &tcx.hir().krate().attrs {
53             ams.check_attr(attr);
54         }
55     })
56 }
57
58 struct AssertModuleSource<'tcx> {
59     tcx: TyCtxt<'tcx>,
60     available_cgus: BTreeSet<Symbol>,
61 }
62
63 impl AssertModuleSource<'tcx> {
64     fn check_attr(&self, attr: &ast::Attribute) {
65         let (expected_reuse, comp_kind) = if attr.check_name(ATTR_PARTITION_REUSED) {
66             (CguReuse::PreLto, ComparisonKind::AtLeast)
67         } else if attr.check_name(ATTR_PARTITION_CODEGENED) {
68             (CguReuse::No, ComparisonKind::Exact)
69         } else if attr.check_name(ATTR_EXPECTED_CGU_REUSE) {
70             match &*self.field(attr, sym::kind).as_str() {
71                 "no" => (CguReuse::No, ComparisonKind::Exact),
72                 "pre-lto" => (CguReuse::PreLto, ComparisonKind::Exact),
73                 "post-lto" => (CguReuse::PostLto, ComparisonKind::Exact),
74                 "any" => (CguReuse::PreLto, ComparisonKind::AtLeast),
75                 other => {
76                     self.tcx.sess.span_fatal(
77                         attr.span,
78                         &format!("unknown cgu-reuse-kind `{}` specified", other));
79                 }
80             }
81         } else {
82             return;
83         };
84
85         if !self.tcx.sess.opts.debugging_opts.query_dep_graph {
86             self.tcx.sess.span_fatal(
87                 attr.span,
88                 &format!("found CGU-reuse attribute but `-Zquery-dep-graph` \
89                           was not specified"));
90         }
91
92         if !self.check_config(attr) {
93             debug!("check_attr: config does not match, ignoring attr");
94             return;
95         }
96
97         let user_path = self.field(attr, sym::module).to_string();
98         let crate_name = self.tcx.crate_name(LOCAL_CRATE).to_string();
99
100         if !user_path.starts_with(&crate_name) {
101             let msg = format!("Found malformed codegen unit name `{}`. \
102                 Codegen units names must always start with the name of the \
103                 crate (`{}` in this case).", user_path, crate_name);
104             self.tcx.sess.span_fatal(attr.span, &msg);
105         }
106
107         // Split of the "special suffix" if there is one.
108         let (user_path, cgu_special_suffix) = if let Some(index) = user_path.rfind(".") {
109             (&user_path[..index], Some(&user_path[index + 1 ..]))
110         } else {
111             (&user_path[..], None)
112         };
113
114         let mut cgu_path_components = user_path.split('-').collect::<Vec<_>>();
115
116         // Remove the crate name
117         assert_eq!(cgu_path_components.remove(0), crate_name);
118
119         let cgu_name_builder = &mut CodegenUnitNameBuilder::new(self.tcx);
120         let cgu_name = cgu_name_builder.build_cgu_name(LOCAL_CRATE,
121                                                        cgu_path_components,
122                                                        cgu_special_suffix);
123
124         debug!("mapping '{}' to cgu name '{}'", self.field(attr, sym::module), cgu_name);
125
126         if !self.available_cgus.contains(&cgu_name) {
127             self.tcx.sess.span_err(attr.span,
128                 &format!("no module named `{}` (mangled: {}). \
129                           Available modules: {}",
130                     user_path,
131                     cgu_name,
132                     self.available_cgus
133                         .iter()
134                         .map(|cgu| cgu.to_string())
135                         .collect::<Vec<_>>()
136                         .join(", ")));
137         }
138
139         self.tcx.sess.cgu_reuse_tracker.set_expectation(&cgu_name.as_str(),
140                                                         &user_path,
141                                                         attr.span,
142                                                         expected_reuse,
143                                                         comp_kind);
144     }
145
146     fn field(&self, attr: &ast::Attribute, name: Symbol) -> ast::Name {
147         for item in attr.meta_item_list().unwrap_or_else(Vec::new) {
148             if item.check_name(name) {
149                 if let Some(value) = item.value_str() {
150                     return value;
151                 } else {
152                     self.tcx.sess.span_fatal(
153                         item.span(),
154                         &format!("associated value expected for `{}`", name));
155                 }
156             }
157         }
158
159         self.tcx.sess.span_fatal(
160             attr.span,
161             &format!("no field `{}`", name));
162     }
163
164     /// Scan for a `cfg="foo"` attribute and check whether we have a
165     /// cfg flag called `foo`.
166     fn check_config(&self, attr: &ast::Attribute) -> bool {
167         let config = &self.tcx.sess.parse_sess.config;
168         let value = self.field(attr, sym::cfg);
169         debug!("check_config(config={:?}, value={:?})", config, value);
170         if config.iter().any(|&(name, _)| name == value) {
171             debug!("check_config: matched");
172             return true;
173         }
174         debug!("check_config: no match found");
175         return false;
176     }
177 }