]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_builtin_macros/src/proc_macro_harness.rs
Rollup merge of #104404 - GuillaumeGomez:fix-missing-minification, r=notriddle
[rust.git] / compiler / rustc_builtin_macros / src / proc_macro_harness.rs
1 use std::mem;
2
3 use rustc_ast::attr;
4 use rustc_ast::ptr::P;
5 use rustc_ast::visit::{self, Visitor};
6 use rustc_ast::{self as ast, NodeId};
7 use rustc_ast_pretty::pprust;
8 use rustc_expand::base::{parse_macro_name_and_helper_attrs, ExtCtxt, ResolverExpand};
9 use rustc_expand::expand::{AstFragment, ExpansionConfig};
10 use rustc_session::Session;
11 use rustc_span::hygiene::AstPass;
12 use rustc_span::source_map::SourceMap;
13 use rustc_span::symbol::{kw, sym, Ident, Symbol};
14 use rustc_span::{Span, DUMMY_SP};
15 use smallvec::smallvec;
16
17 struct ProcMacroDerive {
18     id: NodeId,
19     trait_name: Symbol,
20     function_name: Ident,
21     span: Span,
22     attrs: Vec<Symbol>,
23 }
24
25 struct ProcMacroDef {
26     id: NodeId,
27     function_name: Ident,
28     span: Span,
29 }
30
31 enum ProcMacro {
32     Derive(ProcMacroDerive),
33     Attr(ProcMacroDef),
34     Bang(ProcMacroDef),
35 }
36
37 struct CollectProcMacros<'a> {
38     sess: &'a Session,
39     macros: Vec<ProcMacro>,
40     in_root: bool,
41     handler: &'a rustc_errors::Handler,
42     source_map: &'a SourceMap,
43     is_proc_macro_crate: bool,
44     is_test_crate: bool,
45 }
46
47 pub fn inject(
48     sess: &Session,
49     resolver: &mut dyn ResolverExpand,
50     mut krate: ast::Crate,
51     is_proc_macro_crate: bool,
52     has_proc_macro_decls: bool,
53     is_test_crate: bool,
54     handler: &rustc_errors::Handler,
55 ) -> ast::Crate {
56     let ecfg = ExpansionConfig::default("proc_macro".to_string());
57     let mut cx = ExtCtxt::new(sess, ecfg, resolver, None);
58
59     let mut collect = CollectProcMacros {
60         sess,
61         macros: Vec::new(),
62         in_root: true,
63         handler,
64         source_map: sess.source_map(),
65         is_proc_macro_crate,
66         is_test_crate,
67     };
68
69     if has_proc_macro_decls || is_proc_macro_crate {
70         visit::walk_crate(&mut collect, &krate);
71     }
72     let macros = collect.macros;
73
74     if !is_proc_macro_crate {
75         return krate;
76     }
77
78     if is_test_crate {
79         return krate;
80     }
81
82     let decls = mk_decls(&mut cx, &macros);
83     krate.items.push(decls);
84
85     krate
86 }
87
88 impl<'a> CollectProcMacros<'a> {
89     fn check_not_pub_in_root(&self, vis: &ast::Visibility, sp: Span) {
90         if self.is_proc_macro_crate && self.in_root && vis.kind.is_pub() {
91             self.handler.span_err(
92                 sp,
93                 "`proc-macro` crate types currently cannot export any items other \
94                     than functions tagged with `#[proc_macro]`, `#[proc_macro_derive]`, \
95                     or `#[proc_macro_attribute]`",
96             );
97         }
98     }
99
100     fn collect_custom_derive(&mut self, item: &'a ast::Item, attr: &'a ast::Attribute) {
101         let Some((trait_name, proc_attrs)) = parse_macro_name_and_helper_attrs(self.handler, attr, "derive") else {
102             return;
103         };
104
105         if self.in_root && item.vis.kind.is_pub() {
106             self.macros.push(ProcMacro::Derive(ProcMacroDerive {
107                 id: item.id,
108                 span: item.span,
109                 trait_name,
110                 function_name: item.ident,
111                 attrs: proc_attrs,
112             }));
113         } else {
114             let msg = if !self.in_root {
115                 "functions tagged with `#[proc_macro_derive]` must \
116                  currently reside in the root of the crate"
117             } else {
118                 "functions tagged with `#[proc_macro_derive]` must be `pub`"
119             };
120             self.handler.span_err(self.source_map.guess_head_span(item.span), msg);
121         }
122     }
123
124     fn collect_attr_proc_macro(&mut self, item: &'a ast::Item) {
125         if self.in_root && item.vis.kind.is_pub() {
126             self.macros.push(ProcMacro::Attr(ProcMacroDef {
127                 id: item.id,
128                 span: item.span,
129                 function_name: item.ident,
130             }));
131         } else {
132             let msg = if !self.in_root {
133                 "functions tagged with `#[proc_macro_attribute]` must \
134                  currently reside in the root of the crate"
135             } else {
136                 "functions tagged with `#[proc_macro_attribute]` must be `pub`"
137             };
138             self.handler.span_err(self.source_map.guess_head_span(item.span), msg);
139         }
140     }
141
142     fn collect_bang_proc_macro(&mut self, item: &'a ast::Item) {
143         if self.in_root && item.vis.kind.is_pub() {
144             self.macros.push(ProcMacro::Bang(ProcMacroDef {
145                 id: item.id,
146                 span: item.span,
147                 function_name: item.ident,
148             }));
149         } else {
150             let msg = if !self.in_root {
151                 "functions tagged with `#[proc_macro]` must \
152                  currently reside in the root of the crate"
153             } else {
154                 "functions tagged with `#[proc_macro]` must be `pub`"
155             };
156             self.handler.span_err(self.source_map.guess_head_span(item.span), msg);
157         }
158     }
159 }
160
161 impl<'a> Visitor<'a> for CollectProcMacros<'a> {
162     fn visit_item(&mut self, item: &'a ast::Item) {
163         if let ast::ItemKind::MacroDef(..) = item.kind {
164             if self.is_proc_macro_crate && self.sess.contains_name(&item.attrs, sym::macro_export) {
165                 let msg =
166                     "cannot export macro_rules! macros from a `proc-macro` crate type currently";
167                 self.handler.span_err(self.source_map.guess_head_span(item.span), msg);
168             }
169         }
170
171         // First up, make sure we're checking a bare function. If we're not then
172         // we're just not interested in this item.
173         //
174         // If we find one, try to locate a `#[proc_macro_derive]` attribute on it.
175         let is_fn = matches!(item.kind, ast::ItemKind::Fn(..));
176
177         let mut found_attr: Option<&'a ast::Attribute> = None;
178
179         for attr in &item.attrs {
180             if self.sess.is_proc_macro_attr(&attr) {
181                 if let Some(prev_attr) = found_attr {
182                     let prev_item = prev_attr.get_normal_item();
183                     let item = attr.get_normal_item();
184                     let path_str = pprust::path_to_string(&item.path);
185                     let msg = if item.path.segments[0].ident.name
186                         == prev_item.path.segments[0].ident.name
187                     {
188                         format!(
189                             "only one `#[{}]` attribute is allowed on any given function",
190                             path_str,
191                         )
192                     } else {
193                         format!(
194                             "`#[{}]` and `#[{}]` attributes cannot both be applied
195                             to the same function",
196                             path_str,
197                             pprust::path_to_string(&prev_item.path),
198                         )
199                     };
200
201                     self.handler
202                         .struct_span_err(attr.span, &msg)
203                         .span_label(prev_attr.span, "previous attribute here")
204                         .emit();
205
206                     return;
207                 }
208
209                 found_attr = Some(attr);
210             }
211         }
212
213         let Some(attr) = found_attr else {
214             self.check_not_pub_in_root(&item.vis, self.source_map.guess_head_span(item.span));
215             let prev_in_root = mem::replace(&mut self.in_root, false);
216             visit::walk_item(self, item);
217             self.in_root = prev_in_root;
218             return;
219         };
220
221         if !is_fn {
222             let msg = format!(
223                 "the `#[{}]` attribute may only be used on bare functions",
224                 pprust::path_to_string(&attr.get_normal_item().path),
225             );
226
227             self.handler.span_err(attr.span, &msg);
228             return;
229         }
230
231         if self.is_test_crate {
232             return;
233         }
234
235         if !self.is_proc_macro_crate {
236             let msg = format!(
237                 "the `#[{}]` attribute is only usable with crates of the `proc-macro` crate type",
238                 pprust::path_to_string(&attr.get_normal_item().path),
239             );
240
241             self.handler.span_err(attr.span, &msg);
242             return;
243         }
244
245         if attr.has_name(sym::proc_macro_derive) {
246             self.collect_custom_derive(item, attr);
247         } else if attr.has_name(sym::proc_macro_attribute) {
248             self.collect_attr_proc_macro(item);
249         } else if attr.has_name(sym::proc_macro) {
250             self.collect_bang_proc_macro(item);
251         };
252
253         let prev_in_root = mem::replace(&mut self.in_root, false);
254         visit::walk_item(self, item);
255         self.in_root = prev_in_root;
256     }
257 }
258
259 // Creates a new module which looks like:
260 //
261 //      const _: () = {
262 //          extern crate proc_macro;
263 //
264 //          use proc_macro::bridge::client::ProcMacro;
265 //
266 //          #[rustc_proc_macro_decls]
267 //          #[allow(deprecated)]
268 //          static DECLS: &[ProcMacro] = &[
269 //              ProcMacro::custom_derive($name_trait1, &[], ::$name1);
270 //              ProcMacro::custom_derive($name_trait2, &["attribute_name"], ::$name2);
271 //              // ...
272 //          ];
273 //      }
274 fn mk_decls(cx: &mut ExtCtxt<'_>, macros: &[ProcMacro]) -> P<ast::Item> {
275     let expn_id = cx.resolver.expansion_for_ast_pass(
276         DUMMY_SP,
277         AstPass::ProcMacroHarness,
278         &[sym::rustc_attrs, sym::proc_macro_internals],
279         None,
280     );
281     let span = DUMMY_SP.with_def_site_ctxt(expn_id.to_expn_id());
282
283     let proc_macro = Ident::new(sym::proc_macro, span);
284     let krate = cx.item(span, proc_macro, ast::AttrVec::new(), ast::ItemKind::ExternCrate(None));
285
286     let bridge = Ident::new(sym::bridge, span);
287     let client = Ident::new(sym::client, span);
288     let proc_macro_ty = Ident::new(sym::ProcMacro, span);
289     let custom_derive = Ident::new(sym::custom_derive, span);
290     let attr = Ident::new(sym::attr, span);
291     let bang = Ident::new(sym::bang, span);
292
293     // We add NodeIds to 'resolver.proc_macros' in the order
294     // that we generate expressions. The position of each NodeId
295     // in the 'proc_macros' Vec corresponds to its position
296     // in the static array that will be generated
297     let decls = macros
298         .iter()
299         .map(|m| {
300             let harness_span = span;
301             let span = match m {
302                 ProcMacro::Derive(m) => m.span,
303                 ProcMacro::Attr(m) | ProcMacro::Bang(m) => m.span,
304             };
305             let local_path = |cx: &ExtCtxt<'_>, name| cx.expr_path(cx.path(span, vec![name]));
306             let proc_macro_ty_method_path = |cx: &ExtCtxt<'_>, method| {
307                 cx.expr_path(cx.path(
308                     span.with_ctxt(harness_span.ctxt()),
309                     vec![proc_macro, bridge, client, proc_macro_ty, method],
310                 ))
311             };
312             match m {
313                 ProcMacro::Derive(cd) => {
314                     cx.resolver.declare_proc_macro(cd.id);
315                     cx.expr_call(
316                         span,
317                         proc_macro_ty_method_path(cx, custom_derive),
318                         vec![
319                             cx.expr_str(span, cd.trait_name),
320                             cx.expr_array_ref(
321                                 span,
322                                 cd.attrs.iter().map(|&s| cx.expr_str(span, s)).collect::<Vec<_>>(),
323                             ),
324                             local_path(cx, cd.function_name),
325                         ],
326                     )
327                 }
328                 ProcMacro::Attr(ca) | ProcMacro::Bang(ca) => {
329                     cx.resolver.declare_proc_macro(ca.id);
330                     let ident = match m {
331                         ProcMacro::Attr(_) => attr,
332                         ProcMacro::Bang(_) => bang,
333                         ProcMacro::Derive(_) => unreachable!(),
334                     };
335
336                     cx.expr_call(
337                         span,
338                         proc_macro_ty_method_path(cx, ident),
339                         vec![
340                             cx.expr_str(span, ca.function_name.name),
341                             local_path(cx, ca.function_name),
342                         ],
343                     )
344                 }
345             }
346         })
347         .collect();
348
349     let decls_static = cx
350         .item_static(
351             span,
352             Ident::new(sym::_DECLS, span),
353             cx.ty_rptr(
354                 span,
355                 cx.ty(
356                     span,
357                     ast::TyKind::Slice(
358                         cx.ty_path(cx.path(span, vec![proc_macro, bridge, client, proc_macro_ty])),
359                     ),
360                 ),
361                 None,
362                 ast::Mutability::Not,
363             ),
364             ast::Mutability::Not,
365             cx.expr_array_ref(span, decls),
366         )
367         .map(|mut i| {
368             let attr = cx.meta_word(span, sym::rustc_proc_macro_decls);
369             i.attrs.push(cx.attribute(attr));
370
371             let deprecated_attr = attr::mk_nested_word_item(Ident::new(sym::deprecated, span));
372             let allow_deprecated_attr =
373                 attr::mk_list_item(Ident::new(sym::allow, span), vec![deprecated_attr]);
374             i.attrs.push(cx.attribute(allow_deprecated_attr));
375
376             i
377         });
378
379     let block = cx.expr_block(
380         cx.block(span, vec![cx.stmt_item(span, krate), cx.stmt_item(span, decls_static)]),
381     );
382
383     let anon_constant = cx.item_const(
384         span,
385         Ident::new(kw::Underscore, span),
386         cx.ty(span, ast::TyKind::Tup(Vec::new())),
387         block,
388     );
389
390     // Integrate the new item into existing module structures.
391     let items = AstFragment::Items(smallvec![anon_constant]);
392     cx.monotonic_expander().fully_expand_fragment(items).make_items().pop().unwrap()
393 }