zig0

my attempts at zig bootstrapping in C
Log | Files | Refs | README | LICENSE

zig0.c (1375B) - Raw


      1 #include "common.h"
      2 
      3 #include <stdbool.h>
      4 #include <stdio.h>
      5 #include <stdlib.h>
      6 
      7 // API:
      8 // - code = 0: program successfully terminated.
      9 // - code = 1: panicked, panic message in msg. Caller should free msg.
     10 // - code = 2: interpreter error, error in msg. Caller should free msg.
     11 static int zig0Run(const char* program, char** msg) {
     12     (void)program;
     13     (void)msg;
     14     return 0;
     15 }
     16 
     17 // API: run and:
     18 // code = 3: abnormal error, expect something in stderr.
     19 int zig0RunFile(const char* fname, char** msg) {
     20     FILE* f = fopen(fname, "r");
     21     if (f == NULL) {
     22         perror("fopen");
     23         return 3;
     24     }
     25     fseek(f, 0, SEEK_END);
     26     long fsizel = ftell(f);
     27     if (fsizel == -1) {
     28         perror("ftell");
     29         fclose(f);
     30         return 3;
     31     }
     32     unsigned long fsize = (unsigned long)fsizel;
     33     fseek(f, 0, SEEK_SET);
     34 
     35     char* program = malloc(fsize + 1);
     36     if (program == NULL) {
     37         perror("malloc");
     38         fclose(f);
     39         return 3;
     40     }
     41 
     42     size_t bytes_read = fread(program, 1, fsize, f);
     43     if (bytes_read < fsize) {
     44         if (ferror(f)) {
     45             perror("fread");
     46         } else {
     47             fprintf(stderr, "Unexpected end of file\n");
     48         }
     49         free(program);
     50         fclose(f);
     51         return 3;
     52     }
     53     fclose(f);
     54     program[fsize] = 0;
     55 
     56     int code = zig0Run(program, msg);
     57     free(program);
     58     return code;
     59 }