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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
use heck::AsPascalCase;
use proc_macro::TokenStream;
use proc_macro2::{Delimiter, Group, Span};
use quote::{quote, ToTokens, TokenStreamExt};
use syn::{
parse::{Parse, ParseStream, Parser},
parse_macro_input,
punctuated::Punctuated,
spanned::Spanned,
FnArg, Ident, Pat, PatType, Token,
};
fn pascalize(ident: &Ident) -> Ident {
Ident::new(&AsPascalCase(&ident.to_string()).to_string(), ident.span())
}
#[derive(Debug)]
struct GotoBlockContents(proc_macro2::TokenStream);
impl Parse for GotoBlockContents {
fn parse(input: ParseStream) -> syn::Result<Self> {
let mut tokens = proc_macro2::TokenStream::new();
while let Ok(token) = input.parse::<proc_macro2::TokenTree>() {
let tt = match token {
proc_macro2::TokenTree::Group(grp) => {
let delim = grp.delimiter();
let span = grp.span();
let contents: GotoBlockContents = syn::parse2(grp.stream())?;
let mut grp = Group::new(delim, contents.0);
grp.set_span(span);
proc_macro2::TokenTree::Group(grp)
}
proc_macro2::TokenTree::Ident(ref ident) => {
if ident == "goto" {
let id: Ident = input.parse().map_err(|e| {
syn::Error::new(e.span(), "Invalid syntax for goto statement")
})?;
let variant = pascalize(&id).clone();
let call: Group = input.parse()?;
if call.delimiter() != Delimiter::Parenthesis {
return Err(syn::Error::new(call.span_open(), "expected `(`"));
}
let call = if call.stream().is_empty() {
proc_macro2::TokenStream::new()
} else {
quote!(#call)
};
syn::parse2(quote!(
{
goto = States::#variant #call;
continue 'goto
}
))
.expect("This should parse as a group")
} else if ident == "safe_goto" {
return Err(syn::Error::new(
ident.span(),
"using safe_goto inside safe_goto is not allowed",
));
} else {
proc_macro2::TokenTree::Ident(ident.clone())
}
}
tt => tt,
};
tokens.append(tt);
}
Ok(GotoBlockContents(tokens))
}
}
impl ToTokens for GotoBlock {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
let GotoBlock {
contents,
delimiter,
} = self;
tokens.append(Group::new(*delimiter, contents.0.clone()));
}
}
#[derive(Debug)]
struct GotoBlock {
delimiter: Delimiter,
contents: GotoBlockContents,
}
impl From<GotoBlock> for Group {
fn from(gtb: GotoBlock) -> Self {
Group::new(gtb.delimiter, gtb.contents.0)
}
}
impl Parse for GotoBlock {
fn parse(input: ParseStream) -> syn::Result<Self> {
let group: Group = input.parse()?;
let delimiter = group.delimiter();
let contents: GotoBlockContents = syn::parse2(group.stream())?;
Ok(GotoBlock {
delimiter,
contents,
})
}
}
struct VariantArgsDelimited {
contents: Punctuated<PatType, Token!(,)>,
}
impl Parse for VariantArgsDelimited {
fn parse(input: ParseStream) -> syn::Result<Self> {
let group: Group = input.parse()?;
let contents = if group.delimiter() == Delimiter::Parenthesis {
let parser = Punctuated::<FnArg, Token![,]>::parse_terminated;
parser.parse2(group.stream())?
} else {
return Err(syn::Error::new(group.span_open(), "expected `(`"));
};
let mut new_contents = Punctuated::<PatType, Token!(,)>::new();
for pair in contents.pairs() {
if let FnArg::Typed(pat) = pair.value() {
new_contents.push_value(pat.clone())
} else {
return Err(syn::Error::new(contents.span(), "unexpected `self`"));
}
if let Some(&&punct) = pair.punct() {
new_contents.push_punct(punct)
}
}
Ok(VariantArgsDelimited {
contents: new_contents,
})
}
}
impl ToTokens for VariantArgsDelimited {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
if !self.contents.is_empty() {
let args = &self.contents;
tokens.append_all(quote!(
(#args)
))
}
}
}
struct GotoBranch {
id: Ident,
block: GotoBlock,
variant_args: VariantArgsDelimited,
}
impl Parse for GotoBranch {
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
let id = input.parse()?;
let variant_args = input.parse()?;
let block = input.parse()?;
Ok(GotoBranch {
id,
block,
variant_args,
})
}
}
struct VariantTypesDelimited {
contents: Punctuated<Box<syn::Type>, Token!(,)>,
}
impl ToTokens for VariantTypesDelimited {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
if !self.contents.is_empty() {
let args = &self.contents;
tokens.append_all(quote!(
(#args)
))
}
}
}
struct VariantPatsDelimited {
contents: Punctuated<Box<Pat>, Token!(,)>,
}
impl ToTokens for VariantPatsDelimited {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
if !self.contents.is_empty() {
let args = &self.contents;
tokens.append_all(quote!(
(#args)
))
}
}
}
struct SafeGoto(Punctuated<GotoBranch, Token!(,)>);
impl SafeGoto {
fn idents(&self) -> impl Iterator<Item = &Ident> {
self.0.iter().map(|branch| &branch.id)
}
fn variant_types(&self) -> impl Iterator<Item = VariantTypesDelimited> + '_ {
self.0.iter().map(|branch| {
let mut ret = Punctuated::new();
for pair in branch.variant_args.contents.pairs() {
ret.push_value(pair.value().ty.clone());
if let Some(&&punct) = pair.punct() {
ret.push_punct(punct)
}
}
VariantTypesDelimited { contents: ret }
})
}
fn variant_pats(&self) -> impl Iterator<Item = VariantPatsDelimited> + '_ {
self.0.iter().map(|branch| {
let mut ret = Punctuated::new();
for pair in branch.variant_args.contents.pairs() {
ret.push_value(pair.value().pat.clone());
if let Some(&&punct) = pair.punct() {
ret.push_punct(punct)
}
}
VariantPatsDelimited { contents: ret }
})
}
fn blocks(&self) -> impl Iterator<Item = &GotoBlock> {
self.0.iter().map(|branch| &branch.block)
}
}
impl Parse for SafeGoto {
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
let ret = SafeGoto(input.parse_terminated::<GotoBranch, Token!(,)>(GotoBranch::parse)?);
let lifetimes: Vec<_> = ret.idents().collect();
for i in 0..lifetimes.len() {
if lifetimes[i + 1..].contains(&lifetimes[i]) {
return Err(syn::Error::new(
lifetimes[i].span(),
"block label occurs more than once",
));
}
}
Ok(ret)
}
}
#[proc_macro]
pub fn safe_goto(t: TokenStream) -> TokenStream {
let input = parse_macro_input!(t as SafeGoto);
if !input.idents().any(|id| id == "begin") {
return syn::Error::new(Span::call_site(), "expected `begin` block")
.to_compile_error()
.into();
}
let states_enum = Ident::new("States", Span::call_site());
let variants: Vec<_> = input.idents().map(pascalize).collect();
let variant_pats = input.variant_pats();
let variant_types = input.variant_types();
let blocks = input.blocks();
quote!(
{
enum #states_enum {
#(#variants #variant_types),*
}
let mut goto = #states_enum::Begin;
'goto: loop {
break match goto {
#(#states_enum::#variants #variant_pats => #blocks),*
}
}
}
)
.into()
}