derw-lang/index.mjs

106 lines
2.2 KiB
JavaScript
Raw Normal View History

2024-11-28 23:25:40 -05:00
import objs from './objs.mjs';
let openers = {
'{': '}',
'[': ']',
2024-11-29 15:47:46 -05:00
'(': ')'
2024-11-28 23:25:40 -05:00
};
let specialOpeners = {
//':': 'wildcard'
};
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) {
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);
}
let data = parser(`
on(
[start]
{
2024-11-29 15:47:46 -05:00
echo(add([2][3]))
echo([Hello World!])
echo(add([2][3]))
echo([Hello World!])
2024-11-28 23:25:40 -05:00
}
)
`);
console.log(data);
(async function () {
await runner(data, objs);
let ev = new Event('start');
objs.events.dispatchEvent(ev);
})()