3 use rustc_ast::ast::{self, Ident, NodeId};
5 use rustc_ast::expand::is_proc_macro_attr;
7 use rustc_ast::visit::{self, Visitor};
8 use rustc_ast_pretty::pprust;
9 use rustc_expand::base::{ExtCtxt, Resolver};
10 use rustc_expand::expand::{AstFragment, ExpansionConfig};
11 use rustc_session::parse::ParseSess;
12 use rustc_span::hygiene::AstPass;
13 use rustc_span::symbol::{kw, sym};
14 use rustc_span::{Span, DUMMY_SP};
15 use smallvec::smallvec;
16 use std::cell::RefCell;
18 struct ProcMacroDerive {
20 trait_name: ast::Name,
23 attrs: Vec<ast::Name>,
26 enum ProcMacroDefType {
35 def_type: ProcMacroDefType,
39 Derive(ProcMacroDerive),
43 struct CollectProcMacros<'a> {
44 macros: Vec<ProcMacro>,
46 handler: &'a rustc_errors::Handler,
47 is_proc_macro_crate: bool,
53 resolver: &mut dyn Resolver,
54 mut krate: ast::Crate,
55 is_proc_macro_crate: bool,
56 has_proc_macro_decls: bool,
58 num_crate_types: usize,
59 handler: &rustc_errors::Handler,
61 let ecfg = ExpansionConfig::default("proc_macro".to_string());
62 let mut cx = ExtCtxt::new(sess, ecfg, resolver);
64 let mut collect = CollectProcMacros {
72 if has_proc_macro_decls || is_proc_macro_crate {
73 visit::walk_crate(&mut collect, &krate);
75 let macros = collect.macros;
77 if !is_proc_macro_crate {
81 if num_crate_types > 1 {
82 handler.err("cannot mix `proc-macro` crate type with others");
89 let decls = mk_decls(&mut krate, &mut cx, ¯os);
90 krate.module.items.push(decls);
95 impl<'a> CollectProcMacros<'a> {
96 fn check_not_pub_in_root(&self, vis: &ast::Visibility, sp: Span) {
97 if self.is_proc_macro_crate && self.in_root && vis.node.is_pub() {
98 self.handler.span_err(
100 "`proc-macro` crate types currently cannot export any items other \
101 than functions tagged with `#[proc_macro]`, `#[proc_macro_derive]`, \
102 or `#[proc_macro_attribute]`",
107 fn collect_custom_derive(&mut self, item: &'a ast::Item, attr: &'a ast::Attribute) {
108 // Once we've located the `#[proc_macro_derive]` attribute, verify
109 // that it's of the form `#[proc_macro_derive(Foo)]` or
110 // `#[proc_macro_derive(Foo, attributes(A, ..))]`
111 let list = match attr.meta_item_list() {
115 if list.len() != 1 && list.len() != 2 {
116 self.handler.span_err(attr.span, "attribute must have either one or two arguments");
119 let trait_attr = match list[0].meta_item() {
120 Some(meta_item) => meta_item,
122 self.handler.span_err(list[0].span(), "not a meta item");
126 let trait_ident = match trait_attr.ident() {
127 Some(trait_ident) if trait_attr.is_word() => trait_ident,
129 self.handler.span_err(trait_attr.span, "must only be one word");
134 if !trait_ident.name.can_be_raw() {
135 self.handler.span_err(
137 &format!("`{}` cannot be a name of derive macro", trait_ident),
141 let attributes_attr = list.get(1);
142 let proc_attrs: Vec<_> = if let Some(attr) = attributes_attr {
143 if !attr.check_name(sym::attributes) {
144 self.handler.span_err(attr.span(), "second argument must be `attributes`")
146 attr.meta_item_list()
149 .span_err(attr.span(), "attribute must be of form: `attributes(foo, bar)`");
154 let attr = match attr.meta_item() {
155 Some(meta_item) => meta_item,
157 self.handler.span_err(attr.span(), "not a meta item");
162 let ident = match attr.ident() {
163 Some(ident) if attr.is_word() => ident,
165 self.handler.span_err(attr.span, "must only be one word");
169 if !ident.name.can_be_raw() {
170 self.handler.span_err(
172 &format!("`{}` cannot be a name of derive helper attribute", ident),
183 if self.in_root && item.vis.node.is_pub() {
184 self.macros.push(ProcMacro::Derive(ProcMacroDerive {
187 trait_name: trait_ident.name,
188 function_name: item.ident,
192 let msg = if !self.in_root {
193 "functions tagged with `#[proc_macro_derive]` must \
194 currently reside in the root of the crate"
196 "functions tagged with `#[proc_macro_derive]` must be `pub`"
198 self.handler.span_err(item.span, msg);
202 fn collect_attr_proc_macro(&mut self, item: &'a ast::Item) {
203 if self.in_root && item.vis.node.is_pub() {
204 self.macros.push(ProcMacro::Def(ProcMacroDef {
207 function_name: item.ident,
208 def_type: ProcMacroDefType::Attr,
211 let msg = if !self.in_root {
212 "functions tagged with `#[proc_macro_attribute]` must \
213 currently reside in the root of the crate"
215 "functions tagged with `#[proc_macro_attribute]` must be `pub`"
217 self.handler.span_err(item.span, msg);
221 fn collect_bang_proc_macro(&mut self, item: &'a ast::Item) {
222 if self.in_root && item.vis.node.is_pub() {
223 self.macros.push(ProcMacro::Def(ProcMacroDef {
226 function_name: item.ident,
227 def_type: ProcMacroDefType::Bang,
230 let msg = if !self.in_root {
231 "functions tagged with `#[proc_macro]` must \
232 currently reside in the root of the crate"
234 "functions tagged with `#[proc_macro]` must be `pub`"
236 self.handler.span_err(item.span, msg);
241 impl<'a> Visitor<'a> for CollectProcMacros<'a> {
242 fn visit_item(&mut self, item: &'a ast::Item) {
243 if let ast::ItemKind::MacroDef(..) = item.kind {
244 if self.is_proc_macro_crate && attr::contains_name(&item.attrs, sym::macro_export) {
246 "cannot export macro_rules! macros from a `proc-macro` crate type currently";
247 self.handler.span_err(item.span, msg);
251 // First up, make sure we're checking a bare function. If we're not then
252 // we're just not interested in this item.
254 // If we find one, try to locate a `#[proc_macro_derive]` attribute on it.
255 let is_fn = match item.kind {
256 ast::ItemKind::Fn(..) => true,
260 let mut found_attr: Option<&'a ast::Attribute> = None;
262 for attr in &item.attrs {
263 if is_proc_macro_attr(&attr) {
264 if let Some(prev_attr) = found_attr {
265 let prev_item = prev_attr.get_normal_item();
266 let item = attr.get_normal_item();
267 let path_str = pprust::path_to_string(&item.path);
268 let msg = if item.path.segments[0].ident.name
269 == prev_item.path.segments[0].ident.name
272 "only one `#[{}]` attribute is allowed on any given function",
277 "`#[{}]` and `#[{}]` attributes cannot both be applied
278 to the same function",
280 pprust::path_to_string(&prev_item.path),
285 .struct_span_err(attr.span, &msg)
286 .span_label(prev_attr.span, "previous attribute here")
292 found_attr = Some(attr);
296 let attr = match found_attr {
298 self.check_not_pub_in_root(&item.vis, item.span);
299 let prev_in_root = mem::replace(&mut self.in_root, false);
300 visit::walk_item(self, item);
301 self.in_root = prev_in_root;
309 "the `#[{}]` attribute may only be used on bare functions",
310 pprust::path_to_string(&attr.get_normal_item().path),
313 self.handler.span_err(attr.span, &msg);
317 if self.is_test_crate {
321 if !self.is_proc_macro_crate {
323 "the `#[{}]` attribute is only usable with crates of the `proc-macro` crate type",
324 pprust::path_to_string(&attr.get_normal_item().path),
327 self.handler.span_err(attr.span, &msg);
331 if attr.check_name(sym::proc_macro_derive) {
332 self.collect_custom_derive(item, attr);
333 } else if attr.check_name(sym::proc_macro_attribute) {
334 self.collect_attr_proc_macro(item);
335 } else if attr.check_name(sym::proc_macro) {
336 self.collect_bang_proc_macro(item);
339 let prev_in_root = mem::replace(&mut self.in_root, false);
340 visit::walk_item(self, item);
341 self.in_root = prev_in_root;
344 fn visit_mac(&mut self, mac: &'a ast::Mac) {
345 visit::walk_mac(self, mac)
349 // Creates a new module which looks like:
352 // extern crate proc_macro;
354 // use proc_macro::bridge::client::ProcMacro;
356 // #[rustc_proc_macro_decls]
357 // #[allow(deprecated)]
358 // static DECLS: &[ProcMacro] = &[
359 // ProcMacro::custom_derive($name_trait1, &[], ::$name1);
360 // ProcMacro::custom_derive($name_trait2, &["attribute_name"], ::$name2);
365 ast_krate: &mut ast::Crate,
366 cx: &mut ExtCtxt<'_>,
367 macros: &[ProcMacro],
369 // We're the ones filling in this Vec,
370 // so it should be empty to start with
371 assert!(ast_krate.proc_macros.is_empty());
373 let expn_id = cx.resolver.expansion_for_ast_pass(
375 AstPass::ProcMacroHarness,
376 &[sym::rustc_attrs, sym::proc_macro_internals],
379 let span = DUMMY_SP.with_def_site_ctxt(expn_id);
381 let proc_macro = Ident::new(sym::proc_macro, span);
382 let krate = cx.item(span, proc_macro, Vec::new(), ast::ItemKind::ExternCrate(None));
384 let bridge = cx.ident_of("bridge", span);
385 let client = cx.ident_of("client", span);
386 let proc_macro_ty = cx.ident_of("ProcMacro", span);
387 let custom_derive = cx.ident_of("custom_derive", span);
388 let attr = cx.ident_of("attr", span);
389 let bang = cx.ident_of("bang", span);
391 let krate_ref = RefCell::new(ast_krate);
393 // We add NodeIds to 'krate.proc_macros' in the order
394 // that we generate expressions. The position of each NodeId
395 // in the 'proc_macros' Vec corresponds to its position
396 // in the static array that will be generated
399 |sp: Span, name| cx.expr_path(cx.path(sp.with_ctxt(span.ctxt()), vec![name]));
400 let proc_macro_ty_method_path = |method| {
401 cx.expr_path(cx.path(span, vec![proc_macro, bridge, client, proc_macro_ty, method]))
406 ProcMacro::Derive(cd) => {
407 krate_ref.borrow_mut().proc_macros.push(cd.id);
410 proc_macro_ty_method_path(custom_derive),
412 cx.expr_str(cd.span, cd.trait_name),
417 .map(|&s| cx.expr_str(cd.span, s))
418 .collect::<Vec<_>>(),
420 local_path(cd.span, cd.function_name),
424 ProcMacro::Def(ca) => {
425 krate_ref.borrow_mut().proc_macros.push(ca.id);
426 let ident = match ca.def_type {
427 ProcMacroDefType::Attr => attr,
428 ProcMacroDefType::Bang => bang,
433 proc_macro_ty_method_path(ident),
435 cx.expr_str(ca.span, ca.function_name.name),
436 local_path(ca.span, ca.function_name),
444 let decls_static = cx
447 cx.ident_of("_DECLS", span),
453 cx.ty_path(cx.path(span, vec![proc_macro, bridge, client, proc_macro_ty])),
457 ast::Mutability::Not,
459 ast::Mutability::Not,
460 cx.expr_vec_slice(span, decls),
463 let attr = cx.meta_word(span, sym::rustc_proc_macro_decls);
464 i.attrs.push(cx.attribute(attr));
466 let deprecated_attr = attr::mk_nested_word_item(Ident::new(sym::deprecated, span));
467 let allow_deprecated_attr =
468 attr::mk_list_item(Ident::new(sym::allow, span), vec![deprecated_attr]);
469 i.attrs.push(cx.attribute(allow_deprecated_attr));
474 let block = cx.expr_block(
475 cx.block(span, vec![cx.stmt_item(span, krate), cx.stmt_item(span, decls_static)]),
478 let anon_constant = cx.item_const(
480 ast::Ident::new(kw::Underscore, span),
481 cx.ty(span, ast::TyKind::Tup(Vec::new())),
485 // Integrate the new item into existing module structures.
486 let items = AstFragment::Items(smallvec![anon_constant]);
487 cx.monotonic_expander().fully_expand_fragment(items).make_items().pop().unwrap()