derw-lang/js/parser.mjs

91 lines
2 KiB
JavaScript
Raw Permalink Normal View History

2024-11-29 20:09:54 -05:00
//import objs from './objs.mjs';
2024-11-28 23:25:40 -05:00
let openers = {
2024-11-29 21:04:43 -05:00
'{': '}', // function
'[': ']', // string
'(': ')', // group
// TODO: dropdowns, custom blocks
2024-11-28 23:25:40 -05:00
};
function parser(str, context = '(') {
str = str.replaceAll(/^\s+([^\s]+)/gms, '$1')
str = str.replaceAll(/([^\s]+)\s+$/gms, '$1')
2024-11-29 15:47:46 -05:00
let nextI = str.search(/[^A-Za-z0-9;\s]/gms);
2024-11-28 23:25:40 -05:00
if (context == '[') {
nextI = str.search(/[\]]/);
}
if (nextI == -1) nextI = 0;
let nextChar = str[nextI];
2024-11-29 15:47:46 -05:00
let sliced = str.slice(0, nextI);
let rest = str.slice(nextI + 1);
2024-11-28 23:25:40 -05:00
2024-11-29 15:47:46 -05:00
if (nextChar == openers[context] || !(openers[context])) {
return { context, str: sliced, next: rest, end: nextChar == openers[context] || sliced.indexOf(';') != -1};
2024-11-28 23:25:40 -05:00
} else {
let args = [];
2024-11-29 15:47:46 -05:00
let nextStr = rest;
2024-11-28 23:25:40 -05:00
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;
}
2024-11-29 15:47:46 -05:00
let o = { context: sliced, args, next: nextStr, op: nextChar };
2024-11-28 23:25:40 -05:00
return o;
}
}
async function runner(script, objects) {
2024-11-30 04:26:22 -05:00
if (script.canDelete) return;
2024-11-28 23:25:40 -05:00
let { op, context } = script;
let obj = objects[context.trim()];
let h = false;
if (op == '{') {
h = (async function () {
2024-11-29 15:47:46 -05:00
let output = false;
for (let a of script.args) {
output = await runner(a, objects);
}
return output;
2024-11-28 23:25:40 -05:00
})
} 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;
2024-11-29 15:47:46 -05:00
} else if (op == '[') {
h = script.args[0].str;
2024-11-28 23:25:40 -05:00
}
if (typeof obj != 'function') {
return h;
}
return await obj(h, objects);
}
2024-11-29 20:09:54 -05:00
export {
parser,
runner,
openers
};