2 Object.defineProperty(exports, "__esModule", { value: true });
3 exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0;
4 const code_1 = require("./code");
5 const scope_1 = require("./scope");
6 var code_2 = require("./code");
7 Object.defineProperty(exports, "_", { enumerable: true, get: function () { return code_2._; } });
8 Object.defineProperty(exports, "str", { enumerable: true, get: function () { return code_2.str; } });
9 Object.defineProperty(exports, "strConcat", { enumerable: true, get: function () { return code_2.strConcat; } });
10 Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return code_2.nil; } });
11 Object.defineProperty(exports, "getProperty", { enumerable: true, get: function () { return code_2.getProperty; } });
12 Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return code_2.stringify; } });
13 Object.defineProperty(exports, "regexpCode", { enumerable: true, get: function () { return code_2.regexpCode; } });
14 Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return code_2.Name; } });
15 var scope_2 = require("./scope");
16 Object.defineProperty(exports, "Scope", { enumerable: true, get: function () { return scope_2.Scope; } });
17 Object.defineProperty(exports, "ValueScope", { enumerable: true, get: function () { return scope_2.ValueScope; } });
18 Object.defineProperty(exports, "ValueScopeName", { enumerable: true, get: function () { return scope_2.ValueScopeName; } });
19 Object.defineProperty(exports, "varKinds", { enumerable: true, get: function () { return scope_2.varKinds; } });
21 GT: new code_1._Code(">"),
22 GTE: new code_1._Code(">="),
23 LT: new code_1._Code("<"),
24 LTE: new code_1._Code("<="),
25 EQ: new code_1._Code("==="),
26 NEQ: new code_1._Code("!=="),
27 NOT: new code_1._Code("!"),
28 OR: new code_1._Code("||"),
29 AND: new code_1._Code("&&"),
30 ADD: new code_1._Code("+"),
36 optimizeNames(_names, _constants) {
40 class Def extends Node {
41 constructor(varKind, name, rhs) {
43 this.varKind = varKind;
48 const varKind = es5 ? scope_1.varKinds.var : this.varKind;
49 const rhs = this.rhs === undefined ? "" : ` = ${this.rhs}`;
50 return `${varKind} ${this.name}${rhs};` + _n;
52 optimizeNames(names, constants) {
53 if (!names[this.name.str])
56 this.rhs = optimizeExpr(this.rhs, names, constants);
60 return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {};
63 class Assign extends Node {
64 constructor(lhs, rhs, sideEffects) {
68 this.sideEffects = sideEffects;
71 return `${this.lhs} = ${this.rhs};` + _n;
73 optimizeNames(names, constants) {
74 if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects)
76 this.rhs = optimizeExpr(this.rhs, names, constants);
80 const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names };
81 return addExprNames(names, this.rhs);
84 class AssignOp extends Assign {
85 constructor(lhs, op, rhs, sideEffects) {
86 super(lhs, rhs, sideEffects);
90 return `${this.lhs} ${this.op}= ${this.rhs};` + _n;
93 class Label extends Node {
100 return `${this.label}:` + _n;
103 class Break extends Node {
110 const label = this.label ? ` ${this.label}` : "";
111 return `break${label};` + _n;
114 class Throw extends Node {
120 return `throw ${this.error};` + _n;
123 return this.error.names;
126 class AnyCode extends Node {
132 return `${this.code};` + _n;
135 return `${this.code}` ? this : undefined;
137 optimizeNames(names, constants) {
138 this.code = optimizeExpr(this.code, names, constants);
142 return this.code instanceof code_1._CodeOrName ? this.code.names : {};
145 class ParentNode extends Node {
146 constructor(nodes = []) {
151 return this.nodes.reduce((code, n) => code + n.render(opts), "");
154 const { nodes } = this;
155 let i = nodes.length;
157 const n = nodes[i].optimizeNodes();
158 if (Array.isArray(n))
159 nodes.splice(i, 1, ...n);
165 return nodes.length > 0 ? this : undefined;
167 optimizeNames(names, constants) {
168 const { nodes } = this;
169 let i = nodes.length;
171 // iterating backwards improves 1-pass optimization
173 if (n.optimizeNames(names, constants))
175 subtractNames(names, n.names);
178 return nodes.length > 0 ? this : undefined;
181 return this.nodes.reduce((names, n) => addNames(names, n.names), {});
184 class BlockNode extends ParentNode {
186 return "{" + opts._n + super.render(opts) + "}" + opts._n;
189 class Root extends ParentNode {
191 class Else extends BlockNode {
194 class If extends BlockNode {
195 constructor(condition, nodes) {
197 this.condition = condition;
200 let code = `if(${this.condition})` + super.render(opts);
202 code += "else " + this.else.render(opts);
206 super.optimizeNodes();
207 const cond = this.condition;
209 return this.nodes; // else is ignored here
212 const ns = e.optimizeNodes();
213 e = this.else = Array.isArray(ns) ? new Else(ns) : ns;
217 return e instanceof If ? e : e.nodes;
218 if (this.nodes.length)
220 return new If(not(cond), e instanceof If ? [e] : e.nodes);
222 if (cond === false || !this.nodes.length)
226 optimizeNames(names, constants) {
228 this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants);
229 if (!(super.optimizeNames(names, constants) || this.else))
231 this.condition = optimizeExpr(this.condition, names, constants);
235 const names = super.names;
236 addExprNames(names, this.condition);
238 addNames(names, this.else.names);
243 class For extends BlockNode {
246 class ForLoop extends For {
247 constructor(iteration) {
249 this.iteration = iteration;
252 return `for(${this.iteration})` + super.render(opts);
254 optimizeNames(names, constants) {
255 if (!super.optimizeNames(names, constants))
257 this.iteration = optimizeExpr(this.iteration, names, constants);
261 return addNames(super.names, this.iteration.names);
264 class ForRange extends For {
265 constructor(varKind, name, from, to) {
267 this.varKind = varKind;
273 const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind;
274 const { name, from, to } = this;
275 return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts);
278 const names = addExprNames(super.names, this.from);
279 return addExprNames(names, this.to);
282 class ForIter extends For {
283 constructor(loop, varKind, name, iterable) {
286 this.varKind = varKind;
288 this.iterable = iterable;
291 return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);
293 optimizeNames(names, constants) {
294 if (!super.optimizeNames(names, constants))
296 this.iterable = optimizeExpr(this.iterable, names, constants);
300 return addNames(super.names, this.iterable.names);
303 class Func extends BlockNode {
304 constructor(name, args, async) {
311 const _async = this.async ? "async " : "";
312 return `${_async}function ${this.name}(${this.args})` + super.render(opts);
316 class Return extends ParentNode {
318 return "return " + super.render(opts);
321 Return.kind = "return";
322 class Try extends BlockNode {
324 let code = "try" + super.render(opts);
326 code += this.catch.render(opts);
328 code += this.finally.render(opts);
333 super.optimizeNodes();
334 (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNodes();
335 (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes();
338 optimizeNames(names, constants) {
340 super.optimizeNames(names, constants);
341 (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants);
342 (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants);
346 const names = super.names;
348 addNames(names, this.catch.names);
350 addNames(names, this.finally.names);
354 class Catch extends BlockNode {
360 return `catch(${this.error})` + super.render(opts);
363 Catch.kind = "catch";
364 class Finally extends BlockNode {
366 return "finally" + super.render(opts);
369 Finally.kind = "finally";
371 constructor(extScope, opts = {}) {
373 this._blockStarts = [];
374 this._constants = {};
375 this.opts = { ...opts, _n: opts.lines ? "\n" : "" };
376 this._extScope = extScope;
377 this._scope = new scope_1.Scope({ parent: extScope });
378 this._nodes = [new Root()];
381 return this._root.render(this.opts);
383 // returns unique name in the internal scope
385 return this._scope.name(prefix);
387 // reserves unique name in the external scope
389 return this._extScope.name(prefix);
391 // reserves unique name in the external scope and assigns value to it
392 scopeValue(prefixOrName, value) {
393 const name = this._extScope.value(prefixOrName, value);
394 const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set());
398 getScopeValue(prefix, keyOrRef) {
399 return this._extScope.getValue(prefix, keyOrRef);
401 // return code that assigns values in the external scope to the names that are used internally
402 // (same names that were returned by gen.scopeName or gen.scopeValue)
403 scopeRefs(scopeName) {
404 return this._extScope.scopeRefs(scopeName, this._values);
407 return this._extScope.scopeCode(this._values);
409 _def(varKind, nameOrPrefix, rhs, constant) {
410 const name = this._scope.toName(nameOrPrefix);
411 if (rhs !== undefined && constant)
412 this._constants[name.str] = rhs;
413 this._leafNode(new Def(varKind, name, rhs));
416 // `const` declaration (`var` in es5 mode)
417 const(nameOrPrefix, rhs, _constant) {
418 return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant);
420 // `let` declaration with optional assignment (`var` in es5 mode)
421 let(nameOrPrefix, rhs, _constant) {
422 return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant);
424 // `var` declaration with optional assignment
425 var(nameOrPrefix, rhs, _constant) {
426 return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant);
429 assign(lhs, rhs, sideEffects) {
430 return this._leafNode(new Assign(lhs, rhs, sideEffects));
434 return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs));
436 // appends passed SafeExpr to code or executes Block
438 if (typeof c == "function")
440 else if (c !== code_1.nil)
441 this._leafNode(new AnyCode(c));
444 // returns code for object literal for the passed argument list of key-value pairs
445 object(...keyValues) {
447 for (const [key, value] of keyValues) {
451 if (key !== value || this.opts.es5) {
453 (0, code_1.addCodeArg)(code, value);
457 return new code_1._Code(code);
459 // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed)
460 if(condition, thenBody, elseBody) {
461 this._blockNode(new If(condition));
462 if (thenBody && elseBody) {
463 this.code(thenBody).else().code(elseBody).endIf();
466 this.code(thenBody).endIf();
469 throw new Error('CodeGen: "else" body without "then" body');
473 // `else if` clause - invalid without `if` or after `else` clauses
475 return this._elseNode(new If(condition));
477 // `else` clause - only valid after `if` or `else if` clauses
479 return this._elseNode(new Else());
481 // end `if` statement (needed if gen.if was used only with condition)
483 return this._endBlockNode(If, Else);
485 _for(node, forBody) {
486 this._blockNode(node);
488 this.code(forBody).endFor();
491 // a generic `for` clause (or statement if `forBody` is passed)
492 for(iteration, forBody) {
493 return this._for(new ForLoop(iteration), forBody);
495 // `for` statement for a range of values
496 forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) {
497 const name = this._scope.toName(nameOrPrefix);
498 return this._for(new ForRange(varKind, name, from, to), () => forBody(name));
500 // `for-of` statement (in es5 mode replace with a normal for loop)
501 forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) {
502 const name = this._scope.toName(nameOrPrefix);
504 const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable);
505 return this.forRange("_i", 0, (0, code_1._) `${arr}.length`, (i) => {
506 this.var(name, (0, code_1._) `${arr}[${i}]`);
510 return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name));
512 // `for-in` statement.
513 // With option `ownProperties` replaced with a `for-of` loop for object keys
514 forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) {
515 if (this.opts.ownProperties) {
516 return this.forOf(nameOrPrefix, (0, code_1._) `Object.keys(${obj})`, forBody);
518 const name = this._scope.toName(nameOrPrefix);
519 return this._for(new ForIter("in", varKind, name, obj), () => forBody(name));
523 return this._endBlockNode(For);
527 return this._leafNode(new Label(label));
531 return this._leafNode(new Break(label));
533 // `return` statement
535 const node = new Return();
536 this._blockNode(node);
538 if (node.nodes.length !== 1)
539 throw new Error('CodeGen: "return" should have one node');
540 return this._endBlockNode(Return);
543 try(tryBody, catchCode, finallyCode) {
544 if (!catchCode && !finallyCode)
545 throw new Error('CodeGen: "try" without "catch" and "finally"');
546 const node = new Try();
547 this._blockNode(node);
550 const error = this.name("e");
551 this._currNode = node.catch = new Catch(error);
555 this._currNode = node.finally = new Finally();
556 this.code(finallyCode);
558 return this._endBlockNode(Catch, Finally);
562 return this._leafNode(new Throw(error));
564 // start self-balancing block
565 block(body, nodeCount) {
566 this._blockStarts.push(this._nodes.length);
568 this.code(body).endBlock(nodeCount);
571 // end the current self-balancing block
572 endBlock(nodeCount) {
573 const len = this._blockStarts.pop();
574 if (len === undefined)
575 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`);
580 this._nodes.length = len;
583 // `function` heading (or definition if funcBody is passed)
584 func(name, args = code_1.nil, async, funcBody) {
585 this._blockNode(new Func(name, args, async));
587 this.code(funcBody).endFunc();
590 // end function definition
592 return this._endBlockNode(Func);
596 this._root.optimizeNodes();
597 this._root.optimizeNames(this._root.names, this._constants);
601 this._currNode.nodes.push(node);
605 this._currNode.nodes.push(node);
606 this._nodes.push(node);
608 _endBlockNode(N1, N2) {
609 const n = this._currNode;
610 if (n instanceof N1 || (N2 && n instanceof N2)) {
614 throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`);
617 const n = this._currNode;
618 if (!(n instanceof If)) {
619 throw new Error('CodeGen: "else" without "if"');
621 this._currNode = n.else = node;
625 return this._nodes[0];
628 const ns = this._nodes;
629 return ns[ns.length - 1];
631 set _currNode(node) {
632 const ns = this._nodes;
633 ns[ns.length - 1] = node;
636 exports.CodeGen = CodeGen;
637 function addNames(names, from) {
638 for (const n in from)
639 names[n] = (names[n] || 0) + (from[n] || 0);
642 function addExprNames(names, from) {
643 return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names;
645 function optimizeExpr(expr, names, constants) {
646 if (expr instanceof code_1.Name)
647 return replaceName(expr);
648 if (!canOptimize(expr))
650 return new code_1._Code(expr._items.reduce((items, c) => {
651 if (c instanceof code_1.Name)
653 if (c instanceof code_1._Code)
654 items.push(...c._items);
659 function replaceName(n) {
660 const c = constants[n.str];
661 if (c === undefined || names[n.str] !== 1)
666 function canOptimize(e) {
667 return (e instanceof code_1._Code &&
668 e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== undefined));
671 function subtractNames(names, from) {
672 for (const n in from)
673 names[n] = (names[n] || 0) - (from[n] || 0);
676 return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._) `!${par(x)}`;
679 const andCode = mappend(exports.operators.AND);
680 // boolean AND (&&) expression with the passed arguments
681 function and(...args) {
682 return args.reduce(andCode);
685 const orCode = mappend(exports.operators.OR);
686 // boolean OR (||) expression with the passed arguments
687 function or(...args) {
688 return args.reduce(orCode);
691 function mappend(op) {
692 return (x, y) => (x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._) `${par(x)} ${op} ${par(y)}`);
695 return x instanceof code_1.Name ? x : (0, code_1._) `(${x})`;
697 //# sourceMappingURL=index.js.map