]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/config.rs
review comments
[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.struct_span_err(attr.span, "bad `cfg_attr` attribute")
99                 .span_label(attr.span, "missing condition and attribute")
100                 .note("`cfg_attr` must be of the form: \
101                        `#[cfg_attr(condition, attribute, other_attribute, ...)]`")
102                 .note("for more information, visit \
103                        <https://doc.rust-lang.org/reference/conditional-compilation.html\
104                        #the-cfg_attr-attribute>")
105                 .emit();
106             return vec![];
107         }
108
109         let (cfg_predicate, expanded_attrs) = match attr.parse(self.sess, |parser| {
110             parser.expect(&token::OpenDelim(token::Paren))?;
111
112             let cfg_predicate = parser.parse_meta_item()?;
113             parser.expect(&token::Comma)?;
114
115             // Presumably, the majority of the time there will only be one attr.
116             let mut expanded_attrs = Vec::with_capacity(1);
117
118             while !parser.check(&token::CloseDelim(token::Paren)) {
119                 let lo = parser.span.lo();
120                 let (path, tokens) = parser.parse_meta_item_unrestricted()?;
121                 expanded_attrs.push((path, tokens, parser.prev_span.with_lo(lo)));
122                 parser.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Paren)])?;
123             }
124
125             parser.expect(&token::CloseDelim(token::Paren))?;
126             Ok((cfg_predicate, expanded_attrs))
127         }) {
128             Ok(result) => result,
129             Err(mut e) => {
130                 e.emit();
131                 return vec![];
132             }
133         };
134
135         // Check feature gate and lint on zero attributes in source. Even if the feature is gated,
136         // we still compute as if it wasn't, since the emitted error will stop compilation further
137         // along the compilation.
138         if expanded_attrs.len() == 0 {
139             // FIXME: Emit unused attribute lint here.
140         }
141
142         if attr::cfg_matches(&cfg_predicate, self.sess, self.features) {
143             // We call `process_cfg_attr` recursively in case there's a
144             // `cfg_attr` inside of another `cfg_attr`. E.g.
145             //  `#[cfg_attr(false, cfg_attr(true, some_attr))]`.
146             expanded_attrs.into_iter()
147             .flat_map(|(path, tokens, span)| self.process_cfg_attr(ast::Attribute {
148                 id: attr::mk_attr_id(),
149                 style: attr.style,
150                 path,
151                 tokens,
152                 is_sugared_doc: false,
153                 span,
154             }))
155             .collect()
156         } else {
157             Vec::new()
158         }
159     }
160
161     /// Determines if a node with the given attributes should be included in this configuration.
162     pub fn in_cfg(&mut self, attrs: &[ast::Attribute]) -> bool {
163         attrs.iter().all(|attr| {
164             if !is_cfg(attr) {
165                 return true;
166             }
167
168             let error = |span, msg, suggestion: &str| {
169                 let mut err = self.sess.span_diagnostic.struct_span_err(span, msg);
170                 if !suggestion.is_empty() {
171                     err.span_suggestion(
172                         span,
173                         "expected syntax is",
174                         suggestion.into(),
175                         Applicability::MaybeIncorrect,
176                     );
177                 }
178                 err.emit();
179                 true
180             };
181
182             let meta_item = match attr.parse_meta(self.sess) {
183                 Ok(meta_item) => meta_item,
184                 Err(mut err) => { err.emit(); return true; }
185             };
186             let nested_meta_items = if let Some(nested_meta_items) = meta_item.meta_item_list() {
187                 nested_meta_items
188             } else {
189                 return error(meta_item.span, "`cfg` is not followed by parentheses",
190                                              "cfg(/* predicate */)");
191             };
192
193             if nested_meta_items.is_empty() {
194                 return error(meta_item.span, "`cfg` predicate is not specified", "");
195             } else if nested_meta_items.len() > 1 {
196                 return error(nested_meta_items.last().unwrap().span(),
197                              "multiple `cfg` predicates are specified", "");
198             }
199
200             match nested_meta_items[0].meta_item() {
201                 Some(meta_item) => attr::cfg_matches(meta_item, self.sess, self.features),
202                 None => error(nested_meta_items[0].span(),
203                               "`cfg` predicate key cannot be a literal", ""),
204             }
205         })
206     }
207
208     /// Visit attributes on expression and statements (but not attributes on items in blocks).
209     fn visit_expr_attrs(&mut self, attrs: &[ast::Attribute]) {
210         // flag the offending attributes
211         for attr in attrs.iter() {
212             self.maybe_emit_expr_attr_err(attr);
213         }
214     }
215
216     /// If attributes are not allowed on expressions, emit an error for `attr`
217     pub fn maybe_emit_expr_attr_err(&self, attr: &ast::Attribute) {
218         if !self.features.map(|features| features.stmt_expr_attributes).unwrap_or(true) {
219             let mut err = feature_err(self.sess,
220                                       sym::stmt_expr_attributes,
221                                       attr.span,
222                                       GateIssue::Language,
223                                       EXPLAIN_STMT_ATTR_SYNTAX);
224
225             if attr.is_sugared_doc {
226                 err.help("`///` is for documentation comments. For a plain comment, use `//`.");
227             }
228
229             err.emit();
230         }
231     }
232
233     pub fn configure_foreign_mod(&mut self, foreign_mod: &mut ast::ForeignMod) {
234         let ast::ForeignMod { abi: _, items } = foreign_mod;
235         items.flat_map_in_place(|item| self.configure(item));
236     }
237
238     fn configure_variant_data(&mut self, vdata: &mut ast::VariantData) {
239         match vdata {
240             ast::VariantData::Struct(fields, ..) | ast::VariantData::Tuple(fields, _) =>
241                 fields.flat_map_in_place(|field| self.configure(field)),
242             ast::VariantData::Unit(_) => {}
243         }
244     }
245
246     pub fn configure_item_kind(&mut self, item: &mut ast::ItemKind) {
247         match item {
248             ast::ItemKind::Struct(def, _generics) |
249             ast::ItemKind::Union(def, _generics) => self.configure_variant_data(def),
250             ast::ItemKind::Enum(ast::EnumDef { variants }, _generics) => {
251                 variants.flat_map_in_place(|variant| self.configure(variant));
252                 for variant in variants {
253                     self.configure_variant_data(&mut variant.node.data);
254                 }
255             }
256             _ => {}
257         }
258     }
259
260     pub fn configure_expr_kind(&mut self, expr_kind: &mut ast::ExprKind) {
261         match expr_kind {
262             ast::ExprKind::Match(_m, arms) => {
263                 arms.flat_map_in_place(|arm| self.configure(arm));
264             }
265             ast::ExprKind::Struct(_path, fields, _base) => {
266                 fields.flat_map_in_place(|field| self.configure(field));
267             }
268             _ => {}
269         }
270     }
271
272     pub fn configure_expr(&mut self, expr: &mut P<ast::Expr>) {
273         self.visit_expr_attrs(expr.attrs());
274
275         // If an expr is valid to cfg away it will have been removed by the
276         // outer stmt or expression folder before descending in here.
277         // Anything else is always required, and thus has to error out
278         // in case of a cfg attr.
279         //
280         // N.B., this is intentionally not part of the visit_expr() function
281         //     in order for filter_map_expr() to be able to avoid this check
282         if let Some(attr) = expr.attrs().iter().find(|a| is_cfg(a)) {
283             let msg = "removing an expression is not supported in this position";
284             self.sess.span_diagnostic.span_err(attr.span, msg);
285         }
286
287         self.process_cfg_attrs(expr)
288     }
289
290     pub fn configure_pat(&mut self, pat: &mut P<ast::Pat>) {
291         if let ast::PatKind::Struct(_path, fields, _etc) = &mut pat.node {
292             fields.flat_map_in_place(|field| self.configure(field));
293         }
294     }
295
296     /// Denies `#[cfg]` on generic parameters until we decide what to do with it.
297     /// See issue #51279.
298     pub fn disallow_cfg_on_generic_param(&mut self, param: &ast::GenericParam) {
299         for attr in param.attrs() {
300             let offending_attr = if attr.check_name(sym::cfg) {
301                 "cfg"
302             } else if attr.check_name(sym::cfg_attr) {
303                 "cfg_attr"
304             } else {
305                 continue;
306             };
307             let msg = format!("#[{}] cannot be applied on a generic parameter", offending_attr);
308             self.sess.span_diagnostic.span_err(attr.span, &msg);
309         }
310     }
311 }
312
313 impl<'a> MutVisitor for StripUnconfigured<'a> {
314     fn visit_foreign_mod(&mut self, foreign_mod: &mut ast::ForeignMod) {
315         self.configure_foreign_mod(foreign_mod);
316         noop_visit_foreign_mod(foreign_mod, self);
317     }
318
319     fn visit_item_kind(&mut self, item: &mut ast::ItemKind) {
320         self.configure_item_kind(item);
321         noop_visit_item_kind(item, self);
322     }
323
324     fn visit_expr(&mut self, expr: &mut P<ast::Expr>) {
325         self.configure_expr(expr);
326         self.configure_expr_kind(&mut expr.node);
327         noop_visit_expr(expr, self);
328     }
329
330     fn filter_map_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
331         let mut expr = configure!(self, expr);
332         self.configure_expr_kind(&mut expr.node);
333         noop_visit_expr(&mut expr, self);
334         Some(expr)
335     }
336
337     fn flat_map_stmt(&mut self, stmt: ast::Stmt) -> SmallVec<[ast::Stmt; 1]> {
338         noop_flat_map_stmt(configure!(self, stmt), self)
339     }
340
341     fn flat_map_item(&mut self, item: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
342         noop_flat_map_item(configure!(self, item), self)
343     }
344
345     fn flat_map_impl_item(&mut self, item: ast::ImplItem) -> SmallVec<[ast::ImplItem; 1]> {
346         noop_flat_map_impl_item(configure!(self, item), self)
347     }
348
349     fn flat_map_trait_item(&mut self, item: ast::TraitItem) -> SmallVec<[ast::TraitItem; 1]> {
350         noop_flat_map_trait_item(configure!(self, item), self)
351     }
352
353     fn visit_mac(&mut self, _mac: &mut ast::Mac) {
354         // Don't configure interpolated AST (cf. issue #34171).
355         // Interpolated AST will get configured once the surrounding tokens are parsed.
356     }
357
358     fn visit_pat(&mut self, pat: &mut P<ast::Pat>) {
359         self.configure_pat(pat);
360         noop_visit_pat(pat, self)
361     }
362 }
363
364 fn is_cfg(attr: &ast::Attribute) -> bool {
365     attr.check_name(sym::cfg)
366 }