]> git.lizzy.rs Git - rust.git/blob - src/libsyntax_ext/proc_macro_registrar.rs
ef29e5a6b022b624498854b93e13b4d81be48a22
[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, NodeId};
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 ::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 == ast::VisibilityKind::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 == ast::VisibilityKind::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 let Some(_) = attr.meta_item_list() {
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 == ast::VisibilityKind::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 let Some(_) = attr.meta_item_list() {
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 == ast::VisibilityKind::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 == prev_attr.path {
275                         format!("Only one `#[{}]` attribute is allowed on any given function",
276                                 attr.path)
277                     } else {
278                         format!("`#[{}]` and `#[{}]` attributes cannot both be applied \
279                                 to the same function", attr.path, prev_attr.path)
280                     };
281
282                     self.handler.struct_span_err(attr.span(), &msg)
283                         .span_note(prev_attr.span(), "Previous attribute here")
284                         .emit();
285
286                     return;
287                 }
288
289                 found_attr = Some(attr);
290             }
291         }
292
293         let attr = match found_attr {
294             None => {
295                 self.check_not_pub_in_root(&item.vis, item.span);
296                 return visit::walk_item(self, item);
297             },
298             Some(attr) => attr,
299         };
300
301         if !is_fn {
302             let msg = format!("the `#[{}]` attribute may only be used on bare functions",
303                               attr.path);
304
305             self.handler.span_err(attr.span(), &msg);
306             return;
307         }
308
309         if self.is_test_crate {
310             return;
311         }
312
313         if !self.is_proc_macro_crate {
314             let msg = format!("the `#[{}]` attribute is only usable with crates of the \
315                               `proc-macro` crate type", attr.path);
316
317             self.handler.span_err(attr.span(), &msg);
318             return;
319         }
320
321         if attr.check_name("proc_macro_derive") {
322             self.collect_custom_derive(item, attr);
323         } else if attr.check_name("proc_macro_attribute") {
324             self.collect_attr_proc_macro(item, attr);
325         } else if attr.check_name("proc_macro") {
326             self.collect_bang_proc_macro(item, attr);
327         };
328
329         visit::walk_item(self, item);
330     }
331
332     fn visit_mod(&mut self, m: &'a ast::Mod, _s: Span, _a: &[ast::Attribute], id: NodeId) {
333         let mut prev_in_root = self.in_root;
334         if id != ast::CRATE_NODE_ID {
335             prev_in_root = mem::replace(&mut self.in_root, false);
336         }
337         visit::walk_mod(self, m);
338         self.in_root = prev_in_root;
339     }
340
341     fn visit_mac(&mut self, mac: &ast::Mac) {
342         visit::walk_mac(self, mac)
343     }
344 }
345
346 // Creates a new module which looks like:
347 //
348 //      mod $gensym {
349 //          extern crate proc_macro;
350 //
351 //          use proc_macro::__internal::Registry;
352 //
353 //          #[plugin_registrar]
354 //          fn registrar(registrar: &mut Registry) {
355 //              registrar.register_custom_derive($name_trait1, ::$name1, &[]);
356 //              registrar.register_custom_derive($name_trait2, ::$name2, &["attribute_name"]);
357 //              // ...
358 //          }
359 //      }
360 fn mk_registrar(cx: &mut ExtCtxt,
361                 custom_derives: &[ProcMacroDerive],
362                 custom_attrs: &[ProcMacroDef],
363                 custom_macros: &[ProcMacroDef]) -> P<ast::Item> {
364     let mark = Mark::fresh(Mark::root());
365     mark.set_expn_info(ExpnInfo {
366         call_site: DUMMY_SP,
367         def_site: None,
368         format: MacroAttribute(Symbol::intern("proc_macro")),
369         allow_internal_unstable: true,
370         allow_internal_unsafe: false,
371         local_inner_macros: false,
372         edition: hygiene::default_edition(),
373     });
374     let span = DUMMY_SP.apply_mark(mark);
375
376     let proc_macro = Ident::from_str("proc_macro");
377     let krate = cx.item(span,
378                         proc_macro,
379                         Vec::new(),
380                         ast::ItemKind::ExternCrate(None));
381
382     let __internal = Ident::from_str("__internal");
383     let registry = Ident::from_str("Registry");
384     let registrar = Ident::from_str("_registrar");
385     let register_custom_derive = Ident::from_str("register_custom_derive");
386     let register_attr_proc_macro = Ident::from_str("register_attr_proc_macro");
387     let register_bang_proc_macro = Ident::from_str("register_bang_proc_macro");
388
389     let mut stmts = custom_derives.iter().map(|cd| {
390         let path = cx.path_global(cd.span, vec![cd.function_name]);
391         let trait_name = cx.expr_str(cd.span, cd.trait_name);
392         let attrs = cx.expr_vec_slice(
393             span,
394             cd.attrs.iter().map(|&s| cx.expr_str(cd.span, s)).collect::<Vec<_>>()
395         );
396         let registrar = cx.expr_ident(span, registrar);
397         let ufcs_path = cx.path(span, vec![proc_macro, __internal, registry,
398                                            register_custom_derive]);
399
400         cx.stmt_expr(cx.expr_call(span, cx.expr_path(ufcs_path),
401                                   vec![registrar, trait_name, cx.expr_path(path), attrs]))
402
403     }).collect::<Vec<_>>();
404
405     stmts.extend(custom_attrs.iter().map(|ca| {
406         let name = cx.expr_str(ca.span, ca.function_name.name);
407         let path = cx.path_global(ca.span, vec![ca.function_name]);
408         let registrar = cx.expr_ident(ca.span, registrar);
409
410         let ufcs_path = cx.path(span,
411                                 vec![proc_macro, __internal, registry, register_attr_proc_macro]);
412
413         cx.stmt_expr(cx.expr_call(span, cx.expr_path(ufcs_path),
414                                   vec![registrar, name, cx.expr_path(path)]))
415     }));
416
417     stmts.extend(custom_macros.iter().map(|cm| {
418         let name = cx.expr_str(cm.span, cm.function_name.name);
419         let path = cx.path_global(cm.span, vec![cm.function_name]);
420         let registrar = cx.expr_ident(cm.span, registrar);
421
422         let ufcs_path = cx.path(span,
423                                 vec![proc_macro, __internal, registry, register_bang_proc_macro]);
424
425         cx.stmt_expr(cx.expr_call(span, cx.expr_path(ufcs_path),
426                                   vec![registrar, name, cx.expr_path(path)]))
427     }));
428
429     let path = cx.path(span, vec![proc_macro, __internal, registry]);
430     let registrar_path = cx.ty_path(path);
431     let arg_ty = cx.ty_rptr(span, registrar_path, None, ast::Mutability::Mutable);
432     let func = cx.item_fn(span,
433                           registrar,
434                           vec![cx.arg(span, registrar, arg_ty)],
435                           cx.ty(span, ast::TyKind::Tup(Vec::new())),
436                           cx.block(span, stmts));
437
438     let derive_registrar = cx.meta_word(span, Symbol::intern("rustc_derive_registrar"));
439     let derive_registrar = cx.attribute(span, derive_registrar);
440     let func = func.map(|mut i| {
441         i.attrs.push(derive_registrar);
442         i.vis = respan(span, ast::VisibilityKind::Public);
443         i
444     });
445     let ident = ast::Ident::with_empty_ctxt(Symbol::gensym("registrar"));
446     let module = cx.item_mod(span, span, ident, Vec::new(), vec![krate, func]).map(|mut i| {
447         i.vis = respan(span, ast::VisibilityKind::Public);
448         i
449     });
450
451     cx.monotonic_expander().fold_item(module).pop().unwrap()
452 }