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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
|
/// src/parse.h
//
// Copyright (C) 2026 by Martin Michalec <martin@michalec.dev>
//
// SPDX-License-Identifier: MIT
//
/// Commentary:
//
/// Code:
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include "utils.h"
#include "arena.h"
#include "sv.h"
#include "rs274ngc_lexer.h"
#include "rs274ngc_cst.h"
#define INDENTATION 2
void
print_cst (struct arena *temp, struct rs274ngc_lexer *lexer, struct rs274ngc_cst_branch *root, size_t alignment)
{
void *bottom = ARENA_COPY (temp, root);
ARENA_COPY (temp, alignment);
while (temp->tail->free != bottom) {
alignment = *(size_t *) arena_pop (temp, sizeof (alignment));
void *node = *(void **) arena_pop (temp, sizeof (node ));
ASSERT (node);
if (RS274NGC_CST_NODE_KIND (node) < RS274NGC_CST_TERMINAL_COUNT) { // leaf
struct rs274ngc_cst_leaf *leaf = &RS274NGC_CST_NODE_PTR (node)->leaf;
struct location location = find_location (lexer->sv, leaf->sv);
print_location (lexer->filename, location, alignment, "- leaf: %s",
rs274ngc_cst_node_kind_names[RS274NGC_CST_NODE_KIND (node)]);
} else { // branch
struct rs274ngc_cst_branch *branch = &RS274NGC_CST_NODE_PTR (node)->branch;
if (1 || RS274NGC_CST_NODE_KIND_EQ (node, LINE)) {
struct location location = find_location (lexer->sv, branch->sv);
print_location (lexer->filename, location, alignment, "- branch: %s",
rs274ngc_cst_node_kind_names[RS274NGC_CST_NODE_KIND (node)]);
}
alignment += INDENTATION;
for (size_t i = branch->count; i > 0; --i) {
ASSERT (branch->children[i - 1]);
ARENA_COPY (temp, branch->children[i - 1]);
ARENA_COPY (temp, alignment);
}
}
}
}
int
main (int argc, char *argv[])
{
progname = argv[0];
const char *filename;
int fd = 0;
if (argc == 1) {
filename = "-";
} else if (argc == 2) {
filename = argv[1];
fd = open (filename, O_RDONLY);
} else {
DIE ("too many arguments provided");
}
struct arena a = {0};
struct arena t = {0};
struct sv rs274ngc = read_until_eof (&a, fd);
if (fd) close (fd);
int base_alignment = strlen (filename) + 15;
rs274ngc_lexer_compile_regexes ();
struct rs274ngc_lexer lexer = rs274ngc_lexer_from_sv (rs274ngc, filename);
struct rs274ngc_cst_parser parser = {
.lexer = &lexer,
.output = &a,
.temporary = &t,
};
struct rs274ngc_cst_branch *program = &RS274NGC_CST_PARSE (parser, PROGRAM)->branch;
// ensure no memory leaked
ASSERT (t.head == t.tail );
ASSERT (t.head->free == t.head->begin);
printf ("Memory used %lu\n", arena_used (parser.output));
print_cst (&t, &lexer, program, base_alignment);
return EXIT_SUCCESS;
}
/// src/parse.h ends here
|