index.ts 23 KB

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