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