From 99cf6e8eca2e3d29874b8b80e8c4312cd1bc87ba Mon Sep 17 00:00:00 2001 From: dx Date: Fri, 22 May 2020 19:13:15 +0100 Subject: ~compile_lines -> compile_file, shuffle I've redid the compiler to use a FILE object pointer, which means that we can leave error checking for FILES on the main program. Furthermore, I've removed the use of the array_t type with a two pass system. One pass is done for the number of lines (along with potentially other diagnostics), another is done for the actual compilation. This means at runtime we have an understanding about the size of the file and can optimize for it. Also, we have a single memory block to assign to, where we know the size of the array. --- Converter/src/compiler.c | 51 ++++++++++++++++++++++++++++++++---------------- 1 file changed, 34 insertions(+), 17 deletions(-) (limited to 'Converter/src') diff --git a/Converter/src/compiler.c b/Converter/src/compiler.c index ddbe6ff..04e97e7 100644 --- a/Converter/src/compiler.c +++ b/Converter/src/compiler.c @@ -1,6 +1,5 @@ #include "../includes/compiler.h" #include "../includes/array.h" -#include #include int find_string(string src, string query, size_t sz_src, size_t sz_query) @@ -115,7 +114,7 @@ void compile_inner_text(string dest, string src, size_t sz_src, else { // error, no matching asterisk - fprintf(stderr, "No corresponding %s for %s:%d\n", md_tag, + fprintf(stderr, "No corresponding %s for %s:%lu\n", md_tag, line_or_source, i + md_tag_size); exit(0); } @@ -191,31 +190,49 @@ string compile_line(string line, size_t size_of_line, string line_or_source) return compiled_line; } -char **get_lines(char *filename) +int nlines(FILE *fp) { - FILE *fp; - char **lines, *line; - array_t *arr; - int i; + fseek(fp, 0, SEEK_SET); + int line_number = 0; + char ch; - array_init(arr); + while (!feof(fp)) + { + if (ch == '\n') + ++line_number; + ch = fgetc(fp); + } + return line_number; +} + +string *compile_file(FILE *fp, string filename, int nlines) +{ + fseek(fp, 0, SEEK_SET); + string current_header, compiled_line, line, *lines; + int i, line_num; + size_t sz_filename; + + current_header = malloc(sizeof(*current_header) * sz_filename); + strcpy(current_header, filename); - fp = fopen(filename, "r"); + sz_filename = strlen(filename); + lines = malloc(sizeof(*lines) * nlines); - while(!feof(fp)) + for (line_num = 1; (line_num - 1) < nlines; ++line_num) { - // Get line line = malloc(sizeof(*line) * 1024); fgets(line, 1024, fp); - // Terminate line - for (i = 0; line[i] != '\n'; ++i); + // Null terminate line + for (i = 0; line[i] != '\n' && line[i] != '\0'; ++i) + ; line[i] = '\0'; - array_append(arr, line); - } + sprintf(current_header + sz_filename, ":%d", line_num); - lines = (char**)arr->data; - free(arr); + // Compile and append line + compiled_line = compile_line(line, strlen(line), current_header); + lines[line_num - 1] = compiled_line; + } return lines; } -- cgit v1.2.3-13-gbd6f