1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
use syntax::ast;
use syntax::codemap::{self, DUMMY_SP, Span, respan};
use syntax::ext::base::ExtCtxt;
use syntax::ext::expand;
use syntax::ext::quote::rt::ToTokens;
use syntax::parse::ParseSess;
use syntax::ptr::P;
use expr::ExprBuilder;
use invoke::{Invoke, Identity};
pub struct MacBuilder<F=Identity> {
callback: F,
span: Span,
tokens: Vec<ast::TokenTree>,
path: Option<ast::Path>,
}
impl MacBuilder {
pub fn new() -> Self {
MacBuilder::new_with_callback(Identity)
}
}
impl<F> MacBuilder<F>
where F: Invoke<ast::Mac>
{
pub fn new_with_callback(callback: F) -> Self {
MacBuilder {
callback: callback,
span: DUMMY_SP,
tokens: vec![],
path: None,
}
}
pub fn span(mut self, span: Span) -> Self {
self.span = span;
self
}
pub fn path(mut self, path: ast::Path) -> Self {
self.path = Some(path);
self
}
pub fn build(self) -> F::Result {
let mac = ast::Mac_::MacInvocTT(
self.path.expect("No path set for macro"), self.tokens, 0);
self.callback.invoke(respan(self.span, mac))
}
pub fn with_args<I, T>(self, iter: I) -> Self
where I: IntoIterator<Item=T>, T: ToTokens
{
iter.into_iter().fold(self, |self_, expr| self_.with_arg(expr))
}
pub fn with_arg<T>(mut self, expr: T) -> Self
where T: ToTokens
{
let parse_sess = ParseSess::new();
let cx = make_ext_ctxt(&parse_sess);
let tokens = expr.to_tokens(&cx);
assert!(tokens.len() == 1);
self.tokens.push(tokens[0].clone());
self
}
pub fn expr(self) -> ExprBuilder<Self> {
ExprBuilder::new_with_callback(self)
}
}
impl<F> Invoke<P<ast::Expr>> for MacBuilder<F>
where F: Invoke<ast::Mac>,
{
type Result = Self;
fn invoke(self, expr: P<ast::Expr>) -> Self {
self.with_arg(expr)
}
}
fn make_ext_ctxt(sess: &ParseSess) -> ExtCtxt {
let info = codemap::ExpnInfo {
call_site: codemap::DUMMY_SP,
callee: codemap::NameAndSpan {
name: "test".to_string(),
format: codemap::MacroAttribute,
allow_internal_unstable: false,
span: None
}
};
let cfg = vec![];
let ecfg = expand::ExpansionConfig::default(String::new());
let mut cx = ExtCtxt::new(&sess, cfg, ecfg);
cx.bt_push(info);
cx
}