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