]> git.lizzy.rs Git - rust.git/blob - src/librustc_parse/config.rs
Rollup merge of #68339 - msizanoen1:patch-1, r=pietroalbini
[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_data_structures::fx::FxHashMap;
13 use rustc_errors::{error_code, struct_span_err, Applicability, Handler};
14 use rustc_feature::{Feature, Features, State as FeatureState};
15 use rustc_feature::{
16     ACCEPTED_FEATURES, ACTIVE_FEATURES, REMOVED_FEATURES, STABLE_REMOVED_FEATURES,
17 };
18 use rustc_span::edition::{Edition, ALL_EDITIONS};
19 use rustc_span::symbol::{sym, Symbol};
20 use rustc_span::{Span, DUMMY_SP};
21 use syntax::ast::{self, AttrItem, Attribute, MetaItem};
22 use syntax::attr;
23 use syntax::attr::HasAttrs;
24 use syntax::mut_visit::*;
25 use syntax::ptr::P;
26 use syntax::sess::{feature_err, ParseSess};
27 use syntax::util::map_in_place::MapInPlace;
28
29 use smallvec::SmallVec;
30
31 /// A folder that strips out items that do not belong in the current configuration.
32 pub struct StripUnconfigured<'a> {
33     pub sess: &'a ParseSess,
34     pub features: Option<&'a Features>,
35 }
36
37 fn get_features(
38     span_handler: &Handler,
39     krate_attrs: &[ast::Attribute],
40     crate_edition: Edition,
41     allow_features: &Option<Vec<String>>,
42 ) -> Features {
43     fn feature_removed(span_handler: &Handler, span: Span, reason: Option<&str>) {
44         let mut err = struct_span_err!(span_handler, span, E0557, "feature has been removed");
45         err.span_label(span, "feature has been removed");
46         if let Some(reason) = reason {
47             err.note(reason);
48         }
49         err.emit();
50     }
51
52     fn active_features_up_to(edition: Edition) -> impl Iterator<Item = &'static Feature> {
53         ACTIVE_FEATURES.iter().filter(move |feature| {
54             if let Some(feature_edition) = feature.edition {
55                 feature_edition <= edition
56             } else {
57                 false
58             }
59         })
60     }
61
62     let mut features = Features::default();
63     let mut edition_enabled_features = FxHashMap::default();
64
65     for &edition in ALL_EDITIONS {
66         if edition <= crate_edition {
67             // The `crate_edition` implies its respective umbrella feature-gate
68             // (i.e., `#![feature(rust_20XX_preview)]` isn't needed on edition 20XX).
69             edition_enabled_features.insert(edition.feature_name(), edition);
70         }
71     }
72
73     for feature in active_features_up_to(crate_edition) {
74         feature.set(&mut features, DUMMY_SP);
75         edition_enabled_features.insert(feature.name, crate_edition);
76     }
77
78     // Process the edition umbrella feature-gates first, to ensure
79     // `edition_enabled_features` is completed before it's queried.
80     for attr in krate_attrs {
81         if !attr.check_name(sym::feature) {
82             continue;
83         }
84
85         let list = match attr.meta_item_list() {
86             Some(list) => list,
87             None => continue,
88         };
89
90         for mi in list {
91             if !mi.is_word() {
92                 continue;
93             }
94
95             let name = mi.name_or_empty();
96
97             let edition = ALL_EDITIONS.iter().find(|e| name == e.feature_name()).copied();
98             if let Some(edition) = edition {
99                 if edition <= crate_edition {
100                     continue;
101                 }
102
103                 for feature in active_features_up_to(edition) {
104                     // FIXME(Manishearth) there is currently no way to set
105                     // lib features by edition
106                     feature.set(&mut features, DUMMY_SP);
107                     edition_enabled_features.insert(feature.name, edition);
108                 }
109             }
110         }
111     }
112
113     for attr in krate_attrs {
114         if !attr.check_name(sym::feature) {
115             continue;
116         }
117
118         let list = match attr.meta_item_list() {
119             Some(list) => list,
120             None => continue,
121         };
122
123         let bad_input = |span| {
124             struct_span_err!(span_handler, span, E0556, "malformed `feature` attribute input")
125         };
126
127         for mi in list {
128             let name = match mi.ident() {
129                 Some(ident) if mi.is_word() => ident.name,
130                 Some(ident) => {
131                     bad_input(mi.span())
132                         .span_suggestion(
133                             mi.span(),
134                             "expected just one word",
135                             format!("{}", ident.name),
136                             Applicability::MaybeIncorrect,
137                         )
138                         .emit();
139                     continue;
140                 }
141                 None => {
142                     bad_input(mi.span()).span_label(mi.span(), "expected just one word").emit();
143                     continue;
144                 }
145             };
146
147             if let Some(edition) = edition_enabled_features.get(&name) {
148                 let msg =
149                     &format!("the feature `{}` is included in the Rust {} edition", name, edition);
150                 span_handler.struct_span_warn_with_code(mi.span(), msg, error_code!(E0705)).emit();
151                 continue;
152             }
153
154             if ALL_EDITIONS.iter().any(|e| name == e.feature_name()) {
155                 // Handled in the separate loop above.
156                 continue;
157             }
158
159             let removed = REMOVED_FEATURES.iter().find(|f| name == f.name);
160             let stable_removed = STABLE_REMOVED_FEATURES.iter().find(|f| name == f.name);
161             if let Some(Feature { state, .. }) = removed.or(stable_removed) {
162                 if let FeatureState::Removed { reason } | FeatureState::Stabilized { reason } =
163                     state
164                 {
165                     feature_removed(span_handler, mi.span(), *reason);
166                     continue;
167                 }
168             }
169
170             if let Some(Feature { since, .. }) = ACCEPTED_FEATURES.iter().find(|f| name == f.name) {
171                 let since = Some(Symbol::intern(since));
172                 features.declared_lang_features.push((name, mi.span(), since));
173                 continue;
174             }
175
176             if let Some(allowed) = allow_features.as_ref() {
177                 if allowed.iter().find(|&f| name.as_str() == *f).is_none() {
178                     struct_span_err!(
179                         span_handler,
180                         mi.span(),
181                         E0725,
182                         "the feature `{}` is not in the list of allowed features",
183                         name
184                     )
185                     .emit();
186                     continue;
187                 }
188             }
189
190             if let Some(f) = ACTIVE_FEATURES.iter().find(|f| name == f.name) {
191                 f.set(&mut features, mi.span());
192                 features.declared_lang_features.push((name, mi.span(), None));
193                 continue;
194             }
195
196             features.declared_lib_features.push((name, mi.span()));
197         }
198     }
199
200     features
201 }
202
203 // `cfg_attr`-process the crate's attributes and compute the crate's features.
204 pub fn features(
205     mut krate: ast::Crate,
206     sess: &ParseSess,
207     edition: Edition,
208     allow_features: &Option<Vec<String>>,
209 ) -> (ast::Crate, Features) {
210     let features;
211     {
212         let mut strip_unconfigured = StripUnconfigured { sess, features: None };
213
214         let unconfigured_attrs = krate.attrs.clone();
215         let err_count = sess.span_diagnostic.err_count();
216         if let Some(attrs) = strip_unconfigured.configure(krate.attrs) {
217             krate.attrs = attrs;
218         } else {
219             // the entire crate is unconfigured
220             krate.attrs = Vec::new();
221             krate.module.items = Vec::new();
222             return (krate, Features::default());
223         }
224
225         features = get_features(&sess.span_diagnostic, &krate.attrs, edition, allow_features);
226
227         // Avoid reconfiguring malformed `cfg_attr`s
228         if err_count == sess.span_diagnostic.err_count() {
229             strip_unconfigured.features = Some(&features);
230             strip_unconfigured.configure(unconfigured_attrs);
231         }
232     }
233
234     (krate, features)
235 }
236
237 #[macro_export]
238 macro_rules! configure {
239     ($this:ident, $node:ident) => {
240         match $this.configure($node) {
241             Some(node) => node,
242             None => return Default::default(),
243         }
244     };
245 }
246
247 const CFG_ATTR_GRAMMAR_HELP: &str = "#[cfg_attr(condition, attribute, other_attribute, ...)]";
248 const CFG_ATTR_NOTE_REF: &str = "for more information, visit \
249     <https://doc.rust-lang.org/reference/conditional-compilation.html\
250     #the-cfg_attr-attribute>";
251
252 impl<'a> StripUnconfigured<'a> {
253     pub fn configure<T: HasAttrs>(&mut self, mut node: T) -> Option<T> {
254         self.process_cfg_attrs(&mut node);
255         self.in_cfg(node.attrs()).then_some(node)
256     }
257
258     /// Parse and expand all `cfg_attr` attributes into a list of attributes
259     /// that are within each `cfg_attr` that has a true configuration predicate.
260     ///
261     /// Gives compiler warnigns if any `cfg_attr` does not contain any
262     /// attributes and is in the original source code. Gives compiler errors if
263     /// the syntax of any `cfg_attr` is incorrect.
264     pub fn process_cfg_attrs<T: HasAttrs>(&mut self, node: &mut T) {
265         node.visit_attrs(|attrs| {
266             attrs.flat_map_in_place(|attr| self.process_cfg_attr(attr));
267         });
268     }
269
270     /// Parse and expand a single `cfg_attr` attribute into a list of attributes
271     /// when the configuration predicate is true, or otherwise expand into an
272     /// empty list of attributes.
273     ///
274     /// Gives a compiler warning when the `cfg_attr` contains no attributes and
275     /// is in the original source file. Gives a compiler error if the syntax of
276     /// the attribute is incorrect.
277     fn process_cfg_attr(&mut self, attr: Attribute) -> Vec<Attribute> {
278         if !attr.has_name(sym::cfg_attr) {
279             return vec![attr];
280         }
281
282         let (cfg_predicate, expanded_attrs) = match self.parse_cfg_attr(&attr) {
283             None => return vec![],
284             Some(r) => r,
285         };
286
287         // Lint on zero attributes in source.
288         if expanded_attrs.is_empty() {
289             return vec![attr];
290         }
291
292         // At this point we know the attribute is considered used.
293         attr::mark_used(&attr);
294
295         if !attr::cfg_matches(&cfg_predicate, self.sess, self.features) {
296             return vec![];
297         }
298
299         // We call `process_cfg_attr` recursively in case there's a
300         // `cfg_attr` inside of another `cfg_attr`. E.g.
301         //  `#[cfg_attr(false, cfg_attr(true, some_attr))]`.
302         expanded_attrs
303             .into_iter()
304             .flat_map(|(item, span)| {
305                 let attr = attr::mk_attr_from_item(attr.style, item, span);
306                 self.process_cfg_attr(attr)
307             })
308             .collect()
309     }
310
311     fn parse_cfg_attr(&self, attr: &Attribute) -> Option<(MetaItem, Vec<(AttrItem, Span)>)> {
312         match attr.get_normal_item().args {
313             ast::MacArgs::Delimited(dspan, delim, ref tts) if !tts.is_empty() => {
314                 let msg = "wrong `cfg_attr` delimiters";
315                 validate_attr::check_meta_bad_delim(self.sess, dspan, delim, msg);
316                 match parse_in(self.sess, tts.clone(), "`cfg_attr` input", |p| p.parse_cfg_attr()) {
317                     Ok(r) => return Some(r),
318                     Err(mut e) => e
319                         .help(&format!("the valid syntax is `{}`", CFG_ATTR_GRAMMAR_HELP))
320                         .note(CFG_ATTR_NOTE_REF)
321                         .emit(),
322                 }
323             }
324             _ => self.error_malformed_cfg_attr_missing(attr.span),
325         }
326         None
327     }
328
329     fn error_malformed_cfg_attr_missing(&self, span: Span) {
330         self.sess
331             .span_diagnostic
332             .struct_span_err(span, "malformed `cfg_attr` attribute input")
333             .span_suggestion(
334                 span,
335                 "missing condition and attribute",
336                 CFG_ATTR_GRAMMAR_HELP.to_string(),
337                 Applicability::HasPlaceholders,
338             )
339             .note(CFG_ATTR_NOTE_REF)
340             .emit();
341     }
342
343     /// Determines if a node with the given attributes should be included in this configuration.
344     pub fn in_cfg(&self, attrs: &[Attribute]) -> bool {
345         attrs.iter().all(|attr| {
346             if !is_cfg(attr) {
347                 return true;
348             }
349
350             let error = |span, msg, suggestion: &str| {
351                 let mut err = self.sess.span_diagnostic.struct_span_err(span, msg);
352                 if !suggestion.is_empty() {
353                     err.span_suggestion(
354                         span,
355                         "expected syntax is",
356                         suggestion.into(),
357                         Applicability::MaybeIncorrect,
358                     );
359                 }
360                 err.emit();
361                 true
362             };
363
364             let meta_item = match validate_attr::parse_meta(self.sess, attr) {
365                 Ok(meta_item) => meta_item,
366                 Err(mut err) => {
367                     err.emit();
368                     return true;
369                 }
370             };
371             let nested_meta_items = if let Some(nested_meta_items) = meta_item.meta_item_list() {
372                 nested_meta_items
373             } else {
374                 return error(
375                     meta_item.span,
376                     "`cfg` is not followed by parentheses",
377                     "cfg(/* predicate */)",
378                 );
379             };
380
381             if nested_meta_items.is_empty() {
382                 return error(meta_item.span, "`cfg` predicate is not specified", "");
383             } else if nested_meta_items.len() > 1 {
384                 return error(
385                     nested_meta_items.last().unwrap().span(),
386                     "multiple `cfg` predicates are specified",
387                     "",
388                 );
389             }
390
391             match nested_meta_items[0].meta_item() {
392                 Some(meta_item) => attr::cfg_matches(meta_item, self.sess, self.features),
393                 None => error(
394                     nested_meta_items[0].span(),
395                     "`cfg` predicate key cannot be a literal",
396                     "",
397                 ),
398             }
399         })
400     }
401
402     /// Visit attributes on expression and statements (but not attributes on items in blocks).
403     fn visit_expr_attrs(&mut self, attrs: &[Attribute]) {
404         // flag the offending attributes
405         for attr in attrs.iter() {
406             self.maybe_emit_expr_attr_err(attr);
407         }
408     }
409
410     /// If attributes are not allowed on expressions, emit an error for `attr`
411     pub fn maybe_emit_expr_attr_err(&self, attr: &Attribute) {
412         if !self.features.map(|features| features.stmt_expr_attributes).unwrap_or(true) {
413             let mut err = feature_err(
414                 self.sess,
415                 sym::stmt_expr_attributes,
416                 attr.span,
417                 "attributes on expressions are experimental",
418             );
419
420             if attr.is_doc_comment() {
421                 err.help("`///` is for documentation comments. For a plain comment, use `//`.");
422             }
423
424             err.emit();
425         }
426     }
427
428     pub fn configure_foreign_mod(&mut self, foreign_mod: &mut ast::ForeignMod) {
429         let ast::ForeignMod { abi: _, items } = foreign_mod;
430         items.flat_map_in_place(|item| self.configure(item));
431     }
432
433     pub fn configure_generic_params(&mut self, params: &mut Vec<ast::GenericParam>) {
434         params.flat_map_in_place(|param| self.configure(param));
435     }
436
437     fn configure_variant_data(&mut self, vdata: &mut ast::VariantData) {
438         match vdata {
439             ast::VariantData::Struct(fields, ..) | ast::VariantData::Tuple(fields, _) => {
440                 fields.flat_map_in_place(|field| self.configure(field))
441             }
442             ast::VariantData::Unit(_) => {}
443         }
444     }
445
446     pub fn configure_item_kind(&mut self, item: &mut ast::ItemKind) {
447         match item {
448             ast::ItemKind::Struct(def, _generics) | ast::ItemKind::Union(def, _generics) => {
449                 self.configure_variant_data(def)
450             }
451             ast::ItemKind::Enum(ast::EnumDef { variants }, _generics) => {
452                 variants.flat_map_in_place(|variant| self.configure(variant));
453                 for variant in variants {
454                     self.configure_variant_data(&mut variant.data);
455                 }
456             }
457             _ => {}
458         }
459     }
460
461     pub fn configure_expr_kind(&mut self, expr_kind: &mut ast::ExprKind) {
462         match expr_kind {
463             ast::ExprKind::Match(_m, arms) => {
464                 arms.flat_map_in_place(|arm| self.configure(arm));
465             }
466             ast::ExprKind::Struct(_path, fields, _base) => {
467                 fields.flat_map_in_place(|field| self.configure(field));
468             }
469             _ => {}
470         }
471     }
472
473     pub fn configure_expr(&mut self, expr: &mut P<ast::Expr>) {
474         self.visit_expr_attrs(expr.attrs());
475
476         // If an expr is valid to cfg away it will have been removed by the
477         // outer stmt or expression folder before descending in here.
478         // Anything else is always required, and thus has to error out
479         // in case of a cfg attr.
480         //
481         // N.B., this is intentionally not part of the visit_expr() function
482         //     in order for filter_map_expr() to be able to avoid this check
483         if let Some(attr) = expr.attrs().iter().find(|a| is_cfg(a)) {
484             let msg = "removing an expression is not supported in this position";
485             self.sess.span_diagnostic.span_err(attr.span, msg);
486         }
487
488         self.process_cfg_attrs(expr)
489     }
490
491     pub fn configure_pat(&mut self, pat: &mut P<ast::Pat>) {
492         if let ast::PatKind::Struct(_path, fields, _etc) = &mut pat.kind {
493             fields.flat_map_in_place(|field| self.configure(field));
494         }
495     }
496
497     pub fn configure_fn_decl(&mut self, fn_decl: &mut ast::FnDecl) {
498         fn_decl.inputs.flat_map_in_place(|arg| self.configure(arg));
499     }
500 }
501
502 impl<'a> MutVisitor for StripUnconfigured<'a> {
503     fn visit_foreign_mod(&mut self, foreign_mod: &mut ast::ForeignMod) {
504         self.configure_foreign_mod(foreign_mod);
505         noop_visit_foreign_mod(foreign_mod, self);
506     }
507
508     fn visit_item_kind(&mut self, item: &mut ast::ItemKind) {
509         self.configure_item_kind(item);
510         noop_visit_item_kind(item, self);
511     }
512
513     fn visit_expr(&mut self, expr: &mut P<ast::Expr>) {
514         self.configure_expr(expr);
515         self.configure_expr_kind(&mut expr.kind);
516         noop_visit_expr(expr, self);
517     }
518
519     fn filter_map_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
520         let mut expr = configure!(self, expr);
521         self.configure_expr_kind(&mut expr.kind);
522         noop_visit_expr(&mut expr, self);
523         Some(expr)
524     }
525
526     fn flat_map_stmt(&mut self, stmt: ast::Stmt) -> SmallVec<[ast::Stmt; 1]> {
527         noop_flat_map_stmt(configure!(self, stmt), self)
528     }
529
530     fn flat_map_item(&mut self, item: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
531         noop_flat_map_item(configure!(self, item), self)
532     }
533
534     fn flat_map_impl_item(&mut self, item: ast::AssocItem) -> SmallVec<[ast::AssocItem; 1]> {
535         noop_flat_map_assoc_item(configure!(self, item), self)
536     }
537
538     fn flat_map_trait_item(&mut self, item: ast::AssocItem) -> SmallVec<[ast::AssocItem; 1]> {
539         noop_flat_map_assoc_item(configure!(self, item), self)
540     }
541
542     fn visit_mac(&mut self, _mac: &mut ast::Mac) {
543         // Don't configure interpolated AST (cf. issue #34171).
544         // Interpolated AST will get configured once the surrounding tokens are parsed.
545     }
546
547     fn visit_pat(&mut self, pat: &mut P<ast::Pat>) {
548         self.configure_pat(pat);
549         noop_visit_pat(pat, self)
550     }
551
552     fn visit_fn_decl(&mut self, mut fn_decl: &mut P<ast::FnDecl>) {
553         self.configure_fn_decl(&mut fn_decl);
554         noop_visit_fn_decl(fn_decl, self);
555     }
556 }
557
558 fn is_cfg(attr: &Attribute) -> bool {
559     attr.check_name(sym::cfg)
560 }
561
562 /// Process the potential `cfg` attributes on a module.
563 /// Also determine if the module should be included in this configuration.
564 pub fn process_configure_mod(
565     sess: &ParseSess,
566     cfg_mods: bool,
567     attrs: &[Attribute],
568 ) -> (bool, Vec<Attribute>) {
569     // Don't perform gated feature checking.
570     let mut strip_unconfigured = StripUnconfigured { sess, features: None };
571     let mut attrs = attrs.to_owned();
572     strip_unconfigured.process_cfg_attrs(&mut attrs);
573     (!cfg_mods || strip_unconfigured.in_cfg(&attrs), attrs)
574 }