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