Factor out common infix op logic

This commit is contained in:
Tangent Wantwight 2024-05-18 21:33:17 -04:00
parent 1078dc3653
commit 5a34b0f6f7

View file

@ -58,44 +58,26 @@ function map(
}
}
function makeInfixOp(token:RegExp, leftBindingPower: number,rightBindingPower: number, op: (left: number, right: number) => Value | ErrorResult):TokenHandler {
return {
leftBindingPower,
token,
parse: ({ value: left }, matched, parser) =>
map(parser.parseSubExpression(rightBindingPower), (right) => op(left, right)),
}
}
const Operators: TokenHandler[] = [
{
leftBindingPower: -1,
token: NUMBER_TOKEN,
parse: (left, matched) => ({ value: Number(matched) }),
},
{
leftBindingPower: 10,
token: PLUS_TOKEN,
parse: ({ value: left }, matched, parser) =>
map(parser.parseSubExpression(11), (right) => ({ value: left + right })),
},
{
leftBindingPower: 10,
token: MINUS_TOKEN,
parse: ({ value: left }, matched, parser) =>
map(parser.parseSubExpression(11), (right) => ({ value: left - right })),
},
{
leftBindingPower: 20,
token: TIMES_TOKEN,
parse: ({ value: left }, matched, parser) =>
map(parser.parseSubExpression(21), (right) => ({ value: left * right })),
},
{
leftBindingPower: 20,
token: FLOOR_TOKEN,
parse: ({ value: left }, matched, parser) =>
map(parser.parseSubExpression(21), (right) => ({
value: Math.floor(left / right),
})),
},
{
leftBindingPower: 20,
token: DIV_TOKEN,
parse: ({ value: left }, matched, parser) =>
map(parser.parseSubExpression(21), (right) => ({ value: left / right })),
},
makeInfixOp(PLUS_TOKEN, 10, 11, (left, right) => ({ value: left + right })),
makeInfixOp(MINUS_TOKEN, 10, 11, (left, right) => ({ value: left - right })),
makeInfixOp(TIMES_TOKEN, 10, 11, (left, right) => ({ value: left * right })),
makeInfixOp(FLOOR_TOKEN, 10, 11, (left, right) => ({ value: Math.floor(left / right) })),
makeInfixOp(DIV_TOKEN, 10, 11, (left, right) => ({ value: left / right })),
];
const ZERO = { value: 0 };