1 //! Process the potential `cfg` attributes on a module.
2 //! Also determine if the module should be included in this configuration.
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.
7 //! A principled solution to this wrong location would be to implement [#64197].
9 //! [#64197]: https://github.com/rust-lang/rust/issues/64197
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};
16 ACCEPTED_FEATURES, ACTIVE_FEATURES, REMOVED_FEATURES, STABLE_REMOVED_FEATURES,
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};
23 use syntax::attr::HasAttrs;
24 use syntax::mut_visit::*;
26 use syntax::sess::{feature_err, ParseSess};
27 use syntax::util::map_in_place::MapInPlace;
29 use smallvec::SmallVec;
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>,
38 span_handler: &Handler,
39 krate_attrs: &[ast::Attribute],
40 crate_edition: Edition,
41 allow_features: &Option<Vec<String>>,
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 {
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
62 let mut features = Features::default();
63 let mut edition_enabled_features = FxHashMap::default();
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);
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);
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) {
85 let list = match attr.meta_item_list() {
95 let name = mi.name_or_empty();
97 let edition = ALL_EDITIONS.iter().find(|e| name == e.feature_name()).copied();
98 if let Some(edition) = edition {
99 if edition <= crate_edition {
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);
113 for attr in krate_attrs {
114 if !attr.check_name(sym::feature) {
118 let list = match attr.meta_item_list() {
123 let bad_input = |span| {
124 struct_span_err!(span_handler, span, E0556, "malformed `feature` attribute input")
128 let name = match mi.ident() {
129 Some(ident) if mi.is_word() => ident.name,
134 "expected just one word",
135 format!("{}", ident.name),
136 Applicability::MaybeIncorrect,
142 bad_input(mi.span()).span_label(mi.span(), "expected just one word").emit();
147 if let Some(edition) = edition_enabled_features.get(&name) {
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();
154 if ALL_EDITIONS.iter().any(|e| name == e.feature_name()) {
155 // Handled in the separate loop above.
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 } =
165 feature_removed(span_handler, mi.span(), *reason);
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));
176 if let Some(allowed) = allow_features.as_ref() {
177 if allowed.iter().find(|&f| name.as_str() == *f).is_none() {
182 "the feature `{}` is not in the list of allowed features",
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));
196 features.declared_lib_features.push((name, mi.span()));
203 // `cfg_attr`-process the crate's attributes and compute the crate's features.
205 mut krate: ast::Crate,
208 allow_features: &Option<Vec<String>>,
209 ) -> (ast::Crate, Features) {
212 let mut strip_unconfigured = StripUnconfigured { sess, features: None };
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) {
219 // the entire crate is unconfigured
220 krate.attrs = Vec::new();
221 krate.module.items = Vec::new();
222 return (krate, Features::default());
225 features = get_features(&sess.span_diagnostic, &krate.attrs, edition, allow_features);
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);
238 macro_rules! configure {
239 ($this:ident, $node:ident) => {
240 match $this.configure($node) {
242 None => return Default::default(),
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>";
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)
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.
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));
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.
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) {
282 let (cfg_predicate, expanded_attrs) = match self.parse_cfg_attr(&attr) {
283 None => return vec![],
287 // Lint on zero attributes in source.
288 if expanded_attrs.is_empty() {
292 // At this point we know the attribute is considered used.
293 attr::mark_used(&attr);
295 if !attr::cfg_matches(&cfg_predicate, self.sess, self.features) {
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))]`.
304 .flat_map(|(item, span)| {
305 let attr = attr::mk_attr_from_item(attr.style, item, span);
306 self.process_cfg_attr(attr)
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),
319 .help(&format!("the valid syntax is `{}`", CFG_ATTR_GRAMMAR_HELP))
320 .note(CFG_ATTR_NOTE_REF)
324 _ => self.error_malformed_cfg_attr_missing(attr.span),
329 fn error_malformed_cfg_attr_missing(&self, span: Span) {
332 .struct_span_err(span, "malformed `cfg_attr` attribute input")
335 "missing condition and attribute",
336 CFG_ATTR_GRAMMAR_HELP.to_string(),
337 Applicability::HasPlaceholders,
339 .note(CFG_ATTR_NOTE_REF)
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| {
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() {
355 "expected syntax is",
357 Applicability::MaybeIncorrect,
364 let meta_item = match validate_attr::parse_meta(self.sess, attr) {
365 Ok(meta_item) => meta_item,
371 let nested_meta_items = if let Some(nested_meta_items) = meta_item.meta_item_list() {
376 "`cfg` is not followed by parentheses",
377 "cfg(/* predicate */)",
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 {
385 nested_meta_items.last().unwrap().span(),
386 "multiple `cfg` predicates are specified",
391 match nested_meta_items[0].meta_item() {
392 Some(meta_item) => attr::cfg_matches(meta_item, self.sess, self.features),
394 nested_meta_items[0].span(),
395 "`cfg` predicate key cannot be a literal",
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);
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(
415 sym::stmt_expr_attributes,
417 "attributes on expressions are experimental",
420 if attr.is_doc_comment() {
421 err.help("`///` is for documentation comments. For a plain comment, use `//`.");
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));
433 pub fn configure_generic_params(&mut self, params: &mut Vec<ast::GenericParam>) {
434 params.flat_map_in_place(|param| self.configure(param));
437 fn configure_variant_data(&mut self, vdata: &mut ast::VariantData) {
439 ast::VariantData::Struct(fields, ..) | ast::VariantData::Tuple(fields, _) => {
440 fields.flat_map_in_place(|field| self.configure(field))
442 ast::VariantData::Unit(_) => {}
446 pub fn configure_item_kind(&mut self, item: &mut ast::ItemKind) {
448 ast::ItemKind::Struct(def, _generics) | ast::ItemKind::Union(def, _generics) => {
449 self.configure_variant_data(def)
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);
461 pub fn configure_expr_kind(&mut self, expr_kind: &mut ast::ExprKind) {
463 ast::ExprKind::Match(_m, arms) => {
464 arms.flat_map_in_place(|arm| self.configure(arm));
466 ast::ExprKind::Struct(_path, fields, _base) => {
467 fields.flat_map_in_place(|field| self.configure(field));
473 pub fn configure_expr(&mut self, expr: &mut P<ast::Expr>) {
474 self.visit_expr_attrs(expr.attrs());
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.
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);
488 self.process_cfg_attrs(expr)
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));
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));
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);
508 fn visit_item_kind(&mut self, item: &mut ast::ItemKind) {
509 self.configure_item_kind(item);
510 noop_visit_item_kind(item, self);
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);
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);
526 fn flat_map_stmt(&mut self, stmt: ast::Stmt) -> SmallVec<[ast::Stmt; 1]> {
527 noop_flat_map_stmt(configure!(self, stmt), self)
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)
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)
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)
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.
547 fn visit_pat(&mut self, pat: &mut P<ast::Pat>) {
548 self.configure_pat(pat);
549 noop_visit_pat(pat, self)
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);
558 fn is_cfg(attr: &Attribute) -> bool {
559 attr.check_name(sym::cfg)
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(
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)