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