UNPKG

expression-evaluation

Version:
29 lines (28 loc) 1.03 kB
import { Node } from '../Node.js'; import { ConstantNode } from './ConstantNode.js'; import { typeUnknown } from '../Type.js'; export class ProgramNode extends Node { _subnodes; constructor(frame, _subnodes) { super(frame); this._subnodes = _subnodes; } get type() { return this._subnodes[this._subnodes.length - 1].type; } compile(type) { let constant = true; for (let i = 0, last = this._subnodes.length - 1; i < this._subnodes.length; ++i) { this._subnodes[i] = this._subnodes[i].compile(i < last ? typeUnknown : type); constant &&= this._subnodes[i].constant; } return constant ? new ConstantNode(this, this.evaluate()) : this; } evaluate() { return this._subnodes.map((s) => s.evaluate())[this._subnodes.length - 1]; } toString(ident = 0) { return `${super.toString(ident)} program node` + `, subnodes:\n${this._subnodes.map((s) => s.toString(ident + 1)).join('\n')}`; } }