-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmachine.go
More file actions
57 lines (51 loc) · 1.21 KB
/
Copy pathmachine.go
File metadata and controls
57 lines (51 loc) · 1.21 KB
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
package main
import (
"fmt"
"os"
)
// Word is the machine's 16 bit data bus.
type Word int
// machineMemory is the number of words in the machine's 12-bit addressed memory.
const machineMemory = 1 << 12 // 4096
// Machine simulates a Marie machine. Most of the registers are not needed for the simulation,
// but they are added to illustrate the Marie machine described in the book.
type Machine struct {
AC Word
PC Word
MAR Word
MBR Word
IR Word
IN Word
OUT Word
M [machineMemory]Word
}
// Run starts execution of the program stored in the machine's memory.
func (m *Machine) Run() {
for {
m.MAR = m.PC
m.MBR = m.M[m.PC]
m.IR = m.MBR
m.PC++
opcode := Opcode(m.IR >> 12)
operand := m.IR & 0xFFF
instruction[opcode](m, operand)
}
}
// Load loads f to the machine's memory.
func (m *Machine) Load(f *os.File) error {
program, err := Assemble(f)
switch err := err.(type) {
case nil:
case SyntaxError:
return fmt.Errorf("syntax: %s:%d: %s\n", f.Name(), err.lineNo, err.line)
default:
return fmt.Errorf("%v", err)
}
if len(program) >= machineMemory {
return fmt.Errorf("program too long: %d/%d instructions", len(program), machineMemory)
}
for i, w := range program {
m.M[i] = w
}
return nil
}