]> git.lizzy.rs Git - rust.git/blob - src/libsyntax_ext/proc_macro_decls.rs
Rollup merge of #58138 - ishitatsuyuki:stability-delay, r=estebank
[rust.git] / src / libsyntax_ext / proc_macro_decls.rs
1 use std::mem;
2
3 use errors;
4
5 use syntax::ast::{self, Ident};
6 use syntax::attr;
7 use syntax::source_map::{ExpnInfo, MacroAttribute, hygiene, respan};
8 use syntax::ext::base::ExtCtxt;
9 use syntax::ext::build::AstBuilder;
10 use syntax::ext::expand::ExpansionConfig;
11 use syntax::ext::hygiene::Mark;
12 use syntax::fold::Folder;
13 use syntax::parse::ParseSess;
14 use syntax::ptr::P;
15 use syntax::symbol::Symbol;
16 use syntax::symbol::keywords;
17 use syntax::visit::{self, Visitor};
18
19 use syntax_pos::{Span, DUMMY_SP};
20
21 use deriving;
22
23 const PROC_MACRO_KINDS: [&str; 3] = ["proc_macro_derive", "proc_macro_attribute", "proc_macro"];
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 = &list[0];
119         let attributes_attr = list.get(1);
120         let trait_name = match trait_attr.name() {
121             Some(name) => name,
122             _ => {
123                 self.handler.span_err(trait_attr.span(), "not a meta item");
124                 return
125             }
126         };
127         if !trait_attr.is_word() {
128             self.handler.span_err(trait_attr.span(), "must only be one word");
129         }
130
131         if deriving::is_builtin_trait(trait_name) {
132             self.handler.span_err(trait_attr.span(),
133                                   "cannot override a built-in #[derive] mode");
134         }
135
136         let proc_attrs: Vec<_> = if let Some(attr) = attributes_attr {
137             if !attr.check_name("attributes") {
138                 self.handler.span_err(attr.span(), "second argument must be `attributes`")
139             }
140             attr.meta_item_list().unwrap_or_else(|| {
141                 self.handler.span_err(attr.span(),
142                                       "attribute must be of form: \
143                                        `attributes(foo, bar)`");
144                 &[]
145             }).into_iter().filter_map(|attr| {
146                 let name = match attr.name() {
147                     Some(name) => name,
148                     _ => {
149                         self.handler.span_err(attr.span(), "not a meta item");
150                         return None;
151                     },
152                 };
153
154                 if !attr.is_word() {
155                     self.handler.span_err(attr.span(), "must only be one word");
156                     return None;
157                 }
158
159                 Some(name)
160             }).collect()
161         } else {
162             Vec::new()
163         };
164
165         if self.in_root && item.vis.node.is_pub() {
166             self.derives.push(ProcMacroDerive {
167                 span: item.span,
168                 trait_name,
169                 function_name: item.ident,
170                 attrs: proc_attrs,
171             });
172         } else {
173             let msg = if !self.in_root {
174                 "functions tagged with `#[proc_macro_derive]` must \
175                  currently reside in the root of the crate"
176             } else {
177                 "functions tagged with `#[proc_macro_derive]` must be `pub`"
178             };
179             self.handler.span_err(item.span, msg);
180         }
181     }
182
183     fn collect_attr_proc_macro(&mut self, item: &'a ast::Item) {
184         if self.in_root && item.vis.node.is_pub() {
185             self.attr_macros.push(ProcMacroDef {
186                 span: item.span,
187                 function_name: item.ident,
188             });
189         } else {
190             let msg = if !self.in_root {
191                 "functions tagged with `#[proc_macro_attribute]` must \
192                  currently reside in the root of the crate"
193             } else {
194                 "functions tagged with `#[proc_macro_attribute]` must be `pub`"
195             };
196             self.handler.span_err(item.span, msg);
197         }
198     }
199
200     fn collect_bang_proc_macro(&mut self, item: &'a ast::Item) {
201         if self.in_root && item.vis.node.is_pub() {
202             self.bang_macros.push(ProcMacroDef {
203                 span: item.span,
204                 function_name: item.ident,
205             });
206         } else {
207             let msg = if !self.in_root {
208                 "functions tagged with `#[proc_macro]` must \
209                  currently reside in the root of the crate"
210             } else {
211                 "functions tagged with `#[proc_macro]` must be `pub`"
212             };
213             self.handler.span_err(item.span, msg);
214         }
215     }
216 }
217
218 impl<'a> Visitor<'a> for CollectProcMacros<'a> {
219     fn visit_item(&mut self, item: &'a ast::Item) {
220         if let ast::ItemKind::MacroDef(..) = item.node {
221             if self.is_proc_macro_crate && attr::contains_name(&item.attrs, "macro_export") {
222                 let msg =
223                     "cannot export macro_rules! macros from a `proc-macro` crate type currently";
224                 self.handler.span_err(item.span, msg);
225             }
226         }
227
228         // First up, make sure we're checking a bare function. If we're not then
229         // we're just not interested in this item.
230         //
231         // If we find one, try to locate a `#[proc_macro_derive]` attribute on
232         // it.
233         let is_fn = match item.node {
234             ast::ItemKind::Fn(..) => true,
235             _ => false,
236         };
237
238         let mut found_attr: Option<&'a ast::Attribute> = None;
239
240         for attr in &item.attrs {
241             if is_proc_macro_attr(&attr) {
242                 if let Some(prev_attr) = found_attr {
243                     let msg = if attr.path.segments[0].ident.name ==
244                                  prev_attr.path.segments[0].ident.name {
245                         format!("Only one `#[{}]` attribute is allowed on any given function",
246                                 attr.path)
247                     } else {
248                         format!("`#[{}]` and `#[{}]` attributes cannot both be applied \
249                                 to the same function", attr.path, prev_attr.path)
250                     };
251
252                     self.handler.struct_span_err(attr.span(), &msg)
253                         .span_note(prev_attr.span(), "Previous attribute here")
254                         .emit();
255
256                     return;
257                 }
258
259                 found_attr = Some(attr);
260             }
261         }
262
263         let attr = match found_attr {
264             None => {
265                 self.check_not_pub_in_root(&item.vis, item.span);
266                 let prev_in_root = mem::replace(&mut self.in_root, false);
267                 visit::walk_item(self, item);
268                 self.in_root = prev_in_root;
269                 return;
270             },
271             Some(attr) => attr,
272         };
273
274         if !is_fn {
275             let msg = format!("the `#[{}]` attribute may only be used on bare functions",
276                               attr.path);
277
278             self.handler.span_err(attr.span(), &msg);
279             return;
280         }
281
282         if self.is_test_crate {
283             return;
284         }
285
286         if !self.is_proc_macro_crate {
287             let msg = format!("the `#[{}]` attribute is only usable with crates of the \
288                               `proc-macro` crate type", attr.path);
289
290             self.handler.span_err(attr.span(), &msg);
291             return;
292         }
293
294         if attr.check_name("proc_macro_derive") {
295             self.collect_custom_derive(item, attr);
296         } else if attr.check_name("proc_macro_attribute") {
297             self.collect_attr_proc_macro(item);
298         } else if attr.check_name("proc_macro") {
299             self.collect_bang_proc_macro(item);
300         };
301
302         let prev_in_root = mem::replace(&mut self.in_root, false);
303         visit::walk_item(self, item);
304         self.in_root = prev_in_root;
305     }
306
307     fn visit_mac(&mut self, mac: &ast::Mac) {
308         visit::walk_mac(self, mac)
309     }
310 }
311
312 // Creates a new module which looks like:
313 //
314 //      mod $gensym {
315 //          extern crate proc_macro;
316 //
317 //          use proc_macro::bridge::client::ProcMacro;
318 //
319 //          #[rustc_proc_macro_decls]
320 //          static DECLS: &[ProcMacro] = &[
321 //              ProcMacro::custom_derive($name_trait1, &[], ::$name1);
322 //              ProcMacro::custom_derive($name_trait2, &["attribute_name"], ::$name2);
323 //              // ...
324 //          ];
325 //      }
326 fn mk_decls(
327     cx: &mut ExtCtxt,
328     custom_derives: &[ProcMacroDerive],
329     custom_attrs: &[ProcMacroDef],
330     custom_macros: &[ProcMacroDef],
331 ) -> P<ast::Item> {
332     let mark = Mark::fresh(Mark::root());
333     mark.set_expn_info(ExpnInfo {
334         call_site: DUMMY_SP,
335         def_site: None,
336         format: MacroAttribute(Symbol::intern("proc_macro")),
337         allow_internal_unstable: true,
338         allow_internal_unsafe: false,
339         local_inner_macros: false,
340         edition: hygiene::default_edition(),
341     });
342     let span = DUMMY_SP.apply_mark(mark);
343
344     let proc_macro = Ident::from_str("proc_macro");
345     let krate = cx.item(span,
346                         proc_macro,
347                         Vec::new(),
348                         ast::ItemKind::ExternCrate(None));
349
350     let bridge = Ident::from_str("bridge");
351     let client = Ident::from_str("client");
352     let proc_macro_ty = Ident::from_str("ProcMacro");
353     let custom_derive = Ident::from_str("custom_derive");
354     let attr = Ident::from_str("attr");
355     let bang = Ident::from_str("bang");
356     let crate_kw = Ident::with_empty_ctxt(keywords::Crate.name());
357
358     let decls = {
359         let local_path = |sp: Span, name| {
360             cx.expr_path(cx.path(sp.with_ctxt(span.ctxt()), vec![crate_kw, name]))
361         };
362         let proc_macro_ty_method_path = |method| cx.expr_path(cx.path(span, vec![
363             proc_macro, bridge, client, proc_macro_ty, method,
364         ]));
365         custom_derives.iter().map(|cd| {
366             cx.expr_call(span, proc_macro_ty_method_path(custom_derive), vec![
367                 cx.expr_str(cd.span, cd.trait_name),
368                 cx.expr_vec_slice(
369                     span,
370                     cd.attrs.iter().map(|&s| cx.expr_str(cd.span, s)).collect::<Vec<_>>()
371                 ),
372                 local_path(cd.span, cd.function_name),
373             ])
374         }).chain(custom_attrs.iter().map(|ca| {
375             cx.expr_call(span, proc_macro_ty_method_path(attr), vec![
376                 cx.expr_str(ca.span, ca.function_name.name),
377                 local_path(ca.span, ca.function_name),
378             ])
379         })).chain(custom_macros.iter().map(|cm| {
380             cx.expr_call(span, proc_macro_ty_method_path(bang), vec![
381                 cx.expr_str(cm.span, cm.function_name.name),
382                 local_path(cm.span, cm.function_name),
383             ])
384         })).collect()
385     };
386
387     let decls_static = cx.item_static(
388         span,
389         Ident::from_str("_DECLS"),
390         cx.ty_rptr(span,
391             cx.ty(span, ast::TyKind::Slice(
392                 cx.ty_path(cx.path(span,
393                     vec![proc_macro, bridge, client, proc_macro_ty])))),
394             None, ast::Mutability::Immutable),
395         ast::Mutability::Immutable,
396         cx.expr_vec_slice(span, decls),
397     ).map(|mut i| {
398         let attr = cx.meta_word(span, Symbol::intern("rustc_proc_macro_decls"));
399         i.attrs.push(cx.attribute(span, attr));
400         i.vis = respan(span, ast::VisibilityKind::Public);
401         i
402     });
403
404     let module = cx.item_mod(
405         span,
406         span,
407         ast::Ident::with_empty_ctxt(Symbol::gensym("decls")),
408         vec![],
409         vec![krate, decls_static],
410     ).map(|mut i| {
411         i.vis = respan(span, ast::VisibilityKind::Public);
412         i
413     });
414
415     cx.monotonic_expander().fold_item(module).pop().unwrap()
416 }