]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/config.rs
Various minor/cosmetic improvements to code
[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::{
13     feature_err,
14     EXPLAIN_STMT_ATTR_SYNTAX,
15     Features,
16     get_features,
17     GateIssue,
18     emit_feature_err,
19 };
20 use {fold, attr};
21 use ast;
22 use source_map::Spanned;
23 use edition::Edition;
24 use parse::{token, ParseSess};
25 use smallvec::SmallVec;
26 use errors::Applicability;
27
28 use ptr::P;
29
30 /// A folder that strips out items that do not belong in the current configuration.
31 pub struct StripUnconfigured<'a> {
32     pub sess: &'a ParseSess,
33     pub features: Option<&'a Features>,
34 }
35
36 // `cfg_attr`-process the crate's attributes and compute the crate's features.
37 pub fn features(mut krate: ast::Crate, sess: &ParseSess, edition: Edition)
38                 -> (ast::Crate, Features) {
39     let features;
40     {
41         let mut strip_unconfigured = StripUnconfigured {
42             sess,
43             features: None,
44         };
45
46         let unconfigured_attrs = krate.attrs.clone();
47         let err_count = sess.span_diagnostic.err_count();
48         if let Some(attrs) = strip_unconfigured.configure(krate.attrs) {
49             krate.attrs = attrs;
50         } else { // the entire crate is unconfigured
51             krate.attrs = Vec::new();
52             krate.module.items = Vec::new();
53             return (krate, Features::new());
54         }
55
56         features = get_features(&sess.span_diagnostic, &krate.attrs, edition);
57
58         // Avoid reconfiguring malformed `cfg_attr`s
59         if err_count == sess.span_diagnostic.err_count() {
60             strip_unconfigured.features = Some(&features);
61             strip_unconfigured.configure(unconfigured_attrs);
62         }
63     }
64
65     (krate, features)
66 }
67
68 macro_rules! configure {
69     ($this:ident, $node:ident) => {
70         match $this.configure($node) {
71             Some(node) => node,
72             None => return Default::default(),
73         }
74     }
75 }
76
77 impl<'a> StripUnconfigured<'a> {
78     pub fn configure<T: HasAttrs>(&mut self, node: T) -> Option<T> {
79         let node = self.process_cfg_attrs(node);
80         if self.in_cfg(node.attrs()) { Some(node) } else { None }
81     }
82
83     /// Parse and expand all `cfg_attr` attributes into a list of attributes
84     /// that are within each `cfg_attr` that has a true configuration predicate.
85     ///
86     /// Gives compiler warnigns if any `cfg_attr` does not contain any
87     /// attributes and is in the original source code. Gives compiler errors if
88     /// the syntax of any `cfg_attr` is incorrect.
89     pub fn process_cfg_attrs<T: HasAttrs>(&mut self, node: T) -> T {
90         node.map_attrs(|attrs| {
91             attrs.into_iter().flat_map(|attr| self.process_cfg_attr(attr)).collect()
92         })
93     }
94
95     /// Parse and expand a single `cfg_attr` attribute into a list of attributes
96     /// when the configuration predicate is true, or otherwise expand into an
97     /// empty list of attributes.
98     ///
99     /// Gives a compiler warning when the `cfg_attr` contains no attributes and
100     /// is in the original source file. Gives a compiler error if the syntax of
101     /// the attribute is incorrect
102     fn process_cfg_attr(&mut self, attr: ast::Attribute) -> Vec<ast::Attribute> {
103         if !attr.check_name("cfg_attr") {
104             return vec![attr];
105         }
106
107         let gate_cfg_attr_multi = if let Some(ref features) = self.features {
108             !features.cfg_attr_multi
109         } else {
110             false
111         };
112         let cfg_attr_span = attr.span;
113
114         let (cfg_predicate, expanded_attrs) = match attr.parse(self.sess, |parser| {
115             parser.expect(&token::OpenDelim(token::Paren))?;
116
117             let cfg_predicate = parser.parse_meta_item()?;
118             parser.expect(&token::Comma)?;
119
120             // Presumably, the majority of the time there will only be one attr.
121             let mut expanded_attrs = Vec::with_capacity(1);
122
123             while !parser.check(&token::CloseDelim(token::Paren)) {
124                 let lo = parser.span.lo();
125                 let (path, tokens) = parser.parse_meta_item_unrestricted()?;
126                 expanded_attrs.push((path, tokens, parser.prev_span.with_lo(lo)));
127                 parser.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Paren)])?;
128             }
129
130             parser.expect(&token::CloseDelim(token::Paren))?;
131             Ok((cfg_predicate, expanded_attrs))
132         }) {
133             Ok(result) => result,
134             Err(mut e) => {
135                 e.emit();
136                 return Vec::new();
137             }
138         };
139
140         // Check feature gate and lint on zero attributes in source. Even if the feature is gated,
141         // we still compute as if it wasn't, since the emitted error will stop compilation further
142         // along the compilation.
143         match (expanded_attrs.len(), gate_cfg_attr_multi) {
144             (0, false) => {
145                 // FIXME: Emit unused attribute lint here.
146             },
147             (1, _) => {},
148             (_, true) => {
149                 emit_feature_err(
150                     self.sess,
151                     "cfg_attr_multi",
152                     cfg_attr_span,
153                     GateIssue::Language,
154                     "cfg_attr with zero or more than one attributes is experimental",
155                 );
156             },
157             (_, false) => {}
158         }
159
160         if attr::cfg_matches(&cfg_predicate, self.sess, self.features) {
161             // We call `process_cfg_attr` recursively in case there's a
162             // `cfg_attr` inside of another `cfg_attr`. E.g.
163             //  `#[cfg_attr(false, cfg_attr(true, some_attr))]`.
164             expanded_attrs.into_iter()
165             .flat_map(|(path, tokens, span)| self.process_cfg_attr(ast::Attribute {
166                 id: attr::mk_attr_id(),
167                 style: attr.style,
168                 path,
169                 tokens,
170                 is_sugared_doc: false,
171                 span,
172             }))
173             .collect()
174         } else {
175             Vec::new()
176         }
177     }
178
179     /// Determine if a node with the given attributes should be included in this configuration.
180     pub fn in_cfg(&mut self, attrs: &[ast::Attribute]) -> bool {
181         attrs.iter().all(|attr| {
182             if !is_cfg(attr) {
183                 return true;
184             }
185
186             let error = |span, msg, suggestion: &str| {
187                 let mut err = self.sess.span_diagnostic.struct_span_err(span, msg);
188                 if !suggestion.is_empty() {
189                     err.span_suggestion_with_applicability(
190                         span,
191                         "expected syntax is",
192                         suggestion.into(),
193                         Applicability::MaybeIncorrect,
194                     );
195                 }
196                 err.emit();
197                 true
198             };
199
200             let meta_item = if let Some(meta_item) = attr.meta() {
201                 meta_item
202             } else {
203                 // Not a well-formed meta-item. Why? We don't know.
204                 return error(attr.span, "`cfg` is not a well-formed meta-item",
205                                         "#[cfg(/* predicate */)]");
206             };
207             let nested_meta_items = if let Some(nested_meta_items) = meta_item.meta_item_list() {
208                 nested_meta_items
209             } else {
210                 return error(meta_item.span, "`cfg` is not followed by parentheses",
211                                              "cfg(/* predicate */)");
212             };
213
214             if nested_meta_items.is_empty() {
215                 return error(meta_item.span, "`cfg` predicate is not specified", "");
216             } else if nested_meta_items.len() > 1 {
217                 return error(nested_meta_items.last().unwrap().span,
218                              "multiple `cfg` predicates are specified", "");
219             }
220
221             match nested_meta_items[0].meta_item() {
222                 Some(meta_item) => attr::cfg_matches(meta_item, self.sess, self.features),
223                 None => error(nested_meta_items[0].span,
224                               "`cfg` predicate key cannot be a literal", ""),
225             }
226         })
227     }
228
229     /// Visit attributes on expression and statements (but not attributes on items in blocks).
230     fn visit_expr_attrs(&mut self, attrs: &[ast::Attribute]) {
231         // flag the offending attributes
232         for attr in attrs.iter() {
233             self.maybe_emit_expr_attr_err(attr);
234         }
235     }
236
237     /// If attributes are not allowed on expressions, emit an error for `attr`
238     pub fn maybe_emit_expr_attr_err(&self, attr: &ast::Attribute) {
239         if !self.features.map(|features| features.stmt_expr_attributes).unwrap_or(true) {
240             let mut err = feature_err(self.sess,
241                                       "stmt_expr_attributes",
242                                       attr.span,
243                                       GateIssue::Language,
244                                       EXPLAIN_STMT_ATTR_SYNTAX);
245
246             if attr.is_sugared_doc {
247                 err.help("`///` is for documentation comments. For a plain comment, use `//`.");
248             }
249
250             err.emit();
251         }
252     }
253
254     pub fn configure_foreign_mod(&mut self, foreign_mod: ast::ForeignMod) -> ast::ForeignMod {
255         ast::ForeignMod {
256             abi: foreign_mod.abi,
257             items: foreign_mod.items.into_iter().filter_map(|item| self.configure(item)).collect(),
258         }
259     }
260
261     fn configure_variant_data(&mut self, vdata: ast::VariantData) -> ast::VariantData {
262         match vdata {
263             ast::VariantData::Struct(fields, id) => {
264                 let fields = fields.into_iter().filter_map(|field| self.configure(field));
265                 ast::VariantData::Struct(fields.collect(), id)
266             }
267             ast::VariantData::Tuple(fields, id) => {
268                 let fields = fields.into_iter().filter_map(|field| self.configure(field));
269                 ast::VariantData::Tuple(fields.collect(), id)
270             }
271             ast::VariantData::Unit(id) => ast::VariantData::Unit(id)
272         }
273     }
274
275     pub fn configure_item_kind(&mut self, item: ast::ItemKind) -> ast::ItemKind {
276         match item {
277             ast::ItemKind::Struct(def, generics) => {
278                 ast::ItemKind::Struct(self.configure_variant_data(def), generics)
279             }
280             ast::ItemKind::Union(def, generics) => {
281                 ast::ItemKind::Union(self.configure_variant_data(def), generics)
282             }
283             ast::ItemKind::Enum(def, generics) => {
284                 let variants = def.variants.into_iter().filter_map(|v| {
285                     self.configure(v).map(|v| {
286                         Spanned {
287                             node: ast::Variant_ {
288                                 ident: v.node.ident,
289                                 attrs: v.node.attrs,
290                                 data: self.configure_variant_data(v.node.data),
291                                 disr_expr: v.node.disr_expr,
292                             },
293                             span: v.span
294                         }
295                     })
296                 });
297                 ast::ItemKind::Enum(ast::EnumDef {
298                     variants: variants.collect(),
299                 }, generics)
300             }
301             item => item,
302         }
303     }
304
305     pub fn configure_expr_kind(&mut self, expr_kind: ast::ExprKind) -> ast::ExprKind {
306         match expr_kind {
307             ast::ExprKind::Match(m, arms) => {
308                 let arms = arms.into_iter().filter_map(|a| self.configure(a)).collect();
309                 ast::ExprKind::Match(m, arms)
310             }
311             ast::ExprKind::Struct(path, fields, base) => {
312                 let fields = fields.into_iter()
313                     .filter_map(|field| {
314                         self.configure(field)
315                     })
316                     .collect();
317                 ast::ExprKind::Struct(path, fields, base)
318             }
319             _ => expr_kind,
320         }
321     }
322
323     pub fn configure_expr(&mut self, expr: P<ast::Expr>) -> P<ast::Expr> {
324         self.visit_expr_attrs(expr.attrs());
325
326         // If an expr is valid to cfg away it will have been removed by the
327         // outer stmt or expression folder before descending in here.
328         // Anything else is always required, and thus has to error out
329         // in case of a cfg attr.
330         //
331         // N.B., this is intentionally not part of the fold_expr() function
332         //     in order for fold_opt_expr() to be able to avoid this check
333         if let Some(attr) = expr.attrs().iter().find(|a| is_cfg(a)) {
334             let msg = "removing an expression is not supported in this position";
335             self.sess.span_diagnostic.span_err(attr.span, msg);
336         }
337
338         self.process_cfg_attrs(expr)
339     }
340
341     pub fn configure_stmt(&mut self, stmt: ast::Stmt) -> Option<ast::Stmt> {
342         self.configure(stmt)
343     }
344
345     pub fn configure_struct_expr_field(&mut self, field: ast::Field) -> Option<ast::Field> {
346         self.configure(field)
347     }
348
349     pub fn configure_pat(&mut self, pattern: P<ast::Pat>) -> P<ast::Pat> {
350         pattern.map(|mut pattern| {
351             if let ast::PatKind::Struct(path, fields, etc) = pattern.node {
352                 let fields = fields.into_iter()
353                     .filter_map(|field| {
354                         self.configure(field)
355                     })
356                     .collect();
357                 pattern.node = ast::PatKind::Struct(path, fields, etc);
358             }
359             pattern
360         })
361     }
362
363     // deny #[cfg] on generic parameters until we decide what to do with it.
364     // see issue #51279.
365     pub fn disallow_cfg_on_generic_param(&mut self, param: &ast::GenericParam) {
366         for attr in param.attrs() {
367             let offending_attr = if attr.check_name("cfg") {
368                 "cfg"
369             } else if attr.check_name("cfg_attr") {
370                 "cfg_attr"
371             } else {
372                 continue;
373             };
374             let msg = format!("#[{}] cannot be applied on a generic parameter", offending_attr);
375             self.sess.span_diagnostic.span_err(attr.span, &msg);
376         }
377     }
378 }
379
380 impl<'a> fold::Folder for StripUnconfigured<'a> {
381     fn fold_foreign_mod(&mut self, foreign_mod: ast::ForeignMod) -> ast::ForeignMod {
382         let foreign_mod = self.configure_foreign_mod(foreign_mod);
383         fold::noop_fold_foreign_mod(foreign_mod, self)
384     }
385
386     fn fold_item_kind(&mut self, item: ast::ItemKind) -> ast::ItemKind {
387         let item = self.configure_item_kind(item);
388         fold::noop_fold_item_kind(item, self)
389     }
390
391     fn fold_expr(&mut self, expr: P<ast::Expr>) -> P<ast::Expr> {
392         let mut expr = self.configure_expr(expr).into_inner();
393         expr.node = self.configure_expr_kind(expr.node);
394         P(fold::noop_fold_expr(expr, self))
395     }
396
397     fn fold_opt_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
398         let mut expr = configure!(self, expr).into_inner();
399         expr.node = self.configure_expr_kind(expr.node);
400         Some(P(fold::noop_fold_expr(expr, self)))
401     }
402
403     fn fold_stmt(&mut self, stmt: ast::Stmt) -> SmallVec<[ast::Stmt; 1]> {
404         match self.configure_stmt(stmt) {
405             Some(stmt) => fold::noop_fold_stmt(stmt, self),
406             None => return SmallVec::new(),
407         }
408     }
409
410     fn fold_item(&mut self, item: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
411         fold::noop_fold_item(configure!(self, item), self)
412     }
413
414     fn fold_impl_item(&mut self, item: ast::ImplItem) -> SmallVec<[ast::ImplItem; 1]>
415     {
416         fold::noop_fold_impl_item(configure!(self, item), self)
417     }
418
419     fn fold_trait_item(&mut self, item: ast::TraitItem) -> SmallVec<[ast::TraitItem; 1]> {
420         fold::noop_fold_trait_item(configure!(self, item), self)
421     }
422
423     fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
424         // Don't configure interpolated AST (cf. issue #34171).
425         // Interpolated AST will get configured once the surrounding tokens are parsed.
426         mac
427     }
428
429     fn fold_pat(&mut self, pattern: P<ast::Pat>) -> P<ast::Pat> {
430         fold::noop_fold_pat(self.configure_pat(pattern), self)
431     }
432 }
433
434 fn is_cfg(attr: &ast::Attribute) -> bool {
435     attr.check_name("cfg")
436 }