/**
* The ASTs of the Egg Lang
* @external Grammar
* @see {@link https://ull-esit-pl-2223.github.io/temas/syntax-analysis/ast.html#gramatica-informal-de-los-arboles-del-parser-de-egg}
*/
/**
* Builds a number value object from a token.
*
* @param {Array} token - The token array containing the number value.
* @returns {Object} The number value object.
*/
function buildNumberValue([token]) {
//console.log(token);
return {
type: "value",
value: token.value,
raw: token.text,
};
}
/**
* Builds a string value object from a token.
*
* @param {Array} token - The token array containing the string value.
* @returns {Object} - The string value object with type, value, and raw properties.
*/
function buildStringValue([token]) {
//console.log(token);
return {
type: "value",
value: token.value.replace(/^"|"$/g, ""),
raw: token.text,
};
}
/**
* Builds an Abstract Syntax Tree (AST) for a word and its applies.
*
* @param {Array} wordApplies - An array containing a word and its applies.
* @param {Object} wordApplies[0] - The word object.
* @param {Array} wordApplies[1] - An array of applies.
* @returns {Object} - The constructed AST.
*/
function buildWordApplies([word, applies]) {
//console.log(word);
//console.log(JSON.stringify(applies, null,2));
if (applies == null) {
word.type = "word";
word.name = word.value;
delete(word.value);
delete(word.text);
return word;
}
let ast = {
type: "apply",
operator: word,
args: applies[0],
};
if (applies.length == 1) {
return ast;
}
for(let i=1; i < applies.length; i++) {
let oldAst = ast;
ast = {
type: "apply",
operator: oldAst,
args: applies[i]
}
}
//console.log("nested applies");
return ast;
}
/**
* Builds an array of nested applies.
*
* @param {Array} parenExp - The expression enclosed in parentheses.
* @param {Array} applies - The array of applies.
* @returns {Array} - The array of nested applies.
*/
function buildNestedApplies([parenExp, applies]) {
//console.log("buildNestedApplies---\n", JSON.stringify(applies, null,2));
if (applies) return [parenExp].concat(applies)
return [ parenExp ];
}
module.exports = { buildStringValue, buildNumberValue, buildWordApplies, buildNestedApplies };