]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_builtin_macros/src/cfg_eval.rs
Rollup merge of #106946 - dtolnay:hashlinecolumn, r=m-ou-se
[rust.git] / compiler / rustc_builtin_macros / src / cfg_eval.rs
1 use crate::util::{check_builtin_macro_attribute, warn_on_duplicate_attribute};
2
3 use rustc_ast as ast;
4 use rustc_ast::mut_visit::MutVisitor;
5 use rustc_ast::ptr::P;
6 use rustc_ast::visit::Visitor;
7 use rustc_ast::NodeId;
8 use rustc_ast::{mut_visit, visit};
9 use rustc_ast::{Attribute, HasAttrs, HasTokens};
10 use rustc_errors::PResult;
11 use rustc_expand::base::{Annotatable, ExtCtxt};
12 use rustc_expand::config::StripUnconfigured;
13 use rustc_expand::configure;
14 use rustc_feature::Features;
15 use rustc_parse::parser::{ForceCollect, Parser};
16 use rustc_session::Session;
17 use rustc_span::symbol::sym;
18 use rustc_span::Span;
19 use smallvec::SmallVec;
20
21 pub(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
32 pub(crate) fn cfg_eval(
33     sess: &Session,
34     features: Option<&Features>,
35     annotatable: Annotatable,
36     lint_node_id: NodeId,
37 ) -> Annotatable {
38     CfgEval { cfg: &mut StripUnconfigured { sess, features, config_tokens: true, lint_node_id } }
39         .configure_annotatable(annotatable)
40         // Since the item itself has already been configured by the `InvocationCollector`,
41         // we know that fold result vector will contain exactly one element.
42         .unwrap()
43 }
44
45 struct CfgEval<'a, 'b> {
46     cfg: &'a mut StripUnconfigured<'b>,
47 }
48
49 fn flat_map_annotatable(
50     vis: &mut impl MutVisitor,
51     annotatable: Annotatable,
52 ) -> Option<Annotatable> {
53     match annotatable {
54         Annotatable::Item(item) => vis.flat_map_item(item).pop().map(Annotatable::Item),
55         Annotatable::TraitItem(item) => {
56             vis.flat_map_trait_item(item).pop().map(Annotatable::TraitItem)
57         }
58         Annotatable::ImplItem(item) => {
59             vis.flat_map_impl_item(item).pop().map(Annotatable::ImplItem)
60         }
61         Annotatable::ForeignItem(item) => {
62             vis.flat_map_foreign_item(item).pop().map(Annotatable::ForeignItem)
63         }
64         Annotatable::Stmt(stmt) => {
65             vis.flat_map_stmt(stmt.into_inner()).pop().map(P).map(Annotatable::Stmt)
66         }
67         Annotatable::Expr(mut expr) => {
68             vis.visit_expr(&mut expr);
69             Some(Annotatable::Expr(expr))
70         }
71         Annotatable::Arm(arm) => vis.flat_map_arm(arm).pop().map(Annotatable::Arm),
72         Annotatable::ExprField(field) => {
73             vis.flat_map_expr_field(field).pop().map(Annotatable::ExprField)
74         }
75         Annotatable::PatField(fp) => vis.flat_map_pat_field(fp).pop().map(Annotatable::PatField),
76         Annotatable::GenericParam(param) => {
77             vis.flat_map_generic_param(param).pop().map(Annotatable::GenericParam)
78         }
79         Annotatable::Param(param) => vis.flat_map_param(param).pop().map(Annotatable::Param),
80         Annotatable::FieldDef(sf) => vis.flat_map_field_def(sf).pop().map(Annotatable::FieldDef),
81         Annotatable::Variant(v) => vis.flat_map_variant(v).pop().map(Annotatable::Variant),
82         Annotatable::Crate(mut krate) => {
83             vis.visit_crate(&mut krate);
84             Some(Annotatable::Crate(krate))
85         }
86     }
87 }
88
89 struct CfgFinder {
90     has_cfg_or_cfg_attr: bool,
91 }
92
93 impl CfgFinder {
94     fn has_cfg_or_cfg_attr(annotatable: &Annotatable) -> bool {
95         let mut finder = CfgFinder { has_cfg_or_cfg_attr: false };
96         match annotatable {
97             Annotatable::Item(item) => finder.visit_item(&item),
98             Annotatable::TraitItem(item) => finder.visit_assoc_item(&item, visit::AssocCtxt::Trait),
99             Annotatable::ImplItem(item) => finder.visit_assoc_item(&item, visit::AssocCtxt::Impl),
100             Annotatable::ForeignItem(item) => finder.visit_foreign_item(&item),
101             Annotatable::Stmt(stmt) => finder.visit_stmt(&stmt),
102             Annotatable::Expr(expr) => finder.visit_expr(&expr),
103             Annotatable::Arm(arm) => finder.visit_arm(&arm),
104             Annotatable::ExprField(field) => finder.visit_expr_field(&field),
105             Annotatable::PatField(field) => finder.visit_pat_field(&field),
106             Annotatable::GenericParam(param) => finder.visit_generic_param(&param),
107             Annotatable::Param(param) => finder.visit_param(&param),
108             Annotatable::FieldDef(field) => finder.visit_field_def(&field),
109             Annotatable::Variant(variant) => finder.visit_variant(&variant),
110             Annotatable::Crate(krate) => finder.visit_crate(krate),
111         };
112         finder.has_cfg_or_cfg_attr
113     }
114 }
115
116 impl<'ast> visit::Visitor<'ast> for CfgFinder {
117     fn visit_attribute(&mut self, attr: &'ast Attribute) {
118         // We want short-circuiting behavior, so don't use the '|=' operator.
119         self.has_cfg_or_cfg_attr = self.has_cfg_or_cfg_attr
120             || attr
121                 .ident()
122                 .map_or(false, |ident| ident.name == sym::cfg || ident.name == sym::cfg_attr);
123     }
124 }
125
126 impl CfgEval<'_, '_> {
127     fn configure<T: HasAttrs + HasTokens>(&mut self, node: T) -> Option<T> {
128         self.cfg.configure(node)
129     }
130
131     fn configure_annotatable(&mut self, mut annotatable: Annotatable) -> Option<Annotatable> {
132         // Tokenizing and re-parsing the `Annotatable` can have a significant
133         // performance impact, so try to avoid it if possible
134         if !CfgFinder::has_cfg_or_cfg_attr(&annotatable) {
135             return Some(annotatable);
136         }
137
138         // The majority of parsed attribute targets will never need to have early cfg-expansion
139         // run (e.g. they are not part of a `#[derive]` or `#[cfg_eval]` macro input).
140         // Therefore, we normally do not capture the necessary information about `#[cfg]`
141         // and `#[cfg_attr]` attributes during parsing.
142         //
143         // Therefore, when we actually *do* run early cfg-expansion, we need to tokenize
144         // and re-parse the attribute target, this time capturing information about
145         // the location of `#[cfg]` and `#[cfg_attr]` in the token stream. The tokenization
146         // process is lossless, so this process is invisible to proc-macros.
147
148         let parse_annotatable_with: for<'a> fn(&mut Parser<'a>) -> PResult<'a, _> =
149             match annotatable {
150                 Annotatable::Item(_) => {
151                     |parser| Ok(Annotatable::Item(parser.parse_item(ForceCollect::Yes)?.unwrap()))
152                 }
153                 Annotatable::TraitItem(_) => |parser| {
154                     Ok(Annotatable::TraitItem(
155                         parser.parse_trait_item(ForceCollect::Yes)?.unwrap().unwrap(),
156                     ))
157                 },
158                 Annotatable::ImplItem(_) => |parser| {
159                     Ok(Annotatable::ImplItem(
160                         parser.parse_impl_item(ForceCollect::Yes)?.unwrap().unwrap(),
161                     ))
162                 },
163                 Annotatable::ForeignItem(_) => |parser| {
164                     Ok(Annotatable::ForeignItem(
165                         parser.parse_foreign_item(ForceCollect::Yes)?.unwrap().unwrap(),
166                     ))
167                 },
168                 Annotatable::Stmt(_) => |parser| {
169                     Ok(Annotatable::Stmt(P(parser.parse_stmt(ForceCollect::Yes)?.unwrap())))
170                 },
171                 Annotatable::Expr(_) => {
172                     |parser| Ok(Annotatable::Expr(parser.parse_expr_force_collect()?))
173                 }
174                 _ => unreachable!(),
175             };
176
177         // 'Flatten' all nonterminals (i.e. `TokenKind::Interpolated`)
178         // to `None`-delimited groups containing the corresponding tokens. This
179         // is normally delayed until the proc-macro server actually needs to
180         // provide a `TokenKind::Interpolated` to a proc-macro. We do this earlier,
181         // so that we can handle cases like:
182         //
183         // ```rust
184         // #[cfg_eval] #[cfg] $item
185         //```
186         //
187         // where `$item` is `#[cfg_attr] struct Foo {}`. We want to make
188         // sure to evaluate *all* `#[cfg]` and `#[cfg_attr]` attributes - the simplest
189         // way to do this is to do a single parse of a stream without any nonterminals.
190         let orig_tokens = annotatable.to_tokens().flattened();
191
192         // Re-parse the tokens, setting the `capture_cfg` flag to save extra information
193         // to the captured `AttrTokenStream` (specifically, we capture
194         // `AttrTokenTree::AttributesData` for all occurrences of `#[cfg]` and `#[cfg_attr]`)
195         let mut parser =
196             rustc_parse::stream_to_parser(&self.cfg.sess.parse_sess, orig_tokens, None);
197         parser.capture_cfg = true;
198         match parse_annotatable_with(&mut parser) {
199             Ok(a) => annotatable = a,
200             Err(mut err) => {
201                 err.emit();
202                 return Some(annotatable);
203             }
204         }
205
206         // Now that we have our re-parsed `AttrTokenStream`, recursively configuring
207         // our attribute target will correctly the tokens as well.
208         flat_map_annotatable(self, annotatable)
209     }
210 }
211
212 impl MutVisitor for CfgEval<'_, '_> {
213     #[instrument(level = "trace", skip(self))]
214     fn visit_expr(&mut self, expr: &mut P<ast::Expr>) {
215         self.cfg.configure_expr(expr, false);
216         mut_visit::noop_visit_expr(expr, self);
217     }
218
219     #[instrument(level = "trace", skip(self))]
220     fn visit_method_receiver_expr(&mut self, expr: &mut P<ast::Expr>) {
221         self.cfg.configure_expr(expr, true);
222         mut_visit::noop_visit_expr(expr, self);
223     }
224
225     fn filter_map_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
226         let mut expr = configure!(self, expr);
227         mut_visit::noop_visit_expr(&mut expr, self);
228         Some(expr)
229     }
230
231     fn flat_map_generic_param(
232         &mut self,
233         param: ast::GenericParam,
234     ) -> SmallVec<[ast::GenericParam; 1]> {
235         mut_visit::noop_flat_map_generic_param(configure!(self, param), self)
236     }
237
238     fn flat_map_stmt(&mut self, stmt: ast::Stmt) -> SmallVec<[ast::Stmt; 1]> {
239         mut_visit::noop_flat_map_stmt(configure!(self, stmt), self)
240     }
241
242     fn flat_map_item(&mut self, item: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
243         mut_visit::noop_flat_map_item(configure!(self, item), self)
244     }
245
246     fn flat_map_impl_item(&mut self, item: P<ast::AssocItem>) -> SmallVec<[P<ast::AssocItem>; 1]> {
247         mut_visit::noop_flat_map_assoc_item(configure!(self, item), self)
248     }
249
250     fn flat_map_trait_item(&mut self, item: P<ast::AssocItem>) -> SmallVec<[P<ast::AssocItem>; 1]> {
251         mut_visit::noop_flat_map_assoc_item(configure!(self, item), self)
252     }
253
254     fn flat_map_foreign_item(
255         &mut self,
256         foreign_item: P<ast::ForeignItem>,
257     ) -> SmallVec<[P<ast::ForeignItem>; 1]> {
258         mut_visit::noop_flat_map_foreign_item(configure!(self, foreign_item), self)
259     }
260
261     fn flat_map_arm(&mut self, arm: ast::Arm) -> SmallVec<[ast::Arm; 1]> {
262         mut_visit::noop_flat_map_arm(configure!(self, arm), self)
263     }
264
265     fn flat_map_expr_field(&mut self, field: ast::ExprField) -> SmallVec<[ast::ExprField; 1]> {
266         mut_visit::noop_flat_map_expr_field(configure!(self, field), self)
267     }
268
269     fn flat_map_pat_field(&mut self, fp: ast::PatField) -> SmallVec<[ast::PatField; 1]> {
270         mut_visit::noop_flat_map_pat_field(configure!(self, fp), self)
271     }
272
273     fn flat_map_param(&mut self, p: ast::Param) -> SmallVec<[ast::Param; 1]> {
274         mut_visit::noop_flat_map_param(configure!(self, p), self)
275     }
276
277     fn flat_map_field_def(&mut self, sf: ast::FieldDef) -> SmallVec<[ast::FieldDef; 1]> {
278         mut_visit::noop_flat_map_field_def(configure!(self, sf), self)
279     }
280
281     fn flat_map_variant(&mut self, variant: ast::Variant) -> SmallVec<[ast::Variant; 1]> {
282         mut_visit::noop_flat_map_variant(configure!(self, variant), self)
283     }
284 }