]> git.lizzy.rs Git - rust.git/blob - src/libsyntax_ext/proc_macro_decls.rs
Simplify SaveHandler trait
[rust.git] / src / libsyntax_ext / proc_macro_decls.rs
1 use std::mem;
2
3 use syntax::ast::{self, Ident};
4 use syntax::attr;
5 use syntax::source_map::{ExpnInfo, ExpnKind, respan};
6 use syntax::ext::base::{ExtCtxt, MacroKind};
7 use syntax::ext::build::AstBuilder;
8 use syntax::ext::expand::ExpansionConfig;
9 use syntax::ext::hygiene::ExpnId;
10 use syntax::mut_visit::MutVisitor;
11 use syntax::parse::ParseSess;
12 use syntax::ptr::P;
13 use syntax::symbol::Symbol;
14 use syntax::symbol::{kw, sym};
15 use syntax::visit::{self, Visitor};
16
17 use syntax_pos::{Span, DUMMY_SP};
18
19 const PROC_MACRO_KINDS: [Symbol; 3] = [
20     sym::proc_macro_derive,
21     sym::proc_macro_attribute,
22     sym::proc_macro
23 ];
24
25 struct ProcMacroDerive {
26     trait_name: ast::Name,
27     function_name: Ident,
28     span: Span,
29     attrs: Vec<ast::Name>,
30 }
31
32 struct ProcMacroDef {
33     function_name: Ident,
34     span: Span,
35 }
36
37 struct CollectProcMacros<'a> {
38     derives: Vec<ProcMacroDerive>,
39     attr_macros: Vec<ProcMacroDef>,
40     bang_macros: Vec<ProcMacroDef>,
41     in_root: bool,
42     handler: &'a errors::Handler,
43     is_proc_macro_crate: bool,
44     is_test_crate: bool,
45 }
46
47 pub fn modify(sess: &ParseSess,
48               resolver: &mut dyn (::syntax::ext::base::Resolver),
49               mut krate: ast::Crate,
50               is_proc_macro_crate: bool,
51               has_proc_macro_decls: bool,
52               is_test_crate: bool,
53               num_crate_types: usize,
54               handler: &errors::Handler) -> ast::Crate {
55     let ecfg = ExpansionConfig::default("proc_macro".to_string());
56     let mut cx = ExtCtxt::new(sess, ecfg, resolver);
57
58     let (derives, attr_macros, bang_macros) = {
59         let mut collect = CollectProcMacros {
60             derives: Vec::new(),
61             attr_macros: Vec::new(),
62             bang_macros: Vec::new(),
63             in_root: true,
64             handler,
65             is_proc_macro_crate,
66             is_test_crate,
67         };
68         if has_proc_macro_decls || is_proc_macro_crate {
69             visit::walk_crate(&mut collect, &krate);
70         }
71         (collect.derives, collect.attr_macros, collect.bang_macros)
72     };
73
74     if !is_proc_macro_crate {
75         return krate
76     }
77
78     if num_crate_types > 1 {
79         handler.err("cannot mix `proc-macro` crate type with others");
80     }
81
82     if is_test_crate {
83         return krate;
84     }
85
86     krate.module.items.push(mk_decls(&mut cx, &derives, &attr_macros, &bang_macros));
87
88     krate
89 }
90
91 pub fn is_proc_macro_attr(attr: &ast::Attribute) -> bool {
92     PROC_MACRO_KINDS.iter().any(|kind| attr.check_name(*kind))
93 }
94
95 impl<'a> CollectProcMacros<'a> {
96     fn check_not_pub_in_root(&self, vis: &ast::Visibility, sp: Span) {
97         if self.is_proc_macro_crate && self.in_root && vis.node.is_pub() {
98             self.handler.span_err(sp,
99                                   "`proc-macro` crate types cannot \
100                                    export any items other than functions \
101                                    tagged with `#[proc_macro_derive]` currently");
102         }
103     }
104
105     fn collect_custom_derive(&mut self, item: &'a ast::Item, attr: &'a ast::Attribute) {
106         // Once we've located the `#[proc_macro_derive]` attribute, verify
107         // that it's of the form `#[proc_macro_derive(Foo)]` or
108         // `#[proc_macro_derive(Foo, attributes(A, ..))]`
109         let list = match attr.meta_item_list() {
110             Some(list) => list,
111             None => return,
112         };
113         if list.len() != 1 && list.len() != 2 {
114             self.handler.span_err(attr.span,
115                                   "attribute must have either one or two arguments");
116             return
117         }
118         let trait_attr = match list[0].meta_item() {
119             Some(meta_item) => meta_item,
120             _ => {
121                 self.handler.span_err(list[0].span(), "not a meta item");
122                 return
123             }
124         };
125         let trait_ident = match trait_attr.ident() {
126             Some(trait_ident) if trait_attr.is_word() => trait_ident,
127             _ => {
128                 self.handler.span_err(trait_attr.span, "must only be one word");
129                 return
130             }
131         };
132
133         if !trait_ident.name.can_be_raw() {
134             self.handler.span_err(trait_attr.span,
135                                   &format!("`{}` cannot be a name of derive macro", trait_ident));
136         }
137
138         let attributes_attr = list.get(1);
139         let proc_attrs: Vec<_> = if let Some(attr) = attributes_attr {
140             if !attr.check_name(sym::attributes) {
141                 self.handler.span_err(attr.span(), "second argument must be `attributes`")
142             }
143             attr.meta_item_list().unwrap_or_else(|| {
144                 self.handler.span_err(attr.span(),
145                                       "attribute must be of form: `attributes(foo, bar)`");
146                 &[]
147             }).into_iter().filter_map(|attr| {
148                 let attr = match attr.meta_item() {
149                     Some(meta_item) => meta_item,
150                     _ => {
151                         self.handler.span_err(attr.span(), "not a meta item");
152                         return None;
153                     }
154                 };
155
156                 let ident = match attr.ident() {
157                     Some(ident) if attr.is_word() => ident,
158                     _ => {
159                         self.handler.span_err(attr.span, "must only be one word");
160                         return None;
161                     }
162                 };
163                 if !ident.name.can_be_raw() {
164                     self.handler.span_err(
165                         attr.span,
166                         &format!("`{}` cannot be a name of derive helper attribute", ident),
167                     );
168                 }
169
170                 Some(ident.name)
171             }).collect()
172         } else {
173             Vec::new()
174         };
175
176         if self.in_root && item.vis.node.is_pub() {
177             self.derives.push(ProcMacroDerive {
178                 span: item.span,
179                 trait_name: trait_ident.name,
180                 function_name: item.ident,
181                 attrs: proc_attrs,
182             });
183         } else {
184             let msg = if !self.in_root {
185                 "functions tagged with `#[proc_macro_derive]` must \
186                  currently reside in the root of the crate"
187             } else {
188                 "functions tagged with `#[proc_macro_derive]` must be `pub`"
189             };
190             self.handler.span_err(item.span, msg);
191         }
192     }
193
194     fn collect_attr_proc_macro(&mut self, item: &'a ast::Item) {
195         if self.in_root && item.vis.node.is_pub() {
196             self.attr_macros.push(ProcMacroDef {
197                 span: item.span,
198                 function_name: item.ident,
199             });
200         } else {
201             let msg = if !self.in_root {
202                 "functions tagged with `#[proc_macro_attribute]` must \
203                  currently reside in the root of the crate"
204             } else {
205                 "functions tagged with `#[proc_macro_attribute]` must be `pub`"
206             };
207             self.handler.span_err(item.span, msg);
208         }
209     }
210
211     fn collect_bang_proc_macro(&mut self, item: &'a ast::Item) {
212         if self.in_root && item.vis.node.is_pub() {
213             self.bang_macros.push(ProcMacroDef {
214                 span: item.span,
215                 function_name: item.ident,
216             });
217         } else {
218             let msg = if !self.in_root {
219                 "functions tagged with `#[proc_macro]` must \
220                  currently reside in the root of the crate"
221             } else {
222                 "functions tagged with `#[proc_macro]` must be `pub`"
223             };
224             self.handler.span_err(item.span, msg);
225         }
226     }
227 }
228
229 impl<'a> Visitor<'a> for CollectProcMacros<'a> {
230     fn visit_item(&mut self, item: &'a ast::Item) {
231         if let ast::ItemKind::MacroDef(..) = item.node {
232             if self.is_proc_macro_crate && attr::contains_name(&item.attrs, sym::macro_export) {
233                 let msg =
234                     "cannot export macro_rules! macros from a `proc-macro` crate type currently";
235                 self.handler.span_err(item.span, msg);
236             }
237         }
238
239         // First up, make sure we're checking a bare function. If we're not then
240         // we're just not interested in this item.
241         //
242         // If we find one, try to locate a `#[proc_macro_derive]` attribute on it.
243         let is_fn = match item.node {
244             ast::ItemKind::Fn(..) => true,
245             _ => false,
246         };
247
248         let mut found_attr: Option<&'a ast::Attribute> = None;
249
250         for attr in &item.attrs {
251             if is_proc_macro_attr(&attr) {
252                 if let Some(prev_attr) = found_attr {
253                     let msg = if attr.path.segments[0].ident.name ==
254                                  prev_attr.path.segments[0].ident.name {
255                         format!("only one `#[{}]` attribute is allowed on any given function",
256                                 attr.path)
257                     } else {
258                         format!("`#[{}]` and `#[{}]` attributes cannot both be applied \
259                                 to the same function", attr.path, prev_attr.path)
260                     };
261
262                     self.handler.struct_span_err(attr.span, &msg)
263                         .span_note(prev_attr.span, "previous attribute here")
264                         .emit();
265
266                     return;
267                 }
268
269                 found_attr = Some(attr);
270             }
271         }
272
273         let attr = match found_attr {
274             None => {
275                 self.check_not_pub_in_root(&item.vis, item.span);
276                 let prev_in_root = mem::replace(&mut self.in_root, false);
277                 visit::walk_item(self, item);
278                 self.in_root = prev_in_root;
279                 return;
280             },
281             Some(attr) => attr,
282         };
283
284         if !is_fn {
285             let msg = format!("the `#[{}]` attribute may only be used on bare functions",
286                               attr.path);
287
288             self.handler.span_err(attr.span, &msg);
289             return;
290         }
291
292         if self.is_test_crate {
293             return;
294         }
295
296         if !self.is_proc_macro_crate {
297             let msg = format!("the `#[{}]` attribute is only usable with crates of the \
298                               `proc-macro` crate type", attr.path);
299
300             self.handler.span_err(attr.span, &msg);
301             return;
302         }
303
304         if attr.check_name(sym::proc_macro_derive) {
305             self.collect_custom_derive(item, attr);
306         } else if attr.check_name(sym::proc_macro_attribute) {
307             self.collect_attr_proc_macro(item);
308         } else if attr.check_name(sym::proc_macro) {
309             self.collect_bang_proc_macro(item);
310         };
311
312         let prev_in_root = mem::replace(&mut self.in_root, false);
313         visit::walk_item(self, item);
314         self.in_root = prev_in_root;
315     }
316
317     fn visit_mac(&mut self, mac: &'a ast::Mac) {
318         visit::walk_mac(self, mac)
319     }
320 }
321
322 // Creates a new module which looks like:
323 //
324 //      #[doc(hidden)]
325 //      mod $gensym {
326 //          extern crate proc_macro;
327 //
328 //          use proc_macro::bridge::client::ProcMacro;
329 //
330 //          #[rustc_proc_macro_decls]
331 //          static DECLS: &[ProcMacro] = &[
332 //              ProcMacro::custom_derive($name_trait1, &[], ::$name1);
333 //              ProcMacro::custom_derive($name_trait2, &["attribute_name"], ::$name2);
334 //              // ...
335 //          ];
336 //      }
337 fn mk_decls(
338     cx: &mut ExtCtxt<'_>,
339     custom_derives: &[ProcMacroDerive],
340     custom_attrs: &[ProcMacroDef],
341     custom_macros: &[ProcMacroDef],
342 ) -> P<ast::Item> {
343     let span = DUMMY_SP.fresh_expansion(ExpnId::root(), ExpnInfo::allow_unstable(
344         ExpnKind::Macro(MacroKind::Attr, sym::proc_macro), DUMMY_SP, cx.parse_sess.edition,
345         [sym::rustc_attrs, sym::proc_macro_internals][..].into(),
346     ));
347
348     let hidden = cx.meta_list_item_word(span, sym::hidden);
349     let doc = cx.meta_list(span, sym::doc, vec![hidden]);
350     let doc_hidden = cx.attribute(span, doc);
351
352     let proc_macro = Ident::with_empty_ctxt(sym::proc_macro);
353     let krate = cx.item(span,
354                         proc_macro,
355                         Vec::new(),
356                         ast::ItemKind::ExternCrate(None));
357
358     let bridge = Ident::from_str("bridge");
359     let client = Ident::from_str("client");
360     let proc_macro_ty = Ident::from_str("ProcMacro");
361     let custom_derive = Ident::from_str("custom_derive");
362     let attr = Ident::from_str("attr");
363     let bang = Ident::from_str("bang");
364     let crate_kw = Ident::with_empty_ctxt(kw::Crate);
365
366     let decls = {
367         let local_path = |sp: Span, name| {
368             cx.expr_path(cx.path(sp.with_ctxt(span.ctxt()), vec![crate_kw, name]))
369         };
370         let proc_macro_ty_method_path = |method| cx.expr_path(cx.path(span, vec![
371             proc_macro, bridge, client, proc_macro_ty, method,
372         ]));
373         custom_derives.iter().map(|cd| {
374             cx.expr_call(span, proc_macro_ty_method_path(custom_derive), vec![
375                 cx.expr_str(cd.span, cd.trait_name),
376                 cx.expr_vec_slice(
377                     span,
378                     cd.attrs.iter().map(|&s| cx.expr_str(cd.span, s)).collect::<Vec<_>>()
379                 ),
380                 local_path(cd.span, cd.function_name),
381             ])
382         }).chain(custom_attrs.iter().map(|ca| {
383             cx.expr_call(span, proc_macro_ty_method_path(attr), vec![
384                 cx.expr_str(ca.span, ca.function_name.name),
385                 local_path(ca.span, ca.function_name),
386             ])
387         })).chain(custom_macros.iter().map(|cm| {
388             cx.expr_call(span, proc_macro_ty_method_path(bang), vec![
389                 cx.expr_str(cm.span, cm.function_name.name),
390                 local_path(cm.span, cm.function_name),
391             ])
392         })).collect()
393     };
394
395     let decls_static = cx.item_static(
396         span,
397         Ident::from_str("_DECLS"),
398         cx.ty_rptr(span,
399             cx.ty(span, ast::TyKind::Slice(
400                 cx.ty_path(cx.path(span,
401                     vec![proc_macro, bridge, client, proc_macro_ty])))),
402             None, ast::Mutability::Immutable),
403         ast::Mutability::Immutable,
404         cx.expr_vec_slice(span, decls),
405     ).map(|mut i| {
406         let attr = cx.meta_word(span, sym::rustc_proc_macro_decls);
407         i.attrs.push(cx.attribute(span, attr));
408         i.vis = respan(span, ast::VisibilityKind::Public);
409         i
410     });
411
412     let module = cx.item_mod(
413         span,
414         span,
415         ast::Ident::from_str("decls").gensym(),
416         vec![doc_hidden],
417         vec![krate, decls_static],
418     ).map(|mut i| {
419         i.vis = respan(span, ast::VisibilityKind::Public);
420         i
421     });
422
423     cx.monotonic_expander().flat_map_item(module).pop().unwrap()
424 }