Skip to main content

rustc_expand/
config.rs

1//! Conditional compilation stripping.
2
3use std::iter;
4
5use rustc_ast::token::{Delimiter, Token, TokenKind};
6use rustc_ast::tokenstream::{
7    AttrTokenStream, AttrTokenTree, LazyAttrTokenStream, Spacing, TokenTree,
8};
9use rustc_ast::{
10    self as ast, AttrItemKind, AttrKind, AttrStyle, Attribute, EarlyParsedAttribute, HasAttrs,
11    HasTokens, MetaItem, MetaItemInner, NodeId, NormalAttr,
12};
13use rustc_attr_parsing as attr;
14use rustc_attr_parsing::{
15    AttributeParser, CFG_TEMPLATE, EvalConfigResult, ShouldEmit, eval_config_entry, parse_cfg,
16};
17use rustc_data_structures::flat_map_in_place::FlatMapInPlace;
18use rustc_errors::msg;
19use rustc_feature::{
20    ACCEPTED_LANG_FEATURES, EnabledLangFeature, EnabledLibFeature, Features, REMOVED_LANG_FEATURES,
21    UNSTABLE_LANG_FEATURES,
22};
23use rustc_hir::Target;
24use rustc_parse::parser::Recovery;
25use rustc_session::Session;
26use rustc_session::parse::feature_err;
27use rustc_span::{STDLIB_STABLE_CRATES, Span, Symbol, sym};
28use thin_vec::ThinVec;
29use tracing::instrument;
30
31use crate::errors::{
32    CrateNameInCfgAttr, CrateTypeInCfgAttr, FeatureNotAllowed, FeatureRemoved,
33    FeatureRemovedReason, InvalidCfg, MalformedFeatureAttribute, MalformedFeatureAttributeHelp,
34    RemoveExprNotSupported,
35};
36
37/// A folder that strips out items that do not belong in the current configuration.
38pub struct StripUnconfigured<'a> {
39    pub sess: &'a Session,
40    pub features: Option<&'a Features>,
41    /// If `true`, perform cfg-stripping on attached tokens.
42    /// This is only used for the input to derive macros,
43    /// which needs eager expansion of `cfg` and `cfg_attr`
44    pub config_tokens: bool,
45    pub lint_node_id: NodeId,
46}
47
48pub fn features(sess: &Session, krate_attrs: &[Attribute], crate_name: Symbol) -> Features {
49    fn feature_list(attr: &Attribute) -> ThinVec<ast::MetaItemInner> {
50        if attr.has_name(sym::feature)
51            && let Some(list) = attr.meta_item_list()
52        {
53            list
54        } else {
55            ThinVec::new()
56        }
57    }
58
59    let mut features = Features::default();
60
61    // Process all features enabled in the code.
62    for attr in krate_attrs {
63        for mi in feature_list(attr) {
64            let name = match mi.ident() {
65                Some(ident) if mi.is_word() => ident.name,
66                Some(ident) => {
67                    sess.dcx().emit_err(MalformedFeatureAttribute {
68                        span: mi.span(),
69                        help: MalformedFeatureAttributeHelp::Suggestion {
70                            span: mi.span(),
71                            suggestion: ident.name,
72                        },
73                    });
74                    continue;
75                }
76                None => {
77                    sess.dcx().emit_err(MalformedFeatureAttribute {
78                        span: mi.span(),
79                        help: MalformedFeatureAttributeHelp::Label { span: mi.span() },
80                    });
81                    continue;
82                }
83            };
84
85            // If the enabled feature has been removed, issue an error.
86            if let Some(f) = REMOVED_LANG_FEATURES.iter().find(|f| name == f.feature.name) {
87                let pull_note = if let Some(pull) = f.pull {
88                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("; see <https://github.com/rust-lang/rust/pull/{0}> for more information",
                pull))
    })format!(
89                        "; see <https://github.com/rust-lang/rust/pull/{}> for more information",
90                        pull
91                    )
92                } else {
93                    "".to_owned()
94                };
95                sess.dcx().emit_err(FeatureRemoved {
96                    span: mi.span(),
97                    reason: f.reason.map(|reason| FeatureRemovedReason { reason }),
98                    removed_rustc_version: f.feature.since,
99                    pull_note,
100                });
101                continue;
102            }
103
104            // If the enabled feature is stable, record it.
105            if let Some(f) = ACCEPTED_LANG_FEATURES.iter().find(|f| name == f.name) {
106                features.set_enabled_lang_feature(EnabledLangFeature {
107                    gate_name: name,
108                    attr_sp: mi.span(),
109                    stable_since: Some(Symbol::intern(f.since)),
110                });
111                continue;
112            }
113
114            // If `-Z allow-features` is used and the enabled feature is
115            // unstable and not also listed as one of the allowed features,
116            // issue an error.
117            if let Some(allowed) = sess.opts.unstable_opts.allow_features.as_ref() {
118                if allowed.iter().all(|f| name.as_str() != f) {
119                    sess.dcx().emit_err(FeatureNotAllowed { span: mi.span(), name });
120                    continue;
121                }
122            }
123
124            // If the enabled feature is unstable, record it.
125            if UNSTABLE_LANG_FEATURES.iter().find(|f| name == f.name).is_some() {
126                // When the ICE comes a standard library crate, there's a chance that the person
127                // hitting the ICE may be using -Zbuild-std or similar with an untested target.
128                // The bug is probably in the standard library and not the compiler in that case,
129                // but that doesn't really matter - we want a bug report.
130                if features.internal(name) && !STDLIB_STABLE_CRATES.contains(&crate_name) {
131                    sess.using_internal_features.store(true, std::sync::atomic::Ordering::Relaxed);
132                }
133
134                features.set_enabled_lang_feature(EnabledLangFeature {
135                    gate_name: name,
136                    attr_sp: mi.span(),
137                    stable_since: None,
138                });
139                continue;
140            }
141
142            // Otherwise, the feature is unknown. Enable it as a lib feature.
143            // It will be checked later whether the feature really exists.
144            features
145                .set_enabled_lib_feature(EnabledLibFeature { gate_name: name, attr_sp: mi.span() });
146
147            // Similar to above, detect internal lib features to suppress
148            // the ICE message that asks for a report.
149            if features.internal(name) && !STDLIB_STABLE_CRATES.contains(&crate_name) {
150                sess.using_internal_features.store(true, std::sync::atomic::Ordering::Relaxed);
151            }
152        }
153    }
154
155    features
156}
157
158pub fn pre_configure_attrs(sess: &Session, attrs: &[Attribute]) -> ast::AttrVec {
159    let strip_unconfigured = StripUnconfigured {
160        sess,
161        features: None,
162        config_tokens: false,
163        lint_node_id: ast::CRATE_NODE_ID,
164    };
165    attrs
166        .iter()
167        .flat_map(|attr| strip_unconfigured.process_cfg_attr(attr))
168        .take_while(|attr| {
169            !is_cfg(attr) || strip_unconfigured.cfg_true(attr, ShouldEmit::Nothing).as_bool()
170        })
171        .collect()
172}
173
174pub(crate) fn attr_into_trace(mut attr: Attribute, trace_name: Symbol) -> Attribute {
175    match &mut attr.kind {
176        AttrKind::Normal(normal) => {
177            let NormalAttr { item, tokens } = &mut **normal;
178            item.path.segments[0].ident.name = trace_name;
179            // This makes the trace attributes unobservable to token-based proc macros.
180            *tokens = Some(LazyAttrTokenStream::new_direct(AttrTokenStream::default()));
181        }
182        AttrKind::DocComment(..) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
183    }
184    attr
185}
186
187#[macro_export]
188macro_rules! configure {
189    ($this:ident, $node:ident) => {
190        match $this.configure($node) {
191            Some(node) => node,
192            None => return Default::default(),
193        }
194    };
195}
196
197impl<'a> StripUnconfigured<'a> {
198    pub fn configure<T: HasAttrs + HasTokens>(&self, mut node: T) -> Option<T> {
199        self.process_cfg_attrs(&mut node);
200        self.in_cfg(node.attrs()).then(|| {
201            self.try_configure_tokens(&mut node);
202            node
203        })
204    }
205
206    fn try_configure_tokens<T: HasTokens>(&self, node: &mut T) {
207        if self.config_tokens {
208            if let Some(Some(tokens)) = node.tokens_mut() {
209                let attr_stream = tokens.to_attr_token_stream();
210                *tokens = LazyAttrTokenStream::new_direct(self.configure_tokens(&attr_stream));
211            }
212        }
213    }
214
215    /// Performs cfg-expansion on `stream`, producing a new `AttrTokenStream`.
216    /// This is only used during the invocation of `derive` proc-macros,
217    /// which require that we cfg-expand their entire input.
218    /// Normal cfg-expansion operates on parsed AST nodes via the `configure` method
219    fn configure_tokens(&self, stream: &AttrTokenStream) -> AttrTokenStream {
220        fn can_skip(stream: &AttrTokenStream) -> bool {
221            stream.0.iter().all(|tree| match tree {
222                AttrTokenTree::AttrsTarget(_) => false,
223                AttrTokenTree::Token(..) => true,
224                AttrTokenTree::Delimited(.., inner) => can_skip(inner),
225            })
226        }
227
228        if can_skip(stream) {
229            return stream.clone();
230        }
231
232        let trees: Vec<_> = stream
233            .0
234            .iter()
235            .filter_map(|tree| match tree.clone() {
236                AttrTokenTree::AttrsTarget(mut target) => {
237                    // Expand any `cfg_attr` attributes.
238                    target.attrs.flat_map_in_place(|attr| self.process_cfg_attr(&attr));
239
240                    if self.in_cfg(&target.attrs) {
241                        target.tokens = LazyAttrTokenStream::new_direct(
242                            self.configure_tokens(&target.tokens.to_attr_token_stream()),
243                        );
244                        Some(AttrTokenTree::AttrsTarget(target))
245                    } else {
246                        // Remove the target if there's a `cfg` attribute and
247                        // the condition isn't satisfied.
248                        None
249                    }
250                }
251                AttrTokenTree::Delimited(sp, spacing, delim, mut inner) => {
252                    inner = self.configure_tokens(&inner);
253                    Some(AttrTokenTree::Delimited(sp, spacing, delim, inner))
254                }
255                AttrTokenTree::Token(Token { kind, .. }, _) if kind.is_delim() => {
256                    {
    ::core::panicking::panic_fmt(format_args!("Should be `AttrTokenTree::Delimited`, not delim tokens: {0:?}",
            tree));
};panic!("Should be `AttrTokenTree::Delimited`, not delim tokens: {:?}", tree);
257                }
258                AttrTokenTree::Token(token, spacing) => Some(AttrTokenTree::Token(token, spacing)),
259            })
260            .collect();
261        AttrTokenStream::new(trees)
262    }
263
264    /// Parse and expand all `cfg_attr` attributes into a list of attributes
265    /// that are within each `cfg_attr` that has a true configuration predicate.
266    ///
267    /// Gives compiler warnings if any `cfg_attr` does not contain any
268    /// attributes and is in the original source code. Gives compiler errors if
269    /// the syntax of any `cfg_attr` is incorrect.
270    fn process_cfg_attrs<T: HasAttrs>(&self, node: &mut T) {
271        node.visit_attrs(|attrs| {
272            attrs.flat_map_in_place(|attr| self.process_cfg_attr(&attr));
273        });
274    }
275
276    fn process_cfg_attr(&self, attr: &Attribute) -> Vec<Attribute> {
277        if attr.has_name(sym::cfg_attr) {
278            self.expand_cfg_attr(attr, true)
279        } else {
280            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [attr.clone()]))vec![attr.clone()]
281        }
282    }
283
284    /// Parse and expand a single `cfg_attr` attribute into a list of attributes
285    /// when the configuration predicate is true, or otherwise expand into an
286    /// empty list of attributes.
287    ///
288    /// Gives a compiler warning when the `cfg_attr` contains no attributes and
289    /// is in the original source file. Gives a compiler error if the syntax of
290    /// the attribute is incorrect.
291    pub(crate) fn expand_cfg_attr(&self, cfg_attr: &Attribute, recursive: bool) -> Vec<Attribute> {
292        // A trace attribute left in AST in place of the original `cfg_attr` attribute.
293        // It can later be used by lints or other diagnostics.
294        let mut trace_attr = cfg_attr.clone();
295        trace_attr.replace_args(AttrItemKind::Parsed(EarlyParsedAttribute::CfgAttrTrace));
296        let trace_attr = attr_into_trace(trace_attr, sym::cfg_attr_trace);
297
298        let Some((cfg_predicate, expanded_attrs)) =
299            rustc_attr_parsing::parse_cfg_attr(cfg_attr, &self.sess, self.features)
300        else {
301            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];
302        };
303
304        // Lint on zero attributes in source.
305        if expanded_attrs.is_empty() {
306            self.sess.psess.buffer_lint(
307                rustc_lint_defs::builtin::UNUSED_ATTRIBUTES,
308                cfg_attr.span,
309                ast::CRATE_NODE_ID,
310                crate::errors::CfgAttrNoAttributes,
311            );
312        }
313
314        if !attr::eval_config_entry(self.sess, &cfg_predicate).as_bool() {
315            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];
316        }
317
318        if recursive {
319            // We call `process_cfg_attr` recursively in case there's a
320            // `cfg_attr` inside of another `cfg_attr`. E.g.
321            //  `#[cfg_attr(false, cfg_attr(true, some_attr))]`.
322            let expanded_attrs = expanded_attrs
323                .into_iter()
324                .flat_map(|item| self.process_cfg_attr(&self.expand_cfg_attr_item(cfg_attr, item)));
325            iter::once(trace_attr).chain(expanded_attrs).collect()
326        } else {
327            let expanded_attrs =
328                expanded_attrs.into_iter().map(|item| self.expand_cfg_attr_item(cfg_attr, item));
329            iter::once(trace_attr).chain(expanded_attrs).collect()
330        }
331    }
332
333    fn expand_cfg_attr_item(
334        &self,
335        cfg_attr: &Attribute,
336        (item, item_span): (ast::AttrItem, Span),
337    ) -> Attribute {
338        // Convert `#[cfg_attr(pred, attr)]` to `#[attr]`.
339
340        // Use the `#` from `#[cfg_attr(pred, attr)]` in the result `#[attr]`.
341        let mut orig_trees = cfg_attr.token_trees().into_iter();
342        let Some(TokenTree::Token(pound_token @ Token { kind: TokenKind::Pound, .. }, _)) =
343            orig_trees.next()
344        else {
345            {
    ::core::panicking::panic_fmt(format_args!("Bad tokens for attribute {0:?}",
            cfg_attr));
};panic!("Bad tokens for attribute {cfg_attr:?}");
346        };
347
348        // For inner attributes, we do the same thing for the `!` in `#![attr]`.
349        let mut trees = if cfg_attr.style == AttrStyle::Inner {
350            let Some(TokenTree::Token(bang_token @ Token { kind: TokenKind::Bang, .. }, _)) =
351                orig_trees.next()
352            else {
353                {
    ::core::panicking::panic_fmt(format_args!("Bad tokens for attribute {0:?}",
            cfg_attr));
};panic!("Bad tokens for attribute {cfg_attr:?}");
354            };
355            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [AttrTokenTree::Token(pound_token, Spacing::Joint),
                AttrTokenTree::Token(bang_token, Spacing::JointHidden)]))vec![
356                AttrTokenTree::Token(pound_token, Spacing::Joint),
357                AttrTokenTree::Token(bang_token, Spacing::JointHidden),
358            ]
359        } else {
360            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [AttrTokenTree::Token(pound_token, Spacing::JointHidden)]))vec![AttrTokenTree::Token(pound_token, Spacing::JointHidden)]
361        };
362
363        // And the same thing for the `[`/`]` delimiters in `#[attr]`.
364        let Some(TokenTree::Delimited(delim_span, delim_spacing, Delimiter::Bracket, _)) =
365            orig_trees.next()
366        else {
367            {
    ::core::panicking::panic_fmt(format_args!("Bad tokens for attribute {0:?}",
            cfg_attr));
};panic!("Bad tokens for attribute {cfg_attr:?}");
368        };
369        trees.push(AttrTokenTree::Delimited(
370            delim_span,
371            delim_spacing,
372            Delimiter::Bracket,
373            item.tokens
374                .as_ref()
375                .unwrap_or_else(|| {
    ::core::panicking::panic_fmt(format_args!("Missing tokens for {0:?}",
            item));
}panic!("Missing tokens for {item:?}"))
376                .to_attr_token_stream(),
377        ));
378
379        let tokens = Some(LazyAttrTokenStream::new_direct(AttrTokenStream::new(trees)));
380        let attr = ast::attr::mk_attr_from_item(
381            &self.sess.psess.attr_id_generator,
382            item,
383            tokens,
384            cfg_attr.style,
385            item_span,
386        );
387        if attr.has_name(sym::crate_type) {
388            self.sess.dcx().emit_err(CrateTypeInCfgAttr { span: attr.span });
389        }
390        if attr.has_name(sym::crate_name) {
391            self.sess.dcx().emit_err(CrateNameInCfgAttr { span: attr.span });
392        }
393        attr
394    }
395
396    /// Determines if a node with the given attributes should be included in this configuration.
397    fn in_cfg(&self, attrs: &[Attribute]) -> bool {
398        attrs.iter().all(|attr| {
399            !is_cfg(attr)
400                || self
401                    .cfg_true(attr, ShouldEmit::ErrorsAndLints { recovery: Recovery::Allowed })
402                    .as_bool()
403        })
404    }
405
406    pub(crate) fn cfg_true(&self, attr: &Attribute, emit_errors: ShouldEmit) -> EvalConfigResult {
407        let Some(cfg) = AttributeParser::parse_single(
408            self.sess,
409            attr,
410            attr.span,
411            self.lint_node_id,
412            // Doesn't matter what the target actually is here.
413            Target::Crate,
414            self.features,
415            emit_errors,
416            parse_cfg,
417            &CFG_TEMPLATE,
418        ) else {
419            // Cfg attribute was not parsable, give up
420            return EvalConfigResult::True;
421        };
422
423        eval_config_entry(self.sess, &cfg)
424    }
425
426    /// If attributes are not allowed on expressions, emit an error for `attr`
427    #[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("compiler/rustc_expand/src/config.rs"),
                                    ::tracing_core::__macro_support::Option::Some(427u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_expand::config"),
                                    ::tracing_core::field::FieldSet::new(&["attr"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&attr)
                                                            as &dyn 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))]
428    pub(crate) fn maybe_emit_expr_attr_err(&self, attr: &Attribute) {
429        if self.features.is_some_and(|features| !features.stmt_expr_attributes())
430            && !attr.span.allows_unstable(sym::stmt_expr_attributes)
431        {
432            let mut err = feature_err(
433                &self.sess,
434                sym::stmt_expr_attributes,
435                attr.span,
436                msg!("attributes on expressions are experimental"),
437            );
438
439            if attr.is_doc_comment() {
440                err.help(if attr.style == AttrStyle::Outer {
441                    msg!("`///` is used for outer documentation comments; for a plain comment, use `//`")
442                } else {
443                    msg!("`//!` is used for inner documentation comments; for a plain comment, use `//` by removing the `!` or inserting a space in between them: `// !`")
444                });
445            }
446
447            err.emit();
448        }
449    }
450
451    #[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("compiler/rustc_expand/src/config.rs"),
                                    ::tracing_core::__macro_support::Option::Some(451u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_expand::config"),
                                    ::tracing_core::field::FieldSet::new(&["expr",
                                                    "method_receiver"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expr)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&method_receiver as
                                                            &dyn 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(RemoveExprNotSupported {
                        span: attr.span,
                    });
            }
            self.process_cfg_attrs(expr);
            self.try_configure_tokens(&mut *expr);
        }
    }
}#[instrument(level = "trace", skip(self))]
452    pub fn configure_expr(&self, expr: &mut ast::Expr, method_receiver: bool) {
453        if !method_receiver {
454            for attr in expr.attrs.iter() {
455                self.maybe_emit_expr_attr_err(attr);
456            }
457        }
458
459        // If an expr is valid to cfg away it will have been removed by the
460        // outer stmt or expression folder before descending in here.
461        // Anything else is always required, and thus has to error out
462        // in case of a cfg attr.
463        //
464        // N.B., this is intentionally not part of the visit_expr() function
465        //     in order for filter_map_expr() to be able to avoid this check
466        if let Some(attr) = expr.attrs().iter().find(|a| is_cfg(a)) {
467            self.sess.dcx().emit_err(RemoveExprNotSupported { span: attr.span });
468        }
469
470        self.process_cfg_attrs(expr);
471        self.try_configure_tokens(&mut *expr);
472    }
473}
474
475/// FIXME: Still used by Rustdoc, should be removed after
476pub fn parse_cfg_old<'a>(meta_item: &'a MetaItem, sess: &Session) -> Option<&'a MetaItemInner> {
477    let span = meta_item.span;
478    match meta_item.meta_item_list() {
479        None => {
480            sess.dcx().emit_err(InvalidCfg::NotFollowedByParens { span });
481            None
482        }
483        Some([]) => {
484            sess.dcx().emit_err(InvalidCfg::NoPredicate { span });
485            None
486        }
487        Some([_, .., l]) => {
488            sess.dcx().emit_err(InvalidCfg::MultiplePredicates { span: l.span() });
489            None
490        }
491        Some([single]) => match single.meta_item_or_bool() {
492            Some(meta_item) => Some(meta_item),
493            None => {
494                sess.dcx().emit_err(InvalidCfg::PredicateLiteral { span: single.span() });
495                None
496            }
497        },
498    }
499}
500
501fn is_cfg(attr: &Attribute) -> bool {
502    attr.has_name(sym::cfg)
503}