-
-
Notifications
You must be signed in to change notification settings - Fork 864
/
index.ts
694 lines (606 loc) · 18.3 KB
/
index.ts
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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
import type {ScopeValueSets, NameValue, ValueScope, ValueScopeName} from "./scope"
import {
_,
nil,
_Code,
Code,
Name,
UsedNames,
usedNames,
updateUsedNames,
CodeItem,
addCodeArg,
} from "./code"
import {Scope} from "./scope"
export {_, str, strConcat, nil, getProperty, stringify, Name, Code} from "./code"
export {Scope, ScopeStore, ValueScope} from "./scope"
// type for expressions that can be safely inserted in code without quotes
export type SafeExpr = Code | number | boolean | null
// type that is either Code of function that adds code to CodeGen instance using its methods
export type Block = Code | (() => void)
export const operators = {
GT: new _Code(">"),
GTE: new _Code(">="),
LT: new _Code("<"),
LTE: new _Code("<="),
EQ: new _Code("==="),
NEQ: new _Code("!=="),
NOT: new _Code("!"),
OR: new _Code("||"),
AND: new _Code("&&"),
}
export const varKinds = {
const: new Name("const"),
let: new Name("let"),
var: new Name("var"),
}
export interface CodeGenOptions {
es5?: boolean
lines?: boolean
ownProperties?: boolean
}
enum Node {
AnyCode,
Def,
Assign,
Label,
Break,
Throw,
Root,
If = "if",
Else = "else",
For = "for",
Func = "func",
Return = "return",
Try = "try",
Catch = "catch",
Finally = "finally",
}
interface _Node {
kind: Node
names?: UsedNames
}
interface DefNode extends _Node {
kind: Node.Def
varKind: Name
name: Name
rhs?: SafeExpr
}
interface AssignNode extends _Node {
kind: Node.Assign
lhs: Code
rhs: SafeExpr
}
interface LabelNode extends _Node {
kind: Node.Label
label: Name
names?: never
}
interface BreakNode extends _Node {
kind: Node.Break
label?: Code
names?: never
}
interface ThrowNode extends _Node {
kind: Node.Throw
error: Code
}
interface CodeNode extends _Node {
kind: Node.AnyCode
code: SafeExpr
}
interface _ParentNode extends _Node {
nodes: ChildNode[]
block?: boolean
}
interface RootNode extends _ParentNode {
kind: Node.Root
block: false
names?: never
}
interface IfNode extends _ParentNode {
kind: Node.If
condition: Code | boolean
else?: IfNode | ElseNode
}
interface ElseNode extends _ParentNode {
kind: Node.Else
names?: never
}
interface ForNode extends _ParentNode {
kind: Node.For
iteration: Code
}
interface FuncNode extends _ParentNode {
kind: Node.Func
name: Name
args: Code
async?: boolean
names?: never
}
interface ReturnNode extends _ParentNode {
kind: Node.Return
block: false
names?: never
}
interface TryNode extends _ParentNode {
kind: Node.Try
catch?: CatchNode
finally?: FinallyNode
names?: never
}
interface CatchNode extends _ParentNode {
kind: Node.Catch
error: Name
finally?: FinallyNode
names?: never
}
interface FinallyNode extends _ParentNode {
kind: Node.Finally
names?: never
}
type BlockNode = IfNode | ForNode | FuncNode | ReturnNode | TryNode
type LeafNode = DefNode | AssignNode | LabelNode | BreakNode | ThrowNode | CodeNode
type ParentNode = RootNode | BlockNode | ElseNode | CatchNode | FinallyNode
type ChildNode = BlockNode | LeafNode
export class CodeGen {
readonly _scope: Scope
readonly _extScope: ValueScope
readonly _values: ScopeValueSets = {}
private readonly _nodes: ParentNode[]
private readonly _blockStarts: number[] = []
private readonly opts: CodeGenOptions
private readonly _n: string
private _out = ""
nodeCount = 0
constructor(extScope: ValueScope, opts: CodeGenOptions = {}) {
this.opts = opts
this._extScope = extScope
this._scope = new Scope({parent: extScope})
this._nodes = [{kind: Node.Root, nodes: [], block: false}]
this._n = opts.lines ? "\n" : ""
}
toString(): string {
this._out = ""
this._nodeCode(this._nodes[0])
return this._out
}
// returns unique name in the internal scope
name(prefix: string): Name {
return this._scope.name(prefix)
}
// reserves unique name in the external scope
scopeName(prefix: string): ValueScopeName {
return this._extScope.name(prefix)
}
// reserves unique name in the external scope and assigns value to it
scopeValue(prefixOrName: ValueScopeName | string, value: NameValue): Name {
const name = this._extScope.value(prefixOrName, value)
const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set())
vs.add(name)
return name
}
getScopeValue(prefix: string, keyOrRef: unknown): ValueScopeName | undefined {
return this._extScope.getValue(prefix, keyOrRef)
}
// return code that assigns values in the external scope to the names that are used internally
// (same names that were returned by gen.scopeName or gen.scopeValue)
scopeRefs(scopeName: Name): Code {
return this._extScope.scopeRefs(scopeName, this._values)
}
scopeCode(): Code {
return this._extScope.scopeCode(this._values)
}
private _def(varKind: Name, nameOrPrefix: Name | string, rhs?: SafeExpr): Name {
const name = this._scope.toName(nameOrPrefix)
this._leafNode({kind: Node.Def, varKind, name, rhs, names: usedNames(rhs)})
return name
}
// `const` declaration (`var` in es5 mode)
const(nameOrPrefix: Name | string, rhs: SafeExpr): Name {
return this._def(varKinds.const, nameOrPrefix, rhs)
}
// `let` declaration with optional assignment (`var` in es5 mode)
let(nameOrPrefix: Name | string, rhs?: SafeExpr): Name {
return this._def(varKinds.let, nameOrPrefix, rhs)
}
// `var` declaration with optional assignment
var(nameOrPrefix: Name | string, rhs?: SafeExpr): Name {
return this._def(varKinds.var, nameOrPrefix, rhs)
}
// assignment code
assign(lhs: Code, rhs: SafeExpr): CodeGen {
const names = usedNames(rhs) || {}
if (!(lhs instanceof Name)) updateUsedNames(lhs, names)
return this._leafNode({kind: Node.Assign, lhs, rhs, names})
}
// appends passed SafeExpr to code or executes Block
code(c: Block | SafeExpr): CodeGen {
if (typeof c == "function") c()
else if (c !== nil) this._leafNode({kind: Node.AnyCode, code: c, names: usedNames(c)})
return this
}
// returns code for object literal for the passed argument list of key-value pairs
object(...keyValues: [Name, SafeExpr | string][]): _Code {
const code: CodeItem[] = ["{"]
for (const [key, value] of keyValues) {
if (code.length > 1) code.push(",")
code.push(key)
if (key !== value || this.opts.es5) {
code.push(":")
addCodeArg(code, value)
}
}
code.push("}")
return new _Code(code)
}
// `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed)
if(condition: Code | boolean, thenBody?: Block, elseBody?: Block): CodeGen {
this._blockNode({kind: Node.If, condition, nodes: [], names: usedNames(condition)})
if (thenBody && elseBody) {
this.code(thenBody).else().code(elseBody).endIf()
} else if (thenBody) {
this.code(thenBody).endIf()
} else if (elseBody) {
throw new Error('CodeGen: "else" body without "then" body')
}
return this
}
// `if` clause or statement with negated condition,
// useful to avoid using _ template just to negate the name
ifNot(condition: Code, thenBody?: Block, elseBody?: Block): CodeGen {
const cond = condition instanceof Name ? _`!${condition}` : _`!(${condition})`
return this.if(cond, thenBody, elseBody)
}
// `else if` clause - invalid without `if` or after `else` clauses
elseIf(condition: Code | boolean): CodeGen {
return this._elseNode({kind: Node.If, condition, nodes: [], names: usedNames(condition)})
}
// `else` clause - only valid after `if` or `else if` clauses
else(): CodeGen {
return this._elseNode({kind: Node.Else, nodes: []})
}
// end `if` statement (needed if gen.if was used only with condition)
endIf(): CodeGen {
return this._endBlockNode(Node.If, Node.Else)
}
// a generic `for` clause (or statement if `forBody` is passed)
for(iteration: Code, forBody?: Block): CodeGen {
this._blockNode({kind: Node.For, iteration, nodes: [], names: usedNames(iteration)})
if (forBody) this.code(forBody).endFor()
return this
}
// `for` statement for a range of values
forRange(
nameOrPrefix: Name | string,
from: SafeExpr,
to: SafeExpr,
forBody: (index: Name) => void,
varKind: Code = varKinds.let
): CodeGen {
const i = this._scope.toName(nameOrPrefix)
if (this.opts.es5) varKind = varKinds.var
return this.for(_`${varKind} ${i}=${from}; ${i}<${to}; ${i}++`, () => forBody(i))
}
// `for-of` statement (in es5 mode replace with a normal for loop)
forOf(
nameOrPrefix: Name | string,
iterable: SafeExpr,
forBody: (item: Name) => void,
varKind: Code = varKinds.const
): CodeGen {
const name = this._scope.toName(nameOrPrefix)
if (this.opts.es5) {
const arr = iterable instanceof Name ? iterable : this.var("_arr", iterable)
return this.forRange("_i", 0, _`${arr}.length`, (i) => {
this.var(name, _`${arr}[${i}]`)
forBody(name)
})
}
return this.for(_`${varKind} ${name} of ${iterable}`, () => forBody(name))
}
// `for-in` statement.
// With option `ownProperties` replaced with a `for-of` loop for object keys
forIn(
nameOrPrefix: Name | string,
obj: SafeExpr,
forBody: (item: Name) => void,
varKind: Code = varKinds.const
): CodeGen {
if (this.opts.ownProperties) {
return this.forOf(nameOrPrefix, _`Object.keys(${obj})`, forBody)
}
const name = this._scope.toName(nameOrPrefix)
return this.for(_`${varKind} ${name} in ${obj}`, () => forBody(name))
}
// end `for` loop
endFor(): CodeGen {
return this._endBlockNode(Node.For)
}
// `label` statement
label(label: Name): CodeGen {
return this._leafNode({kind: Node.Label, label})
}
// `break` statement
break(label?: Code): CodeGen {
return this._leafNode({kind: Node.Break, label})
}
// `return` statement
return(value: Block | SafeExpr): CodeGen {
const node: ReturnNode = {kind: Node.Return, nodes: [], block: false}
this._blockNode(node)
this.code(value)
if (node.nodes.length !== 1) throw new Error('CodeGen: "return" should have one node')
return this._endBlockNode(Node.Return)
}
// `try` statement
try(tryBody: Block, catchCode?: (e: Name) => void, finallyCode?: Block): CodeGen {
if (!catchCode && !finallyCode) throw new Error('CodeGen: "try" without "catch" and "finally"')
const tryNode: TryNode = {kind: Node.Try, nodes: []}
this._blockNode(tryNode)
this.code(tryBody)
let node: TryNode | CatchNode = tryNode
if (catchCode) {
const error = this.name("e")
node = this._currNode = node.catch = {kind: Node.Catch, error, nodes: []}
catchCode(error)
}
if (finallyCode) {
this._currNode = node.finally = {kind: Node.Finally, nodes: []}
this.code(finallyCode)
}
return this._endBlockNode(Node.Catch, Node.Finally)
}
// `throw` statement
throw(error: Code): CodeGen {
return this._leafNode({kind: Node.Throw, error, names: usedNames(error)})
}
// start self-balancing block
block(body?: Block, nodeCount?: number): CodeGen {
this._blockStarts.push(this._nodes.length)
if (body) this.code(body).endBlock(nodeCount)
return this
}
// end the current self-balancing block
endBlock(nodeCount?: number): CodeGen {
const len = this._blockStarts.pop()
if (len === undefined) throw new Error("CodeGen: not in self-balancing block")
const toClose = this._nodes.length - len
if (toClose < 0 || (nodeCount !== undefined && toClose !== nodeCount)) {
throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`)
}
this._nodes.length = len
return this
}
// `function` heading (or definition if funcBody is passed)
func(name: Name, args: Code = nil, async?: boolean, funcBody?: Block): CodeGen {
this._blockNode({kind: Node.Func, name, args, async, nodes: []})
if (funcBody) this.code(funcBody).endFunc()
return this
}
// end function definition
endFunc(): CodeGen {
return this._endBlockNode(Node.Func)
}
optimize(n = 1): void {
const {nodes} = this._nodes[0]
while (n--) {
optimizeNodes(nodes)
const names = getUsedNames(nodes)
removeUnusedNames(nodes, names)
}
}
private _leafNode(node: LeafNode): CodeGen {
this._currNode.nodes.push(node)
return this
}
private _blockNode(node: BlockNode): void {
this._currNode.nodes.push(node)
this._nodes.push(node)
}
private _endBlockNode(n1: Node, n2?: Node): CodeGen {
const {kind} = this._currNode
if (kind !== n1 && kind !== n2) {
throw new Error(`CodeGen: not in block "${n2 ? `${n1}/${n2}` : n1}"`)
}
this._nodes.pop()
return this
}
private _elseNode(node: IfNode | ElseNode): CodeGen {
const n = this._currNode
if (n.kind !== Node.If) {
throw new Error('CodeGen: "else" without "if"')
}
this._currNode = n.else = node
return this
}
private _nodeCode(node: ParentNode): void {
this.nodeCount++
switch (node.kind) {
case Node.If:
this._out += `if(${node.condition})`
this._blockCode(node)
if (node.else) {
this._out += "else "
this._nodeCode(node.else)
}
return
case Node.Try:
this._out += "try"
this._blockCode(node)
if (node.catch) this._nodeCode(node.catch)
if (node.finally) this._nodeCode(node.finally)
return
case Node.Catch:
this._out += `catch(${node.error})`
this._blockCode(node)
if (node.finally) this._nodeCode(node.finally)
return
case Node.For:
this._out += `for(${node.iteration})`
break
case Node.Func: {
this._out += (node.async ? "async " : "") + `function ${node.name}(${node.args})`
break
}
case Node.Return:
this._out += "return "
break
case Node.Finally: {
this._out += "finally"
break
}
case Node.Root:
case Node.Else:
break
default:
throw new Error("ajv implementation error")
}
this._blockCode(node)
}
private _leafNodeCode(node: LeafNode): void {
this.nodeCount++
let code: string
switch (node.kind) {
case Node.Def: {
const varKind = this.opts.es5 ? varKinds.var : node.varKind
code = `${varKind} ${node.name}` + (node.rhs === undefined ? ";" : ` = ${node.rhs};`)
break
}
case Node.Assign:
code = `${node.lhs} = ${node.rhs};`
break
case Node.Label:
code = `${node.label}:`
break
case Node.Break:
code = node.label ? `break ${node.label};` : "break;"
break
case Node.Throw:
code = `throw ${node.error};`
break
case Node.AnyCode:
code = `${node.code};`
break
default:
throw new Error("ajv implementation error")
}
this._out += code + this._n
}
private _blockCode({nodes, block = true}: ParentNode): void {
if (block) this._out += "{" + this._n
nodes.forEach((n) => ("nodes" in n ? this._nodeCode(n) : this._leafNodeCode(n)))
if (block) this._out += "}" + this._n
}
private get _currNode(): ParentNode {
const ns = this._nodes
return ns[ns.length - 1]
}
private set _currNode(node: ParentNode) {
const ns = this._nodes
ns[ns.length - 1] = node
}
}
function optimizeNodes(nodes: ChildNode[]): void {
let i = 0
while (i < nodes.length) {
const n = nodes[i]
if ("nodes" in n) optimizeNodes(n.nodes)
switch (n.kind) {
case Node.If: {
const ns = optimiseIf(n)
if (ns === n) break
if (Array.isArray(ns)) nodes.splice(i, 1, ...ns)
else if (ns) nodes.splice(i, 1, ns)
else nodes.splice(i, 1)
continue
}
case Node.For:
if (n.nodes.length) break
nodes.splice(i, 1)
continue
}
i++
}
}
function optimiseIf(node: IfNode): IfNode | ChildNode[] | undefined {
const cond = node.condition
if (cond === true) return node.nodes // else is ignored here
optimizeElse(node)
if (node.else) {
const e = node.else
if (cond === false) return e.kind === Node.If ? e : e.nodes
if (node.nodes.length) return node
return {
kind: Node.If,
condition: cond instanceof Name ? _`!${cond}` : _`!(${cond})`,
nodes: e.kind === Node.If ? [e] : e.nodes,
names: node.names,
}
}
if (cond === false || !node.nodes.length) return undefined
return node
}
function optimizeElse(node: IfNode): void {
if (!node.else) return
if (node.else.kind === Node.Else) {
if (node.else.nodes.length === 0) delete node.else
return
}
const nodes = optimiseIf(node.else)
node.else = Array.isArray(nodes) ? {kind: Node.Else, nodes} : nodes
}
function getUsedNames(nodes: ChildNode[], names: UsedNames = {}): UsedNames {
nodes.forEach((n) => {
countNodeNames(n, names)
})
return names
}
function countNodeNames(node: ParentNode | ChildNode, names: UsedNames): void {
if ("nodes" in node) getUsedNames(node.nodes, names)
if (node.names) updateUsedNames(node, names)
switch (node.kind) {
case Node.If:
if (node.else) countNodeNames(node.else, names)
break
case Node.Try:
if (node.catch) countNodeNames(node.catch, names)
if (node.finally) countNodeNames(node.finally, names)
break
case Node.Catch:
if (node.finally) countNodeNames(node.finally, names)
}
}
function removeUnusedNames(nodes: ChildNode[], names: UsedNames): void {
let i = 0
while (i < nodes.length) {
const n = nodes[i]
if ("nodes" in n) removeUnusedNames(n.nodes, names)
if (unusedName(n, names)) {
updateUsedNames(n, names, -1)
nodes.splice(i, 1)
continue
}
i++
}
}
function unusedName(n: ChildNode, names: UsedNames): boolean {
return (
(n.kind === Node.Def && !names[n.name.str]) ||
(n.kind === Node.Assign && n.lhs instanceof Name && !names[n.lhs.str])
)
}
const andCode = mappend(operators.AND)
// boolean AND (&&) expression with the passed arguments
export function and(...args: Code[]): Code {
return args.reduce(andCode)
}
const orCode = mappend(operators.OR)
// boolean OR (||) expression with the passed arguments
export function or(...args: Code[]): Code {
return args.reduce(orCode)
}
type MAppend = (x: Code, y: Code) => Code
function mappend(op: Code): MAppend {
return (x, y) => (x === nil ? y : y === nil ? x : _`${x} ${op} ${y}`)
}