]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/config.rs
Auto merge of #35051 - japaric:backtrace, r=alexcrichton
[rust.git] / src / libsyntax / config.rs
1 // Copyright 2012-2014 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 use attr::{AttrMetaMethods, HasAttrs};
12 use feature_gate::{emit_feature_err, EXPLAIN_STMT_ATTR_SYNTAX, Features, get_features, GateIssue};
13 use fold::Folder;
14 use {fold, attr};
15 use ast;
16 use codemap::{Spanned, respan};
17 use parse::{ParseSess, token};
18 use ptr::P;
19
20 use util::small_vector::SmallVector;
21
22 /// A folder that strips out items that do not belong in the current configuration.
23 pub struct StripUnconfigured<'a> {
24     pub config: &'a ast::CrateConfig,
25     pub should_test: bool,
26     pub sess: &'a ParseSess,
27     pub features: Option<&'a Features>,
28 }
29
30 impl<'a> StripUnconfigured<'a> {
31     fn configure<T: HasAttrs>(&mut self, node: T) -> Option<T> {
32         let node = self.process_cfg_attrs(node);
33         if self.in_cfg(node.attrs()) { Some(node) } else { None }
34     }
35
36     pub fn process_cfg_attrs<T: HasAttrs>(&mut self, node: T) -> T {
37         node.map_attrs(|attrs| {
38             attrs.into_iter().filter_map(|attr| self.process_cfg_attr(attr)).collect()
39         })
40     }
41
42     fn process_cfg_attr(&mut self, attr: ast::Attribute) -> Option<ast::Attribute> {
43         if !attr.check_name("cfg_attr") {
44             return Some(attr);
45         }
46
47         let attr_list = match attr.meta_item_list() {
48             Some(attr_list) => attr_list,
49             None => {
50                 let msg = "expected `#[cfg_attr(<cfg pattern>, <attr>)]`";
51                 self.sess.span_diagnostic.span_err(attr.span, msg);
52                 return None;
53             }
54         };
55         let (cfg, mi) = match (attr_list.len(), attr_list.get(0), attr_list.get(1)) {
56             (2, Some(cfg), Some(mi)) => (cfg, mi),
57             _ => {
58                 let msg = "expected `#[cfg_attr(<cfg pattern>, <attr>)]`";
59                 self.sess.span_diagnostic.span_err(attr.span, msg);
60                 return None;
61             }
62         };
63
64         if attr::cfg_matches(self.config, &cfg, self.sess, self.features) {
65             self.process_cfg_attr(respan(mi.span, ast::Attribute_ {
66                 id: attr::mk_attr_id(),
67                 style: attr.node.style,
68                 value: mi.clone(),
69                 is_sugared_doc: false,
70             }))
71         } else {
72             None
73         }
74     }
75
76     // Determine if a node with the given attributes should be included in this configuation.
77     fn in_cfg(&mut self, attrs: &[ast::Attribute]) -> bool {
78         attrs.iter().all(|attr| {
79             // When not compiling with --test we should not compile the #[test] functions
80             if !self.should_test && is_test_or_bench(attr) {
81                 return false;
82             }
83
84             let mis = match attr.node.value.node {
85                 ast::MetaItemKind::List(_, ref mis) if is_cfg(&attr) => mis,
86                 _ => return true
87             };
88
89             if mis.len() != 1 {
90                 self.sess.span_diagnostic.span_err(attr.span, "expected 1 cfg-pattern");
91                 return true;
92             }
93
94             attr::cfg_matches(self.config, &mis[0], self.sess, self.features)
95         })
96     }
97
98     // Visit attributes on expression and statements (but not attributes on items in blocks).
99     fn visit_stmt_or_expr_attrs(&mut self, attrs: &[ast::Attribute]) {
100         // flag the offending attributes
101         for attr in attrs.iter() {
102             if !self.features.map(|features| features.stmt_expr_attributes).unwrap_or(true) {
103                 emit_feature_err(&self.sess.span_diagnostic,
104                                  "stmt_expr_attributes",
105                                  attr.span,
106                                  GateIssue::Language,
107                                  EXPLAIN_STMT_ATTR_SYNTAX);
108             }
109         }
110     }
111 }
112
113 // Support conditional compilation by transforming the AST, stripping out
114 // any items that do not belong in the current configuration
115 pub fn strip_unconfigured_items(mut krate: ast::Crate, sess: &ParseSess, should_test: bool)
116                                 -> (ast::Crate, Features) {
117     let features;
118     {
119         let mut strip_unconfigured = StripUnconfigured {
120             config: &krate.config.clone(),
121             should_test: should_test,
122             sess: sess,
123             features: None,
124         };
125
126         let err_count = sess.span_diagnostic.err_count();
127         let krate_attrs = strip_unconfigured.configure(krate.attrs.clone()).unwrap_or_default();
128         features = get_features(&sess.span_diagnostic, &krate_attrs);
129         if err_count < sess.span_diagnostic.err_count() {
130             krate.attrs = krate_attrs.clone(); // Avoid reconfiguring malformed `cfg_attr`s
131         }
132
133         strip_unconfigured.features = Some(&features);
134         krate = strip_unconfigured.fold_crate(krate);
135         krate.attrs = krate_attrs;
136     }
137
138     (krate, features)
139 }
140
141 impl<'a> fold::Folder for StripUnconfigured<'a> {
142     fn fold_foreign_mod(&mut self, foreign_mod: ast::ForeignMod) -> ast::ForeignMod {
143         ast::ForeignMod {
144             abi: foreign_mod.abi,
145             items: foreign_mod.items.into_iter().filter_map(|item| {
146                 self.configure(item).map(|item| fold::noop_fold_foreign_item(item, self))
147             }).collect(),
148         }
149     }
150
151     fn fold_item_kind(&mut self, item: ast::ItemKind) -> ast::ItemKind {
152         let fold_struct = |this: &mut Self, vdata| match vdata {
153             ast::VariantData::Struct(fields, id) => {
154                 let fields = fields.into_iter().filter_map(|field| this.configure(field));
155                 ast::VariantData::Struct(fields.collect(), id)
156             }
157             ast::VariantData::Tuple(fields, id) => {
158                 let fields = fields.into_iter().filter_map(|field| this.configure(field));
159                 ast::VariantData::Tuple(fields.collect(), id)
160             }
161             ast::VariantData::Unit(id) => ast::VariantData::Unit(id)
162         };
163
164         let item = match item {
165             ast::ItemKind::Struct(def, generics) => {
166                 ast::ItemKind::Struct(fold_struct(self, def), generics)
167             }
168             ast::ItemKind::Enum(def, generics) => {
169                 let variants = def.variants.into_iter().filter_map(|v| {
170                     self.configure(v).map(|v| {
171                         Spanned {
172                             node: ast::Variant_ {
173                                 name: v.node.name,
174                                 attrs: v.node.attrs,
175                                 data: fold_struct(self, v.node.data),
176                                 disr_expr: v.node.disr_expr,
177                             },
178                             span: v.span
179                         }
180                     })
181                 });
182                 ast::ItemKind::Enum(ast::EnumDef {
183                     variants: variants.collect(),
184                 }, generics)
185             }
186             item => item,
187         };
188
189         fold::noop_fold_item_kind(item, self)
190     }
191
192     fn fold_expr(&mut self, expr: P<ast::Expr>) -> P<ast::Expr> {
193         self.visit_stmt_or_expr_attrs(expr.attrs());
194
195         // If an expr is valid to cfg away it will have been removed by the
196         // outer stmt or expression folder before descending in here.
197         // Anything else is always required, and thus has to error out
198         // in case of a cfg attr.
199         //
200         // NB: This is intentionally not part of the fold_expr() function
201         //     in order for fold_opt_expr() to be able to avoid this check
202         if let Some(attr) = expr.attrs().iter().find(|a| is_cfg(a) || is_test_or_bench(a)) {
203             let msg = "removing an expression is not supported in this position";
204             self.sess.span_diagnostic.span_err(attr.span, msg);
205         }
206
207         let expr = self.process_cfg_attrs(expr);
208         fold_expr(self, expr)
209     }
210
211     fn fold_opt_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
212         self.configure(expr).map(|expr| fold_expr(self, expr))
213     }
214
215     fn fold_stmt(&mut self, stmt: ast::Stmt) -> SmallVector<ast::Stmt> {
216         self.visit_stmt_or_expr_attrs(stmt.attrs());
217         self.configure(stmt).map(|stmt| fold::noop_fold_stmt(stmt, self))
218                             .unwrap_or(SmallVector::zero())
219     }
220
221     fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
222         fold::noop_fold_mac(mac, self)
223     }
224
225     fn fold_item(&mut self, item: P<ast::Item>) -> SmallVector<P<ast::Item>> {
226         self.configure(item).map(|item| fold::noop_fold_item(item, self))
227                             .unwrap_or(SmallVector::zero())
228     }
229
230     fn fold_impl_item(&mut self, item: ast::ImplItem) -> SmallVector<ast::ImplItem> {
231         self.configure(item).map(|item| fold::noop_fold_impl_item(item, self))
232                             .unwrap_or(SmallVector::zero())
233     }
234
235     fn fold_trait_item(&mut self, item: ast::TraitItem) -> SmallVector<ast::TraitItem> {
236         self.configure(item).map(|item| fold::noop_fold_trait_item(item, self))
237                             .unwrap_or(SmallVector::zero())
238     }
239
240     fn fold_interpolated(&mut self, nt: token::Nonterminal) -> token::Nonterminal {
241         // Don't configure interpolated AST (c.f. #34171).
242         // Interpolated AST will get configured once the surrounding tokens are parsed.
243         nt
244     }
245 }
246
247 fn fold_expr(folder: &mut StripUnconfigured, expr: P<ast::Expr>) -> P<ast::Expr> {
248     expr.map(|ast::Expr {id, span, node, attrs}| {
249         fold::noop_fold_expr(ast::Expr {
250             id: id,
251             node: match node {
252                 ast::ExprKind::Match(m, arms) => {
253                     ast::ExprKind::Match(m, arms.into_iter()
254                                         .filter_map(|a| folder.configure(a))
255                                         .collect())
256                 }
257                 _ => node
258             },
259             span: span,
260             attrs: attrs,
261         }, folder)
262     })
263 }
264
265 fn is_cfg(attr: &ast::Attribute) -> bool {
266     attr.check_name("cfg")
267 }
268
269 fn is_test_or_bench(attr: &ast::Attribute) -> bool {
270     attr.check_name("test") || attr.check_name("bench")
271 }