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