Arithmetic

This commit is contained in:
Chuck Smith
2024-01-26 12:13:23 -05:00
parent e34991c081
commit b4cc771baa
6 changed files with 111 additions and 14 deletions

View File

@@ -34,6 +34,7 @@ func (c *Compiler) Compile(node ast.Node) error {
if err != nil {
return err
}
c.emit(code.OpPop)
case *ast.InfixExpression:
err := c.Compile(node.Left)
@@ -49,6 +50,12 @@ func (c *Compiler) Compile(node ast.Node) error {
switch node.Operator {
case "+":
c.emit(code.OpAdd)
case "-":
c.emit(code.OpSub)
case "*":
c.emit(code.OpMul)
case "/":
c.emit(code.OpDiv)
default:
return fmt.Errorf("unknown operator %s", node.Operator)
}

View File

@@ -25,6 +25,47 @@ func TestIntegerArithmetic(t *testing.T) {
code.Make(code.OpConstant, 0),
code.Make(code.OpConstant, 1),
code.Make(code.OpAdd),
code.Make(code.OpPop),
},
},
{
input: "1; 2",
expectedConstants: []interface{}{1, 2},
expectedInstructions: []code.Instructions{
code.Make(code.OpConstant, 0),
code.Make(code.OpPop),
code.Make(code.OpConstant, 1),
code.Make(code.OpPop),
},
},
{
input: "1 - 2",
expectedConstants: []interface{}{1, 2},
expectedInstructions: []code.Instructions{
code.Make(code.OpConstant, 0),
code.Make(code.OpConstant, 1),
code.Make(code.OpSub),
code.Make(code.OpPop),
},
},
{
input: "1 * 2",
expectedConstants: []interface{}{1, 2},
expectedInstructions: []code.Instructions{
code.Make(code.OpConstant, 0),
code.Make(code.OpConstant, 1),
code.Make(code.OpMul),
code.Make(code.OpPop),
},
},
{
input: "2 / 1",
expectedConstants: []interface{}{2, 1},
expectedInstructions: []code.Instructions{
code.Make(code.OpConstant, 0),
code.Make(code.OpConstant, 1),
code.Make(code.OpDiv),
code.Make(code.OpPop),
},
},
}