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;
15 struct ProcMacroDerive {
30 Derive(ProcMacroDerive),
35 struct CollectProcMacros<'a> {
37 macros: Vec<ProcMacro>,
39 handler: &'a rustc_errors::Handler,
40 source_map: &'a SourceMap,
41 is_proc_macro_crate: bool,
47 resolver: &mut dyn ResolverExpand,
48 mut krate: ast::Crate,
49 is_proc_macro_crate: bool,
50 has_proc_macro_decls: bool,
52 handler: &rustc_errors::Handler,
54 let ecfg = ExpansionConfig::default("proc_macro".to_string());
55 let mut cx = ExtCtxt::new(sess, ecfg, resolver, None);
57 let mut collect = CollectProcMacros {
62 source_map: sess.source_map(),
67 if has_proc_macro_decls || is_proc_macro_crate {
68 visit::walk_crate(&mut collect, &krate);
70 let macros = collect.macros;
72 if !is_proc_macro_crate {
80 let decls = mk_decls(&mut cx, ¯os);
81 krate.items.push(decls);
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(
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]`",
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 {
103 if self.in_root && item.vis.kind.is_pub() {
104 self.macros.push(ProcMacro::Derive(ProcMacroDerive {
108 function_name: item.ident,
112 let msg = if !self.in_root {
113 "functions tagged with `#[proc_macro_derive]` must \
114 currently reside in the root of the crate"
116 "functions tagged with `#[proc_macro_derive]` must be `pub`"
118 self.handler.span_err(self.source_map.guess_head_span(item.span), msg);
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 {
127 function_name: item.ident,
130 let msg = if !self.in_root {
131 "functions tagged with `#[proc_macro_attribute]` must \
132 currently reside in the root of the crate"
134 "functions tagged with `#[proc_macro_attribute]` must be `pub`"
136 self.handler.span_err(self.source_map.guess_head_span(item.span), msg);
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 {
145 function_name: item.ident,
148 let msg = if !self.in_root {
149 "functions tagged with `#[proc_macro]` must \
150 currently reside in the root of the crate"
152 "functions tagged with `#[proc_macro]` must be `pub`"
154 self.handler.span_err(self.source_map.guess_head_span(item.span), msg);
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) {
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);
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.
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(..));
175 let mut found_attr: Option<&'a ast::Attribute> = None;
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
187 "only one `#[{}]` attribute is allowed on any given function",
192 "`#[{}]` and `#[{}]` attributes cannot both be applied
193 to the same function",
195 pprust::path_to_string(&prev_item.path),
200 .struct_span_err(attr.span, &msg)
201 .span_label(prev_attr.span, "previous attribute here")
207 found_attr = Some(attr);
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;
221 "the `#[{}]` attribute may only be used on bare functions",
222 pprust::path_to_string(&attr.get_normal_item().path),
225 self.handler.span_err(attr.span, &msg);
229 if self.is_test_crate {
233 if !self.is_proc_macro_crate {
235 "the `#[{}]` attribute is only usable with crates of the `proc-macro` crate type",
236 pprust::path_to_string(&attr.get_normal_item().path),
239 self.handler.span_err(attr.span, &msg);
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);
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;
257 // Creates a new module which looks like:
260 // extern crate proc_macro;
262 // use proc_macro::bridge::client::ProcMacro;
264 // #[rustc_proc_macro_decls]
266 // #[allow(deprecated)]
267 // static DECLS: &[ProcMacro] = &[
268 // ProcMacro::custom_derive($name_trait1, &[], ::$name1);
269 // ProcMacro::custom_derive($name_trait2, &["attribute_name"], ::$name2);
273 fn mk_decls(cx: &mut ExtCtxt<'_>, macros: &[ProcMacro]) -> P<ast::Item> {
274 let expn_id = cx.resolver.expansion_for_ast_pass(
276 AstPass::ProcMacroHarness,
277 &[sym::rustc_attrs, sym::proc_macro_internals],
280 let span = DUMMY_SP.with_def_site_ctxt(expn_id.to_expn_id());
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));
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);
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
299 let harness_span = span;
301 ProcMacro::Derive(m) => m.span,
302 ProcMacro::Attr(m) | ProcMacro::Bang(m) => m.span,
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],
312 ProcMacro::Derive(cd) => {
313 cx.resolver.declare_proc_macro(cd.id);
316 proc_macro_ty_method_path(cx, custom_derive),
318 cx.expr_str(span, cd.trait_name),
321 cd.attrs.iter().map(|&s| cx.expr_str(span, s)).collect::<Vec<_>>(),
323 local_path(cx, cd.function_name),
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!(),
337 proc_macro_ty_method_path(cx, ident),
339 cx.expr_str(span, ca.function_name.name),
340 local_path(cx, ca.function_name),
348 let decls_static = cx
351 Ident::new(sym::_DECLS, span),
357 cx.ty_path(cx.path(span, vec![proc_macro, bridge, client, proc_macro_ty])),
361 ast::Mutability::Not,
363 ast::Mutability::Not,
364 cx.expr_array_ref(span, decls),
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));
373 let block = cx.expr_block(
374 cx.block(span, vec![cx.stmt_item(span, krate), cx.stmt_item(span, decls_static)]),
377 let anon_constant = cx.item_const(
379 Ident::new(kw::Underscore, span),
380 cx.ty(span, ast::TyKind::Tup(Vec::new())),
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()