]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/config.rs
Rollup merge of #61499 - varkor:issue-53457, r=oli-obk
[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.check_name(sym::cfg_attr) {
95             return vec![attr];
96         }
97         if attr.tokens.len() == 0 {
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::new();
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.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         if expanded_attrs.len() == 0 {
144             // FIXME: Emit unused attribute lint here.
145         }
146
147         if attr::cfg_matches(&cfg_predicate, self.sess, self.features) {
148             // We call `process_cfg_attr` recursively in case there's a
149             // `cfg_attr` inside of another `cfg_attr`. E.g.
150             //  `#[cfg_attr(false, cfg_attr(true, some_attr))]`.
151             expanded_attrs.into_iter()
152             .flat_map(|(path, tokens, span)| self.process_cfg_attr(ast::Attribute {
153                 id: attr::mk_attr_id(),
154                 style: attr.style,
155                 path,
156                 tokens,
157                 is_sugared_doc: false,
158                 span,
159             }))
160             .collect()
161         } else {
162             Vec::new()
163         }
164     }
165
166     /// Determines if a node with the given attributes should be included in this configuration.
167     pub fn in_cfg(&mut self, attrs: &[ast::Attribute]) -> bool {
168         attrs.iter().all(|attr| {
169             if !is_cfg(attr) {
170                 return true;
171             }
172
173             let error = |span, msg, suggestion: &str| {
174                 let mut err = self.sess.span_diagnostic.struct_span_err(span, msg);
175                 if !suggestion.is_empty() {
176                     err.span_suggestion(
177                         span,
178                         "expected syntax is",
179                         suggestion.into(),
180                         Applicability::MaybeIncorrect,
181                     );
182                 }
183                 err.emit();
184                 true
185             };
186
187             let meta_item = match attr.parse_meta(self.sess) {
188                 Ok(meta_item) => meta_item,
189                 Err(mut err) => { err.emit(); return true; }
190             };
191             let nested_meta_items = if let Some(nested_meta_items) = meta_item.meta_item_list() {
192                 nested_meta_items
193             } else {
194                 return error(meta_item.span, "`cfg` is not followed by parentheses",
195                                              "cfg(/* predicate */)");
196             };
197
198             if nested_meta_items.is_empty() {
199                 return error(meta_item.span, "`cfg` predicate is not specified", "");
200             } else if nested_meta_items.len() > 1 {
201                 return error(nested_meta_items.last().unwrap().span(),
202                              "multiple `cfg` predicates are specified", "");
203             }
204
205             match nested_meta_items[0].meta_item() {
206                 Some(meta_item) => attr::cfg_matches(meta_item, self.sess, self.features),
207                 None => error(nested_meta_items[0].span(),
208                               "`cfg` predicate key cannot be a literal", ""),
209             }
210         })
211     }
212
213     /// Visit attributes on expression and statements (but not attributes on items in blocks).
214     fn visit_expr_attrs(&mut self, attrs: &[ast::Attribute]) {
215         // flag the offending attributes
216         for attr in attrs.iter() {
217             self.maybe_emit_expr_attr_err(attr);
218         }
219     }
220
221     /// If attributes are not allowed on expressions, emit an error for `attr`
222     pub fn maybe_emit_expr_attr_err(&self, attr: &ast::Attribute) {
223         if !self.features.map(|features| features.stmt_expr_attributes).unwrap_or(true) {
224             let mut err = feature_err(self.sess,
225                                       sym::stmt_expr_attributes,
226                                       attr.span,
227                                       GateIssue::Language,
228                                       EXPLAIN_STMT_ATTR_SYNTAX);
229
230             if attr.is_sugared_doc {
231                 err.help("`///` is for documentation comments. For a plain comment, use `//`.");
232             }
233
234             err.emit();
235         }
236     }
237
238     pub fn configure_foreign_mod(&mut self, foreign_mod: &mut ast::ForeignMod) {
239         let ast::ForeignMod { abi: _, items } = foreign_mod;
240         items.flat_map_in_place(|item| self.configure(item));
241     }
242
243     fn configure_variant_data(&mut self, vdata: &mut ast::VariantData) {
244         match vdata {
245             ast::VariantData::Struct(fields, ..) | ast::VariantData::Tuple(fields, _) =>
246                 fields.flat_map_in_place(|field| self.configure(field)),
247             ast::VariantData::Unit(_) => {}
248         }
249     }
250
251     pub fn configure_item_kind(&mut self, item: &mut ast::ItemKind) {
252         match item {
253             ast::ItemKind::Struct(def, _generics) |
254             ast::ItemKind::Union(def, _generics) => self.configure_variant_data(def),
255             ast::ItemKind::Enum(ast::EnumDef { variants }, _generics) => {
256                 variants.flat_map_in_place(|variant| self.configure(variant));
257                 for variant in variants {
258                     self.configure_variant_data(&mut variant.node.data);
259                 }
260             }
261             _ => {}
262         }
263     }
264
265     pub fn configure_expr_kind(&mut self, expr_kind: &mut ast::ExprKind) {
266         match expr_kind {
267             ast::ExprKind::Match(_m, arms) => {
268                 arms.flat_map_in_place(|arm| self.configure(arm));
269             }
270             ast::ExprKind::Struct(_path, fields, _base) => {
271                 fields.flat_map_in_place(|field| self.configure(field));
272             }
273             _ => {}
274         }
275     }
276
277     pub fn configure_expr(&mut self, expr: &mut P<ast::Expr>) {
278         self.visit_expr_attrs(expr.attrs());
279
280         // If an expr is valid to cfg away it will have been removed by the
281         // outer stmt or expression folder before descending in here.
282         // Anything else is always required, and thus has to error out
283         // in case of a cfg attr.
284         //
285         // N.B., this is intentionally not part of the visit_expr() function
286         //     in order for filter_map_expr() to be able to avoid this check
287         if let Some(attr) = expr.attrs().iter().find(|a| is_cfg(a)) {
288             let msg = "removing an expression is not supported in this position";
289             self.sess.span_diagnostic.span_err(attr.span, msg);
290         }
291
292         self.process_cfg_attrs(expr)
293     }
294
295     pub fn configure_pat(&mut self, pat: &mut P<ast::Pat>) {
296         if let ast::PatKind::Struct(_path, fields, _etc) = &mut pat.node {
297             fields.flat_map_in_place(|field| self.configure(field));
298         }
299     }
300
301     /// Denies `#[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(sym::cfg) {
306                 "cfg"
307             } else if attr.check_name(sym::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> MutVisitor for StripUnconfigured<'a> {
319     fn visit_foreign_mod(&mut self, foreign_mod: &mut ast::ForeignMod) {
320         self.configure_foreign_mod(foreign_mod);
321         noop_visit_foreign_mod(foreign_mod, self);
322     }
323
324     fn visit_item_kind(&mut self, item: &mut ast::ItemKind) {
325         self.configure_item_kind(item);
326         noop_visit_item_kind(item, self);
327     }
328
329     fn visit_expr(&mut self, expr: &mut P<ast::Expr>) {
330         self.configure_expr(expr);
331         self.configure_expr_kind(&mut expr.node);
332         noop_visit_expr(expr, self);
333     }
334
335     fn filter_map_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
336         let mut expr = configure!(self, expr);
337         self.configure_expr_kind(&mut expr.node);
338         noop_visit_expr(&mut expr, self);
339         Some(expr)
340     }
341
342     fn flat_map_stmt(&mut self, stmt: ast::Stmt) -> SmallVec<[ast::Stmt; 1]> {
343         noop_flat_map_stmt(configure!(self, stmt), self)
344     }
345
346     fn flat_map_item(&mut self, item: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
347         noop_flat_map_item(configure!(self, item), self)
348     }
349
350     fn flat_map_impl_item(&mut self, item: ast::ImplItem) -> SmallVec<[ast::ImplItem; 1]> {
351         noop_flat_map_impl_item(configure!(self, item), self)
352     }
353
354     fn flat_map_trait_item(&mut self, item: ast::TraitItem) -> SmallVec<[ast::TraitItem; 1]> {
355         noop_flat_map_trait_item(configure!(self, item), self)
356     }
357
358     fn visit_mac(&mut self, _mac: &mut ast::Mac) {
359         // Don't configure interpolated AST (cf. issue #34171).
360         // Interpolated AST will get configured once the surrounding tokens are parsed.
361     }
362
363     fn visit_pat(&mut self, pat: &mut P<ast::Pat>) {
364         self.configure_pat(pat);
365         noop_visit_pat(pat, self)
366     }
367 }
368
369 fn is_cfg(attr: &ast::Attribute) -> bool {
370     attr.check_name(sym::cfg)
371 }