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::{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 use std::cell::RefCell;
18 struct ProcMacroDerive {
26 enum ProcMacroDefType {
35 def_type: ProcMacroDefType,
39 Derive(ProcMacroDerive),
43 struct CollectProcMacros<'a> {
45 macros: Vec<ProcMacro>,
47 handler: &'a rustc_errors::Handler,
48 source_map: &'a SourceMap,
49 is_proc_macro_crate: bool,
55 resolver: &mut dyn ResolverExpand,
56 mut krate: ast::Crate,
57 is_proc_macro_crate: bool,
58 has_proc_macro_decls: bool,
60 num_crate_types: usize,
61 handler: &rustc_errors::Handler,
63 let ecfg = ExpansionConfig::default("proc_macro".to_string());
64 let mut cx = ExtCtxt::new(sess, ecfg, resolver, None);
66 let mut collect = CollectProcMacros {
71 source_map: sess.source_map(),
76 if has_proc_macro_decls || is_proc_macro_crate {
77 visit::walk_crate(&mut collect, &krate);
79 let macros = collect.macros;
81 if !is_proc_macro_crate {
85 if num_crate_types > 1 {
86 handler.err("cannot mix `proc-macro` crate type with others");
93 let decls = mk_decls(&mut krate, &mut cx, ¯os);
94 krate.items.push(decls);
99 impl<'a> CollectProcMacros<'a> {
100 fn check_not_pub_in_root(&self, vis: &ast::Visibility, sp: Span) {
101 if self.is_proc_macro_crate && self.in_root && vis.kind.is_pub() {
102 self.handler.span_err(
104 "`proc-macro` crate types currently cannot export any items other \
105 than functions tagged with `#[proc_macro]`, `#[proc_macro_derive]`, \
106 or `#[proc_macro_attribute]`",
111 fn collect_custom_derive(&mut self, item: &'a ast::Item, attr: &'a ast::Attribute) {
112 // Once we've located the `#[proc_macro_derive]` attribute, verify
113 // that it's of the form `#[proc_macro_derive(Foo)]` or
114 // `#[proc_macro_derive(Foo, attributes(A, ..))]`
115 let list = match attr.meta_item_list() {
119 if list.len() != 1 && list.len() != 2 {
120 self.handler.span_err(attr.span, "attribute must have either one or two arguments");
123 let trait_attr = match list[0].meta_item() {
124 Some(meta_item) => meta_item,
126 self.handler.span_err(list[0].span(), "not a meta item");
130 let trait_ident = match trait_attr.ident() {
131 Some(trait_ident) if trait_attr.is_word() => trait_ident,
133 self.handler.span_err(trait_attr.span, "must only be one word");
138 if !trait_ident.name.can_be_raw() {
139 self.handler.span_err(
141 &format!("`{}` cannot be a name of derive macro", trait_ident),
145 let attributes_attr = list.get(1);
146 let proc_attrs: Vec<_> = if let Some(attr) = attributes_attr {
147 if !attr.has_name(sym::attributes) {
148 self.handler.span_err(attr.span(), "second argument must be `attributes`")
150 attr.meta_item_list()
153 .span_err(attr.span(), "attribute must be of form: `attributes(foo, bar)`");
158 let attr = match attr.meta_item() {
159 Some(meta_item) => meta_item,
161 self.handler.span_err(attr.span(), "not a meta item");
166 let ident = match attr.ident() {
167 Some(ident) if attr.is_word() => ident,
169 self.handler.span_err(attr.span, "must only be one word");
173 if !ident.name.can_be_raw() {
174 self.handler.span_err(
176 &format!("`{}` cannot be a name of derive helper attribute", ident),
187 if self.in_root && item.vis.kind.is_pub() {
188 self.macros.push(ProcMacro::Derive(ProcMacroDerive {
191 trait_name: trait_ident.name,
192 function_name: item.ident,
196 let msg = if !self.in_root {
197 "functions tagged with `#[proc_macro_derive]` must \
198 currently reside in the root of the crate"
200 "functions tagged with `#[proc_macro_derive]` must be `pub`"
202 self.handler.span_err(self.source_map.guess_head_span(item.span), msg);
206 fn collect_attr_proc_macro(&mut self, item: &'a ast::Item) {
207 if self.in_root && item.vis.kind.is_pub() {
208 self.macros.push(ProcMacro::Def(ProcMacroDef {
211 function_name: item.ident,
212 def_type: ProcMacroDefType::Attr,
215 let msg = if !self.in_root {
216 "functions tagged with `#[proc_macro_attribute]` must \
217 currently reside in the root of the crate"
219 "functions tagged with `#[proc_macro_attribute]` must be `pub`"
221 self.handler.span_err(self.source_map.guess_head_span(item.span), msg);
225 fn collect_bang_proc_macro(&mut self, item: &'a ast::Item) {
226 if self.in_root && item.vis.kind.is_pub() {
227 self.macros.push(ProcMacro::Def(ProcMacroDef {
230 function_name: item.ident,
231 def_type: ProcMacroDefType::Bang,
234 let msg = if !self.in_root {
235 "functions tagged with `#[proc_macro]` must \
236 currently reside in the root of the crate"
238 "functions tagged with `#[proc_macro]` must be `pub`"
240 self.handler.span_err(self.source_map.guess_head_span(item.span), msg);
245 impl<'a> Visitor<'a> for CollectProcMacros<'a> {
246 fn visit_item(&mut self, item: &'a ast::Item) {
247 if let ast::ItemKind::MacroDef(..) = item.kind {
248 if self.is_proc_macro_crate && self.sess.contains_name(&item.attrs, sym::macro_export) {
250 "cannot export macro_rules! macros from a `proc-macro` crate type currently";
251 self.handler.span_err(self.source_map.guess_head_span(item.span), msg);
255 // First up, make sure we're checking a bare function. If we're not then
256 // we're just not interested in this item.
258 // If we find one, try to locate a `#[proc_macro_derive]` attribute on it.
259 let is_fn = matches!(item.kind, ast::ItemKind::Fn(..));
261 let mut found_attr: Option<&'a ast::Attribute> = None;
263 for attr in &item.attrs {
264 if self.sess.is_proc_macro_attr(&attr) {
265 if let Some(prev_attr) = found_attr {
266 let prev_item = prev_attr.get_normal_item();
267 let item = attr.get_normal_item();
268 let path_str = pprust::path_to_string(&item.path);
269 let msg = if item.path.segments[0].ident.name
270 == prev_item.path.segments[0].ident.name
273 "only one `#[{}]` attribute is allowed on any given function",
278 "`#[{}]` and `#[{}]` attributes cannot both be applied
279 to the same function",
281 pprust::path_to_string(&prev_item.path),
286 .struct_span_err(attr.span, &msg)
287 .span_label(prev_attr.span, "previous attribute here")
293 found_attr = Some(attr);
297 let attr = match found_attr {
299 self.check_not_pub_in_root(&item.vis, self.source_map.guess_head_span(item.span));
300 let prev_in_root = mem::replace(&mut self.in_root, false);
301 visit::walk_item(self, item);
302 self.in_root = prev_in_root;
310 "the `#[{}]` attribute may only be used on bare functions",
311 pprust::path_to_string(&attr.get_normal_item().path),
314 self.handler.span_err(attr.span, &msg);
318 if self.is_test_crate {
322 if !self.is_proc_macro_crate {
324 "the `#[{}]` attribute is only usable with crates of the `proc-macro` crate type",
325 pprust::path_to_string(&attr.get_normal_item().path),
328 self.handler.span_err(attr.span, &msg);
332 if self.sess.check_name(attr, sym::proc_macro_derive) {
333 self.collect_custom_derive(item, attr);
334 } else if self.sess.check_name(attr, sym::proc_macro_attribute) {
335 self.collect_attr_proc_macro(item);
336 } else if self.sess.check_name(attr, sym::proc_macro) {
337 self.collect_bang_proc_macro(item);
340 let prev_in_root = mem::replace(&mut self.in_root, false);
341 visit::walk_item(self, item);
342 self.in_root = prev_in_root;
346 // Creates a new module which looks like:
349 // extern crate proc_macro;
351 // use proc_macro::bridge::client::ProcMacro;
353 // #[rustc_proc_macro_decls]
354 // #[allow(deprecated)]
355 // static DECLS: &[ProcMacro] = &[
356 // ProcMacro::custom_derive($name_trait1, &[], ::$name1);
357 // ProcMacro::custom_derive($name_trait2, &["attribute_name"], ::$name2);
362 ast_krate: &mut ast::Crate,
363 cx: &mut ExtCtxt<'_>,
364 macros: &[ProcMacro],
366 // We're the ones filling in this Vec,
367 // so it should be empty to start with
368 assert!(ast_krate.proc_macros.is_empty());
370 let expn_id = cx.resolver.expansion_for_ast_pass(
372 AstPass::ProcMacroHarness,
373 &[sym::rustc_attrs, sym::proc_macro_internals],
376 let span = DUMMY_SP.with_def_site_ctxt(expn_id);
378 let proc_macro = Ident::new(sym::proc_macro, span);
379 let krate = cx.item(span, proc_macro, Vec::new(), ast::ItemKind::ExternCrate(None));
381 let bridge = Ident::new(sym::bridge, span);
382 let client = Ident::new(sym::client, span);
383 let proc_macro_ty = Ident::new(sym::ProcMacro, span);
384 let custom_derive = Ident::new(sym::custom_derive, span);
385 let attr = Ident::new(sym::attr, span);
386 let bang = Ident::new(sym::bang, span);
388 let krate_ref = RefCell::new(ast_krate);
390 // We add NodeIds to 'krate.proc_macros' in the order
391 // that we generate expressions. The position of each NodeId
392 // in the 'proc_macros' Vec corresponds to its position
393 // in the static array that will be generated
396 |sp: Span, name| cx.expr_path(cx.path(sp.with_ctxt(span.ctxt()), vec![name]));
397 let proc_macro_ty_method_path = |method| {
398 cx.expr_path(cx.path(span, vec![proc_macro, bridge, client, proc_macro_ty, method]))
403 ProcMacro::Derive(cd) => {
404 krate_ref.borrow_mut().proc_macros.push(cd.id);
407 proc_macro_ty_method_path(custom_derive),
409 cx.expr_str(cd.span, cd.trait_name),
414 .map(|&s| cx.expr_str(cd.span, s))
415 .collect::<Vec<_>>(),
417 local_path(cd.span, cd.function_name),
421 ProcMacro::Def(ca) => {
422 krate_ref.borrow_mut().proc_macros.push(ca.id);
423 let ident = match ca.def_type {
424 ProcMacroDefType::Attr => attr,
425 ProcMacroDefType::Bang => bang,
430 proc_macro_ty_method_path(ident),
432 cx.expr_str(ca.span, ca.function_name.name),
433 local_path(ca.span, ca.function_name),
441 let decls_static = cx
444 Ident::new(sym::_DECLS, span),
450 cx.ty_path(cx.path(span, vec![proc_macro, bridge, client, proc_macro_ty])),
454 ast::Mutability::Not,
456 ast::Mutability::Not,
457 cx.expr_vec_slice(span, decls),
460 let attr = cx.meta_word(span, sym::rustc_proc_macro_decls);
461 i.attrs.push(cx.attribute(attr));
463 let deprecated_attr = attr::mk_nested_word_item(Ident::new(sym::deprecated, span));
464 let allow_deprecated_attr =
465 attr::mk_list_item(Ident::new(sym::allow, span), vec![deprecated_attr]);
466 i.attrs.push(cx.attribute(allow_deprecated_attr));
471 let block = cx.expr_block(
472 cx.block(span, vec![cx.stmt_item(span, krate), cx.stmt_item(span, decls_static)]),
475 let anon_constant = cx.item_const(
477 Ident::new(kw::Underscore, span),
478 cx.ty(span, ast::TyKind::Tup(Vec::new())),
482 // Integrate the new item into existing module structures.
483 let items = AstFragment::Items(smallvec![anon_constant]);
484 cx.monotonic_expander().fully_expand_fragment(items).make_items().pop().unwrap()