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};
11 use syntax::expand::is_proc_macro_attr;
12 use syntax::print::pprust;
14 use syntax::sess::ParseSess;
15 use syntax::visit::{self, Visitor};
17 struct ProcMacroDerive {
18 trait_name: ast::Name,
21 attrs: Vec<ast::Name>,
24 enum ProcMacroDefType {
32 def_type: ProcMacroDefType,
36 Derive(ProcMacroDerive),
40 struct CollectProcMacros<'a> {
41 macros: Vec<ProcMacro>,
43 handler: &'a rustc_errors::Handler,
44 is_proc_macro_crate: bool,
50 resolver: &mut dyn Resolver,
51 mut krate: ast::Crate,
52 is_proc_macro_crate: bool,
53 has_proc_macro_decls: bool,
55 num_crate_types: usize,
56 handler: &rustc_errors::Handler,
58 let ecfg = ExpansionConfig::default("proc_macro".to_string());
59 let mut cx = ExtCtxt::new(sess, ecfg, resolver);
61 let mut collect = CollectProcMacros {
69 if has_proc_macro_decls || is_proc_macro_crate {
70 visit::walk_crate(&mut collect, &krate);
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;
77 if !is_proc_macro_crate {
81 if num_crate_types > 1 {
82 handler.err("cannot mix `proc-macro` crate type with others");
89 krate.module.items.push(mk_decls(&mut cx, ¯os));
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(
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]`",
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() {
114 if list.len() != 1 && list.len() != 2 {
115 self.handler.span_err(attr.span, "attribute must have either one or two arguments");
118 let trait_attr = match list[0].meta_item() {
119 Some(meta_item) => meta_item,
121 self.handler.span_err(list[0].span(), "not a meta item");
125 let trait_ident = match trait_attr.ident() {
126 Some(trait_ident) if trait_attr.is_word() => trait_ident,
128 self.handler.span_err(trait_attr.span, "must only be one word");
133 if !trait_ident.name.can_be_raw() {
134 self.handler.span_err(
136 &format!("`{}` cannot be a name of derive macro", trait_ident),
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`")
145 attr.meta_item_list()
148 .span_err(attr.span(), "attribute must be of form: `attributes(foo, bar)`");
153 let attr = match attr.meta_item() {
154 Some(meta_item) => meta_item,
156 self.handler.span_err(attr.span(), "not a meta item");
161 let ident = match attr.ident() {
162 Some(ident) if attr.is_word() => ident,
164 self.handler.span_err(attr.span, "must only be one word");
168 if !ident.name.can_be_raw() {
169 self.handler.span_err(
171 &format!("`{}` cannot be a name of derive helper attribute", ident),
182 if self.in_root && item.vis.node.is_pub() {
183 self.macros.push(ProcMacro::Derive(ProcMacroDerive {
185 trait_name: trait_ident.name,
186 function_name: item.ident,
190 let msg = if !self.in_root {
191 "functions tagged with `#[proc_macro_derive]` must \
192 currently reside in the root of the crate"
194 "functions tagged with `#[proc_macro_derive]` must be `pub`"
196 self.handler.span_err(item.span, msg);
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 {
204 function_name: item.ident,
205 def_type: ProcMacroDefType::Attr,
208 let msg = if !self.in_root {
209 "functions tagged with `#[proc_macro_attribute]` must \
210 currently reside in the root of the crate"
212 "functions tagged with `#[proc_macro_attribute]` must be `pub`"
214 self.handler.span_err(item.span, msg);
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 {
222 function_name: item.ident,
223 def_type: ProcMacroDefType::Bang,
226 let msg = if !self.in_root {
227 "functions tagged with `#[proc_macro]` must \
228 currently reside in the root of the crate"
230 "functions tagged with `#[proc_macro]` must be `pub`"
232 self.handler.span_err(item.span, msg);
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) {
242 "cannot export macro_rules! macros from a `proc-macro` crate type currently";
243 self.handler.span_err(item.span, msg);
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.
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,
256 let mut found_attr: Option<&'a ast::Attribute> = None;
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
268 "only one `#[{}]` attribute is allowed on any given function",
273 "`#[{}]` and `#[{}]` attributes cannot both be applied
274 to the same function",
276 pprust::path_to_string(&prev_item.path),
281 .struct_span_err(attr.span, &msg)
282 .span_label(prev_attr.span, "previous attribute here")
288 found_attr = Some(attr);
292 let attr = match found_attr {
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;
305 "the `#[{}]` attribute may only be used on bare functions",
306 pprust::path_to_string(&attr.get_normal_item().path),
309 self.handler.span_err(attr.span, &msg);
313 if self.is_test_crate {
317 if !self.is_proc_macro_crate {
319 "the `#[{}]` attribute is only usable with crates of the `proc-macro` crate type",
320 pprust::path_to_string(&attr.get_normal_item().path),
323 self.handler.span_err(attr.span, &msg);
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);
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;
340 fn visit_mac(&mut self, mac: &'a ast::Mac) {
341 visit::walk_mac(self, mac)
345 // Creates a new module which looks like:
348 // extern crate proc_macro;
350 // use proc_macro::bridge::client::ProcMacro;
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);
360 fn mk_decls(cx: &mut ExtCtxt<'_>, macros: &[ProcMacro]) -> P<ast::Item> {
361 let expn_id = cx.resolver.expansion_for_ast_pass(
363 AstPass::ProcMacroHarness,
364 &[sym::rustc_attrs, sym::proc_macro_internals],
367 let span = DUMMY_SP.with_def_site_ctxt(expn_id);
369 let proc_macro = Ident::new(sym::proc_macro, span);
370 let krate = cx.item(span, proc_macro, Vec::new(), ast::ItemKind::ExternCrate(None));
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);
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]))
388 ProcMacro::Derive(cd) => cx.expr_call(
390 proc_macro_ty_method_path(custom_derive),
392 cx.expr_str(cd.span, cd.trait_name),
395 cd.attrs.iter().map(|&s| cx.expr_str(cd.span, s)).collect::<Vec<_>>(),
397 local_path(cd.span, cd.function_name),
400 ProcMacro::Def(ca) => {
401 let ident = match ca.def_type {
402 ProcMacroDefType::Attr => attr,
403 ProcMacroDefType::Bang => bang,
408 proc_macro_ty_method_path(ident),
410 cx.expr_str(ca.span, ca.function_name.name),
411 local_path(ca.span, ca.function_name),
419 let decls_static = cx
422 cx.ident_of("_DECLS", span),
428 cx.ty_path(cx.path(span, vec![proc_macro, bridge, client, proc_macro_ty])),
432 ast::Mutability::Not,
434 ast::Mutability::Not,
435 cx.expr_vec_slice(span, decls),
438 let attr = cx.meta_word(span, sym::rustc_proc_macro_decls);
439 i.attrs.push(cx.attribute(attr));
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));
449 let block = cx.expr_block(
450 cx.block(span, vec![cx.stmt_item(span, krate), cx.stmt_item(span, decls_static)]),
453 let anon_constant = cx.item_const(
455 ast::Ident::new(kw::Underscore, span),
456 cx.ty(span, ast::TyKind::Tup(Vec::new())),
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()