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_ast
::ast
::{self, AttrItem, Attribute, MetaItem}
;
13 use rustc_ast
::attr
::HasAttrs
;
14 use rustc_ast
::mut_visit
::*;
15 use rustc_ast
::ptr
::P
;
16 use rustc_ast
::util
::map_in_place
::MapInPlace
;
17 use rustc_attr
as attr
;
18 use rustc_data_structures
::fx
::FxHashMap
;
19 use rustc_errors
::{error_code, struct_span_err, Applicability, Handler}
;
20 use rustc_feature
::{Feature, Features, State as FeatureState}
;
22 ACCEPTED_FEATURES
, ACTIVE_FEATURES
, REMOVED_FEATURES
, STABLE_REMOVED_FEATURES
,
24 use rustc_session
::parse
::{feature_err, ParseSess}
;
25 use rustc_span
::edition
::{Edition, ALL_EDITIONS}
;
26 use rustc_span
::symbol
::{sym, Symbol}
;
27 use rustc_span
::{Span, DUMMY_SP}
;
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
) {
210 let mut strip_unconfigured
= StripUnconfigured { sess, features: None }
;
212 let unconfigured_attrs
= krate
.attrs
.clone();
213 let diag
= &sess
.span_diagnostic
;
214 let err_count
= diag
.err_count();
215 let features
= match strip_unconfigured
.configure(krate
.attrs
) {
217 // The entire crate is unconfigured.
218 krate
.attrs
= Vec
::new();
219 krate
.module
.items
= Vec
::new();
224 let features
= get_features(diag
, &krate
.attrs
, edition
, allow_features
);
225 if err_count
== diag
.err_count() {
226 // Avoid reconfiguring malformed `cfg_attr`s.
227 strip_unconfigured
.features
= Some(&features
);
228 strip_unconfigured
.configure(unconfigured_attrs
);
237 macro_rules
! configure
{
238 ($this
:ident
, $node
:ident
) => {
239 match $this
.configure($node
) {
241 None
=> return Default
::default(),
246 const CFG_ATTR_GRAMMAR_HELP
: &str = "#[cfg_attr(condition, attribute, other_attribute, ...)]";
247 const CFG_ATTR_NOTE_REF
: &str = "for more information, visit \
248 <https://doc.rust-lang.org/reference/conditional-compilation.html\
249 #the-cfg_attr-attribute>";
251 impl<'a
> StripUnconfigured
<'a
> {
252 pub fn configure
<T
: HasAttrs
>(&mut self, mut node
: T
) -> Option
<T
> {
253 self.process_cfg_attrs(&mut node
);
254 self.in_cfg(node
.attrs()).then_some(node
)
257 /// Parse and expand all `cfg_attr` attributes into a list of attributes
258 /// that are within each `cfg_attr` that has a true configuration predicate.
260 /// Gives compiler warnings if any `cfg_attr` does not contain any
261 /// attributes and is in the original source code. Gives compiler errors if
262 /// the syntax of any `cfg_attr` is incorrect.
263 pub fn process_cfg_attrs
<T
: HasAttrs
>(&mut self, node
: &mut T
) {
264 node
.visit_attrs(|attrs
| {
265 attrs
.flat_map_in_place(|attr
| self.process_cfg_attr(attr
));
269 /// Parse and expand a single `cfg_attr` attribute into a list of attributes
270 /// when the configuration predicate is true, or otherwise expand into an
271 /// empty list of attributes.
273 /// Gives a compiler warning when the `cfg_attr` contains no attributes and
274 /// is in the original source file. Gives a compiler error if the syntax of
275 /// the attribute is incorrect.
276 fn process_cfg_attr(&mut self, attr
: Attribute
) -> Vec
<Attribute
> {
277 if !attr
.has_name(sym
::cfg_attr
) {
281 let (cfg_predicate
, expanded_attrs
) = match self.parse_cfg_attr(&attr
) {
282 None
=> return vec
![],
286 // Lint on zero attributes in source.
287 if expanded_attrs
.is_empty() {
291 // At this point we know the attribute is considered used.
292 attr
::mark_used(&attr
);
294 if !attr
::cfg_matches(&cfg_predicate
, self.sess
, self.features
) {
298 // We call `process_cfg_attr` recursively in case there's a
299 // `cfg_attr` inside of another `cfg_attr`. E.g.
300 // `#[cfg_attr(false, cfg_attr(true, some_attr))]`.
303 .flat_map(|(item
, span
)| {
304 let attr
= attr
::mk_attr_from_item(attr
.style
, item
, span
);
305 self.process_cfg_attr(attr
)
310 fn parse_cfg_attr(&self, attr
: &Attribute
) -> Option
<(MetaItem
, Vec
<(AttrItem
, Span
)>)> {
311 match attr
.get_normal_item().args
{
312 ast
::MacArgs
::Delimited(dspan
, delim
, ref tts
) if !tts
.is_empty() => {
313 let msg
= "wrong `cfg_attr` delimiters";
314 validate_attr
::check_meta_bad_delim(self.sess
, dspan
, delim
, msg
);
315 match parse_in(self.sess
, tts
.clone(), "`cfg_attr` input", |p
| p
.parse_cfg_attr()) {
316 Ok(r
) => return Some(r
),
318 e
.help(&format
!("the valid syntax is `{}`", CFG_ATTR_GRAMMAR_HELP
))
319 .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
| {
349 let meta_item
= match validate_attr
::parse_meta(self.sess
, attr
) {
350 Ok(meta_item
) => meta_item
,
356 let error
= |span
, msg
, suggestion
: &str| {
357 let mut err
= self.sess
.span_diagnostic
.struct_span_err(span
, msg
);
358 if !suggestion
.is_empty() {
361 "expected syntax is",
363 Applicability
::MaybeIncorrect
,
369 let span
= meta_item
.span
;
370 match meta_item
.meta_item_list() {
371 None
=> error(span
, "`cfg` is not followed by parentheses", "cfg(/* predicate */)"),
372 Some([]) => error(span
, "`cfg` predicate is not specified", ""),
373 Some([_
, .., l
]) => error(l
.span(), "multiple `cfg` predicates are specified", ""),
374 Some([single
]) => match single
.meta_item() {
375 Some(meta_item
) => attr
::cfg_matches(meta_item
, self.sess
, self.features
),
376 None
=> error(single
.span(), "`cfg` predicate key cannot be a literal", ""),
382 /// Visit attributes on expression and statements (but not attributes on items in blocks).
383 fn visit_expr_attrs(&mut self, attrs
: &[Attribute
]) {
384 // flag the offending attributes
385 for attr
in attrs
.iter() {
386 self.maybe_emit_expr_attr_err(attr
);
390 /// If attributes are not allowed on expressions, emit an error for `attr`
391 pub fn maybe_emit_expr_attr_err(&self, attr
: &Attribute
) {
392 if !self.features
.map(|features
| features
.stmt_expr_attributes
).unwrap_or(true) {
393 let mut err
= feature_err(
395 sym
::stmt_expr_attributes
,
397 "attributes on expressions are experimental",
400 if attr
.is_doc_comment() {
401 err
.help("`///` is for documentation comments. For a plain comment, use `//`.");
408 pub fn configure_foreign_mod(&mut self, foreign_mod
: &mut ast
::ForeignMod
) {
409 let ast
::ForeignMod { abi: _, items }
= foreign_mod
;
410 items
.flat_map_in_place(|item
| self.configure(item
));
413 pub fn configure_generic_params(&mut self, params
: &mut Vec
<ast
::GenericParam
>) {
414 params
.flat_map_in_place(|param
| self.configure(param
));
417 fn configure_variant_data(&mut self, vdata
: &mut ast
::VariantData
) {
419 ast
::VariantData
::Struct(fields
, ..) | ast
::VariantData
::Tuple(fields
, _
) => {
420 fields
.flat_map_in_place(|field
| self.configure(field
))
422 ast
::VariantData
::Unit(_
) => {}
426 pub fn configure_item_kind(&mut self, item
: &mut ast
::ItemKind
) {
428 ast
::ItemKind
::Struct(def
, _generics
) | ast
::ItemKind
::Union(def
, _generics
) => {
429 self.configure_variant_data(def
)
431 ast
::ItemKind
::Enum(ast
::EnumDef { variants }
, _generics
) => {
432 variants
.flat_map_in_place(|variant
| self.configure(variant
));
433 for variant
in variants
{
434 self.configure_variant_data(&mut variant
.data
);
441 pub fn configure_expr_kind(&mut self, expr_kind
: &mut ast
::ExprKind
) {
443 ast
::ExprKind
::Match(_m
, arms
) => {
444 arms
.flat_map_in_place(|arm
| self.configure(arm
));
446 ast
::ExprKind
::Struct(_path
, fields
, _base
) => {
447 fields
.flat_map_in_place(|field
| self.configure(field
));
453 pub fn configure_expr(&mut self, expr
: &mut P
<ast
::Expr
>) {
454 self.visit_expr_attrs(expr
.attrs());
456 // If an expr is valid to cfg away it will have been removed by the
457 // outer stmt or expression folder before descending in here.
458 // Anything else is always required, and thus has to error out
459 // in case of a cfg attr.
461 // N.B., this is intentionally not part of the visit_expr() function
462 // in order for filter_map_expr() to be able to avoid this check
463 if let Some(attr
) = expr
.attrs().iter().find(|a
| is_cfg(a
)) {
464 let msg
= "removing an expression is not supported in this position";
465 self.sess
.span_diagnostic
.span_err(attr
.span
, msg
);
468 self.process_cfg_attrs(expr
)
471 pub fn configure_pat(&mut self, pat
: &mut P
<ast
::Pat
>) {
472 if let ast
::PatKind
::Struct(_path
, fields
, _etc
) = &mut pat
.kind
{
473 fields
.flat_map_in_place(|field
| self.configure(field
));
477 pub fn configure_fn_decl(&mut self, fn_decl
: &mut ast
::FnDecl
) {
478 fn_decl
.inputs
.flat_map_in_place(|arg
| self.configure(arg
));
482 impl<'a
> MutVisitor
for StripUnconfigured
<'a
> {
483 fn visit_foreign_mod(&mut self, foreign_mod
: &mut ast
::ForeignMod
) {
484 self.configure_foreign_mod(foreign_mod
);
485 noop_visit_foreign_mod(foreign_mod
, self);
488 fn visit_item_kind(&mut self, item
: &mut ast
::ItemKind
) {
489 self.configure_item_kind(item
);
490 noop_visit_item_kind(item
, self);
493 fn visit_expr(&mut self, expr
: &mut P
<ast
::Expr
>) {
494 self.configure_expr(expr
);
495 self.configure_expr_kind(&mut expr
.kind
);
496 noop_visit_expr(expr
, self);
499 fn filter_map_expr(&mut self, expr
: P
<ast
::Expr
>) -> Option
<P
<ast
::Expr
>> {
500 let mut expr
= configure
!(self, expr
);
501 self.configure_expr_kind(&mut expr
.kind
);
502 noop_visit_expr(&mut expr
, self);
506 fn flat_map_stmt(&mut self, stmt
: ast
::Stmt
) -> SmallVec
<[ast
::Stmt
; 1]> {
507 noop_flat_map_stmt(configure
!(self, stmt
), self)
510 fn flat_map_item(&mut self, item
: P
<ast
::Item
>) -> SmallVec
<[P
<ast
::Item
>; 1]> {
511 noop_flat_map_item(configure
!(self, item
), self)
514 fn flat_map_impl_item(&mut self, item
: P
<ast
::AssocItem
>) -> SmallVec
<[P
<ast
::AssocItem
>; 1]> {
515 noop_flat_map_assoc_item(configure
!(self, item
), self)
518 fn flat_map_trait_item(&mut self, item
: P
<ast
::AssocItem
>) -> SmallVec
<[P
<ast
::AssocItem
>; 1]> {
519 noop_flat_map_assoc_item(configure
!(self, item
), self)
522 fn visit_mac(&mut self, _mac
: &mut ast
::Mac
) {
523 // Don't configure interpolated AST (cf. issue #34171).
524 // Interpolated AST will get configured once the surrounding tokens are parsed.
527 fn visit_pat(&mut self, pat
: &mut P
<ast
::Pat
>) {
528 self.configure_pat(pat
);
529 noop_visit_pat(pat
, self)
532 fn visit_fn_decl(&mut self, mut fn_decl
: &mut P
<ast
::FnDecl
>) {
533 self.configure_fn_decl(&mut fn_decl
);
534 noop_visit_fn_decl(fn_decl
, self);
538 fn is_cfg(attr
: &Attribute
) -> bool
{
539 attr
.check_name(sym
::cfg
)
542 /// Process the potential `cfg` attributes on a module.
543 /// Also determine if the module should be included in this configuration.
544 pub fn process_configure_mod(sess
: &ParseSess
, cfg_mods
: bool
, attrs
: &mut Vec
<Attribute
>) -> bool
{
545 // Don't perform gated feature checking.
546 let mut strip_unconfigured
= StripUnconfigured { sess, features: None }
;
547 strip_unconfigured
.process_cfg_attrs(attrs
);
548 !cfg_mods
|| strip_unconfigured
.in_cfg(&attrs
)