3 use smallvec::smallvec;
4 use syntax::ast::{self, Ident};
6 use syntax::ext::base::ExtCtxt;
7 use syntax::ext::expand::{AstFragment, ExpansionConfig};
8 use syntax::ext::proc_macro::is_proc_macro_attr;
9 use syntax::parse::ParseSess;
11 use syntax::symbol::{kw, sym};
12 use syntax::visit::{self, Visitor};
13 use syntax_pos::{Span, DUMMY_SP};
14 use syntax_pos::hygiene::AstPass;
16 struct ProcMacroDerive {
17 trait_name: ast::Name,
20 attrs: Vec<ast::Name>,
23 enum ProcMacroDefType {
31 def_type: ProcMacroDefType
35 Derive(ProcMacroDerive),
39 struct CollectProcMacros<'a> {
40 macros: Vec<ProcMacro>,
42 handler: &'a errors::Handler,
43 is_proc_macro_crate: bool,
47 pub fn inject(sess: &ParseSess,
48 resolver: &mut dyn (::syntax::ext::base::Resolver),
49 mut krate: ast::Crate,
50 is_proc_macro_crate: bool,
51 has_proc_macro_decls: bool,
53 num_crate_types: usize,
54 handler: &errors::Handler) -> ast::Crate {
55 let ecfg = ExpansionConfig::default("proc_macro".to_string());
56 let mut cx = ExtCtxt::new(sess, ecfg, resolver);
58 let mut collect = CollectProcMacros {
66 if has_proc_macro_decls || is_proc_macro_crate {
67 visit::walk_crate(&mut collect, &krate);
69 // NOTE: If you change the order of macros in this vec
70 // for any reason, you must also update 'raw_proc_macro'
71 // in src/librustc_metadata/decoder.rs
72 let macros = collect.macros;
74 if !is_proc_macro_crate {
78 if num_crate_types > 1 {
79 handler.err("cannot mix `proc-macro` crate type with others");
86 krate.module.items.push(mk_decls(&mut cx, ¯os));
91 impl<'a> CollectProcMacros<'a> {
92 fn check_not_pub_in_root(&self, vis: &ast::Visibility, sp: Span) {
93 if self.is_proc_macro_crate && self.in_root && vis.node.is_pub() {
94 self.handler.span_err(sp,
95 "`proc-macro` crate types cannot \
96 export any items other than functions \
97 tagged with `#[proc_macro_derive]` currently");
101 fn collect_custom_derive(&mut self, item: &'a ast::Item, attr: &'a ast::Attribute) {
102 // Once we've located the `#[proc_macro_derive]` attribute, verify
103 // that it's of the form `#[proc_macro_derive(Foo)]` or
104 // `#[proc_macro_derive(Foo, attributes(A, ..))]`
105 let list = match attr.meta_item_list() {
109 if list.len() != 1 && list.len() != 2 {
110 self.handler.span_err(attr.span,
111 "attribute must have either one or two arguments");
114 let trait_attr = match list[0].meta_item() {
115 Some(meta_item) => meta_item,
117 self.handler.span_err(list[0].span(), "not a meta item");
121 let trait_ident = match trait_attr.ident() {
122 Some(trait_ident) if trait_attr.is_word() => trait_ident,
124 self.handler.span_err(trait_attr.span, "must only be one word");
129 if !trait_ident.name.can_be_raw() {
130 self.handler.span_err(trait_attr.span,
131 &format!("`{}` cannot be a name of derive macro", trait_ident));
134 let attributes_attr = list.get(1);
135 let proc_attrs: Vec<_> = if let Some(attr) = attributes_attr {
136 if !attr.check_name(sym::attributes) {
137 self.handler.span_err(attr.span(), "second argument must be `attributes`")
139 attr.meta_item_list().unwrap_or_else(|| {
140 self.handler.span_err(attr.span(),
141 "attribute must be of form: `attributes(foo, bar)`");
143 }).into_iter().filter_map(|attr| {
144 let attr = match attr.meta_item() {
145 Some(meta_item) => meta_item,
147 self.handler.span_err(attr.span(), "not a meta item");
152 let ident = match attr.ident() {
153 Some(ident) if attr.is_word() => ident,
155 self.handler.span_err(attr.span, "must only be one word");
159 if !ident.name.can_be_raw() {
160 self.handler.span_err(
162 &format!("`{}` cannot be a name of derive helper attribute", ident),
172 if self.in_root && item.vis.node.is_pub() {
173 self.macros.push(ProcMacro::Derive(ProcMacroDerive {
175 trait_name: trait_ident.name,
176 function_name: item.ident,
180 let msg = if !self.in_root {
181 "functions tagged with `#[proc_macro_derive]` must \
182 currently reside in the root of the crate"
184 "functions tagged with `#[proc_macro_derive]` must be `pub`"
186 self.handler.span_err(item.span, msg);
190 fn collect_attr_proc_macro(&mut self, item: &'a ast::Item) {
191 if self.in_root && item.vis.node.is_pub() {
192 self.macros.push(ProcMacro::Def(ProcMacroDef {
194 function_name: item.ident,
195 def_type: ProcMacroDefType::Attr
198 let msg = if !self.in_root {
199 "functions tagged with `#[proc_macro_attribute]` must \
200 currently reside in the root of the crate"
202 "functions tagged with `#[proc_macro_attribute]` must be `pub`"
204 self.handler.span_err(item.span, msg);
208 fn collect_bang_proc_macro(&mut self, item: &'a ast::Item) {
209 if self.in_root && item.vis.node.is_pub() {
210 self.macros.push(ProcMacro::Def(ProcMacroDef {
212 function_name: item.ident,
213 def_type: ProcMacroDefType::Bang
216 let msg = if !self.in_root {
217 "functions tagged with `#[proc_macro]` must \
218 currently reside in the root of the crate"
220 "functions tagged with `#[proc_macro]` must be `pub`"
222 self.handler.span_err(item.span, msg);
227 impl<'a> Visitor<'a> for CollectProcMacros<'a> {
228 fn visit_item(&mut self, item: &'a ast::Item) {
229 if let ast::ItemKind::MacroDef(..) = item.node {
230 if self.is_proc_macro_crate && attr::contains_name(&item.attrs, sym::macro_export) {
232 "cannot export macro_rules! macros from a `proc-macro` crate type currently";
233 self.handler.span_err(item.span, msg);
237 // First up, make sure we're checking a bare function. If we're not then
238 // we're just not interested in this item.
240 // If we find one, try to locate a `#[proc_macro_derive]` attribute on it.
241 let is_fn = match item.node {
242 ast::ItemKind::Fn(..) => true,
246 let mut found_attr: Option<&'a ast::Attribute> = None;
248 for attr in &item.attrs {
249 if is_proc_macro_attr(&attr) {
250 if let Some(prev_attr) = found_attr {
251 let msg = if attr.path.segments[0].ident.name ==
252 prev_attr.path.segments[0].ident.name {
253 format!("only one `#[{}]` attribute is allowed on any given function",
256 format!("`#[{}]` and `#[{}]` attributes cannot both be applied \
257 to the same function", attr.path, prev_attr.path)
260 self.handler.struct_span_err(attr.span, &msg)
261 .span_note(prev_attr.span, "previous attribute here")
267 found_attr = Some(attr);
271 let attr = match found_attr {
273 self.check_not_pub_in_root(&item.vis, item.span);
274 let prev_in_root = mem::replace(&mut self.in_root, false);
275 visit::walk_item(self, item);
276 self.in_root = prev_in_root;
283 let msg = format!("the `#[{}]` attribute may only be used on bare functions",
286 self.handler.span_err(attr.span, &msg);
290 if self.is_test_crate {
294 if !self.is_proc_macro_crate {
295 let msg = format!("the `#[{}]` attribute is only usable with crates of the \
296 `proc-macro` crate type", attr.path);
298 self.handler.span_err(attr.span, &msg);
302 if attr.check_name(sym::proc_macro_derive) {
303 self.collect_custom_derive(item, attr);
304 } else if attr.check_name(sym::proc_macro_attribute) {
305 self.collect_attr_proc_macro(item);
306 } else if attr.check_name(sym::proc_macro) {
307 self.collect_bang_proc_macro(item);
310 let prev_in_root = mem::replace(&mut self.in_root, false);
311 visit::walk_item(self, item);
312 self.in_root = prev_in_root;
315 fn visit_mac(&mut self, mac: &'a ast::Mac) {
316 visit::walk_mac(self, mac)
320 // Creates a new module which looks like:
323 // extern crate proc_macro;
325 // use proc_macro::bridge::client::ProcMacro;
327 // #[rustc_proc_macro_decls]
328 // static DECLS: &[ProcMacro] = &[
329 // ProcMacro::custom_derive($name_trait1, &[], ::$name1);
330 // ProcMacro::custom_derive($name_trait2, &["attribute_name"], ::$name2);
335 cx: &mut ExtCtxt<'_>,
336 macros: &[ProcMacro],
338 let expn_id = cx.resolver.expansion_for_ast_pass(
340 AstPass::ProcMacroHarness,
341 &[sym::rustc_attrs, sym::proc_macro_internals],
344 let span = DUMMY_SP.with_def_site_ctxt(expn_id);
346 let proc_macro = Ident::new(sym::proc_macro, span);
347 let krate = cx.item(span,
350 ast::ItemKind::ExternCrate(None));
352 let bridge = cx.ident_of("bridge", span);
353 let client = cx.ident_of("client", span);
354 let proc_macro_ty = cx.ident_of("ProcMacro", span);
355 let custom_derive = cx.ident_of("custom_derive", span);
356 let attr = cx.ident_of("attr", span);
357 let bang = cx.ident_of("bang", span);
360 let local_path = |sp: Span, name| {
361 cx.expr_path(cx.path(sp.with_ctxt(span.ctxt()), vec![name]))
363 let proc_macro_ty_method_path = |method| cx.expr_path(cx.path(span, vec![
364 proc_macro, bridge, client, proc_macro_ty, method,
366 macros.iter().map(|m| {
368 ProcMacro::Derive(cd) => {
369 cx.expr_call(span, proc_macro_ty_method_path(custom_derive), vec![
370 cx.expr_str(cd.span, cd.trait_name),
373 cd.attrs.iter().map(|&s| cx.expr_str(cd.span, s)).collect::<Vec<_>>()
375 local_path(cd.span, cd.function_name),
378 ProcMacro::Def(ca) => {
379 let ident = match ca.def_type {
380 ProcMacroDefType::Attr => attr,
381 ProcMacroDefType::Bang => bang
384 cx.expr_call(span, proc_macro_ty_method_path(ident), vec![
385 cx.expr_str(ca.span, ca.function_name.name),
386 local_path(ca.span, ca.function_name),
394 let decls_static = cx.item_static(
396 cx.ident_of("_DECLS", span),
398 cx.ty(span, ast::TyKind::Slice(
399 cx.ty_path(cx.path(span,
400 vec![proc_macro, bridge, client, proc_macro_ty])))),
401 None, ast::Mutability::Immutable),
402 ast::Mutability::Immutable,
403 cx.expr_vec_slice(span, decls),
405 let attr = cx.meta_word(span, sym::rustc_proc_macro_decls);
406 i.attrs.push(cx.attribute(attr));
410 let block = cx.expr_block(cx.block(
412 vec![cx.stmt_item(span, krate), cx.stmt_item(span, decls_static)],
415 let anon_constant = cx.item_const(
417 ast::Ident::new(kw::Underscore, span),
418 cx.ty(span, ast::TyKind::Tup(Vec::new())),
422 // Integrate the new item into existing module structures.
423 let items = AstFragment::Items(smallvec![anon_constant]);
424 cx.monotonic_expander().fully_expand_fragment(items).make_items().pop().unwrap()