index.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832
  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"
  4. export {_, str, strConcat, nil, getProperty, stringify, regexpCode, Name, Code} from "./code"
  5. export {Scope, ScopeStore, ValueScope, ValueScopeName, ScopeValueSets, varKinds} from "./scope"
  6. // type for expressions that can be safely inserted in code without quotes
  7. export type SafeExpr = Code | number | boolean | null
  8. // type that is either Code of function that adds code to CodeGen instance using its methods
  9. export type Block = Code | (() => void)
  10. export const operators = {
  11. GT: new _Code(">"),
  12. GTE: new _Code(">="),
  13. LT: new _Code("<"),
  14. LTE: new _Code("<="),
  15. EQ: new _Code("==="),
  16. NEQ: new _Code("!=="),
  17. NOT: new _Code("!"),
  18. OR: new _Code("||"),
  19. AND: new _Code("&&"),
  20. ADD: new _Code("+"),
  21. }
  22. abstract class Node {
  23. abstract readonly names: UsedNames
  24. optimizeNodes(): this | ChildNode | ChildNode[] | undefined {
  25. return this
  26. }
  27. optimizeNames(_names: UsedNames, _constants: Constants): this | undefined {
  28. return this
  29. }
  30. // get count(): number {
  31. // return 1
  32. // }
  33. }
  34. class Def extends Node {
  35. constructor(private readonly varKind: Name, private readonly name: Name, private rhs?: SafeExpr) {
  36. super()
  37. }
  38. render({es5, _n}: CGOptions): string {
  39. const varKind = es5 ? varKinds.var : this.varKind
  40. const rhs = this.rhs === undefined ? "" : ` = ${this.rhs}`
  41. return `${varKind} ${this.name}${rhs};` + _n
  42. }
  43. optimizeNames(names: UsedNames, constants: Constants): this | undefined {
  44. if (!names[this.name.str]) return
  45. if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants)
  46. return this
  47. }
  48. get names(): UsedNames {
  49. return this.rhs instanceof _CodeOrName ? this.rhs.names : {}
  50. }
  51. }
  52. class Assign extends Node {
  53. constructor(readonly lhs: Code, public rhs: SafeExpr, private readonly sideEffects?: boolean) {
  54. super()
  55. }
  56. render({_n}: CGOptions): string {
  57. return `${this.lhs} = ${this.rhs};` + _n
  58. }
  59. optimizeNames(names: UsedNames, constants: Constants): this | undefined {
  60. if (this.lhs instanceof Name && !names[this.lhs.str] && !this.sideEffects) return
  61. this.rhs = optimizeExpr(this.rhs, names, constants)
  62. return this
  63. }
  64. get names(): UsedNames {
  65. const names = this.lhs instanceof Name ? {} : {...this.lhs.names}
  66. return addExprNames(names, this.rhs)
  67. }
  68. }
  69. class AssignOp extends Assign {
  70. constructor(lhs: Code, private readonly op: Code, rhs: SafeExpr, sideEffects?: boolean) {
  71. super(lhs, rhs, sideEffects)
  72. }
  73. render({_n}: CGOptions): string {
  74. return `${this.lhs} ${this.op}= ${this.rhs};` + _n
  75. }
  76. }
  77. class Label extends Node {
  78. readonly names: UsedNames = {}
  79. constructor(readonly label: Name) {
  80. super()
  81. }
  82. render({_n}: CGOptions): string {
  83. return `${this.label}:` + _n
  84. }
  85. }
  86. class Break extends Node {
  87. readonly names: UsedNames = {}
  88. constructor(readonly label?: Code) {
  89. super()
  90. }
  91. render({_n}: CGOptions): string {
  92. const label = this.label ? ` ${this.label}` : ""
  93. return `break${label};` + _n
  94. }
  95. }
  96. class Throw extends Node {
  97. constructor(readonly error: Code) {
  98. super()
  99. }
  100. render({_n}: CGOptions): string {
  101. return `throw ${this.error};` + _n
  102. }
  103. get names(): UsedNames {
  104. return this.error.names
  105. }
  106. }
  107. class AnyCode extends Node {
  108. constructor(private code: SafeExpr) {
  109. super()
  110. }
  111. render({_n}: CGOptions): string {
  112. return `${this.code};` + _n
  113. }
  114. optimizeNodes(): this | undefined {
  115. return `${this.code}` ? this : undefined
  116. }
  117. optimizeNames(names: UsedNames, constants: Constants): this {
  118. this.code = optimizeExpr(this.code, names, constants)
  119. return this
  120. }
  121. get names(): UsedNames {
  122. return this.code instanceof _CodeOrName ? this.code.names : {}
  123. }
  124. }
  125. abstract class ParentNode extends Node {
  126. constructor(readonly nodes: ChildNode[] = []) {
  127. super()
  128. }
  129. render(opts: CGOptions): string {
  130. return this.nodes.reduce((code, n) => code + n.render(opts), "")
  131. }
  132. optimizeNodes(): this | ChildNode | ChildNode[] | undefined {
  133. const {nodes} = this
  134. let i = nodes.length
  135. while (i--) {
  136. const n = nodes[i].optimizeNodes()
  137. if (Array.isArray(n)) nodes.splice(i, 1, ...n)
  138. else if (n) nodes[i] = n
  139. else nodes.splice(i, 1)
  140. }
  141. return nodes.length > 0 ? this : undefined
  142. }
  143. optimizeNames(names: UsedNames, constants: Constants): this | undefined {
  144. const {nodes} = this
  145. let i = nodes.length
  146. while (i--) {
  147. // iterating backwards improves 1-pass optimization
  148. const n = nodes[i]
  149. if (n.optimizeNames(names, constants)) continue
  150. subtractNames(names, n.names)
  151. nodes.splice(i, 1)
  152. }
  153. return nodes.length > 0 ? this : undefined
  154. }
  155. get names(): UsedNames {
  156. return this.nodes.reduce((names: UsedNames, n) => addNames(names, n.names), {})
  157. }
  158. // get count(): number {
  159. // return this.nodes.reduce((c, n) => c + n.count, 1)
  160. // }
  161. }
  162. abstract class BlockNode extends ParentNode {
  163. render(opts: CGOptions): string {
  164. return "{" + opts._n + super.render(opts) + "}" + opts._n
  165. }
  166. }
  167. class Root extends ParentNode {}
  168. class Else extends BlockNode {
  169. static readonly kind = "else"
  170. }
  171. class If extends BlockNode {
  172. static readonly kind = "if"
  173. else?: If | Else
  174. constructor(private condition: Code | boolean, nodes?: ChildNode[]) {
  175. super(nodes)
  176. }
  177. render(opts: CGOptions): string {
  178. let code = `if(${this.condition})` + super.render(opts)
  179. if (this.else) code += "else " + this.else.render(opts)
  180. return code
  181. }
  182. optimizeNodes(): If | ChildNode[] | undefined {
  183. super.optimizeNodes()
  184. const cond = this.condition
  185. if (cond === true) return this.nodes // else is ignored here
  186. let e = this.else
  187. if (e) {
  188. const ns = e.optimizeNodes()
  189. e = this.else = Array.isArray(ns) ? new Else(ns) : (ns as Else | undefined)
  190. }
  191. if (e) {
  192. if (cond === false) return e instanceof If ? e : e.nodes
  193. if (this.nodes.length) return this
  194. return new If(not(cond), e instanceof If ? [e] : e.nodes)
  195. }
  196. if (cond === false || !this.nodes.length) return undefined
  197. return this
  198. }
  199. optimizeNames(names: UsedNames, constants: Constants): this | undefined {
  200. this.else = this.else?.optimizeNames(names, constants)
  201. if (!(super.optimizeNames(names, constants) || this.else)) return
  202. this.condition = optimizeExpr(this.condition, names, constants)
  203. return this
  204. }
  205. get names(): UsedNames {
  206. const names = super.names
  207. addExprNames(names, this.condition)
  208. if (this.else) addNames(names, this.else.names)
  209. return names
  210. }
  211. // get count(): number {
  212. // return super.count + (this.else?.count || 0)
  213. // }
  214. }
  215. abstract class For extends BlockNode {
  216. static readonly kind = "for"
  217. }
  218. class ForLoop extends For {
  219. constructor(private iteration: Code) {
  220. super()
  221. }
  222. render(opts: CGOptions): string {
  223. return `for(${this.iteration})` + super.render(opts)
  224. }
  225. optimizeNames(names: UsedNames, constants: Constants): this | undefined {
  226. if (!super.optimizeNames(names, constants)) return
  227. this.iteration = optimizeExpr(this.iteration, names, constants)
  228. return this
  229. }
  230. get names(): UsedNames {
  231. return addNames(super.names, this.iteration.names)
  232. }
  233. }
  234. class ForRange extends For {
  235. constructor(
  236. private readonly varKind: Name,
  237. private readonly name: Name,
  238. private readonly from: SafeExpr,
  239. private readonly to: SafeExpr
  240. ) {
  241. super()
  242. }
  243. render(opts: CGOptions): string {
  244. const varKind = opts.es5 ? varKinds.var : this.varKind
  245. const {name, from, to} = this
  246. return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts)
  247. }
  248. get names(): UsedNames {
  249. const names = addExprNames(super.names, this.from)
  250. return addExprNames(names, this.to)
  251. }
  252. }
  253. class ForIter extends For {
  254. constructor(
  255. private readonly loop: "of" | "in",
  256. private readonly varKind: Name,
  257. private readonly name: Name,
  258. private iterable: Code
  259. ) {
  260. super()
  261. }
  262. render(opts: CGOptions): string {
  263. return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts)
  264. }
  265. optimizeNames(names: UsedNames, constants: Constants): this | undefined {
  266. if (!super.optimizeNames(names, constants)) return
  267. this.iterable = optimizeExpr(this.iterable, names, constants)
  268. return this
  269. }
  270. get names(): UsedNames {
  271. return addNames(super.names, this.iterable.names)
  272. }
  273. }
  274. class Func extends BlockNode {
  275. static readonly kind = "func"
  276. constructor(public name: Name, public args: Code, public async?: boolean) {
  277. super()
  278. }
  279. render(opts: CGOptions): string {
  280. const _async = this.async ? "async " : ""
  281. return `${_async}function ${this.name}(${this.args})` + super.render(opts)
  282. }
  283. }
  284. class Return extends ParentNode {
  285. static readonly kind = "return"
  286. render(opts: CGOptions): string {
  287. return "return " + super.render(opts)
  288. }
  289. }
  290. class Try extends BlockNode {
  291. catch?: Catch
  292. finally?: Finally
  293. render(opts: CGOptions): string {
  294. let code = "try" + super.render(opts)
  295. if (this.catch) code += this.catch.render(opts)
  296. if (this.finally) code += this.finally.render(opts)
  297. return code
  298. }
  299. optimizeNodes(): this {
  300. super.optimizeNodes()
  301. this.catch?.optimizeNodes() as Catch | undefined
  302. this.finally?.optimizeNodes() as Finally | undefined
  303. return this
  304. }
  305. optimizeNames(names: UsedNames, constants: Constants): this {
  306. super.optimizeNames(names, constants)
  307. this.catch?.optimizeNames(names, constants)
  308. this.finally?.optimizeNames(names, constants)
  309. return this
  310. }
  311. get names(): UsedNames {
  312. const names = super.names
  313. if (this.catch) addNames(names, this.catch.names)
  314. if (this.finally) addNames(names, this.finally.names)
  315. return names
  316. }
  317. // get count(): number {
  318. // return super.count + (this.catch?.count || 0) + (this.finally?.count || 0)
  319. // }
  320. }
  321. class Catch extends BlockNode {
  322. static readonly kind = "catch"
  323. constructor(readonly error: Name) {
  324. super()
  325. }
  326. render(opts: CGOptions): string {
  327. return `catch(${this.error})` + super.render(opts)
  328. }
  329. }
  330. class Finally extends BlockNode {
  331. static readonly kind = "finally"
  332. render(opts: CGOptions): string {
  333. return "finally" + super.render(opts)
  334. }
  335. }
  336. type StartBlockNode = If | For | Func | Return | Try
  337. type LeafNode = Def | Assign | Label | Break | Throw | AnyCode
  338. type ChildNode = StartBlockNode | LeafNode
  339. type EndBlockNodeType =
  340. | typeof If
  341. | typeof Else
  342. | typeof For
  343. | typeof Func
  344. | typeof Return
  345. | typeof Catch
  346. | typeof Finally
  347. type Constants = Record<string, SafeExpr | undefined>
  348. export interface CodeGenOptions {
  349. es5?: boolean
  350. lines?: boolean
  351. ownProperties?: boolean
  352. }
  353. interface CGOptions extends CodeGenOptions {
  354. _n: "\n" | ""
  355. }
  356. export class CodeGen {
  357. readonly _scope: Scope
  358. readonly _extScope: ValueScope
  359. readonly _values: ScopeValueSets = {}
  360. private readonly _nodes: ParentNode[]
  361. private readonly _blockStarts: number[] = []
  362. private readonly _constants: Constants = {}
  363. private readonly opts: CGOptions
  364. constructor(extScope: ValueScope, opts: CodeGenOptions = {}) {
  365. this.opts = {...opts, _n: opts.lines ? "\n" : ""}
  366. this._extScope = extScope
  367. this._scope = new Scope({parent: extScope})
  368. this._nodes = [new Root()]
  369. }
  370. toString(): string {
  371. return this._root.render(this.opts)
  372. }
  373. // returns unique name in the internal scope
  374. name(prefix: string): Name {
  375. return this._scope.name(prefix)
  376. }
  377. // reserves unique name in the external scope
  378. scopeName(prefix: string): ValueScopeName {
  379. return this._extScope.name(prefix)
  380. }
  381. // reserves unique name in the external scope and assigns value to it
  382. scopeValue(prefixOrName: ValueScopeName | string, value: NameValue): Name {
  383. const name = this._extScope.value(prefixOrName, value)
  384. const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set())
  385. vs.add(name)
  386. return name
  387. }
  388. getScopeValue(prefix: string, keyOrRef: unknown): ValueScopeName | undefined {
  389. return this._extScope.getValue(prefix, keyOrRef)
  390. }
  391. // return code that assigns values in the external scope to the names that are used internally
  392. // (same names that were returned by gen.scopeName or gen.scopeValue)
  393. scopeRefs(scopeName: Name): Code {
  394. return this._extScope.scopeRefs(scopeName, this._values)
  395. }
  396. scopeCode(): Code {
  397. return this._extScope.scopeCode(this._values)
  398. }
  399. private _def(
  400. varKind: Name,
  401. nameOrPrefix: Name | string,
  402. rhs?: SafeExpr,
  403. constant?: boolean
  404. ): Name {
  405. const name = this._scope.toName(nameOrPrefix)
  406. if (rhs !== undefined && constant) this._constants[name.str] = rhs
  407. this._leafNode(new Def(varKind, name, rhs))
  408. return name
  409. }
  410. // `const` declaration (`var` in es5 mode)
  411. const(nameOrPrefix: Name | string, rhs: SafeExpr, _constant?: boolean): Name {
  412. return this._def(varKinds.const, nameOrPrefix, rhs, _constant)
  413. }
  414. // `let` declaration with optional assignment (`var` in es5 mode)
  415. let(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name {
  416. return this._def(varKinds.let, nameOrPrefix, rhs, _constant)
  417. }
  418. // `var` declaration with optional assignment
  419. var(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name {
  420. return this._def(varKinds.var, nameOrPrefix, rhs, _constant)
  421. }
  422. // assignment code
  423. assign(lhs: Code, rhs: SafeExpr, sideEffects?: boolean): CodeGen {
  424. return this._leafNode(new Assign(lhs, rhs, sideEffects))
  425. }
  426. // `+=` code
  427. add(lhs: Code, rhs: SafeExpr): CodeGen {
  428. return this._leafNode(new AssignOp(lhs, operators.ADD, rhs))
  429. }
  430. // appends passed SafeExpr to code or executes Block
  431. code(c: Block | SafeExpr): CodeGen {
  432. if (typeof c == "function") c()
  433. else if (c !== nil) this._leafNode(new AnyCode(c))
  434. return this
  435. }
  436. // returns code for object literal for the passed argument list of key-value pairs
  437. object(...keyValues: [Name | string, SafeExpr | string][]): _Code {
  438. const code: CodeItem[] = ["{"]
  439. for (const [key, value] of keyValues) {
  440. if (code.length > 1) code.push(",")
  441. code.push(key)
  442. if (key !== value || this.opts.es5) {
  443. code.push(":")
  444. addCodeArg(code, value)
  445. }
  446. }
  447. code.push("}")
  448. return new _Code(code)
  449. }
  450. // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed)
  451. if(condition: Code | boolean, thenBody?: Block, elseBody?: Block): CodeGen {
  452. this._blockNode(new If(condition))
  453. if (thenBody && elseBody) {
  454. this.code(thenBody).else().code(elseBody).endIf()
  455. } else if (thenBody) {
  456. this.code(thenBody).endIf()
  457. } else if (elseBody) {
  458. throw new Error('CodeGen: "else" body without "then" body')
  459. }
  460. return this
  461. }
  462. // `else if` clause - invalid without `if` or after `else` clauses
  463. elseIf(condition: Code | boolean): CodeGen {
  464. return this._elseNode(new If(condition))
  465. }
  466. // `else` clause - only valid after `if` or `else if` clauses
  467. else(): CodeGen {
  468. return this._elseNode(new Else())
  469. }
  470. // end `if` statement (needed if gen.if was used only with condition)
  471. endIf(): CodeGen {
  472. return this._endBlockNode(If, Else)
  473. }
  474. private _for(node: For, forBody?: Block): CodeGen {
  475. this._blockNode(node)
  476. if (forBody) this.code(forBody).endFor()
  477. return this
  478. }
  479. // a generic `for` clause (or statement if `forBody` is passed)
  480. for(iteration: Code, forBody?: Block): CodeGen {
  481. return this._for(new ForLoop(iteration), forBody)
  482. }
  483. // `for` statement for a range of values
  484. forRange(
  485. nameOrPrefix: Name | string,
  486. from: SafeExpr,
  487. to: SafeExpr,
  488. forBody: (index: Name) => void,
  489. varKind: Code = this.opts.es5 ? varKinds.var : varKinds.let
  490. ): CodeGen {
  491. const name = this._scope.toName(nameOrPrefix)
  492. return this._for(new ForRange(varKind, name, from, to), () => forBody(name))
  493. }
  494. // `for-of` statement (in es5 mode replace with a normal for loop)
  495. forOf(
  496. nameOrPrefix: Name | string,
  497. iterable: Code,
  498. forBody: (item: Name) => void,
  499. varKind: Code = varKinds.const
  500. ): CodeGen {
  501. const name = this._scope.toName(nameOrPrefix)
  502. if (this.opts.es5) {
  503. const arr = iterable instanceof Name ? iterable : this.var("_arr", iterable)
  504. return this.forRange("_i", 0, _`${arr}.length`, (i) => {
  505. this.var(name, _`${arr}[${i}]`)
  506. forBody(name)
  507. })
  508. }
  509. return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name))
  510. }
  511. // `for-in` statement.
  512. // With option `ownProperties` replaced with a `for-of` loop for object keys
  513. forIn(
  514. nameOrPrefix: Name | string,
  515. obj: Code,
  516. forBody: (item: Name) => void,
  517. varKind: Code = this.opts.es5 ? varKinds.var : varKinds.const
  518. ): CodeGen {
  519. if (this.opts.ownProperties) {
  520. return this.forOf(nameOrPrefix, _`Object.keys(${obj})`, forBody)
  521. }
  522. const name = this._scope.toName(nameOrPrefix)
  523. return this._for(new ForIter("in", varKind, name, obj), () => forBody(name))
  524. }
  525. // end `for` loop
  526. endFor(): CodeGen {
  527. return this._endBlockNode(For)
  528. }
  529. // `label` statement
  530. label(label: Name): CodeGen {
  531. return this._leafNode(new Label(label))
  532. }
  533. // `break` statement
  534. break(label?: Code): CodeGen {
  535. return this._leafNode(new Break(label))
  536. }
  537. // `return` statement
  538. return(value: Block | SafeExpr): CodeGen {
  539. const node = new Return()
  540. this._blockNode(node)
  541. this.code(value)
  542. if (node.nodes.length !== 1) throw new Error('CodeGen: "return" should have one node')
  543. return this._endBlockNode(Return)
  544. }
  545. // `try` statement
  546. try(tryBody: Block, catchCode?: (e: Name) => void, finallyCode?: Block): CodeGen {
  547. if (!catchCode && !finallyCode) throw new Error('CodeGen: "try" without "catch" and "finally"')
  548. const node = new Try()
  549. this._blockNode(node)
  550. this.code(tryBody)
  551. if (catchCode) {
  552. const error = this.name("e")
  553. this._currNode = node.catch = new Catch(error)
  554. catchCode(error)
  555. }
  556. if (finallyCode) {
  557. this._currNode = node.finally = new Finally()
  558. this.code(finallyCode)
  559. }
  560. return this._endBlockNode(Catch, Finally)
  561. }
  562. // `throw` statement
  563. throw(error: Code): CodeGen {
  564. return this._leafNode(new Throw(error))
  565. }
  566. // start self-balancing block
  567. block(body?: Block, nodeCount?: number): CodeGen {
  568. this._blockStarts.push(this._nodes.length)
  569. if (body) this.code(body).endBlock(nodeCount)
  570. return this
  571. }
  572. // end the current self-balancing block
  573. endBlock(nodeCount?: number): CodeGen {
  574. const len = this._blockStarts.pop()
  575. if (len === undefined) throw new Error("CodeGen: not in self-balancing block")
  576. const toClose = this._nodes.length - len
  577. if (toClose < 0 || (nodeCount !== undefined && toClose !== nodeCount)) {
  578. throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`)
  579. }
  580. this._nodes.length = len
  581. return this
  582. }
  583. // `function` heading (or definition if funcBody is passed)
  584. func(name: Name, args: Code = nil, async?: boolean, funcBody?: Block): CodeGen {
  585. this._blockNode(new Func(name, args, async))
  586. if (funcBody) this.code(funcBody).endFunc()
  587. return this
  588. }
  589. // end function definition
  590. endFunc(): CodeGen {
  591. return this._endBlockNode(Func)
  592. }
  593. optimize(n = 1): void {
  594. while (n-- > 0) {
  595. this._root.optimizeNodes()
  596. this._root.optimizeNames(this._root.names, this._constants)
  597. }
  598. }
  599. private _leafNode(node: LeafNode): CodeGen {
  600. this._currNode.nodes.push(node)
  601. return this
  602. }
  603. private _blockNode(node: StartBlockNode): void {
  604. this._currNode.nodes.push(node)
  605. this._nodes.push(node)
  606. }
  607. private _endBlockNode(N1: EndBlockNodeType, N2?: EndBlockNodeType): CodeGen {
  608. const n = this._currNode
  609. if (n instanceof N1 || (N2 && n instanceof N2)) {
  610. this._nodes.pop()
  611. return this
  612. }
  613. throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`)
  614. }
  615. private _elseNode(node: If | Else): CodeGen {
  616. const n = this._currNode
  617. if (!(n instanceof If)) {
  618. throw new Error('CodeGen: "else" without "if"')
  619. }
  620. this._currNode = n.else = node
  621. return this
  622. }
  623. private get _root(): Root {
  624. return this._nodes[0] as Root
  625. }
  626. private get _currNode(): ParentNode {
  627. const ns = this._nodes
  628. return ns[ns.length - 1]
  629. }
  630. private set _currNode(node: ParentNode) {
  631. const ns = this._nodes
  632. ns[ns.length - 1] = node
  633. }
  634. // get nodeCount(): number {
  635. // return this._root.count
  636. // }
  637. }
  638. function addNames(names: UsedNames, from: UsedNames): UsedNames {
  639. for (const n in from) names[n] = (names[n] || 0) + (from[n] || 0)
  640. return names
  641. }
  642. function addExprNames(names: UsedNames, from: SafeExpr): UsedNames {
  643. return from instanceof _CodeOrName ? addNames(names, from.names) : names
  644. }
  645. function optimizeExpr<T extends SafeExpr | Code>(expr: T, names: UsedNames, constants: Constants): T
  646. function optimizeExpr(expr: SafeExpr, names: UsedNames, constants: Constants): SafeExpr {
  647. if (expr instanceof Name) return replaceName(expr)
  648. if (!canOptimize(expr)) return expr
  649. return new _Code(
  650. expr._items.reduce((items: CodeItem[], c: SafeExpr | string) => {
  651. if (c instanceof Name) c = replaceName(c)
  652. if (c instanceof _Code) items.push(...c._items)
  653. else items.push(c)
  654. return items
  655. }, [])
  656. )
  657. function replaceName(n: Name): SafeExpr {
  658. const c = constants[n.str]
  659. if (c === undefined || names[n.str] !== 1) return n
  660. delete names[n.str]
  661. return c
  662. }
  663. function canOptimize(e: SafeExpr): e is _Code {
  664. return (
  665. e instanceof _Code &&
  666. e._items.some(
  667. (c) => c instanceof Name && names[c.str] === 1 && constants[c.str] !== undefined
  668. )
  669. )
  670. }
  671. }
  672. function subtractNames(names: UsedNames, from: UsedNames): void {
  673. for (const n in from) names[n] = (names[n] || 0) - (from[n] || 0)
  674. }
  675. export function not<T extends Code | SafeExpr>(x: T): T
  676. export function not(x: Code | SafeExpr): Code | SafeExpr {
  677. return typeof x == "boolean" || typeof x == "number" || x === null ? !x : _`!${par(x)}`
  678. }
  679. const andCode = mappend(operators.AND)
  680. // boolean AND (&&) expression with the passed arguments
  681. export function and(...args: Code[]): Code {
  682. return args.reduce(andCode)
  683. }
  684. const orCode = mappend(operators.OR)
  685. // boolean OR (||) expression with the passed arguments
  686. export function or(...args: Code[]): Code {
  687. return args.reduce(orCode)
  688. }
  689. type MAppend = (x: Code, y: Code) => Code
  690. function mappend(op: Code): MAppend {
  691. return (x, y) => (x === nil ? y : y === nil ? x : _`${par(x)} ${op} ${par(y)}`)
  692. }
  693. function par(x: Code): Code {
  694. return x instanceof Name ? x : _`(${x})`
  695. }