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