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