You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

67 lines
1.3 KiB
JavaScript

'use strict';
function stringifyNode(node) {
switch (node.type) {
case "operatorExpression":
return stringifyOperator(node);
case "numberLiteral":
return stringifyNumberLiteral(node);
case "stringLiteral":
return stringifyStringLiteral(node);
case "identifier":
return stringifyIdentifier(node);
default:
throw new Error(`Unexpected node type '${node.type}'`);
}
}
function stringifyOperator(node) {
let result;
switch (node.operator) {
case "+":
case "-":
case "/":
case "*":
case "++":
case "//":
case "&&":
case "||":
case "==":
case "!=":
case "<":
case "<=":
case ">":
case ">=":
result = `${stringifyNode(node.left)} ${node.operator} ${stringifyNode(node.right)}`;
break;
case "call":
result = `${stringifyNode(node.left)} ${stringifyNode(node.right)}`;
break;
case "numericalNegate":
result = `-${stringifyNode(node.right)}`;
break;
case "booleanNegate":
result = `!${stringifyNode(node.right)}`;
break;
}
return `(${result})`;
}
function stringifyStringLiteral(node) {
return `"${node.value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
}
function stringifyNumberLiteral(node) {
return `${node.value}`;
}
function stringifyIdentifier(node) {
return `${node.identifier}`;
}
module.exports = function stringifyTree(tree) {
return stringifyNode(tree);
};