functions with bindings
This commit is contained in:
13
code/code.go
13
code/code.go
@@ -35,6 +35,8 @@ const (
|
||||
OpCall
|
||||
OpReturnValue
|
||||
OpReturn
|
||||
OpGetLocal
|
||||
OpSetLocal
|
||||
)
|
||||
|
||||
type Definition struct {
|
||||
@@ -67,6 +69,8 @@ var definitions = map[Opcode]*Definition{
|
||||
OpCall: {"OpCall", []int{}},
|
||||
OpReturnValue: {"OpReturnValue", []int{}},
|
||||
OpReturn: {"OpReturn", []int{}},
|
||||
OpGetLocal: {"OpGetLocal", []int{1}},
|
||||
OpSetLocal: {"OpSetLocal", []int{1}},
|
||||
}
|
||||
|
||||
func Lookup(op byte) (*Definition, error) {
|
||||
@@ -98,6 +102,8 @@ func Make(op Opcode, operands ...int) []byte {
|
||||
switch width {
|
||||
case 2:
|
||||
binary.BigEndian.PutUint16(instruction[offset:], uint16(o))
|
||||
case 1:
|
||||
instruction[offset] = byte(o)
|
||||
}
|
||||
offset += width
|
||||
}
|
||||
@@ -151,6 +157,9 @@ func ReadOperands(def *Definition, ins Instructions) ([]int, int) {
|
||||
switch width {
|
||||
case 2:
|
||||
operands[i] = int(ReadUint16(ins[offset:]))
|
||||
case 1:
|
||||
operands[i] = int(ReadUint8(ins[offset:]))
|
||||
|
||||
}
|
||||
|
||||
offset += width
|
||||
@@ -162,3 +171,7 @@ func ReadOperands(def *Definition, ins Instructions) ([]int, int) {
|
||||
func ReadUint16(ins Instructions) uint16 {
|
||||
return binary.BigEndian.Uint16(ins)
|
||||
}
|
||||
|
||||
func ReadUint8(ins Instructions) uint8 {
|
||||
return ins[0]
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ func TestMake(t *testing.T) {
|
||||
}{
|
||||
{OpConstant, []int{65534}, []byte{byte(OpConstant), 255, 254}},
|
||||
{OpAdd, []int{}, []byte{byte(OpAdd)}},
|
||||
{OpGetLocal, []int{255}, []byte{byte(OpGetLocal), 255}},
|
||||
}
|
||||
|
||||
for _, tt := range test {
|
||||
@@ -30,13 +31,15 @@ func TestMake(t *testing.T) {
|
||||
func TestInstructions(t *testing.T) {
|
||||
instructions := []Instructions{
|
||||
Make(OpAdd),
|
||||
Make(OpGetLocal, 1),
|
||||
Make(OpConstant, 2),
|
||||
Make(OpConstant, 65535),
|
||||
}
|
||||
|
||||
expected := `0000 OpAdd
|
||||
0001 OpConstant 2
|
||||
0004 OpConstant 65535
|
||||
0001 OpGetLocal 1
|
||||
0003 OpConstant 2
|
||||
0006 OpConstant 65535
|
||||
`
|
||||
|
||||
concatted := Instructions{}
|
||||
@@ -49,13 +52,14 @@ func TestInstructions(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestOperands(t *testing.T) {
|
||||
func TestReadOperands(t *testing.T) {
|
||||
tests := []struct {
|
||||
op Opcode
|
||||
operands []int
|
||||
bytesRead int
|
||||
}{
|
||||
{OpConstant, []int{65535}, 2},
|
||||
{OpGetLocal, []int{255}, 1},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
|
||||
Reference in New Issue
Block a user