[6a3a178] | 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 |
|
---|
| 5 | export {_, str, strConcat, nil, getProperty, stringify, regexpCode, Name, Code} from "./code"
|
---|
| 6 | export {Scope, ScopeStore, ValueScope, ValueScopeName, ScopeValueSets, varKinds} from "./scope"
|
---|
| 7 |
|
---|
| 8 | // type for expressions that can be safely inserted in code without quotes
|
---|
| 9 | export type SafeExpr = Code | number | boolean | null
|
---|
| 10 |
|
---|
| 11 | // type that is either Code of function that adds code to CodeGen instance using its methods
|
---|
| 12 | export type Block = Code | (() => void)
|
---|
| 13 |
|
---|
| 14 | export const operators = {
|
---|
| 15 | GT: new _Code(">"),
|
---|
| 16 | GTE: new _Code(">="),
|
---|
| 17 | LT: new _Code("<"),
|
---|
| 18 | LTE: new _Code("<="),
|
---|
| 19 | EQ: new _Code("==="),
|
---|
| 20 | NEQ: new _Code("!=="),
|
---|
| 21 | NOT: new _Code("!"),
|
---|
| 22 | OR: new _Code("||"),
|
---|
| 23 | AND: new _Code("&&"),
|
---|
| 24 | ADD: new _Code("+"),
|
---|
| 25 | }
|
---|
| 26 |
|
---|
| 27 | abstract class Node {
|
---|
| 28 | abstract readonly names: UsedNames
|
---|
| 29 |
|
---|
| 30 | optimizeNodes(): this | ChildNode | ChildNode[] | undefined {
|
---|
| 31 | return this
|
---|
| 32 | }
|
---|
| 33 |
|
---|
| 34 | optimizeNames(_names: UsedNames, _constants: Constants): this | undefined {
|
---|
| 35 | return this
|
---|
| 36 | }
|
---|
| 37 |
|
---|
| 38 | // get count(): number {
|
---|
| 39 | // return 1
|
---|
| 40 | // }
|
---|
| 41 | }
|
---|
| 42 |
|
---|
| 43 | class Def extends Node {
|
---|
| 44 | constructor(private readonly varKind: Name, private readonly name: Name, private rhs?: SafeExpr) {
|
---|
| 45 | super()
|
---|
| 46 | }
|
---|
| 47 |
|
---|
| 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
|
---|
| 52 | }
|
---|
| 53 |
|
---|
| 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)
|
---|
| 57 | return this
|
---|
| 58 | }
|
---|
| 59 |
|
---|
| 60 | get names(): UsedNames {
|
---|
| 61 | return this.rhs instanceof _CodeOrName ? this.rhs.names : {}
|
---|
| 62 | }
|
---|
| 63 | }
|
---|
| 64 |
|
---|
| 65 | class Assign extends Node {
|
---|
| 66 | constructor(readonly lhs: Code, public rhs: SafeExpr, private readonly sideEffects?: boolean) {
|
---|
| 67 | super()
|
---|
| 68 | }
|
---|
| 69 |
|
---|
| 70 | render({_n}: CGOptions): string {
|
---|
| 71 | return `${this.lhs} = ${this.rhs};` + _n
|
---|
| 72 | }
|
---|
| 73 |
|
---|
| 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)
|
---|
| 77 | return this
|
---|
| 78 | }
|
---|
| 79 |
|
---|
| 80 | get names(): UsedNames {
|
---|
| 81 | const names = this.lhs instanceof Name ? {} : {...this.lhs.names}
|
---|
| 82 | return addExprNames(names, this.rhs)
|
---|
| 83 | }
|
---|
| 84 | }
|
---|
| 85 |
|
---|
| 86 | class AssignOp extends Assign {
|
---|
| 87 | constructor(lhs: Code, private readonly op: Code, rhs: SafeExpr, sideEffects?: boolean) {
|
---|
| 88 | super(lhs, rhs, sideEffects)
|
---|
| 89 | }
|
---|
| 90 |
|
---|
| 91 | render({_n}: CGOptions): string {
|
---|
| 92 | return `${this.lhs} ${this.op}= ${this.rhs};` + _n
|
---|
| 93 | }
|
---|
| 94 | }
|
---|
| 95 |
|
---|
| 96 | class Label extends Node {
|
---|
| 97 | readonly names: UsedNames = {}
|
---|
| 98 | constructor(readonly label: Name) {
|
---|
| 99 | super()
|
---|
| 100 | }
|
---|
| 101 |
|
---|
| 102 | render({_n}: CGOptions): string {
|
---|
| 103 | return `${this.label}:` + _n
|
---|
| 104 | }
|
---|
| 105 | }
|
---|
| 106 |
|
---|
| 107 | class Break extends Node {
|
---|
| 108 | readonly names: UsedNames = {}
|
---|
| 109 | constructor(readonly label?: Code) {
|
---|
| 110 | super()
|
---|
| 111 | }
|
---|
| 112 |
|
---|
| 113 | render({_n}: CGOptions): string {
|
---|
| 114 | const label = this.label ? ` ${this.label}` : ""
|
---|
| 115 | return `break${label};` + _n
|
---|
| 116 | }
|
---|
| 117 | }
|
---|
| 118 |
|
---|
| 119 | class Throw extends Node {
|
---|
| 120 | constructor(readonly error: Code) {
|
---|
| 121 | super()
|
---|
| 122 | }
|
---|
| 123 |
|
---|
| 124 | render({_n}: CGOptions): string {
|
---|
| 125 | return `throw ${this.error};` + _n
|
---|
| 126 | }
|
---|
| 127 |
|
---|
| 128 | get names(): UsedNames {
|
---|
| 129 | return this.error.names
|
---|
| 130 | }
|
---|
| 131 | }
|
---|
| 132 |
|
---|
| 133 | class AnyCode extends Node {
|
---|
| 134 | constructor(private code: SafeExpr) {
|
---|
| 135 | super()
|
---|
| 136 | }
|
---|
| 137 |
|
---|
| 138 | render({_n}: CGOptions): string {
|
---|
| 139 | return `${this.code};` + _n
|
---|
| 140 | }
|
---|
| 141 |
|
---|
| 142 | optimizeNodes(): this | undefined {
|
---|
| 143 | return `${this.code}` ? this : undefined
|
---|
| 144 | }
|
---|
| 145 |
|
---|
| 146 | optimizeNames(names: UsedNames, constants: Constants): this {
|
---|
| 147 | this.code = optimizeExpr(this.code, names, constants)
|
---|
| 148 | return this
|
---|
| 149 | }
|
---|
| 150 |
|
---|
| 151 | get names(): UsedNames {
|
---|
| 152 | return this.code instanceof _CodeOrName ? this.code.names : {}
|
---|
| 153 | }
|
---|
| 154 | }
|
---|
| 155 |
|
---|
| 156 | abstract class ParentNode extends Node {
|
---|
| 157 | constructor(readonly nodes: ChildNode[] = []) {
|
---|
| 158 | super()
|
---|
| 159 | }
|
---|
| 160 |
|
---|
| 161 | render(opts: CGOptions): string {
|
---|
| 162 | return this.nodes.reduce((code, n) => code + n.render(opts), "")
|
---|
| 163 | }
|
---|
| 164 |
|
---|
| 165 | optimizeNodes(): this | ChildNode | ChildNode[] | undefined {
|
---|
| 166 | const {nodes} = this
|
---|
| 167 | let i = nodes.length
|
---|
| 168 | while (i--) {
|
---|
| 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)
|
---|
| 173 | }
|
---|
| 174 | return nodes.length > 0 ? this : undefined
|
---|
| 175 | }
|
---|
| 176 |
|
---|
| 177 | optimizeNames(names: UsedNames, constants: Constants): this | undefined {
|
---|
| 178 | const {nodes} = this
|
---|
| 179 | let i = nodes.length
|
---|
| 180 | while (i--) {
|
---|
| 181 | // iterating backwards improves 1-pass optimization
|
---|
| 182 | const n = nodes[i]
|
---|
| 183 | if (n.optimizeNames(names, constants)) continue
|
---|
| 184 | subtractNames(names, n.names)
|
---|
| 185 | nodes.splice(i, 1)
|
---|
| 186 | }
|
---|
| 187 | return nodes.length > 0 ? this : undefined
|
---|
| 188 | }
|
---|
| 189 |
|
---|
| 190 | get names(): UsedNames {
|
---|
| 191 | return this.nodes.reduce((names: UsedNames, n) => addNames(names, n.names), {})
|
---|
| 192 | }
|
---|
| 193 |
|
---|
| 194 | // get count(): number {
|
---|
| 195 | // return this.nodes.reduce((c, n) => c + n.count, 1)
|
---|
| 196 | // }
|
---|
| 197 | }
|
---|
| 198 |
|
---|
| 199 | abstract class BlockNode extends ParentNode {
|
---|
| 200 | render(opts: CGOptions): string {
|
---|
| 201 | return "{" + opts._n + super.render(opts) + "}" + opts._n
|
---|
| 202 | }
|
---|
| 203 | }
|
---|
| 204 |
|
---|
| 205 | class Root extends ParentNode {}
|
---|
| 206 |
|
---|
| 207 | class Else extends BlockNode {
|
---|
| 208 | static readonly kind = "else"
|
---|
| 209 | }
|
---|
| 210 |
|
---|
| 211 | class If extends BlockNode {
|
---|
| 212 | static readonly kind = "if"
|
---|
| 213 | else?: If | Else
|
---|
| 214 | constructor(private condition: Code | boolean, nodes?: ChildNode[]) {
|
---|
| 215 | super(nodes)
|
---|
| 216 | }
|
---|
| 217 |
|
---|
| 218 | render(opts: CGOptions): string {
|
---|
| 219 | let code = `if(${this.condition})` + super.render(opts)
|
---|
| 220 | if (this.else) code += "else " + this.else.render(opts)
|
---|
| 221 | return code
|
---|
| 222 | }
|
---|
| 223 |
|
---|
| 224 | optimizeNodes(): If | ChildNode[] | undefined {
|
---|
| 225 | super.optimizeNodes()
|
---|
| 226 | const cond = this.condition
|
---|
| 227 | if (cond === true) return this.nodes // else is ignored here
|
---|
| 228 | let e = this.else
|
---|
| 229 | if (e) {
|
---|
| 230 | const ns = e.optimizeNodes()
|
---|
| 231 | e = this.else = Array.isArray(ns) ? new Else(ns) : (ns as Else | undefined)
|
---|
| 232 | }
|
---|
| 233 | if (e) {
|
---|
| 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)
|
---|
| 237 | }
|
---|
| 238 | if (cond === false || !this.nodes.length) return undefined
|
---|
| 239 | return this
|
---|
| 240 | }
|
---|
| 241 |
|
---|
| 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)
|
---|
| 246 | return this
|
---|
| 247 | }
|
---|
| 248 |
|
---|
| 249 | get names(): UsedNames {
|
---|
| 250 | const names = super.names
|
---|
| 251 | addExprNames(names, this.condition)
|
---|
| 252 | if (this.else) addNames(names, this.else.names)
|
---|
| 253 | return names
|
---|
| 254 | }
|
---|
| 255 |
|
---|
| 256 | // get count(): number {
|
---|
| 257 | // return super.count + (this.else?.count || 0)
|
---|
| 258 | // }
|
---|
| 259 | }
|
---|
| 260 |
|
---|
| 261 | abstract class For extends BlockNode {
|
---|
| 262 | static readonly kind = "for"
|
---|
| 263 | }
|
---|
| 264 |
|
---|
| 265 | class ForLoop extends For {
|
---|
| 266 | constructor(private iteration: Code) {
|
---|
| 267 | super()
|
---|
| 268 | }
|
---|
| 269 |
|
---|
| 270 | render(opts: CGOptions): string {
|
---|
| 271 | return `for(${this.iteration})` + super.render(opts)
|
---|
| 272 | }
|
---|
| 273 |
|
---|
| 274 | optimizeNames(names: UsedNames, constants: Constants): this | undefined {
|
---|
| 275 | if (!super.optimizeNames(names, constants)) return
|
---|
| 276 | this.iteration = optimizeExpr(this.iteration, names, constants)
|
---|
| 277 | return this
|
---|
| 278 | }
|
---|
| 279 |
|
---|
| 280 | get names(): UsedNames {
|
---|
| 281 | return addNames(super.names, this.iteration.names)
|
---|
| 282 | }
|
---|
| 283 | }
|
---|
| 284 |
|
---|
| 285 | class ForRange extends For {
|
---|
| 286 | constructor(
|
---|
| 287 | private readonly varKind: Name,
|
---|
| 288 | private readonly name: Name,
|
---|
| 289 | private readonly from: SafeExpr,
|
---|
| 290 | private readonly to: SafeExpr
|
---|
| 291 | ) {
|
---|
| 292 | super()
|
---|
| 293 | }
|
---|
| 294 |
|
---|
| 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)
|
---|
| 299 | }
|
---|
| 300 |
|
---|
| 301 | get names(): UsedNames {
|
---|
| 302 | const names = addExprNames(super.names, this.from)
|
---|
| 303 | return addExprNames(names, this.to)
|
---|
| 304 | }
|
---|
| 305 | }
|
---|
| 306 |
|
---|
| 307 | class ForIter extends For {
|
---|
| 308 | constructor(
|
---|
| 309 | private readonly loop: "of" | "in",
|
---|
| 310 | private readonly varKind: Name,
|
---|
| 311 | private readonly name: Name,
|
---|
| 312 | private iterable: Code
|
---|
| 313 | ) {
|
---|
| 314 | super()
|
---|
| 315 | }
|
---|
| 316 |
|
---|
| 317 | render(opts: CGOptions): string {
|
---|
| 318 | return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts)
|
---|
| 319 | }
|
---|
| 320 |
|
---|
| 321 | optimizeNames(names: UsedNames, constants: Constants): this | undefined {
|
---|
| 322 | if (!super.optimizeNames(names, constants)) return
|
---|
| 323 | this.iterable = optimizeExpr(this.iterable, names, constants)
|
---|
| 324 | return this
|
---|
| 325 | }
|
---|
| 326 |
|
---|
| 327 | get names(): UsedNames {
|
---|
| 328 | return addNames(super.names, this.iterable.names)
|
---|
| 329 | }
|
---|
| 330 | }
|
---|
| 331 |
|
---|
| 332 | class Func extends BlockNode {
|
---|
| 333 | static readonly kind = "func"
|
---|
| 334 | constructor(public name: Name, public args: Code, public async?: boolean) {
|
---|
| 335 | super()
|
---|
| 336 | }
|
---|
| 337 |
|
---|
| 338 | render(opts: CGOptions): string {
|
---|
| 339 | const _async = this.async ? "async " : ""
|
---|
| 340 | return `${_async}function ${this.name}(${this.args})` + super.render(opts)
|
---|
| 341 | }
|
---|
| 342 | }
|
---|
| 343 |
|
---|
| 344 | class Return extends ParentNode {
|
---|
| 345 | static readonly kind = "return"
|
---|
| 346 |
|
---|
| 347 | render(opts: CGOptions): string {
|
---|
| 348 | return "return " + super.render(opts)
|
---|
| 349 | }
|
---|
| 350 | }
|
---|
| 351 |
|
---|
| 352 | class Try extends BlockNode {
|
---|
| 353 | catch?: Catch
|
---|
| 354 | finally?: Finally
|
---|
| 355 |
|
---|
| 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)
|
---|
| 360 | return code
|
---|
| 361 | }
|
---|
| 362 |
|
---|
| 363 | optimizeNodes(): this {
|
---|
| 364 | super.optimizeNodes()
|
---|
| 365 | this.catch?.optimizeNodes() as Catch | undefined
|
---|
| 366 | this.finally?.optimizeNodes() as Finally | undefined
|
---|
| 367 | return this
|
---|
| 368 | }
|
---|
| 369 |
|
---|
| 370 | optimizeNames(names: UsedNames, constants: Constants): this {
|
---|
| 371 | super.optimizeNames(names, constants)
|
---|
| 372 | this.catch?.optimizeNames(names, constants)
|
---|
| 373 | this.finally?.optimizeNames(names, constants)
|
---|
| 374 | return this
|
---|
| 375 | }
|
---|
| 376 |
|
---|
| 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)
|
---|
| 381 | return names
|
---|
| 382 | }
|
---|
| 383 |
|
---|
| 384 | // get count(): number {
|
---|
| 385 | // return super.count + (this.catch?.count || 0) + (this.finally?.count || 0)
|
---|
| 386 | // }
|
---|
| 387 | }
|
---|
| 388 |
|
---|
| 389 | class Catch extends BlockNode {
|
---|
| 390 | static readonly kind = "catch"
|
---|
| 391 | constructor(readonly error: Name) {
|
---|
| 392 | super()
|
---|
| 393 | }
|
---|
| 394 |
|
---|
| 395 | render(opts: CGOptions): string {
|
---|
| 396 | return `catch(${this.error})` + super.render(opts)
|
---|
| 397 | }
|
---|
| 398 | }
|
---|
| 399 |
|
---|
| 400 | class Finally extends BlockNode {
|
---|
| 401 | static readonly kind = "finally"
|
---|
| 402 | render(opts: CGOptions): string {
|
---|
| 403 | return "finally" + super.render(opts)
|
---|
| 404 | }
|
---|
| 405 | }
|
---|
| 406 |
|
---|
| 407 | type StartBlockNode = If | For | Func | Return | Try
|
---|
| 408 |
|
---|
| 409 | type LeafNode = Def | Assign | Label | Break | Throw | AnyCode
|
---|
| 410 |
|
---|
| 411 | type ChildNode = StartBlockNode | LeafNode
|
---|
| 412 |
|
---|
| 413 | type EndBlockNodeType =
|
---|
| 414 | | typeof If
|
---|
| 415 | | typeof Else
|
---|
| 416 | | typeof For
|
---|
| 417 | | typeof Func
|
---|
| 418 | | typeof Return
|
---|
| 419 | | typeof Catch
|
---|
| 420 | | typeof Finally
|
---|
| 421 |
|
---|
| 422 | type Constants = Record<string, SafeExpr | undefined>
|
---|
| 423 |
|
---|
| 424 | export interface CodeGenOptions {
|
---|
| 425 | es5?: boolean
|
---|
| 426 | lines?: boolean
|
---|
| 427 | ownProperties?: boolean
|
---|
| 428 | }
|
---|
| 429 |
|
---|
| 430 | interface CGOptions extends CodeGenOptions {
|
---|
| 431 | _n: "\n" | ""
|
---|
| 432 | }
|
---|
| 433 |
|
---|
| 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
|
---|
| 442 |
|
---|
| 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()]
|
---|
| 448 | }
|
---|
| 449 |
|
---|
| 450 | toString(): string {
|
---|
| 451 | return this._root.render(this.opts)
|
---|
| 452 | }
|
---|
| 453 |
|
---|
| 454 | // returns unique name in the internal scope
|
---|
| 455 | name(prefix: string): Name {
|
---|
| 456 | return this._scope.name(prefix)
|
---|
| 457 | }
|
---|
| 458 |
|
---|
| 459 | // reserves unique name in the external scope
|
---|
| 460 | scopeName(prefix: string): ValueScopeName {
|
---|
| 461 | return this._extScope.name(prefix)
|
---|
| 462 | }
|
---|
| 463 |
|
---|
| 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())
|
---|
| 468 | vs.add(name)
|
---|
| 469 | return name
|
---|
| 470 | }
|
---|
| 471 |
|
---|
| 472 | getScopeValue(prefix: string, keyOrRef: unknown): ValueScopeName | undefined {
|
---|
| 473 | return this._extScope.getValue(prefix, keyOrRef)
|
---|
| 474 | }
|
---|
| 475 |
|
---|
| 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)
|
---|
| 480 | }
|
---|
| 481 |
|
---|
| 482 | scopeCode(): Code {
|
---|
| 483 | return this._extScope.scopeCode(this._values)
|
---|
| 484 | }
|
---|
| 485 |
|
---|
| 486 | private _def(
|
---|
| 487 | varKind: Name,
|
---|
| 488 | nameOrPrefix: Name | string,
|
---|
| 489 | rhs?: SafeExpr,
|
---|
| 490 | constant?: boolean
|
---|
| 491 | ): Name {
|
---|
| 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))
|
---|
| 495 | return name
|
---|
| 496 | }
|
---|
| 497 |
|
---|
| 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)
|
---|
| 501 | }
|
---|
| 502 |
|
---|
| 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)
|
---|
| 506 | }
|
---|
| 507 |
|
---|
| 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)
|
---|
| 511 | }
|
---|
| 512 |
|
---|
| 513 | // assignment code
|
---|
| 514 | assign(lhs: Code, rhs: SafeExpr, sideEffects?: boolean): CodeGen {
|
---|
| 515 | return this._leafNode(new Assign(lhs, rhs, sideEffects))
|
---|
| 516 | }
|
---|
| 517 |
|
---|
| 518 | // `+=` code
|
---|
| 519 | add(lhs: Code, rhs: SafeExpr): CodeGen {
|
---|
| 520 | return this._leafNode(new AssignOp(lhs, operators.ADD, rhs))
|
---|
| 521 | }
|
---|
| 522 |
|
---|
| 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))
|
---|
| 527 | return this
|
---|
| 528 | }
|
---|
| 529 |
|
---|
| 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(",")
|
---|
| 535 | code.push(key)
|
---|
| 536 | if (key !== value || this.opts.es5) {
|
---|
| 537 | code.push(":")
|
---|
| 538 | addCodeArg(code, value)
|
---|
| 539 | }
|
---|
| 540 | }
|
---|
| 541 | code.push("}")
|
---|
| 542 | return new _Code(code)
|
---|
| 543 | }
|
---|
| 544 |
|
---|
| 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))
|
---|
| 548 |
|
---|
| 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')
|
---|
| 555 | }
|
---|
| 556 | return this
|
---|
| 557 | }
|
---|
| 558 |
|
---|
| 559 | // `else if` clause - invalid without `if` or after `else` clauses
|
---|
| 560 | elseIf(condition: Code | boolean): CodeGen {
|
---|
| 561 | return this._elseNode(new If(condition))
|
---|
| 562 | }
|
---|
| 563 |
|
---|
| 564 | // `else` clause - only valid after `if` or `else if` clauses
|
---|
| 565 | else(): CodeGen {
|
---|
| 566 | return this._elseNode(new Else())
|
---|
| 567 | }
|
---|
| 568 |
|
---|
| 569 | // end `if` statement (needed if gen.if was used only with condition)
|
---|
| 570 | endIf(): CodeGen {
|
---|
| 571 | return this._endBlockNode(If, Else)
|
---|
| 572 | }
|
---|
| 573 |
|
---|
| 574 | private _for(node: For, forBody?: Block): CodeGen {
|
---|
| 575 | this._blockNode(node)
|
---|
| 576 | if (forBody) this.code(forBody).endFor()
|
---|
| 577 | return this
|
---|
| 578 | }
|
---|
| 579 |
|
---|
| 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)
|
---|
| 583 | }
|
---|
| 584 |
|
---|
| 585 | // `for` statement for a range of values
|
---|
| 586 | forRange(
|
---|
| 587 | nameOrPrefix: Name | string,
|
---|
| 588 | from: SafeExpr,
|
---|
| 589 | to: SafeExpr,
|
---|
| 590 | forBody: (index: Name) => void,
|
---|
| 591 | varKind: Code = this.opts.es5 ? varKinds.var : varKinds.let
|
---|
| 592 | ): CodeGen {
|
---|
| 593 | const name = this._scope.toName(nameOrPrefix)
|
---|
| 594 | return this._for(new ForRange(varKind, name, from, to), () => forBody(name))
|
---|
| 595 | }
|
---|
| 596 |
|
---|
| 597 | // `for-of` statement (in es5 mode replace with a normal for loop)
|
---|
| 598 | forOf(
|
---|
| 599 | nameOrPrefix: Name | string,
|
---|
| 600 | iterable: Code,
|
---|
| 601 | forBody: (item: Name) => void,
|
---|
| 602 | varKind: Code = varKinds.const
|
---|
| 603 | ): CodeGen {
|
---|
| 604 | const name = this._scope.toName(nameOrPrefix)
|
---|
| 605 | if (this.opts.es5) {
|
---|
| 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}]`)
|
---|
| 609 | forBody(name)
|
---|
| 610 | })
|
---|
| 611 | }
|
---|
| 612 | return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name))
|
---|
| 613 | }
|
---|
| 614 |
|
---|
| 615 | // `for-in` statement.
|
---|
| 616 | // With option `ownProperties` replaced with a `for-of` loop for object keys
|
---|
| 617 | forIn(
|
---|
| 618 | nameOrPrefix: Name | string,
|
---|
| 619 | obj: Code,
|
---|
| 620 | forBody: (item: Name) => void,
|
---|
| 621 | varKind: Code = this.opts.es5 ? varKinds.var : varKinds.const
|
---|
| 622 | ): CodeGen {
|
---|
| 623 | if (this.opts.ownProperties) {
|
---|
| 624 | return this.forOf(nameOrPrefix, _`Object.keys(${obj})`, forBody)
|
---|
| 625 | }
|
---|
| 626 | const name = this._scope.toName(nameOrPrefix)
|
---|
| 627 | return this._for(new ForIter("in", varKind, name, obj), () => forBody(name))
|
---|
| 628 | }
|
---|
| 629 |
|
---|
| 630 | // end `for` loop
|
---|
| 631 | endFor(): CodeGen {
|
---|
| 632 | return this._endBlockNode(For)
|
---|
| 633 | }
|
---|
| 634 |
|
---|
| 635 | // `label` statement
|
---|
| 636 | label(label: Name): CodeGen {
|
---|
| 637 | return this._leafNode(new Label(label))
|
---|
| 638 | }
|
---|
| 639 |
|
---|
| 640 | // `break` statement
|
---|
| 641 | break(label?: Code): CodeGen {
|
---|
| 642 | return this._leafNode(new Break(label))
|
---|
| 643 | }
|
---|
| 644 |
|
---|
| 645 | // `return` statement
|
---|
| 646 | return(value: Block | SafeExpr): CodeGen {
|
---|
| 647 | const node = new Return()
|
---|
| 648 | this._blockNode(node)
|
---|
| 649 | this.code(value)
|
---|
| 650 | if (node.nodes.length !== 1) throw new Error('CodeGen: "return" should have one node')
|
---|
| 651 | return this._endBlockNode(Return)
|
---|
| 652 | }
|
---|
| 653 |
|
---|
| 654 | // `try` statement
|
---|
| 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)
|
---|
| 659 | this.code(tryBody)
|
---|
| 660 | if (catchCode) {
|
---|
| 661 | const error = this.name("e")
|
---|
| 662 | this._currNode = node.catch = new Catch(error)
|
---|
| 663 | catchCode(error)
|
---|
| 664 | }
|
---|
| 665 | if (finallyCode) {
|
---|
| 666 | this._currNode = node.finally = new Finally()
|
---|
| 667 | this.code(finallyCode)
|
---|
| 668 | }
|
---|
| 669 | return this._endBlockNode(Catch, Finally)
|
---|
| 670 | }
|
---|
| 671 |
|
---|
| 672 | // `throw` statement
|
---|
| 673 | throw(error: Code): CodeGen {
|
---|
| 674 | return this._leafNode(new Throw(error))
|
---|
| 675 | }
|
---|
| 676 |
|
---|
| 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)
|
---|
| 681 | return this
|
---|
| 682 | }
|
---|
| 683 |
|
---|
| 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`)
|
---|
| 691 | }
|
---|
| 692 | this._nodes.length = len
|
---|
| 693 | return this
|
---|
| 694 | }
|
---|
| 695 |
|
---|
| 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()
|
---|
| 700 | return this
|
---|
| 701 | }
|
---|
| 702 |
|
---|
| 703 | // end function definition
|
---|
| 704 | endFunc(): CodeGen {
|
---|
| 705 | return this._endBlockNode(Func)
|
---|
| 706 | }
|
---|
| 707 |
|
---|
| 708 | optimize(n = 1): void {
|
---|
| 709 | while (n-- > 0) {
|
---|
| 710 | this._root.optimizeNodes()
|
---|
| 711 | this._root.optimizeNames(this._root.names, this._constants)
|
---|
| 712 | }
|
---|
| 713 | }
|
---|
| 714 |
|
---|
| 715 | private _leafNode(node: LeafNode): CodeGen {
|
---|
| 716 | this._currNode.nodes.push(node)
|
---|
| 717 | return this
|
---|
| 718 | }
|
---|
| 719 |
|
---|
| 720 | private _blockNode(node: StartBlockNode): void {
|
---|
| 721 | this._currNode.nodes.push(node)
|
---|
| 722 | this._nodes.push(node)
|
---|
| 723 | }
|
---|
| 724 |
|
---|
| 725 | private _endBlockNode(N1: EndBlockNodeType, N2?: EndBlockNodeType): CodeGen {
|
---|
| 726 | const n = this._currNode
|
---|
| 727 | if (n instanceof N1 || (N2 && n instanceof N2)) {
|
---|
| 728 | this._nodes.pop()
|
---|
| 729 | return this
|
---|
| 730 | }
|
---|
| 731 | throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`)
|
---|
| 732 | }
|
---|
| 733 |
|
---|
| 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"')
|
---|
| 738 | }
|
---|
| 739 | this._currNode = n.else = node
|
---|
| 740 | return this
|
---|
| 741 | }
|
---|
| 742 |
|
---|
| 743 | private get _root(): Root {
|
---|
| 744 | return this._nodes[0] as Root
|
---|
| 745 | }
|
---|
| 746 |
|
---|
| 747 | private get _currNode(): ParentNode {
|
---|
| 748 | const ns = this._nodes
|
---|
| 749 | return ns[ns.length - 1]
|
---|
| 750 | }
|
---|
| 751 |
|
---|
| 752 | private set _currNode(node: ParentNode) {
|
---|
| 753 | const ns = this._nodes
|
---|
| 754 | ns[ns.length - 1] = node
|
---|
| 755 | }
|
---|
| 756 |
|
---|
| 757 | // get nodeCount(): number {
|
---|
| 758 | // return this._root.count
|
---|
| 759 | // }
|
---|
| 760 | }
|
---|
| 761 |
|
---|
| 762 | function addNames(names: UsedNames, from: UsedNames): UsedNames {
|
---|
| 763 | for (const n in from) names[n] = (names[n] || 0) + (from[n] || 0)
|
---|
| 764 | return names
|
---|
| 765 | }
|
---|
| 766 |
|
---|
| 767 | function addExprNames(names: UsedNames, from: SafeExpr): UsedNames {
|
---|
| 768 | return from instanceof _CodeOrName ? addNames(names, from.names) : names
|
---|
| 769 | }
|
---|
| 770 |
|
---|
| 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
|
---|
| 775 | return new _Code(
|
---|
| 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)
|
---|
| 779 | else items.push(c)
|
---|
| 780 | return items
|
---|
| 781 | }, [])
|
---|
| 782 | )
|
---|
| 783 |
|
---|
| 784 | function replaceName(n: Name): SafeExpr {
|
---|
| 785 | const c = constants[n.str]
|
---|
| 786 | if (c === undefined || names[n.str] !== 1) return n
|
---|
| 787 | delete names[n.str]
|
---|
| 788 | return c
|
---|
| 789 | }
|
---|
| 790 |
|
---|
| 791 | function canOptimize(e: SafeExpr): e is _Code {
|
---|
| 792 | return (
|
---|
| 793 | e instanceof _Code &&
|
---|
| 794 | e._items.some(
|
---|
| 795 | (c) => c instanceof Name && names[c.str] === 1 && constants[c.str] !== undefined
|
---|
| 796 | )
|
---|
| 797 | )
|
---|
| 798 | }
|
---|
| 799 | }
|
---|
| 800 |
|
---|
| 801 | function subtractNames(names: UsedNames, from: UsedNames): void {
|
---|
| 802 | for (const n in from) names[n] = (names[n] || 0) - (from[n] || 0)
|
---|
| 803 | }
|
---|
| 804 |
|
---|
| 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)}`
|
---|
| 808 | }
|
---|
| 809 |
|
---|
| 810 | const andCode = mappend(operators.AND)
|
---|
| 811 |
|
---|
| 812 | // boolean AND (&&) expression with the passed arguments
|
---|
| 813 | export function and(...args: Code[]): Code {
|
---|
| 814 | return args.reduce(andCode)
|
---|
| 815 | }
|
---|
| 816 |
|
---|
| 817 | const orCode = mappend(operators.OR)
|
---|
| 818 |
|
---|
| 819 | // boolean OR (||) expression with the passed arguments
|
---|
| 820 | export function or(...args: Code[]): Code {
|
---|
| 821 | return args.reduce(orCode)
|
---|
| 822 | }
|
---|
| 823 |
|
---|
| 824 | type MAppend = (x: Code, y: Code) => Code
|
---|
| 825 |
|
---|
| 826 | function mappend(op: Code): MAppend {
|
---|
| 827 | return (x, y) => (x === nil ? y : y === nil ? x : _`${par(x)} ${op} ${par(y)}`)
|
---|
| 828 | }
|
---|
| 829 |
|
---|
| 830 | function par(x: Code): Code {
|
---|
| 831 | return x instanceof Name ? x : _`(${x})`
|
---|
| 832 | }
|
---|