forked from ProtoDef-io/node-protodef
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcompiler.js
446 lines (400 loc) · 14.1 KB
/
compiler.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
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
const numeric = require('./datatypes/numeric')
const utils = require('./datatypes/utils')
const conditionalDatatypes = require('./datatypes/compiler-conditional')
const structuresDatatypes = require('./datatypes/compiler-structures')
const utilsDatatypes = require('./datatypes/compiler-utils')
const { tryCatch } = require('./utils')
class ProtoDefCompiler {
constructor () {
this.readCompiler = new ReadCompiler()
this.writeCompiler = new WriteCompiler()
this.sizeOfCompiler = new SizeOfCompiler()
}
addTypes (types) {
this.readCompiler.addTypes(types.Read)
this.writeCompiler.addTypes(types.Write)
this.sizeOfCompiler.addTypes(types.SizeOf)
}
addTypesToCompile (types) {
this.readCompiler.addTypesToCompile(types)
this.writeCompiler.addTypesToCompile(types)
this.sizeOfCompiler.addTypesToCompile(types)
}
addProtocol (protocolData, path) {
this.readCompiler.addProtocol(protocolData, path)
this.writeCompiler.addProtocol(protocolData, path)
this.sizeOfCompiler.addProtocol(protocolData, path)
}
addVariable (key, val) {
this.readCompiler.addContextType(key, val)
this.writeCompiler.addContextType(key, val)
this.sizeOfCompiler.addContextType(key, val)
}
compileProtoDefSync (options = { printCode: false }) {
const sizeOfCode = this.sizeOfCompiler.generate()
const writeCode = this.writeCompiler.generate()
const readCode = this.readCompiler.generate()
if (options.printCode) {
console.log('// SizeOf:')
console.log(sizeOfCode)
console.log('// Write:')
console.log(writeCode)
console.log('// Read:')
console.log(readCode)
}
const sizeOfCtx = this.sizeOfCompiler.compile(sizeOfCode)
const writeCtx = this.writeCompiler.compile(writeCode)
const readCtx = this.readCompiler.compile(readCode)
return new CompiledProtodef(sizeOfCtx, writeCtx, readCtx)
}
}
class CompiledProtodef {
constructor (sizeOfCtx, writeCtx, readCtx) {
this.sizeOfCtx = sizeOfCtx
this.writeCtx = writeCtx
this.readCtx = readCtx
}
read (buffer, cursor, type) {
const readFn = this.readCtx[type]
if (!readFn) { throw new Error('missing data type: ' + type) }
return readFn(buffer, cursor)
}
write (value, buffer, cursor, type) {
const writeFn = this.writeCtx[type]
if (!writeFn) { throw new Error('missing data type: ' + type) }
return writeFn(value, buffer, cursor)
}
setVariable (key, val) {
this.sizeOfCtx[key] = val
this.readCtx[key] = val
this.writeCtx[key] = val
}
sizeOf (value, type) {
const sizeFn = this.sizeOfCtx[type]
if (!sizeFn) { throw new Error('missing data type: ' + type) }
if (typeof sizeFn === 'function') {
return sizeFn(value)
} else {
return sizeFn
}
}
createPacketBuffer (type, packet) {
const length = tryCatch(() => this.sizeOf(packet, type),
(e) => {
e.message = `SizeOf error for ${e.field} : ${e.message}`
throw e
})
const buffer = Buffer.allocUnsafe(length)
tryCatch(() => this.write(packet, buffer, 0, type),
(e) => {
e.message = `Write error for ${e.field} : ${e.message}`
throw e
})
return buffer
}
parsePacketBuffer (type, buffer, offset = 0) {
try {
const { value, size } = this.read(buffer, offset, type)
return {
data: value,
metadata: { size },
buffer: buffer.slice(0, size),
fullBuffer: buffer
}
} catch (e) {
console.warn(`Ignoring large array size error: ${e.message}`)
return {
data: [],
metadata: { size: buffer.length },
buffer: buffer,
fullBuffer: buffer
}
}
}
}
class Compiler {
constructor () {
this.primitiveTypes = {}
this.native = {}
this.context = {}
this.types = {}
this.scopeStack = []
this.parameterizableTypes = {}
}
/**
* A native type is a type read or written by a function that will be called in it's
* original context.
* @param {*} type
* @param {*} fn
*/
addNativeType (type, fn) {
this.primitiveTypes[type] = `native.${type}`
this.native[type] = fn
this.types[type] = 'native'
}
/**
* A context type is a type that will be called in the protocol's context. It can refer to
* registred native types using native.{type}() or context type (provided and generated)
* using ctx.{type}(), but cannot access it's original context.
* @param {*} type
* @param {*} fn
*/
addContextType (type, fn) {
this.primitiveTypes[type] = `ctx.${type}`
this.context[type] = fn.toString()
}
/**
* A parametrizable type is a function that will be generated at compile time using the
* provided maker function
* @param {*} type
* @param {*} maker
*/
addParametrizableType (type, maker) {
this.parameterizableTypes[type] = maker
}
addTypes (types) {
for (const [type, [kind, fn]] of Object.entries(types)) {
if (kind === 'native') this.addNativeType(type, fn)
else if (kind === 'context') this.addContextType(type, fn)
else if (kind === 'parametrizable') this.addParametrizableType(type, fn)
}
}
addTypesToCompile (types) {
for (const [type, json] of Object.entries(types)) {
// Replace native type, otherwise first in wins
if (!this.types[type] || this.types[type] === 'native') this.types[type] = json
}
}
addProtocol (protocolData, path) {
const self = this
function recursiveAddTypes (protocolData, path) {
if (protocolData === undefined) { return }
if (protocolData.types) { self.addTypesToCompile(protocolData.types) }
recursiveAddTypes(protocolData[path.shift()], path)
}
recursiveAddTypes(protocolData, path.slice(0))
}
indent (code, indent = ' ') {
return code.split('\n').map((line) => indent + line).join('\n')
}
getField (name, noAssign) {
const path = name.split('/')
let i = this.scopeStack.length - 1
const reserved = ['value', 'enum', 'default', 'size', 'offset']
while (path.length) {
const scope = this.scopeStack[i]
const field = path.shift()
if (field === '..') {
i--
continue
}
// We are at the right level
if (scope[field]) return scope[field] + (path.length ? ('.' + path.join('.')) : '')
if (path.length !== 0) {
throw new Error('Cannot access properties of undefined field')
}
// Count how many collision occured in the scope
let count = 0
if (reserved.includes(field)) count++
for (let j = 0; j < i; j++) {
if (this.scopeStack[j][field]) count++
}
if (noAssign) { // referencing a variable, inherit from parent scope
scope[field] = field
} else { // creating a new variable in this scope
scope[field] = field + (count || '') // If the name is already used, add a number
}
return scope[field]
}
throw new Error('Unknown field ' + path)
}
generate () {
this.scopeStack = [{}]
const functions = []
for (const type in this.context) {
functions[type] = this.context[type]
}
for (const type in this.types) {
if (!functions[type]) {
if (this.types[type] !== 'native') {
functions[type] = this.compileType(this.types[type])
if (functions[type].startsWith('ctx')) {
functions[type] = 'function () { return ' + functions[type] + '(...arguments) }'
}
if (!isNaN(functions[type])) { functions[type] = this.wrapCode(' return ' + functions[type]) }
} else {
functions[type] = `native.${type}`
}
}
}
return '() => {\n' + this.indent('const ctx = {\n' + this.indent(Object.keys(functions).map((type) => {
return type + ': ' + functions[type]
}).join(',\n')) + '\n}\nreturn ctx') + '\n}'
}
/**
* Compile the given js code, providing native.{type} to the context, return the compiled types
* @param {*} code
*/
compile (code) {
// Local variable to provide some context to eval()
const native = this.native // eslint-disable-line
const { PartialReadError } = require('./utils') // eslint-disable-line
return eval(code)() // eslint-disable-line
}
}
class ReadCompiler extends Compiler {
constructor () {
super()
this.addTypes(conditionalDatatypes.Read)
this.addTypes(structuresDatatypes.Read)
this.addTypes(utilsDatatypes.Read)
// Add default types
for (const key in numeric) {
this.addNativeType(key, numeric[key][0])
}
for (const key in utils) {
this.addNativeType(key, utils[key][0])
}
}
compileType (type) {
if (type instanceof Array) {
if (this.parameterizableTypes[type[0]]) { return this.parameterizableTypes[type[0]](this, type[1]) }
if (this.types[type[0]] && this.types[type[0]] !== 'native') {
return this.wrapCode('return ' + this.callType(type[0], 'offset', Object.values(type[1])))
}
throw new Error('Unknown parametrizable type: ' + JSON.stringify(type[0]))
} else { // Primitive type
if (type === 'native') return 'null'
if (this.types[type]) { return 'ctx.' + type }
return this.primitiveTypes[type]
}
}
wrapCode (code, args = []) {
if (args.length > 0) return '(buffer, offset, ' + args.join(', ') + ') => {\n' + this.indent(code) + '\n}'
return '(buffer, offset) => {\n' + this.indent(code) + '\n}'
}
callType (type, offsetExpr = 'offset', args = []) {
if (type instanceof Array) {
if (this.types[type[0]] && this.types[type[0]] !== 'native') {
return this.callType(type[0], offsetExpr, Object.values(type[1]))
}
}
if (type instanceof Array && type[0] === 'container') this.scopeStack.push({})
const code = this.compileType(type)
if (type instanceof Array && type[0] === 'container') this.scopeStack.pop()
if (args.length > 0) return '(' + code + `)(buffer, ${offsetExpr}, ` + args.map(name => this.getField(name)).join(', ') + ')'
return '(' + code + `)(buffer, ${offsetExpr})`
}
}
class WriteCompiler extends Compiler {
constructor () {
super()
this.addTypes(conditionalDatatypes.Write)
this.addTypes(structuresDatatypes.Write)
this.addTypes(utilsDatatypes.Write)
// Add default types
for (const key in numeric) {
this.addNativeType(key, numeric[key][1])
}
for (const key in utils) {
this.addNativeType(key, utils[key][1])
}
}
compileType (type) {
if (type instanceof Array) {
if (this.parameterizableTypes[type[0]]) { return this.parameterizableTypes[type[0]](this, type[1]) }
if (this.types[type[0]] && this.types[type[0]] !== 'native') {
return this.wrapCode('return ' + this.callType('value', type[0], 'offset', Object.values(type[1])))
}
throw new Error('Unknown parametrizable type: ' + type[0])
} else { // Primitive type
if (type === 'native') return 'null'
if (this.types[type]) { return 'ctx.' + type }
return this.primitiveTypes[type]
}
}
wrapCode (code, args = []) {
if (args.length > 0) return '(value, buffer, offset, ' + args.join(', ') + ') => {\n' + this.indent(code) + '\n}'
return '(value, buffer, offset) => {\n' + this.indent(code) + '\n}'
}
callType (value, type, offsetExpr = 'offset', args = []) {
if (type instanceof Array) {
if (this.types[type[0]] && this.types[type[0]] !== 'native') {
return this.callType(value, type[0], offsetExpr, Object.values(type[1]))
}
}
if (type instanceof Array && type[0] === 'container') this.scopeStack.push({})
const code = this.compileType(type)
if (type instanceof Array && type[0] === 'container') this.scopeStack.pop()
if (args.length > 0) return '(' + code + `)(${value}, buffer, ${offsetExpr}, ` + args.map(name => this.getField(name)).join(', ') + ')'
return '(' + code + `)(${value}, buffer, ${offsetExpr})`
}
}
class SizeOfCompiler extends Compiler {
constructor () {
super()
this.addTypes(conditionalDatatypes.SizeOf)
this.addTypes(structuresDatatypes.SizeOf)
this.addTypes(utilsDatatypes.SizeOf)
// Add default types
for (const key in numeric) {
this.addNativeType(key, numeric[key][2])
}
for (const key in utils) {
this.addNativeType(key, utils[key][2])
}
}
/**
* A native type is a type read or written by a function that will be called in it's
* original context.
* @param {*} type
* @param {*} fn
*/
addNativeType (type, fn) {
this.primitiveTypes[type] = `native.${type}`
if (!isNaN(fn)) {
this.native[type] = (value) => { return fn }
} else {
this.native[type] = fn
}
this.types[type] = 'native'
}
compileType (type) {
if (type instanceof Array) {
if (this.parameterizableTypes[type[0]]) { return this.parameterizableTypes[type[0]](this, type[1]) }
if (this.types[type[0]] && this.types[type[0]] !== 'native') {
return this.wrapCode('return ' + this.callType('value', type[0], Object.values(type[1])))
}
throw new Error('Unknown parametrizable type: ' + type[0])
} else { // Primitive type
if (type === 'native') return 'null'
if (!isNaN(this.primitiveTypes[type])) return this.primitiveTypes[type]
if (this.types[type]) { return 'ctx.' + type }
return this.primitiveTypes[type]
}
}
wrapCode (code, args = []) {
if (args.length > 0) return '(value, ' + args.join(', ') + ') => {\n' + this.indent(code) + '\n}'
return '(value) => {\n' + this.indent(code) + '\n}'
}
callType (value, type, args = []) {
if (type instanceof Array) {
if (this.types[type[0]] && this.types[type[0]] !== 'native') {
return this.callType(value, type[0], Object.values(type[1]))
}
}
if (type instanceof Array && type[0] === 'container') this.scopeStack.push({})
const code = this.compileType(type)
if (type instanceof Array && type[0] === 'container') this.scopeStack.pop()
if (!isNaN(code)) return code
if (args.length > 0) return '(' + code + `)(${value}, ` + args.map(name => this.getField(name)).join(', ') + ')'
return '(' + code + `)(${value})`
}
}
module.exports = {
ReadCompiler,
WriteCompiler,
SizeOfCompiler,
ProtoDefCompiler,
CompiledProtodef
}