-
Notifications
You must be signed in to change notification settings - Fork 0
/
MIXsim.c
97 lines (84 loc) · 2.46 KB
/
MIXsim.c
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "mix_instr_decode.h"
#include "mix_machine.h"
#include "mix_word.h"
static void print_instr_callback(int ip, const mix_word *instr) {
char mix_instr_text[100];
fprintf(stderr, "Running instr %d: ", ip);
if (mix_instr_decode(instr, mix_instr_text) == NULL) {
fprintf(stderr, "Could not decode instruction %s\n", mix_word_tostring(instr));
} else {
fprintf(stderr, "%s\n", mix_instr_text);
}
}
int main (int argc, char * argv[]) {
mix_machine *m;
char readbuf[500];
int ip;
int i = 0;
int loc;
mix_word w;
int ret;
FILE *infile = stdin;
int debugflag = 0;
int ch;
while ((ch = getopt(argc, argv, "df:")) != -1) {
switch (ch) {
case 'd':
debugflag = 1;
break;
case 'f':
infile = fopen(optarg, "r");
break;
case '?':
default:
exit(EXIT_FAILURE);
}
}
// argc -= optind;
// argv += optind;
/* create new machine */
m = mix_machine_create();
mix_machine_device_attach(m, mix_device_printer_create(), 18);
if (debugflag == 1)
mix_machine_set_callback_exec(m, print_instr_callback);
/* read start line and set Ip */
if (fgets(readbuf, 500, infile) != NULL) {
sscanf(readbuf, "START: %d\n", &ip);
} else {
return -1;
}
mix_machine_set_ip(m, ip);
/* for each remaining line */
while (fgets(readbuf, 500, infile) != NULL) {
if (readbuf[4] != ':') {
continue;
}
readbuf[4] = '\0';
loc = atoi(readbuf);
mix_word_set(&w, &(readbuf[6]));
mix_machine_load_mem(m, &w, loc);
i++;
}
printf("Locations loaded: %d\n", i);
printf("Starting instruction: %d\n", ip);
do {
ret = mix_machine_execute(m);
} while (ret == MIX_M_OK);
if (ret == MIX_M_HALT) {
printf("Program halted!\n");
} else {
switch (ret) {
case MIX_M_UNIMPLEMENTED:
printf("Unimplemented instruction!\n");
break;
default:
printf("Machine aborted!\n");
}
printf("Instruction was %s\n", mix_word_tostring(mix_machine_read_mem(m, &w, mix_machine_get_ip(m))));
}
printf("Time elapsed = %d\n", mix_machine_get_time(m));
return 0;
}