-
Notifications
You must be signed in to change notification settings - Fork 0
/
preprocess.c
97 lines (88 loc) · 2.53 KB
/
preprocess.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 <stdbool.h>
#include "stack.h"
int num_cols = 100;
int num_rows = 100;
void free_bi_array(BracketInfo **bi) {
for (int i = 0; i < num_rows; ++i) {
free(bi[i]);
bi[i] = NULL;
}
free(bi);
bi = NULL;
}
void free_preprocess_info(PreprocessInfo *preprocess_info) {
free_bi_array(preprocess_info->open_to_close);
free_bi_array(preprocess_info->close_to_open);
preprocess_info = NULL;
}
bool cmp_bracket_info(BracketInfo *me, BracketInfo *you) {
return (me->linenum == you->linenum && me->pos == you->pos);
}
PreprocessInfo* preprocess_file(char* input_file) {
FILE *fp;
fp = fopen(input_file, "r");
if (fp == NULL) {
printf("Unable to open file. exiting\n");
exit(1);
}
return preprocess(fp);
}
PreprocessInfo* preprocess(FILE *fp) {
Stack brackets;
init_stack(&brackets, 100);
BracketInfo **open_to_close = (BracketInfo**)malloc(sizeof(BracketInfo*) * num_rows);
for (int i = 0; i < num_rows; ++i) {
open_to_close[i] = (BracketInfo*)malloc(sizeof(BracketInfo) * num_cols);
}
BracketInfo **close_to_open = (BracketInfo**)malloc(sizeof(BracketInfo*) * num_rows);
for (int i = 0; i < num_rows; ++i) {
close_to_open[i] = (BracketInfo*)malloc(sizeof(BracketInfo) * num_cols);
}
char *line = NULL;
size_t linecap = 0;
ssize_t linelen;
char *tmp = NULL;
int linenum = 0;
int pos;
BracketInfo open_bi;
BracketInfo close_bi;
BracketInfo null_bi = {-1, -1};
while ((linelen = getline(&line, &linecap, fp)) > 0) {
tmp = line;
pos = 0;
while (*tmp != '\0') {
if (*tmp != '[' && *tmp != ']') {
tmp++;
pos++;
continue;
}
if (*tmp == '[') {
open_bi = (BracketInfo){linenum, pos};
push(&brackets, &open_bi);
} else {
open_bi = pop(&brackets);
if (cmp_bracket_info(&open_bi, &null_bi)) {
fprintf(stderr, "[ERROR] compiler error - bracket mismatch.\n");
return NULL;
}
close_bi = (BracketInfo){linenum, pos};
open_to_close[open_bi.linenum][open_bi.pos] = close_bi;
close_to_open[close_bi.linenum][close_bi.pos] = open_bi;
}
pos++;
tmp++;
}
linenum++;
}
if (!is_empty(&brackets)) {
fprintf(stderr, "[ERROR] compiler error - bracket mismatch.\n");
return NULL;
}
PreprocessInfo *preprocess_info = (PreprocessInfo*)malloc(sizeof(PreprocessInfo));
preprocess_info->open_to_close = open_to_close;
preprocess_info->close_to_open = close_to_open;
fclose(fp);
return preprocess_info;
}