lua_to_cpls
Version:
A tool capable of compiling a subset of Lua to Please lang compiled files
92 lines (80 loc) • 2.17 kB
JavaScript
const makeWord = (name) => {
return {
type: 'Word',
name: name,
}
};
const makeValue = (val) => {
return {
type: 'Value',
value: val,
}
};
const makeCall = (operator, args) => {
return {
type: "Call",
operator: operator,
args: args,
}
};
const binaryOperation = (match) => {
return makeCall(makeWord(match[1].value), [match[0], match[2]]);
};
const makeFunction = ([_, name, args]) => {
return makeCall(makeWord("let"), [makeWord(name.value), makeCall(makeWord("fn"), args)]);
};
const makeDeclaration = (match) => {
return makeCall(makeWord("let"), [makeWord(match[1].value), match[3]]);
};
const makeIf = (match) => {
if (match[4] == undefined) {
return makeCall(makeWord("if"), [match[1], match[3]]);
}
return makeCall(makeWord("if"), [match[1], match[3], match[4][1]]);
}
const makeArray = (match) => {
let elements = [];
if (match[1] != undefined) {
elements.push(match[1][0]);
if (match[1][1] != undefined) {
elements = elements.concat(match[1][1].map(([_, element]) => element));
}
}
return makeCall(makeWord("array"), elements);
};
const makeFor = (match) => {
return makeCall(makeWord("foreach"), [makeWord(match[1].value), match[3], match[4]]);
};
const processArgs = (match) => {
let args = [];
if (match[1] != undefined) {
args.push(match[1][0]);
if (match[1][1] != undefined) {
args = args.concat(match[1][1].map(([_, arg]) => arg));
}
}
return args;
};
const processParameters = (match) => {
let args = [];
if (match[1] != undefined) {
args.push(makeWord(match[1][0].value));
if (match[1][1] != undefined) {
args = args.concat(match[1][1].map(([_, arg]) => makeWord(arg.value)));
}
}
return args;
};
const processBlock = (match) => {
let statements = [];
if (match[0] != undefined) {
statements = match[0].filter((x) => x != undefined);
}
statements.push(match[1]);
return makeCall(makeWord("do"), statements);
};
module.exports = {
makeWord, makeValue, makeCall, makeFunction,
makeDeclaration, binaryOperation, makeIf, makeArray,
makeFor, processArgs, processParameters, processBlock,
};