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