11//
2- // This is a simple port of the virtual machine to golang
2+ // This is a simple port of the virtual machineinterpreter to golang.
33//
4- // It is not complete, because it only operates upon some of the examples.
5- //
6- // For example the loop script:
4+ // For example the loop script could be compiled to bytecode like this:
75//
86// ./compiler examples/loop.in
9- // go run main.go examples/loop.raw
10- //
11- // And the jumping script:
127//
13- // ./compiler examples/jump.in
14- // go run main.go examples/jump.raw
8+ // Once that has been done it can be executed:
159//
16- // Still it shows how you could "port" this software, if you had a pressing
17- // need for a Golang based VM.
10+ // go run main.go examples/loop.raw
1811//
1912// Steve
2013// --
@@ -34,7 +27,7 @@ import (
3427"time"
3528)
3629
37- // Flags holds the CPU flags.
30+ // Flags holds the CPU flags - of which we only have one .
3831type Flags struct {
3932// Zero-flag
4033z bool
@@ -83,7 +76,7 @@ type CPU struct {
8376// Global functions
8477//
8578
86- // debugPrintf outputs some debugging details `$DEBUG=1`.
79+ // debugPrintf outputs some debugging detailswhen `$DEBUG=1`.
8780func debugPrintf (fmt_ string ,args ... interface {}) {
8881if os .Getenv ("DEBUG" )== "" {
8982return
@@ -93,7 +86,7 @@ func debugPrintf(fmt_ string, args ...interface{}) {
9386}
9487
9588// Split a line of text into tokens, but keep anything "quoted"
96- // together..
89+ // together.
9790//
9891// So this input:
9992//
@@ -204,22 +197,28 @@ func (s *Stack) Pop() int {
204197// CPU / VM functions
205198//
206199
207- // NewCPU returns a new CPU object
200+ // NewCPU returns a new CPU object.
208201func NewCPU ()* CPU {
209202x := & CPU {}
203+ x .Reset ()
204+ return x
205+ }
206+
207+ // Reset sets the CPU into a known-good state, by setting the IP to zero,
208+ // and emptying all registers (i.e. setting them to zero too.)
209+ func (c * CPU )Reset () {
210210for i := 0 ;i < 16 ;i ++ {
211- x .regs [i ].SetInt (0 )
211+ c .regs [i ].SetInt (0 )
212212}
213- x .ip = 0
214- x .stack = NewStack ()
215- return x
213+ c .ip = 0
214+ c .stack = NewStack ()
216215}
217216
218- // Load opens the named program andloads it
217+ // Load opens the named program andexecutes it.
219218func (c * CPU )Load (path string ) {
220219
221220// Ensure we reset our state.
222- c .ip = 0
221+ c .Reset ()
223222
224223// Load the file
225224b ,err := ioutil .ReadFile (path )