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, sym};
17 use syntax::visit::{self, Visitor};
19 use syntax_pos::{Span, DUMMY_SP};
21 const PROC_MACRO_KINDS: [Symbol; 3] = [
22 sym::proc_macro_derive,
23 sym::proc_macro_attribute,
27 struct ProcMacroDerive {
28 trait_name: ast::Name,
31 attrs: Vec<ast::Name>,
39 struct CollectProcMacros<'a> {
40 derives: Vec<ProcMacroDerive>,
41 attr_macros: Vec<ProcMacroDef>,
42 bang_macros: Vec<ProcMacroDef>,
44 handler: &'a errors::Handler,
45 is_proc_macro_crate: bool,
49 pub fn modify(sess: &ParseSess,
50 resolver: &mut dyn (::syntax::ext::base::Resolver),
51 mut krate: ast::Crate,
52 is_proc_macro_crate: bool,
53 has_proc_macro_decls: bool,
55 num_crate_types: usize,
56 handler: &errors::Handler) -> ast::Crate {
57 let ecfg = ExpansionConfig::default("proc_macro".to_string());
58 let mut cx = ExtCtxt::new(sess, ecfg, resolver);
60 let (derives, attr_macros, bang_macros) = {
61 let mut collect = CollectProcMacros {
63 attr_macros: Vec::new(),
64 bang_macros: Vec::new(),
70 if has_proc_macro_decls || is_proc_macro_crate {
71 visit::walk_crate(&mut collect, &krate);
73 (collect.derives, collect.attr_macros, collect.bang_macros)
76 if !is_proc_macro_crate {
80 if num_crate_types > 1 {
81 handler.err("cannot mix `proc-macro` crate type with others");
88 krate.module.items.push(mk_decls(&mut cx, &derives, &attr_macros, &bang_macros));
93 pub fn is_proc_macro_attr(attr: &ast::Attribute) -> bool {
94 PROC_MACRO_KINDS.iter().any(|kind| attr.check_name(*kind))
97 impl<'a> CollectProcMacros<'a> {
98 fn check_not_pub_in_root(&self, vis: &ast::Visibility, sp: Span) {
99 if self.is_proc_macro_crate && self.in_root && vis.node.is_pub() {
100 self.handler.span_err(sp,
101 "`proc-macro` crate types cannot \
102 export any items other than functions \
103 tagged with `#[proc_macro_derive]` currently");
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,
117 "attribute must have either one or two arguments");
120 let trait_attr = match list[0].meta_item() {
121 Some(meta_item) => meta_item,
123 self.handler.span_err(list[0].span(), "not a meta item");
127 let trait_ident = match trait_attr.ident() {
128 Some(trait_ident) if trait_attr.is_word() => trait_ident,
130 self.handler.span_err(trait_attr.span, "must only be one word");
135 if !trait_ident.can_be_raw() {
136 self.handler.span_err(trait_attr.span,
137 &format!("`{}` cannot be a name of derive macro", trait_ident));
139 if deriving::is_builtin_trait(trait_ident.name) {
140 self.handler.span_err(trait_attr.span,
141 "cannot override a built-in derive macro");
144 let attributes_attr = list.get(1);
145 let proc_attrs: Vec<_> = if let Some(attr) = attributes_attr {
146 if !attr.check_name(sym::attributes) {
147 self.handler.span_err(attr.span(), "second argument must be `attributes`")
149 attr.meta_item_list().unwrap_or_else(|| {
150 self.handler.span_err(attr.span(),
151 "attribute must be of form: `attributes(foo, bar)`");
153 }).into_iter().filter_map(|attr| {
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.can_be_raw() {
170 self.handler.span_err(
172 &format!("`{}` cannot be a name of derive helper attribute", ident),
182 if self.in_root && item.vis.node.is_pub() {
183 self.derives.push(ProcMacroDerive {
185 trait_name: trait_ident.name,
186 function_name: item.ident,
190 let msg = if !self.in_root {
191 "functions tagged with `#[proc_macro_derive]` must \
192 currently reside in the root of the crate"
194 "functions tagged with `#[proc_macro_derive]` must be `pub`"
196 self.handler.span_err(item.span, msg);
200 fn collect_attr_proc_macro(&mut self, item: &'a ast::Item) {
201 if self.in_root && item.vis.node.is_pub() {
202 self.attr_macros.push(ProcMacroDef {
204 function_name: item.ident,
207 let msg = if !self.in_root {
208 "functions tagged with `#[proc_macro_attribute]` must \
209 currently reside in the root of the crate"
211 "functions tagged with `#[proc_macro_attribute]` must be `pub`"
213 self.handler.span_err(item.span, msg);
217 fn collect_bang_proc_macro(&mut self, item: &'a ast::Item) {
218 if self.in_root && item.vis.node.is_pub() {
219 self.bang_macros.push(ProcMacroDef {
221 function_name: item.ident,
224 let msg = if !self.in_root {
225 "functions tagged with `#[proc_macro]` must \
226 currently reside in the root of the crate"
228 "functions tagged with `#[proc_macro]` must be `pub`"
230 self.handler.span_err(item.span, msg);
235 impl<'a> Visitor<'a> for CollectProcMacros<'a> {
236 fn visit_item(&mut self, item: &'a ast::Item) {
237 if let ast::ItemKind::MacroDef(..) = item.node {
238 if self.is_proc_macro_crate && attr::contains_name(&item.attrs, sym::macro_export) {
240 "cannot export macro_rules! macros from a `proc-macro` crate type currently";
241 self.handler.span_err(item.span, msg);
245 // First up, make sure we're checking a bare function. If we're not then
246 // we're just not interested in this item.
248 // If we find one, try to locate a `#[proc_macro_derive]` attribute on
250 let is_fn = match item.node {
251 ast::ItemKind::Fn(..) => true,
255 let mut found_attr: Option<&'a ast::Attribute> = None;
257 for attr in &item.attrs {
258 if is_proc_macro_attr(&attr) {
259 if let Some(prev_attr) = found_attr {
260 let msg = if attr.path.segments[0].ident.name ==
261 prev_attr.path.segments[0].ident.name {
262 format!("Only one `#[{}]` attribute is allowed on any given function",
265 format!("`#[{}]` and `#[{}]` attributes cannot both be applied \
266 to the same function", attr.path, prev_attr.path)
269 self.handler.struct_span_err(attr.span, &msg)
270 .span_note(prev_attr.span, "Previous attribute here")
276 found_attr = Some(attr);
280 let attr = match found_attr {
282 self.check_not_pub_in_root(&item.vis, item.span);
283 let prev_in_root = mem::replace(&mut self.in_root, false);
284 visit::walk_item(self, item);
285 self.in_root = prev_in_root;
292 let msg = format!("the `#[{}]` attribute may only be used on bare functions",
295 self.handler.span_err(attr.span, &msg);
299 if self.is_test_crate {
303 if !self.is_proc_macro_crate {
304 let msg = format!("the `#[{}]` attribute is only usable with crates of the \
305 `proc-macro` crate type", attr.path);
307 self.handler.span_err(attr.span, &msg);
311 if attr.check_name(sym::proc_macro_derive) {
312 self.collect_custom_derive(item, attr);
313 } else if attr.check_name(sym::proc_macro_attribute) {
314 self.collect_attr_proc_macro(item);
315 } else if attr.check_name(sym::proc_macro) {
316 self.collect_bang_proc_macro(item);
319 let prev_in_root = mem::replace(&mut self.in_root, false);
320 visit::walk_item(self, item);
321 self.in_root = prev_in_root;
324 fn visit_mac(&mut self, mac: &'a ast::Mac) {
325 visit::walk_mac(self, mac)
329 // Creates a new module which looks like:
333 // extern crate proc_macro;
335 // use proc_macro::bridge::client::ProcMacro;
337 // #[rustc_proc_macro_decls]
338 // static DECLS: &[ProcMacro] = &[
339 // ProcMacro::custom_derive($name_trait1, &[], ::$name1);
340 // ProcMacro::custom_derive($name_trait2, &["attribute_name"], ::$name2);
345 cx: &mut ExtCtxt<'_>,
346 custom_derives: &[ProcMacroDerive],
347 custom_attrs: &[ProcMacroDef],
348 custom_macros: &[ProcMacroDef],
350 let mark = Mark::fresh(Mark::root());
351 mark.set_expn_info(ExpnInfo {
354 format: MacroAttribute(Symbol::intern("proc_macro")),
355 allow_internal_unstable: Some(vec![
356 Symbol::intern("rustc_attrs"),
357 Symbol::intern("proc_macro_internals"),
359 allow_internal_unsafe: false,
360 local_inner_macros: false,
361 edition: hygiene::default_edition(),
363 let span = DUMMY_SP.apply_mark(mark);
365 let hidden = cx.meta_list_item_word(span, sym::hidden);
366 let doc = cx.meta_list(span, sym::doc, vec![hidden]);
367 let doc_hidden = cx.attribute(span, doc);
369 let proc_macro = Ident::with_empty_ctxt(sym::proc_macro);
370 let krate = cx.item(span,
373 ast::ItemKind::ExternCrate(None));
375 let bridge = Ident::from_str("bridge");
376 let client = Ident::from_str("client");
377 let proc_macro_ty = Ident::from_str("ProcMacro");
378 let custom_derive = Ident::from_str("custom_derive");
379 let attr = Ident::from_str("attr");
380 let bang = Ident::from_str("bang");
381 let crate_kw = Ident::with_empty_ctxt(keywords::Crate.name());
384 let local_path = |sp: Span, name| {
385 cx.expr_path(cx.path(sp.with_ctxt(span.ctxt()), vec![crate_kw, name]))
387 let proc_macro_ty_method_path = |method| cx.expr_path(cx.path(span, vec![
388 proc_macro, bridge, client, proc_macro_ty, method,
390 custom_derives.iter().map(|cd| {
391 cx.expr_call(span, proc_macro_ty_method_path(custom_derive), vec![
392 cx.expr_str(cd.span, cd.trait_name),
395 cd.attrs.iter().map(|&s| cx.expr_str(cd.span, s)).collect::<Vec<_>>()
397 local_path(cd.span, cd.function_name),
399 }).chain(custom_attrs.iter().map(|ca| {
400 cx.expr_call(span, proc_macro_ty_method_path(attr), vec![
401 cx.expr_str(ca.span, ca.function_name.name),
402 local_path(ca.span, ca.function_name),
404 })).chain(custom_macros.iter().map(|cm| {
405 cx.expr_call(span, proc_macro_ty_method_path(bang), vec![
406 cx.expr_str(cm.span, cm.function_name.name),
407 local_path(cm.span, cm.function_name),
412 let decls_static = cx.item_static(
414 Ident::from_str("_DECLS"),
416 cx.ty(span, ast::TyKind::Slice(
417 cx.ty_path(cx.path(span,
418 vec![proc_macro, bridge, client, proc_macro_ty])))),
419 None, ast::Mutability::Immutable),
420 ast::Mutability::Immutable,
421 cx.expr_vec_slice(span, decls),
423 let attr = cx.meta_word(span, Symbol::intern("rustc_proc_macro_decls"));
424 i.attrs.push(cx.attribute(span, attr));
425 i.vis = respan(span, ast::VisibilityKind::Public);
429 let module = cx.item_mod(
432 ast::Ident::with_empty_ctxt(Symbol::gensym("decls")),
434 vec![krate, decls_static],
436 i.vis = respan(span, ast::VisibilityKind::Public);
440 cx.monotonic_expander().flat_map_item(module).pop().unwrap()