]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/config.rs
tests: prefer edition: directives to compile-flags:--edition.
[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::HasAttrs;
12 use feature_gate::{feature_err, EXPLAIN_STMT_ATTR_SYNTAX, Features, get_features, GateIssue};
13 use {fold, attr};
14 use ast;
15 use codemap::Spanned;
16 use edition::Edition;
17 use parse::{token, ParseSess};
18 use OneVector;
19
20 use ptr::P;
21
22 /// A folder that strips out items that do not belong in the current configuration.
23 pub struct StripUnconfigured<'a> {
24     pub should_test: bool,
25     pub sess: &'a ParseSess,
26     pub features: Option<&'a Features>,
27 }
28
29 // `cfg_attr`-process the crate's attributes and compute the crate's features.
30 pub fn features(mut krate: ast::Crate, sess: &ParseSess, should_test: bool, edition: Edition)
31                 -> (ast::Crate, Features) {
32     let features;
33     {
34         let mut strip_unconfigured = StripUnconfigured {
35             should_test,
36             sess,
37             features: None,
38         };
39
40         let unconfigured_attrs = krate.attrs.clone();
41         let err_count = sess.span_diagnostic.err_count();
42         if let Some(attrs) = strip_unconfigured.configure(krate.attrs) {
43             krate.attrs = attrs;
44         } else { // the entire crate is unconfigured
45             krate.attrs = Vec::new();
46             krate.module.items = Vec::new();
47             return (krate, Features::new());
48         }
49
50         features = get_features(&sess.span_diagnostic, &krate.attrs, edition);
51
52         // Avoid reconfiguring malformed `cfg_attr`s
53         if err_count == sess.span_diagnostic.err_count() {
54             strip_unconfigured.features = Some(&features);
55             strip_unconfigured.configure(unconfigured_attrs);
56         }
57     }
58
59     (krate, features)
60 }
61
62 macro_rules! configure {
63     ($this:ident, $node:ident) => {
64         match $this.configure($node) {
65             Some(node) => node,
66             None => return Default::default(),
67         }
68     }
69 }
70
71 impl<'a> StripUnconfigured<'a> {
72     pub fn configure<T: HasAttrs>(&mut self, node: T) -> Option<T> {
73         let node = self.process_cfg_attrs(node);
74         if self.in_cfg(node.attrs()) { Some(node) } else { None }
75     }
76
77     pub fn process_cfg_attrs<T: HasAttrs>(&mut self, node: T) -> T {
78         node.map_attrs(|attrs| {
79             attrs.into_iter().filter_map(|attr| self.process_cfg_attr(attr)).collect()
80         })
81     }
82
83     fn process_cfg_attr(&mut self, attr: ast::Attribute) -> Option<ast::Attribute> {
84         if !attr.check_name("cfg_attr") {
85             return Some(attr);
86         }
87
88         let (cfg, path, tokens, span) = match attr.parse(self.sess, |parser| {
89             parser.expect(&token::OpenDelim(token::Paren))?;
90             let cfg = parser.parse_meta_item()?;
91             parser.expect(&token::Comma)?;
92             let lo = parser.span.lo();
93             let (path, tokens) = parser.parse_path_and_tokens()?;
94             parser.expect(&token::CloseDelim(token::Paren))?;
95             Ok((cfg, path, tokens, parser.prev_span.with_lo(lo)))
96         }) {
97             Ok(result) => result,
98             Err(mut e) => {
99                 e.emit();
100                 return None;
101             }
102         };
103
104         if attr::cfg_matches(&cfg, self.sess, self.features) {
105             self.process_cfg_attr(ast::Attribute {
106                 id: attr::mk_attr_id(),
107                 style: attr.style,
108                 path,
109                 tokens,
110                 is_sugared_doc: false,
111                 span,
112             })
113         } else {
114             None
115         }
116     }
117
118     // Determine if a node with the given attributes should be included in this configuration.
119     pub fn in_cfg(&mut self, attrs: &[ast::Attribute]) -> bool {
120         attrs.iter().all(|attr| {
121             // When not compiling with --test we should not compile the #[test] functions
122             if !self.should_test && is_test_or_bench(attr) {
123                 return false;
124             }
125
126             let mis = if !is_cfg(attr) {
127                 return true;
128             } else if let Some(mis) = attr.meta_item_list() {
129                 mis
130             } else {
131                 return true;
132             };
133
134             if mis.len() != 1 {
135                 self.sess.span_diagnostic.span_err(attr.span, "expected 1 cfg-pattern");
136                 return true;
137             }
138
139             if !mis[0].is_meta_item() {
140                 self.sess.span_diagnostic.span_err(mis[0].span, "unexpected literal");
141                 return true;
142             }
143
144             attr::cfg_matches(mis[0].meta_item().unwrap(), self.sess, self.features)
145         })
146     }
147
148     // Visit attributes on expression and statements (but not attributes on items in blocks).
149     fn visit_expr_attrs(&mut self, attrs: &[ast::Attribute]) {
150         // flag the offending attributes
151         for attr in attrs.iter() {
152             self.maybe_emit_expr_attr_err(attr);
153         }
154     }
155
156     /// If attributes are not allowed on expressions, emit an error for `attr`
157     pub fn maybe_emit_expr_attr_err(&self, attr: &ast::Attribute) {
158         if !self.features.map(|features| features.stmt_expr_attributes).unwrap_or(true) {
159             let mut err = feature_err(self.sess,
160                                       "stmt_expr_attributes",
161                                       attr.span,
162                                       GateIssue::Language,
163                                       EXPLAIN_STMT_ATTR_SYNTAX);
164
165             if attr.is_sugared_doc {
166                 err.help("`///` is for documentation comments. For a plain comment, use `//`.");
167             }
168
169             err.emit();
170         }
171     }
172
173     pub fn configure_foreign_mod(&mut self, foreign_mod: ast::ForeignMod) -> ast::ForeignMod {
174         ast::ForeignMod {
175             abi: foreign_mod.abi,
176             items: foreign_mod.items.into_iter().filter_map(|item| self.configure(item)).collect(),
177         }
178     }
179
180     fn configure_variant_data(&mut self, vdata: ast::VariantData) -> ast::VariantData {
181         match vdata {
182             ast::VariantData::Struct(fields, id) => {
183                 let fields = fields.into_iter().filter_map(|field| self.configure(field));
184                 ast::VariantData::Struct(fields.collect(), id)
185             }
186             ast::VariantData::Tuple(fields, id) => {
187                 let fields = fields.into_iter().filter_map(|field| self.configure(field));
188                 ast::VariantData::Tuple(fields.collect(), id)
189             }
190             ast::VariantData::Unit(id) => ast::VariantData::Unit(id)
191         }
192     }
193
194     pub fn configure_item_kind(&mut self, item: ast::ItemKind) -> ast::ItemKind {
195         match item {
196             ast::ItemKind::Struct(def, generics) => {
197                 ast::ItemKind::Struct(self.configure_variant_data(def), generics)
198             }
199             ast::ItemKind::Union(def, generics) => {
200                 ast::ItemKind::Union(self.configure_variant_data(def), generics)
201             }
202             ast::ItemKind::Enum(def, generics) => {
203                 let variants = def.variants.into_iter().filter_map(|v| {
204                     self.configure(v).map(|v| {
205                         Spanned {
206                             node: ast::Variant_ {
207                                 ident: v.node.ident,
208                                 attrs: v.node.attrs,
209                                 data: self.configure_variant_data(v.node.data),
210                                 disr_expr: v.node.disr_expr,
211                             },
212                             span: v.span
213                         }
214                     })
215                 });
216                 ast::ItemKind::Enum(ast::EnumDef {
217                     variants: variants.collect(),
218                 }, generics)
219             }
220             item => item,
221         }
222     }
223
224     pub fn configure_expr_kind(&mut self, expr_kind: ast::ExprKind) -> ast::ExprKind {
225         match expr_kind {
226             ast::ExprKind::Match(m, arms) => {
227                 let arms = arms.into_iter().filter_map(|a| self.configure(a)).collect();
228                 ast::ExprKind::Match(m, arms)
229             }
230             ast::ExprKind::Struct(path, fields, base) => {
231                 let fields = fields.into_iter()
232                     .filter_map(|field| {
233                         self.configure(field)
234                     })
235                     .collect();
236                 ast::ExprKind::Struct(path, fields, base)
237             }
238             _ => expr_kind,
239         }
240     }
241
242     pub fn configure_expr(&mut self, expr: P<ast::Expr>) -> P<ast::Expr> {
243         self.visit_expr_attrs(expr.attrs());
244
245         // If an expr is valid to cfg away it will have been removed by the
246         // outer stmt or expression folder before descending in here.
247         // Anything else is always required, and thus has to error out
248         // in case of a cfg attr.
249         //
250         // NB: This is intentionally not part of the fold_expr() function
251         //     in order for fold_opt_expr() to be able to avoid this check
252         if let Some(attr) = expr.attrs().iter().find(|a| is_cfg(a) || is_test_or_bench(a)) {
253             let msg = "removing an expression is not supported in this position";
254             self.sess.span_diagnostic.span_err(attr.span, msg);
255         }
256
257         self.process_cfg_attrs(expr)
258     }
259
260     pub fn configure_stmt(&mut self, stmt: ast::Stmt) -> Option<ast::Stmt> {
261         self.configure(stmt)
262     }
263
264     pub fn configure_struct_expr_field(&mut self, field: ast::Field) -> Option<ast::Field> {
265         self.configure(field)
266     }
267
268     pub fn configure_pat(&mut self, pattern: P<ast::Pat>) -> P<ast::Pat> {
269         pattern.map(|mut pattern| {
270             if let ast::PatKind::Struct(path, fields, etc) = pattern.node {
271                 let fields = fields.into_iter()
272                     .filter_map(|field| {
273                         self.configure(field)
274                     })
275                     .collect();
276                 pattern.node = ast::PatKind::Struct(path, fields, etc);
277             }
278             pattern
279         })
280     }
281
282     // deny #[cfg] on generic parameters until we decide what to do with it.
283     // see issue #51279.
284     pub fn disallow_cfg_on_generic_param(&mut self, param: &ast::GenericParam) {
285         for attr in param.attrs() {
286             let offending_attr = if attr.check_name("cfg") {
287                 "cfg"
288             } else if attr.check_name("cfg_attr") {
289                 "cfg_attr"
290             } else {
291                 continue;
292             };
293             let msg = format!("#[{}] cannot be applied on a generic parameter", offending_attr);
294             self.sess.span_diagnostic.span_err(attr.span, &msg);
295         }
296     }
297 }
298
299 impl<'a> fold::Folder for StripUnconfigured<'a> {
300     fn fold_foreign_mod(&mut self, foreign_mod: ast::ForeignMod) -> ast::ForeignMod {
301         let foreign_mod = self.configure_foreign_mod(foreign_mod);
302         fold::noop_fold_foreign_mod(foreign_mod, self)
303     }
304
305     fn fold_item_kind(&mut self, item: ast::ItemKind) -> ast::ItemKind {
306         let item = self.configure_item_kind(item);
307         fold::noop_fold_item_kind(item, self)
308     }
309
310     fn fold_expr(&mut self, expr: P<ast::Expr>) -> P<ast::Expr> {
311         let mut expr = self.configure_expr(expr).into_inner();
312         expr.node = self.configure_expr_kind(expr.node);
313         P(fold::noop_fold_expr(expr, self))
314     }
315
316     fn fold_opt_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
317         let mut expr = configure!(self, expr).into_inner();
318         expr.node = self.configure_expr_kind(expr.node);
319         Some(P(fold::noop_fold_expr(expr, self)))
320     }
321
322     fn fold_stmt(&mut self, stmt: ast::Stmt) -> OneVector<ast::Stmt> {
323         match self.configure_stmt(stmt) {
324             Some(stmt) => fold::noop_fold_stmt(stmt, self),
325             None => return OneVector::new(),
326         }
327     }
328
329     fn fold_item(&mut self, item: P<ast::Item>) -> OneVector<P<ast::Item>> {
330         fold::noop_fold_item(configure!(self, item), self)
331     }
332
333     fn fold_impl_item(&mut self, item: ast::ImplItem) -> OneVector<ast::ImplItem> {
334         fold::noop_fold_impl_item(configure!(self, item), self)
335     }
336
337     fn fold_trait_item(&mut self, item: ast::TraitItem) -> OneVector<ast::TraitItem> {
338         fold::noop_fold_trait_item(configure!(self, item), self)
339     }
340
341     fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
342         // Don't configure interpolated AST (c.f. #34171).
343         // Interpolated AST will get configured once the surrounding tokens are parsed.
344         mac
345     }
346
347     fn fold_pat(&mut self, pattern: P<ast::Pat>) -> P<ast::Pat> {
348         fold::noop_fold_pat(self.configure_pat(pattern), self)
349     }
350 }
351
352 fn is_cfg(attr: &ast::Attribute) -> bool {
353     attr.check_name("cfg")
354 }
355
356 pub fn is_test_or_bench(attr: &ast::Attribute) -> bool {
357     attr.check_name("test") || attr.check_name("bench")
358 }