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