import { Node } from 'acorn'; import { NodeError } from './nodeError'; import { ValueNode, InterpreterNode } from './types/valueNode'; import * as NodeProcessors from './node-processors/index'; import { Interpreter } from './types/interpreter'; import { Maybe, nullable } from './types/maybe'; import { protectHostObject } from './sandbox'; function isNode(obj: any): obj is Node { return obj && obj.start !== undefined; } if (!Object.fromEntries) { const fromEntries = require('object.fromentries'); // eslint-disable-line fromEntries.shim(); } const SafeConstructors = Object.freeze({ String, Number, Set, isNaN, // eslint-disable-line Error }); class InterpreterInstance implements Interpreter { // Scopes have no prototype so identifiers such as `constructor` or `__proto__` cannot resolve to inherited host objects. #stack: Array> = [Object.create(null)]; #heap: Record; #nodeHints: WeakMap> = new WeakMap(); constructor( customObjects: Record, keywords: string[], it: any, public ast: any, public source: string ) { this.#heap = Object.assign(Object.create(null), { it: new ValueNode('it', it, { optional: true, optionalChaining: true }), undefined: new ValueNode('undefined', undefined), null: new ValueNode('null', null), print: new ValueNode('print', (...values) => console.log(...values)) }); Object.values(customObjects).forEach(protectHostObject); this.addDictToHeap(customObjects); this.addDictToHeap(keywords); this.addDictToHeap(SafeConstructors); } get stack() { return this.#stack[0]; } get heap() { return this.#heap; } addDictToHeap(dict: Record) { for (const [key, value] of Object.entries(dict)) { this.#heap[key] = new ValueNode(key, value); } } pushStack() { this.#stack.unshift(Object.assign(Object.create(null), this.#stack[0])); } popStack({ capturesReturn = false, capturesControl = false } = {}) { const { controlFlow, returnFlow } = this; const { _returnValue, _continues, _breaks } = this.#stack[0]; this.#stack.shift(); if (_returnValue !== undefined && !capturesReturn) { this.#stack[0]._returnValue = _returnValue; } if (_continues !== undefined && !capturesControl) { this.#stack[0]._continues = _continues; } if (_breaks !== undefined && !capturesControl) { this.#stack[0]._breaks = _breaks; } return { controlFlow, returnFlow }; } get controlFlow() { return { continues: this.#stack[0]._continues?.value === true, breaks: this.#stack[0]._breaks?.value === true }; } get returnFlow() { return { returns: this.#stack[0]._returnValue !== undefined, returnValue: this.#stack[0]._returnValue }; } processNode(node: InterpreterNode, hints?: Record): any { // Input data can hold plain objects with a `type` field; only real nodes may be dispatched. if (!NodeProcessors.isNode(node)) { return node; } const nodeInstance = (NodeProcessors as any)[node.type]; if (isNode(node) && !nodeInstance) { throw new NodeError(`Unexpected node [${node.type}]`, node, this.source); } else if (!nodeInstance) { return node; } if (hints) { this.setHints(node, hints); } try { const func = nodeInstance as (instance: Interpreter, nodeToProcess: InterpreterNode) => T; const result = func(this, node); return result; } catch (e: any) { if (e instanceof NodeError) { throw e; } throw new NodeError(`Unexpected error: ${e.message}`, node, this.source); } } execute() { // ast is a node with type of Program this.processNode(this.ast); return this.unwrapValue('_returnValue'); } unwrap(node: InterpreterNode, hints?: Record): T { if (hints) { this.setHints(node, hints); } return NodeProcessors.unwrap(this, node); } /** * From a given string, search the stack and heap for the corresponding node * and process, returning the value of the node * @param identifier * @returns processed node */ getValueNode(identifier: string): Maybe> { return nullable(this.stack[identifier] ?? this.heap[identifier]); } unwrapValue(identifier: string): T | null | undefined { const valueNode = this.getValueNode(identifier); return valueNode.type === 'Nothing' ? undefined : valueNode.value.value; } setValue(id: string, value: ValueNode | any, opts?: any) { if (value instanceof ValueNode) { this.stack[id] = value; } else if (this.stack[id]) { this.stack[id].value = value; } else { this.stack[id] = new ValueNode(id, value, { assign: (_value) => this.setValue(id, _value), ...opts }); } } getNode(identifier: string): ValueNode | undefined { if (this.stack[identifier]) { return this.stack[identifier]; } if (this.heap[identifier]) { return this.heap[identifier]; } } setHints(node: InterpreterNode, hints: T) { return this.#nodeHints.set(node, Object.assign(this.#nodeHints.get(node) ?? {}, hints)).get(node); } getHints>(node: InterpreterNode): T { return (this.#nodeHints.get(node) ?? {}) as T; } } export default InterpreterInstance;