fix jmp illegal condition

This commit is contained in:
2024-01-20 04:35:16 +07:00
parent bbf055b7c7
commit 0a8f8dfb8d

14
elm.go
View File

@@ -139,7 +139,7 @@ func (m* Machine) Execute() error {
m.sp--
m.ip++
case JMP:
if (m.ip < instr.Operand || instr.Operand < 0) {
if (len(m.program) < instr.Operand || instr.Operand < 0) {
return errors.New("Illegal access")
}
@@ -149,7 +149,7 @@ func (m* Machine) Execute() error {
return errors.New("Stack Underflow")
}
if (m.ip < instr.Operand || instr.Operand < 0) {
if (len(m.program) <= instr.Operand || instr.Operand < 0) {
return errors.New("Illegal access")
}
@@ -184,20 +184,22 @@ func main() {
// m.Push(Inst{Operation: DIV})
// m.Push(Inst{Operation: HALT})
m.Push(Inst{Operation: PUSH, Operand: 0})
m.Push(Inst{Operation: PUSH, Operand: 1})
m.Push(Inst{Operation: ADD})
m.Push(Inst{Operation: JMP, Operand: 1})
m.Push(Inst{Operation: JMPIF, Operand: 3})
m.Push(Inst{Operation: HALT})
m.Push(Inst{Operation: PUSH, Operand: 1})
m.Push(Inst{Operation: PUSH, Operand: 2})
m.Push(Inst{Operation: HALT})
stackCounter := 0
for !m.isHalted && stackCounter < 69 {
m.Print()
err := m.Execute()
m.Print()
if err != nil {
fmt.Fprintf(os.Stderr, "[ERR] %s\n", err);
os.Exit(1)
}
stackCounter++
}