school

thing1's amazing school repo
Log | Files | Refs | Submodules | README

parser.c (1925B)


      1 #include <stdio.h>
      2 #include <stdlib.h>
      3 #include <string.h>
      4 
      5 #include "../global/types.h"
      6 #include "../global/util.h"
      7 
      8 char *readFile(char *filename){
      9 	FILE *f = fopen(filename, "r");
     10 	if (f == NULL)
     11 		Die();	
     12 
     13 	fseek(f, 0, SEEK_END);
     14 	size_t len = ftell(f);
     15 	rewind(f);
     16 	
     17 	char *out = CheckedMalloc(len+1);
     18 
     19 	char c;
     20 	for (int i = 0; i < len; i++){
     21 		c = fgetc(f);	
     22 		if (c == '\n' || c == '\t')
     23 			out[i] = ' ';
     24 		else
     25 			out[i] = c;
     26 	}
     27 	out[len+1] = '\0';
     28 
     29 	fclose(f);
     30 	return out;
     31 }
     32 
     33 FILE *preProcess(char *contents){
     34 	int currentSize = strlen(contents)+1;
     35 	char *out = CheckedMalloc(currentSize);
     36 
     37 	FILE *tmp = fopen("/tmp/zpy.tmp", "w+");
     38 
     39 	for (char c = contents[0]; c != '\0'; c = (contents += 1)[0]){
     40 		if (c == '"'){
     41 			fprintf(tmp, "[");
     42 			c = (contents += 1)[0];
     43 			do {
     44 				fprintf(tmp, "'%c'", c);
     45 				if ((contents+1)[0] != '"') {
     46 					fprintf(tmp, ",");
     47 				}
     48 				c = (contents += 1)[0];
     49 			} while (c != '"');
     50 			c = (contents += 1)[0];
     51 			fprintf(tmp, "]");
     52 		}	
     53 		fprintf(tmp, "%c", c);
     54 	}
     55 	fprintf(tmp, "\n");
     56 	return tmp;
     57 }
     58 
     59 char **getExpressions(char *file){ // this doesn't work because str gets overwritten which changes the data stored at it's pointer, memcpy should be used
     60 	char **code = CheckedMalloc(strlen(file)/4);
     61 	int counter = 0;
     62 	int depth = 0;
     63 	char *str = CheckedMalloc(strlen(file)+1);
     64 	int pos = 0;
     65 	for (int i = 0; i < strlen(file); i++){
     66 		str[pos] = file[i];
     67 		pos++;
     68 		if (file[i] == '(')
     69 			depth++;
     70 		if (file[i] == ')')
     71 			depth--;
     72 
     73 		if (depth == 0) {
     74 			str[pos] = '\0';
     75 			printf("%s\n", str);
     76 			code[counter] = malloc(strlen(str)+1);
     77 			memcpy(code[counter], str, strlen((str)+1));
     78 			counter++;
     79 			pos = 0;
     80 		}
     81 	}
     82 	return code;
     83 	
     84 }
     85 
     86 char **parser(char *fileName){
     87 	FILE *tmp = preProcess(readFile(fileName));
     88 	fseek(tmp, 0, SEEK_END);
     89 	int len = ftell(tmp);
     90 	rewind(tmp);
     91 	char *buf = CheckedMalloc(len);
     92 	fgets(buf, len, tmp);
     93 	fclose(tmp);
     94 	return getExpressions(buf);
     95 }