derw-lang/js/parser.mjs
2024-11-30 04:26:22 -05:00

90 lines
2 KiB
JavaScript

//import objs from './objs.mjs';
let openers = {
'{': '}', // function
'[': ']', // string
'(': ')', // group
// TODO: dropdowns, custom blocks
};
function parser(str, context = '(') {
str = str.replaceAll(/^\s+([^\s]+)/gms, '$1')
str = str.replaceAll(/([^\s]+)\s+$/gms, '$1')
let nextI = str.search(/[^A-Za-z0-9;\s]/gms);
if (context == '[') {
nextI = str.search(/[\]]/);
}
if (nextI == -1) nextI = 0;
let nextChar = str[nextI];
let sliced = str.slice(0, nextI);
let rest = str.slice(nextI + 1);
if (nextChar == openers[context] || !(openers[context])) {
return { context, str: sliced, next: rest, end: nextChar == openers[context] || sliced.indexOf(';') != -1};
} else {
let args = [];
let nextStr = rest;
while (nextStr && nextStr.length > 0) {
args.push(parser(nextStr, nextChar));
let a = args[args.length - 1];
nextStr = a.next;
if (a.str == '') {
args.pop();
}
if (a.end) break;
}
let o = { context: sliced, args, next: nextStr, op: nextChar };
return o;
}
}
async function runner(script, objects) {
if (script.canDelete) return;
let { op, context } = script;
let obj = objects[context.trim()];
let h = false;
if (op == '{') {
h = (async function () {
let output = false;
for (let a of script.args) {
output = await runner(a, objects);
}
return output;
})
} else if (op == '(') {
let arger = [];
for (let arg of script.args) {
arger.push(await runner(arg, objects));
}
if (arger.length == 1) arger = arger[0];
h = arger;
} else if (op == '[') {
h = script.args[0].str;
}
if (typeof obj != 'function') {
return h;
}
return await obj(h, objects);
}
export {
parser,
runner,
openers
};