summaryrefslogtreecommitdiff
path: root/tools/gencode.js
blob: 750d730426356380edf0b6a7ca4c149f2a4f6906 (plain)
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
"use strict"

let fs = require("fs")

let pc = 0

function tokenize(s) {
	let list = []
	let p = 0,
		n = s.length
	while (p < n) {
		while (p < n && s[p] === " ")
			++p
		if (p < n) {
			let m = p
			while (p < n && s[p] !== " ") {
				let q = s[p++]
				switch (q) {
					case "(":
					case "[":
					case "{":
						for (let x = 1; p < n && x > 0; ++p) {
							switch (s[p]) {
								case "(":
								case "[":
								case "{":
									++x
									break
								case ")":
								case "]":
								case "}":
									--x
									break
							}
						}
						break
					case '"':
					case "'":
					case "`":
						while (p < n && s[p] !== q)
							++p
					break
				}
			}
			list.push(s.substring(m, p))
		}
	}
	return list
}

function emit(line) {
	++pc
	line[0] = "vm_" + line[0]
	for (let i = 1; i < line.length; ++i) {
		if (typeof line[i] === "string") {
			if (line[i] === "all")
				line[i] = 999
			if (line[i][0] === "(" && !line[i].match(/\)=>/))
				line[i] = "()=>" + line[i]
			if (line[i][0] === "`")
				line[i] = "()=>" + line[i]
		}
	}
	console.log("\t[ " + line.join(", ") + " ],")
}

console.log("// #region GENERATED EVENT CODE")
console.log("const CODE = []")
let first = false

for (let line of fs.readFileSync("events.txt", "utf-8").split("\n")) {
	line = line.trim()
	if (line.length === 0 || line[0] === "#")
		continue
	if (line === "EOF")
		break
	line = tokenize(line)
	switch (line[0]) {
	case "CARD":
		if (first++) {
			emit(["return"])
			console.log("]")
		}
		console.log("")
		console.log("CODE[" + line[1] + "] = [ // " + line.slice(3).join(" "))
		break

	case "log":
	case "prompt":
		emit([ line[0], line.slice(1).join(" ") ])
		break

	case "asm":
	case "if":
	case "while":
		emit([ line[0], "()=>" + line.slice(1).join(" ") ])
		break

	default:
		emit(line)
		break
	}
}

emit(["return"])
console.log("]")
console.log("// #endregion")