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