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