aboutsummaryrefslogtreecommitdiff
path: root/src/bnf-preprocessor.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/bnf-preprocessor.c')
-rw-r--r--src/bnf-preprocessor.c76
1 files changed, 76 insertions, 0 deletions
diff --git a/src/bnf-preprocessor.c b/src/bnf-preprocessor.c
new file mode 100644
index 0000000..67fafc7
--- /dev/null
+++ b/src/bnf-preprocessor.c
@@ -0,0 +1,76 @@
1#include "bnf-preprocessor.h"
2#include "string-builder.h"
3#include <errno.h>
4#include <fcntl.h>
5#include <unistd.h>
6#include <sys/stat.h>
7#include <sys/mman.h>
8
9struct preprocessor {
10 struct {
11 struct open_file {
12 struct string_view sv;
13 const char *filename;
14 const char *cursor;
15 } *items;
16 uint32_t count;
17 uint32_t capacity;
18 } open_files;
19 struct string_builder sb;
20};
21
22static const char import_cstr[] = "import";
23static struct string_view import_sv = {
24 .beg = import_cstr,
25 .end = import_cstr + sizeof (import_cstr) - 1,
26};
27
28
29static void
30preprocess_file (struct string_builder *sb, const char *filename)
31{
32 struct string_view file_contents;
33 const char *cursor;
34
35 int fd = open (filename, O_RDONLY);
36 if (fd == -1) DIE ("error: %s: %s", strerror (errno), filename);
37
38 struct stat st;
39 fstat (fd, &st);
40 cursor = file_contents.beg =
41 mmap (NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
42 close (fd);
43 file_contents.end = file_contents.beg + st.st_size;
44 DYNAMIC_ARRAY_ENSURE_CAPACITY (*sb, STRING_VIEW_LEN (file_contents));
45
46 do {
47 if (*cursor == '!') {
48 cursor += 1;
49 while (*cursor == ' ') cursor += 1;
50 if ()
51 while (*cursor != '\n') cursor += 1;
52 cursor += 1;
53 preprocess_file (sb, import_filename);
54 continue;
55 }
56
57 DYNAMIC_ARRAY_APPEND_FAST (*sb, *cursor++);
58 } while (1);
59
60 munmap ((char *) file_contents.beg, STRING_VIEW_LEN (file_contents));
61}
62
63struct string_view
64bnf_preprocess_file (const char *filename)
65{
66 struct string_builder sb = {0};
67
68 preprocess_file (&sb, filename);
69
70 struct string_view output = {
71 .beg = sb.string,
72 .end = sb.string + sb.count,
73 };
74
75 return output;
76}