Fix expression parser to require parsing full string

This commit is contained in:
Tangent Wantwight 2024-05-18 21:24:19 -04:00
parent 1a46130b1d
commit 21e8d95f98
2 changed files with 27 additions and 15 deletions

View file

@ -2,21 +2,29 @@ import { AsText, TextPiece } from "../words";
import { Expr } from "./expr";
describe("expr", () => {
test.each([
["1", "1"],
["1 + 2", "3"],
["1 - 2", "-1"],
["1 * 2", "2"],
["1 / 2", "0.5"],
["1 // 2", "0"],
// TODO: operator precedence
// TODO: parentheses
// TODO; eror reporting
])("Expr does math: %s", (expression, result) => {
const actualResult = Expr({}, [{ text: expression }]);
console.log(actualResult)
expect("error" in actualResult).toBeFalsy();
expect(AsText(actualResult as TextPiece)).toEqual(result);
describe("Expr does math", () => {
test.each([
["1", "1"],
["1 + 2", "3"],
["1 - 2", "-1"],
["1 * 2", "2"],
["1 / 2", "0.5"],
["1 // 2", "0"],
// TODO: operator precedence
// TODO: parentheses
])("%s", (expression, result) => {
const actualResult = Expr({}, [{ text: expression }]);
expect("error" in actualResult).toBeFalsy();
expect(AsText(actualResult as TextPiece)).toEqual(result);
});
});
// TODO; error reporting
describe("Expr rejects invalid expressions", () => {
test.each([["1 $ 2"], ["1 1 + 2"], ["$ 1"]])("%s", (expression) => {
const actualResult = Expr({}, [{ text: expression }]);
expect("error" in actualResult).toBeTruthy();
});
});
// TODO: handle expr prefix

View file

@ -12,6 +12,10 @@ export function Expr({}, argv: TextPiece[]): ProcResult {
const parser = new ExpressionParser(expression);
const result = parser.parseSubExpression(0);
if(parser.pos != expression.length) {
return {error: "Couldn't parse full expression"}
}
if ("value" in result) {
return { text: String(result.value) };
} else {