]> git.lizzy.rs Git - rust.git/blob - src/libsyntax_ext/proc_macro_registrar.rs
5cbd978257532142708bc7a96be116195ee3a2b9
[rust.git] / src / libsyntax_ext / proc_macro_registrar.rs
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.
4 //
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.
10
11 use std::mem;
12
13 use errors;
14
15 use syntax::ast::{self, Ident};
16 use syntax::attr;
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;
24 use syntax::ptr::P;
25 use syntax::symbol::Symbol;
26 use syntax::visit::{self, Visitor};
27
28 use syntax_pos::{Span, DUMMY_SP};
29
30 use deriving;
31
32 const PROC_MACRO_KINDS: [&'static str; 3] =
33     ["proc_macro_derive", "proc_macro_attribute", "proc_macro"];
34
35 struct ProcMacroDerive {
36     trait_name: ast::Name,
37     function_name: Ident,
38     span: Span,
39     attrs: Vec<ast::Name>,
40 }
41
42 struct ProcMacroDef {
43     function_name: Ident,
44     span: Span,
45 }
46
47 struct CollectProcMacros<'a> {
48     derives: Vec<ProcMacroDerive>,
49     attr_macros: Vec<ProcMacroDef>,
50     bang_macros: Vec<ProcMacroDef>,
51     in_root: bool,
52     handler: &'a errors::Handler,
53     is_proc_macro_crate: bool,
54     is_test_crate: bool,
55 }
56
57 pub fn modify(sess: &ParseSess,
58               resolver: &mut dyn (::syntax::ext::base::Resolver),
59               mut krate: ast::Crate,
60               is_proc_macro_crate: bool,
61               is_test_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);
66
67     let (derives, attr_macros, bang_macros) = {
68         let mut collect = CollectProcMacros {
69             derives: Vec::new(),
70             attr_macros: Vec::new(),
71             bang_macros: Vec::new(),
72             in_root: true,
73             handler,
74             is_proc_macro_crate,
75             is_test_crate,
76         };
77         visit::walk_crate(&mut collect, &krate);
78         (collect.derives, collect.attr_macros, collect.bang_macros)
79     };
80
81     if !is_proc_macro_crate {
82         return krate
83     }
84
85     if num_crate_types > 1 {
86         handler.err("cannot mix `proc-macro` crate type with others");
87     }
88
89     if is_test_crate {
90         return krate;
91     }
92
93     krate.module.items.push(mk_registrar(&mut cx, &derives, &attr_macros, &bang_macros));
94
95     krate
96 }
97
98 fn is_proc_macro_attr(attr: &ast::Attribute) -> bool {
99     PROC_MACRO_KINDS.iter().any(|kind| attr.check_name(kind))
100 }
101
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 &&
105            self.in_root &&
106            vis.node.is_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");
111         }
112     }
113
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() {
119             Some(list) => list,
120             None => {
121                 self.handler.span_err(attr.span(),
122                                       "attribute must be of form: \
123                                        #[proc_macro_derive(TraitName)]");
124                 return
125             }
126         };
127         if list.len() != 1 && list.len() != 2 {
128             self.handler.span_err(attr.span(),
129                                   "attribute must have either one or two arguments");
130             return
131         }
132         let trait_attr = &list[0];
133         let attributes_attr = list.get(1);
134         let trait_name = match trait_attr.name() {
135             Some(name) => name,
136             _ => {
137                 self.handler.span_err(trait_attr.span(), "not a meta item");
138                 return
139             }
140         };
141         if !trait_attr.is_word() {
142             self.handler.span_err(trait_attr.span(), "must only be one word");
143         }
144
145         if deriving::is_builtin_trait(trait_name) {
146             self.handler.span_err(trait_attr.span(),
147                                   "cannot override a built-in #[derive] mode");
148         }
149
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");
153         }
154
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`")
158             }
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)`");
163                 &[]
164             }).into_iter().filter_map(|attr| {
165                 let name = match attr.name() {
166                     Some(name) => name,
167                     _ => {
168                         self.handler.span_err(attr.span(), "not a meta item");
169                         return None;
170                     },
171                 };
172
173                 if !attr.is_word() {
174                     self.handler.span_err(attr.span(), "must only be one word");
175                     return None;
176                 }
177
178                 Some(name)
179             }).collect()
180         } else {
181             Vec::new()
182         };
183
184         if self.in_root && item.vis.node.is_public() {
185             self.derives.push(ProcMacroDerive {
186                 span: item.span,
187                 trait_name,
188                 function_name: item.ident,
189                 attrs: proc_attrs,
190             });
191         } else {
192             let msg = if !self.in_root {
193                 "functions tagged with `#[proc_macro_derive]` must \
194                  currently reside in the root of the crate"
195             } else {
196                 "functions tagged with `#[proc_macro_derive]` must be `pub`"
197             };
198             self.handler.span_err(item.span, msg);
199         }
200     }
201
202     fn collect_attr_proc_macro(&mut self, item: &'a ast::Item, attr: &'a ast::Attribute) {
203         if !attr.is_word() {
204             self.handler.span_err(attr.span, "`#[proc_macro_attribute]` attribute \
205                 does not take any arguments");
206             return;
207         }
208
209         if self.in_root && item.vis.node.is_public() {
210             self.attr_macros.push(ProcMacroDef {
211                 span: item.span,
212                 function_name: item.ident,
213             });
214         } else {
215             let msg = if !self.in_root {
216                 "functions tagged with `#[proc_macro_attribute]` must \
217                  currently reside in the root of the crate"
218             } else {
219                 "functions tagged with `#[proc_macro_attribute]` must be `pub`"
220             };
221             self.handler.span_err(item.span, msg);
222         }
223     }
224
225     fn collect_bang_proc_macro(&mut self, item: &'a ast::Item, attr: &'a ast::Attribute) {
226         if !attr.is_word() {
227             self.handler.span_err(attr.span, "`#[proc_macro]` attribute \
228                 does not take any arguments");
229             return;
230         }
231
232         if self.in_root && item.vis.node.is_public() {
233             self.bang_macros.push(ProcMacroDef {
234                 span: item.span,
235                 function_name: item.ident,
236             });
237         } else {
238             let msg = if !self.in_root {
239                 "functions tagged with `#[proc_macro]` must \
240                  currently reside in the root of the crate"
241             } else {
242                 "functions tagged with `#[proc_macro]` must be `pub`"
243             };
244             self.handler.span_err(item.span, msg);
245         }
246     }
247 }
248
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") {
253                 let msg =
254                     "cannot export macro_rules! macros from a `proc-macro` crate type currently";
255                 self.handler.span_err(item.span, msg);
256             }
257         }
258
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.
261         //
262         // If we find one, try to locate a `#[proc_macro_derive]` attribute on
263         // it.
264         let is_fn = match item.node {
265             ast::ItemKind::Fn(..) => true,
266             _ => false,
267         };
268
269         let mut found_attr: Option<&'a ast::Attribute> = None;
270
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.segments[0].ident.name ==
275                                  prev_attr.path.segments[0].ident.name {
276                         format!("Only one `#[{}]` attribute is allowed on any given function",
277                                 attr.path)
278                     } else {
279                         format!("`#[{}]` and `#[{}]` attributes cannot both be applied \
280                                 to the same function", attr.path, prev_attr.path)
281                     };
282
283                     self.handler.struct_span_err(attr.span(), &msg)
284                         .span_note(prev_attr.span(), "Previous attribute here")
285                         .emit();
286
287                     return;
288                 }
289
290                 found_attr = Some(attr);
291             }
292         }
293
294         let attr = match found_attr {
295             None => {
296                 self.check_not_pub_in_root(&item.vis, item.span);
297                 let prev_in_root = mem::replace(&mut self.in_root, false);
298                 visit::walk_item(self, item);
299                 self.in_root = prev_in_root;
300                 return;
301             },
302             Some(attr) => attr,
303         };
304
305         if !is_fn {
306             let msg = format!("the `#[{}]` attribute may only be used on bare functions",
307                               attr.path);
308
309             self.handler.span_err(attr.span(), &msg);
310             return;
311         }
312
313         if self.is_test_crate {
314             return;
315         }
316
317         if !self.is_proc_macro_crate {
318             let msg = format!("the `#[{}]` attribute is only usable with crates of the \
319                               `proc-macro` crate type", attr.path);
320
321             self.handler.span_err(attr.span(), &msg);
322             return;
323         }
324
325         if attr.check_name("proc_macro_derive") {
326             self.collect_custom_derive(item, attr);
327         } else if attr.check_name("proc_macro_attribute") {
328             self.collect_attr_proc_macro(item, attr);
329         } else if attr.check_name("proc_macro") {
330             self.collect_bang_proc_macro(item, attr);
331         };
332
333         let prev_in_root = mem::replace(&mut self.in_root, false);
334         visit::walk_item(self, item);
335         self.in_root = prev_in_root;
336     }
337
338     fn visit_mac(&mut self, mac: &ast::Mac) {
339         visit::walk_mac(self, mac)
340     }
341 }
342
343 // Creates a new module which looks like:
344 //
345 //      mod $gensym {
346 //          extern crate proc_macro;
347 //
348 //          use proc_macro::__internal::Registry;
349 //
350 //          #[plugin_registrar]
351 //          fn registrar(registrar: &mut Registry) {
352 //              registrar.register_custom_derive($name_trait1, ::$name1, &[]);
353 //              registrar.register_custom_derive($name_trait2, ::$name2, &["attribute_name"]);
354 //              // ...
355 //          }
356 //      }
357 fn mk_registrar(cx: &mut ExtCtxt,
358                 custom_derives: &[ProcMacroDerive],
359                 custom_attrs: &[ProcMacroDef],
360                 custom_macros: &[ProcMacroDef]) -> P<ast::Item> {
361     let mark = Mark::fresh(Mark::root());
362     mark.set_expn_info(ExpnInfo {
363         call_site: DUMMY_SP,
364         def_site: None,
365         format: MacroAttribute(Symbol::intern("proc_macro")),
366         allow_internal_unstable: true,
367         allow_internal_unsafe: false,
368         local_inner_macros: false,
369         edition: hygiene::default_edition(),
370     });
371     let span = DUMMY_SP.apply_mark(mark);
372
373     let proc_macro = Ident::from_str("proc_macro");
374     let krate = cx.item(span,
375                         proc_macro,
376                         Vec::new(),
377                         ast::ItemKind::ExternCrate(None));
378
379     let __internal = Ident::from_str("__internal");
380     let registry = Ident::from_str("Registry");
381     let registrar = Ident::from_str("_registrar");
382     let register_custom_derive = Ident::from_str("register_custom_derive");
383     let register_attr_proc_macro = Ident::from_str("register_attr_proc_macro");
384     let register_bang_proc_macro = Ident::from_str("register_bang_proc_macro");
385
386     let mut stmts = custom_derives.iter().map(|cd| {
387         let path = cx.path_global(cd.span, vec![cd.function_name]);
388         let trait_name = cx.expr_str(cd.span, cd.trait_name);
389         let attrs = cx.expr_vec_slice(
390             span,
391             cd.attrs.iter().map(|&s| cx.expr_str(cd.span, s)).collect::<Vec<_>>()
392         );
393         let registrar = cx.expr_ident(span, registrar);
394         let ufcs_path = cx.path(span, vec![proc_macro, __internal, registry,
395                                            register_custom_derive]);
396
397         cx.stmt_expr(cx.expr_call(span, cx.expr_path(ufcs_path),
398                                   vec![registrar, trait_name, cx.expr_path(path), attrs]))
399
400     }).collect::<Vec<_>>();
401
402     stmts.extend(custom_attrs.iter().map(|ca| {
403         let name = cx.expr_str(ca.span, ca.function_name.name);
404         let path = cx.path_global(ca.span, vec![ca.function_name]);
405         let registrar = cx.expr_ident(ca.span, registrar);
406
407         let ufcs_path = cx.path(span,
408                                 vec![proc_macro, __internal, registry, register_attr_proc_macro]);
409
410         cx.stmt_expr(cx.expr_call(span, cx.expr_path(ufcs_path),
411                                   vec![registrar, name, cx.expr_path(path)]))
412     }));
413
414     stmts.extend(custom_macros.iter().map(|cm| {
415         let name = cx.expr_str(cm.span, cm.function_name.name);
416         let path = cx.path_global(cm.span, vec![cm.function_name]);
417         let registrar = cx.expr_ident(cm.span, registrar);
418
419         let ufcs_path = cx.path(span,
420                                 vec![proc_macro, __internal, registry, register_bang_proc_macro]);
421
422         cx.stmt_expr(cx.expr_call(span, cx.expr_path(ufcs_path),
423                                   vec![registrar, name, cx.expr_path(path)]))
424     }));
425
426     let path = cx.path(span, vec![proc_macro, __internal, registry]);
427     let registrar_path = cx.ty_path(path);
428     let arg_ty = cx.ty_rptr(span, registrar_path, None, ast::Mutability::Mutable);
429     let func = cx.item_fn(span,
430                           registrar,
431                           vec![cx.arg(span, registrar, arg_ty)],
432                           cx.ty(span, ast::TyKind::Tup(Vec::new())),
433                           cx.block(span, stmts));
434
435     let derive_registrar = cx.meta_word(span, Symbol::intern("rustc_derive_registrar"));
436     let derive_registrar = cx.attribute(span, derive_registrar);
437     let func = func.map(|mut i| {
438         i.attrs.push(derive_registrar);
439         i.vis = respan(span, ast::VisibilityKind::Public);
440         i
441     });
442     let ident = ast::Ident::with_empty_ctxt(Symbol::gensym("registrar"));
443     let module = cx.item_mod(span, span, ident, Vec::new(), vec![krate, func]).map(|mut i| {
444         i.vis = respan(span, ast::VisibilityKind::Public);
445         i
446     });
447
448     cx.monotonic_expander().fold_item(module).pop().unwrap()
449 }