]> git.lizzy.rs Git - rust.git/blob - src/libsyntax_ext/proc_macro_harness.rs
Rename `Stmt.node` to `Stmt.kind`
[rust.git] / src / libsyntax_ext / proc_macro_harness.rs
1 use std::mem;
2
3 use smallvec::smallvec;
4 use syntax::ast::{self, Ident};
5 use syntax::attr;
6 use syntax::ext::base::ExtCtxt;
7 use syntax::ext::expand::{AstFragment, ExpansionConfig};
8 use syntax::ext::proc_macro::is_proc_macro_attr;
9 use syntax::parse::ParseSess;
10 use syntax::ptr::P;
11 use syntax::symbol::{kw, sym};
12 use syntax::visit::{self, Visitor};
13 use syntax_pos::{Span, DUMMY_SP};
14 use syntax_pos::hygiene::AstPass;
15
16 struct ProcMacroDerive {
17     trait_name: ast::Name,
18     function_name: Ident,
19     span: Span,
20     attrs: Vec<ast::Name>,
21 }
22
23 enum ProcMacroDefType {
24     Attr,
25     Bang
26 }
27
28 struct ProcMacroDef {
29     function_name: Ident,
30     span: Span,
31     def_type: ProcMacroDefType
32 }
33
34 enum ProcMacro {
35     Derive(ProcMacroDerive),
36     Def(ProcMacroDef)
37 }
38
39 struct CollectProcMacros<'a> {
40     macros: Vec<ProcMacro>,
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 inject(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 mut collect = CollectProcMacros {
59         macros: Vec::new(),
60         in_root: true,
61         handler,
62         is_proc_macro_crate,
63         is_test_crate,
64     };
65
66     if has_proc_macro_decls || is_proc_macro_crate {
67         visit::walk_crate(&mut collect, &krate);
68     }
69     // NOTE: If you change the order of macros in this vec
70     // for any reason, you must also update 'raw_proc_macro'
71     // in src/librustc_metadata/decoder.rs
72     let macros = collect.macros;
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, &macros));
87
88     krate
89 }
90
91 impl<'a> CollectProcMacros<'a> {
92     fn check_not_pub_in_root(&self, vis: &ast::Visibility, sp: Span) {
93         if self.is_proc_macro_crate && self.in_root && vis.node.is_pub() {
94             self.handler.span_err(sp,
95                                   "`proc-macro` crate types cannot \
96                                    export any items other than functions \
97                                    tagged with `#[proc_macro_derive]` currently");
98         }
99     }
100
101     fn collect_custom_derive(&mut self, item: &'a ast::Item, attr: &'a ast::Attribute) {
102         // Once we've located the `#[proc_macro_derive]` attribute, verify
103         // that it's of the form `#[proc_macro_derive(Foo)]` or
104         // `#[proc_macro_derive(Foo, attributes(A, ..))]`
105         let list = match attr.meta_item_list() {
106             Some(list) => list,
107             None => return,
108         };
109         if list.len() != 1 && list.len() != 2 {
110             self.handler.span_err(attr.span,
111                                   "attribute must have either one or two arguments");
112             return
113         }
114         let trait_attr = match list[0].meta_item() {
115             Some(meta_item) => meta_item,
116             _ => {
117                 self.handler.span_err(list[0].span(), "not a meta item");
118                 return
119             }
120         };
121         let trait_ident = match trait_attr.ident() {
122             Some(trait_ident) if trait_attr.is_word() => trait_ident,
123             _ => {
124                 self.handler.span_err(trait_attr.span, "must only be one word");
125                 return
126             }
127         };
128
129         if !trait_ident.name.can_be_raw() {
130             self.handler.span_err(trait_attr.span,
131                                   &format!("`{}` cannot be a name of derive macro", trait_ident));
132         }
133
134         let attributes_attr = list.get(1);
135         let proc_attrs: Vec<_> = if let Some(attr) = attributes_attr {
136             if !attr.check_name(sym::attributes) {
137                 self.handler.span_err(attr.span(), "second argument must be `attributes`")
138             }
139             attr.meta_item_list().unwrap_or_else(|| {
140                 self.handler.span_err(attr.span(),
141                                       "attribute must be of form: `attributes(foo, bar)`");
142                 &[]
143             }).into_iter().filter_map(|attr| {
144                 let attr = match attr.meta_item() {
145                     Some(meta_item) => meta_item,
146                     _ => {
147                         self.handler.span_err(attr.span(), "not a meta item");
148                         return None;
149                     }
150                 };
151
152                 let ident = match attr.ident() {
153                     Some(ident) if attr.is_word() => ident,
154                     _ => {
155                         self.handler.span_err(attr.span, "must only be one word");
156                         return None;
157                     }
158                 };
159                 if !ident.name.can_be_raw() {
160                     self.handler.span_err(
161                         attr.span,
162                         &format!("`{}` cannot be a name of derive helper attribute", ident),
163                     );
164                 }
165
166                 Some(ident.name)
167             }).collect()
168         } else {
169             Vec::new()
170         };
171
172         if self.in_root && item.vis.node.is_pub() {
173             self.macros.push(ProcMacro::Derive(ProcMacroDerive {
174                 span: item.span,
175                 trait_name: trait_ident.name,
176                 function_name: item.ident,
177                 attrs: proc_attrs,
178             }));
179         } else {
180             let msg = if !self.in_root {
181                 "functions tagged with `#[proc_macro_derive]` must \
182                  currently reside in the root of the crate"
183             } else {
184                 "functions tagged with `#[proc_macro_derive]` must be `pub`"
185             };
186             self.handler.span_err(item.span, msg);
187         }
188     }
189
190     fn collect_attr_proc_macro(&mut self, item: &'a ast::Item) {
191         if self.in_root && item.vis.node.is_pub() {
192             self.macros.push(ProcMacro::Def(ProcMacroDef {
193                 span: item.span,
194                 function_name: item.ident,
195                 def_type: ProcMacroDefType::Attr
196             }));
197         } else {
198             let msg = if !self.in_root {
199                 "functions tagged with `#[proc_macro_attribute]` must \
200                  currently reside in the root of the crate"
201             } else {
202                 "functions tagged with `#[proc_macro_attribute]` must be `pub`"
203             };
204             self.handler.span_err(item.span, msg);
205         }
206     }
207
208     fn collect_bang_proc_macro(&mut self, item: &'a ast::Item) {
209         if self.in_root && item.vis.node.is_pub() {
210             self.macros.push(ProcMacro::Def(ProcMacroDef {
211                 span: item.span,
212                 function_name: item.ident,
213                 def_type: ProcMacroDefType::Bang
214             }));
215         } else {
216             let msg = if !self.in_root {
217                 "functions tagged with `#[proc_macro]` must \
218                  currently reside in the root of the crate"
219             } else {
220                 "functions tagged with `#[proc_macro]` must be `pub`"
221             };
222             self.handler.span_err(item.span, msg);
223         }
224     }
225 }
226
227 impl<'a> Visitor<'a> for CollectProcMacros<'a> {
228     fn visit_item(&mut self, item: &'a ast::Item) {
229         if let ast::ItemKind::MacroDef(..) = item.node {
230             if self.is_proc_macro_crate && attr::contains_name(&item.attrs, sym::macro_export) {
231                 let msg =
232                     "cannot export macro_rules! macros from a `proc-macro` crate type currently";
233                 self.handler.span_err(item.span, msg);
234             }
235         }
236
237         // First up, make sure we're checking a bare function. If we're not then
238         // we're just not interested in this item.
239         //
240         // If we find one, try to locate a `#[proc_macro_derive]` attribute on it.
241         let is_fn = match item.node {
242             ast::ItemKind::Fn(..) => true,
243             _ => false,
244         };
245
246         let mut found_attr: Option<&'a ast::Attribute> = None;
247
248         for attr in &item.attrs {
249             if is_proc_macro_attr(&attr) {
250                 if let Some(prev_attr) = found_attr {
251                     let msg = if attr.path.segments[0].ident.name ==
252                                  prev_attr.path.segments[0].ident.name {
253                         format!("only one `#[{}]` attribute is allowed on any given function",
254                                 attr.path)
255                     } else {
256                         format!("`#[{}]` and `#[{}]` attributes cannot both be applied \
257                                 to the same function", attr.path, prev_attr.path)
258                     };
259
260                     self.handler.struct_span_err(attr.span, &msg)
261                         .span_note(prev_attr.span, "previous attribute here")
262                         .emit();
263
264                     return;
265                 }
266
267                 found_attr = Some(attr);
268             }
269         }
270
271         let attr = match found_attr {
272             None => {
273                 self.check_not_pub_in_root(&item.vis, item.span);
274                 let prev_in_root = mem::replace(&mut self.in_root, false);
275                 visit::walk_item(self, item);
276                 self.in_root = prev_in_root;
277                 return;
278             },
279             Some(attr) => attr,
280         };
281
282         if !is_fn {
283             let msg = format!("the `#[{}]` attribute may only be used on bare functions",
284                               attr.path);
285
286             self.handler.span_err(attr.span, &msg);
287             return;
288         }
289
290         if self.is_test_crate {
291             return;
292         }
293
294         if !self.is_proc_macro_crate {
295             let msg = format!("the `#[{}]` attribute is only usable with crates of the \
296                               `proc-macro` crate type", attr.path);
297
298             self.handler.span_err(attr.span, &msg);
299             return;
300         }
301
302         if attr.check_name(sym::proc_macro_derive) {
303             self.collect_custom_derive(item, attr);
304         } else if attr.check_name(sym::proc_macro_attribute) {
305             self.collect_attr_proc_macro(item);
306         } else if attr.check_name(sym::proc_macro) {
307             self.collect_bang_proc_macro(item);
308         };
309
310         let prev_in_root = mem::replace(&mut self.in_root, false);
311         visit::walk_item(self, item);
312         self.in_root = prev_in_root;
313     }
314
315     fn visit_mac(&mut self, mac: &'a ast::Mac) {
316         visit::walk_mac(self, mac)
317     }
318 }
319
320 // Creates a new module which looks like:
321 //
322 //      const _: () = {
323 //          extern crate proc_macro;
324 //
325 //          use proc_macro::bridge::client::ProcMacro;
326 //
327 //          #[rustc_proc_macro_decls]
328 //          static DECLS: &[ProcMacro] = &[
329 //              ProcMacro::custom_derive($name_trait1, &[], ::$name1);
330 //              ProcMacro::custom_derive($name_trait2, &["attribute_name"], ::$name2);
331 //              // ...
332 //          ];
333 //      }
334 fn mk_decls(
335     cx: &mut ExtCtxt<'_>,
336     macros: &[ProcMacro],
337 ) -> P<ast::Item> {
338     let expn_id = cx.resolver.expansion_for_ast_pass(
339         DUMMY_SP,
340         AstPass::ProcMacroHarness,
341         &[sym::rustc_attrs, sym::proc_macro_internals],
342         None,
343     );
344     let span = DUMMY_SP.with_def_site_ctxt(expn_id);
345
346     let proc_macro = Ident::new(sym::proc_macro, span);
347     let krate = cx.item(span,
348                         proc_macro,
349                         Vec::new(),
350                         ast::ItemKind::ExternCrate(None));
351
352     let bridge = cx.ident_of("bridge", span);
353     let client = cx.ident_of("client", span);
354     let proc_macro_ty = cx.ident_of("ProcMacro", span);
355     let custom_derive = cx.ident_of("custom_derive", span);
356     let attr = cx.ident_of("attr", span);
357     let bang = cx.ident_of("bang", span);
358
359     let decls = {
360         let local_path = |sp: Span, name| {
361             cx.expr_path(cx.path(sp.with_ctxt(span.ctxt()), vec![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         macros.iter().map(|m| {
367             match m {
368                 ProcMacro::Derive(cd) => {
369                     cx.expr_call(span, proc_macro_ty_method_path(custom_derive), vec![
370                         cx.expr_str(cd.span, cd.trait_name),
371                         cx.expr_vec_slice(
372                             span,
373                             cd.attrs.iter().map(|&s| cx.expr_str(cd.span, s)).collect::<Vec<_>>()
374                         ),
375                         local_path(cd.span, cd.function_name),
376                     ])
377                 },
378                 ProcMacro::Def(ca) => {
379                     let ident = match ca.def_type {
380                         ProcMacroDefType::Attr => attr,
381                         ProcMacroDefType::Bang => bang
382                     };
383
384                     cx.expr_call(span, proc_macro_ty_method_path(ident), vec![
385                         cx.expr_str(ca.span, ca.function_name.name),
386                         local_path(ca.span, ca.function_name),
387                     ])
388
389                 }
390             }
391         }).collect()
392     };
393
394     let decls_static = cx.item_static(
395         span,
396         cx.ident_of("_DECLS", span),
397         cx.ty_rptr(span,
398             cx.ty(span, ast::TyKind::Slice(
399                 cx.ty_path(cx.path(span,
400                     vec![proc_macro, bridge, client, proc_macro_ty])))),
401             None, ast::Mutability::Immutable),
402         ast::Mutability::Immutable,
403         cx.expr_vec_slice(span, decls),
404     ).map(|mut i| {
405         let attr = cx.meta_word(span, sym::rustc_proc_macro_decls);
406         i.attrs.push(cx.attribute(attr));
407         i
408     });
409
410     let block = cx.expr_block(cx.block(
411         span,
412         vec![cx.stmt_item(span, krate), cx.stmt_item(span, decls_static)],
413     ));
414
415     let anon_constant = cx.item_const(
416         span,
417         ast::Ident::new(kw::Underscore, span),
418         cx.ty(span, ast::TyKind::Tup(Vec::new())),
419         block,
420     );
421
422     // Integrate the new item into existing module structures.
423     let items = AstFragment::Items(smallvec![anon_constant]);
424     cx.monotonic_expander().fully_expand_fragment(items).make_items().pop().unwrap()
425 }