1 // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
15 use syntax::ast::{self, Ident, NodeId};
16 use syntax::codemap::{ExpnInfo, NameAndSpan, MacroAttribute};
17 use syntax::ext::base::ExtCtxt;
18 use syntax::ext::build::AstBuilder;
19 use syntax::ext::expand::ExpansionConfig;
20 use syntax::ext::hygiene::{Mark, SyntaxContext};
21 use syntax::fold::Folder;
22 use syntax::parse::ParseSess;
24 use syntax::symbol::Symbol;
25 use syntax::visit::{self, Visitor};
27 use syntax_pos::{Span, DUMMY_SP};
31 const PROC_MACRO_KINDS: [&'static str; 3] =
32 ["proc_macro_derive", "proc_macro_attribute", "proc_macro"];
34 struct ProcMacroDerive {
35 trait_name: ast::Name,
38 attrs: Vec<ast::Name>,
46 struct CollectProcMacros<'a> {
47 derives: Vec<ProcMacroDerive>,
48 attr_macros: Vec<ProcMacroDef>,
49 bang_macros: Vec<ProcMacroDef>,
51 handler: &'a errors::Handler,
52 is_proc_macro_crate: bool,
56 pub fn modify(sess: &ParseSess,
57 resolver: &mut ::syntax::ext::base::Resolver,
58 mut krate: ast::Crate,
59 is_proc_macro_crate: bool,
61 num_crate_types: usize,
62 handler: &errors::Handler) -> ast::Crate {
63 let ecfg = ExpansionConfig::default("proc_macro".to_string());
64 let mut cx = ExtCtxt::new(sess, ecfg, resolver);
66 let (derives, attr_macros, bang_macros) = {
67 let mut collect = CollectProcMacros {
69 attr_macros: Vec::new(),
70 bang_macros: Vec::new(),
73 is_proc_macro_crate: is_proc_macro_crate,
74 is_test_crate: is_test_crate,
76 visit::walk_crate(&mut collect, &krate);
77 (collect.derives, collect.attr_macros, collect.bang_macros)
80 if !is_proc_macro_crate {
84 if num_crate_types > 1 {
85 handler.err("cannot mix `proc-macro` crate type with others");
92 krate.module.items.push(mk_registrar(&mut cx, &derives, &attr_macros, &bang_macros));
97 fn is_proc_macro_attr(attr: &ast::Attribute) -> bool {
98 PROC_MACRO_KINDS.iter().any(|kind| attr.check_name(kind))
101 impl<'a> CollectProcMacros<'a> {
102 fn check_not_pub_in_root(&self, vis: &ast::Visibility, sp: Span) {
103 if self.is_proc_macro_crate &&
105 *vis == ast::Visibility::Public {
106 self.handler.span_err(sp,
107 "`proc-macro` crate types cannot \
108 export any items other than functions \
109 tagged with `#[proc_macro_derive]` currently");
113 fn collect_custom_derive(&mut self, item: &'a ast::Item, attr: &'a ast::Attribute) {
114 // Once we've located the `#[proc_macro_derive]` attribute, verify
115 // that it's of the form `#[proc_macro_derive(Foo)]` or
116 // `#[proc_macro_derive(Foo, attributes(A, ..))]`
117 let list = match attr.meta_item_list() {
120 self.handler.span_err(attr.span(),
121 "attribute must be of form: \
122 #[proc_macro_derive(TraitName)]");
126 if list.len() != 1 && list.len() != 2 {
127 self.handler.span_err(attr.span(),
128 "attribute must have either one or two arguments");
131 let trait_attr = &list[0];
132 let attributes_attr = list.get(1);
133 let trait_name = match trait_attr.name() {
136 self.handler.span_err(trait_attr.span(), "not a meta item");
140 if !trait_attr.is_word() {
141 self.handler.span_err(trait_attr.span(), "must only be one word");
144 if deriving::is_builtin_trait(trait_name) {
145 self.handler.span_err(trait_attr.span(),
146 "cannot override a built-in #[derive] mode");
149 if self.derives.iter().any(|d| d.trait_name == trait_name) {
150 self.handler.span_err(trait_attr.span(),
151 "derive mode defined twice in this crate");
154 let proc_attrs: Vec<_> = if let Some(attr) = attributes_attr {
155 if !attr.check_name("attributes") {
156 self.handler.span_err(attr.span(), "second argument must be `attributes`")
158 attr.meta_item_list().unwrap_or_else(|| {
159 self.handler.span_err(attr.span(),
160 "attribute must be of form: \
161 `attributes(foo, bar)`");
163 }).into_iter().filter_map(|attr| {
164 let name = match attr.name() {
167 self.handler.span_err(attr.span(), "not a meta item");
173 self.handler.span_err(attr.span(), "must only be one word");
183 if self.in_root && item.vis == ast::Visibility::Public {
184 self.derives.push(ProcMacroDerive {
186 trait_name: trait_name,
187 function_name: item.ident,
191 let msg = if !self.in_root {
192 "functions tagged with `#[proc_macro_derive]` must \
193 currently reside in the root of the crate"
195 "functions tagged with `#[proc_macro_derive]` must be `pub`"
197 self.handler.span_err(item.span, msg);
201 fn collect_attr_proc_macro(&mut self, item: &'a ast::Item, attr: &'a ast::Attribute) {
202 if let Some(_) = attr.meta_item_list() {
203 self.handler.span_err(attr.span, "`#[proc_macro_attribute]` attribute
204 does not take any arguments");
208 if self.in_root && item.vis == ast::Visibility::Public {
209 self.attr_macros.push(ProcMacroDef {
211 function_name: item.ident,
214 let msg = if !self.in_root {
215 "functions tagged with `#[proc_macro_attribute]` must \
216 currently reside in the root of the crate"
218 "functions tagged with `#[proc_macro_attribute]` must be `pub`"
220 self.handler.span_err(item.span, msg);
224 fn collect_bang_proc_macro(&mut self, item: &'a ast::Item, attr: &'a ast::Attribute) {
225 if let Some(_) = attr.meta_item_list() {
226 self.handler.span_err(attr.span, "`#[proc_macro]` attribute
227 does not take any arguments");
231 if self.in_root && item.vis == ast::Visibility::Public {
232 self.bang_macros.push(ProcMacroDef {
234 function_name: item.ident,
237 let msg = if !self.in_root {
238 "functions tagged with `#[proc_macro]` must \
239 currently reside in the root of the crate"
241 "functions tagged with `#[proc_macro]` must be `pub`"
243 self.handler.span_err(item.span, msg);
248 impl<'a> Visitor<'a> for CollectProcMacros<'a> {
249 fn visit_item(&mut self, item: &'a ast::Item) {
250 if let ast::ItemKind::MacroDef(..) = item.node {
251 if self.is_proc_macro_crate &&
252 item.attrs.iter().any(|attr| attr.path == "macro_export") {
254 "cannot export macro_rules! macros from a `proc-macro` crate type currently";
255 self.handler.span_err(item.span, msg);
259 // First up, make sure we're checking a bare function. If we're not then
260 // we're just not interested in this item.
262 // If we find one, try to locate a `#[proc_macro_derive]` attribute on
264 let is_fn = match item.node {
265 ast::ItemKind::Fn(..) => true,
269 let mut found_attr: Option<&'a ast::Attribute> = None;
271 for attr in &item.attrs {
272 if is_proc_macro_attr(&attr) {
273 if let Some(prev_attr) = found_attr {
274 let msg = if attr.path == prev_attr.path {
275 format!("Only one `#[{}]` attribute is allowed on any given function",
278 format!("`#[{}]` and `#[{}]` attributes cannot both be applied \
279 to the same function", attr.path, prev_attr.path)
282 self.handler.struct_span_err(attr.span(), &msg)
283 .span_note(prev_attr.span(), "Previous attribute here")
289 found_attr = Some(attr);
293 let attr = match found_attr {
295 self.check_not_pub_in_root(&item.vis, item.span);
296 return visit::walk_item(self, item);
302 let msg = format!("the `#[{}]` attribute may only be used on bare functions",
305 self.handler.span_err(attr.span(), &msg);
309 if self.is_test_crate {
313 if !self.is_proc_macro_crate {
314 let msg = format!("the `#[{}]` attribute is only usable with crates of the \
315 `proc-macro` crate type", attr.path);
317 self.handler.span_err(attr.span(), &msg);
321 if attr.check_name("proc_macro_derive") {
322 self.collect_custom_derive(item, attr);
323 } else if attr.check_name("proc_macro_attribute") {
324 self.collect_attr_proc_macro(item, attr);
325 } else if attr.check_name("proc_macro") {
326 self.collect_bang_proc_macro(item, attr);
329 visit::walk_item(self, item);
332 fn visit_mod(&mut self, m: &'a ast::Mod, _s: Span, _a: &[ast::Attribute], id: NodeId) {
333 let mut prev_in_root = self.in_root;
334 if id != ast::CRATE_NODE_ID {
335 prev_in_root = mem::replace(&mut self.in_root, false);
337 visit::walk_mod(self, m);
338 self.in_root = prev_in_root;
341 fn visit_mac(&mut self, mac: &ast::Mac) {
342 visit::walk_mac(self, mac)
346 // Creates a new module which looks like:
349 // extern crate proc_macro;
351 // use proc_macro::__internal::Registry;
353 // #[plugin_registrar]
354 // fn registrar(registrar: &mut Registry) {
355 // registrar.register_custom_derive($name_trait1, ::$name1, &[]);
356 // registrar.register_custom_derive($name_trait2, ::$name2, &["attribute_name"]);
360 fn mk_registrar(cx: &mut ExtCtxt,
361 custom_derives: &[ProcMacroDerive],
362 custom_attrs: &[ProcMacroDef],
363 custom_macros: &[ProcMacroDef]) -> P<ast::Item> {
364 let mark = Mark::fresh(Mark::root());
365 mark.set_expn_info(ExpnInfo {
367 callee: NameAndSpan {
368 format: MacroAttribute(Symbol::intern("proc_macro")),
370 allow_internal_unstable: true,
371 allow_internal_unsafe: false,
374 let span = Span { ctxt: SyntaxContext::empty().apply_mark(mark), ..DUMMY_SP };
376 let proc_macro = Ident::from_str("proc_macro");
377 let krate = cx.item(span,
380 ast::ItemKind::ExternCrate(None));
382 let __internal = Ident::from_str("__internal");
383 let registry = Ident::from_str("Registry");
384 let registrar = Ident::from_str("registrar");
385 let register_custom_derive = Ident::from_str("register_custom_derive");
386 let register_attr_proc_macro = Ident::from_str("register_attr_proc_macro");
387 let register_bang_proc_macro = Ident::from_str("register_bang_proc_macro");
389 let mut stmts = custom_derives.iter().map(|cd| {
390 let path = cx.path_global(cd.span, vec![cd.function_name]);
391 let trait_name = cx.expr_str(cd.span, cd.trait_name);
392 let attrs = cx.expr_vec_slice(
394 cd.attrs.iter().map(|&s| cx.expr_str(cd.span, s)).collect::<Vec<_>>()
396 let registrar = cx.expr_ident(span, registrar);
397 let ufcs_path = cx.path(span, vec![proc_macro, __internal, registry,
398 register_custom_derive]);
400 cx.stmt_expr(cx.expr_call(span, cx.expr_path(ufcs_path),
401 vec![registrar, trait_name, cx.expr_path(path), attrs]))
403 }).collect::<Vec<_>>();
405 stmts.extend(custom_attrs.iter().map(|ca| {
406 let name = cx.expr_str(ca.span, ca.function_name.name);
407 let path = cx.path_global(ca.span, vec![ca.function_name]);
408 let registrar = cx.expr_ident(ca.span, registrar);
410 let ufcs_path = cx.path(span,
411 vec![proc_macro, __internal, registry, register_attr_proc_macro]);
413 cx.stmt_expr(cx.expr_call(span, cx.expr_path(ufcs_path),
414 vec![registrar, name, cx.expr_path(path)]))
417 stmts.extend(custom_macros.iter().map(|cm| {
418 let name = cx.expr_str(cm.span, cm.function_name.name);
419 let path = cx.path_global(cm.span, vec![cm.function_name]);
420 let registrar = cx.expr_ident(cm.span, registrar);
422 let ufcs_path = cx.path(span,
423 vec![proc_macro, __internal, registry, register_bang_proc_macro]);
425 cx.stmt_expr(cx.expr_call(span, cx.expr_path(ufcs_path),
426 vec![registrar, name, cx.expr_path(path)]))
429 let path = cx.path(span, vec![proc_macro, __internal, registry]);
430 let registrar_path = cx.ty_path(path);
431 let arg_ty = cx.ty_rptr(span, registrar_path, None, ast::Mutability::Mutable);
432 let func = cx.item_fn(span,
434 vec![cx.arg(span, registrar, arg_ty)],
435 cx.ty(span, ast::TyKind::Tup(Vec::new())),
436 cx.block(span, stmts));
438 let derive_registrar = cx.meta_word(span, Symbol::intern("rustc_derive_registrar"));
439 let derive_registrar = cx.attribute(span, derive_registrar);
440 let func = func.map(|mut i| {
441 i.attrs.push(derive_registrar);
442 i.vis = ast::Visibility::Public;
445 let ident = ast::Ident::with_empty_ctxt(Symbol::gensym("registrar"));
446 let module = cx.item_mod(span, span, ident, Vec::new(), vec![krate, func]).map(|mut i| {
447 i.vis = ast::Visibility::Public;
451 cx.monotonic_expander().fold_item(module).pop().unwrap()