3 use smallvec::smallvec;
4 use syntax::ast::{self, Ident};
6 use syntax::expand::is_proc_macro_attr;
7 use syntax::print::pprust;
9 use syntax::sess::ParseSess;
10 use syntax::symbol::{kw, sym};
11 use syntax::visit::{self, Visitor};
12 use syntax_expand::base::{ExtCtxt, Resolver};
13 use syntax_expand::expand::{AstFragment, ExpansionConfig};
14 use syntax_pos::{Span, DUMMY_SP};
15 use syntax_pos::hygiene::AstPass;
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 errors::Handler,
44 is_proc_macro_crate: bool,
48 pub fn inject(sess: &ParseSess,
49 resolver: &mut dyn Resolver,
50 mut krate: ast::Crate,
51 is_proc_macro_crate: bool,
52 has_proc_macro_decls: bool,
54 num_crate_types: usize,
55 handler: &errors::Handler) -> ast::Crate {
56 let ecfg = ExpansionConfig::default("proc_macro".to_string());
57 let mut cx = ExtCtxt::new(sess, ecfg, resolver);
59 let mut collect = CollectProcMacros {
67 if has_proc_macro_decls || is_proc_macro_crate {
68 visit::walk_crate(&mut collect, &krate);
70 // NOTE: If you change the order of macros in this vec
71 // for any reason, you must also update 'raw_proc_macro'
72 // in src/librustc_metadata/decoder.rs
73 let macros = collect.macros;
75 if !is_proc_macro_crate {
79 if num_crate_types > 1 {
80 handler.err("cannot mix `proc-macro` crate type with others");
87 krate.module.items.push(mk_decls(&mut cx, ¯os));
92 impl<'a> CollectProcMacros<'a> {
93 fn check_not_pub_in_root(&self, vis: &ast::Visibility, sp: Span) {
94 if self.is_proc_macro_crate && self.in_root && vis.node.is_pub() {
95 self.handler.span_err(sp,
96 "`proc-macro` crate types cannot \
97 export any items other than functions \
98 tagged with `#[proc_macro_derive]` currently");
102 fn collect_custom_derive(&mut self, item: &'a ast::Item, attr: &'a ast::Attribute) {
103 // Once we've located the `#[proc_macro_derive]` attribute, verify
104 // that it's of the form `#[proc_macro_derive(Foo)]` or
105 // `#[proc_macro_derive(Foo, attributes(A, ..))]`
106 let list = match attr.meta_item_list() {
110 if list.len() != 1 && list.len() != 2 {
111 self.handler.span_err(attr.span,
112 "attribute must have either one or two arguments");
115 let trait_attr = match list[0].meta_item() {
116 Some(meta_item) => meta_item,
118 self.handler.span_err(list[0].span(), "not a meta item");
122 let trait_ident = match trait_attr.ident() {
123 Some(trait_ident) if trait_attr.is_word() => trait_ident,
125 self.handler.span_err(trait_attr.span, "must only be one word");
130 if !trait_ident.name.can_be_raw() {
131 self.handler.span_err(trait_attr.span,
132 &format!("`{}` cannot be a name of derive macro", trait_ident));
135 let attributes_attr = list.get(1);
136 let proc_attrs: Vec<_> = if let Some(attr) = attributes_attr {
137 if !attr.check_name(sym::attributes) {
138 self.handler.span_err(attr.span(), "second argument must be `attributes`")
140 attr.meta_item_list().unwrap_or_else(|| {
141 self.handler.span_err(attr.span(),
142 "attribute must be of form: `attributes(foo, bar)`");
144 }).into_iter().filter_map(|attr| {
145 let attr = match attr.meta_item() {
146 Some(meta_item) => meta_item,
148 self.handler.span_err(attr.span(), "not a meta item");
153 let ident = match attr.ident() {
154 Some(ident) if attr.is_word() => ident,
156 self.handler.span_err(attr.span, "must only be one word");
160 if !ident.name.can_be_raw() {
161 self.handler.span_err(
163 &format!("`{}` cannot be a name of derive helper attribute", ident),
173 if self.in_root && item.vis.node.is_pub() {
174 self.macros.push(ProcMacro::Derive(ProcMacroDerive {
176 trait_name: trait_ident.name,
177 function_name: item.ident,
181 let msg = if !self.in_root {
182 "functions tagged with `#[proc_macro_derive]` must \
183 currently reside in the root of the crate"
185 "functions tagged with `#[proc_macro_derive]` must be `pub`"
187 self.handler.span_err(item.span, msg);
191 fn collect_attr_proc_macro(&mut self, item: &'a ast::Item) {
192 if self.in_root && item.vis.node.is_pub() {
193 self.macros.push(ProcMacro::Def(ProcMacroDef {
195 function_name: item.ident,
196 def_type: ProcMacroDefType::Attr
199 let msg = if !self.in_root {
200 "functions tagged with `#[proc_macro_attribute]` must \
201 currently reside in the root of the crate"
203 "functions tagged with `#[proc_macro_attribute]` must be `pub`"
205 self.handler.span_err(item.span, msg);
209 fn collect_bang_proc_macro(&mut self, item: &'a ast::Item) {
210 if self.in_root && item.vis.node.is_pub() {
211 self.macros.push(ProcMacro::Def(ProcMacroDef {
213 function_name: item.ident,
214 def_type: ProcMacroDefType::Bang
217 let msg = if !self.in_root {
218 "functions tagged with `#[proc_macro]` must \
219 currently reside in the root of the crate"
221 "functions tagged with `#[proc_macro]` must be `pub`"
223 self.handler.span_err(item.span, msg);
228 impl<'a> Visitor<'a> for CollectProcMacros<'a> {
229 fn visit_item(&mut self, item: &'a ast::Item) {
230 if let ast::ItemKind::MacroDef(..) = item.kind {
231 if self.is_proc_macro_crate && attr::contains_name(&item.attrs, sym::macro_export) {
233 "cannot export macro_rules! macros from a `proc-macro` crate type currently";
234 self.handler.span_err(item.span, msg);
238 // First up, make sure we're checking a bare function. If we're not then
239 // we're just not interested in this item.
241 // If we find one, try to locate a `#[proc_macro_derive]` attribute on it.
242 let is_fn = match item.kind {
243 ast::ItemKind::Fn(..) => true,
247 let mut found_attr: Option<&'a ast::Attribute> = None;
249 for attr in &item.attrs {
250 if is_proc_macro_attr(&attr) {
251 if let Some(prev_attr) = found_attr {
252 let path_str = pprust::path_to_string(&attr.path);
253 let msg = if attr.path.segments[0].ident.name ==
254 prev_attr.path.segments[0].ident.name {
256 "only one `#[{}]` attribute is allowed on any given function",
261 "`#[{}]` and `#[{}]` attributes cannot both be applied
262 to the same function",
264 pprust::path_to_string(&prev_attr.path),
268 self.handler.struct_span_err(attr.span, &msg)
269 .span_note(prev_attr.span, "previous attribute here")
275 found_attr = Some(attr);
279 let attr = match found_attr {
281 self.check_not_pub_in_root(&item.vis, item.span);
282 let prev_in_root = mem::replace(&mut self.in_root, false);
283 visit::walk_item(self, item);
284 self.in_root = prev_in_root;
292 "the `#[{}]` attribute may only be used on bare functions",
293 pprust::path_to_string(&attr.path),
296 self.handler.span_err(attr.span, &msg);
300 if self.is_test_crate {
304 if !self.is_proc_macro_crate {
306 "the `#[{}]` attribute is only usable with crates of the `proc-macro` crate type",
307 pprust::path_to_string(&attr.path),
310 self.handler.span_err(attr.span, &msg);
314 if attr.check_name(sym::proc_macro_derive) {
315 self.collect_custom_derive(item, attr);
316 } else if attr.check_name(sym::proc_macro_attribute) {
317 self.collect_attr_proc_macro(item);
318 } else if attr.check_name(sym::proc_macro) {
319 self.collect_bang_proc_macro(item);
322 let prev_in_root = mem::replace(&mut self.in_root, false);
323 visit::walk_item(self, item);
324 self.in_root = prev_in_root;
327 fn visit_mac(&mut self, mac: &'a ast::Mac) {
328 visit::walk_mac(self, mac)
332 // Creates a new module which looks like:
335 // extern crate proc_macro;
337 // use proc_macro::bridge::client::ProcMacro;
339 // #[rustc_proc_macro_decls]
340 // #[allow(deprecated)]
341 // static DECLS: &[ProcMacro] = &[
342 // ProcMacro::custom_derive($name_trait1, &[], ::$name1);
343 // ProcMacro::custom_derive($name_trait2, &["attribute_name"], ::$name2);
348 cx: &mut ExtCtxt<'_>,
349 macros: &[ProcMacro],
351 let expn_id = cx.resolver.expansion_for_ast_pass(
353 AstPass::ProcMacroHarness,
354 &[sym::rustc_attrs, sym::proc_macro_internals],
357 let span = DUMMY_SP.with_def_site_ctxt(expn_id);
359 let proc_macro = Ident::new(sym::proc_macro, span);
360 let krate = cx.item(span,
363 ast::ItemKind::ExternCrate(None));
365 let bridge = cx.ident_of("bridge", span);
366 let client = cx.ident_of("client", span);
367 let proc_macro_ty = cx.ident_of("ProcMacro", span);
368 let custom_derive = cx.ident_of("custom_derive", span);
369 let attr = cx.ident_of("attr", span);
370 let bang = cx.ident_of("bang", span);
373 let local_path = |sp: Span, name| {
374 cx.expr_path(cx.path(sp.with_ctxt(span.ctxt()), vec![name]))
376 let proc_macro_ty_method_path = |method| cx.expr_path(cx.path(span, vec![
377 proc_macro, bridge, client, proc_macro_ty, method,
379 macros.iter().map(|m| {
381 ProcMacro::Derive(cd) => {
382 cx.expr_call(span, proc_macro_ty_method_path(custom_derive), vec![
383 cx.expr_str(cd.span, cd.trait_name),
386 cd.attrs.iter().map(|&s| cx.expr_str(cd.span, s)).collect::<Vec<_>>()
388 local_path(cd.span, cd.function_name),
391 ProcMacro::Def(ca) => {
392 let ident = match ca.def_type {
393 ProcMacroDefType::Attr => attr,
394 ProcMacroDefType::Bang => bang
397 cx.expr_call(span, proc_macro_ty_method_path(ident), vec![
398 cx.expr_str(ca.span, ca.function_name.name),
399 local_path(ca.span, ca.function_name),
407 let decls_static = cx.item_static(
409 cx.ident_of("_DECLS", span),
411 cx.ty(span, ast::TyKind::Slice(
412 cx.ty_path(cx.path(span,
413 vec![proc_macro, bridge, client, proc_macro_ty])))),
414 None, ast::Mutability::Immutable),
415 ast::Mutability::Immutable,
416 cx.expr_vec_slice(span, decls),
418 let attr = cx.meta_word(span, sym::rustc_proc_macro_decls);
419 i.attrs.push(cx.attribute(attr));
421 let deprecated_attr = attr::mk_nested_word_item(
422 Ident::new(sym::deprecated, span)
424 let allow_deprecated_attr = attr::mk_list_item(
425 Ident::new(sym::allow, span),
426 vec![deprecated_attr]
428 i.attrs.push(cx.attribute(allow_deprecated_attr));
433 let block = cx.expr_block(cx.block(
435 vec![cx.stmt_item(span, krate), cx.stmt_item(span, decls_static)],
438 let anon_constant = cx.item_const(
440 ast::Ident::new(kw::Underscore, span),
441 cx.ty(span, ast::TyKind::Tup(Vec::new())),
445 // Integrate the new item into existing module structures.
446 let items = AstFragment::Items(smallvec![anon_constant]);
447 cx.monotonic_expander().fully_expand_fragment(items).make_items().pop().unwrap()