-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.c
153 lines (128 loc) · 2.37 KB
/
main.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
#include "interpret-bf.h"
int main(int argv, char *argc[]) {
cell_n = 0;
pc = 0;
if(argv < 2)
die(USAGE_MSG, stderr);
// TODO: add more arguments
cell = (CELL_TYPE *)calloc(N_OF_CELLS, sizeof(CELL_TYPE));
if(cell == (CELL_TYPE *)NULL)
die("Memory allocation failed:");
fname = (char *)malloc(1096);
if(fname == (char *)NULL)
die("Memory allocation failed:");
strcpy(fname, argc[argv-1]);
if(!realloc(fname, strlen(fname)))
die("Reallocation failed:");
FILE *fp;
fp = fopen(fname, "r");
if(fp == (FILE *)NULL)
die("Failed to open file \"%s\":", fname);
remove_extra_chars(fp);
fclose(fp);
while(*(program+pc) != NULL) {
interpret_command();
pc++;
}
return 0;
}
void remove_extra_chars(FILE *fp) { // TODO: rename this function
char ch;
uint32_t i;
line_n = 1;
i = 0;
while((ch = fgetc(fp)) != EOF)
switch(ch) {
case '<':
case '>':
case '+':
case '-':
case '.':
case ',':
case '[':
case ']':
case '\n':
i++;
default:
break;
}
program = (char *)malloc(i * sizeof(CELL_TYPE));
if(program == NULL)
die("Memory allocation failed:");
i = 0;
rewind(fp);
while((ch = fgetc(fp)) != EOF)
switch(ch) {
case '<':
case '>':
case '+':
case '-':
case '.':
case ',':
case '[':
case ']':
case '\n':
*(program+i++) = ch;
default:
break;
}
}
void interpret_command(void) {
uint32_t l, endl;
switch(*(program+pc)) {
case '>':
if(cell_n >= N_OF_CELLS)
die(DEFAULT_ERROR_MSG, line_n, CELL_NOT_ACCESSIBLE_MSG);
++cell_n;
break;
case '<':
if(cell_n <= 0)
die(DEFAULT_ERROR_MSG, line_n, CELL_NOT_ACCESSIBLE_MSG);
--cell_n;
break;
case '+':
++*(cell+cell_n);
break;
case '-':
--*(cell+cell_n);
break;
case '.':
putchar(*(cell+cell_n));
break;
case ',':
fscanf(stdin, "%c", (cell+cell_n));
break;
case '[':
l = ++pc;
endl = get_end_of_loop();
while(true) {
if(!(*(cell+cell_n)))
break;
for(pc = l; pc < endl; pc++) {
interpret_command();
}
}
break;
case '\n':
line_n++;
break;
default:
break;
}
}
uint32_t get_end_of_loop(void) {
while(true) {
if(*(program+pc) == NULL)
die(DEFAULT_ERROR_MSG, line_n, MISMATCHED_BRACKETS_MSG);
if(*(program+pc) == ']')
break;
else if(*(program+pc) == '[') {
pc++;
get_end_of_loop();
pc++;
}
else
pc++;
}
return pc;
}