1 import type {ScopeValueSets, NameValue, ValueScope, ValueScopeName} from "./scope"
2 import {_, nil, _Code, Code, Name, UsedNames, CodeItem, addCodeArg, _CodeOrName} from "./code"
3 import {Scope, varKinds} from "./scope"
5 export {_, str, strConcat, nil, getProperty, stringify, regexpCode, Name, Code} from "./code"
6 export {Scope, ScopeStore, ValueScope, ValueScopeName, ScopeValueSets, varKinds} from "./scope"
8 // type for expressions that can be safely inserted in code without quotes
9 export type SafeExpr = Code | number | boolean | null
11 // type that is either Code of function that adds code to CodeGen instance using its methods
12 export type Block = Code | (() => void)
14 export const operators = {
20 NEQ: new _Code("!=="),
28 abstract readonly names: UsedNames
30 optimizeNodes(): this | ChildNode | ChildNode[] | undefined {
34 optimizeNames(_names: UsedNames, _constants: Constants): this | undefined {
38 // get count(): number {
43 class Def extends Node {
44 constructor(private readonly varKind: Name, private readonly name: Name, private rhs?: SafeExpr) {
48 render({es5, _n}: CGOptions): string {
49 const varKind = es5 ? varKinds.var : this.varKind
50 const rhs = this.rhs === undefined ? "" : ` = ${this.rhs}`
51 return `${varKind} ${this.name}${rhs};` + _n
54 optimizeNames(names: UsedNames, constants: Constants): this | undefined {
55 if (!names[this.name.str]) return
56 if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants)
60 get names(): UsedNames {
61 return this.rhs instanceof _CodeOrName ? this.rhs.names : {}
65 class Assign extends Node {
66 constructor(readonly lhs: Code, public rhs: SafeExpr, private readonly sideEffects?: boolean) {
70 render({_n}: CGOptions): string {
71 return `${this.lhs} = ${this.rhs};` + _n
74 optimizeNames(names: UsedNames, constants: Constants): this | undefined {
75 if (this.lhs instanceof Name && !names[this.lhs.str] && !this.sideEffects) return
76 this.rhs = optimizeExpr(this.rhs, names, constants)
80 get names(): UsedNames {
81 const names = this.lhs instanceof Name ? {} : {...this.lhs.names}
82 return addExprNames(names, this.rhs)
86 class AssignOp extends Assign {
87 constructor(lhs: Code, private readonly op: Code, rhs: SafeExpr, sideEffects?: boolean) {
88 super(lhs, rhs, sideEffects)
91 render({_n}: CGOptions): string {
92 return `${this.lhs} ${this.op}= ${this.rhs};` + _n
96 class Label extends Node {
97 readonly names: UsedNames = {}
98 constructor(readonly label: Name) {
102 render({_n}: CGOptions): string {
103 return `${this.label}:` + _n
107 class Break extends Node {
108 readonly names: UsedNames = {}
109 constructor(readonly label?: Code) {
113 render({_n}: CGOptions): string {
114 const label = this.label ? ` ${this.label}` : ""
115 return `break${label};` + _n
119 class Throw extends Node {
120 constructor(readonly error: Code) {
124 render({_n}: CGOptions): string {
125 return `throw ${this.error};` + _n
128 get names(): UsedNames {
129 return this.error.names
133 class AnyCode extends Node {
134 constructor(private code: SafeExpr) {
138 render({_n}: CGOptions): string {
139 return `${this.code};` + _n
142 optimizeNodes(): this | undefined {
143 return `${this.code}` ? this : undefined
146 optimizeNames(names: UsedNames, constants: Constants): this {
147 this.code = optimizeExpr(this.code, names, constants)
151 get names(): UsedNames {
152 return this.code instanceof _CodeOrName ? this.code.names : {}
156 abstract class ParentNode extends Node {
157 constructor(readonly nodes: ChildNode[] = []) {
161 render(opts: CGOptions): string {
162 return this.nodes.reduce((code, n) => code + n.render(opts), "")
165 optimizeNodes(): this | ChildNode | ChildNode[] | undefined {
169 const n = nodes[i].optimizeNodes()
170 if (Array.isArray(n)) nodes.splice(i, 1, ...n)
171 else if (n) nodes[i] = n
172 else nodes.splice(i, 1)
174 return nodes.length > 0 ? this : undefined
177 optimizeNames(names: UsedNames, constants: Constants): this | undefined {
181 // iterating backwards improves 1-pass optimization
183 if (n.optimizeNames(names, constants)) continue
184 subtractNames(names, n.names)
187 return nodes.length > 0 ? this : undefined
190 get names(): UsedNames {
191 return this.nodes.reduce((names: UsedNames, n) => addNames(names, n.names), {})
194 // get count(): number {
195 // return this.nodes.reduce((c, n) => c + n.count, 1)
199 abstract class BlockNode extends ParentNode {
200 render(opts: CGOptions): string {
201 return "{" + opts._n + super.render(opts) + "}" + opts._n
205 class Root extends ParentNode {}
207 class Else extends BlockNode {
208 static readonly kind = "else"
211 class If extends BlockNode {
212 static readonly kind = "if"
214 constructor(private condition: Code | boolean, nodes?: ChildNode[]) {
218 render(opts: CGOptions): string {
219 let code = `if(${this.condition})` + super.render(opts)
220 if (this.else) code += "else " + this.else.render(opts)
224 optimizeNodes(): If | ChildNode[] | undefined {
225 super.optimizeNodes()
226 const cond = this.condition
227 if (cond === true) return this.nodes // else is ignored here
230 const ns = e.optimizeNodes()
231 e = this.else = Array.isArray(ns) ? new Else(ns) : (ns as Else | undefined)
234 if (cond === false) return e instanceof If ? e : e.nodes
235 if (this.nodes.length) return this
236 return new If(not(cond), e instanceof If ? [e] : e.nodes)
238 if (cond === false || !this.nodes.length) return undefined
242 optimizeNames(names: UsedNames, constants: Constants): this | undefined {
243 this.else = this.else?.optimizeNames(names, constants)
244 if (!(super.optimizeNames(names, constants) || this.else)) return
245 this.condition = optimizeExpr(this.condition, names, constants)
249 get names(): UsedNames {
250 const names = super.names
251 addExprNames(names, this.condition)
252 if (this.else) addNames(names, this.else.names)
256 // get count(): number {
257 // return super.count + (this.else?.count || 0)
261 abstract class For extends BlockNode {
262 static readonly kind = "for"
265 class ForLoop extends For {
266 constructor(private iteration: Code) {
270 render(opts: CGOptions): string {
271 return `for(${this.iteration})` + super.render(opts)
274 optimizeNames(names: UsedNames, constants: Constants): this | undefined {
275 if (!super.optimizeNames(names, constants)) return
276 this.iteration = optimizeExpr(this.iteration, names, constants)
280 get names(): UsedNames {
281 return addNames(super.names, this.iteration.names)
285 class ForRange extends For {
287 private readonly varKind: Name,
288 private readonly name: Name,
289 private readonly from: SafeExpr,
290 private readonly to: SafeExpr
295 render(opts: CGOptions): string {
296 const varKind = opts.es5 ? varKinds.var : this.varKind
297 const {name, from, to} = this
298 return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts)
301 get names(): UsedNames {
302 const names = addExprNames(super.names, this.from)
303 return addExprNames(names, this.to)
307 class ForIter extends For {
309 private readonly loop: "of" | "in",
310 private readonly varKind: Name,
311 private readonly name: Name,
312 private iterable: Code
317 render(opts: CGOptions): string {
318 return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts)
321 optimizeNames(names: UsedNames, constants: Constants): this | undefined {
322 if (!super.optimizeNames(names, constants)) return
323 this.iterable = optimizeExpr(this.iterable, names, constants)
327 get names(): UsedNames {
328 return addNames(super.names, this.iterable.names)
332 class Func extends BlockNode {
333 static readonly kind = "func"
334 constructor(public name: Name, public args: Code, public async?: boolean) {
338 render(opts: CGOptions): string {
339 const _async = this.async ? "async " : ""
340 return `${_async}function ${this.name}(${this.args})` + super.render(opts)
344 class Return extends ParentNode {
345 static readonly kind = "return"
347 render(opts: CGOptions): string {
348 return "return " + super.render(opts)
352 class Try extends BlockNode {
356 render(opts: CGOptions): string {
357 let code = "try" + super.render(opts)
358 if (this.catch) code += this.catch.render(opts)
359 if (this.finally) code += this.finally.render(opts)
363 optimizeNodes(): this {
364 super.optimizeNodes()
365 this.catch?.optimizeNodes() as Catch | undefined
366 this.finally?.optimizeNodes() as Finally | undefined
370 optimizeNames(names: UsedNames, constants: Constants): this {
371 super.optimizeNames(names, constants)
372 this.catch?.optimizeNames(names, constants)
373 this.finally?.optimizeNames(names, constants)
377 get names(): UsedNames {
378 const names = super.names
379 if (this.catch) addNames(names, this.catch.names)
380 if (this.finally) addNames(names, this.finally.names)
384 // get count(): number {
385 // return super.count + (this.catch?.count || 0) + (this.finally?.count || 0)
389 class Catch extends BlockNode {
390 static readonly kind = "catch"
391 constructor(readonly error: Name) {
395 render(opts: CGOptions): string {
396 return `catch(${this.error})` + super.render(opts)
400 class Finally extends BlockNode {
401 static readonly kind = "finally"
402 render(opts: CGOptions): string {
403 return "finally" + super.render(opts)
407 type StartBlockNode = If | For | Func | Return | Try
409 type LeafNode = Def | Assign | Label | Break | Throw | AnyCode
411 type ChildNode = StartBlockNode | LeafNode
413 type EndBlockNodeType =
422 type Constants = Record<string, SafeExpr | undefined>
424 export interface CodeGenOptions {
427 ownProperties?: boolean
430 interface CGOptions extends CodeGenOptions {
434 export class CodeGen {
435 readonly _scope: Scope
436 readonly _extScope: ValueScope
437 readonly _values: ScopeValueSets = {}
438 private readonly _nodes: ParentNode[]
439 private readonly _blockStarts: number[] = []
440 private readonly _constants: Constants = {}
441 private readonly opts: CGOptions
443 constructor(extScope: ValueScope, opts: CodeGenOptions = {}) {
444 this.opts = {...opts, _n: opts.lines ? "\n" : ""}
445 this._extScope = extScope
446 this._scope = new Scope({parent: extScope})
447 this._nodes = [new Root()]
451 return this._root.render(this.opts)
454 // returns unique name in the internal scope
455 name(prefix: string): Name {
456 return this._scope.name(prefix)
459 // reserves unique name in the external scope
460 scopeName(prefix: string): ValueScopeName {
461 return this._extScope.name(prefix)
464 // reserves unique name in the external scope and assigns value to it
465 scopeValue(prefixOrName: ValueScopeName | string, value: NameValue): Name {
466 const name = this._extScope.value(prefixOrName, value)
467 const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set())
472 getScopeValue(prefix: string, keyOrRef: unknown): ValueScopeName | undefined {
473 return this._extScope.getValue(prefix, keyOrRef)
476 // return code that assigns values in the external scope to the names that are used internally
477 // (same names that were returned by gen.scopeName or gen.scopeValue)
478 scopeRefs(scopeName: Name): Code {
479 return this._extScope.scopeRefs(scopeName, this._values)
483 return this._extScope.scopeCode(this._values)
488 nameOrPrefix: Name | string,
492 const name = this._scope.toName(nameOrPrefix)
493 if (rhs !== undefined && constant) this._constants[name.str] = rhs
494 this._leafNode(new Def(varKind, name, rhs))
498 // `const` declaration (`var` in es5 mode)
499 const(nameOrPrefix: Name | string, rhs: SafeExpr, _constant?: boolean): Name {
500 return this._def(varKinds.const, nameOrPrefix, rhs, _constant)
503 // `let` declaration with optional assignment (`var` in es5 mode)
504 let(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name {
505 return this._def(varKinds.let, nameOrPrefix, rhs, _constant)
508 // `var` declaration with optional assignment
509 var(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name {
510 return this._def(varKinds.var, nameOrPrefix, rhs, _constant)
514 assign(lhs: Code, rhs: SafeExpr, sideEffects?: boolean): CodeGen {
515 return this._leafNode(new Assign(lhs, rhs, sideEffects))
519 add(lhs: Code, rhs: SafeExpr): CodeGen {
520 return this._leafNode(new AssignOp(lhs, operators.ADD, rhs))
523 // appends passed SafeExpr to code or executes Block
524 code(c: Block | SafeExpr): CodeGen {
525 if (typeof c == "function") c()
526 else if (c !== nil) this._leafNode(new AnyCode(c))
530 // returns code for object literal for the passed argument list of key-value pairs
531 object(...keyValues: [Name | string, SafeExpr | string][]): _Code {
532 const code: CodeItem[] = ["{"]
533 for (const [key, value] of keyValues) {
534 if (code.length > 1) code.push(",")
536 if (key !== value || this.opts.es5) {
538 addCodeArg(code, value)
542 return new _Code(code)
545 // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed)
546 if(condition: Code | boolean, thenBody?: Block, elseBody?: Block): CodeGen {
547 this._blockNode(new If(condition))
549 if (thenBody && elseBody) {
550 this.code(thenBody).else().code(elseBody).endIf()
551 } else if (thenBody) {
552 this.code(thenBody).endIf()
553 } else if (elseBody) {
554 throw new Error('CodeGen: "else" body without "then" body')
559 // `else if` clause - invalid without `if` or after `else` clauses
560 elseIf(condition: Code | boolean): CodeGen {
561 return this._elseNode(new If(condition))
564 // `else` clause - only valid after `if` or `else if` clauses
566 return this._elseNode(new Else())
569 // end `if` statement (needed if gen.if was used only with condition)
571 return this._endBlockNode(If, Else)
574 private _for(node: For, forBody?: Block): CodeGen {
575 this._blockNode(node)
576 if (forBody) this.code(forBody).endFor()
580 // a generic `for` clause (or statement if `forBody` is passed)
581 for(iteration: Code, forBody?: Block): CodeGen {
582 return this._for(new ForLoop(iteration), forBody)
585 // `for` statement for a range of values
587 nameOrPrefix: Name | string,
590 forBody: (index: Name) => void,
591 varKind: Code = this.opts.es5 ? varKinds.var : varKinds.let
593 const name = this._scope.toName(nameOrPrefix)
594 return this._for(new ForRange(varKind, name, from, to), () => forBody(name))
597 // `for-of` statement (in es5 mode replace with a normal for loop)
599 nameOrPrefix: Name | string,
601 forBody: (item: Name) => void,
602 varKind: Code = varKinds.const
604 const name = this._scope.toName(nameOrPrefix)
606 const arr = iterable instanceof Name ? iterable : this.var("_arr", iterable)
607 return this.forRange("_i", 0, _`${arr}.length`, (i) => {
608 this.var(name, _`${arr}[${i}]`)
612 return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name))
615 // `for-in` statement.
616 // With option `ownProperties` replaced with a `for-of` loop for object keys
618 nameOrPrefix: Name | string,
620 forBody: (item: Name) => void,
621 varKind: Code = this.opts.es5 ? varKinds.var : varKinds.const
623 if (this.opts.ownProperties) {
624 return this.forOf(nameOrPrefix, _`Object.keys(${obj})`, forBody)
626 const name = this._scope.toName(nameOrPrefix)
627 return this._for(new ForIter("in", varKind, name, obj), () => forBody(name))
632 return this._endBlockNode(For)
636 label(label: Name): CodeGen {
637 return this._leafNode(new Label(label))
641 break(label?: Code): CodeGen {
642 return this._leafNode(new Break(label))
645 // `return` statement
646 return(value: Block | SafeExpr): CodeGen {
647 const node = new Return()
648 this._blockNode(node)
650 if (node.nodes.length !== 1) throw new Error('CodeGen: "return" should have one node')
651 return this._endBlockNode(Return)
655 try(tryBody: Block, catchCode?: (e: Name) => void, finallyCode?: Block): CodeGen {
656 if (!catchCode && !finallyCode) throw new Error('CodeGen: "try" without "catch" and "finally"')
657 const node = new Try()
658 this._blockNode(node)
661 const error = this.name("e")
662 this._currNode = node.catch = new Catch(error)
666 this._currNode = node.finally = new Finally()
667 this.code(finallyCode)
669 return this._endBlockNode(Catch, Finally)
673 throw(error: Code): CodeGen {
674 return this._leafNode(new Throw(error))
677 // start self-balancing block
678 block(body?: Block, nodeCount?: number): CodeGen {
679 this._blockStarts.push(this._nodes.length)
680 if (body) this.code(body).endBlock(nodeCount)
684 // end the current self-balancing block
685 endBlock(nodeCount?: number): CodeGen {
686 const len = this._blockStarts.pop()
687 if (len === undefined) throw new Error("CodeGen: not in self-balancing block")
688 const toClose = this._nodes.length - len
689 if (toClose < 0 || (nodeCount !== undefined && toClose !== nodeCount)) {
690 throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`)
692 this._nodes.length = len
696 // `function` heading (or definition if funcBody is passed)
697 func(name: Name, args: Code = nil, async?: boolean, funcBody?: Block): CodeGen {
698 this._blockNode(new Func(name, args, async))
699 if (funcBody) this.code(funcBody).endFunc()
703 // end function definition
705 return this._endBlockNode(Func)
708 optimize(n = 1): void {
710 this._root.optimizeNodes()
711 this._root.optimizeNames(this._root.names, this._constants)
715 private _leafNode(node: LeafNode): CodeGen {
716 this._currNode.nodes.push(node)
720 private _blockNode(node: StartBlockNode): void {
721 this._currNode.nodes.push(node)
722 this._nodes.push(node)
725 private _endBlockNode(N1: EndBlockNodeType, N2?: EndBlockNodeType): CodeGen {
726 const n = this._currNode
727 if (n instanceof N1 || (N2 && n instanceof N2)) {
731 throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`)
734 private _elseNode(node: If | Else): CodeGen {
735 const n = this._currNode
736 if (!(n instanceof If)) {
737 throw new Error('CodeGen: "else" without "if"')
739 this._currNode = n.else = node
743 private get _root(): Root {
744 return this._nodes[0] as Root
747 private get _currNode(): ParentNode {
748 const ns = this._nodes
749 return ns[ns.length - 1]
752 private set _currNode(node: ParentNode) {
753 const ns = this._nodes
754 ns[ns.length - 1] = node
757 // get nodeCount(): number {
758 // return this._root.count
762 function addNames(names: UsedNames, from: UsedNames): UsedNames {
763 for (const n in from) names[n] = (names[n] || 0) + (from[n] || 0)
767 function addExprNames(names: UsedNames, from: SafeExpr): UsedNames {
768 return from instanceof _CodeOrName ? addNames(names, from.names) : names
771 function optimizeExpr<T extends SafeExpr | Code>(expr: T, names: UsedNames, constants: Constants): T
772 function optimizeExpr(expr: SafeExpr, names: UsedNames, constants: Constants): SafeExpr {
773 if (expr instanceof Name) return replaceName(expr)
774 if (!canOptimize(expr)) return expr
776 expr._items.reduce((items: CodeItem[], c: SafeExpr | string) => {
777 if (c instanceof Name) c = replaceName(c)
778 if (c instanceof _Code) items.push(...c._items)
784 function replaceName(n: Name): SafeExpr {
785 const c = constants[n.str]
786 if (c === undefined || names[n.str] !== 1) return n
791 function canOptimize(e: SafeExpr): e is _Code {
793 e instanceof _Code &&
795 (c) => c instanceof Name && names[c.str] === 1 && constants[c.str] !== undefined
801 function subtractNames(names: UsedNames, from: UsedNames): void {
802 for (const n in from) names[n] = (names[n] || 0) - (from[n] || 0)
805 export function not<T extends Code | SafeExpr>(x: T): T
806 export function not(x: Code | SafeExpr): Code | SafeExpr {
807 return typeof x == "boolean" || typeof x == "number" || x === null ? !x : _`!${par(x)}`
810 const andCode = mappend(operators.AND)
812 // boolean AND (&&) expression with the passed arguments
813 export function and(...args: Code[]): Code {
814 return args.reduce(andCode)
817 const orCode = mappend(operators.OR)
819 // boolean OR (||) expression with the passed arguments
820 export function or(...args: Code[]): Code {
821 return args.reduce(orCode)
824 type MAppend = (x: Code, y: Code) => Code
826 function mappend(op: Code): MAppend {
827 return (x, y) => (x === nil ? y : y === nil ? x : _`${par(x)} ${op} ${par(y)}`)
830 function par(x: Code): Code {
831 return x instanceof Name ? x : _`(${x})`