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