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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
use crate::{
matcher::{
MacroRepOp, MacroRepSep, MatchStringBuilder, MatchTokensBuilder, PatternItems, RawMatch,
},
token_entry::TokenStringBuilder,
utils::{to_close_str, to_open_str, RangeBuilder},
ParseStreamEx, Rule, Source,
};
use proc_macro2::{Delimiter, Group, Ident, Span, TokenStream, TokenTree};
use quote::{ToTokens, TokenStreamExt};
use std::{ops::Range, str::FromStr};
use structmeta::{Parse, ToTokens};
use syn::{
ext::IdentExt,
parse::{Parse, ParseStream},
spanned::Spanned,
token, Error, Result, Token,
};
#[derive(Debug, Clone)]
pub struct Transcriber {
items: TranscriberItems,
is_ready_string: bool,
}
impl FromStr for Transcriber {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
let (source, input) = Source::from_str(s)?;
let mut to = ParseStreamEx::parse_from_tokens(input, 0, Self::parse_ex)?;
to.items.ready_string(&source);
to.is_ready_string = true;
Ok(to)
}
}
impl Transcriber {
pub fn parse(input: ParseStream) -> Result<Self> {
Self::parse_ex(&mut ParseStreamEx::new(input, 0))
}
fn parse_ex(input: &mut ParseStreamEx) -> Result<Self> {
Ok(Self {
items: TranscriberItems::parse(input)?,
is_ready_string: false,
})
}
pub(crate) fn attach(&mut self, p: &PatternItems) -> Result<()> {
self.items.attach(p)
}
pub(crate) fn apply_tokens_to(&self, m: &RawMatch, b: &mut MatchTokensBuilder) {
self.items.apply_tokens_to(m, b)
}
pub(crate) fn apply_string(
&self,
m: &RawMatch,
rule: &Rule,
tes_len: usize,
b: &mut TokenStringBuilder,
) {
let mut b = MatchStringBuilder {
b,
rule,
tes_len,
is_ready_string: self.is_ready_string,
};
self.items.apply_string(m, &mut b)
}
}
#[derive(Debug, Clone)]
struct TranscriberItems {
items: Vec<TranscriberItem>,
}
impl TranscriberItems {
fn parse(input: &mut ParseStreamEx) -> Result<Self> {
let mut items = Vec::new();
let mut tokens = Vec::new();
let mut tes_range = RangeBuilder::new();
while !input.is_empty() {
if input.peek(token::Paren) || input.peek(token::Brace) || input.peek(token::Bracket) {
push_tokens(&mut tokens, &mut items, &mut tes_range);
let g = input.parse_group(|g, input| {
Ok(TranscriberGroup {
delimiter: g.group.delimiter(),
content: Self::parse(input)?,
tes_range_open: g.tes_range_open,
tes_range_close: g.tes_range_close,
span: g.group.span(),
})
})?;
items.push(TranscriberItem::Group(g));
continue;
}
if input.peek(Token![$]) {
if input.peek2(Ident::peek_any) {
push_tokens(&mut tokens, &mut items, &mut tes_range);
items.push(TranscriberItem::Var(input.parse()?));
continue;
}
if input.peek2(token::Paren) {
push_tokens(&mut tokens, &mut items, &mut tes_range);
items.push(TranscriberItem::Rep(TranscriberRep::parse(input)?));
continue;
}
}
let tes_start = input.tes_offset;
let token: TokenTree = input.parse().unwrap();
let tes_end = input.tes_offset;
tes_range.push(tes_start..tes_end);
tokens.push(token);
}
push_tokens(&mut tokens, &mut items, &mut tes_range);
Ok(Self { items })
}
fn ready_string(&mut self, source: &Source) {
self.ready_string_with(source, &mut RangeBuilder::new());
}
fn ready_string_with(&mut self, source: &Source, tes_range: &mut RangeBuilder) {
for item in &mut self.items {
item.ready_string_with(source, tes_range);
}
}
fn attach(&mut self, p: &PatternItems) -> Result<()> {
for i in &mut self.items {
i.attach(p)?;
}
Ok(())
}
fn get_var(&self) -> Option<MacroTranscriberVar> {
for i in &self.items {
if let Some(b) = i.get_var() {
return Some(b);
}
}
None
}
fn apply_tokens_to(&self, m: &RawMatch, b: &mut MatchTokensBuilder) {
for item in &self.items {
item.apply_tokens_to(m, b);
}
}
fn apply_string(&self, m: &RawMatch, b: &mut MatchStringBuilder) {
for item in &self.items {
item.apply_string(m, b)
}
}
}
fn push_tokens(
tokens: &mut Vec<TokenTree>,
items: &mut Vec<TranscriberItem>,
tes_range: &mut RangeBuilder,
) {
if let Some(tes_range) = tes_range.take() {
if !tokens.is_empty() {
let tokens = TokenStream::from_iter(tokens.drain(..));
items.push(TranscriberItem::Tokens(TranscriberTokens {
tokens,
tes_range,
}));
}
}
items.push(TranscriberItem::String(String::new()));
}
#[derive(Debug, Clone)]
enum TranscriberItem {
Tokens(TranscriberTokens),
Group(TranscriberGroup),
String(String),
Var(TranscriberVar),
Rep(TranscriberRep),
}
impl TranscriberItem {
fn ready_string_with(&mut self, source: &Source, tes_range: &mut RangeBuilder) {
match self {
Self::Tokens(t) => tes_range.push(t.tes_range.clone()),
Self::Group(g) => g.ready_string_with(source, tes_range),
Self::String(ref mut s) => {
if let Some(tes_range) = tes_range.take() {
let mut b = TokenStringBuilder::new(source);
b.push_tes(tes_range);
*s = b.s;
}
}
Self::Var(_) => {}
Self::Rep(r) => r.content.ready_string(source),
}
}
fn attach(&mut self, p: &PatternItems) -> Result<()> {
match self {
Self::Tokens(_) | Self::String(_) => Ok(()),
Self::Group(g) => g.content.attach(p),
Self::Var(v) => v.attach(p),
Self::Rep(r) => r.attach(p),
}
}
fn get_var(&self) -> Option<MacroTranscriberVar> {
match self {
TranscriberItem::Tokens(_) => None,
TranscriberItem::Group(g) => g.content.get_var(),
TranscriberItem::String(_) => None,
TranscriberItem::Var(v) => Some(v.var.clone()),
TranscriberItem::Rep(r) => Some(r.var.clone()),
}
}
fn apply_tokens_to(&self, m: &RawMatch, b: &mut MatchTokensBuilder) {
match self {
TranscriberItem::Tokens(t) => t.tokens.to_tokens(b.tokens),
TranscriberItem::String(_) => {}
TranscriberItem::Group(g) => g.apply_tokens_to(m, b),
TranscriberItem::Var(v) => v.apply_tokens_to(m, b),
TranscriberItem::Rep(r) => r.apply_tokens_to(m, b),
}
}
fn apply_string(&self, m: &RawMatch, b: &mut MatchStringBuilder) {
match self {
TranscriberItem::Tokens(tokens) => tokens.apply_string(b),
TranscriberItem::Group(g) => g.apply_string(m, b),
TranscriberItem::String(s) => b.b.push_str(s),
TranscriberItem::Var(v) => v.apply_string(m, b),
TranscriberItem::Rep(r) => r.apply_string(m, b),
}
}
}
#[derive(Debug, Clone)]
struct TranscriberTokens {
tokens: TokenStream,
tes_range: Range<usize>,
}
impl TranscriberTokens {
fn apply_string(&self, b: &mut MatchStringBuilder) {
if !b.is_ready_string {
b.b.push_tokens(&self.tokens)
}
}
}
#[derive(Debug, Clone)]
struct TranscriberGroup {
delimiter: Delimiter,
content: TranscriberItems,
span: Span,
tes_range_open: Range<usize>,
tes_range_close: Range<usize>,
}
impl TranscriberGroup {
fn ready_string_with(&mut self, source: &Source, tes_range: &mut RangeBuilder) {
tes_range.push(self.tes_range_open.clone());
self.content.ready_string_with(source, tes_range);
tes_range.push(self.tes_range_close.clone());
}
fn apply_tokens_to(&self, m: &RawMatch, b: &mut MatchTokensBuilder) {
let mut stream = TokenStream::new();
self.content.apply_tokens_to(
m,
&mut MatchTokensBuilder {
tokens: &mut stream,
..*b
},
);
let mut g = Group::new(self.delimiter, stream);
g.set_span(self.span);
b.tokens.append(g);
}
fn apply_string(&self, m: &RawMatch, b: &mut MatchStringBuilder) {
if !b.is_ready_string {
b.b.push_str(to_open_str(self.delimiter));
}
self.content.apply_string(m, b);
if !b.is_ready_string {
b.b.push_str(to_close_str(self.delimiter));
}
}
}
#[derive(Parse, ToTokens, Debug, Clone)]
struct MacroTranscriberVar {
dollar_token: Token![$],
name: Ident,
}
#[derive(Debug, Clone)]
struct TranscriberVar {
var: MacroTranscriberVar,
var_index: usize,
}
impl Parse for TranscriberVar {
fn parse(input: ParseStream) -> Result<Self> {
Ok(Self {
var: input.parse()?,
var_index: usize::MAX,
})
}
}
impl TranscriberVar {
fn attach(&mut self, p: &PatternItems) -> Result<()> {
let name = self.var.name.to_string();
let span = self.var.span();
if let Some(b) = p.vars.get(&name) {
if b.depth != 0 {
bail!(span, "variable '{name}' is still repeating at this depth",);
}
self.var_index = b.var_index_or_rep_index;
Ok(())
} else {
bail!(span, "attempted to repeat an expression containing no syntax variables matched as repeating at this depth")
}
}
fn apply_tokens_to(&self, m: &RawMatch, b: &mut MatchTokensBuilder) {
m.vars[self.var_index].apply_tokens_to(b)
}
fn apply_string(&self, m: &RawMatch, b: &mut MatchStringBuilder) {
m.vars[self.var_index].apply_string(b)
}
}
#[derive(Debug, Clone)]
struct TranscriberRep {
content: TranscriberItems,
sep: MacroRepSep,
op: MacroRepOp,
span: Span,
var: MacroTranscriberVar,
rep_index: usize,
}
impl TranscriberRep {
fn parse(input: &mut ParseStreamEx) -> Result<Self> {
let _dollar_token: Token![$] = input.parse()?;
input.expect(token::Paren)?;
let content = input.parse_group(|_g, input| TranscriberItems::parse(input))?;
let sep = input.parse()?;
let op: MacroRepOp = input.parse()?;
let span = _dollar_token.span();
let span = span.join(op.span()).unwrap_or(span);
let Some(var) = content.get_var() else {
bail!(span, "attempted to repeat an expression containing no syntax variables");
};
Ok(Self {
content,
sep,
op,
span,
var,
rep_index: usize::MAX,
})
}
fn attach(&mut self, p: &PatternItems) -> Result<()> {
let var_name = self.var.name.to_string();
if let Some(b) = p.vars.get(&var_name) {
if b.depth > 0 {
self.rep_index = b.var_index_or_rep_index;
if let Some(r) = p.find_rep(&var_name) {
if self.op != r.op {
bail!(
self.span,
"mismatch repeat operator. expected {:?}, found {:?}",
r.op,
self.op
);
}
return self.content.attach(&r.content);
}
}
}
bail!(self.var.span(), "attempted to repeat an expression containing no syntax variables matched as repeating at this depth")
}
fn apply_tokens_to(&self, m: &RawMatch, b: &mut MatchTokensBuilder) {
let mut is_next = false;
for m in &m.reps[self.rep_index].0 {
if is_next {
if let Some(sep) = &self.sep.0 {
sep.to_tokens(b.tokens);
}
}
is_next = true;
self.content.apply_tokens_to(m, b)
}
}
fn apply_string(&self, m: &RawMatch, b: &mut MatchStringBuilder) {
let mut is_next = false;
for m in &m.reps[self.rep_index].0 {
if is_next {
if let Some(sep) = &self.sep.0 {
b.b.push_tokens(&sep.to_token_stream());
}
}
is_next = true;
self.content.apply_string(m, b)
}
}
}