1 // Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
13 #![feature(plugin_registrar, quote, rustc_private)]
17 extern crate rustc_plugin;
18 extern crate syntax_pos;
20 use syntax::ast::{self, Item, MetaItem, ItemKind};
21 use syntax::codemap::DUMMY_SP;
22 use syntax::ext::base::*;
23 use syntax::ext::quote::rt::ToTokens;
24 use syntax::parse::{self, token};
26 use syntax::symbol::Symbol;
27 use syntax::tokenstream::TokenTree;
29 use rustc_plugin::Registry;
32 macro_rules! exported_macro { () => (2) }
33 macro_rules! unexported_macro { () => (3) }
36 pub fn plugin_registrar(reg: &mut Registry) {
37 reg.register_macro("make_a_1", expand_make_a_1);
38 reg.register_macro("identity", expand_identity);
39 reg.register_syntax_extension(
40 Symbol::intern("into_multi_foo"),
41 MultiModifier(Box::new(expand_into_foo_multi)));
42 reg.register_syntax_extension(
43 Symbol::intern("duplicate"),
44 MultiDecorator(Box::new(expand_duplicate)));
45 reg.register_syntax_extension(
46 Symbol::intern("caller"),
47 MultiDecorator(Box::new(expand_caller)));
50 fn expand_make_a_1(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree]) -> Box<MacResult + 'static> {
52 cx.span_fatal(sp, "make_a_1 takes no arguments");
54 MacEager::expr(quote_expr!(cx, 1))
58 fn expand_identity(cx: &mut ExtCtxt, _span: Span, tts: &[TokenTree]) -> Box<MacResult + 'static> {
59 // Parse an expression and emit it unchanged.
60 let mut parser = parse::new_parser_from_tts(cx.parse_sess(), tts.to_vec());
61 let expr = parser.parse_expr().unwrap();
62 MacEager::expr(quote_expr!(&mut *cx, $expr))
65 fn expand_into_foo_multi(cx: &mut ExtCtxt,
71 Annotatable::Item(it) => vec![
72 Annotatable::Item(P(Item {
73 attrs: it.attrs.clone(),
74 ..(*quote_item!(cx, enum Foo2 { Bar2, Baz2 }).unwrap()).clone()
76 Annotatable::Item(quote_item!(cx, enum Foo3 { Bar }).unwrap()),
77 Annotatable::Item(quote_item!(cx, #[cfg(any())] fn foo2() {}).unwrap()),
79 Annotatable::ImplItem(_it) => vec![
80 quote_item!(cx, impl X { fn foo(&self) -> i32 { 42 } }).unwrap().and_then(|i| {
82 ItemKind::Impl(.., mut items) => {
83 Annotatable::ImplItem(P(items.pop().expect("impl method not found")))
85 _ => unreachable!("impl parsed to something other than impl")
89 Annotatable::TraitItem(_it) => vec![
90 quote_item!(cx, trait X { fn foo(&self) -> i32 { 0 } }).unwrap().and_then(|i| {
92 ItemKind::Trait(.., mut items) => {
93 Annotatable::TraitItem(P(items.pop().expect("trait method not found")))
95 _ => unreachable!("trait parsed to something other than trait")
99 // covered in proc_macro/macros-in-extern.rs
100 Annotatable::ForeignItem(..) => unimplemented!(),
101 // covered in proc_macro/attr-stmt-expr.rs
102 Annotatable::Stmt(_) | Annotatable::Expr(_) => panic!("expected item"),
106 // Create a duplicate of the annotatable, based on the MetaItem
107 fn expand_duplicate(cx: &mut ExtCtxt,
111 push: &mut FnMut(Annotatable)) {
112 let copy_name = match mi.node {
113 ast::MetaItemKind::List(ref xs) => {
114 if let Some(word) = xs[0].word() {
117 cx.span_err(mi.span, "Expected word");
122 cx.span_err(mi.span, "Expected list");
127 // Duplicate the item but replace its ident by the MetaItem
129 Annotatable::Item(it) => {
130 let mut new_it = (*it).clone();
131 new_it.attrs.clear();
132 new_it.ident = copy_name;
133 push(Annotatable::Item(P(new_it)));
135 Annotatable::ImplItem(it) => {
136 let mut new_it = (*it).clone();
137 new_it.attrs.clear();
138 new_it.ident = copy_name;
139 push(Annotatable::ImplItem(P(new_it)));
141 Annotatable::TraitItem(tt) => {
142 let mut new_it = (*tt).clone();
143 new_it.attrs.clear();
144 new_it.ident = copy_name;
145 push(Annotatable::TraitItem(P(new_it)));
147 // covered in proc_macro/macros-in-extern.rs
148 Annotatable::ForeignItem(..) => unimplemented!(),
149 // covered in proc_macro/attr-stmt-expr.rs
150 Annotatable::Stmt(_) | Annotatable::Expr(_) => panic!("expected item")
154 pub fn token_separate<T: ToTokens>(ecx: &ExtCtxt, things: &[T],
155 token: token::Token) -> Vec<TokenTree> {
156 let mut output: Vec<TokenTree> = vec![];
157 for (i, thing) in things.iter().enumerate() {
158 output.extend(thing.to_tokens(ecx));
159 if i < things.len() - 1 {
160 output.push(TokenTree::Token(DUMMY_SP, token.clone()));
167 fn expand_caller(cx: &mut ExtCtxt,
171 push: &mut FnMut(Annotatable)) {
172 let (orig_fn_name, ret_type) = match *it {
173 Annotatable::Item(ref item) => match item.node {
174 ItemKind::Fn(ref decl, ..) => {
175 (item.ident, &decl.output)
177 _ => cx.span_fatal(item.span, "Only functions with return types can be annotated.")
179 _ => cx.span_fatal(sp, "Only functions can be annotated.")
182 let (caller_name, arguments) = if let Some(list) = mi.meta_item_list() {
184 cx.span_fatal(mi.span(), "Need a function name and at least one parameter.");
187 let fn_name = match list[0].name() {
188 Some(name) => ast::Ident::with_empty_ctxt(name),
189 None => cx.span_fatal(list[0].span(), "First parameter must be an ident.")
192 (fn_name, &list[1..])
194 cx.span_fatal(mi.span, "Expected list.");
197 let literals: Vec<ast::Lit> = arguments.iter().map(|arg| {
198 if let Some(lit) = arg.literal() {
201 cx.span_fatal(arg.span(), "Expected literal.");
205 let arguments = token_separate(cx, literals.as_slice(), token::Comma);
206 if let ast::FunctionRetTy::Ty(ref rt) = *ret_type {
207 push(Annotatable::Item(quote_item!(cx,
208 fn $caller_name() -> $rt {
209 $orig_fn_name($arguments)
212 push(Annotatable::Item(quote_item!(cx,
214 $orig_fn_name($arguments)