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