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};
17 use syntax::source_map::{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::symbol::keywords;
27 use syntax::visit::{self, Visitor};
29 use syntax_pos::{Span, DUMMY_SP};
33 const PROC_MACRO_KINDS: [&'static str; 3] =
34 ["proc_macro_derive", "proc_macro_attribute", "proc_macro"];
36 struct ProcMacroDerive {
37 trait_name: ast::Name,
40 attrs: Vec<ast::Name>,
48 struct CollectProcMacros<'a> {
49 derives: Vec<ProcMacroDerive>,
50 attr_macros: Vec<ProcMacroDef>,
51 bang_macros: Vec<ProcMacroDef>,
53 handler: &'a errors::Handler,
54 is_proc_macro_crate: bool,
58 pub fn modify(sess: &ParseSess,
59 resolver: &mut dyn (::syntax::ext::base::Resolver),
60 mut krate: ast::Crate,
61 is_proc_macro_crate: bool,
63 num_crate_types: usize,
64 handler: &errors::Handler) -> ast::Crate {
65 let ecfg = ExpansionConfig::default("proc_macro".to_string());
66 let mut cx = ExtCtxt::new(sess, ecfg, resolver);
68 let (derives, attr_macros, bang_macros) = {
69 let mut collect = CollectProcMacros {
71 attr_macros: Vec::new(),
72 bang_macros: Vec::new(),
78 visit::walk_crate(&mut collect, &krate);
79 (collect.derives, collect.attr_macros, collect.bang_macros)
82 if !is_proc_macro_crate {
86 if num_crate_types > 1 {
87 handler.err("cannot mix `proc-macro` crate type with others");
94 krate.module.items.push(mk_registrar(&mut cx, &derives, &attr_macros, &bang_macros));
99 fn is_proc_macro_attr(attr: &ast::Attribute) -> bool {
100 PROC_MACRO_KINDS.iter().any(|kind| attr.check_name(kind))
103 impl<'a> CollectProcMacros<'a> {
104 fn check_not_pub_in_root(&self, vis: &ast::Visibility, sp: Span) {
105 if self.is_proc_macro_crate && self.in_root && vis.node.is_pub() {
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 let proc_attrs: Vec<_> = if let Some(attr) = attributes_attr {
150 if !attr.check_name("attributes") {
151 self.handler.span_err(attr.span(), "second argument must be `attributes`")
153 attr.meta_item_list().unwrap_or_else(|| {
154 self.handler.span_err(attr.span(),
155 "attribute must be of form: \
156 `attributes(foo, bar)`");
158 }).into_iter().filter_map(|attr| {
159 let name = match attr.name() {
162 self.handler.span_err(attr.span(), "not a meta item");
168 self.handler.span_err(attr.span(), "must only be one word");
178 if self.in_root && item.vis.node.is_pub() {
179 self.derives.push(ProcMacroDerive {
182 function_name: item.ident,
186 let msg = if !self.in_root {
187 "functions tagged with `#[proc_macro_derive]` must \
188 currently reside in the root of the crate"
190 "functions tagged with `#[proc_macro_derive]` must be `pub`"
192 self.handler.span_err(item.span, msg);
196 fn collect_attr_proc_macro(&mut self, item: &'a ast::Item, attr: &'a ast::Attribute) {
198 self.handler.span_err(attr.span, "`#[proc_macro_attribute]` attribute \
199 does not take any arguments");
203 if self.in_root && item.vis.node.is_pub() {
204 self.attr_macros.push(ProcMacroDef {
206 function_name: item.ident,
209 let msg = if !self.in_root {
210 "functions tagged with `#[proc_macro_attribute]` must \
211 currently reside in the root of the crate"
213 "functions tagged with `#[proc_macro_attribute]` must be `pub`"
215 self.handler.span_err(item.span, msg);
219 fn collect_bang_proc_macro(&mut self, item: &'a ast::Item, attr: &'a ast::Attribute) {
221 self.handler.span_err(attr.span, "`#[proc_macro]` attribute \
222 does not take any arguments");
226 if self.in_root && item.vis.node.is_pub() {
227 self.bang_macros.push(ProcMacroDef {
229 function_name: item.ident,
232 let msg = if !self.in_root {
233 "functions tagged with `#[proc_macro]` must \
234 currently reside in the root of the crate"
236 "functions tagged with `#[proc_macro]` must be `pub`"
238 self.handler.span_err(item.span, msg);
243 impl<'a> Visitor<'a> for CollectProcMacros<'a> {
244 fn visit_item(&mut self, item: &'a ast::Item) {
245 if let ast::ItemKind::MacroDef(..) = item.node {
246 if self.is_proc_macro_crate && attr::contains_name(&item.attrs, "macro_export") {
248 "cannot export macro_rules! macros from a `proc-macro` crate type currently";
249 self.handler.span_err(item.span, msg);
253 // First up, make sure we're checking a bare function. If we're not then
254 // we're just not interested in this item.
256 // If we find one, try to locate a `#[proc_macro_derive]` attribute on
258 let is_fn = match item.node {
259 ast::ItemKind::Fn(..) => true,
263 let mut found_attr: Option<&'a ast::Attribute> = None;
265 for attr in &item.attrs {
266 if is_proc_macro_attr(&attr) {
267 if let Some(prev_attr) = found_attr {
268 let msg = if attr.path.segments[0].ident.name ==
269 prev_attr.path.segments[0].ident.name {
270 format!("Only one `#[{}]` attribute is allowed on any given function",
273 format!("`#[{}]` and `#[{}]` attributes cannot both be applied \
274 to the same function", attr.path, prev_attr.path)
277 self.handler.struct_span_err(attr.span(), &msg)
278 .span_note(prev_attr.span(), "Previous attribute here")
284 found_attr = Some(attr);
288 let attr = match found_attr {
290 self.check_not_pub_in_root(&item.vis, item.span);
291 let prev_in_root = mem::replace(&mut self.in_root, false);
292 visit::walk_item(self, item);
293 self.in_root = prev_in_root;
300 let msg = format!("the `#[{}]` attribute may only be used on bare functions",
303 self.handler.span_err(attr.span(), &msg);
307 if self.is_test_crate {
311 if !self.is_proc_macro_crate {
312 let msg = format!("the `#[{}]` attribute is only usable with crates of the \
313 `proc-macro` crate type", attr.path);
315 self.handler.span_err(attr.span(), &msg);
319 if attr.check_name("proc_macro_derive") {
320 self.collect_custom_derive(item, attr);
321 } else if attr.check_name("proc_macro_attribute") {
322 self.collect_attr_proc_macro(item, attr);
323 } else if attr.check_name("proc_macro") {
324 self.collect_bang_proc_macro(item, attr);
327 let prev_in_root = mem::replace(&mut self.in_root, false);
328 visit::walk_item(self, item);
329 self.in_root = prev_in_root;
332 fn visit_mac(&mut self, mac: &ast::Mac) {
333 visit::walk_mac(self, mac)
337 // Creates a new module which looks like:
340 // extern crate proc_macro;
342 // use proc_macro::__internal::Registry;
344 // #[plugin_registrar]
345 // fn registrar(registrar: &mut Registry) {
346 // registrar.register_custom_derive($name_trait1, ::$name1, &[]);
347 // registrar.register_custom_derive($name_trait2, ::$name2, &["attribute_name"]);
351 fn mk_registrar(cx: &mut ExtCtxt,
352 custom_derives: &[ProcMacroDerive],
353 custom_attrs: &[ProcMacroDef],
354 custom_macros: &[ProcMacroDef]) -> P<ast::Item> {
355 let mark = Mark::fresh(Mark::root());
356 mark.set_expn_info(ExpnInfo {
359 format: MacroAttribute(Symbol::intern("proc_macro")),
360 allow_internal_unstable: true,
361 allow_internal_unsafe: false,
362 local_inner_macros: false,
363 edition: hygiene::default_edition(),
365 let span = DUMMY_SP.apply_mark(mark);
367 let proc_macro = Ident::from_str("proc_macro");
368 let krate = cx.item(span,
371 ast::ItemKind::ExternCrate(None));
373 let __internal = Ident::from_str("__internal");
374 let registry = Ident::from_str("Registry");
375 let registrar = Ident::from_str("_registrar");
376 let register_custom_derive = Ident::from_str("register_custom_derive");
377 let register_attr_proc_macro = Ident::from_str("register_attr_proc_macro");
378 let register_bang_proc_macro = Ident::from_str("register_bang_proc_macro");
379 let crate_kw = Ident::with_empty_ctxt(keywords::Crate.name());
380 let local_path = |cx: &mut ExtCtxt, sp: Span, name: Ident| {
381 cx.path(sp.with_ctxt(span.ctxt()), vec![crate_kw, name])
384 let mut stmts = custom_derives.iter().map(|cd| {
385 let path = local_path(cx, cd.span, cd.function_name);
386 let trait_name = cx.expr_str(cd.span, cd.trait_name);
387 let attrs = cx.expr_vec_slice(
389 cd.attrs.iter().map(|&s| cx.expr_str(cd.span, s)).collect::<Vec<_>>()
391 let registrar = cx.expr_ident(span, registrar);
392 let ufcs_path = cx.path(span, vec![proc_macro, __internal, registry,
393 register_custom_derive]);
395 cx.stmt_expr(cx.expr_call(span, cx.expr_path(ufcs_path),
396 vec![registrar, trait_name, cx.expr_path(path), attrs]))
398 }).collect::<Vec<_>>();
400 stmts.extend(custom_attrs.iter().map(|ca| {
401 let name = cx.expr_str(ca.span, ca.function_name.name);
402 let path = local_path(cx, ca.span, ca.function_name);
403 let registrar = cx.expr_ident(ca.span, registrar);
405 let ufcs_path = cx.path(span,
406 vec![proc_macro, __internal, registry, register_attr_proc_macro]);
408 cx.stmt_expr(cx.expr_call(span, cx.expr_path(ufcs_path),
409 vec![registrar, name, cx.expr_path(path)]))
412 stmts.extend(custom_macros.iter().map(|cm| {
413 let name = cx.expr_str(cm.span, cm.function_name.name);
414 let path = local_path(cx, cm.span, cm.function_name);
415 let registrar = cx.expr_ident(cm.span, registrar);
417 let ufcs_path = cx.path(span,
418 vec![proc_macro, __internal, registry, register_bang_proc_macro]);
420 cx.stmt_expr(cx.expr_call(span, cx.expr_path(ufcs_path),
421 vec![registrar, name, cx.expr_path(path)]))
424 let path = cx.path(span, vec![proc_macro, __internal, registry]);
425 let registrar_path = cx.ty_path(path);
426 let arg_ty = cx.ty_rptr(span, registrar_path, None, ast::Mutability::Mutable);
427 let func = cx.item_fn(span,
429 vec![cx.arg(span, registrar, arg_ty)],
430 cx.ty(span, ast::TyKind::Tup(Vec::new())),
431 cx.block(span, stmts));
433 let derive_registrar = cx.meta_word(span, Symbol::intern("rustc_derive_registrar"));
434 let derive_registrar = cx.attribute(span, derive_registrar);
435 let func = func.map(|mut i| {
436 i.attrs.push(derive_registrar);
437 i.vis = respan(span, ast::VisibilityKind::Public);
440 let ident = ast::Ident::with_empty_ctxt(Symbol::gensym("registrar"));
441 let module = cx.item_mod(span, span, ident, Vec::new(), vec![krate, func]).map(|mut i| {
442 i.vis = respan(span, ast::VisibilityKind::Public);
446 cx.monotonic_expander().fold_item(module).pop().unwrap()