commit 0496419
uint
·
2026-10-24 18:46:28 +0000 UTC
parent feb1232
Simplify parser macros
1 files changed,
+20,
-18
M
expl.c
M
expl.c
+20,
-18
1@@ -5,10 +5,12 @@
2
3 #include "expl.h"
4
5-#define current_char(p, c) ((p)->src[(p)->pos] == (c))
6-#define advance(p) ((p)->pos++)
7-#define pos(p) ((p)->pos)
8-#define peek(p) ((p)->src[(p)->pos + 1])
9+#define current(p) ((p)->src[(p)->pos])
10+#define peek(p) ((p)->src[(p)->pos + 1])
11+#define is(p, c) (current(p) == (c))
12+#define end(p) (is(p, '\0'))
13+#define advance(p) ((p)->pos++)
14+#define length(p, s) ((p)->pos - (s))
15
16 typedef enum {
17 EXPRESSION_TYPE_ATOM,
18@@ -98,7 +100,7 @@ static expression*
19 parse_expression(parser* p)
20 {
21 skip_space(p);
22- switch (p->src[p->pos]) {
23+ switch (current(p)) {
24 case '"':
25 return value(p, EXPRESSION_TYPE_STRING);
26 case '(':
27@@ -129,7 +131,7 @@ list(parser* p)
28 next = &node->child;
29
30 skip_space(p);
31- while (!current_char(p, ')') && !current_char(p, '\0')) {
32+ while (!is(p, ')') && !end(p)) {
33 *next = parse_expression(p);
34 if (!*next) {
35 free_node(node);
36@@ -140,7 +142,7 @@ list(parser* p)
37 skip_space(p);
38 }
39
40- if (current_char(p, '\0')) {
41+ if (end(p)) {
42 p->err = EXPL_ERR_EXPECTED_LIST;
43 free_node(node);
44 return NULL;
45@@ -174,7 +176,7 @@ parse(const char* source)
46 p.src = source;
47
48 skip_space(&p);
49- while (!current_char(&p, '\0')) {
50+ while (!end(&p)) {
51 *next = parse_expression(&p);
52 if (!*next) {
53 free_node(head);
54@@ -200,21 +202,21 @@ value(parser* p, expression_type type)
55 start = p->pos;
56
57 if (type == EXPRESSION_TYPE_STRING) {
58- while (!current_char(p, '"') && !current_char(p, '\0')) {
59- if (current_char(p, '\\') && p->src[p->pos + 1])
60+ while (!is(p, '"') && !end(p)) {
61+ if (is(p, '\\') && peek(p))
62 advance(p);
63 advance(p);
64 }
65
66- if (current_char(p, '\0')) {
67+ if (end(p)) {
68 p->err = EXPL_ERR_EXPECTED_STRING;
69 return NULL;
70 }
71 }
72 else {
73- while (p->src[p->pos] &&
74- !strchr("();\"", p->src[p->pos]) &&
75- !isspace((unsigned char)p->src[p->pos]))
76+ while (!end(p) &&
77+ !strchr("();\"", current(p)) &&
78+ !isspace((unsigned char)current(p)))
79 advance(p);
80 }
81
82@@ -229,7 +231,7 @@ value(parser* p, expression_type type)
83 return NULL;
84 }
85
86- node->value = _strndup(p->src + start, p->pos - start);
87+ node->value = _strndup(p->src + start, length(p, start));
88 if (!node->value) {
89 free_node(node);
90 p->err = EXPL_ERR_OUT_OF_MEMORY;
91@@ -418,10 +420,10 @@ register_native(environment** env, const char* name, expl_native fn, void* data)
92 static void
93 skip_space(parser* p)
94 {
95- while (isspace((unsigned char)p->src[p->pos]) || current_char(p, ';')) {
96+ while (isspace((unsigned char)current(p)) || is(p, ';')) {
97 /* comment */
98- if (current_char(p, ';')) {
99- while (!current_char(p, '\n') && !current_char(p, '\0'))
100+ if (is(p, ';')) {
101+ while (!is(p, '\n') && !end(p))
102 advance(p);
103 }
104