Skip to main content

rustc_expand/
config.rs

1//! Conditional compilation stripping.
2
3use std::iter;
4
5use rustc_ast::attr::data_structures::CfgEntry;
6use rustc_ast::token::{Delimiter, Token, TokenKind};
7use rustc_ast::tokenstream::{LazyTokenStream, Spacing, TokenStream, TokenTree, WithTokens};
8use rustc_ast::{self as ast, AttrStyle, Attribute, HasAttrs, HasTokens, NodeId, SyntheticAttr};
9use rustc_attr_ir::target::{AstTarget, Target};
10use rustc_attr_ir::{self as attrs, AttributeKind};
11use rustc_attr_parsing::parser::AllowExprMetavar;
12use rustc_attr_parsing::{
13    self as attr, AttributeParser, AttributeSafety, CFG_TEMPLATE, EvalConfigResult, ShouldEmit,
14    eval_config_entry, parse_cfg,
15};
16use rustc_data_structures::flat_map_in_place::FlatMapInPlace;
17use rustc_errors::msg;
18use rustc_feature::{
19    ACCEPTED_LANG_FEATURES, EnabledLangFeature, EnabledLibFeature, Features, REMOVED_LANG_FEATURES,
20    UNSTABLE_LANG_FEATURES,
21};
22use rustc_lint_defs::builtin::UNUSED_ATTRIBUTES;
23use rustc_parse::parser::Recovery;
24use rustc_session::Session;
25use rustc_session::diagnostics::feature_err;
26use rustc_span::{STDLIB_STABLE_CRATES, Span, Symbol, sym};
27use tracing::instrument;
28
29use crate::diagnostics::{
30    CfgNotSupportedInPosition, CrateNameInCfgAttr, CrateTypeInCfgAttr, FeatureNotAllowed,
31    FeatureRemoved, FeatureRemovedReason,
32};
33
34/// A folder that strips out items that do not belong in the current configuration.
35pub struct StripUnconfigured<'a> {
36    pub sess: &'a Session,
37    pub features: Option<&'a Features>,
38    /// If `true`, perform cfg-stripping on attached tokens.
39    /// This is only used for the input to derive macros,
40    /// which needs eager expansion of `cfg` and `cfg_attr`
41    pub config_tokens: bool,
42    pub lint_node_id: NodeId,
43}
44
45pub fn features(sess: &Session, krate_attrs: &[Attribute], crate_name: Symbol) -> Features {
46    let mut features = Features::default();
47
48    if let Some(attrs::Attribute::Parsed(AttributeKind::Feature(feature_idents, _))) =
49        AttributeParser::parse_limited_sym(sess, krate_attrs, &[sym::feature])
50    {
51        for feature_ident in feature_idents {
52            // If the enabled feature has been removed, issue an error.
53            if let Some(f) =
54                REMOVED_LANG_FEATURES.iter().find(|f| feature_ident.name == f.feature.name)
55            {
56                let pull_note = if let Some(pull) = f.pull {
57                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("; see <https://github.com/rust-lang/rust/pull/{0}> for more information",
                pull))
    })format!(
58                        "; see <https://github.com/rust-lang/rust/pull/{pull}> for more information",
59                    )
60                } else {
61                    "".to_owned()
62                };
63                sess.dcx().emit_err(FeatureRemoved {
64                    span: feature_ident.span,
65                    reason: f.reason.map(|reason| FeatureRemovedReason { reason }),
66                    removed_rustc_version: f.feature.since,
67                    pull_note,
68                });
69                continue;
70            }
71
72            // If the enabled feature is stable, record it.
73            if let Some(f) = ACCEPTED_LANG_FEATURES.iter().find(|f| feature_ident.name == f.name) {
74                features.set_enabled_lang_feature(EnabledLangFeature {
75                    gate_name: feature_ident.name,
76                    attr_sp: feature_ident.span,
77                    stable_since: Some(Symbol::intern(f.since)),
78                });
79                continue;
80            }
81
82            // If `-Z allow-features` is used and the enabled feature is
83            // unstable and not also listed as one of the allowed features,
84            // issue an error.
85            if let Some(allowed) = sess.opts.unstable_opts.allow_features.as_ref() {
86                if allowed.iter().all(|f| feature_ident.name.as_str() != f) {
87                    sess.dcx().emit_err(FeatureNotAllowed {
88                        span: feature_ident.span,
89                        name: feature_ident.name,
90                    });
91                    continue;
92                }
93            }
94
95            // If the enabled feature is unstable, record it.
96            if UNSTABLE_LANG_FEATURES.iter().find(|f| feature_ident.name == f.name).is_some() {
97                features.set_enabled_lang_feature(EnabledLangFeature {
98                    gate_name: feature_ident.name,
99                    attr_sp: feature_ident.span,
100                    stable_since: None,
101                });
102            } else {
103                // Otherwise, the feature is unknown. Enable it as a lib feature.
104                // It will be checked later whether the feature really exists.
105                features.set_enabled_lib_feature(EnabledLibFeature {
106                    gate_name: feature_ident.name,
107                    attr_sp: feature_ident.span,
108                });
109            }
110
111            // When the ICE comes from a standard library crate, there's a chance that the person
112            // hitting the ICE may be using -Zbuild-std or similar with an untested target.
113            // The bug is probably in the standard library and not the compiler in that case,
114            // but that doesn't really matter - we want a bug report.
115            if features.internal(feature_ident.name) && !STDLIB_STABLE_CRATES.contains(&crate_name)
116            {
117                sess.using_internal_features.store(true, std::sync::atomic::Ordering::Relaxed);
118            }
119        }
120    }
121
122    features
123}
124
125pub fn pre_configure_attrs(sess: &Session, attrs: &[Attribute]) -> ast::AttrVec {
126    let strip_unconfigured = StripUnconfigured {
127        sess,
128        features: None,
129        config_tokens: false,
130        lint_node_id: ast::CRATE_NODE_ID,
131    };
132    attrs
133        .iter()
134        .flat_map(|attr| strip_unconfigured.process_cfg_attr(attr))
135        .take_while(|attr| {
136            !is_cfg(attr) || strip_unconfigured.cfg_true(attr, ShouldEmit::Nothing).as_bool()
137        })
138        .collect()
139}
140
141#[macro_export]
142macro_rules! configure {
143    ($this:ident, $node:ident) => {
144        match $this.configure($node) {
145            Some(node) => node,
146            None => return Default::default(),
147        }
148    };
149}
150
151impl<'a> StripUnconfigured<'a> {
152    pub fn configure<T: HasTokens>(&self, mut node: T) -> Option<T> {
153        self.process_cfg_attrs(&mut node);
154        self.in_cfg(node.attrs()).then(|| {
155            self.try_configure_tokens(&mut node);
156            node
157        })
158    }
159
160    fn try_configure_tokens<T: HasTokens>(&self, node: &mut T) {
161        if self.config_tokens {
162            if let Some(Some(tokens)) = node.tokens_mut() {
163                let stream = tokens.to_configured_token_stream(&mut |target| {
164                    // Expand any `cfg_attr` attributes.
165                    target.attrs.flat_map_in_place(|attr| self.process_cfg_attr(&attr));
166                    // This return value means we remove the target if there's a `cfg` attribute and
167                    // the condition isn't satisfied.
168                    self.in_cfg(&target.attrs)
169                });
170                *tokens = LazyTokenStream::new_direct(stream);
171            }
172        }
173    }
174
175    /// Parse and expand all `cfg_attr` attributes into a list of attributes
176    /// that are within each `cfg_attr` that has a true configuration predicate.
177    ///
178    /// Gives compiler warnings if any `cfg_attr` does not contain any
179    /// attributes and is in the original source code. Gives compiler errors if
180    /// the syntax of any `cfg_attr` is incorrect.
181    fn process_cfg_attrs<T: HasAttrs>(&self, node: &mut T) {
182        node.visit_attrs(|attrs| {
183            attrs.flat_map_in_place(|attr| self.process_cfg_attr(&attr));
184        });
185    }
186
187    fn process_cfg_attr(&self, attr: &Attribute) -> Vec<Attribute> {
188        if attr.has_name(sym::cfg_attr) {
189            self.expand_cfg_attr(attr, true)
190        } else {
191            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [attr.clone()]))vec![attr.clone()]
192        }
193    }
194
195    /// Parse and expand a single `cfg_attr` attribute into a list of attributes
196    /// when the configuration predicate is true, or otherwise expand into an
197    /// empty list of attributes.
198    ///
199    /// Gives a compiler warning when the `cfg_attr` contains no attributes and
200    /// is in the original source file. Gives a compiler error if the syntax of
201    /// the attribute is incorrect.
202    pub(crate) fn expand_cfg_attr(&self, cfg_attr: &Attribute, recursive: bool) -> Vec<Attribute> {
203        let Some((cfg_predicate, expanded_attrs)) = rustc_attr_parsing::parse_cfg_attr(
204            cfg_attr,
205            self.sess,
206            self.features,
207            self.lint_node_id,
208        ) else {
209            let trace_attr = cfg_attr.clone().convert_normal_to_synthetic(
210                SyntheticAttr::CfgAttrTrace(CfgEntry::Bool(true, cfg_attr.span)),
211            );
212            return ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [trace_attr]))vec![trace_attr];
213        };
214
215        // Lint on zero attributes in source.
216        if expanded_attrs.is_empty() {
217            self.sess.psess.buffer_lint(
218                UNUSED_ATTRIBUTES,
219                cfg_attr.span,
220                ast::CRATE_NODE_ID,
221                crate::diagnostics::CfgAttrNoAttributes,
222            );
223        }
224
225        let cfg_eval = attr::eval_config_entry(self.sess, &cfg_predicate).as_bool();
226
227        // A synthetic trace attribute left in AST in place of the original `cfg_attr` attribute.
228        // It can later be used by lints or other diagnostics.
229        let trace_attr = cfg_attr
230            .clone()
231            .convert_normal_to_synthetic(SyntheticAttr::CfgAttrTrace(cfg_predicate));
232
233        if !cfg_eval {
234            return ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [trace_attr]))vec![trace_attr];
235        }
236
237        if recursive {
238            // We call `process_cfg_attr` recursively in case there's a
239            // `cfg_attr` inside of another `cfg_attr`. E.g.
240            //  `#[cfg_attr(false, cfg_attr(true, some_attr))]`.
241            let expanded_attrs = expanded_attrs
242                .into_iter()
243                .flat_map(|item| self.process_cfg_attr(&self.expand_cfg_attr_item(cfg_attr, item)));
244            iter::once(trace_attr).chain(expanded_attrs).collect()
245        } else {
246            let expanded_attrs =
247                expanded_attrs.into_iter().map(|item| self.expand_cfg_attr_item(cfg_attr, item));
248            iter::once(trace_attr).chain(expanded_attrs).collect()
249        }
250    }
251
252    fn expand_cfg_attr_item(
253        &self,
254        cfg_attr: &Attribute,
255        (attr_item, attr_item_span): (WithTokens<ast::AttrItem>, Span),
256    ) -> Attribute {
257        // Convert `#[cfg_attr(pred, attr)]` to `#[attr]`.
258
259        // Use the `#` from `#[cfg_attr(pred, attr)]` in the result `#[attr]`.
260        let mut orig_trees = ::alloc::vec::Vec::new()vec![];
261        cfg_attr.append_token_trees_to(&mut orig_trees);
262        let mut orig_trees = orig_trees.into_iter();
263        let Some(TokenTree::Token(pound_token @ Token { kind: TokenKind::Pound, .. }, _)) =
264            orig_trees.next()
265        else {
266            {
    ::core::panicking::panic_fmt(format_args!("Bad tokens for attribute {0:?}",
            cfg_attr));
};panic!("Bad tokens for attribute {cfg_attr:?}");
267        };
268
269        // For inner attributes, we do the same thing for the `!` in `#![attr]`.
270        let mut trees = if cfg_attr.style == AttrStyle::Inner {
271            let Some(TokenTree::Token(bang_token @ Token { kind: TokenKind::Bang, .. }, _)) =
272                orig_trees.next()
273            else {
274                {
    ::core::panicking::panic_fmt(format_args!("Bad tokens for attribute {0:?}",
            cfg_attr));
};panic!("Bad tokens for attribute {cfg_attr:?}");
275            };
276            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [TokenTree::Token(pound_token, Spacing::Joint),
                TokenTree::Token(bang_token, Spacing::JointHidden)]))vec![
277                TokenTree::Token(pound_token, Spacing::Joint),
278                TokenTree::Token(bang_token, Spacing::JointHidden),
279            ]
280        } else {
281            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [TokenTree::Token(pound_token, Spacing::JointHidden)]))vec![TokenTree::Token(pound_token, Spacing::JointHidden)]
282        };
283
284        // And the same thing for the `[`/`]` delimiters in `#[attr]`.
285        let Some(TokenTree::Delimited(delim_span, delim_spacing, Delimiter::Bracket, _)) =
286            orig_trees.next()
287        else {
288            {
    ::core::panicking::panic_fmt(format_args!("Bad tokens for attribute {0:?}",
            cfg_attr));
};panic!("Bad tokens for attribute {cfg_attr:?}");
289        };
290        trees.push(TokenTree::Delimited(
291            delim_span,
292            delim_spacing,
293            Delimiter::Bracket,
294            attr_item
295                .tokens
296                .as_ref()
297                .unwrap_or_else(|| {
    ::core::panicking::panic_fmt(format_args!("Missing tokens for {0:?}",
            attr_item.node));
}panic!("Missing tokens for {:?}", attr_item.node))
298                .to_token_stream(),
299        ));
300
301        let attr_item_path_span = attr_item.node.path.span;
302        let attr_tokens = Some(LazyTokenStream::new_direct(TokenStream::new(trees)));
303        let attr = ast::attr::mk_attr_from_item(
304            &self.sess.psess.attr_id_generator,
305            attr_item.node,
306            attr_tokens,
307            cfg_attr.style,
308            attr_item_span,
309        );
310        if attr.has_name(sym::crate_type) {
311            self.sess.dcx().emit_err(CrateTypeInCfgAttr { span: attr_item_path_span });
312        }
313        if attr.has_name(sym::crate_name) {
314            self.sess.dcx().emit_err(CrateNameInCfgAttr { span: attr_item_path_span });
315        }
316        attr
317    }
318
319    /// Determines if a node with the given attributes should be included in this configuration.
320    fn in_cfg(&self, attrs: &[Attribute]) -> bool {
321        attrs.iter().all(|attr| {
322            !is_cfg(attr)
323                || self
324                    .cfg_true(attr, ShouldEmit::ErrorsAndLints { recovery: Recovery::Allowed })
325                    .as_bool()
326        })
327    }
328
329    pub(crate) fn cfg_true(&self, attr: &Attribute, emit_errors: ShouldEmit) -> EvalConfigResult {
330        let Some(cfg) = AttributeParser::parse_single(
331            self.sess,
332            attr,
333            attr.span,
334            self.lint_node_id,
335            // Doesn't matter what the target actually is here.
336            AstTarget::None(Target::Crate),
337            self.features,
338            emit_errors,
339            parse_cfg,
340            &CFG_TEMPLATE,
341            AllowExprMetavar::Yes,
342            AttributeSafety::Normal,
343        ) else {
344            // Cfg attribute was not parsable, give up
345            return EvalConfigResult::True;
346        };
347
348        eval_config_entry(self.sess, &cfg)
349    }
350
351    /// If attributes are not allowed on expressions, emit an error for `attr`
352    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("maybe_emit_expr_attr_err",
                                    "rustc_expand::config", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/bbcdfd90a3f81ca2a5f6d69b943a6ff0d8582102/compiler/rustc_expand/src/config.rs"),
                                    ::tracing_core::__macro_support::Option::Some(352u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_expand::config"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("attr")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("attr");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&attr)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if self.features.is_some_and(|features|
                            !features.stmt_expr_attributes()) &&
                    !attr.span.allows_unstable(sym::stmt_expr_attributes) {
                let mut err =
                    feature_err(self.sess, sym::stmt_expr_attributes, attr.span,
                        rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("attributes on expressions are experimental")));
                if attr.is_doc_comment() {
                    err.help(if attr.style == AttrStyle::Outer {
                            rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`///` is used for outer documentation comments; for a plain comment, use `//`"))
                        } else {
                            rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`//!` is used for inner documentation comments; for a plain comment, use `//` by removing the `!` or inserting a space in between them: `// !`"))
                        });
                }
                err.emit();
            }
        }
    }
}#[instrument(level = "trace", skip(self))]
353    pub(crate) fn maybe_emit_expr_attr_err(&self, attr: &Attribute) {
354        if self.features.is_some_and(|features| !features.stmt_expr_attributes())
355            && !attr.span.allows_unstable(sym::stmt_expr_attributes)
356        {
357            let mut err = feature_err(
358                self.sess,
359                sym::stmt_expr_attributes,
360                attr.span,
361                msg!("attributes on expressions are experimental"),
362            );
363
364            if attr.is_doc_comment() {
365                err.help(if attr.style == AttrStyle::Outer {
366                    msg!("`///` is used for outer documentation comments; for a plain comment, use `//`")
367                } else {
368                    msg!("`//!` is used for inner documentation comments; for a plain comment, use `//` by removing the `!` or inserting a space in between them: `// !`")
369                });
370            }
371
372            err.emit();
373        }
374    }
375
376    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("configure_expr",
                                    "rustc_expand::config", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/bbcdfd90a3f81ca2a5f6d69b943a6ff0d8582102/compiler/rustc_expand/src/config.rs"),
                                    ::tracing_core::__macro_support::Option::Some(376u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_expand::config"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("expr")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("expr");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("method_receiver")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("method_receiver");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expr)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&method_receiver
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if !method_receiver {
                for attr in expr.attrs.iter() {
                    self.maybe_emit_expr_attr_err(attr);
                }
            }
            if let Some(attr) = expr.attrs().iter().find(|a| is_cfg(a)) {
                self.sess.dcx().emit_err(CfgNotSupportedInPosition {
                        span: attr.span,
                    });
            }
            self.process_cfg_attrs(expr);
            self.try_configure_tokens(&mut *expr);
        }
    }
}#[instrument(level = "trace", skip(self))]
377    pub fn configure_expr(&self, expr: &mut ast::Expr, method_receiver: bool) {
378        if !method_receiver {
379            for attr in expr.attrs.iter() {
380                self.maybe_emit_expr_attr_err(attr);
381            }
382        }
383
384        // If an expr is valid to cfg away it will have been removed by the
385        // outer stmt or expression folder before descending in here.
386        // Anything else is always required, and thus has to error out
387        // in case of a cfg attr.
388        //
389        // N.B., this is intentionally not part of the visit_expr() function
390        //     in order for filter_map_expr() to be able to avoid this check
391        if let Some(attr) = expr.attrs().iter().find(|a| is_cfg(a)) {
392            self.sess.dcx().emit_err(CfgNotSupportedInPosition { span: attr.span });
393        }
394
395        self.process_cfg_attrs(expr);
396        self.try_configure_tokens(&mut *expr);
397    }
398}
399
400fn is_cfg(attr: &Attribute) -> bool {
401    attr.has_name(sym::cfg)
402}