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;
17 struct ProcMacroDerive {
32 Derive(ProcMacroDerive),
37 struct CollectProcMacros<'a> {
39 macros: Vec<ProcMacro>,
41 handler: &'a rustc_errors::Handler,
42 source_map: &'a SourceMap,
43 is_proc_macro_crate: bool,
49 resolver: &mut dyn ResolverExpand,
50 mut krate: ast::Crate,
51 is_proc_macro_crate: bool,
52 has_proc_macro_decls: bool,
54 handler: &rustc_errors::Handler,
56 let ecfg = ExpansionConfig::default("proc_macro".to_string());
57 let mut cx = ExtCtxt::new(sess, ecfg, resolver, None);
59 let mut collect = CollectProcMacros {
64 source_map: sess.source_map(),
69 if has_proc_macro_decls || is_proc_macro_crate {
70 visit::walk_crate(&mut collect, &krate);
72 let macros = collect.macros;
74 if !is_proc_macro_crate {
82 let decls = mk_decls(&mut cx, ¯os);
83 krate.items.push(decls);
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(
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]`",
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 {
105 if self.in_root && item.vis.kind.is_pub() {
106 self.macros.push(ProcMacro::Derive(ProcMacroDerive {
110 function_name: item.ident,
114 let msg = if !self.in_root {
115 "functions tagged with `#[proc_macro_derive]` must \
116 currently reside in the root of the crate"
118 "functions tagged with `#[proc_macro_derive]` must be `pub`"
120 self.handler.span_err(self.source_map.guess_head_span(item.span), msg);
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 {
129 function_name: item.ident,
132 let msg = if !self.in_root {
133 "functions tagged with `#[proc_macro_attribute]` must \
134 currently reside in the root of the crate"
136 "functions tagged with `#[proc_macro_attribute]` must be `pub`"
138 self.handler.span_err(self.source_map.guess_head_span(item.span), msg);
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 {
147 function_name: item.ident,
150 let msg = if !self.in_root {
151 "functions tagged with `#[proc_macro]` must \
152 currently reside in the root of the crate"
154 "functions tagged with `#[proc_macro]` must be `pub`"
156 self.handler.span_err(self.source_map.guess_head_span(item.span), msg);
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) {
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);
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.
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(..));
177 let mut found_attr: Option<&'a ast::Attribute> = None;
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
189 "only one `#[{}]` attribute is allowed on any given function",
194 "`#[{}]` and `#[{}]` attributes cannot both be applied
195 to the same function",
197 pprust::path_to_string(&prev_item.path),
202 .struct_span_err(attr.span, &msg)
203 .span_label(prev_attr.span, "previous attribute here")
209 found_attr = Some(attr);
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;
223 "the `#[{}]` attribute may only be used on bare functions",
224 pprust::path_to_string(&attr.get_normal_item().path),
227 self.handler.span_err(attr.span, &msg);
231 if self.is_test_crate {
235 if !self.is_proc_macro_crate {
237 "the `#[{}]` attribute is only usable with crates of the `proc-macro` crate type",
238 pprust::path_to_string(&attr.get_normal_item().path),
241 self.handler.span_err(attr.span, &msg);
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);
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;
259 // Creates a new module which looks like:
262 // extern crate proc_macro;
264 // use proc_macro::bridge::client::ProcMacro;
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);
274 fn mk_decls(cx: &mut ExtCtxt<'_>, macros: &[ProcMacro]) -> P<ast::Item> {
275 let expn_id = cx.resolver.expansion_for_ast_pass(
277 AstPass::ProcMacroHarness,
278 &[sym::rustc_attrs, sym::proc_macro_internals],
281 let span = DUMMY_SP.with_def_site_ctxt(expn_id.to_expn_id());
283 let proc_macro = Ident::new(sym::proc_macro, span);
284 let krate = cx.item(span, proc_macro, Vec::new(), ast::ItemKind::ExternCrate(None));
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);
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
300 let harness_span = span;
302 ProcMacro::Derive(m) => m.span,
303 ProcMacro::Attr(m) | ProcMacro::Bang(m) => m.span,
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],
313 ProcMacro::Derive(cd) => {
314 cx.resolver.declare_proc_macro(cd.id);
317 proc_macro_ty_method_path(cx, custom_derive),
319 cx.expr_str(span, cd.trait_name),
322 cd.attrs.iter().map(|&s| cx.expr_str(span, s)).collect::<Vec<_>>(),
324 local_path(cx, cd.function_name),
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!(),
338 proc_macro_ty_method_path(cx, ident),
340 cx.expr_str(span, ca.function_name.name),
341 local_path(cx, ca.function_name),
349 let decls_static = cx
352 Ident::new(sym::_DECLS, span),
358 cx.ty_path(cx.path(span, vec![proc_macro, bridge, client, proc_macro_ty])),
362 ast::Mutability::Not,
364 ast::Mutability::Not,
365 cx.expr_array_ref(span, decls),
368 let attr = cx.meta_word(span, sym::rustc_proc_macro_decls);
369 i.attrs.push(cx.attribute(attr));
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));
379 let block = cx.expr_block(
380 cx.block(span, vec![cx.stmt_item(span, krate), cx.stmt_item(span, decls_static)]),
383 let anon_constant = cx.item_const(
385 Ident::new(kw::Underscore, span),
386 cx.ty(span, ast::TyKind::Tup(Vec::new())),
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()