]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/config.rs
Merge Variant and Variant_
[rust.git] / src / libsyntax / config.rs
1 use crate::attr::HasAttrs;
2 use crate::feature_gate::{
3     feature_err,
4     EXPLAIN_STMT_ATTR_SYNTAX,
5     Features,
6     get_features,
7     GateIssue,
8 };
9 use crate::attr;
10 use crate::ast;
11 use crate::edition::Edition;
12 use crate::mut_visit::*;
13 use crate::parse::{token, ParseSess};
14 use crate::ptr::P;
15 use crate::symbol::sym;
16 use crate::util::map_in_place::MapInPlace;
17
18 use errors::Applicability;
19 use smallvec::SmallVec;
20
21 /// A folder that strips out items that do not belong in the current configuration.
22 pub struct StripUnconfigured<'a> {
23     pub sess: &'a ParseSess,
24     pub features: Option<&'a Features>,
25 }
26
27 // `cfg_attr`-process the crate's attributes and compute the crate's features.
28 pub fn features(mut krate: ast::Crate, sess: &ParseSess, edition: Edition,
29                 allow_features: &Option<Vec<String>>) -> (ast::Crate, Features) {
30     let features;
31     {
32         let mut strip_unconfigured = StripUnconfigured {
33             sess,
34             features: None,
35         };
36
37         let unconfigured_attrs = krate.attrs.clone();
38         let err_count = sess.span_diagnostic.err_count();
39         if let Some(attrs) = strip_unconfigured.configure(krate.attrs) {
40             krate.attrs = attrs;
41         } else { // the entire crate is unconfigured
42             krate.attrs = Vec::new();
43             krate.module.items = Vec::new();
44             return (krate, Features::new());
45         }
46
47         features = get_features(&sess.span_diagnostic, &krate.attrs, edition, allow_features);
48
49         // Avoid reconfiguring malformed `cfg_attr`s
50         if err_count == sess.span_diagnostic.err_count() {
51             strip_unconfigured.features = Some(&features);
52             strip_unconfigured.configure(unconfigured_attrs);
53         }
54     }
55
56     (krate, features)
57 }
58
59 macro_rules! configure {
60     ($this:ident, $node:ident) => {
61         match $this.configure($node) {
62             Some(node) => node,
63             None => return Default::default(),
64         }
65     }
66 }
67
68 impl<'a> StripUnconfigured<'a> {
69     pub fn configure<T: HasAttrs>(&mut self, mut node: T) -> Option<T> {
70         self.process_cfg_attrs(&mut node);
71         if self.in_cfg(node.attrs()) { Some(node) } else { None }
72     }
73
74     /// Parse and expand all `cfg_attr` attributes into a list of attributes
75     /// that are within each `cfg_attr` that has a true configuration predicate.
76     ///
77     /// Gives compiler warnigns if any `cfg_attr` does not contain any
78     /// attributes and is in the original source code. Gives compiler errors if
79     /// the syntax of any `cfg_attr` is incorrect.
80     pub fn process_cfg_attrs<T: HasAttrs>(&mut self, node: &mut T) {
81         node.visit_attrs(|attrs| {
82             attrs.flat_map_in_place(|attr| self.process_cfg_attr(attr));
83         });
84     }
85
86     /// Parse and expand a single `cfg_attr` attribute into a list of attributes
87     /// when the configuration predicate is true, or otherwise expand into an
88     /// empty list of attributes.
89     ///
90     /// Gives a compiler warning when the `cfg_attr` contains no attributes and
91     /// is in the original source file. Gives a compiler error if the syntax of
92     /// the attribute is incorrect.
93     fn process_cfg_attr(&mut self, attr: ast::Attribute) -> Vec<ast::Attribute> {
94         if attr.path != sym::cfg_attr {
95             return vec![attr];
96         }
97         if attr.tokens.is_empty() {
98             self.sess.span_diagnostic
99                 .struct_span_err(
100                     attr.span,
101                     "malformed `cfg_attr` attribute input",
102                 ).span_suggestion(
103                     attr.span,
104                     "missing condition and attribute",
105                     "#[cfg_attr(condition, attribute, other_attribute, ...)]".to_owned(),
106                     Applicability::HasPlaceholders,
107                 ).note("for more information, visit \
108                        <https://doc.rust-lang.org/reference/conditional-compilation.html\
109                        #the-cfg_attr-attribute>")
110                 .emit();
111             return vec![];
112         }
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.token.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![];
137             }
138         };
139
140         // Lint on zero attributes in source.
141         if expanded_attrs.is_empty() {
142             return vec![attr];
143         }
144
145         // At this point we know the attribute is considered used.
146         attr::mark_used(&attr);
147
148         if attr::cfg_matches(&cfg_predicate, self.sess, self.features) {
149             // We call `process_cfg_attr` recursively in case there's a
150             // `cfg_attr` inside of another `cfg_attr`. E.g.
151             //  `#[cfg_attr(false, cfg_attr(true, some_attr))]`.
152             expanded_attrs.into_iter()
153             .flat_map(|(path, tokens, span)| self.process_cfg_attr(ast::Attribute {
154                 id: attr::mk_attr_id(),
155                 style: attr.style,
156                 path,
157                 tokens,
158                 is_sugared_doc: false,
159                 span,
160             }))
161             .collect()
162         } else {
163             vec![]
164         }
165     }
166
167     /// Determines if a node with the given attributes should be included in this configuration.
168     pub fn in_cfg(&mut self, attrs: &[ast::Attribute]) -> bool {
169         attrs.iter().all(|attr| {
170             if !is_cfg(attr) {
171                 return true;
172             }
173
174             let error = |span, msg, suggestion: &str| {
175                 let mut err = self.sess.span_diagnostic.struct_span_err(span, msg);
176                 if !suggestion.is_empty() {
177                     err.span_suggestion(
178                         span,
179                         "expected syntax is",
180                         suggestion.into(),
181                         Applicability::MaybeIncorrect,
182                     );
183                 }
184                 err.emit();
185                 true
186             };
187
188             let meta_item = match attr.parse_meta(self.sess) {
189                 Ok(meta_item) => meta_item,
190                 Err(mut err) => { err.emit(); return true; }
191             };
192             let nested_meta_items = if let Some(nested_meta_items) = meta_item.meta_item_list() {
193                 nested_meta_items
194             } else {
195                 return error(meta_item.span, "`cfg` is not followed by parentheses",
196                                              "cfg(/* predicate */)");
197             };
198
199             if nested_meta_items.is_empty() {
200                 return error(meta_item.span, "`cfg` predicate is not specified", "");
201             } else if nested_meta_items.len() > 1 {
202                 return error(nested_meta_items.last().unwrap().span(),
203                              "multiple `cfg` predicates are specified", "");
204             }
205
206             match nested_meta_items[0].meta_item() {
207                 Some(meta_item) => attr::cfg_matches(meta_item, self.sess, self.features),
208                 None => error(nested_meta_items[0].span(),
209                               "`cfg` predicate key cannot be a literal", ""),
210             }
211         })
212     }
213
214     /// Visit attributes on expression and statements (but not attributes on items in blocks).
215     fn visit_expr_attrs(&mut self, attrs: &[ast::Attribute]) {
216         // flag the offending attributes
217         for attr in attrs.iter() {
218             self.maybe_emit_expr_attr_err(attr);
219         }
220     }
221
222     /// If attributes are not allowed on expressions, emit an error for `attr`
223     pub fn maybe_emit_expr_attr_err(&self, attr: &ast::Attribute) {
224         if !self.features.map(|features| features.stmt_expr_attributes).unwrap_or(true) {
225             let mut err = feature_err(self.sess,
226                                       sym::stmt_expr_attributes,
227                                       attr.span,
228                                       GateIssue::Language,
229                                       EXPLAIN_STMT_ATTR_SYNTAX);
230
231             if attr.is_sugared_doc {
232                 err.help("`///` is for documentation comments. For a plain comment, use `//`.");
233             }
234
235             err.emit();
236         }
237     }
238
239     pub fn configure_foreign_mod(&mut self, foreign_mod: &mut ast::ForeignMod) {
240         let ast::ForeignMod { abi: _, items } = foreign_mod;
241         items.flat_map_in_place(|item| self.configure(item));
242     }
243
244     pub fn configure_generic_params(&mut self, params: &mut Vec<ast::GenericParam>) {
245         params.flat_map_in_place(|param| self.configure(param));
246     }
247
248     fn configure_variant_data(&mut self, vdata: &mut ast::VariantData) {
249         match vdata {
250             ast::VariantData::Struct(fields, ..) | ast::VariantData::Tuple(fields, _) =>
251                 fields.flat_map_in_place(|field| self.configure(field)),
252             ast::VariantData::Unit(_) => {}
253         }
254     }
255
256     pub fn configure_item_kind(&mut self, item: &mut ast::ItemKind) {
257         match item {
258             ast::ItemKind::Struct(def, _generics) |
259             ast::ItemKind::Union(def, _generics) => self.configure_variant_data(def),
260             ast::ItemKind::Enum(ast::EnumDef { variants }, _generics) => {
261                 variants.flat_map_in_place(|variant| self.configure(variant));
262                 for variant in variants {
263                     self.configure_variant_data(&mut variant.data);
264                 }
265             }
266             _ => {}
267         }
268     }
269
270     pub fn configure_expr_kind(&mut self, expr_kind: &mut ast::ExprKind) {
271         match expr_kind {
272             ast::ExprKind::Match(_m, arms) => {
273                 arms.flat_map_in_place(|arm| self.configure(arm));
274             }
275             ast::ExprKind::Struct(_path, fields, _base) => {
276                 fields.flat_map_in_place(|field| self.configure(field));
277             }
278             _ => {}
279         }
280     }
281
282     pub fn configure_expr(&mut self, expr: &mut P<ast::Expr>) {
283         self.visit_expr_attrs(expr.attrs());
284
285         // If an expr is valid to cfg away it will have been removed by the
286         // outer stmt or expression folder before descending in here.
287         // Anything else is always required, and thus has to error out
288         // in case of a cfg attr.
289         //
290         // N.B., this is intentionally not part of the visit_expr() function
291         //     in order for filter_map_expr() to be able to avoid this check
292         if let Some(attr) = expr.attrs().iter().find(|a| is_cfg(a)) {
293             let msg = "removing an expression is not supported in this position";
294             self.sess.span_diagnostic.span_err(attr.span, msg);
295         }
296
297         self.process_cfg_attrs(expr)
298     }
299
300     pub fn configure_pat(&mut self, pat: &mut P<ast::Pat>) {
301         if let ast::PatKind::Struct(_path, fields, _etc) = &mut pat.node {
302             fields.flat_map_in_place(|field| self.configure(field));
303         }
304     }
305
306     pub fn configure_fn_decl(&mut self, fn_decl: &mut ast::FnDecl) {
307         fn_decl.inputs.flat_map_in_place(|arg| self.configure(arg));
308     }
309 }
310
311 impl<'a> MutVisitor for StripUnconfigured<'a> {
312     fn visit_foreign_mod(&mut self, foreign_mod: &mut ast::ForeignMod) {
313         self.configure_foreign_mod(foreign_mod);
314         noop_visit_foreign_mod(foreign_mod, self);
315     }
316
317     fn visit_item_kind(&mut self, item: &mut ast::ItemKind) {
318         self.configure_item_kind(item);
319         noop_visit_item_kind(item, self);
320     }
321
322     fn visit_expr(&mut self, expr: &mut P<ast::Expr>) {
323         self.configure_expr(expr);
324         self.configure_expr_kind(&mut expr.node);
325         noop_visit_expr(expr, self);
326     }
327
328     fn filter_map_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
329         let mut expr = configure!(self, expr);
330         self.configure_expr_kind(&mut expr.node);
331         noop_visit_expr(&mut expr, self);
332         Some(expr)
333     }
334
335     fn flat_map_stmt(&mut self, stmt: ast::Stmt) -> SmallVec<[ast::Stmt; 1]> {
336         noop_flat_map_stmt(configure!(self, stmt), self)
337     }
338
339     fn flat_map_item(&mut self, item: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
340         noop_flat_map_item(configure!(self, item), self)
341     }
342
343     fn flat_map_impl_item(&mut self, item: ast::ImplItem) -> SmallVec<[ast::ImplItem; 1]> {
344         noop_flat_map_impl_item(configure!(self, item), self)
345     }
346
347     fn flat_map_trait_item(&mut self, item: ast::TraitItem) -> SmallVec<[ast::TraitItem; 1]> {
348         noop_flat_map_trait_item(configure!(self, item), self)
349     }
350
351     fn visit_mac(&mut self, _mac: &mut ast::Mac) {
352         // Don't configure interpolated AST (cf. issue #34171).
353         // Interpolated AST will get configured once the surrounding tokens are parsed.
354     }
355
356     fn visit_pat(&mut self, pat: &mut P<ast::Pat>) {
357         self.configure_pat(pat);
358         noop_visit_pat(pat, self)
359     }
360
361     fn visit_fn_decl(&mut self, mut fn_decl: &mut P<ast::FnDecl>) {
362         self.configure_fn_decl(&mut fn_decl);
363         noop_visit_fn_decl(fn_decl, self);
364     }
365 }
366
367 fn is_cfg(attr: &ast::Attribute) -> bool {
368     attr.check_name(sym::cfg)
369 }