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