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                let pull_note = if let Some(pull) = f.pull {
84                    format!(
85                        "; see <https://github.com/rust-lang/rust/pull/{}> for more information",
86                        pull
87                    )
88                } else {
89                    "".to_owned()
90                };
91                sess.dcx().emit_err(FeatureRemoved {
92                    span: mi.span(),
93                    reason: f.reason.map(|reason| FeatureRemovedReason { reason }),
94                    removed_rustc_version: f.feature.since,
95                    current_rustc_version: sess.cfg_version,
96                    pull_note,
97                });
98                continue;
99            }
100
101            // If the enabled feature is stable, record it.
102            if let Some(f) = ACCEPTED_LANG_FEATURES.iter().find(|f| name == f.name) {
103                features.set_enabled_lang_feature(EnabledLangFeature {
104                    gate_name: name,
105                    attr_sp: mi.span(),
106                    stable_since: Some(Symbol::intern(f.since)),
107                });
108                continue;
109            }
110
111            // If `-Z allow-features` is used and the enabled feature is
112            // unstable and not also listed as one of the allowed features,
113            // issue an error.
114            if let Some(allowed) = sess.opts.unstable_opts.allow_features.as_ref() {
115                if allowed.iter().all(|f| name.as_str() != f) {
116                    sess.dcx().emit_err(FeatureNotAllowed { span: mi.span(), name });
117                    continue;
118                }
119            }
120
121            // If the enabled feature is unstable, record it.
122            if UNSTABLE_LANG_FEATURES.iter().find(|f| name == f.name).is_some() {
123                // When the ICE comes a standard library crate, there's a chance that the person
124                // hitting the ICE may be using -Zbuild-std or similar with an untested target.
125                // The bug is probably in the standard library and not the compiler in that case,
126                // but that doesn't really matter - we want a bug report.
127                if features.internal(name) && !STDLIB_STABLE_CRATES.contains(&crate_name) {
128                    sess.using_internal_features.store(true, std::sync::atomic::Ordering::Relaxed);
129                }
130
131                features.set_enabled_lang_feature(EnabledLangFeature {
132                    gate_name: name,
133                    attr_sp: mi.span(),
134                    stable_since: None,
135                });
136                continue;
137            }
138
139            // Otherwise, the feature is unknown. Enable it as a lib feature.
140            // It will be checked later whether the feature really exists.
141            features
142                .set_enabled_lib_feature(EnabledLibFeature { gate_name: name, attr_sp: mi.span() });
143
144            // Similar to above, detect internal lib features to suppress
145            // the ICE message that asks for a report.
146            if features.internal(name) && !STDLIB_STABLE_CRATES.contains(&crate_name) {
147                sess.using_internal_features.store(true, std::sync::atomic::Ordering::Relaxed);
148            }
149        }
150    }
151
152    features
153}
154
155pub fn pre_configure_attrs(sess: &Session, attrs: &[Attribute]) -> ast::AttrVec {
156    let strip_unconfigured = StripUnconfigured {
157        sess,
158        features: None,
159        config_tokens: false,
160        lint_node_id: ast::CRATE_NODE_ID,
161    };
162    attrs
163        .iter()
164        .flat_map(|attr| strip_unconfigured.process_cfg_attr(attr))
165        .take_while(|attr| !is_cfg(attr) || strip_unconfigured.cfg_true(attr).0)
166        .collect()
167}
168
169pub(crate) fn attr_into_trace(mut attr: Attribute, trace_name: Symbol) -> Attribute {
170    match &mut attr.kind {
171        AttrKind::Normal(normal) => {
172            let NormalAttr { item, tokens } = &mut **normal;
173            item.path.segments[0].ident.name = trace_name;
174            // This makes the trace attributes unobservable to token-based proc macros.
175            *tokens = Some(LazyAttrTokenStream::new_direct(AttrTokenStream::default()));
176        }
177        AttrKind::DocComment(..) => unreachable!(),
178    }
179    attr
180}
181
182#[macro_export]
183macro_rules! configure {
184    ($this:ident, $node:ident) => {
185        match $this.configure($node) {
186            Some(node) => node,
187            None => return Default::default(),
188        }
189    };
190}
191
192impl<'a> StripUnconfigured<'a> {
193    pub fn configure<T: HasAttrs + HasTokens>(&self, mut node: T) -> Option<T> {
194        self.process_cfg_attrs(&mut node);
195        self.in_cfg(node.attrs()).then(|| {
196            self.try_configure_tokens(&mut node);
197            node
198        })
199    }
200
201    fn try_configure_tokens<T: HasTokens>(&self, node: &mut T) {
202        if self.config_tokens {
203            if let Some(Some(tokens)) = node.tokens_mut() {
204                let attr_stream = tokens.to_attr_token_stream();
205                *tokens = LazyAttrTokenStream::new_direct(self.configure_tokens(&attr_stream));
206            }
207        }
208    }
209
210    /// Performs cfg-expansion on `stream`, producing a new `AttrTokenStream`.
211    /// This is only used during the invocation of `derive` proc-macros,
212    /// which require that we cfg-expand their entire input.
213    /// Normal cfg-expansion operates on parsed AST nodes via the `configure` method
214    fn configure_tokens(&self, stream: &AttrTokenStream) -> AttrTokenStream {
215        fn can_skip(stream: &AttrTokenStream) -> bool {
216            stream.0.iter().all(|tree| match tree {
217                AttrTokenTree::AttrsTarget(_) => false,
218                AttrTokenTree::Token(..) => true,
219                AttrTokenTree::Delimited(.., inner) => can_skip(inner),
220            })
221        }
222
223        if can_skip(stream) {
224            return stream.clone();
225        }
226
227        let trees: Vec<_> = stream
228            .0
229            .iter()
230            .filter_map(|tree| match tree.clone() {
231                AttrTokenTree::AttrsTarget(mut target) => {
232                    // Expand any `cfg_attr` attributes.
233                    target.attrs.flat_map_in_place(|attr| self.process_cfg_attr(&attr));
234
235                    if self.in_cfg(&target.attrs) {
236                        target.tokens = LazyAttrTokenStream::new_direct(
237                            self.configure_tokens(&target.tokens.to_attr_token_stream()),
238                        );
239                        Some(AttrTokenTree::AttrsTarget(target))
240                    } else {
241                        // Remove the target if there's a `cfg` attribute and
242                        // the condition isn't satisfied.
243                        None
244                    }
245                }
246                AttrTokenTree::Delimited(sp, spacing, delim, mut inner) => {
247                    inner = self.configure_tokens(&inner);
248                    Some(AttrTokenTree::Delimited(sp, spacing, delim, inner))
249                }
250                AttrTokenTree::Token(Token { kind, .. }, _) if kind.is_delim() => {
251                    panic!("Should be `AttrTokenTree::Delimited`, not delim tokens: {:?}", tree);
252                }
253                AttrTokenTree::Token(token, spacing) => Some(AttrTokenTree::Token(token, spacing)),
254            })
255            .collect();
256        AttrTokenStream::new(trees)
257    }
258
259    /// Parse and expand all `cfg_attr` attributes into a list of attributes
260    /// that are within each `cfg_attr` that has a true configuration predicate.
261    ///
262    /// Gives compiler warnings if any `cfg_attr` does not contain any
263    /// attributes and is in the original source code. Gives compiler errors if
264    /// the syntax of any `cfg_attr` is incorrect.
265    fn process_cfg_attrs<T: HasAttrs>(&self, node: &mut T) {
266        node.visit_attrs(|attrs| {
267            attrs.flat_map_in_place(|attr| self.process_cfg_attr(&attr));
268        });
269    }
270
271    fn process_cfg_attr(&self, attr: &Attribute) -> Vec<Attribute> {
272        if attr.has_name(sym::cfg_attr) {
273            self.expand_cfg_attr(attr, true)
274        } else {
275            vec![attr.clone()]
276        }
277    }
278
279    /// Parse and expand a single `cfg_attr` attribute into a list of attributes
280    /// when the configuration predicate is true, or otherwise expand into an
281    /// empty list of attributes.
282    ///
283    /// Gives a compiler warning when the `cfg_attr` contains no attributes and
284    /// is in the original source file. Gives a compiler error if the syntax of
285    /// the attribute is incorrect.
286    pub(crate) fn expand_cfg_attr(&self, cfg_attr: &Attribute, recursive: bool) -> Vec<Attribute> {
287        validate_attr::check_attribute_safety(
288            &self.sess.psess,
289            Some(AttributeSafety::Normal),
290            &cfg_attr,
291            ast::CRATE_NODE_ID,
292        );
293
294        // A trace attribute left in AST in place of the original `cfg_attr` attribute.
295        // It can later be used by lints or other diagnostics.
296        let trace_attr = attr_into_trace(cfg_attr.clone(), sym::cfg_attr_trace);
297
298        let Some((cfg_predicate, expanded_attrs)) =
299            rustc_parse::parse_cfg_attr(cfg_attr, &self.sess.psess)
300        else {
301            return 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                BuiltinLintDiag::CfgAttrNoAttributes,
311            );
312        }
313
314        if !attr::cfg_matches(&cfg_predicate, &self.sess, self.lint_node_id, self.features) {
315            return 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            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                panic!("Bad tokens for attribute {cfg_attr:?}");
354            };
355            vec![
356                AttrTokenTree::Token(pound_token, Spacing::Joint),
357                AttrTokenTree::Token(bang_token, Spacing::JointHidden),
358            ]
359        } else {
360            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            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(|| 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| !is_cfg(attr) || self.cfg_true(attr).0)
399    }
400
401    pub(crate) fn cfg_true(&self, attr: &Attribute) -> (bool, Option<MetaItem>) {
402        let meta_item = match validate_attr::parse_meta(&self.sess.psess, attr) {
403            Ok(meta_item) => meta_item,
404            Err(err) => {
405                err.emit();
406                return (true, None);
407            }
408        };
409
410        validate_attr::deny_builtin_meta_unsafety(&self.sess.psess, &meta_item);
411
412        (
413            parse_cfg(&meta_item, self.sess).is_none_or(|meta_item| {
414                attr::cfg_matches(meta_item, &self.sess, self.lint_node_id, self.features)
415            }),
416            Some(meta_item),
417        )
418    }
419
420    /// If attributes are not allowed on expressions, emit an error for `attr`
421    #[instrument(level = "trace", skip(self))]
422    pub(crate) fn maybe_emit_expr_attr_err(&self, attr: &Attribute) {
423        if self.features.is_some_and(|features| !features.stmt_expr_attributes())
424            && !attr.span.allows_unstable(sym::stmt_expr_attributes)
425        {
426            let mut err = feature_err(
427                &self.sess,
428                sym::stmt_expr_attributes,
429                attr.span,
430                crate::fluent_generated::expand_attributes_on_expressions_experimental,
431            );
432
433            if attr.is_doc_comment() {
434                err.help(if attr.style == AttrStyle::Outer {
435                    crate::fluent_generated::expand_help_outer_doc
436                } else {
437                    crate::fluent_generated::expand_help_inner_doc
438                });
439            }
440
441            err.emit();
442        }
443    }
444
445    #[instrument(level = "trace", skip(self))]
446    pub fn configure_expr(&self, expr: &mut ast::Expr, method_receiver: bool) {
447        if !method_receiver {
448            for attr in expr.attrs.iter() {
449                self.maybe_emit_expr_attr_err(attr);
450            }
451        }
452
453        // If an expr is valid to cfg away it will have been removed by the
454        // outer stmt or expression folder before descending in here.
455        // Anything else is always required, and thus has to error out
456        // in case of a cfg attr.
457        //
458        // N.B., this is intentionally not part of the visit_expr() function
459        //     in order for filter_map_expr() to be able to avoid this check
460        if let Some(attr) = expr.attrs().iter().find(|a| is_cfg(a)) {
461            self.sess.dcx().emit_err(RemoveExprNotSupported { span: attr.span });
462        }
463
464        self.process_cfg_attrs(expr);
465        self.try_configure_tokens(&mut *expr);
466    }
467}
468
469pub fn parse_cfg<'a>(meta_item: &'a MetaItem, sess: &Session) -> Option<&'a MetaItemInner> {
470    let span = meta_item.span;
471    match meta_item.meta_item_list() {
472        None => {
473            sess.dcx().emit_err(InvalidCfg::NotFollowedByParens { span });
474            None
475        }
476        Some([]) => {
477            sess.dcx().emit_err(InvalidCfg::NoPredicate { span });
478            None
479        }
480        Some([_, .., l]) => {
481            sess.dcx().emit_err(InvalidCfg::MultiplePredicates { span: l.span() });
482            None
483        }
484        Some([single]) => match single.meta_item_or_bool() {
485            Some(meta_item) => Some(meta_item),
486            None => {
487                sess.dcx().emit_err(InvalidCfg::PredicateLiteral { span: single.span() });
488                None
489            }
490        },
491    }
492}
493
494fn is_cfg(attr: &Attribute) -> bool {
495    attr.has_name(sym::cfg)
496}