-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
81 lines (70 loc) · 1.43 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package main
import (
"fmt"
)
//3 since our instructions are
//not going to have more than 3 args
//in our simple addition program below
type instruction [3]interface{}
type instructions []instruction
//simple addition program
//push number 5 to the stack
//prog[0] = instruction{"PSH", 5}
//push number 6 to the stack
//prog[1] = instruction{"PSH", 6}
//add the values in stack
//prog[2] = instruction{"ADD"}
//pop the value from stack
//prog[3] = instruction{"POP"}
//halt the system
//prog[4] = instruction{"HLT"}
var prog = instructions{
instruction{"PSH", 5},
instruction{"PSH", 6},
instruction{"ADD"},
instruction{"POP"},
instruction{"HLT"},
}
var stack [256]int
var sp int = 0
//Set running to true
var running = true
var ip = 0
//program [256]instructions, ip int
func fetch() instruction {
// return ipth instruction of program
return prog[ip]
}
func evalinstr(running *bool, instr instruction) {
//
switch instr[0] {
case "PSH":
//push value to the stack
tmp := instr[1].(int)
stack[sp] = tmp
sp++
case "ADD":
//add the values in stack
a := stack[sp-2]
b := stack[sp-1]
result := a + b
sp++
stack[sp] = result
sp++
case "POP":
//pop the value from stack
tmp := stack[sp-1]
fmt.Println(tmp)
case "HLT":
//halt the system
fmt.Println("HLT: system halted!")
*running = false
}
}
func main() {
fmt.Println("Starting emulation")
for running == true {
evalinstr(&running, fetch())
ip++
}
}