commit 50483fa
uint
·
2026-10-23 20:28:59 +0000 UTC
parent 22b6434
Parse atoms, add space skipping
1 files changed,
+74,
-1
M
expl.c
M
expl.c
+74,
-1
1@@ -1,13 +1,71 @@
2+#include <ctype.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5+#include <string.h>
6
7 #include "expl.h"
8
9+typedef struct {
10+ const char* src;
11+ size_t pos;
12+ expl_error err;
13+} parser;
14+
15+static expl_node* atom(parser* p);
16+static char* _strndup(const char* src, size_t len);
17 static expl_node* node_new(expl_type type);
18 static void node_free(expl_node* node);
19+static void skip_whitespace(parser* p);
20+
21+static expl_node* atom(parser* p)
22+{
23+ size_t start = p->pos;
24+ expl_node* node = NULL;
25+
26+ while (p->src[p->pos] &&
27+ !isspace((unsigned char)p->src[p->pos]) &&
28+ p->src[p->pos] != '(' &&
29+ p->src[p->pos] != ')' &&
30+ p->src[p->pos] != '"' &&
31+ p->src[p->pos] != ';')
32+ p->pos++;
33+
34+ if (start == p->pos) {
35+ p->err = EXPL_ERR_EXPECTED_ATOM;
36+ return NULL;
37+ }
38+
39+ node = node_new(EXPL_ATOM);
40+ if (!node) {
41+ p->err = EXPL_ERR_OUT_OF_MEMORY;
42+ return NULL;
43+ }
44+
45+ node->value = _strndup(p->src + start, p->pos - start);
46+ if (!node->value) {
47+ node_free(node);
48+ p->err = EXPL_ERR_OUT_OF_MEMORY;
49+ return NULL;
50+ }
51+
52+ return node;
53+}
54+
55+static char*
56+_strndup(const char* src, size_t len)
57+{
58+ char* str = malloc(len + 1);
59+ if (!str)
60+ return NULL;
61+
62+ memcpy(str, src, len);
63+ str[len] = '\0';
64+
65+ return str;
66+}
67
68 static expl_node*
69-new_node(expl_type type)
70+node_new(expl_type type)
71 {
72 expl_node* node = malloc(sizeof(*node));
73 if (!node)
74@@ -36,6 +94,21 @@ node_free(expl_node* node)
75 free(node);
76 }
77
78+static void skip_whitespace(parser* p)
79+{
80+ while (isspace((unsigned char)p->src[p->pos]) || p->src[p->pos] == ';') {
81+ /* comment */
82+ if (p->src[p->pos] == ';') {
83+ while (p->src[p->pos] != '\n' && p->src[p->pos] != '\0')
84+ p->pos++;
85+ }
86+
87+ /* whitespace */
88+ else
89+ p->pos++;
90+ }
91+}
92+
93 int
94 main(void)
95 {