]> git.lizzy.rs Git - rust.git/blob - src/librustc_incremental/assert_module_sources.rs
Rollup merge of #58182 - jethrogb:jb/sgx-bytebuffer-len-0, r=joshtriplett
[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::dep_graph::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 rustc::ich::{ATTR_PARTITION_REUSED, ATTR_PARTITION_CODEGENED,
31                  ATTR_EXPECTED_CGU_REUSE};
32
33 const MODULE: &str = "module";
34 const CFG: &str = "cfg";
35 const KIND: &str = "kind";
36
37 pub fn assert_module_sources<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
38     tcx.dep_graph.with_ignore(|| {
39         if tcx.sess.opts.incremental.is_none() {
40             return;
41         }
42
43         let available_cgus = tcx
44             .collect_and_partition_mono_items(LOCAL_CRATE)
45             .1
46             .iter()
47             .map(|cgu| format!("{}", cgu.name()))
48             .collect::<BTreeSet<String>>();
49
50         let ams = AssertModuleSource {
51             tcx,
52             available_cgus
53         };
54
55         for attr in &tcx.hir().krate().attrs {
56             ams.check_attr(attr);
57         }
58     })
59 }
60
61 struct AssertModuleSource<'a, 'tcx: 'a> {
62     tcx: TyCtxt<'a, 'tcx, 'tcx>,
63     available_cgus: BTreeSet<String>,
64 }
65
66 impl<'a, 'tcx> AssertModuleSource<'a, 'tcx> {
67     fn check_attr(&self, attr: &ast::Attribute) {
68         let (expected_reuse, comp_kind) = if attr.check_name(ATTR_PARTITION_REUSED) {
69             (CguReuse::PreLto, ComparisonKind::AtLeast)
70         } else if attr.check_name(ATTR_PARTITION_CODEGENED) {
71             (CguReuse::No, ComparisonKind::Exact)
72         } else if attr.check_name(ATTR_EXPECTED_CGU_REUSE) {
73             match &self.field(attr, KIND).as_str()[..] {
74                 "no" => (CguReuse::No, ComparisonKind::Exact),
75                 "pre-lto" => (CguReuse::PreLto, ComparisonKind::Exact),
76                 "post-lto" => (CguReuse::PostLto, ComparisonKind::Exact),
77                 "any" => (CguReuse::PreLto, ComparisonKind::AtLeast),
78                 other => {
79                     self.tcx.sess.span_fatal(
80                         attr.span,
81                         &format!("unknown cgu-reuse-kind `{}` specified", other));
82                 }
83             }
84         } else {
85             return;
86         };
87
88         if !self.tcx.sess.opts.debugging_opts.query_dep_graph {
89             self.tcx.sess.span_fatal(
90                 attr.span,
91                 &format!("found CGU-reuse attribute but `-Zquery-dep-graph` \
92                           was not specified"));
93         }
94
95         if !self.check_config(attr) {
96             debug!("check_attr: config does not match, ignoring attr");
97             return;
98         }
99
100         let user_path = self.field(attr, MODULE).as_str().to_string();
101         let crate_name = self.tcx.crate_name(LOCAL_CRATE).as_str().to_string();
102
103         if !user_path.starts_with(&crate_name) {
104             let msg = format!("Found malformed codegen unit name `{}`. \
105                 Codegen units names must always start with the name of the \
106                 crate (`{}` in this case).", user_path, crate_name);
107             self.tcx.sess.span_fatal(attr.span, &msg);
108         }
109
110         // Split of the "special suffix" if there is one.
111         let (user_path, cgu_special_suffix) = if let Some(index) = user_path.rfind(".") {
112             (&user_path[..index], Some(&user_path[index + 1 ..]))
113         } else {
114             (&user_path[..], None)
115         };
116
117         let mut cgu_path_components = user_path.split('-').collect::<Vec<_>>();
118
119         // Remove the crate name
120         assert_eq!(cgu_path_components.remove(0), crate_name);
121
122         let cgu_name_builder = &mut CodegenUnitNameBuilder::new(self.tcx);
123         let cgu_name = cgu_name_builder.build_cgu_name(LOCAL_CRATE,
124                                                        cgu_path_components,
125                                                        cgu_special_suffix);
126
127         debug!("mapping '{}' to cgu name '{}'", self.field(attr, MODULE), cgu_name);
128
129         if !self.available_cgus.contains(&cgu_name.as_str()[..]) {
130             self.tcx.sess.span_err(attr.span,
131                 &format!("no module named `{}` (mangled: {}). \
132                           Available modules: {}",
133                     user_path,
134                     cgu_name,
135                     self.available_cgus
136                         .iter()
137                         .cloned()
138                         .collect::<Vec<_>>()
139                         .join(", ")));
140         }
141
142         self.tcx.sess.cgu_reuse_tracker.set_expectation(&cgu_name.as_str(),
143                                                         &user_path,
144                                                         attr.span,
145                                                         expected_reuse,
146                                                         comp_kind);
147     }
148
149     fn field(&self, attr: &ast::Attribute, name: &str) -> ast::Name {
150         for item in attr.meta_item_list().unwrap_or_else(Vec::new) {
151             if item.check_name(name) {
152                 if let Some(value) = item.value_str() {
153                     return value;
154                 } else {
155                     self.tcx.sess.span_fatal(
156                         item.span,
157                         &format!("associated value expected for `{}`", name));
158                 }
159             }
160         }
161
162         self.tcx.sess.span_fatal(
163             attr.span,
164             &format!("no field `{}`", name));
165     }
166
167     /// Scan for a `cfg="foo"` attribute and check whether we have a
168     /// cfg flag called `foo`.
169     fn check_config(&self, attr: &ast::Attribute) -> bool {
170         let config = &self.tcx.sess.parse_sess.config;
171         let value = self.field(attr, CFG);
172         debug!("check_config(config={:?}, value={:?})", config, value);
173         if config.iter().any(|&(name, _)| name == value) {
174             debug!("check_config: matched");
175             return true;
176         }
177         debug!("check_config: no match found");
178         return false;
179     }
180 }