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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
/*! Intermediate code representation. */
use super::*;
use crate::reader::Offset;
use crate::utils;
use crate::Compiler;
use crate::{Object, RefValue};
#[derive(Debug, Clone)]
pub(in crate::compiler) enum ImlOp {
Nop, // Empty operation
Op(Op), // VM Operation
Load {
offset: Option<Offset>,
target: ImlValue,
//copy: bool, //enforce copy (Op::Sep)
},
Call {
offset: Option<Offset>,
target: ImlValue,
args: Option<(usize, bool)>,
},
// Alternation (Block) of sequences or ops
Alt {
alts: Vec<ImlOp>,
},
// Sequence of ops, optionally a collection
Seq {
seq: Vec<ImlOp>,
collection: bool, /* According to these operation's semantics, or when an entire sequence is completely recognized,
the sequence is getting accepted. Incomplete sequences are rejected, but might partly be
processed, including data changes, which is a wanted behavior. */
},
// Conditional block
If {
peek: bool, // Peek test value instead of pop (required to implement the or-operator)
test: bool, // Boolean value to test against (true or false)
then: Box<ImlOp>, // Conditional code path
else_: Box<ImlOp>, // Optional code path executed otherwise
},
// Loop construct
Loop {
iterator: bool, // Test condition either for void (=true) or bool (=false)
initial: Box<ImlOp>, // Initialization
condition: Box<ImlOp>, // Abort condition
body: Box<ImlOp>, // Iterating body
},
// v--- below variants are being replaced by Tokay generics as soon as they are implemented ---v //
// Expect (deprecated!)
Expect {
body: Box<ImlOp>,
msg: Option<String>,
},
// Not (deprecated!)
Not {
body: Box<ImlOp>,
},
// Peek (deprecated!)
Peek {
body: Box<ImlOp>,
},
// Repeat (deprecated!)
Repeat {
body: Box<ImlOp>,
min: usize,
max: usize,
},
}
impl ImlOp {
/// Creates a sequence from items, and optimizes stacked, unframed sequences
pub fn seq(items: Vec<ImlOp>, collection: bool) -> ImlOp {
let mut seq = Vec::new();
for item in items {
match item {
ImlOp::Nop => {}
ImlOp::Seq {
collection: false,
seq: items,
} => seq.extend(items),
item => seq.push(item),
}
}
match seq.len() {
0 => ImlOp::Nop,
1 if !collection => seq.pop().unwrap(),
_ => ImlOp::Seq { seq, collection },
}
}
/// Load value
pub fn load(offset: Option<Offset>, value: ImlValue) -> ImlOp {
ImlOp::Load {
offset,
target: value,
}
}
/// Load unknown value by name
pub fn load_by_name(compiler: &mut Compiler, offset: Option<Offset>, name: String) -> ImlOp {
Self::load(
offset.clone(),
ImlValue::Name {
offset,
name,
generic: false,
}
.try_resolve(compiler),
)
}
/// Call known value
pub fn call(offset: Option<Offset>, value: ImlValue, args: Option<(usize, bool)>) -> ImlOp {
// When args is unset, and the value is not callable without arguments,
// consider this call as a load.
if args.is_none() && !value.is_callable(true) {
// Currently not planned as final
return Self::load(offset, value);
}
// Early recognize call to value which is generally not call-able
if !value.is_callable(true) && !value.is_callable(false) {
// Currently not planned as final
todo!("The value {:?} is generally not callable!", value);
}
ImlOp::Call {
offset,
target: value,
args,
}
}
/// Call unknown value by name
pub fn call_by_name(
compiler: &mut Compiler,
offset: Option<Offset>,
name: String,
args: Option<(usize, bool)>,
) -> ImlOp {
// Perform early consumable detection depending on identifier's name
if utils::identifier_is_consumable(&name) {
compiler.parselet_mark_consuming();
}
ImlOp::Call {
offset: offset.clone(),
target: ImlValue::Name {
offset,
name,
generic: false,
}
.try_resolve(compiler),
args,
}
}
/// Turns ImlOp construct into a kleene (none-or-many) occurence.
pub fn into_kleene(self) -> Self {
Self::Repeat {
body: Box::new(self),
min: 0,
max: 0,
}
}
/// Turns ImlOp construct into a positive (one-or-many) occurence.
pub fn into_positive(self) -> Self {
Self::Repeat {
body: Box::new(self),
min: 1,
max: 0,
}
}
/// Turns ImlOp construct into an optional (none-or-one) occurence.
pub fn into_optional(self) -> Self {
Self::Repeat {
body: Box::new(self),
min: 0,
max: 1,
}
}
/// Turns ImlOp construct into a peeked parser
pub fn into_peek(self) -> Self {
Self::Peek {
body: Box::new(self),
}
}
/// Turns ImlOp construct into a negated parser
pub fn into_not(self) -> Self {
Self::Not {
body: Box::new(self),
}
}
/// Turns ImlOp construct into an expecting parser
pub fn into_expect(self, mut msg: Option<String>) -> Self {
// When no msg is provided, generate a message from the next consumables in range!
// This got a bit out of hand, and should be done later via something like a FIRST() attribute on parselet.
// Generally, this code becomes unnecessary when the Expect<P> generic is made available (see #10 for details)
if msg.is_none() {
fn get_expect(op: &ImlOp) -> Option<String> {
match op {
ImlOp::Call { target, .. } | ImlOp::Load { target, .. }
if target.is_consuming() =>
{
Some(format!("{:?}", target).to_string())
}
ImlOp::Seq { seq, .. } => {
let mut txt = None;
for item in seq {
item.walk(&mut |op| {
txt = get_expect(op);
!txt.is_some()
});
if txt.is_some() {
break;
}
}
txt
}
ImlOp::Alt { alts, .. } => {
let mut all_txt = Vec::new();
for item in alts {
let mut txt = None;
item.walk(&mut |op| {
txt = get_expect(op);
!txt.is_some()
});
if let Some(txt) = txt {
all_txt.push(txt);
}
}
if all_txt.is_empty() {
None
} else {
Some(all_txt.join(" or "))
}
}
_ => None,
}
}
self.walk(&mut |op| {
msg = get_expect(op);
!msg.is_some()
});
if let Some(txt) = msg {
msg = Some(format!("Expecting {}", txt).to_string())
}
}
Self::Expect {
body: Box::new(self),
msg,
}
}
/// Compile ImlOp construct into Op instructions of the resulting Tokay VM program
pub fn compile_to_vec(&self, program: &mut ImlProgram) -> Vec<Op> {
let mut ops = Vec::new();
self.compile(program, &mut ops);
ops
}
/// Compile ImlOp construct into Op instructions of the resulting Tokay VM program
pub fn compile(&self, program: &mut ImlProgram, ops: &mut Vec<Op>) -> usize {
let start = ops.len();
match self {
ImlOp::Nop => {}
ImlOp::Op(op) => ops.push(op.clone()),
ImlOp::Load { offset, target } => {
if let Some(offset) = offset {
ops.push(Op::Offset(Box::new(*offset)));
}
target.compile_load(program, ops);
}
ImlOp::Call {
offset,
target,
args,
} => {
if let Some(offset) = offset {
ops.push(Op::Offset(Box::new(*offset)));
}
target.compile_call(program, *args, ops);
}
ImlOp::Alt { alts } => {
let mut ret = Vec::new();
let mut iter = alts.iter();
let mut jumps = Vec::new();
let mut initial_fuse = None;
while let Some(item) = iter.next() {
let mut alt = Vec::new();
item.compile(program, &mut alt);
// When branch has more than one item, Frame it.
if iter.len() > 0 {
let fuse = alt.len() + if item.is_consuming() { 3 } else { 2 };
if initial_fuse.is_none() {
initial_fuse = Some(fuse) // this is used for the initial frame
} else {
ret.push(Op::Fuse(fuse)); // this updates the fuse of the frame
}
ret.extend(alt);
if item.is_consuming() {
// Insert Nop as location for later jump backpatch
ret.push(Op::Nop);
jumps.push(ret.len() - 1);
}
ret.push(Op::Reset);
} else {
ret.extend(alt);
}
}
// Backpatch remembered jumps
while let Some(addr) = jumps.pop() {
ret[addr] = Op::ForwardIfConsumed(ret.len() - addr);
}
// Wrap the entire body in its own frame when more than 1 alternative exists
if let Some(fuse) = initial_fuse {
ret.insert(0, Op::Frame(fuse));
ret.push(Op::Close);
}
ops.extend(ret);
}
ImlOp::Seq { seq, collection } => {
for item in seq.iter() {
item.compile(program, ops);
}
// Check if the sequence exists of more than one operational instruction
if *collection
&& ops[start..]
.iter()
.map(|op| if matches!(op, Op::Offset(_)) { 0 } else { 1 })
.sum::<usize>()
> 1
{
ops.insert(start, Op::Frame(0));
ops.push(Op::Collect);
ops.push(Op::Close);
}
}
ImlOp::If {
peek,
test,
then: then_part,
else_: else_part,
} => {
// Copy on peek
if *peek {
ops.push(Op::Copy(1));
}
let backpatch = ops.len();
ops.push(Op::Nop); // Backpatch operation placeholder
if *peek {
ops.push(Op::Drop)
}
// Then-part
let mut jump = then_part.compile(program, ops) + 1;
if !*peek {
let mut else_ops = Vec::new();
// Else-part
if else_part.compile(program, &mut else_ops) > 0 {
ops.push(Op::Forward(else_ops.len() + 1));
jump += 1;
ops.extend(else_ops);
}
} else {
jump += 1;
}
// Insert the final condition and its failure target.
if *test {
ops[backpatch] = Op::ForwardIfFalse(jump);
} else {
ops[backpatch] = Op::ForwardIfTrue(jump);
}
}
ImlOp::Loop {
iterator,
initial,
condition,
body,
} => {
let consuming: Option<bool> = None; // fixme: Currently not sure if this is an issue.
let mut repeat = Vec::new();
initial.compile(program, ops);
if condition.compile(program, &mut repeat) > 0 {
if *iterator {
repeat.push(Op::ForwardIfNotVoid(2));
} else {
repeat.push(Op::ForwardIfTrue(2));
}
repeat.push(Op::Break);
}
body.compile(program, &mut repeat);
let len = repeat.len() + if consuming.is_some() { 3 } else { 2 };
ops.push(Op::Loop(len));
// fixme: consuming flag must be handled differently.
if consuming.is_some() {
ops.push(Op::Fuse(ops.len() - start + 2));
}
ops.extend(repeat);
ops.push(Op::Continue);
if consuming.is_some() {
ops.push(Op::Break);
}
}
// DEPRECATED BELOW!!!
ImlOp::Expect { body, msg } => {
let mut expect = Vec::new();
body.compile(program, &mut expect);
ops.push(Op::Frame(expect.len() + 2));
ops.extend(expect);
ops.extend(vec![
Op::Forward(2),
Op::Error(Some(if let Some(msg) = msg {
msg.clone()
} else {
format!("Expecting {:?}", body)
})),
Op::Close,
]);
}
ImlOp::Not { body } => {
let mut body_ops = Vec::new();
let body_len = body.compile(program, &mut body_ops);
ops.push(Op::Frame(body_len + 3));
ops.extend(body_ops);
ops.push(Op::Close);
ops.push(Op::Next);
ops.push(Op::Close);
}
ImlOp::Peek { body } => {
ops.push(Op::Frame(0));
body.compile(program, ops);
ops.push(Op::Reset);
ops.push(Op::Close);
}
ImlOp::Repeat { body, min, max } => {
let mut body_ops = Vec::new();
let body_len = body.compile(program, &mut body_ops);
match (min, max) {
(0, 0) => {
// Kleene
ops.extend(vec![
Op::Frame(0), // The overall capture
Op::Frame(body_len + 6), // The fused capture for repetition
]);
ops.extend(body_ops); // here comes the body
ops.extend(vec![
Op::ForwardIfConsumed(2), // When consumed we can commit and jump backward
Op::Forward(4), // otherwise leave the loop
Op::Capture,
Op::Extend,
Op::Backward(body_len + 4), // repeat the body
Op::Close,
Op::InCollect,
Op::Close,
]);
}
(1, 0) => {
// Positive
ops.push(Op::Frame(0)); // The overall capture
ops.extend(body_ops.clone()); // here comes the body for the first time
ops.extend(vec![
Op::ForwardIfConsumed(2), // If nothing was consumed, then...
Op::Next, //...reject
Op::Frame(body_len + 6), // The fused capture for repetition
]);
ops.extend(body_ops); // here comes the body again inside the repetition
ops.extend(vec![
Op::ForwardIfConsumed(2), // When consumed we can commit and jump backward
Op::Forward(4), // otherwise leave the loop
Op::Capture,
Op::Extend,
Op::Backward(body_len + 4), // repeat the body
Op::Close,
Op::InCollect,
Op::Close,
]);
}
(0, 1) => {
// Optional
ops.push(Op::Frame(body_len + 1)); // on error, jump to the collect
ops.extend(body_ops);
ops.push(Op::InCollect);
ops.push(Op::Close);
}
(1, 1) => {}
(_, _) => unimplemented!(
"ImlOp::Repeat construct with min/max configuration > 1 not implemented yet"
),
};
}
}
ops.len() - start
}
/// Generic querying function taking a closure that either walks on the tree or stops.
pub fn walk(&self, func: &mut dyn FnMut(&Self) -> bool) -> bool {
// Call closure on current ImlOp, break on false return
if !func(self) {
return false;
}
// Query along ImlOp structure
match self {
ImlOp::Alt { alts: items } | ImlOp::Seq { seq: items, .. } => {
for item in items {
if !item.walk(func) {
return false;
}
}
true
}
ImlOp::If { then, else_, .. } => {
for i in [&then, &else_] {
if !i.walk(func) {
return false;
}
}
true
}
ImlOp::Loop {
initial,
condition,
body,
..
} => {
for i in [&initial, &condition, &body] {
if !i.walk(func) {
return false;
}
}
true
}
// DEPRECATED BELOW!!!
ImlOp::Expect { body, .. }
| ImlOp::Not { body }
| ImlOp::Peek { body }
| ImlOp::Repeat { body, .. } => body.walk(func),
_ => true,
}
}
pub fn is_consuming(&self) -> bool {
let mut consuming = false;
self.walk(&mut |op| {
match op {
ImlOp::Call { target, .. } => {
if target.is_consuming() {
consuming = true;
return false; // stop further examination
}
}
ImlOp::Op(Op::Next) => {
consuming = true;
return false; // stop further examination
}
_ => {}
}
true
});
consuming
}
/** Returns a value to operate with or evaluate during compile-time.
The function will only return Ok(Value) when the static_expression_evaluation-feature
is enabled, it is ImlOp::Load and the value is NOT a callable! */
pub fn get_evaluable_value(&self) -> Result<RefValue, ()> {
if cfg!(feature = "static_expression_evaluation") {
if let Self::Load {
target: ImlValue::Value(value),
..
} = self
{
if !value.is_callable(true) {
return Ok(value.clone().into());
}
}
}
Err(())
}
}
impl From<Op> for ImlOp {
fn from(op: Op) -> Self {
ImlOp::Op(op)
}
}
impl From<Vec<ImlOp>> for ImlOp {
fn from(items: Vec<ImlOp>) -> Self {
ImlOp::seq(items, false)
}
}