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