rulescribe
Version:
Typescript rule engine
65 lines (64 loc) • 2.06 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const interfaces_1 = require("./interfaces");
// Define symbol table to store variables and functions
class EngineScope {
constructor(builtinFunction = new Map(), symbols = new Map()) {
this.builtinFunction = builtinFunction;
this.symbols = symbols;
this.funcs = new Map();
this.rules = new Map();
}
define(name, value) {
this.symbols.set(name, value);
}
lookup(name) {
if (name.indexOf('.') !== -1) {
const namePath = name.split('.');
let obj = this.symbols.get(namePath[0]);
for (let i = 1; i < namePath.length; i += 1) {
obj = obj[namePath[i]];
}
return obj;
}
return this.symbols.get(name);
}
declare(name, parameters, body) {
this.funcs.set(name, { parameters, func: body });
}
addRule(name, rule) {
this.rules.set(name, rule);
}
getRule(name) {
return this.rules.get(name);
}
getRuleNames() {
return Array.from(this.rules.keys());
}
functionType(name) {
if (this.funcs.has(name)) {
return interfaces_1.FunctionType.USER_DEFINED;
}
if (this.builtinFunction.has(name)) {
return interfaces_1.FunctionType.BUILTIN;
}
if (name.indexOf('@') !== -1) {
return interfaces_1.FunctionType.CLASS_METHOD;
}
return interfaces_1.FunctionType.UNDEFINED;
}
getFunc(name) {
if (name.indexOf('@') !== -1) {
const methodPath = name.split('@');
let method = this.symbols.get(methodPath.pop());
let thisArg;
while (methodPath.length > 0) {
thisArg = method;
method = thisArg[methodPath.pop()];
}
return { func: method, thisArg };
}
return this.funcs.get(name) || this.builtinFunction.get(name);
}
}
exports.default = EngineScope;