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