rustc_expand/
config.rs

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