-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtranscode.rs
More file actions
622 lines (575 loc) · 16.8 KB
/
transcode.rs
File metadata and controls
622 lines (575 loc) · 16.8 KB
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
//! Transcode BL602 Rhai Script to uLisp
use std::convert::TryInto;
use rhai::{
AST,
ASTNode,
Expr,
FnCallExpr,
Position,
Stmt,
StmtBlock,
};
use crate::scope;
/// Transcode the compiled Rhai Script to uLisp
pub fn transcode(ast: &AST) -> String {
// Start the first uLisp Scope
let scope_index = scope::begin_scope("let* ()");
// Walk the nodes in the Rhai Abstract Syntax Tree
ast.walk(&mut transcode_node);
// End the first uLisp Scope and get the uLisp S-Expression for the scope
let output = scope::end_scope(scope_index);
println!("Transcoded uLisp:\n{}", output);
output
}
/// Transcode the Rhai AST Node to uLisp
fn transcode_node(nodes: &[ASTNode]) -> bool {
// We take the root node, ignore the subnodes
let node = &nodes[0];
// Get the source code position
let pos = match node {
ASTNode::Stmt(stmt) => stmt.position(),
ASTNode::Expr(expr) => expr.position(),
};
// Skip this node if we've already handled it
unsafe {
static mut LAST_POSITION: Position = Position::NONE;
if LAST_POSITION == pos { return true; }
LAST_POSITION = pos;
println!("Node: {:#?}", node);
}
// Transcode the Node: Statement or Expression
let output = match node {
ASTNode::Stmt(stmt) => transcode_stmt(stmt),
ASTNode::Expr(expr) => transcode_expr(expr),
};
// Add the transcoded uLisp S-Expression to the current scope
scope::add_to_scope(&output);
// Return true to walk the next node in the tree
true
}
/// Transcode a Rhai Statement to uLisp
fn transcode_stmt(stmt: &Stmt) -> String {
match stmt {
/* Let or Const Statement: `let LED_GPIO = 11`
Var(
11 @ 4:24,
"LED_GPIO" @ 4:13,
(),
4:9,
),
becomes...
( let*
(( LED_GPIO 11 ))
...
)
*/
Stmt::Var(expr, ident, _, _) => {
// Begin a new uLisp Scope
scope::begin_scope(
format!(
"let* (( {} {} ))", // `let* (( LED_GPIO 11 ))`
ident.name, // `LED_GPIO`
transcode_expr(expr), // `11`
).as_str()
);
// Scope will end when the parent scope ends
"".to_string()
}
/* For Statement: `for i in range(0, 10) { ... }`
For(
FnCall {
name: "range",
hash: 7910928861698536248,
args: [
StackSlot(0) @ 10:24,
StackSlot(1) @ 10:27,
],
constants: [
0,
10,
],
} @ 10:18,
(
"i" @ 10:13,
None,
Block[ ... ] @ 10:31,
),
10:9,
)
becomes...
( dotimes (i 10)
...
)
*/
Stmt::For(expr, id_counter, _) => {
// TODO: Support `for` counter
let id = &id_counter.0;
let stmts = &id_counter.2;
// Get the `for` range, e.g. `[0, 10]`
let range = get_range(expr);
let lower_limit = range[0];
let upper_limit = range[1];
assert!(lower_limit == 0); // TODO: Allow Lower Limit to be non-zero
// Begin a new uLisp Scope
let scope_index = scope::begin_scope(
format!(
"dotimes ({} {})", // `dotimes (i 10)`
id.name, // `i`
upper_limit, // `10`
).as_str()
);
// Transcode the Statement Block
transcode_block(stmts);
// End the uLisp Scope and add the transcoded uLisp S-Expression to the parent scope
scope::end_scope(scope_index)
}
/* Loop or While Statement: `loop { ... }`
While(
(),
Block[
Var(
1 @ 4:21,
"a" @ 4:17,
(),
4:13,
),
If(
FnCall {
name: "==",
hash: 12432925577119877140 (native only),
args: [
Variable(a #1) @ 5:16,
StackSlot(0) @ 5:21,
],
constants: [
1,
],
} @ 5:18,
(
Block[
Break(
5:25,
),
] @ 5:23,
Block[],
),
5:13,
),
] @ 3:14,
3:9,
)
becomes...
( loop ... )
*/
Stmt::While(expr, stmts, _) => {
// Begin a new uLisp Scope
let scope_index = scope::begin_scope("loop");
// TODO: Transcode `expr`
assert!("()" == format!("{:?}", expr));
// Transcode the Statement Block
transcode_block(stmts);
// End the uLisp Scope and add the transcoded uLisp S-Expression to the parent scope
scope::end_scope(scope_index)
}
/* If Statement: `if a == 1 { ... }`
If(
FnCall {
name: "==",
hash: 6230347975385344721 (native only),
args: [
Variable(a #1) @ 5:16,
StackSlot(0) @ 5:21,
],
constants: [
1,
],
} @ 5:18,
(
Block[
Break(
5:25,
),
] @ 5:23,
Block[],
),
5:13,
)
becomes...
( if ( eq a 1 ) ... )
*/
Stmt::If(expr, then_else, _) => {
// Begin a new uLisp Scope
let scope_index = scope::begin_scope(
format!(
"if {}",
transcode_expr(expr)
).as_str()
);
// Transcode the Then Statement Block
transcode_block(&then_else.0);
// Transcode the Else Statement Block
transcode_block(&then_else.1);
// End the uLisp Scope and add the transcoded uLisp S-Expression to the parent scope
scope::end_scope(scope_index)
}
// Break Statement: `break`
// becomes `( return )`
Stmt::Break(_) => "( return )".to_string(),
// Function Call: `gpio::enable_output(LED_GPIO, 0, 0)`
Stmt::FnCall(expr, _) => format!(
"{}",
transcode_fncall(expr)
),
_ => panic!("Unknown stmt: {:#?}", stmt)
}
}
/// Transcode a Rhai Expression to uLisp
fn transcode_expr(expr: &Expr) -> String {
match expr {
// Integers become themselves
Expr::IntegerConstant(i, _) => format!("{}", i),
// Variables become their names
Expr::Variable(_, _, var) => format!("{}", var.2),
// Function Call: `gpio::enable_output(LED_GPIO, 0, 0)`
Expr::FnCall(expr, _) => transcode_fncall(expr),
_ => panic!("Unknown expr: {:#?}", expr)
}
}
/// Transcode a Rhai Function Call to uLisp
fn transcode_fncall(expr: &FnCallExpr) -> String {
/* Function Call: `gpio::enable_output(LED_GPIO, 0, 0)`
FnCallExpr {
namespace: Some(
gpio,
),
hashes: 4301736447638837139,
args: [
Variable(LED_GPIO #1) @ 7:29,
StackSlot(0) @ 7:39,
StackSlot(1) @ 7:42,
],
constants: [
0,
0,
],
name: "enable_output",
capture: false,
}
becomes...
( bl_gpio_enable_output 11 0 0 )
*/
// Compose namespace like `bl_gpio_` or ``
let namespace = match &expr.namespace {
Some(ns) => format!("bl_{:#?}_", ns), // TODO
None => "".to_string()
};
// Compose arguments
let args = expr.args.iter().map(|arg| {
// Transcode each argument
let val = match arg {
// Transcode a StackSlot by looking up the constants
Expr::Stack(i, _) => format!("{}", expr.constants[*i]),
// Transcode other expressions
_ => transcode_expr(&arg)
};
val + " "
});
// Transcode to uLisp Function Call:
// `( bl_gpio_enable_output 11 0 0 )`
format!(
"( {}{} {})",
namespace, // `bl_gpio_` or ``
rename_function(&expr.name.as_str()), // `enable_output`, `+` or `mod`
args.collect::<String>() // `11 0 0 `
)
}
/// Transcode the Statement Block and the transcoded uLisp S-Expression to the current scope
fn transcode_block(stmts: &StmtBlock) {
stmts.clone().statements_mut().iter().for_each(|stmt| {
// Transcode each Statement
let output = transcode_stmt(stmt);
// Add the transcoded uLisp S-Expression to the current scope
scope::add_to_scope(&output);
});
}
/// Rename a Rhai Function or Operator Name to uLisp:
/// `%` becomes `mod`, `==` becomes `eq`
fn rename_function(name: &str) -> String {
match name {
"%" => "mod", // `%` becomes `mod`
"==" => "eq", // `==` becomes `eq`
_ => name // Else pass through
}.to_string()
}
/// Given a Rhai range expression like `range(0, 10)`
/// return the lower and upper limits: `[0, 10]`
fn get_range(expr: &Expr) -> [i32; 2] {
match expr {
/* Range Expression: `range(0, 10)`
FnCall {
name: "range",
hash: 7910928861698536248,
args: [
StackSlot(0) @ 10:24,
StackSlot(1) @ 10:27,
],
constants: [
0,
10,
],
}
becomes...
[0, 10]
*/
Expr::FnCall(expr, _) => {
assert!(expr.name == "range");
// Compose arguments
let args = expr.args.iter().map(|arg| {
// Transcode each argument
match arg {
// Transcode a StackSlot by looking up the constants
Expr::Stack(i, _) => expr.constants[*i]
.clone()
.try_cast::<i32>()
.expect("Range arg is not integer"),
// Transcode other expressions
_ => panic!("Unknown range arg: {:#?}", arg)
}
});
// Return the arguments as an array
let result: Vec<i32> = args.collect();
result.try_into()
.expect("Range should have 2 args")
}
_ => panic!("Unknown range: {:#?}", expr)
}
}
/* Output Log:
begin: let* ()
Node: Stmt(
While(
(),
Block[
Var(
1 @ 4:21,
"a" @ 4:17,
(),
4:13,
),
FnCall(
FnCallExpr {
namespace: None,
hashes: 67527529886503918,
args: [
Variable(a #1) @ 5:19,
],
constants: [],
name: "print",
capture: false,
},
5:13,
),
If(
FnCall {
name: "==",
hash: 17995251237036173671 (native only),
args: [
Variable(a #1) @ 6:16,
StackSlot(0) @ 6:21,
],
constants: [
1,
],
} @ 6:18,
(
Block[
Break(
6:25,
),
] @ 6:23,
Block[],
),
6:13,
),
] @ 3:14,
3:9,
),
)
begin: loop
begin: let* (( a 1 ))
add: ( print a )
begin: if ( eq a 1 )
add: ( return )
add: ( if ( eq a 1 )
( return )
)
add: ( loop
( let* (( a 1 ))
( print a )
( if ( eq a 1 )
( return )
)
)
)
Node: Stmt(
Var(
11 @ 11:24,
"LED_GPIO" @ 11:13,
(),
11:9,
),
)
begin: let* (( LED_GPIO 11 ))
Node: Stmt(
FnCall(
FnCallExpr {
namespace: Some(
gpio,
),
hashes: 12987214658708294900,
args: [
Variable(LED_GPIO #1) @ 14:29,
StackSlot(0) @ 14:39,
StackSlot(1) @ 14:42,
],
constants: [
0,
0,
],
name: "enable_output",
capture: false,
},
14:15,
),
)
add: ( bl_gpio_enable_output LED_GPIO 0 0 )
Node: Stmt(
For(
FnCall {
name: "range",
hash: 575929612303946337,
args: [
StackSlot(0) @ 17:24,
StackSlot(1) @ 17:27,
],
constants: [
0,
10,
],
} @ 17:18,
(
"i" @ 17:13,
None,
Block[
FnCall(
FnCallExpr {
namespace: Some(
gpio,
),
hashes: 11353779519759374485,
args: [
Variable(LED_GPIO #2) @ 21:17,
FnCall {
name: "%",
hash: 3751886575790804804 (native only),
args: [
Variable(i #1) @ 22:17,
StackSlot(0) @ 22:21,
],
constants: [
2,
],
} @ 22:19,
],
constants: [],
name: "output_set",
capture: false,
},
20:19,
),
FnCall(
FnCallExpr {
namespace: None,
hashes: 16488626815644268959,
args: [
StackSlot(0) @ 26:24,
],
constants: [
1000,
],
name: "time_delay",
capture: false,
},
26:13,
),
] @ 17:31,
),
17:9,
),
)
begin: dotimes (i 10)
add: ( bl_gpio_output_set LED_GPIO ( mod i 2 ) )
add: ( time_delay 1000 )
add: ( dotimes (i 10)
( bl_gpio_output_set LED_GPIO ( mod i 2 ) )
( time_delay 1000 )
)
Node: Stmt(
Var(
40 @ 30:17,
"a" @ 30:13,
(),
30:9,
),
)
begin: let* (( a 40 ))
Node: Stmt(
Var(
2 @ 31:17,
"b" @ 31:13,
(),
31:9,
),
)
begin: let* (( b 2 ))
Node: Stmt(
FnCall(
FnCallExpr {
namespace: None,
hashes: 749902770210084069 (native only),
args: [
Variable(a #2) @ 32:9,
Variable(b #1) @ 32:13,
],
constants: [],
name: "+",
capture: false,
},
32:11,
),
)
add: ( + a b )
Transcoded uLisp:
( let* ()
( loop
( let* (( a 1 ))
( print a )
( if ( eq a 1 )
( return )
)
)
)
( let* (( LED_GPIO 11 ))
( bl_gpio_enable_output LED_GPIO 0 0 )
( dotimes (i 10)
( bl_gpio_output_set LED_GPIO ( mod i 2 ) )
( time_delay 1000 )
)
( let* (( a 40 ))
( let* (( b 2 ))
( + a b )
)
)
)
)
*/