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 prev_item = prev_attr.get_normal_item();
253 let item = attr.get_normal_item();
254 let path_str = pprust::path_to_string(&item.path);
255 let msg = if item.path.segments[0].ident.name ==
256 prev_item.path.segments[0].ident.name {
258 "only one `#[{}]` attribute is allowed on any given function",
263 "`#[{}]` and `#[{}]` attributes cannot both be applied
264 to the same function",
266 pprust::path_to_string(&prev_item.path),
270 self.handler.struct_span_err(attr.span, &msg)
271 .span_note(prev_attr.span, "previous attribute here")
277 found_attr = Some(attr);
281 let attr = match found_attr {
283 self.check_not_pub_in_root(&item.vis, item.span);
284 let prev_in_root = mem::replace(&mut self.in_root, false);
285 visit::walk_item(self, item);
286 self.in_root = prev_in_root;
294 "the `#[{}]` attribute may only be used on bare functions",
295 pprust::path_to_string(&attr.get_normal_item().path),
298 self.handler.span_err(attr.span, &msg);
302 if self.is_test_crate {
306 if !self.is_proc_macro_crate {
308 "the `#[{}]` attribute is only usable with crates of the `proc-macro` crate type",
309 pprust::path_to_string(&attr.get_normal_item().path),
312 self.handler.span_err(attr.span, &msg);
316 if attr.check_name(sym::proc_macro_derive) {
317 self.collect_custom_derive(item, attr);
318 } else if attr.check_name(sym::proc_macro_attribute) {
319 self.collect_attr_proc_macro(item);
320 } else if attr.check_name(sym::proc_macro) {
321 self.collect_bang_proc_macro(item);
324 let prev_in_root = mem::replace(&mut self.in_root, false);
325 visit::walk_item(self, item);
326 self.in_root = prev_in_root;
329 fn visit_mac(&mut self, mac: &'a ast::Mac) {
330 visit::walk_mac(self, mac)
334 // Creates a new module which looks like:
337 // extern crate proc_macro;
339 // use proc_macro::bridge::client::ProcMacro;
341 // #[rustc_proc_macro_decls]
342 // #[allow(deprecated)]
343 // static DECLS: &[ProcMacro] = &[
344 // ProcMacro::custom_derive($name_trait1, &[], ::$name1);
345 // ProcMacro::custom_derive($name_trait2, &["attribute_name"], ::$name2);
350 cx: &mut ExtCtxt<'_>,
351 macros: &[ProcMacro],
353 let expn_id = cx.resolver.expansion_for_ast_pass(
355 AstPass::ProcMacroHarness,
356 &[sym::rustc_attrs, sym::proc_macro_internals],
359 let span = DUMMY_SP.with_def_site_ctxt(expn_id);
361 let proc_macro = Ident::new(sym::proc_macro, span);
362 let krate = cx.item(span,
365 ast::ItemKind::ExternCrate(None));
367 let bridge = cx.ident_of("bridge", span);
368 let client = cx.ident_of("client", span);
369 let proc_macro_ty = cx.ident_of("ProcMacro", span);
370 let custom_derive = cx.ident_of("custom_derive", span);
371 let attr = cx.ident_of("attr", span);
372 let bang = cx.ident_of("bang", span);
375 let local_path = |sp: Span, name| {
376 cx.expr_path(cx.path(sp.with_ctxt(span.ctxt()), vec![name]))
378 let proc_macro_ty_method_path = |method| cx.expr_path(cx.path(span, vec![
379 proc_macro, bridge, client, proc_macro_ty, method,
381 macros.iter().map(|m| {
383 ProcMacro::Derive(cd) => {
384 cx.expr_call(span, proc_macro_ty_method_path(custom_derive), vec![
385 cx.expr_str(cd.span, cd.trait_name),
388 cd.attrs.iter().map(|&s| cx.expr_str(cd.span, s)).collect::<Vec<_>>()
390 local_path(cd.span, cd.function_name),
393 ProcMacro::Def(ca) => {
394 let ident = match ca.def_type {
395 ProcMacroDefType::Attr => attr,
396 ProcMacroDefType::Bang => bang
399 cx.expr_call(span, proc_macro_ty_method_path(ident), vec![
400 cx.expr_str(ca.span, ca.function_name.name),
401 local_path(ca.span, ca.function_name),
409 let decls_static = cx.item_static(
411 cx.ident_of("_DECLS", span),
413 cx.ty(span, ast::TyKind::Slice(
414 cx.ty_path(cx.path(span,
415 vec![proc_macro, bridge, client, proc_macro_ty])))),
416 None, ast::Mutability::Immutable),
417 ast::Mutability::Immutable,
418 cx.expr_vec_slice(span, decls),
420 let attr = cx.meta_word(span, sym::rustc_proc_macro_decls);
421 i.attrs.push(cx.attribute(attr));
423 let deprecated_attr = attr::mk_nested_word_item(
424 Ident::new(sym::deprecated, span)
426 let allow_deprecated_attr = attr::mk_list_item(
427 Ident::new(sym::allow, span),
428 vec![deprecated_attr]
430 i.attrs.push(cx.attribute(allow_deprecated_attr));
435 let block = cx.expr_block(cx.block(
437 vec![cx.stmt_item(span, krate), cx.stmt_item(span, decls_static)],
440 let anon_constant = cx.item_const(
442 ast::Ident::new(kw::Underscore, span),
443 cx.ty(span, ast::TyKind::Tup(Vec::new())),
447 // Integrate the new item into existing module structures.
448 let items = AstFragment::Items(smallvec![anon_constant]);
449 cx.monotonic_expander().fully_expand_fragment(items).make_items().pop().unwrap()