1 //! Conditional compilation stripping.
3 use rustc_ast
::attr
::HasAttrs
;
4 use rustc_ast
::mut_visit
::*;
6 use rustc_ast
::token
::{DelimToken, Token, TokenKind}
;
7 use rustc_ast
::tokenstream
::{DelimSpan, LazyTokenStreamInner, Spacing, TokenStream, TokenTree}
;
8 use rustc_ast
::{self as ast, AttrItem, Attribute, MetaItem}
;
9 use rustc_attr
as attr
;
10 use rustc_data_structures
::fx
::FxHashMap
;
11 use rustc_data_structures
::map_in_place
::MapInPlace
;
12 use rustc_data_structures
::sync
::Lrc
;
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_parse
::{parse_in, validate_attr}
;
19 use rustc_session
::parse
::feature_err
;
20 use rustc_session
::Session
;
21 use rustc_span
::edition
::{Edition, ALL_EDITIONS}
;
22 use rustc_span
::symbol
::{sym, Symbol}
;
23 use rustc_span
::{Span, DUMMY_SP}
;
25 use smallvec
::SmallVec
;
27 /// A folder that strips out items that do not belong in the current configuration.
28 pub struct StripUnconfigured
<'a
> {
29 pub sess
: &'a Session
,
30 pub features
: Option
<&'a Features
>,
35 span_handler
: &Handler
,
36 krate_attrs
: &[ast
::Attribute
],
38 fn feature_removed(span_handler
: &Handler
, span
: Span
, reason
: Option
<&str>) {
39 let mut err
= struct_span_err
!(span_handler
, span
, E0557
, "feature has been removed");
40 err
.span_label(span
, "feature has been removed");
41 if let Some(reason
) = reason
{
47 fn active_features_up_to(edition
: Edition
) -> impl Iterator
<Item
= &'
static Feature
> {
48 ACTIVE_FEATURES
.iter().filter(move |feature
| {
49 if let Some(feature_edition
) = feature
.edition
{
50 feature_edition
<= edition
57 let mut features
= Features
::default();
58 let mut edition_enabled_features
= FxHashMap
::default();
59 let crate_edition
= sess
.edition();
61 for &edition
in ALL_EDITIONS
{
62 if edition
<= crate_edition
{
63 // The `crate_edition` implies its respective umbrella feature-gate
64 // (i.e., `#![feature(rust_20XX_preview)]` isn't needed on edition 20XX).
65 edition_enabled_features
.insert(edition
.feature_name(), edition
);
69 for feature
in active_features_up_to(crate_edition
) {
70 feature
.set(&mut features
, DUMMY_SP
);
71 edition_enabled_features
.insert(feature
.name
, crate_edition
);
74 // Process the edition umbrella feature-gates first, to ensure
75 // `edition_enabled_features` is completed before it's queried.
76 for attr
in krate_attrs
{
77 if !sess
.check_name(attr
, sym
::feature
) {
81 let list
= match attr
.meta_item_list() {
91 let name
= mi
.name_or_empty();
93 let edition
= ALL_EDITIONS
.iter().find(|e
| name
== e
.feature_name()).copied();
94 if let Some(edition
) = edition
{
95 if edition
<= crate_edition
{
99 for feature
in active_features_up_to(edition
) {
100 // FIXME(Manishearth) there is currently no way to set
101 // lib features by edition
102 feature
.set(&mut features
, DUMMY_SP
);
103 edition_enabled_features
.insert(feature
.name
, edition
);
109 for attr
in krate_attrs
{
110 if !sess
.check_name(attr
, sym
::feature
) {
114 let list
= match attr
.meta_item_list() {
119 let bad_input
= |span
| {
120 struct_span_err
!(span_handler
, span
, E0556
, "malformed `feature` attribute input")
124 let name
= match mi
.ident() {
125 Some(ident
) if mi
.is_word() => ident
.name
,
130 "expected just one word",
131 format
!("{}", ident
.name
),
132 Applicability
::MaybeIncorrect
,
138 bad_input(mi
.span()).span_label(mi
.span(), "expected just one word").emit();
143 if let Some(edition
) = edition_enabled_features
.get(&name
) {
145 &format
!("the feature `{}` is included in the Rust {} edition", name
, edition
);
146 span_handler
.struct_span_warn_with_code(mi
.span(), msg
, error_code
!(E0705
)).emit();
150 if ALL_EDITIONS
.iter().any(|e
| name
== e
.feature_name()) {
151 // Handled in the separate loop above.
155 let removed
= REMOVED_FEATURES
.iter().find(|f
| name
== f
.name
);
156 let stable_removed
= STABLE_REMOVED_FEATURES
.iter().find(|f
| name
== f
.name
);
157 if let Some(Feature { state, .. }
) = removed
.or(stable_removed
) {
158 if let FeatureState
::Removed { reason }
| FeatureState
::Stabilized { reason }
=
161 feature_removed(span_handler
, mi
.span(), *reason
);
166 if let Some(Feature { since, .. }
) = ACCEPTED_FEATURES
.iter().find(|f
| name
== f
.name
) {
167 let since
= Some(Symbol
::intern(since
));
168 features
.declared_lang_features
.push((name
, mi
.span(), since
));
172 if let Some(allowed
) = sess
.opts
.debugging_opts
.allow_features
.as_ref() {
173 if allowed
.iter().find(|&f
| name
.as_str() == *f
).is_none() {
178 "the feature `{}` is not in the list of allowed features",
186 if let Some(f
) = ACTIVE_FEATURES
.iter().find(|f
| name
== f
.name
) {
187 f
.set(&mut features
, mi
.span());
188 features
.declared_lang_features
.push((name
, mi
.span(), None
));
192 features
.declared_lib_features
.push((name
, mi
.span()));
199 // `cfg_attr`-process the crate's attributes and compute the crate's features.
200 pub fn features(sess
: &Session
, mut krate
: ast
::Crate
) -> (ast
::Crate
, Features
) {
201 let mut strip_unconfigured
= StripUnconfigured { sess, features: None }
;
203 let unconfigured_attrs
= krate
.attrs
.clone();
204 let diag
= &sess
.parse_sess
.span_diagnostic
;
205 let err_count
= diag
.err_count();
206 let features
= match strip_unconfigured
.configure(krate
.attrs
) {
208 // The entire crate is unconfigured.
209 krate
.attrs
= Vec
::new();
210 krate
.module
.items
= Vec
::new();
215 let features
= get_features(sess
, diag
, &krate
.attrs
);
216 if err_count
== diag
.err_count() {
217 // Avoid reconfiguring malformed `cfg_attr`s.
218 strip_unconfigured
.features
= Some(&features
);
219 strip_unconfigured
.configure(unconfigured_attrs
);
228 macro_rules
! configure
{
229 ($this
:ident
, $node
:ident
) => {
230 match $this
.configure($node
) {
232 None
=> return Default
::default(),
237 const CFG_ATTR_GRAMMAR_HELP
: &str = "#[cfg_attr(condition, attribute, other_attribute, ...)]";
238 const CFG_ATTR_NOTE_REF
: &str = "for more information, visit \
239 <https://doc.rust-lang.org/reference/conditional-compilation.html\
240 #the-cfg_attr-attribute>";
242 impl<'a
> StripUnconfigured
<'a
> {
243 pub fn configure
<T
: HasAttrs
>(&mut self, mut node
: T
) -> Option
<T
> {
244 self.process_cfg_attrs(&mut node
);
245 self.in_cfg(node
.attrs()).then_some(node
)
248 /// Parse and expand all `cfg_attr` attributes into a list of attributes
249 /// that are within each `cfg_attr` that has a true configuration predicate.
251 /// Gives compiler warnings if any `cfg_attr` does not contain any
252 /// attributes and is in the original source code. Gives compiler errors if
253 /// the syntax of any `cfg_attr` is incorrect.
254 pub fn process_cfg_attrs
<T
: HasAttrs
>(&mut self, node
: &mut T
) {
255 node
.visit_attrs(|attrs
| {
256 attrs
.flat_map_in_place(|attr
| self.process_cfg_attr(attr
));
260 /// Parse and expand a single `cfg_attr` attribute into a list of attributes
261 /// when the configuration predicate is true, or otherwise expand into an
262 /// empty list of attributes.
264 /// Gives a compiler warning when the `cfg_attr` contains no attributes and
265 /// is in the original source file. Gives a compiler error if the syntax of
266 /// the attribute is incorrect.
267 fn process_cfg_attr(&mut self, attr
: Attribute
) -> Vec
<Attribute
> {
268 if !attr
.has_name(sym
::cfg_attr
) {
272 let (cfg_predicate
, expanded_attrs
) = match self.parse_cfg_attr(&attr
) {
273 None
=> return vec
![],
277 // Lint on zero attributes in source.
278 if expanded_attrs
.is_empty() {
282 // At this point we know the attribute is considered used.
283 self.sess
.mark_attr_used(&attr
);
285 if !attr
::cfg_matches(&cfg_predicate
, &self.sess
.parse_sess
, self.features
) {
289 // We call `process_cfg_attr` recursively in case there's a
290 // `cfg_attr` inside of another `cfg_attr`. E.g.
291 // `#[cfg_attr(false, cfg_attr(true, some_attr))]`.
294 .flat_map(|(item
, span
)| {
296 attr
.tokens
.as_ref().unwrap_or_else(|| panic
!("Missing tokens for {:?}", attr
));
298 // We are taking an attribute of the form `#[cfg_attr(pred, attr)]`
299 // and producing an attribute of the form `#[attr]`. We
300 // have captured tokens for `attr` itself, but we need to
301 // synthesize tokens for the wrapper `#` and `[]`, which
304 // Use the `#` in `#[cfg_attr(pred, attr)]` as the `#` token
305 // for `attr` when we expand it to `#[attr]`
306 let pound_token
= orig_tokens
.into_token_stream().trees().next().unwrap();
307 if !matches
!(pound_token
, TokenTree
::Token(Token { kind: TokenKind::Pound, .. }
)) {
308 panic
!("Bad tokens for attribute {:?}", attr
);
310 // We don't really have a good span to use for the syntheized `[]`
311 // in `#[attr]`, so just use the span of the `#` token.
312 let bracket_group
= TokenTree
::Delimited(
313 DelimSpan
::from_single(pound_token
.span()),
317 .unwrap_or_else(|| panic
!("Missing tokens for {:?}", item
))
318 .into_token_stream(),
321 let mut attr
= attr
::mk_attr_from_item(attr
.style
, item
, span
);
322 attr
.tokens
= Some(Lrc
::new(LazyTokenStreamInner
::Ready(TokenStream
::new(vec
![
323 (pound_token
, Spacing
::Alone
),
324 (bracket_group
, Spacing
::Alone
),
326 self.process_cfg_attr(attr
)
331 fn parse_cfg_attr(&self, attr
: &Attribute
) -> Option
<(MetaItem
, Vec
<(AttrItem
, Span
)>)> {
332 match attr
.get_normal_item().args
{
333 ast
::MacArgs
::Delimited(dspan
, delim
, ref tts
) if !tts
.is_empty() => {
334 let msg
= "wrong `cfg_attr` delimiters";
335 validate_attr
::check_meta_bad_delim(&self.sess
.parse_sess
, dspan
, delim
, msg
);
336 match parse_in(&self.sess
.parse_sess
, tts
.clone(), "`cfg_attr` input", |p
| {
339 Ok(r
) => return Some(r
),
341 e
.help(&format
!("the valid syntax is `{}`", CFG_ATTR_GRAMMAR_HELP
))
342 .note(CFG_ATTR_NOTE_REF
)
347 _
=> self.error_malformed_cfg_attr_missing(attr
.span
),
352 fn error_malformed_cfg_attr_missing(&self, span
: Span
) {
356 .struct_span_err(span
, "malformed `cfg_attr` attribute input")
359 "missing condition and attribute",
360 CFG_ATTR_GRAMMAR_HELP
.to_string(),
361 Applicability
::HasPlaceholders
,
363 .note(CFG_ATTR_NOTE_REF
)
367 /// Determines if a node with the given attributes should be included in this configuration.
368 pub fn in_cfg(&self, attrs
: &[Attribute
]) -> bool
{
369 attrs
.iter().all(|attr
| {
370 if !is_cfg(self.sess
, attr
) {
373 let meta_item
= match validate_attr
::parse_meta(&self.sess
.parse_sess
, attr
) {
374 Ok(meta_item
) => meta_item
,
380 let error
= |span
, msg
, suggestion
: &str| {
381 let mut err
= self.sess
.parse_sess
.span_diagnostic
.struct_span_err(span
, msg
);
382 if !suggestion
.is_empty() {
385 "expected syntax is",
387 Applicability
::MaybeIncorrect
,
393 let span
= meta_item
.span
;
394 match meta_item
.meta_item_list() {
395 None
=> error(span
, "`cfg` is not followed by parentheses", "cfg(/* predicate */)"),
396 Some([]) => error(span
, "`cfg` predicate is not specified", ""),
397 Some([_
, .., l
]) => error(l
.span(), "multiple `cfg` predicates are specified", ""),
398 Some([single
]) => match single
.meta_item() {
400 attr
::cfg_matches(meta_item
, &self.sess
.parse_sess
, self.features
)
402 None
=> error(single
.span(), "`cfg` predicate key cannot be a literal", ""),
408 /// Visit attributes on expression and statements (but not attributes on items in blocks).
409 fn visit_expr_attrs(&mut self, attrs
: &[Attribute
]) {
410 // flag the offending attributes
411 for attr
in attrs
.iter() {
412 self.maybe_emit_expr_attr_err(attr
);
416 /// If attributes are not allowed on expressions, emit an error for `attr`
417 pub fn maybe_emit_expr_attr_err(&self, attr
: &Attribute
) {
418 if !self.features
.map(|features
| features
.stmt_expr_attributes
).unwrap_or(true) {
419 let mut err
= feature_err(
420 &self.sess
.parse_sess
,
421 sym
::stmt_expr_attributes
,
423 "attributes on expressions are experimental",
426 if attr
.is_doc_comment() {
427 err
.help("`///` is for documentation comments. For a plain comment, use `//`.");
434 pub fn configure_foreign_mod(&mut self, foreign_mod
: &mut ast
::ForeignMod
) {
435 let ast
::ForeignMod { unsafety: _, abi: _, items }
= foreign_mod
;
436 items
.flat_map_in_place(|item
| self.configure(item
));
439 fn configure_variant_data(&mut self, vdata
: &mut ast
::VariantData
) {
441 ast
::VariantData
::Struct(fields
, ..) | ast
::VariantData
::Tuple(fields
, _
) => {
442 fields
.flat_map_in_place(|field
| self.configure(field
))
444 ast
::VariantData
::Unit(_
) => {}
448 pub fn configure_item_kind(&mut self, item
: &mut ast
::ItemKind
) {
450 ast
::ItemKind
::Struct(def
, _generics
) | ast
::ItemKind
::Union(def
, _generics
) => {
451 self.configure_variant_data(def
)
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
);
463 pub fn configure_expr_kind(&mut self, expr_kind
: &mut ast
::ExprKind
) {
465 ast
::ExprKind
::Match(_m
, arms
) => {
466 arms
.flat_map_in_place(|arm
| self.configure(arm
));
468 ast
::ExprKind
::Struct(_path
, fields
, _base
) => {
469 fields
.flat_map_in_place(|field
| self.configure(field
));
475 pub fn configure_expr(&mut self, expr
: &mut P
<ast
::Expr
>) {
476 self.visit_expr_attrs(expr
.attrs());
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.
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(self.sess
, a
)) {
486 let msg
= "removing an expression is not supported in this position";
487 self.sess
.parse_sess
.span_diagnostic
.span_err(attr
.span
, msg
);
490 self.process_cfg_attrs(expr
)
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
));
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
));
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);
510 fn visit_item_kind(&mut self, item
: &mut ast
::ItemKind
) {
511 self.configure_item_kind(item
);
512 noop_visit_item_kind(item
, self);
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);
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);
528 fn flat_map_generic_param(
530 param
: ast
::GenericParam
,
531 ) -> SmallVec
<[ast
::GenericParam
; 1]> {
532 noop_flat_map_generic_param(configure
!(self, param
), self)
535 fn flat_map_stmt(&mut self, stmt
: ast
::Stmt
) -> SmallVec
<[ast
::Stmt
; 1]> {
536 noop_flat_map_stmt(configure
!(self, stmt
), self)
539 fn flat_map_item(&mut self, item
: P
<ast
::Item
>) -> SmallVec
<[P
<ast
::Item
>; 1]> {
540 noop_flat_map_item(configure
!(self, item
), self)
543 fn flat_map_impl_item(&mut self, item
: P
<ast
::AssocItem
>) -> SmallVec
<[P
<ast
::AssocItem
>; 1]> {
544 noop_flat_map_assoc_item(configure
!(self, item
), self)
547 fn flat_map_trait_item(&mut self, item
: P
<ast
::AssocItem
>) -> SmallVec
<[P
<ast
::AssocItem
>; 1]> {
548 noop_flat_map_assoc_item(configure
!(self, item
), self)
551 fn visit_mac(&mut self, _mac
: &mut ast
::MacCall
) {
552 // Don't configure interpolated AST (cf. issue #34171).
553 // Interpolated AST will get configured once the surrounding tokens are parsed.
556 fn visit_pat(&mut self, pat
: &mut P
<ast
::Pat
>) {
557 self.configure_pat(pat
);
558 noop_visit_pat(pat
, self)
561 fn visit_fn_decl(&mut self, mut fn_decl
: &mut P
<ast
::FnDecl
>) {
562 self.configure_fn_decl(&mut fn_decl
);
563 noop_visit_fn_decl(fn_decl
, self);
567 fn is_cfg(sess
: &Session
, attr
: &Attribute
) -> bool
{
568 sess
.check_name(attr
, sym
::cfg
)