|
| 1 | +#include <stdio.h> |
1 | 2 | #include "emulator.h" |
2 | | -#include "opcode.h" |
3 | 3 |
|
4 | | -void emulator_execute(Word memory[]) |
| 4 | +enum Opcode |
5 | 5 | { |
6 | | - Word* instruction = memory; |
| 6 | + OPCODE_ADD = 1, |
| 7 | + OPCODE_MULTIPLY = 2, |
| 8 | + OPCODE_INPUT = 3, |
| 9 | + OPCODE_OUTPUT = 4, |
| 10 | + OPCODE_TERMINATE = 99 |
| 11 | +}; |
| 12 | + |
| 13 | +typedef enum Opcode Opcode; |
| 14 | + |
| 15 | +Word emulator_load(Emulator instance, Word* instruction, int slot) |
| 16 | +{ |
| 17 | + int denominator = 100; |
| 18 | + |
| 19 | + for (int i = 0; i < slot - 1; i++) |
| 20 | + { |
| 21 | + denominator *= 10; |
| 22 | + } |
| 23 | + |
| 24 | + Word value = instruction[slot]; |
| 25 | + |
| 26 | + if ((*instruction / denominator) % 10 == 0) |
| 27 | + { |
| 28 | + return instance->memory[value]; |
| 29 | + } |
| 30 | + |
| 31 | + return value; |
| 32 | +} |
| 33 | + |
| 34 | +void emulator_execute(Emulator instance) |
| 35 | +{ |
| 36 | + Word* instruction = instance->memory; |
7 | 37 |
|
8 | 38 | for (;;) |
9 | 39 | { |
10 | | - switch (*instruction) |
| 40 | + Opcode opcode = *instruction % 100; |
| 41 | + |
| 42 | + switch (opcode) |
11 | 43 | { |
12 | 44 | case OPCODE_ADD: |
13 | 45 | { |
14 | | - Word* a = memory + instruction[1]; |
15 | | - Word* b = memory + instruction[2]; |
16 | | - Word* result = memory + instruction[3]; |
| 46 | + Word a = emulator_load(instance, instruction, 1); |
| 47 | + Word b = emulator_load(instance, instruction, 2); |
| 48 | + Word* result = instance->memory + instruction[3]; |
17 | 49 |
|
18 | | - *result = *a + *b; |
| 50 | + *result = a + b; |
19 | 51 | instruction += 4; |
20 | 52 | } |
21 | 53 | break; |
22 | 54 |
|
23 | 55 | case OPCODE_MULTIPLY: |
24 | 56 | { |
25 | | - Word* a = memory + instruction[1]; |
26 | | - Word* b = memory + instruction[2]; |
27 | | - Word* result = memory + instruction[3]; |
| 57 | + Word a = emulator_load(instance, instruction, 1); |
| 58 | + Word b = emulator_load(instance, instruction, 2); |
| 59 | + Word* result = instance->memory + instruction[3]; |
28 | 60 |
|
29 | | - *result = *a * *b; |
| 61 | + *result = a * b; |
30 | 62 | instruction += 4; |
31 | 63 | } |
32 | 64 | break; |
33 | 65 |
|
| 66 | + case OPCODE_INPUT: |
| 67 | + { |
| 68 | + Word* result = instance->memory + instruction[1]; |
| 69 | + |
| 70 | + if (scanf(WORD_FORMAT, result) != 1) |
| 71 | + { |
| 72 | + return; |
| 73 | + } |
| 74 | + |
| 75 | + instruction += 2; |
| 76 | + } |
| 77 | + break; |
| 78 | + |
| 79 | + case OPCODE_OUTPUT: |
| 80 | + { |
| 81 | + Word value = emulator_load(instance, instruction, 1); |
| 82 | + |
| 83 | + printf(WORD_FORMAT "\n", value); |
| 84 | + |
| 85 | + instruction += 2; |
| 86 | + } |
| 87 | + break; |
| 88 | + |
34 | 89 | case OPCODE_TERMINATE: return; |
35 | 90 | } |
36 | 91 | } |
|
0 commit comments