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