]> git.lizzy.rs Git - rust.git/blob - src/libsyntax_ext/proc_macro_registrar.rs
Auto merge of #43651 - petrochenkov:foreign-life, r=eddyb
[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::codemap::{ExpnInfo, NameAndSpan, MacroAttribute};
17 use syntax::ext::base::ExtCtxt;
18 use syntax::ext::build::AstBuilder;
19 use syntax::ext::expand::ExpansionConfig;
20 use syntax::ext::hygiene::{Mark, SyntaxContext};
21 use syntax::fold::Folder;
22 use syntax::parse::ParseSess;
23 use syntax::ptr::P;
24 use syntax::symbol::Symbol;
25 use syntax::visit::{self, Visitor};
26
27 use syntax_pos::{Span, DUMMY_SP};
28
29 use deriving;
30
31 const PROC_MACRO_KINDS: [&'static str; 3] =
32     ["proc_macro_derive", "proc_macro_attribute", "proc_macro"];
33
34 struct ProcMacroDerive {
35     trait_name: ast::Name,
36     function_name: Ident,
37     span: Span,
38     attrs: Vec<ast::Name>,
39 }
40
41 struct ProcMacroDef {
42     function_name: Ident,
43     span: Span,
44 }
45
46 struct CollectProcMacros<'a> {
47     derives: Vec<ProcMacroDerive>,
48     attr_macros: Vec<ProcMacroDef>,
49     bang_macros: Vec<ProcMacroDef>,
50     in_root: bool,
51     handler: &'a errors::Handler,
52     is_proc_macro_crate: bool,
53     is_test_crate: bool,
54 }
55
56 pub fn modify(sess: &ParseSess,
57               resolver: &mut ::syntax::ext::base::Resolver,
58               mut krate: ast::Crate,
59               is_proc_macro_crate: bool,
60               is_test_crate: bool,
61               num_crate_types: usize,
62               handler: &errors::Handler) -> ast::Crate {
63     let ecfg = ExpansionConfig::default("proc_macro".to_string());
64     let mut cx = ExtCtxt::new(sess, ecfg, resolver);
65
66     let (derives, attr_macros, bang_macros) = {
67         let mut collect = CollectProcMacros {
68             derives: Vec::new(),
69             attr_macros: Vec::new(),
70             bang_macros: Vec::new(),
71             in_root: true,
72             handler: handler,
73             is_proc_macro_crate: is_proc_macro_crate,
74             is_test_crate: is_test_crate,
75         };
76         visit::walk_crate(&mut collect, &krate);
77         (collect.derives, collect.attr_macros, collect.bang_macros)
78     };
79
80     if !is_proc_macro_crate {
81         return krate
82     }
83
84     if num_crate_types > 1 {
85         handler.err("cannot mix `proc-macro` crate type with others");
86     }
87
88     if is_test_crate {
89         return krate;
90     }
91
92     krate.module.items.push(mk_registrar(&mut cx, &derives, &attr_macros, &bang_macros));
93
94     krate
95 }
96
97 fn is_proc_macro_attr(attr: &ast::Attribute) -> bool {
98     PROC_MACRO_KINDS.iter().any(|kind| attr.check_name(kind))
99 }
100
101 impl<'a> CollectProcMacros<'a> {
102     fn check_not_pub_in_root(&self, vis: &ast::Visibility, sp: Span) {
103         if self.is_proc_macro_crate &&
104            self.in_root &&
105            *vis == ast::Visibility::Public {
106             self.handler.span_err(sp,
107                                   "`proc-macro` crate types cannot \
108                                    export any items other than functions \
109                                    tagged with `#[proc_macro_derive]` currently");
110         }
111     }
112
113     fn collect_custom_derive(&mut self, item: &'a ast::Item, attr: &'a ast::Attribute) {
114         // Once we've located the `#[proc_macro_derive]` attribute, verify
115         // that it's of the form `#[proc_macro_derive(Foo)]` or
116         // `#[proc_macro_derive(Foo, attributes(A, ..))]`
117         let list = match attr.meta_item_list() {
118             Some(list) => list,
119             None => {
120                 self.handler.span_err(attr.span(),
121                                       "attribute must be of form: \
122                                        #[proc_macro_derive(TraitName)]");
123                 return
124             }
125         };
126         if list.len() != 1 && list.len() != 2 {
127             self.handler.span_err(attr.span(),
128                                   "attribute must have either one or two arguments");
129             return
130         }
131         let trait_attr = &list[0];
132         let attributes_attr = list.get(1);
133         let trait_name = match trait_attr.name() {
134             Some(name) => name,
135             _ => {
136                 self.handler.span_err(trait_attr.span(), "not a meta item");
137                 return
138             }
139         };
140         if !trait_attr.is_word() {
141             self.handler.span_err(trait_attr.span(), "must only be one word");
142         }
143
144         if deriving::is_builtin_trait(trait_name) {
145             self.handler.span_err(trait_attr.span(),
146                                   "cannot override a built-in #[derive] mode");
147         }
148
149         if self.derives.iter().any(|d| d.trait_name == trait_name) {
150             self.handler.span_err(trait_attr.span(),
151                                   "derive mode defined twice in this crate");
152         }
153
154         let proc_attrs: Vec<_> = if let Some(attr) = attributes_attr {
155             if !attr.check_name("attributes") {
156                 self.handler.span_err(attr.span(), "second argument must be `attributes`")
157             }
158             attr.meta_item_list().unwrap_or_else(|| {
159                 self.handler.span_err(attr.span(),
160                                       "attribute must be of form: \
161                                        `attributes(foo, bar)`");
162                 &[]
163             }).into_iter().filter_map(|attr| {
164                 let name = match attr.name() {
165                     Some(name) => name,
166                     _ => {
167                         self.handler.span_err(attr.span(), "not a meta item");
168                         return None;
169                     },
170                 };
171
172                 if !attr.is_word() {
173                     self.handler.span_err(attr.span(), "must only be one word");
174                     return None;
175                 }
176
177                 Some(name)
178             }).collect()
179         } else {
180             Vec::new()
181         };
182
183         if self.in_root && item.vis == ast::Visibility::Public {
184             self.derives.push(ProcMacroDerive {
185                 span: item.span,
186                 trait_name: trait_name,
187                 function_name: item.ident,
188                 attrs: proc_attrs,
189             });
190         } else {
191             let msg = if !self.in_root {
192                 "functions tagged with `#[proc_macro_derive]` must \
193                  currently reside in the root of the crate"
194             } else {
195                 "functions tagged with `#[proc_macro_derive]` must be `pub`"
196             };
197             self.handler.span_err(item.span, msg);
198         }
199     }
200
201     fn collect_attr_proc_macro(&mut self, item: &'a ast::Item, attr: &'a ast::Attribute) {
202         if let Some(_) = attr.meta_item_list() {
203             self.handler.span_err(attr.span, "`#[proc_macro_attribute]` attribute
204                 does not take any arguments");
205             return;
206         }
207
208         if self.in_root && item.vis == ast::Visibility::Public {
209             self.attr_macros.push(ProcMacroDef {
210                 span: item.span,
211                 function_name: item.ident,
212             });
213         } else {
214             let msg = if !self.in_root {
215                 "functions tagged with `#[proc_macro_attribute]` must \
216                  currently reside in the root of the crate"
217             } else {
218                 "functions tagged with `#[proc_macro_attribute]` must be `pub`"
219             };
220             self.handler.span_err(item.span, msg);
221         }
222     }
223
224     fn collect_bang_proc_macro(&mut self, item: &'a ast::Item, attr: &'a ast::Attribute) {
225         if let Some(_) = attr.meta_item_list() {
226             self.handler.span_err(attr.span, "`#[proc_macro]` attribute
227                 does not take any arguments");
228             return;
229         }
230
231         if self.in_root && item.vis == ast::Visibility::Public {
232             self.bang_macros.push(ProcMacroDef {
233                 span: item.span,
234                 function_name: item.ident,
235             });
236         } else {
237             let msg = if !self.in_root {
238                 "functions tagged with `#[proc_macro]` must \
239                  currently reside in the root of the crate"
240             } else {
241                 "functions tagged with `#[proc_macro]` must be `pub`"
242             };
243             self.handler.span_err(item.span, msg);
244         }
245     }
246 }
247
248 impl<'a> Visitor<'a> for CollectProcMacros<'a> {
249     fn visit_item(&mut self, item: &'a ast::Item) {
250         if let ast::ItemKind::MacroDef(..) = item.node {
251             if self.is_proc_macro_crate &&
252                item.attrs.iter().any(|attr| attr.path == "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         callee: NameAndSpan {
368             format: MacroAttribute(Symbol::intern("proc_macro")),
369             span: None,
370             allow_internal_unstable: true,
371             allow_internal_unsafe: false,
372         }
373     });
374     let span = Span { ctxt: SyntaxContext::empty().apply_mark(mark), ..DUMMY_SP };
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 = ast::Visibility::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 = ast::Visibility::Public;
448         i
449     });
450
451     cx.monotonic_expander().fold_item(module).pop().unwrap()
452 }