Skip to content

Commit

Permalink
🚤 bytecode: Implement addition and subtraction (#274)
Browse files Browse the repository at this point in the history
These simple operations for integer mathematics will
be expanded upon in the next change, which will add
the multiplication, division and modulo operations.
This change also standardises the compiler and vm test
layouts to increase their readability.

Co-authored-by: joshcarp <[email protected]>
Co-authored-by: pgmitche <[email protected]>
Pull-request: #274
  • Loading branch information
3 people authored Feb 16, 2024
1 parent c27079a commit 29545f8
Show file tree
Hide file tree
Showing 6 changed files with 262 additions and 139 deletions.
24 changes: 21 additions & 3 deletions pkg/bytecode/code.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,23 @@ const (
// OpSetGlobal adds a symbol to the specified index in the symbol
// table.
OpSetGlobal
// OpAdd instructs the virtual machine to perform an addition.
OpAdd
// OpSubtract instructs the virtual machine to perform a subtraction.
OpSubtract
)

// ErrUnknownOp is returned when an unknown opcode is encountered.
var ErrUnknownOp = errors.New("unknown opcode")
var (
// ErrInternal and errors wrapping ErrInternal report internal
// errors of the VM that should not occur during normal
// program execution.
ErrInternal = errors.New("internal error")
// ErrPanic and errors wrapping ErrPanic report runtime errors, such
// as an index out of bounds or a stack overflow.
ErrPanic = errors.New("user error")
// ErrUnknownOpcode is returned when an unknown opcode is encountered.
ErrUnknownOpcode = fmt.Errorf("%w: unknown opcode", ErrInternal)
)

// definitions is a mapping of OpCode to OpDefinition.
var definitions = map[Opcode]*OpDefinition{
Expand All @@ -29,6 +42,11 @@ var definitions = map[Opcode]*OpDefinition{
OpConstant: {"OpConstant", []int{2}},
OpGetGlobal: {"OpGetGlobal", []int{2}},
OpSetGlobal: {"OpSetGlobal", []int{2}},
// Operations like OpAdd have no operand width because the virtual
// machine is expected to pop the values from the stack when reading
// this instruction.
OpAdd: {"OpAdd", nil},
OpSubtract: {"OpSubtract", nil},
}

// OpDefinition defines a name and expected operand width for each OpCode.
Expand Down Expand Up @@ -92,7 +110,7 @@ func ReadUint16(ins Instructions) uint16 {
func Lookup(op Opcode) (*OpDefinition, error) {
def, ok := definitions[op]
if !ok {
return nil, fmt.Errorf("%w: %d", ErrUnknownOp, op)
return nil, fmt.Errorf("%w: %d", ErrUnknownOpcode, op)
}
return def, nil
}
34 changes: 29 additions & 5 deletions pkg/bytecode/compiler.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
package bytecode

import (
"errors"
"fmt"

"evylang.dev/evy/pkg/parser"
)

// ErrUndefinedVar is returned when a variable name cannot
// be resolved in the symbol table.
var ErrUndefinedVar = errors.New("undefined variable")
var (
// ErrUndefinedVar is returned when a variable name cannot
// be resolved in the symbol table.
ErrUndefinedVar = fmt.Errorf("%w: undefined variable", ErrPanic)
// ErrUnknownOperator is returned when an operator cannot
// be resolved.
ErrUnknownOperator = fmt.Errorf("%w: unknown operator", ErrInternal)
)

// Compiler is responsible for turning a parsed evy program into
// bytecode.
Expand Down Expand Up @@ -43,10 +47,12 @@ func (c *Compiler) Compile(node parser.Node) error {
return c.compileDecl(node.Decl)
case *parser.AssignmentStmt:
return c.compileAssignment(node)
case *parser.BinaryExpression:
return c.compileBinaryExpression(node)
case *parser.Var:
return c.compileVar(node)
case *parser.NumLiteral:
num := &numVal{V: node.Value}
num := numVal(node.Value)
if err := c.emit(OpConstant, c.addConstant(num)); err != nil {
return err
}
Expand Down Expand Up @@ -86,6 +92,24 @@ func (c *Compiler) emit(op Opcode, operands ...int) error {
return nil
}

func (c *Compiler) compileBinaryExpression(expr *parser.BinaryExpression) error {
if err := c.Compile(expr.Left); err != nil {
return err
}
if err := c.Compile(expr.Right); err != nil {
return err
}
switch expr.Op {
case parser.OP_PLUS:
return c.emit(OpAdd)
case parser.OP_MINUS:
return c.emit(OpSubtract)
// more operators to follow (*, /, %).
default:
return fmt.Errorf("%w %s", ErrUnknownOperator, expr.Op)
}
}

func (c *Compiler) compileProgram(prog *parser.Program) error {
for _, s := range prog.Statements {
if err := c.Compile(s); err != nil {
Expand Down
88 changes: 0 additions & 88 deletions pkg/bytecode/compiler_test.go

This file was deleted.

25 changes: 8 additions & 17 deletions pkg/bytecode/value.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,29 +10,20 @@ type value interface {
Type() *parser.Type
Equals(value) bool
String() string
Set(value)
}

type numVal struct {
V float64
}

func (n *numVal) Type() *parser.Type { return parser.NUM_TYPE }
type numVal float64

func (n *numVal) String() string { return strconv.FormatFloat(n.V, 'f', -1, 64) }
func (n numVal) Type() *parser.Type { return parser.NUM_TYPE }

func (n *numVal) Equals(v value) bool {
n2, ok := v.(*numVal)
if !ok {
panic("internal error: Num.Equals called with non-Num value")
}
return n.V == n2.V
func (n numVal) String() string {
return strconv.FormatFloat(float64(n), 'f', -1, 64)
}

func (n *numVal) Set(v value) {
n2, ok := v.(*numVal)
func (n numVal) Equals(v value) bool {
n2, ok := v.(numVal)
if !ok {
panic("internal error: Num.Set called with with non-Num value")
panic("internal error: Num.Equals called with non-Num value")
}
*n = *n2
return n == n2
}
42 changes: 36 additions & 6 deletions pkg/bytecode/vm.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package bytecode

import (
"errors"
"fmt"
)

const (
Expand All @@ -13,7 +13,7 @@ const (
)

// ErrStackOverflow is returned when the stack exceeds its size limit.
var ErrStackOverflow = errors.New("stack overflow")
var ErrStackOverflow = fmt.Errorf("%w: stack overflow", ErrPanic)

// VM is responsible for executing evy programs from bytecode.
type VM struct {
Expand Down Expand Up @@ -48,21 +48,29 @@ func (vm *VM) Run() error {
case OpConstant:
constIndex := ReadUint16(vm.instructions[ip+1:])
ip += 2
err := vm.push(vm.constants[constIndex])
if err != nil {
if err := vm.push(vm.constants[constIndex]); err != nil {
return err
}
case OpGetGlobal:
globalIndex := ReadUint16(vm.instructions[ip+1:])
ip += 2
err := vm.push(vm.globals[globalIndex])
if err != nil {
if err := vm.push(vm.globals[globalIndex]); err != nil {
return err
}
case OpSetGlobal:
globalIndex := ReadUint16(vm.instructions[ip+1:])
ip += 2
vm.globals[globalIndex] = vm.pop()
case OpAdd:
right, left := vm.popBinaryNums()
if err := vm.push(numVal(left + right)); err != nil {
return err
}
case OpSubtract:
right, left := vm.popBinaryNums()
if err := vm.push(numVal(left - right)); err != nil {
return err
}
}
}
return nil
Expand Down Expand Up @@ -93,3 +101,25 @@ func (vm *VM) pop() value {
vm.sp--
return o
}

// popBinaryNums pops the top two elements of the stack (the left
// and right sides of the binary expressions) as nums and returns both.
func (vm *VM) popBinaryNums() (float64, float64) {
// the right was compiled last, so is higher on the stack
// than the left
right := vm.popNumVal()
left := vm.popNumVal()
return float64(right), float64(left)
}

// popNumVal pops an element from the stack and casts it to a num
// before returning the value. If elem is not a num it will error.
func (vm *VM) popNumVal() numVal {
elem := vm.pop()
val, ok := elem.(numVal)
if !ok {
panic(fmt.Errorf("%w: expected to pop numVal but got %s",
ErrInternal, elem.Type()))
}
return val
}
Loading

0 comments on commit 29545f8

Please sign in to comment.