]> git.lizzy.rs Git - rust.git/blob - src/libsyntax_ext/proc_macro_decls.rs
Auto merge of #58302 - SimonSapin:tryfrom, r=alexcrichton
[rust.git] / src / libsyntax_ext / proc_macro_decls.rs
1 use std::mem;
2
3 use crate::deriving;
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::mut_visit::MutVisitor;
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 const PROC_MACRO_KINDS: [&str; 3] = ["proc_macro_derive", "proc_macro_attribute", "proc_macro"];
22
23 struct ProcMacroDerive {
24     trait_name: ast::Name,
25     function_name: Ident,
26     span: Span,
27     attrs: Vec<ast::Name>,
28 }
29
30 struct ProcMacroDef {
31     function_name: Ident,
32     span: Span,
33 }
34
35 struct CollectProcMacros<'a> {
36     derives: Vec<ProcMacroDerive>,
37     attr_macros: Vec<ProcMacroDef>,
38     bang_macros: Vec<ProcMacroDef>,
39     in_root: bool,
40     handler: &'a errors::Handler,
41     is_proc_macro_crate: bool,
42     is_test_crate: bool,
43 }
44
45 pub fn modify(sess: &ParseSess,
46               resolver: &mut dyn (::syntax::ext::base::Resolver),
47               mut krate: ast::Crate,
48               is_proc_macro_crate: bool,
49               has_proc_macro_decls: bool,
50               is_test_crate: bool,
51               num_crate_types: usize,
52               handler: &errors::Handler) -> ast::Crate {
53     let ecfg = ExpansionConfig::default("proc_macro".to_string());
54     let mut cx = ExtCtxt::new(sess, ecfg, resolver);
55
56     let (derives, attr_macros, bang_macros) = {
57         let mut collect = CollectProcMacros {
58             derives: Vec::new(),
59             attr_macros: Vec::new(),
60             bang_macros: Vec::new(),
61             in_root: true,
62             handler,
63             is_proc_macro_crate,
64             is_test_crate,
65         };
66         if has_proc_macro_decls || is_proc_macro_crate {
67             visit::walk_crate(&mut collect, &krate);
68         }
69         (collect.derives, collect.attr_macros, collect.bang_macros)
70     };
71
72     if !is_proc_macro_crate {
73         return krate
74     }
75
76     if num_crate_types > 1 {
77         handler.err("cannot mix `proc-macro` crate type with others");
78     }
79
80     if is_test_crate {
81         return krate;
82     }
83
84     krate.module.items.push(mk_decls(&mut cx, &derives, &attr_macros, &bang_macros));
85
86     krate
87 }
88
89 pub fn is_proc_macro_attr(attr: &ast::Attribute) -> bool {
90     PROC_MACRO_KINDS.iter().any(|kind| attr.check_name(kind))
91 }
92
93 impl<'a> CollectProcMacros<'a> {
94     fn check_not_pub_in_root(&self, vis: &ast::Visibility, sp: Span) {
95         if self.is_proc_macro_crate && self.in_root && vis.node.is_pub() {
96             self.handler.span_err(sp,
97                                   "`proc-macro` crate types cannot \
98                                    export any items other than functions \
99                                    tagged with `#[proc_macro_derive]` currently");
100         }
101     }
102
103     fn collect_custom_derive(&mut self, item: &'a ast::Item, attr: &'a ast::Attribute) {
104         // Once we've located the `#[proc_macro_derive]` attribute, verify
105         // that it's of the form `#[proc_macro_derive(Foo)]` or
106         // `#[proc_macro_derive(Foo, attributes(A, ..))]`
107         let list = match attr.meta_item_list() {
108             Some(list) => list,
109             None => return,
110         };
111         if list.len() != 1 && list.len() != 2 {
112             self.handler.span_err(attr.span(),
113                                   "attribute must have either one or two arguments");
114             return
115         }
116         let trait_attr = &list[0];
117         let attributes_attr = list.get(1);
118         let trait_name = match trait_attr.name() {
119             Some(name) => name,
120             _ => {
121                 self.handler.span_err(trait_attr.span(), "not a meta item");
122                 return
123             }
124         };
125         if !trait_attr.is_word() {
126             self.handler.span_err(trait_attr.span(), "must only be one word");
127         }
128
129         if deriving::is_builtin_trait(trait_name) {
130             self.handler.span_err(trait_attr.span(),
131                                   "cannot override a built-in #[derive] mode");
132         }
133
134         let proc_attrs: Vec<_> = if let Some(attr) = attributes_attr {
135             if !attr.check_name("attributes") {
136                 self.handler.span_err(attr.span(), "second argument must be `attributes`")
137             }
138             attr.meta_item_list().unwrap_or_else(|| {
139                 self.handler.span_err(attr.span(),
140                                       "attribute must be of form: \
141                                        `attributes(foo, bar)`");
142                 &[]
143             }).into_iter().filter_map(|attr| {
144                 let name = match attr.name() {
145                     Some(name) => name,
146                     _ => {
147                         self.handler.span_err(attr.span(), "not a meta item");
148                         return None;
149                     },
150                 };
151
152                 if !attr.is_word() {
153                     self.handler.span_err(attr.span(), "must only be one word");
154                     return None;
155                 }
156
157                 Some(name)
158             }).collect()
159         } else {
160             Vec::new()
161         };
162
163         if self.in_root && item.vis.node.is_pub() {
164             self.derives.push(ProcMacroDerive {
165                 span: item.span,
166                 trait_name,
167                 function_name: item.ident,
168                 attrs: proc_attrs,
169             });
170         } else {
171             let msg = if !self.in_root {
172                 "functions tagged with `#[proc_macro_derive]` must \
173                  currently reside in the root of the crate"
174             } else {
175                 "functions tagged with `#[proc_macro_derive]` must be `pub`"
176             };
177             self.handler.span_err(item.span, msg);
178         }
179     }
180
181     fn collect_attr_proc_macro(&mut self, item: &'a ast::Item) {
182         if self.in_root && item.vis.node.is_pub() {
183             self.attr_macros.push(ProcMacroDef {
184                 span: item.span,
185                 function_name: item.ident,
186             });
187         } else {
188             let msg = if !self.in_root {
189                 "functions tagged with `#[proc_macro_attribute]` must \
190                  currently reside in the root of the crate"
191             } else {
192                 "functions tagged with `#[proc_macro_attribute]` must be `pub`"
193             };
194             self.handler.span_err(item.span, msg);
195         }
196     }
197
198     fn collect_bang_proc_macro(&mut self, item: &'a ast::Item) {
199         if self.in_root && item.vis.node.is_pub() {
200             self.bang_macros.push(ProcMacroDef {
201                 span: item.span,
202                 function_name: item.ident,
203             });
204         } else {
205             let msg = if !self.in_root {
206                 "functions tagged with `#[proc_macro]` must \
207                  currently reside in the root of the crate"
208             } else {
209                 "functions tagged with `#[proc_macro]` must be `pub`"
210             };
211             self.handler.span_err(item.span, msg);
212         }
213     }
214 }
215
216 impl<'a> Visitor<'a> for CollectProcMacros<'a> {
217     fn visit_item(&mut self, item: &'a ast::Item) {
218         if let ast::ItemKind::MacroDef(..) = item.node {
219             if self.is_proc_macro_crate && attr::contains_name(&item.attrs, "macro_export") {
220                 let msg =
221                     "cannot export macro_rules! macros from a `proc-macro` crate type currently";
222                 self.handler.span_err(item.span, msg);
223             }
224         }
225
226         // First up, make sure we're checking a bare function. If we're not then
227         // we're just not interested in this item.
228         //
229         // If we find one, try to locate a `#[proc_macro_derive]` attribute on
230         // it.
231         let is_fn = match item.node {
232             ast::ItemKind::Fn(..) => true,
233             _ => false,
234         };
235
236         let mut found_attr: Option<&'a ast::Attribute> = None;
237
238         for attr in &item.attrs {
239             if is_proc_macro_attr(&attr) {
240                 if let Some(prev_attr) = found_attr {
241                     let msg = if attr.path.segments[0].ident.name ==
242                                  prev_attr.path.segments[0].ident.name {
243                         format!("Only one `#[{}]` attribute is allowed on any given function",
244                                 attr.path)
245                     } else {
246                         format!("`#[{}]` and `#[{}]` attributes cannot both be applied \
247                                 to the same function", attr.path, prev_attr.path)
248                     };
249
250                     self.handler.struct_span_err(attr.span(), &msg)
251                         .span_note(prev_attr.span(), "Previous attribute here")
252                         .emit();
253
254                     return;
255                 }
256
257                 found_attr = Some(attr);
258             }
259         }
260
261         let attr = match found_attr {
262             None => {
263                 self.check_not_pub_in_root(&item.vis, item.span);
264                 let prev_in_root = mem::replace(&mut self.in_root, false);
265                 visit::walk_item(self, item);
266                 self.in_root = prev_in_root;
267                 return;
268             },
269             Some(attr) => attr,
270         };
271
272         if !is_fn {
273             let msg = format!("the `#[{}]` attribute may only be used on bare functions",
274                               attr.path);
275
276             self.handler.span_err(attr.span(), &msg);
277             return;
278         }
279
280         if self.is_test_crate {
281             return;
282         }
283
284         if !self.is_proc_macro_crate {
285             let msg = format!("the `#[{}]` attribute is only usable with crates of the \
286                               `proc-macro` crate type", attr.path);
287
288             self.handler.span_err(attr.span(), &msg);
289             return;
290         }
291
292         if attr.check_name("proc_macro_derive") {
293             self.collect_custom_derive(item, attr);
294         } else if attr.check_name("proc_macro_attribute") {
295             self.collect_attr_proc_macro(item);
296         } else if attr.check_name("proc_macro") {
297             self.collect_bang_proc_macro(item);
298         };
299
300         let prev_in_root = mem::replace(&mut self.in_root, false);
301         visit::walk_item(self, item);
302         self.in_root = prev_in_root;
303     }
304
305     fn visit_mac(&mut self, mac: &ast::Mac) {
306         visit::walk_mac(self, mac)
307     }
308 }
309
310 // Creates a new module which looks like:
311 //
312 //      mod $gensym {
313 //          extern crate proc_macro;
314 //
315 //          use proc_macro::bridge::client::ProcMacro;
316 //
317 //          #[rustc_proc_macro_decls]
318 //          static DECLS: &[ProcMacro] = &[
319 //              ProcMacro::custom_derive($name_trait1, &[], ::$name1);
320 //              ProcMacro::custom_derive($name_trait2, &["attribute_name"], ::$name2);
321 //              // ...
322 //          ];
323 //      }
324 fn mk_decls(
325     cx: &mut ExtCtxt<'_>,
326     custom_derives: &[ProcMacroDerive],
327     custom_attrs: &[ProcMacroDef],
328     custom_macros: &[ProcMacroDef],
329 ) -> P<ast::Item> {
330     let mark = Mark::fresh(Mark::root());
331     mark.set_expn_info(ExpnInfo {
332         call_site: DUMMY_SP,
333         def_site: None,
334         format: MacroAttribute(Symbol::intern("proc_macro")),
335         allow_internal_unstable: Some(vec![
336             Symbol::intern("rustc_attrs"),
337             Symbol::intern("proc_macro_internals"),
338         ].into()),
339         allow_internal_unsafe: false,
340         local_inner_macros: false,
341         edition: hygiene::default_edition(),
342     });
343     let span = DUMMY_SP.apply_mark(mark);
344
345     let proc_macro = Ident::from_str("proc_macro");
346     let krate = cx.item(span,
347                         proc_macro,
348                         Vec::new(),
349                         ast::ItemKind::ExternCrate(None));
350
351     let bridge = Ident::from_str("bridge");
352     let client = Ident::from_str("client");
353     let proc_macro_ty = Ident::from_str("ProcMacro");
354     let custom_derive = Ident::from_str("custom_derive");
355     let attr = Ident::from_str("attr");
356     let bang = Ident::from_str("bang");
357     let crate_kw = Ident::with_empty_ctxt(keywords::Crate.name());
358
359     let decls = {
360         let local_path = |sp: Span, name| {
361             cx.expr_path(cx.path(sp.with_ctxt(span.ctxt()), vec![crate_kw, name]))
362         };
363         let proc_macro_ty_method_path = |method| cx.expr_path(cx.path(span, vec![
364             proc_macro, bridge, client, proc_macro_ty, method,
365         ]));
366         custom_derives.iter().map(|cd| {
367             cx.expr_call(span, proc_macro_ty_method_path(custom_derive), vec![
368                 cx.expr_str(cd.span, cd.trait_name),
369                 cx.expr_vec_slice(
370                     span,
371                     cd.attrs.iter().map(|&s| cx.expr_str(cd.span, s)).collect::<Vec<_>>()
372                 ),
373                 local_path(cd.span, cd.function_name),
374             ])
375         }).chain(custom_attrs.iter().map(|ca| {
376             cx.expr_call(span, proc_macro_ty_method_path(attr), vec![
377                 cx.expr_str(ca.span, ca.function_name.name),
378                 local_path(ca.span, ca.function_name),
379             ])
380         })).chain(custom_macros.iter().map(|cm| {
381             cx.expr_call(span, proc_macro_ty_method_path(bang), vec![
382                 cx.expr_str(cm.span, cm.function_name.name),
383                 local_path(cm.span, cm.function_name),
384             ])
385         })).collect()
386     };
387
388     let decls_static = cx.item_static(
389         span,
390         Ident::from_str("_DECLS"),
391         cx.ty_rptr(span,
392             cx.ty(span, ast::TyKind::Slice(
393                 cx.ty_path(cx.path(span,
394                     vec![proc_macro, bridge, client, proc_macro_ty])))),
395             None, ast::Mutability::Immutable),
396         ast::Mutability::Immutable,
397         cx.expr_vec_slice(span, decls),
398     ).map(|mut i| {
399         let attr = cx.meta_word(span, Symbol::intern("rustc_proc_macro_decls"));
400         i.attrs.push(cx.attribute(span, attr));
401         i.vis = respan(span, ast::VisibilityKind::Public);
402         i
403     });
404
405     let module = cx.item_mod(
406         span,
407         span,
408         ast::Ident::with_empty_ctxt(Symbol::gensym("decls")),
409         vec![],
410         vec![krate, decls_static],
411     ).map(|mut i| {
412         i.vis = respan(span, ast::VisibilityKind::Public);
413         i
414     });
415
416     cx.monotonic_expander().flat_map_item(module).pop().unwrap()
417 }