-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathwrite-rust-ops.js
executable file
·77 lines (73 loc) · 2.59 KB
/
write-rust-ops.js
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
// Utility to write out the opcode mapping from `bytecode-table.js`
// as a Rust module.
//
// Run it under `node` with the CLI in `bin/write-rust-ops.js`
define(['./bytecode-table'], function(bytecode_table) {
var bops = [];
while(true) {
var bc = bytecode_table.for_num(bops.length);
if (!bc) { break; }
bops.push(bc);
}
var comma = function(i) { return (i < (bops.length-1)) ? ',' : ''; };
console.log('// generated by TurtleScript write-rust-ops.js');
console.log('');
// ## Emit `Op` enumeration.
console.log('pub enum Op {');
bops.forEach(function(bc, i) {
console.log(' Op_' + bc.name + ' = ' + i + comma(i));
});
console.log('}');
console.log('');
// ## Emit `Op` functions.
console.log('impl Op {');
console.log(' pub fn args(&self) -> uint {');
console.log(' match *self {');
bops.forEach(function(bc, i) {
console.log(' Op_' + bc.name + ' => ' + bc.args + comma(i));
});
console.log(' }');
console.log(' }');
console.log(' pub fn stackpush(&self) -> uint {');
console.log(' match *self {');
bops.forEach(function(bc, i) {
console.log(' Op_' + bc.name + ' => ' + bc.stackpush() + comma(i));
});
console.log(' }');
console.log(' }');
console.log(' pub fn stackpop(&self, args: &[int]) -> uint {');
console.log(' match *self {');
bops.forEach(function(bc, i) {
var stackpop = bc.stackpop();
if (bc.name === 'invoke') {
stackpop = '(args[0] as uint) + 2';
}
console.log(' Op_' + bc.name + ' => ' + stackpop + comma(i));
});
console.log(' }');
console.log(' }');
console.log(' pub fn new_from_uint(val: uint) -> Op {');
console.log(' match val {');
bops.forEach(function(bc, i) {
console.log(' ' + i + ' => Op_' + bc.name + ',');
});
console.log(' _ => fail!()');
console.log(' }');
console.log(' }');
console.log('}');
// ## Unit tests for the generated module.
console.log('');
console.log('#[test]');
console.log('fn test_invoke() {');
console.log(' let op = Op_invoke;');
console.log(' let args : &[int] = &[3];');
console.log(' assert!(op.stackpop(args) == 5);');
console.log('}');
console.log('#[test]');
console.log('fn test_cast() {');
console.log(' let op1a = Op_push_literal;');
console.log(' let op1b = Op::new_from_uint(1);');
console.log(' assert!((op1a as int) == 1);');
console.log(' assert!((op1b as int) == 1);');
console.log('}');
});