index.ts 22 KB

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