forked from microsoft/devicescript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocess.ts
More file actions
420 lines (376 loc) · 11.5 KB
/
process.ts
File metadata and controls
420 lines (376 loc) · 11.5 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
const fs = require("fs")
interface OpCode {
name: string
args: string[]
code: string
rettype: string
printFmt?: string
description?: string
comment?: string
comment2?: string
isExpr?: boolean
isFun?: boolean
takesNumber?: boolean
}
interface SMap<T> {
[name: string]: T
}
interface Spec {
ops: OpCode[]
opProps?: string
opTypes?: string
enums: SMap<OpCode[]>
}
const _spec = processSpec(fs.readFileSync(process.argv[2], "utf-8"))
_spec.opProps = serializeProps(_spec.ops, opcodeProps)
_spec.opTypes = serializeProps(_spec.ops, opcodeType)
writeFile("bytecode.json", JSON.stringify(_spec, null, 4))
writeFile("jacs_bytecode.h", genCode(_spec, false))
writeFile("bytecode.ts", genCode(_spec, true))
writeFile("jacs_bytecode.ts", genCode(_spec, true, true))
function processSpec(filecontent: string): Spec {
const argCodes: SMap<string> = {
x: "e",
y: "e",
value: "e",
object: "e",
buffer: "e",
role: "e",
numfmt: "n",
opcall: "o",
jmpoffset: "j",
role_idx: "R",
string_idx: "S",
local_idx: "L",
func_idx: "F",
global_idx: "G",
param_idx: "P",
f64_idx: "D",
}
let backticksType: string = null
let lineNo = 0
let currColl: OpCode[] = null
let currObj: OpCode = null
let hasErrors = false
let isExpr = false
const res: Spec = {
ops: [],
enums: {
BinFmt: [],
},
}
try {
for (const line of filecontent.split(/\n/)) {
lineNo++
processLine(line)
}
} catch (e) {
error("exception: " + e.message)
}
finish()
checkCont(res.ops)
if (hasErrors) throw new Error()
return res
function computePrintFmt(obj: OpCode) {
if (obj.comment) {
const args = obj.args.slice()
let fmt = obj.comment.replace(/\w+/g, f => {
const idx = args.indexOf(f)
if (idx >= 0) {
args[idx] = null
return bareArgCode(f)
}
return f
})
const missing = args.find(a => a != null)
if (missing) error("missing arg in comment: " + missing)
if (obj.isExpr && fmt.indexOf(" ") >= 0) fmt = `(${fmt})`
obj.printFmt = fmt
} else if (obj.args.length == 1 && obj.takesNumber && obj.isExpr) {
obj.printFmt = argCode(obj.args[0])
} else if (obj.isExpr) {
obj.printFmt =
obj.name + "(" + obj.args.map(argCode).join(", ") + ")"
} else {
obj.printFmt =
obj.name.toUpperCase() + " " + obj.args.map(argCode).join(" ")
}
function bareArgCode(a: string) {
if (argCodes[a]) return "%" + argCodes[a]
return `%e`
}
function argCode(a: string) {
if (argCodes[a]) return "%" + argCodes[a]
return `${a}=%e`
}
}
function checkCont(lst: OpCode[]) {
let nums = [1]
for (const obj of lst) {
const idx = +obj.code
if (nums[idx]) error(`duplicate ${obj.name} ${idx}`)
nums[idx] = 1
}
if (nums.length != lst.length + 1) error("non-cont")
}
function error(msg = "syntax error") {
console.log(`error at ${lineNo}: ${msg}`)
hasErrors = true
}
function processLine(line: string) {
if (backticksType) {
if (line.trim() == "```") {
const prev = backticksType
backticksType = null
if (prev == "default") return
}
} else {
const m = /^```(.*)/.exec(line)
if (m) {
backticksType = m[1] || "default"
// if we just switched into code section, don't interpret this line and don't add to any description
if (backticksType == "default") return
}
}
const interpret =
backticksType == "default" ||
(backticksType == null && line.slice(0, 4) == " ")
if (!interpret) {
let m = /^(##+)\s*(.*)/.exec(line)
if (m) {
finish()
currObj = null
const [, hd, cont] = m
if (hd.length >= 3)
// sub-headers
return
switch (cont) {
case "Statements":
currColl = res.ops
isExpr = false
break
case "Expressions":
currColl = res.ops
isExpr = true
break
case "Format Constants":
isExpr = false
currColl = res.enums.BinFmt
break
default:
isExpr = false
m = /Enum: (\w+)/.exec(cont)
if (m) currColl = res.enums[m[1]] = []
else {
if (currColl == null) return // initial sections
error("bad header")
}
}
}
if (currObj) {
if (line.trim() && !currObj.description)
currObj.description = ""
if (currObj.description != null)
currObj.description += line + "\n"
}
} else {
let lineTr = line.trim()
let isFun = undefined
if (lineTr.startsWith("fun ")) {
isFun = true
lineTr = lineTr.slice(4).trim()
}
let m =
/^(\w+)(\s*\((.*)\))?\s*(:\s*(\w+))?\s*=\s*(\d+|0[bB][01]+|0[Xx][a-fA-F0-9]+)\s*(\/\/\s*(.*))?$/.exec(
lineTr
)
if (!m) {
error()
return
}
if (!currColl) {
error("no container")
return
}
const [
_line,
name,
_paren,
args_str,
_rettype,
rettype,
code,
_cmt,
comment,
] = m
let args: string[] = []
if (args_str) args = args_str.split(/,\s*/).filter(s => !!s.trim())
finish()
currObj = {
name,
args,
code,
comment,
rettype: rettype || "void",
isFun,
}
if (args[0] && args[0][0] == "*") {
currObj.takesNumber = true
args[0] = args[0].slice(1)
}
if (!comment && args.length > 0) {
let c = args.join(", ")
if (c != "x" && c != "x, y") {
if (currObj.takesNumber) c = "*" + c
currObj.comment2 = c
}
}
if (isExpr) {
currObj.isExpr = true
if (!rettype) error("return type not specified")
}
currColl.push(currObj)
}
}
function finish() {
if (currObj?.description)
currObj.description = currObj.description.trim()
if (currObj) computePrintFmt(currObj)
}
}
function writeFile(name: string, cont: string) {
console.log(`write ${name}`)
fs.writeFileSync("build/" + name, cont)
}
function sig(obj: OpCode) {
const numargs = obj.args.length
return (
(obj.isExpr ? "EXPR" : "STMT") +
(obj.takesNumber
? "x" + (numargs - 1 ? numargs - 1 : "")
: "" + numargs)
)
}
function sortByCode(lst: OpCode[]) {
lst = lst.slice()
lst.sort((a, b) => +a.code - +b.code)
return lst
}
function serializeProps(lst: OpCode[], fn: (o: OpCode) => number) {
const nums = sortByCode(lst).map(fn)
nums.unshift(0x7f)
return (
'"' +
nums.map(n => "\\x" + ("00" + n.toString(16)).slice(-2)).join("") +
'"'
)
}
function genJmpTables(spec: Spec) {
let r = "\n#define JACS_OP_HANDLERS expr_invalid, \\\n"
for (const obj of sortByCode(spec.ops)) {
r += `${sig(obj).toLowerCase()}_${obj.name}, \\\n`
}
r += "expr_invalid\n\n"
return r
}
function genCode(spec: Spec, isTS = false, isSTS = false) {
let r = "// Auto-generated from bytecode.md; do not edit.\n"
if (isSTS) r += "\nnamespace jacs {\n"
else if (isTS) r += "\n"
else r += "#pragma once\n\n"
startEnum("Op")
for (const obj of spec.ops) {
emitDefine(`${sig(obj)}_`, obj)
}
emitDefine(`OP_`, {
name: "past_last",
code: spec.ops.length + 1 + "",
rettype: "number",
args: [],
})
endEnum()
emitConst("op_props", spec.opProps)
emitConst("op_types", spec.opTypes)
for (const enName of Object.keys(spec.enums)) {
const pref =
isTS || enName == "BinFmt" ? "" : enName.toUpperCase() + "_"
startEnum(enName)
for (const obj of spec.enums[enName]) {
emitDefine(pref, obj)
}
endEnum()
}
emitFmts("op", spec.ops)
if (isTS)
for (const en of ["Object_Type"])
emitConst(
en,
JSON.stringify(enumNames(spec.enums[en]))
)
if (isSTS) r += "} // jacs\n"
if (!isTS) r += genJmpTables(spec)
return r
function emitFmts(id: string, lst: OpCode[]) {
if (!isTS) return
lst = sortByCode(lst)
emitConst(
id + "_print_fmts",
"[ null, " +
lst.map(o => JSON.stringify(o.printFmt)).join(", ") +
" ]"
)
}
function addCmt(cmt: string) {
if (!cmt) return ""
return " // " + cmt
}
function emitConst(name: string, val: string, comment?: string) {
comment = addCmt(comment)
if (isTS)
r += `export const ${name.toUpperCase()} = ${val} ${comment}\n`
else r += `#define JACS_${name.toUpperCase()} ${val} ${comment}\n`
}
function startEnum(name: string) {
r += "\n"
if (isTS) r += `export enum ${name.replace(/_/g, "")} {\n`
}
function endEnum() {
if (isTS) r += `}\n`
r += "\n"
}
function emitDefine(pref: string, obj: OpCode) {
const cmt = addCmt(obj.comment || obj.comment2)
const val = obj.code
const name = pref + obj.name.toUpperCase()
if (isTS) r += ` ${name} = ${val}, ${cmt}\n`
else r += `#define JACS_${name} ${val} ${cmt}\n`
}
}
function lookupEnum(en: string, fld: string) {
const ent = _spec.enums[en].find(o => o.name == fld)
if (!ent) return undefined
return +ent.code
}
function opcodeProps(obj: OpCode) {
let r = obj.args.length
if (obj.takesNumber) {
r -= 1
r |= lookupEnum("BytecodeFlag", "takes_number")
}
if (obj.isFun) r |= lookupEnum("BytecodeFlag", "is_stateless")
if (!obj.isExpr) r |= lookupEnum("BytecodeFlag", "is_stmt")
if (r == undefined) throw new Error()
return r
}
function opcodeType(obj: OpCode) {
const tp = lookupEnum("Object_Type", obj.rettype)
if (tp == undefined) throw new Error("invalid type: " + obj.rettype)
return tp
}
function enumNames(lst: OpCode[]) {
const names: string[] = []
for (const obj of sortByCode(lst)) {
names[+obj.code] = obj.name
}
return names
}