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(
97 "`proc-macro` crate types currently cannot export any items other \
98 than functions tagged with `#[proc_macro]`, `#[proc_macro_derive]`, \
99 or `#[proc_macro_attribute]`",
104 fn collect_custom_derive(&mut self, item: &'a ast::Item, attr: &'a ast::Attribute) {
105 // Once we've located the `#[proc_macro_derive]` attribute, verify
106 // that it's of the form `#[proc_macro_derive(Foo)]` or
107 // `#[proc_macro_derive(Foo, attributes(A, ..))]`
108 let list = match attr.meta_item_list() {
112 if list.len() != 1 && list.len() != 2 {
113 self.handler.span_err(attr.span,
114 "attribute must have either one or two arguments");
117 let trait_attr = match list[0].meta_item() {
118 Some(meta_item) => meta_item,
120 self.handler.span_err(list[0].span(), "not a meta item");
124 let trait_ident = match trait_attr.ident() {
125 Some(trait_ident) if trait_attr.is_word() => trait_ident,
127 self.handler.span_err(trait_attr.span, "must only be one word");
132 if !trait_ident.name.can_be_raw() {
133 self.handler.span_err(trait_attr.span,
134 &format!("`{}` cannot be a name of derive macro", trait_ident));
137 let attributes_attr = list.get(1);
138 let proc_attrs: Vec<_> = if let Some(attr) = attributes_attr {
139 if !attr.check_name(sym::attributes) {
140 self.handler.span_err(attr.span(), "second argument must be `attributes`")
142 attr.meta_item_list().unwrap_or_else(|| {
143 self.handler.span_err(attr.span(),
144 "attribute must be of form: `attributes(foo, bar)`");
146 }).into_iter().filter_map(|attr| {
147 let attr = match attr.meta_item() {
148 Some(meta_item) => meta_item,
150 self.handler.span_err(attr.span(), "not a meta item");
155 let ident = match attr.ident() {
156 Some(ident) if attr.is_word() => ident,
158 self.handler.span_err(attr.span, "must only be one word");
162 if !ident.name.can_be_raw() {
163 self.handler.span_err(
165 &format!("`{}` cannot be a name of derive helper attribute", ident),
175 if self.in_root && item.vis.node.is_pub() {
176 self.macros.push(ProcMacro::Derive(ProcMacroDerive {
178 trait_name: trait_ident.name,
179 function_name: item.ident,
183 let msg = if !self.in_root {
184 "functions tagged with `#[proc_macro_derive]` must \
185 currently reside in the root of the crate"
187 "functions tagged with `#[proc_macro_derive]` must be `pub`"
189 self.handler.span_err(item.span, msg);
193 fn collect_attr_proc_macro(&mut self, item: &'a ast::Item) {
194 if self.in_root && item.vis.node.is_pub() {
195 self.macros.push(ProcMacro::Def(ProcMacroDef {
197 function_name: item.ident,
198 def_type: ProcMacroDefType::Attr
201 let msg = if !self.in_root {
202 "functions tagged with `#[proc_macro_attribute]` must \
203 currently reside in the root of the crate"
205 "functions tagged with `#[proc_macro_attribute]` must be `pub`"
207 self.handler.span_err(item.span, msg);
211 fn collect_bang_proc_macro(&mut self, item: &'a ast::Item) {
212 if self.in_root && item.vis.node.is_pub() {
213 self.macros.push(ProcMacro::Def(ProcMacroDef {
215 function_name: item.ident,
216 def_type: ProcMacroDefType::Bang
219 let msg = if !self.in_root {
220 "functions tagged with `#[proc_macro]` must \
221 currently reside in the root of the crate"
223 "functions tagged with `#[proc_macro]` must be `pub`"
225 self.handler.span_err(item.span, msg);
230 impl<'a> Visitor<'a> for CollectProcMacros<'a> {
231 fn visit_item(&mut self, item: &'a ast::Item) {
232 if let ast::ItemKind::MacroDef(..) = item.kind {
233 if self.is_proc_macro_crate && attr::contains_name(&item.attrs, sym::macro_export) {
235 "cannot export macro_rules! macros from a `proc-macro` crate type currently";
236 self.handler.span_err(item.span, msg);
240 // First up, make sure we're checking a bare function. If we're not then
241 // we're just not interested in this item.
243 // If we find one, try to locate a `#[proc_macro_derive]` attribute on it.
244 let is_fn = match item.kind {
245 ast::ItemKind::Fn(..) => true,
249 let mut found_attr: Option<&'a ast::Attribute> = None;
251 for attr in &item.attrs {
252 if is_proc_macro_attr(&attr) {
253 if let Some(prev_attr) = found_attr {
254 let prev_item = prev_attr.get_normal_item();
255 let item = attr.get_normal_item();
256 let path_str = pprust::path_to_string(&item.path);
257 let msg = if item.path.segments[0].ident.name ==
258 prev_item.path.segments[0].ident.name {
260 "only one `#[{}]` attribute is allowed on any given function",
265 "`#[{}]` and `#[{}]` attributes cannot both be applied
266 to the same function",
268 pprust::path_to_string(&prev_item.path),
272 self.handler.struct_span_err(attr.span, &msg)
273 .span_note(prev_attr.span, "previous attribute here")
279 found_attr = Some(attr);
283 let attr = match found_attr {
285 self.check_not_pub_in_root(&item.vis, item.span);
286 let prev_in_root = mem::replace(&mut self.in_root, false);
287 visit::walk_item(self, item);
288 self.in_root = prev_in_root;
296 "the `#[{}]` attribute may only be used on bare functions",
297 pprust::path_to_string(&attr.get_normal_item().path),
300 self.handler.span_err(attr.span, &msg);
304 if self.is_test_crate {
308 if !self.is_proc_macro_crate {
310 "the `#[{}]` attribute is only usable with crates of the `proc-macro` crate type",
311 pprust::path_to_string(&attr.get_normal_item().path),
314 self.handler.span_err(attr.span, &msg);
318 if attr.check_name(sym::proc_macro_derive) {
319 self.collect_custom_derive(item, attr);
320 } else if attr.check_name(sym::proc_macro_attribute) {
321 self.collect_attr_proc_macro(item);
322 } else if attr.check_name(sym::proc_macro) {
323 self.collect_bang_proc_macro(item);
326 let prev_in_root = mem::replace(&mut self.in_root, false);
327 visit::walk_item(self, item);
328 self.in_root = prev_in_root;
331 fn visit_mac(&mut self, mac: &'a ast::Mac) {
332 visit::walk_mac(self, mac)
336 // Creates a new module which looks like:
339 // extern crate proc_macro;
341 // use proc_macro::bridge::client::ProcMacro;
343 // #[rustc_proc_macro_decls]
344 // #[allow(deprecated)]
345 // static DECLS: &[ProcMacro] = &[
346 // ProcMacro::custom_derive($name_trait1, &[], ::$name1);
347 // ProcMacro::custom_derive($name_trait2, &["attribute_name"], ::$name2);
352 cx: &mut ExtCtxt<'_>,
353 macros: &[ProcMacro],
355 let expn_id = cx.resolver.expansion_for_ast_pass(
357 AstPass::ProcMacroHarness,
358 &[sym::rustc_attrs, sym::proc_macro_internals],
361 let span = DUMMY_SP.with_def_site_ctxt(expn_id);
363 let proc_macro = Ident::new(sym::proc_macro, span);
364 let krate = cx.item(span,
367 ast::ItemKind::ExternCrate(None));
369 let bridge = cx.ident_of("bridge", span);
370 let client = cx.ident_of("client", span);
371 let proc_macro_ty = cx.ident_of("ProcMacro", span);
372 let custom_derive = cx.ident_of("custom_derive", span);
373 let attr = cx.ident_of("attr", span);
374 let bang = cx.ident_of("bang", span);
377 let local_path = |sp: Span, name| {
378 cx.expr_path(cx.path(sp.with_ctxt(span.ctxt()), vec![name]))
380 let proc_macro_ty_method_path = |method| cx.expr_path(cx.path(span, vec![
381 proc_macro, bridge, client, proc_macro_ty, method,
383 macros.iter().map(|m| {
385 ProcMacro::Derive(cd) => {
386 cx.expr_call(span, proc_macro_ty_method_path(custom_derive), vec![
387 cx.expr_str(cd.span, cd.trait_name),
390 cd.attrs.iter().map(|&s| cx.expr_str(cd.span, s)).collect::<Vec<_>>()
392 local_path(cd.span, cd.function_name),
395 ProcMacro::Def(ca) => {
396 let ident = match ca.def_type {
397 ProcMacroDefType::Attr => attr,
398 ProcMacroDefType::Bang => bang
401 cx.expr_call(span, proc_macro_ty_method_path(ident), vec![
402 cx.expr_str(ca.span, ca.function_name.name),
403 local_path(ca.span, ca.function_name),
411 let decls_static = cx.item_static(
413 cx.ident_of("_DECLS", span),
415 cx.ty(span, ast::TyKind::Slice(
416 cx.ty_path(cx.path(span,
417 vec![proc_macro, bridge, client, proc_macro_ty])))),
418 None, ast::Mutability::Immutable),
419 ast::Mutability::Immutable,
420 cx.expr_vec_slice(span, decls),
422 let attr = cx.meta_word(span, sym::rustc_proc_macro_decls);
423 i.attrs.push(cx.attribute(attr));
425 let deprecated_attr = attr::mk_nested_word_item(
426 Ident::new(sym::deprecated, span)
428 let allow_deprecated_attr = attr::mk_list_item(
429 Ident::new(sym::allow, span),
430 vec![deprecated_attr]
432 i.attrs.push(cx.attribute(allow_deprecated_attr));
437 let block = cx.expr_block(cx.block(
439 vec![cx.stmt_item(span, krate), cx.stmt_item(span, decls_static)],
442 let anon_constant = cx.item_const(
444 ast::Ident::new(kw::Underscore, span),
445 cx.ty(span, ast::TyKind::Tup(Vec::new())),
449 // Integrate the new item into existing module structures.
450 let items = AstFragment::Items(smallvec![anon_constant]);
451 cx.monotonic_expander().fully_expand_fragment(items).make_items().pop().unwrap()