prefix expressions
This commit is contained in:
@@ -91,6 +91,21 @@ func (c *Compiler) Compile(node ast.Node) error {
|
||||
c.emit(code.OpFalse)
|
||||
}
|
||||
|
||||
case *ast.PrefixExpression:
|
||||
err := c.Compile(node.Right)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
switch node.Operator {
|
||||
case "!":
|
||||
c.emit(code.OpBang)
|
||||
case "-":
|
||||
c.emit(code.OpMinus)
|
||||
default:
|
||||
return fmt.Errorf("unknown operator %s", node.Operator)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
@@ -68,6 +68,15 @@ func TestIntegerArithmetic(t *testing.T) {
|
||||
code.Make(code.OpPop),
|
||||
},
|
||||
},
|
||||
{
|
||||
input: "-1",
|
||||
expectedConstants: []interface{}{1},
|
||||
expectedInstructions: []code.Instructions{
|
||||
code.Make(code.OpConstant, 0),
|
||||
code.Make(code.OpMinus),
|
||||
code.Make(code.OpPop),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
runCompilerTests(t, tests)
|
||||
@@ -151,6 +160,15 @@ func TestBooleanExpressions(t *testing.T) {
|
||||
code.Make(code.OpPop),
|
||||
},
|
||||
},
|
||||
{
|
||||
input: "!true",
|
||||
expectedConstants: []interface{}{},
|
||||
expectedInstructions: []code.Instructions{
|
||||
code.Make(code.OpTrue),
|
||||
code.Make(code.OpBang),
|
||||
code.Make(code.OpPop),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
runCompilerTests(t, tests)
|
||||
|
||||
Reference in New Issue
Block a user