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.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, "Name", { enumerable: true, get: function () { return code_2.Name; } });
14 var scope_2 = require("./scope");
15 Object.defineProperty(exports, "Scope", { enumerable: true, get: function () { return scope_2.Scope; } });
16 Object.defineProperty(exports, "ValueScope", { enumerable: true, get: function () { return scope_2.ValueScope; } });
17 Object.defineProperty(exports, "ValueScopeName", { enumerable: true, get: function () { return scope_2.ValueScopeName; } });
18 Object.defineProperty(exports, "varKinds", { enumerable: true, get: function () { return scope_2.varKinds; } });
20 GT: new code_1._Code(">"),
21 GTE: new code_1._Code(">="),
22 LT: new code_1._Code("<"),
23 LTE: new code_1._Code("<="),
24 EQ: new code_1._Code("==="),
25 NEQ: new code_1._Code("!=="),
26 NOT: new code_1._Code("!"),
27 OR: new code_1._Code("||"),
28 AND: new code_1._Code("&&"),
29 ADD: new code_1._Code("+"),
35 optimizeNames(_names, _constants) {
39 class Def extends Node {
40 constructor(varKind, name, rhs) {
42 this.varKind = varKind;
47 const varKind = es5 ? scope_1.varKinds.var : this.varKind;
48 const rhs = this.rhs === undefined ? "" : ` = ${this.rhs}`;
49 return `${varKind} ${this.name}${rhs};` + _n;
51 optimizeNames(names, constants) {
52 if (!names[this.name.str])
55 this.rhs = optimizeExpr(this.rhs, names, constants);
59 return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {};
62 class Assign extends Node {
63 constructor(lhs, rhs, sideEffects) {
67 this.sideEffects = sideEffects;
70 return `${this.lhs} = ${this.rhs};` + _n;
72 optimizeNames(names, constants) {
73 if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects)
75 this.rhs = optimizeExpr(this.rhs, names, constants);
79 const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names };
80 return addExprNames(names, this.rhs);
83 class AssignOp extends Assign {
84 constructor(lhs, op, rhs, sideEffects) {
85 super(lhs, rhs, sideEffects);
89 return `${this.lhs} ${this.op}= ${this.rhs};` + _n;
92 class Label extends Node {
99 return `${this.label}:` + _n;
102 class Break extends Node {
109 const label = this.label ? ` ${this.label}` : "";
110 return `break${label};` + _n;
113 class Throw extends Node {
119 return `throw ${this.error};` + _n;
122 return this.error.names;
125 class AnyCode extends Node {
131 return `${this.code};` + _n;
134 return `${this.code}` ? this : undefined;
136 optimizeNames(names, constants) {
137 this.code = optimizeExpr(this.code, names, constants);
141 return this.code instanceof code_1._CodeOrName ? this.code.names : {};
144 class ParentNode extends Node {
145 constructor(nodes = []) {
150 return this.nodes.reduce((code, n) => code + n.render(opts), "");
153 const { nodes } = this;
154 let i = nodes.length;
156 const n = nodes[i].optimizeNodes();
157 if (Array.isArray(n))
158 nodes.splice(i, 1, ...n);
164 return nodes.length > 0 ? this : undefined;
166 optimizeNames(names, constants) {
167 const { nodes } = this;
168 let i = nodes.length;
170 // iterating backwards improves 1-pass optimization
172 if (n.optimizeNames(names, constants))
174 subtractNames(names, n.names);
177 return nodes.length > 0 ? this : undefined;
180 return this.nodes.reduce((names, n) => addNames(names, n.names), {});
183 class BlockNode extends ParentNode {
185 return "{" + opts._n + super.render(opts) + "}" + opts._n;
188 class Root extends ParentNode {
190 class Else extends BlockNode {
193 class If extends BlockNode {
194 constructor(condition, nodes) {
196 this.condition = condition;
199 let code = `if(${this.condition})` + super.render(opts);
201 code += "else " + this.else.render(opts);
205 super.optimizeNodes();
206 const cond = this.condition;
208 return this.nodes; // else is ignored here
211 const ns = e.optimizeNodes();
212 e = this.else = Array.isArray(ns) ? new Else(ns) : ns;
216 return e instanceof If ? e : e.nodes;
217 if (this.nodes.length)
219 return new If(not(cond), e instanceof If ? [e] : e.nodes);
221 if (cond === false || !this.nodes.length)
225 optimizeNames(names, constants) {
227 this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants);
228 if (!(super.optimizeNames(names, constants) || this.else))
230 this.condition = optimizeExpr(this.condition, names, constants);
234 const names = super.names;
235 addExprNames(names, this.condition);
237 addNames(names, this.else.names);
242 class For extends BlockNode {
245 class ForLoop extends For {
246 constructor(iteration) {
248 this.iteration = iteration;
251 return `for(${this.iteration})` + super.render(opts);
253 optimizeNames(names, constants) {
254 if (!super.optimizeNames(names, constants))
256 this.iteration = optimizeExpr(this.iteration, names, constants);
260 return addNames(super.names, this.iteration.names);
263 class ForRange extends For {
264 constructor(varKind, name, from, to) {
266 this.varKind = varKind;
272 const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind;
273 const { name, from, to } = this;
274 return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts);
277 const names = addExprNames(super.names, this.from);
278 return addExprNames(names, this.to);
281 class ForIter extends For {
282 constructor(loop, varKind, name, iterable) {
285 this.varKind = varKind;
287 this.iterable = iterable;
290 return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);
292 optimizeNames(names, constants) {
293 if (!super.optimizeNames(names, constants))
295 this.iterable = optimizeExpr(this.iterable, names, constants);
299 return addNames(super.names, this.iterable.names);
302 class Func extends BlockNode {
303 constructor(name, args, async) {
310 const _async = this.async ? "async " : "";
311 return `${_async}function ${this.name}(${this.args})` + super.render(opts);
315 class Return extends ParentNode {
317 return "return " + super.render(opts);
320 Return.kind = "return";
321 class Try extends BlockNode {
323 let code = "try" + super.render(opts);
325 code += this.catch.render(opts);
327 code += this.finally.render(opts);
332 super.optimizeNodes();
333 (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNodes();
334 (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes();
337 optimizeNames(names, constants) {
339 super.optimizeNames(names, constants);
340 (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants);
341 (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants);
345 const names = super.names;
347 addNames(names, this.catch.names);
349 addNames(names, this.finally.names);
353 class Catch extends BlockNode {
359 return `catch(${this.error})` + super.render(opts);
362 Catch.kind = "catch";
363 class Finally extends BlockNode {
365 return "finally" + super.render(opts);
368 Finally.kind = "finally";
370 constructor(extScope, opts = {}) {
372 this._blockStarts = [];
373 this._constants = {};
374 this.opts = { ...opts, _n: opts.lines ? "\n" : "" };
375 this._extScope = extScope;
376 this._scope = new scope_1.Scope({ parent: extScope });
377 this._nodes = [new Root()];
380 return this._root.render(this.opts);
382 // returns unique name in the internal scope
384 return this._scope.name(prefix);
386 // reserves unique name in the external scope
388 return this._extScope.name(prefix);
390 // reserves unique name in the external scope and assigns value to it
391 scopeValue(prefixOrName, value) {
392 const name = this._extScope.value(prefixOrName, value);
393 const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set());
397 getScopeValue(prefix, keyOrRef) {
398 return this._extScope.getValue(prefix, keyOrRef);
400 // return code that assigns values in the external scope to the names that are used internally
401 // (same names that were returned by gen.scopeName or gen.scopeValue)
402 scopeRefs(scopeName) {
403 return this._extScope.scopeRefs(scopeName, this._values);
406 return this._extScope.scopeCode(this._values);
408 _def(varKind, nameOrPrefix, rhs, constant) {
409 const name = this._scope.toName(nameOrPrefix);
410 if (rhs !== undefined && constant)
411 this._constants[name.str] = rhs;
412 this._leafNode(new Def(varKind, name, rhs));
415 // `const` declaration (`var` in es5 mode)
416 const(nameOrPrefix, rhs, _constant) {
417 return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant);
419 // `let` declaration with optional assignment (`var` in es5 mode)
420 let(nameOrPrefix, rhs, _constant) {
421 return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant);
423 // `var` declaration with optional assignment
424 var(nameOrPrefix, rhs, _constant) {
425 return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant);
428 assign(lhs, rhs, sideEffects) {
429 return this._leafNode(new Assign(lhs, rhs, sideEffects));
433 return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs));
435 // appends passed SafeExpr to code or executes Block
437 if (typeof c == "function")
439 else if (c !== code_1.nil)
440 this._leafNode(new AnyCode(c));
443 // returns code for object literal for the passed argument list of key-value pairs
444 object(...keyValues) {
446 for (const [key, value] of keyValues) {
450 if (key !== value || this.opts.es5) {
452 code_1.addCodeArg(code, value);
456 return new code_1._Code(code);
458 // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed)
459 if(condition, thenBody, elseBody) {
460 this._blockNode(new If(condition));
461 if (thenBody && elseBody) {
462 this.code(thenBody).else().code(elseBody).endIf();
465 this.code(thenBody).endIf();
468 throw new Error('CodeGen: "else" body without "then" body');
472 // `else if` clause - invalid without `if` or after `else` clauses
474 return this._elseNode(new If(condition));
476 // `else` clause - only valid after `if` or `else if` clauses
478 return this._elseNode(new Else());
480 // end `if` statement (needed if gen.if was used only with condition)
482 return this._endBlockNode(If, Else);
484 _for(node, forBody) {
485 this._blockNode(node);
487 this.code(forBody).endFor();
490 // a generic `for` clause (or statement if `forBody` is passed)
491 for(iteration, forBody) {
492 return this._for(new ForLoop(iteration), forBody);
494 // `for` statement for a range of values
495 forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) {
496 const name = this._scope.toName(nameOrPrefix);
497 return this._for(new ForRange(varKind, name, from, to), () => forBody(name));
499 // `for-of` statement (in es5 mode replace with a normal for loop)
500 forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) {
501 const name = this._scope.toName(nameOrPrefix);
503 const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable);
504 return this.forRange("_i", 0, code_1._ `${arr}.length`, (i) => {
505 this.var(name, code_1._ `${arr}[${i}]`);
509 return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name));
511 // `for-in` statement.
512 // With option `ownProperties` replaced with a `for-of` loop for object keys
513 forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) {
514 if (this.opts.ownProperties) {
515 return this.forOf(nameOrPrefix, code_1._ `Object.keys(${obj})`, forBody);
517 const name = this._scope.toName(nameOrPrefix);
518 return this._for(new ForIter("in", varKind, name, obj), () => forBody(name));
522 return this._endBlockNode(For);
526 return this._leafNode(new Label(label));
530 return this._leafNode(new Break(label));
532 // `return` statement
534 const node = new Return();
535 this._blockNode(node);
537 if (node.nodes.length !== 1)
538 throw new Error('CodeGen: "return" should have one node');
539 return this._endBlockNode(Return);
542 try(tryBody, catchCode, finallyCode) {
543 if (!catchCode && !finallyCode)
544 throw new Error('CodeGen: "try" without "catch" and "finally"');
545 const node = new Try();
546 this._blockNode(node);
549 const error = this.name("e");
550 this._currNode = node.catch = new Catch(error);
554 this._currNode = node.finally = new Finally();
555 this.code(finallyCode);
557 return this._endBlockNode(Catch, Finally);
561 return this._leafNode(new Throw(error));
563 // start self-balancing block
564 block(body, nodeCount) {
565 this._blockStarts.push(this._nodes.length);
567 this.code(body).endBlock(nodeCount);
570 // end the current self-balancing block
571 endBlock(nodeCount) {
572 const len = this._blockStarts.pop();
573 if (len === undefined)
574 throw new Error("CodeGen: not in self-balancing block");
575 const toClose = this._nodes.length - len;
576 if (toClose < 0 || (nodeCount !== undefined && toClose !== nodeCount)) {
577 throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`);
579 this._nodes.length = len;
582 // `function` heading (or definition if funcBody is passed)
583 func(name, args = code_1.nil, async, funcBody) {
584 this._blockNode(new Func(name, args, async));
586 this.code(funcBody).endFunc();
589 // end function definition
591 return this._endBlockNode(Func);
595 this._root.optimizeNodes();
596 this._root.optimizeNames(this._root.names, this._constants);
600 this._currNode.nodes.push(node);
604 this._currNode.nodes.push(node);
605 this._nodes.push(node);
607 _endBlockNode(N1, N2) {
608 const n = this._currNode;
609 if (n instanceof N1 || (N2 && n instanceof N2)) {
613 throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`);
616 const n = this._currNode;
617 if (!(n instanceof If)) {
618 throw new Error('CodeGen: "else" without "if"');
620 this._currNode = n.else = node;
624 return this._nodes[0];
627 const ns = this._nodes;
628 return ns[ns.length - 1];
630 set _currNode(node) {
631 const ns = this._nodes;
632 ns[ns.length - 1] = node;
635 exports.CodeGen = CodeGen;
636 function addNames(names, from) {
637 for (const n in from)
638 names[n] = (names[n] || 0) + (from[n] || 0);
641 function addExprNames(names, from) {
642 return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names;
644 function optimizeExpr(expr, names, constants) {
645 if (expr instanceof code_1.Name)
646 return replaceName(expr);
647 if (!canOptimize(expr))
649 return new code_1._Code(expr._items.reduce((items, c) => {
650 if (c instanceof code_1.Name)
652 if (c instanceof code_1._Code)
653 items.push(...c._items);
658 function replaceName(n) {
659 const c = constants[n.str];
660 if (c === undefined || names[n.str] !== 1)
665 function canOptimize(e) {
666 return (e instanceof code_1._Code &&
667 e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== undefined));
670 function subtractNames(names, from) {
671 for (const n in from)
672 names[n] = (names[n] || 0) - (from[n] || 0);
675 return typeof x == "boolean" || typeof x == "number" || x === null ? !x : code_1._ `!${par(x)}`;
678 const andCode = mappend(exports.operators.AND);
679 // boolean AND (&&) expression with the passed arguments
680 function and(...args) {
681 return args.reduce(andCode);
684 const orCode = mappend(exports.operators.OR);
685 // boolean OR (||) expression with the passed arguments
686 function or(...args) {
687 return args.reduce(orCode);
690 function mappend(op) {
691 return (x, y) => (x === code_1.nil ? y : y === code_1.nil ? x : code_1._ `${par(x)} ${op} ${par(y)}`);
694 return x instanceof code_1.Name ? x : code_1._ `(${x})`;
696 //# sourceMappingURL=index.js.map