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