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