commit 84b452b
uint
·
2026-10-24 14:12:16 +0000 UTC
parent ad2faad
Add environments
1 files changed,
+69,
-4
M
expl.c
M
expl.c
+69,
-4
1@@ -8,16 +8,28 @@
2 #define current_char(p, c) ((p)->src[(p)->pos] == (c))
3 #define advance(p) ((p)->pos++)
4 #define pos(p) ((p)->pos)
5-#define peek(p) ((p)->pos + 1)
6+#define peek(p) ((p)->src[(p)->pos + 1])
7
8-typedef struct {
9+typedef struct parser parser;
10+typedef struct environment environment;
11+
12+struct parser {
13 const char* src;
14 size_t pos;
15 expl_error err;
16-} parser;
17+};
18+
19+struct environment {
20+ char* name;
21+ expl_node* value;
22+ environment* next;
23+};
24
25+static int define(environment** env, const char* name, expl_node* value);
26 static expl_node* expression(parser* p);
27+static expl_node* evaluate(expl_node* n, environment** env);
28 static expl_node* list(parser* p);
29+static expl_node* lookup(environment* env, const char* name);
30 static expl_node* value(parser* p, expl_type type);
31
32 static void skipspace(parser* p);
33@@ -26,6 +38,27 @@ static void unescape(char* src);
34
35 static expl_node* newnode(expl_type type);
36 static void freenode(expl_node* node);
37+static void freeenv(environment* env);
38+
39+static int
40+define(environment** env, const char* name, expl_node* value)
41+{
42+ environment* b = malloc(sizeof(*b));
43+ if (!b)
44+ return 0;
45+
46+ b->name = _strndup(name, strlen(name));
47+ if (!b->name) {
48+ free(b);
49+ return 0;
50+ }
51+
52+ b->value = value;
53+ b->next = *env;
54+ *env = b;
55+
56+ return 1;
57+}
58
59 static expl_node*
60 expression(parser* p)
61@@ -45,6 +78,15 @@ expression(parser* p)
62 }
63 }
64
65+static expl_node*
66+evaluate(expl_node* n, environment** env)
67+{
68+ /* XXX */
69+ (void) n;
70+ (void) env;
71+ return NULL;
72+}
73+
74 static expl_node*
75 list(parser* p)
76 {
77@@ -83,6 +125,18 @@ list(parser* p)
78 return node;
79 }
80
81+static expl_node*
82+lookup(environment* env, const char* name)
83+{
84+ while (env) {
85+ if (strcmp(env->name, name) == 0)
86+ return env->value;
87+ env = env->next;
88+ }
89+
90+ return NULL;
91+}
92+
93 static expl_node*
94 value(parser* p, expl_type type)
95 {
96@@ -227,6 +281,17 @@ freenode(expl_node* node)
97 free(node);
98 }
99
100+static void
101+freeenv(environment* env)
102+{
103+ while (env) {
104+ environment* next = env->next;
105+ free(env->name);
106+ free(env);
107+ env = next;
108+ }
109+}
110+
111 expl_node*
112 expl_parse(const char* source)
113 {
114@@ -285,7 +350,7 @@ expl_print(const expl_node* node, int depth)
115 int
116 main(void)
117 {
118- expl_node* node = expl_parse("(fn (\"hi\n\n\n\" x) (* x x))");
119+ expl_node* node = expl_parse("(fn (\"hi\" x) (* x x))");
120 expl_print(node, 0);
121 freenode(node);
122 return EXIT_SUCCESS;