-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
77 lines (59 loc) · 1.84 KB
/
main.go
File metadata and controls
77 lines (59 loc) · 1.84 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package main
import (
"fmt"
"os"
)
func main() {
// Create a new CPU instance
cpu := NewCPU()
cpu.Debug = true
// Example program: Calculate factorial of 5
// This program demonstrates:
// - Loading immediate values
// - Arithmetic operations (multiplication)
// - Conditional jumps
// - Memory operations
program := []byte{
// LOADI R0, 5 ; R0 = 5 (number to calculate factorial of)
byte(OpLOADI), 0, 0x00, 0x05,
// LOADI R1, 1 ; R1 = 1 (result accumulator)
byte(OpLOADI), 1, 0x00, 0x01,
// LOADI R2, 1 ; R2 = 1 (decrement value)
byte(OpLOADI), 2, 0x00, 0x01,
// loop: (address 0x000C)
// MUL R1, R1, R0 ; R1 = R1 * R0
byte(OpMUL), 1, 1, 0,
// SUB R0, R0, R2 ; R0 = R0 - 1
byte(OpSUB), 0, 0, 2,
// JZ R0, end ; if R0 == 0, jump to end (address 0x001C)
byte(OpJZ), 0, 0x00, 0x1C,
// JMP loop ; jump to loop (address 0x000C)
byte(OpJMP), 0x00, 0x0C, 0x00,
// end: (address 0x001C)
// STORE R1, 0x1000 ; Store result at memory address 0x1000
byte(OpSTORE), 1, 0x10, 0x00,
// HALT
byte(OpHALT), 0, 0, 0,
}
// Load the program into memory
cpu.LoadProgram(program)
fmt.Println("=== Go Micro ISA Emulator ===")
fmt.Println("\nExample Program: Calculate 5!")
fmt.Println("\nExecution trace:")
fmt.Println("--------------------------------------------------")
// Run the program
err := cpu.Run()
if err != nil {
fmt.Printf("Error during execution: %v\n", err)
os.Exit(1)
}
fmt.Println("--------------------------------------------------")
fmt.Println("\nExecution completed successfully!")
fmt.Println()
// Display final register state
cpu.DumpRegisters()
// Read and display the result from memory
result := cpu.ReadMemory32(0x1000)
fmt.Printf("\nResult stored at memory[0x1000]: %d\n", result)
fmt.Printf("Expected: 120 (5! = 5 × 4 × 3 × 2 × 1)\n")
}