5 use syntax::ast::{self, Ident};
7 use syntax::source_map::{ExpnInfo, MacroAttribute, hygiene, respan};
8 use syntax::ext::base::ExtCtxt;
9 use syntax::ext::build::AstBuilder;
10 use syntax::ext::expand::ExpansionConfig;
11 use syntax::ext::hygiene::Mark;
12 use syntax::mut_visit::MutVisitor;
13 use syntax::parse::ParseSess;
15 use syntax::symbol::Symbol;
16 use syntax::symbol::keywords;
17 use syntax::visit::{self, Visitor};
19 use syntax_pos::{Span, DUMMY_SP};
21 const PROC_MACRO_KINDS: [&str; 3] = ["proc_macro_derive", "proc_macro_attribute", "proc_macro"];
23 struct ProcMacroDerive {
24 trait_name: ast::Name,
27 attrs: Vec<ast::Name>,
35 struct CollectProcMacros<'a> {
36 derives: Vec<ProcMacroDerive>,
37 attr_macros: Vec<ProcMacroDef>,
38 bang_macros: Vec<ProcMacroDef>,
40 handler: &'a errors::Handler,
41 is_proc_macro_crate: bool,
45 pub fn modify(sess: &ParseSess,
46 resolver: &mut dyn (::syntax::ext::base::Resolver),
47 mut krate: ast::Crate,
48 is_proc_macro_crate: bool,
49 has_proc_macro_decls: bool,
51 num_crate_types: usize,
52 handler: &errors::Handler) -> ast::Crate {
53 let ecfg = ExpansionConfig::default("proc_macro".to_string());
54 let mut cx = ExtCtxt::new(sess, ecfg, resolver);
56 let (derives, attr_macros, bang_macros) = {
57 let mut collect = CollectProcMacros {
59 attr_macros: Vec::new(),
60 bang_macros: Vec::new(),
66 if has_proc_macro_decls || is_proc_macro_crate {
67 visit::walk_crate(&mut collect, &krate);
69 (collect.derives, collect.attr_macros, collect.bang_macros)
72 if !is_proc_macro_crate {
76 if num_crate_types > 1 {
77 handler.err("cannot mix `proc-macro` crate type with others");
84 krate.module.items.push(mk_decls(&mut cx, &derives, &attr_macros, &bang_macros));
89 pub fn is_proc_macro_attr(attr: &ast::Attribute) -> bool {
90 PROC_MACRO_KINDS.iter().any(|kind| attr.check_name(kind))
93 impl<'a> CollectProcMacros<'a> {
94 fn check_not_pub_in_root(&self, vis: &ast::Visibility, sp: Span) {
95 if self.is_proc_macro_crate && self.in_root && vis.node.is_pub() {
96 self.handler.span_err(sp,
97 "`proc-macro` crate types cannot \
98 export any items other than functions \
99 tagged with `#[proc_macro_derive]` currently");
103 fn collect_custom_derive(&mut self, item: &'a ast::Item, attr: &'a ast::Attribute) {
104 // Once we've located the `#[proc_macro_derive]` attribute, verify
105 // that it's of the form `#[proc_macro_derive(Foo)]` or
106 // `#[proc_macro_derive(Foo, attributes(A, ..))]`
107 let list = match attr.meta_item_list() {
111 if list.len() != 1 && list.len() != 2 {
112 self.handler.span_err(attr.span(),
113 "attribute must have either one or two arguments");
116 let trait_attr = &list[0];
117 let attributes_attr = list.get(1);
118 let trait_name = match trait_attr.name() {
121 self.handler.span_err(trait_attr.span(), "not a meta item");
125 if !trait_attr.is_word() {
126 self.handler.span_err(trait_attr.span(), "must only be one word");
129 if deriving::is_builtin_trait(trait_name) {
130 self.handler.span_err(trait_attr.span(),
131 "cannot override a built-in #[derive] mode");
134 let proc_attrs: Vec<_> = if let Some(attr) = attributes_attr {
135 if !attr.check_name("attributes") {
136 self.handler.span_err(attr.span(), "second argument must be `attributes`")
138 attr.meta_item_list().unwrap_or_else(|| {
139 self.handler.span_err(attr.span(),
140 "attribute must be of form: \
141 `attributes(foo, bar)`");
143 }).into_iter().filter_map(|attr| {
144 let name = match attr.name() {
147 self.handler.span_err(attr.span(), "not a meta item");
153 self.handler.span_err(attr.span(), "must only be one word");
163 if self.in_root && item.vis.node.is_pub() {
164 self.derives.push(ProcMacroDerive {
167 function_name: item.ident,
171 let msg = if !self.in_root {
172 "functions tagged with `#[proc_macro_derive]` must \
173 currently reside in the root of the crate"
175 "functions tagged with `#[proc_macro_derive]` must be `pub`"
177 self.handler.span_err(item.span, msg);
181 fn collect_attr_proc_macro(&mut self, item: &'a ast::Item) {
182 if self.in_root && item.vis.node.is_pub() {
183 self.attr_macros.push(ProcMacroDef {
185 function_name: item.ident,
188 let msg = if !self.in_root {
189 "functions tagged with `#[proc_macro_attribute]` must \
190 currently reside in the root of the crate"
192 "functions tagged with `#[proc_macro_attribute]` must be `pub`"
194 self.handler.span_err(item.span, msg);
198 fn collect_bang_proc_macro(&mut self, item: &'a ast::Item) {
199 if self.in_root && item.vis.node.is_pub() {
200 self.bang_macros.push(ProcMacroDef {
202 function_name: item.ident,
205 let msg = if !self.in_root {
206 "functions tagged with `#[proc_macro]` must \
207 currently reside in the root of the crate"
209 "functions tagged with `#[proc_macro]` must be `pub`"
211 self.handler.span_err(item.span, msg);
216 impl<'a> Visitor<'a> for CollectProcMacros<'a> {
217 fn visit_item(&mut self, item: &'a ast::Item) {
218 if let ast::ItemKind::MacroDef(..) = item.node {
219 if self.is_proc_macro_crate && attr::contains_name(&item.attrs, "macro_export") {
221 "cannot export macro_rules! macros from a `proc-macro` crate type currently";
222 self.handler.span_err(item.span, msg);
226 // First up, make sure we're checking a bare function. If we're not then
227 // we're just not interested in this item.
229 // If we find one, try to locate a `#[proc_macro_derive]` attribute on
231 let is_fn = match item.node {
232 ast::ItemKind::Fn(..) => true,
236 let mut found_attr: Option<&'a ast::Attribute> = None;
238 for attr in &item.attrs {
239 if is_proc_macro_attr(&attr) {
240 if let Some(prev_attr) = found_attr {
241 let msg = if attr.path.segments[0].ident.name ==
242 prev_attr.path.segments[0].ident.name {
243 format!("Only one `#[{}]` attribute is allowed on any given function",
246 format!("`#[{}]` and `#[{}]` attributes cannot both be applied \
247 to the same function", attr.path, prev_attr.path)
250 self.handler.struct_span_err(attr.span(), &msg)
251 .span_note(prev_attr.span(), "Previous attribute here")
257 found_attr = Some(attr);
261 let attr = match found_attr {
263 self.check_not_pub_in_root(&item.vis, item.span);
264 let prev_in_root = mem::replace(&mut self.in_root, false);
265 visit::walk_item(self, item);
266 self.in_root = prev_in_root;
273 let msg = format!("the `#[{}]` attribute may only be used on bare functions",
276 self.handler.span_err(attr.span(), &msg);
280 if self.is_test_crate {
284 if !self.is_proc_macro_crate {
285 let msg = format!("the `#[{}]` attribute is only usable with crates of the \
286 `proc-macro` crate type", attr.path);
288 self.handler.span_err(attr.span(), &msg);
292 if attr.check_name("proc_macro_derive") {
293 self.collect_custom_derive(item, attr);
294 } else if attr.check_name("proc_macro_attribute") {
295 self.collect_attr_proc_macro(item);
296 } else if attr.check_name("proc_macro") {
297 self.collect_bang_proc_macro(item);
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;
305 fn visit_mac(&mut self, mac: &ast::Mac) {
306 visit::walk_mac(self, mac)
310 // Creates a new module which looks like:
313 // extern crate proc_macro;
315 // use proc_macro::bridge::client::ProcMacro;
317 // #[rustc_proc_macro_decls]
318 // static DECLS: &[ProcMacro] = &[
319 // ProcMacro::custom_derive($name_trait1, &[], ::$name1);
320 // ProcMacro::custom_derive($name_trait2, &["attribute_name"], ::$name2);
325 cx: &mut ExtCtxt<'_>,
326 custom_derives: &[ProcMacroDerive],
327 custom_attrs: &[ProcMacroDef],
328 custom_macros: &[ProcMacroDef],
330 let mark = Mark::fresh(Mark::root());
331 mark.set_expn_info(ExpnInfo {
334 format: MacroAttribute(Symbol::intern("proc_macro")),
335 allow_internal_unstable: Some(vec![
336 Symbol::intern("rustc_attrs"),
337 Symbol::intern("proc_macro_internals"),
339 allow_internal_unsafe: false,
340 local_inner_macros: false,
341 edition: hygiene::default_edition(),
343 let span = DUMMY_SP.apply_mark(mark);
345 let proc_macro = Ident::from_str("proc_macro");
346 let krate = cx.item(span,
349 ast::ItemKind::ExternCrate(None));
351 let bridge = Ident::from_str("bridge");
352 let client = Ident::from_str("client");
353 let proc_macro_ty = Ident::from_str("ProcMacro");
354 let custom_derive = Ident::from_str("custom_derive");
355 let attr = Ident::from_str("attr");
356 let bang = Ident::from_str("bang");
357 let crate_kw = Ident::with_empty_ctxt(keywords::Crate.name());
360 let local_path = |sp: Span, name| {
361 cx.expr_path(cx.path(sp.with_ctxt(span.ctxt()), vec![crate_kw, name]))
363 let proc_macro_ty_method_path = |method| cx.expr_path(cx.path(span, vec![
364 proc_macro, bridge, client, proc_macro_ty, method,
366 custom_derives.iter().map(|cd| {
367 cx.expr_call(span, proc_macro_ty_method_path(custom_derive), vec![
368 cx.expr_str(cd.span, cd.trait_name),
371 cd.attrs.iter().map(|&s| cx.expr_str(cd.span, s)).collect::<Vec<_>>()
373 local_path(cd.span, cd.function_name),
375 }).chain(custom_attrs.iter().map(|ca| {
376 cx.expr_call(span, proc_macro_ty_method_path(attr), vec![
377 cx.expr_str(ca.span, ca.function_name.name),
378 local_path(ca.span, ca.function_name),
380 })).chain(custom_macros.iter().map(|cm| {
381 cx.expr_call(span, proc_macro_ty_method_path(bang), vec![
382 cx.expr_str(cm.span, cm.function_name.name),
383 local_path(cm.span, cm.function_name),
388 let decls_static = cx.item_static(
390 Ident::from_str("_DECLS"),
392 cx.ty(span, ast::TyKind::Slice(
393 cx.ty_path(cx.path(span,
394 vec![proc_macro, bridge, client, proc_macro_ty])))),
395 None, ast::Mutability::Immutable),
396 ast::Mutability::Immutable,
397 cx.expr_vec_slice(span, decls),
399 let attr = cx.meta_word(span, Symbol::intern("rustc_proc_macro_decls"));
400 i.attrs.push(cx.attribute(span, attr));
401 i.vis = respan(span, ast::VisibilityKind::Public);
405 let module = cx.item_mod(
408 ast::Ident::with_empty_ctxt(Symbol::gensym("decls")),
410 vec![krate, decls_static],
412 i.vis = respan(span, ast::VisibilityKind::Public);
416 cx.monotonic_expander().flat_map_item(module).pop().unwrap()