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};
17 use syntax::codemap::{ExpnInfo, MacroAttribute, hygiene, respan};
18 use syntax::ext::base::ExtCtxt;
19 use syntax::ext::build::AstBuilder;
20 use syntax::ext::expand::ExpansionConfig;
21 use syntax::ext::hygiene::Mark;
22 use syntax::fold::Folder;
23 use syntax::parse::ParseSess;
25 use syntax::symbol::Symbol;
26 use syntax::visit::{self, Visitor};
28 use syntax_pos::{Span, DUMMY_SP};
32 const PROC_MACRO_KINDS: [&'static str; 3] =
33 ["proc_macro_derive", "proc_macro_attribute", "proc_macro"];
35 struct ProcMacroDerive {
36 trait_name: ast::Name,
39 attrs: Vec<ast::Name>,
47 struct CollectProcMacros<'a> {
48 derives: Vec<ProcMacroDerive>,
49 attr_macros: Vec<ProcMacroDef>,
50 bang_macros: Vec<ProcMacroDef>,
52 handler: &'a errors::Handler,
53 is_proc_macro_crate: bool,
57 pub fn modify(sess: &ParseSess,
58 resolver: &mut ::syntax::ext::base::Resolver,
59 mut krate: ast::Crate,
60 is_proc_macro_crate: bool,
62 num_crate_types: usize,
63 handler: &errors::Handler) -> ast::Crate {
64 let ecfg = ExpansionConfig::default("proc_macro".to_string());
65 let mut cx = ExtCtxt::new(sess, ecfg, resolver);
67 let (derives, attr_macros, bang_macros) = {
68 let mut collect = CollectProcMacros {
70 attr_macros: Vec::new(),
71 bang_macros: Vec::new(),
77 visit::walk_crate(&mut collect, &krate);
78 (collect.derives, collect.attr_macros, collect.bang_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 krate.module.items.push(mk_registrar(&mut cx, &derives, &attr_macros, &bang_macros));
98 fn is_proc_macro_attr(attr: &ast::Attribute) -> bool {
99 PROC_MACRO_KINDS.iter().any(|kind| attr.check_name(kind))
102 impl<'a> CollectProcMacros<'a> {
103 fn check_not_pub_in_root(&self, vis: &ast::Visibility, sp: Span) {
104 if self.is_proc_macro_crate &&
106 vis.node == ast::VisibilityKind::Public {
107 self.handler.span_err(sp,
108 "`proc-macro` crate types cannot \
109 export any items other than functions \
110 tagged with `#[proc_macro_derive]` currently");
114 fn collect_custom_derive(&mut self, item: &'a ast::Item, attr: &'a ast::Attribute) {
115 // Once we've located the `#[proc_macro_derive]` attribute, verify
116 // that it's of the form `#[proc_macro_derive(Foo)]` or
117 // `#[proc_macro_derive(Foo, attributes(A, ..))]`
118 let list = match attr.meta_item_list() {
121 self.handler.span_err(attr.span(),
122 "attribute must be of form: \
123 #[proc_macro_derive(TraitName)]");
127 if list.len() != 1 && list.len() != 2 {
128 self.handler.span_err(attr.span(),
129 "attribute must have either one or two arguments");
132 let trait_attr = &list[0];
133 let attributes_attr = list.get(1);
134 let trait_name = match trait_attr.name() {
137 self.handler.span_err(trait_attr.span(), "not a meta item");
141 if !trait_attr.is_word() {
142 self.handler.span_err(trait_attr.span(), "must only be one word");
145 if deriving::is_builtin_trait(trait_name) {
146 self.handler.span_err(trait_attr.span(),
147 "cannot override a built-in #[derive] mode");
150 if self.derives.iter().any(|d| d.trait_name == trait_name) {
151 self.handler.span_err(trait_attr.span(),
152 "derive mode defined twice in this crate");
155 let proc_attrs: Vec<_> = if let Some(attr) = attributes_attr {
156 if !attr.check_name("attributes") {
157 self.handler.span_err(attr.span(), "second argument must be `attributes`")
159 attr.meta_item_list().unwrap_or_else(|| {
160 self.handler.span_err(attr.span(),
161 "attribute must be of form: \
162 `attributes(foo, bar)`");
164 }).into_iter().filter_map(|attr| {
165 let name = match attr.name() {
168 self.handler.span_err(attr.span(), "not a meta item");
174 self.handler.span_err(attr.span(), "must only be one word");
184 if self.in_root && item.vis.node == ast::VisibilityKind::Public {
185 self.derives.push(ProcMacroDerive {
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, attr: &'a ast::Attribute) {
204 self.handler.span_err(attr.span, "`#[proc_macro_attribute]` attribute \
205 does not take any arguments");
209 if self.in_root && item.vis.node == ast::VisibilityKind::Public {
210 self.attr_macros.push(ProcMacroDef {
212 function_name: item.ident,
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(item.span, msg);
225 fn collect_bang_proc_macro(&mut self, item: &'a ast::Item, attr: &'a ast::Attribute) {
227 self.handler.span_err(attr.span, "`#[proc_macro]` attribute \
228 does not take any arguments");
232 if self.in_root && item.vis.node == ast::VisibilityKind::Public {
233 self.bang_macros.push(ProcMacroDef {
235 function_name: item.ident,
238 let msg = if !self.in_root {
239 "functions tagged with `#[proc_macro]` must \
240 currently reside in the root of the crate"
242 "functions tagged with `#[proc_macro]` must be `pub`"
244 self.handler.span_err(item.span, msg);
249 impl<'a> Visitor<'a> for CollectProcMacros<'a> {
250 fn visit_item(&mut self, item: &'a ast::Item) {
251 if let ast::ItemKind::MacroDef(..) = item.node {
252 if self.is_proc_macro_crate && attr::contains_name(&item.attrs, "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 {
368 format: MacroAttribute(Symbol::intern("proc_macro")),
369 allow_internal_unstable: true,
370 allow_internal_unsafe: false,
371 local_inner_macros: false,
372 edition: hygiene::default_edition(),
374 let span = DUMMY_SP.apply_mark(mark);
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 = respan(span, ast::VisibilityKind::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 = respan(span, ast::VisibilityKind::Public);
451 cx.monotonic_expander().fold_item(module).pop().unwrap()