aboutsummaryrefslogtreecommitdiff
path: root/src/bnf-preprocessor.c
blob: 67fafc7ec930c99f0e9938c0fd5b20944ee26abc (plain)
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
#include "bnf-preprocessor.h"
#include "string-builder.h"
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/mman.h>

struct preprocessor {
  struct {
    struct open_file {
      struct string_view sv;
      const char *filename;
      const char *cursor;
    } *items;
    uint32_t count;
    uint32_t capacity;
  } open_files;
  struct string_builder sb;
};

static const char import_cstr[] = "import";
static struct string_view import_sv = {
  .beg = import_cstr,
  .end = import_cstr + sizeof (import_cstr) - 1,
};


static void
preprocess_file (struct string_builder *sb, const char *filename)
{
  struct string_view file_contents;
  const char *cursor;

  int fd = open (filename, O_RDONLY);
  if (fd == -1) DIE ("error: %s: %s", strerror (errno), filename);

  struct stat st;
  fstat (fd, &st);
  cursor = file_contents.beg =
    mmap (NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
  close (fd);
  file_contents.end = file_contents.beg + st.st_size;
  DYNAMIC_ARRAY_ENSURE_CAPACITY (*sb, STRING_VIEW_LEN (file_contents));

  do {
    if (*cursor == '!') {
      cursor += 1;
      while (*cursor == ' ') cursor += 1;
      if ()
      while (*cursor != '\n') cursor += 1;
      cursor += 1;
      preprocess_file (sb, import_filename);
      continue;
    }

    DYNAMIC_ARRAY_APPEND_FAST (*sb, *cursor++);
  } while (1);

  munmap ((char *) file_contents.beg, STRING_VIEW_LEN (file_contents));
}

struct string_view
bnf_preprocess_file (const char *filename)
{
  struct string_builder sb = {0};

  preprocess_file (&sb, filename);

  struct string_view output = {
    .beg = sb.string,
    .end = sb.string + sb.count,
  };

  return output;
}