]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/config.rs
Auto merge of #56123 - oli-obk:import_miri_from_future, r=eddyb
[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 attr;
10 use ast;
11 use edition::Edition;
12 use errors::Applicability;
13 use mut_visit::*;
14 use parse::{token, ParseSess};
15 use ptr::P;
16 use smallvec::SmallVec;
17 use util::map_in_place::MapInPlace;
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, mut node: T) -> Option<T> {
68         self.process_cfg_attrs(&mut 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: &mut T) {
79         node.visit_attrs(|attrs| {
80             attrs.flat_map_in_place(|attr| self.process_cfg_attr(attr));
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(
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 = match attr.parse_meta(self.sess) {
170                 Ok(meta_item) => meta_item,
171                 Err(mut err) => { err.emit(); return true; }
172             };
173             let nested_meta_items = if let Some(nested_meta_items) = meta_item.meta_item_list() {
174                 nested_meta_items
175             } else {
176                 return error(meta_item.span, "`cfg` is not followed by parentheses",
177                                              "cfg(/* predicate */)");
178             };
179
180             if nested_meta_items.is_empty() {
181                 return error(meta_item.span, "`cfg` predicate is not specified", "");
182             } else if nested_meta_items.len() > 1 {
183                 return error(nested_meta_items.last().unwrap().span,
184                              "multiple `cfg` predicates are specified", "");
185             }
186
187             match nested_meta_items[0].meta_item() {
188                 Some(meta_item) => attr::cfg_matches(meta_item, self.sess, self.features),
189                 None => error(nested_meta_items[0].span,
190                               "`cfg` predicate key cannot be a literal", ""),
191             }
192         })
193     }
194
195     /// Visit attributes on expression and statements (but not attributes on items in blocks).
196     fn visit_expr_attrs(&mut self, attrs: &[ast::Attribute]) {
197         // flag the offending attributes
198         for attr in attrs.iter() {
199             self.maybe_emit_expr_attr_err(attr);
200         }
201     }
202
203     /// If attributes are not allowed on expressions, emit an error for `attr`
204     pub fn maybe_emit_expr_attr_err(&self, attr: &ast::Attribute) {
205         if !self.features.map(|features| features.stmt_expr_attributes).unwrap_or(true) {
206             let mut err = feature_err(self.sess,
207                                       "stmt_expr_attributes",
208                                       attr.span,
209                                       GateIssue::Language,
210                                       EXPLAIN_STMT_ATTR_SYNTAX);
211
212             if attr.is_sugared_doc {
213                 err.help("`///` is for documentation comments. For a plain comment, use `//`.");
214             }
215
216             err.emit();
217         }
218     }
219
220     pub fn configure_foreign_mod(&mut self, foreign_mod: &mut ast::ForeignMod) {
221         let ast::ForeignMod { abi: _, items } = foreign_mod;
222         items.flat_map_in_place(|item| self.configure(item));
223     }
224
225     fn configure_variant_data(&mut self, vdata: &mut ast::VariantData) {
226         match vdata {
227             ast::VariantData::Struct(fields, _id) |
228             ast::VariantData::Tuple(fields, _id) =>
229                 fields.flat_map_in_place(|field| self.configure(field)),
230             ast::VariantData::Unit(_id) => {}
231         }
232     }
233
234     pub fn configure_item_kind(&mut self, item: &mut ast::ItemKind) {
235         match item {
236             ast::ItemKind::Struct(def, _generics) |
237             ast::ItemKind::Union(def, _generics) => self.configure_variant_data(def),
238             ast::ItemKind::Enum(ast::EnumDef { variants }, _generics) => {
239                 variants.flat_map_in_place(|variant| self.configure(variant));
240                 for variant in variants {
241                     self.configure_variant_data(&mut variant.node.data);
242                 }
243             }
244             _ => {}
245         }
246     }
247
248     pub fn configure_expr_kind(&mut self, expr_kind: &mut ast::ExprKind) {
249         match expr_kind {
250             ast::ExprKind::Match(_m, arms) => {
251                 arms.flat_map_in_place(|arm| self.configure(arm));
252             }
253             ast::ExprKind::Struct(_path, fields, _base) => {
254                 fields.flat_map_in_place(|field| self.configure(field));
255             }
256             _ => {}
257         }
258     }
259
260     pub fn configure_expr(&mut self, expr: &mut P<ast::Expr>) {
261         self.visit_expr_attrs(expr.attrs());
262
263         // If an expr is valid to cfg away it will have been removed by the
264         // outer stmt or expression folder before descending in here.
265         // Anything else is always required, and thus has to error out
266         // in case of a cfg attr.
267         //
268         // N.B., this is intentionally not part of the visit_expr() function
269         //     in order for filter_map_expr() to be able to avoid this check
270         if let Some(attr) = expr.attrs().iter().find(|a| is_cfg(a)) {
271             let msg = "removing an expression is not supported in this position";
272             self.sess.span_diagnostic.span_err(attr.span, msg);
273         }
274
275         self.process_cfg_attrs(expr)
276     }
277
278     pub fn configure_pat(&mut self, pat: &mut P<ast::Pat>) {
279         if let ast::PatKind::Struct(_path, fields, _etc) = &mut pat.node {
280             fields.flat_map_in_place(|field| self.configure(field));
281         }
282     }
283
284     // deny #[cfg] on generic parameters until we decide what to do with it.
285     // see issue #51279.
286     pub fn disallow_cfg_on_generic_param(&mut self, param: &ast::GenericParam) {
287         for attr in param.attrs() {
288             let offending_attr = if attr.check_name("cfg") {
289                 "cfg"
290             } else if attr.check_name("cfg_attr") {
291                 "cfg_attr"
292             } else {
293                 continue;
294             };
295             let msg = format!("#[{}] cannot be applied on a generic parameter", offending_attr);
296             self.sess.span_diagnostic.span_err(attr.span, &msg);
297         }
298     }
299 }
300
301 impl<'a> MutVisitor for StripUnconfigured<'a> {
302     fn visit_foreign_mod(&mut self, foreign_mod: &mut ast::ForeignMod) {
303         self.configure_foreign_mod(foreign_mod);
304         noop_visit_foreign_mod(foreign_mod, self);
305     }
306
307     fn visit_item_kind(&mut self, item: &mut ast::ItemKind) {
308         self.configure_item_kind(item);
309         noop_visit_item_kind(item, self);
310     }
311
312     fn visit_expr(&mut self, expr: &mut P<ast::Expr>) {
313         self.configure_expr(expr);
314         self.configure_expr_kind(&mut expr.node);
315         noop_visit_expr(expr, self);
316     }
317
318     fn filter_map_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
319         let mut expr = configure!(self, expr);
320         self.configure_expr_kind(&mut expr.node);
321         noop_visit_expr(&mut expr, self);
322         Some(expr)
323     }
324
325     fn flat_map_stmt(&mut self, stmt: ast::Stmt) -> SmallVec<[ast::Stmt; 1]> {
326         noop_flat_map_stmt(configure!(self, stmt), self)
327     }
328
329     fn flat_map_item(&mut self, item: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
330         noop_flat_map_item(configure!(self, item), self)
331     }
332
333     fn flat_map_impl_item(&mut self, item: ast::ImplItem) -> SmallVec<[ast::ImplItem; 1]> {
334         noop_flat_map_impl_item(configure!(self, item), self)
335     }
336
337     fn flat_map_trait_item(&mut self, item: ast::TraitItem) -> SmallVec<[ast::TraitItem; 1]> {
338         noop_flat_map_trait_item(configure!(self, item), self)
339     }
340
341     fn visit_mac(&mut self, _mac: &mut ast::Mac) {
342         // Don't configure interpolated AST (cf. issue #34171).
343         // Interpolated AST will get configured once the surrounding tokens are parsed.
344     }
345
346     fn visit_pat(&mut self, pat: &mut P<ast::Pat>) {
347         self.configure_pat(pat);
348         noop_visit_pat(pat, self)
349     }
350 }
351
352 fn is_cfg(attr: &ast::Attribute) -> bool {
353     attr.check_name("cfg")
354 }