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