Implement START and STOP

master
Jonas Franz 4 years ago
parent 2d3900728f
commit 65cd45f823
Signed by: JonasFranzDEV
GPG Key ID: 7293A220B7C38080
  1. 2
      example.hal
  2. 11
      hal/instructions.go
  3. 19
      hal/module.go
  4. 4
      parser/program_parser.go

@ -0,0 +1,2 @@
0 START
1 STOP

@ -1,7 +1,6 @@
package hal
import (
"fmt"
"strings"
)
@ -10,15 +9,14 @@ type ProgrammedInstruction struct {
Operand float64
}
func (pi *ProgrammedInstruction) Execute(module *Module) error {
func (pi *ProgrammedInstruction) Execute(module *Module) {
if pi.Instruction.ExecuteWithOperand != nil {
pi.Instruction.ExecuteWithOperand(module, pi.Operand)
} else if pi.Instruction.Execute != nil {
pi.Instruction.Execute(module)
} else {
return fmt.Errorf("instruction is not implemented")
panic("instruction is not implemented")
}
return nil
}
type Instruction struct {
@ -46,14 +44,15 @@ var instructions = []*Instruction{
var InstructionStart = &Instruction{
Name: "START",
Execute: func(module *Module) {
// TODO implement
// actually not required
module.isStopped = false
},
}
var InstructionStop = &Instruction{
Name: "STOP",
Execute: func(module *Module) {
// TODO implement
module.isStopped = true
},
}

@ -2,12 +2,15 @@ package hal
import "fmt"
const maxInstructions = 1000
type Program map[int64]*ProgrammedInstruction
type Module struct {
Accumulator float64
ProgramStorage Program
Register []float64
isStopped bool
}
func (h *Module) ProgramCounter() int64 {
@ -18,13 +21,23 @@ func (h *Module) increaseProgramCounter() {
h.Register[0]++
}
func (h *Module) Step() error {
func (h *Module) Step() {
instruction := h.ProgramStorage[h.ProgramCounter()]
h.increaseProgramCounter()
if instruction == nil {
return fmt.Errorf("instruction not found for program counter = %d", h.ProgramCounter())
return
}
instruction.Execute(h)
}
func (h *Module) Run() error {
for !h.isStopped && h.ProgramCounter() <= maxInstructions {
h.Step()
}
if h.ProgramCounter() > maxInstructions {
return fmt.Errorf("module exceeded max instructions without being stopped")
}
return instruction.Execute(h)
return nil
}
func NewHALModule(program Program, registerSize uint64) (*Module, error) {

@ -13,7 +13,7 @@ func ParseProgram(input []string) (hal.Program, error) {
program := make(hal.Program)
for index, line := range input {
args := strings.Split(line, " ")
if len(args) == 0 {
if len(args) <= 1 {
continue
}
lineNumber, err := strconv.ParseInt(args[0], 10, 64)
@ -39,7 +39,7 @@ func parseInstruction(args []string) (*hal.ProgrammedInstruction, error) {
programmedInstruction := &hal.ProgrammedInstruction{
Instruction: instruction,
}
if len(args) == 1 {
if len(args) == 2 {
operand, err := strconv.ParseFloat(args[1], 64)
if err != nil {
return nil, fmt.Errorf("error while parsing operand for instruction '%s': %v", args[0], err)

Loading…
Cancel
Save