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