More private members

This commit is contained in:
Ian Gulliver
2021-11-16 15:27:30 -10:00
parent f39a856361
commit 7ab0aba088
3 changed files with 32 additions and 20 deletions

View File

@@ -5,18 +5,18 @@ import "bytes"
import "github.com/lunixbochs/struc"
import "github.com/pkg/errors"
const InstructionBytes = 32
type Instruction struct {
OpCode OpCodeType
Reserved [4]byte
Operand1 Operand
Operand2 Operand
opHandler OpHandler `struc:"skip"`
opHandler opHandler `struc:"skip"`
}
func NewInstruction(byteCode []byte) (*Instruction, error) {
const instructionBytes = 32
func NewInstructionFromByteCode(byteCode []byte) (*Instruction, error) {
instr := &Instruction{}
reader := bytes.NewReader(byteCode)
@@ -28,3 +28,25 @@ func NewInstruction(byteCode []byte) (*Instruction, error) {
return instr, nil
}
func NewInstructionsFromByteCode(byteCode []byte) ([]*Instruction, error) {
instrs := []*Instruction{}
for start := 0; start < len(byteCode); start += instructionBytes {
chunk := byteCode[start : start+instructionBytes]
instr, err := NewInstructionFromByteCode(chunk)
if err != nil {
return nil, errors.Wrapf(err, "At byte offset %d", start)
}
instrs = append(instrs, instr)
}
if len(instrs) == 0 || instrs[len(instrs)-1].OpCode != OpReturn {
// Add implicit return at the end of each function
instrs = append(instrs, &Instruction{
OpCode: OpReturn,
})
}
return instrs, nil
}