rustc_builtin_macros/
cfg_eval.rs

1use core::ops::ControlFlow;
2
3use rustc_ast as ast;
4use rustc_ast::mut_visit::MutVisitor;
5use rustc_ast::ptr::P;
6use rustc_ast::visit::{AssocCtxt, Visitor};
7use rustc_ast::{Attribute, HasAttrs, HasTokens, NodeId, mut_visit, visit};
8use rustc_errors::PResult;
9use rustc_expand::base::{Annotatable, ExtCtxt};
10use rustc_expand::config::StripUnconfigured;
11use rustc_expand::configure;
12use rustc_feature::Features;
13use rustc_parse::parser::{ForceCollect, Parser};
14use rustc_session::Session;
15use rustc_span::{Span, sym};
16use smallvec::SmallVec;
17use tracing::instrument;
18
19use crate::util::{check_builtin_macro_attribute, warn_on_duplicate_attribute};
20
21pub(crate) fn expand(
22    ecx: &mut ExtCtxt<'_>,
23    _span: Span,
24    meta_item: &ast::MetaItem,
25    annotatable: Annotatable,
26) -> Vec<Annotatable> {
27    check_builtin_macro_attribute(ecx, meta_item, sym::cfg_eval);
28    warn_on_duplicate_attribute(ecx, &annotatable, sym::cfg_eval);
29    vec![cfg_eval(ecx.sess, ecx.ecfg.features, annotatable, ecx.current_expansion.lint_node_id)]
30}
31
32pub(crate) fn cfg_eval(
33    sess: &Session,
34    features: &Features,
35    annotatable: Annotatable,
36    lint_node_id: NodeId,
37) -> Annotatable {
38    let features = Some(features);
39    CfgEval(StripUnconfigured { sess, features, config_tokens: true, lint_node_id })
40        .configure_annotatable(annotatable)
41}
42
43struct CfgEval<'a>(StripUnconfigured<'a>);
44
45fn has_cfg_or_cfg_attr(annotatable: &Annotatable) -> bool {
46    struct CfgFinder;
47
48    impl<'ast> visit::Visitor<'ast> for CfgFinder {
49        type Result = ControlFlow<()>;
50        fn visit_attribute(&mut self, attr: &'ast Attribute) -> ControlFlow<()> {
51            if attr
52                .ident()
53                .is_some_and(|ident| ident.name == sym::cfg || ident.name == sym::cfg_attr)
54            {
55                ControlFlow::Break(())
56            } else {
57                ControlFlow::Continue(())
58            }
59        }
60    }
61
62    let res = match annotatable {
63        Annotatable::Item(item) => CfgFinder.visit_item(item),
64        Annotatable::AssocItem(item, ctxt) => CfgFinder.visit_assoc_item(item, *ctxt),
65        Annotatable::ForeignItem(item) => CfgFinder.visit_foreign_item(item),
66        Annotatable::Stmt(stmt) => CfgFinder.visit_stmt(stmt),
67        Annotatable::Expr(expr) => CfgFinder.visit_expr(expr),
68        _ => unreachable!(),
69    };
70    res.is_break()
71}
72
73impl CfgEval<'_> {
74    fn configure<T: HasAttrs + HasTokens>(&mut self, node: T) -> Option<T> {
75        self.0.configure(node)
76    }
77
78    fn configure_annotatable(mut self, annotatable: Annotatable) -> Annotatable {
79        // Tokenizing and re-parsing the `Annotatable` can have a significant
80        // performance impact, so try to avoid it if possible
81        if !has_cfg_or_cfg_attr(&annotatable) {
82            return annotatable;
83        }
84
85        // The majority of parsed attribute targets will never need to have early cfg-expansion
86        // run (e.g. they are not part of a `#[derive]` or `#[cfg_eval]` macro input).
87        // Therefore, we normally do not capture the necessary information about `#[cfg]`
88        // and `#[cfg_attr]` attributes during parsing.
89        //
90        // Therefore, when we actually *do* run early cfg-expansion, we need to tokenize
91        // and re-parse the attribute target, this time capturing information about
92        // the location of `#[cfg]` and `#[cfg_attr]` in the token stream. The tokenization
93        // process is lossless, so this process is invisible to proc-macros.
94
95        // Interesting cases:
96        //
97        // ```rust
98        // #[cfg_eval] #[cfg] $item
99        //```
100        //
101        // where `$item` is `#[cfg_attr] struct Foo {}`. We want to make
102        // sure to evaluate *all* `#[cfg]` and `#[cfg_attr]` attributes - the simplest
103        // way to do this is to do a single parse of the token stream.
104        let orig_tokens = annotatable.to_tokens();
105
106        // Re-parse the tokens, setting the `capture_cfg` flag to save extra information
107        // to the captured `AttrTokenStream` (specifically, we capture
108        // `AttrTokenTree::AttrsTarget` for all occurrences of `#[cfg]` and `#[cfg_attr]`)
109        //
110        // After that we have our re-parsed `AttrTokenStream`, recursively configuring
111        // our attribute target will correctly configure the tokens as well.
112        let mut parser = Parser::new(&self.0.sess.psess, orig_tokens, None);
113        parser.capture_cfg = true;
114        let res: PResult<'_, Annotatable> = try {
115            match annotatable {
116                Annotatable::Item(_) => {
117                    let item = parser.parse_item(ForceCollect::Yes)?.unwrap();
118                    Annotatable::Item(self.flat_map_item(item).pop().unwrap())
119                }
120                Annotatable::AssocItem(_, ctxt) => {
121                    let item = parser.parse_trait_item(ForceCollect::Yes)?.unwrap().unwrap();
122                    Annotatable::AssocItem(
123                        self.flat_map_assoc_item(item, ctxt).pop().unwrap(),
124                        ctxt,
125                    )
126                }
127                Annotatable::ForeignItem(_) => {
128                    let item = parser.parse_foreign_item(ForceCollect::Yes)?.unwrap().unwrap();
129                    Annotatable::ForeignItem(self.flat_map_foreign_item(item).pop().unwrap())
130                }
131                Annotatable::Stmt(_) => {
132                    let stmt = parser
133                        .parse_stmt_without_recovery(false, ForceCollect::Yes, false)?
134                        .unwrap();
135                    Annotatable::Stmt(P(self.flat_map_stmt(stmt).pop().unwrap()))
136                }
137                Annotatable::Expr(_) => {
138                    let mut expr = parser.parse_expr_force_collect()?;
139                    self.visit_expr(&mut expr);
140                    Annotatable::Expr(expr)
141                }
142                _ => unreachable!(),
143            }
144        };
145
146        match res {
147            Ok(ann) => ann,
148            Err(err) => {
149                err.emit();
150                annotatable
151            }
152        }
153    }
154}
155
156impl MutVisitor for CfgEval<'_> {
157    #[instrument(level = "trace", skip(self))]
158    fn visit_expr(&mut self, expr: &mut P<ast::Expr>) {
159        self.0.configure_expr(expr, false);
160        mut_visit::walk_expr(self, expr);
161    }
162
163    #[instrument(level = "trace", skip(self))]
164    fn visit_method_receiver_expr(&mut self, expr: &mut P<ast::Expr>) {
165        self.0.configure_expr(expr, true);
166        mut_visit::walk_expr(self, expr);
167    }
168
169    fn filter_map_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
170        let mut expr = configure!(self, expr);
171        mut_visit::walk_expr(self, &mut expr);
172        Some(expr)
173    }
174
175    fn flat_map_generic_param(
176        &mut self,
177        param: ast::GenericParam,
178    ) -> SmallVec<[ast::GenericParam; 1]> {
179        let param = configure!(self, param);
180        mut_visit::walk_flat_map_generic_param(self, param)
181    }
182
183    fn flat_map_stmt(&mut self, stmt: ast::Stmt) -> SmallVec<[ast::Stmt; 1]> {
184        let stmt = configure!(self, stmt);
185        mut_visit::walk_flat_map_stmt(self, stmt)
186    }
187
188    fn flat_map_item(&mut self, item: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
189        let item = configure!(self, item);
190        mut_visit::walk_flat_map_item(self, item)
191    }
192
193    fn flat_map_assoc_item(
194        &mut self,
195        item: P<ast::AssocItem>,
196        ctxt: AssocCtxt,
197    ) -> SmallVec<[P<ast::AssocItem>; 1]> {
198        let item = configure!(self, item);
199        mut_visit::walk_flat_map_assoc_item(self, item, ctxt)
200    }
201
202    fn flat_map_foreign_item(
203        &mut self,
204        foreign_item: P<ast::ForeignItem>,
205    ) -> SmallVec<[P<ast::ForeignItem>; 1]> {
206        let foreign_item = configure!(self, foreign_item);
207        mut_visit::walk_flat_map_foreign_item(self, foreign_item)
208    }
209
210    fn flat_map_arm(&mut self, arm: ast::Arm) -> SmallVec<[ast::Arm; 1]> {
211        let arm = configure!(self, arm);
212        mut_visit::walk_flat_map_arm(self, arm)
213    }
214
215    fn flat_map_expr_field(&mut self, field: ast::ExprField) -> SmallVec<[ast::ExprField; 1]> {
216        let field = configure!(self, field);
217        mut_visit::walk_flat_map_expr_field(self, field)
218    }
219
220    fn flat_map_pat_field(&mut self, fp: ast::PatField) -> SmallVec<[ast::PatField; 1]> {
221        let fp = configure!(self, fp);
222        mut_visit::walk_flat_map_pat_field(self, fp)
223    }
224
225    fn flat_map_param(&mut self, p: ast::Param) -> SmallVec<[ast::Param; 1]> {
226        let p = configure!(self, p);
227        mut_visit::walk_flat_map_param(self, p)
228    }
229
230    fn flat_map_field_def(&mut self, sf: ast::FieldDef) -> SmallVec<[ast::FieldDef; 1]> {
231        let sf = configure!(self, sf);
232        mut_visit::walk_flat_map_field_def(self, sf)
233    }
234
235    fn flat_map_variant(&mut self, variant: ast::Variant) -> SmallVec<[ast::Variant; 1]> {
236        let variant = configure!(self, variant);
237        mut_visit::walk_flat_map_variant(self, variant)
238    }
239}