-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathlamb.c
More file actions
1419 lines (1266 loc) · 42.1 KB
/
lamb.c
File metadata and controls
1419 lines (1266 loc) · 42.1 KB
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ,---@>
// W-W'
// cc -o lamb lamb.c
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdarg.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <signal.h>
#ifdef _WIN32
# define WIN32_LEAN_AND_MEAN
# define _WINUSER_
# define _WINGDI_
# define _IMM_
# define _WINCON_
# include <windows.h>
#else
# include <unistd.h>
# include <sys/wait.h>
# include <sys/stat.h>
#endif // _WIN32
#if defined(__GNUC__) || defined(__clang__)
// https://gcc.gnu.org/onlinedocs/gcc-4.7.2/gcc/Function-Attributes.html
# ifdef __MINGW_PRINTF_FORMAT
# define PRINTF_FORMAT(STRING_INDEX, FIRST_TO_CHECK) __attribute__ ((format (__MINGW_PRINTF_FORMAT, STRING_INDEX, FIRST_TO_CHECK)))
# else
# define PRINTF_FORMAT(STRING_INDEX, FIRST_TO_CHECK) __attribute__ ((format (printf, STRING_INDEX, FIRST_TO_CHECK)))
# endif // __MINGW_PRINTF_FORMAT
#else
// TODO: implement PRINTF_FORMAT for MSVC
# define PRINTF_FORMAT(STRING_INDEX, FIRST_TO_CHECK)
#endif
#define UNUSED(value) (void)(value)
#define TODO(message) do { fprintf(stderr, "%s:%d: TODO: %s\n", __FILE__, __LINE__, message); abort(); } while(0)
#define UNREACHABLE(message) do { fprintf(stderr, "%s:%d: UNREACHABLE: %s\n", __FILE__, __LINE__, message); abort(); } while(0)
#define DA_INIT_CAP 256
#define da_reserve(da, expected_capacity) \
do { \
if ((expected_capacity) > (da)->capacity) { \
if ((da)->capacity == 0) { \
(da)->capacity = DA_INIT_CAP; \
} \
while ((expected_capacity) > (da)->capacity) { \
(da)->capacity *= 2; \
} \
(da)->items = realloc((da)->items, (da)->capacity * sizeof(*(da)->items)); \
assert((da)->items != NULL && "Buy more RAM lol"); \
} \
} while (0)
#define da_append(da, item) \
do { \
da_reserve((da), (da)->count + 1); \
(da)->items[(da)->count++] = (item); \
} while (0)
#define da_delete_at(da, i) \
do { \
size_t index = (i); \
assert(index < (da)->count); \
memmove(&(da)->items[index], &(da)->items[index + 1], ((da)->count - index - 1)*sizeof(*(da)->items)); \
(da)->count -= 1; \
} while(0)
#define sb_append_null(sb) da_append(sb, 0)
typedef struct {
const char **items;
size_t count;
size_t capacity;
} Cmd;
bool cmd_run(Cmd *cmd)
{
if (cmd->count < 1) {
fprintf(stderr, "ERROR: Could not run empty command");
return false;
}
#ifdef _WIN32
TODO("cmd_run is not implemented for windows");
#else
pid_t cpid = fork();
if (cpid < 0) {
fprintf(stderr, "ERROR: Could not fork child process: %s", strerror(errno));
return false;
}
if (cpid == 0) {
// NOTE: This leaks a bit of memory in the child process.
// But do we actually care? It's a one off leak anyway...
da_append(cmd, NULL);
if (execvp(cmd->items[0], (char * const*) cmd->items) < 0) {
fprintf(stderr, "ERROR: Could not exec child process for %s: %s", cmd->items[0], strerror(errno));
exit(1);
}
UNREACHABLE("cmd_run");
}
for (;;) {
int wstatus = 0;
if (waitpid(cpid, &wstatus, 0) < 0) {
fprintf(stderr, "ERROR: Could not wait on command (pid %d): %s", cpid, strerror(errno));
return false;
}
if (WIFEXITED(wstatus)) {
int exit_status = WEXITSTATUS(wstatus);
if (exit_status != 0) {
fprintf(stderr, "ERROR: Command exited with exit code %d", exit_status);
return false;
}
break;
}
if (WIFSIGNALED(wstatus)) {
fprintf(stderr, "ERROR: Command process was terminated by signal %d", WTERMSIG(wstatus));
return false;
}
}
return cpid;
#endif
}
char *copy_string_sized(const char *s, size_t n)
{
char *ds = malloc(n + 1);
assert(ds);
memcpy(ds, s, n);
ds[n] = '\0';
return ds;
}
char *copy_string(const char *s)
{
return copy_string_sized(s, strlen(s));
}
typedef struct {
char *items;
size_t count;
size_t capacity;
} String_Builder;
int sb_appendf(String_Builder *sb, const char *fmt, ...) PRINTF_FORMAT(2, 3);
int sb_appendf(String_Builder *sb, const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
int n = vsnprintf(NULL, 0, fmt, args);
va_end(args);
// NOTE: the new_capacity needs to be +1 because of the null terminator.
// However, further below we increase sb->count by n, not n + 1.
// This is because we don't want the sb to include the null terminator. The user can always sb_append_null() if they want it
da_reserve(sb, sb->count + n + 1);
char *dest = sb->items + sb->count;
va_start(args, fmt);
vsnprintf(dest, n+1, fmt, args);
va_end(args);
sb->count += n;
return n;
}
// RETURNS:
// 0 - file does not exists
// 1 - file exists
// -1 - error while checking if file exists. The error is logged
int file_exists(const char *file_path)
{
#if _WIN32
// TODO: distinguish between "does not exists" and other errors
DWORD dwAttrib = GetFileAttributesA(file_path);
return dwAttrib != INVALID_FILE_ATTRIBUTES;
#else
struct stat statbuf;
if (stat(file_path, &statbuf) < 0) {
if (errno == ENOENT) return 0;
fprintf(stderr, "ERROR: Could not check if file %s exists: %s", file_path, strerror(errno));
return -1;
}
return 1;
#endif
}
bool read_entire_file(const char *path, String_Builder *sb)
{
FILE *f = fopen(path, "rb");
size_t new_count = 0;
long long m = 0;
if (f == NULL) goto fail;
if (fseek(f, 0, SEEK_END) < 0) goto fail;
#ifndef _WIN32
m = ftell(f);
#else
m = _ftelli64(f);
#endif
if (m < 0) goto fail;
if (fseek(f, 0, SEEK_SET) < 0) goto fail;
new_count = sb->count + m;
if (new_count > sb->capacity) {
sb->items = realloc(sb->items, new_count);
assert(sb->items != NULL && "Buy more RAM lool!!");
sb->capacity = new_count;
}
fread(sb->items + sb->count, m, 1, f);
if (ferror(f)) {
// TODO: Afaik, ferror does not set errno. So the error reporting in fail is not correct in this case.
goto fail;
}
sb->count = new_count;
fclose(f);
return true;
fail:
fprintf(stderr, "ERROR: Could not read file %s: %s\n", path, strerror(errno));
if (f) fclose(f);
return false;
}
bool write_entire_file(const char *path, const void *data, size_t size)
{
const char *buf = NULL;
FILE *f = fopen(path, "wb");
if (f == NULL) {
fprintf(stderr, "ERROR: Could not open file %s for writing: %s\n", path, strerror(errno));
goto fail;
}
// len
// v
// aaaaaaaaaa
// ^
// data
buf = (const char*)data;
while (size > 0) {
size_t n = fwrite(buf, 1, size, f);
if (ferror(f)) {
fprintf(stderr, "ERROR: Could not write into file %s: %s\n", path, strerror(errno));
goto fail;
}
size -= n;
buf += n;
}
fclose(f);
return true;
fail:
if (f) fclose(f);
return false;
}
struct {
const char **items;
size_t count;
size_t capacity;
} labels = {0};
const char *intern_label(const char *label)
{
for (size_t i = 0; i < labels.count; ++i) {
if (strcmp(labels.items[i], label) == 0) {
return labels.items[i];
}
}
char *result = copy_string(label);
da_append(&labels, result);
return result;
}
typedef struct {
// Displayed name of the symbol.
const char *label;
// Internal tag that makes two symbols with the same label different if needed.
// Usually used to obtain a fresh symbol for capture avoiding substitution.
size_t tag;
} Symbol;
bool symbol_eq(Symbol a, Symbol b)
{
// NOTE: We compare addresses of the labels because they are expected to be interned with intern_label()
return a.label == b.label && a.tag == b.tag;
}
Symbol symbol(const char *label)
{
Symbol s = { .label = intern_label(label), .tag = 0 };
return s;
}
Symbol symbol_fresh(Symbol s)
{
static size_t global_counter = 0;
s.tag = ++global_counter;
return s;
}
typedef enum {
EXPR_VAR,
EXPR_FUN,
EXPR_APP,
EXPR_MAG,
} Expr_Kind;
typedef struct {
size_t unwrap;
} Expr_Index;
typedef struct {
Expr_Kind kind;
bool visited;
bool live;
union {
Symbol var;
const char *mag;
struct {
Symbol param;
Expr_Index body;
} fun;
struct {
Expr_Index lhs;
Expr_Index rhs;
} app;
} as;
} Expr;
static struct {
struct {
Expr *items;
size_t count;
size_t capacity;
} slots;
struct {
Expr_Index *items;
size_t count;
size_t capacity;
} dead;
struct {
Expr_Index *items;
size_t count;
size_t capacity;
} gens[2];
size_t gen_cur;
} GC = {0};
#define expr_slot(index) ( \
GC.slots.items[ \
(assert((index).unwrap < GC.slots.count), \
assert(GC.slots.items[(index).unwrap].live), \
(index).unwrap)])
#define expr_slot_unsafe(index) GC.slots.items[(index).unwrap]
Expr_Index alloc_expr(void)
{
Expr_Index result;
if (GC.dead.count > 0) {
result = GC.dead.items[--GC.dead.count];
} else {
result.unwrap = GC.slots.count;
Expr expr = {0};
da_append(&GC.slots, expr);
}
assert(!expr_slot_unsafe(result).live);
expr_slot_unsafe(result).live = true;
da_append(&GC.gens[GC.gen_cur], result);
return result;
}
void free_expr(Expr_Index expr)
{
expr_slot(expr).live = false;
da_append(&GC.dead, expr);
}
Expr_Index var(Symbol name)
{
Expr_Index expr = alloc_expr();
expr_slot(expr).kind = EXPR_VAR;
expr_slot(expr).as.var = name;
return expr;
}
Expr_Index magic(const char *label)
{
Expr_Index expr = alloc_expr();
expr_slot(expr).kind = EXPR_MAG;
expr_slot(expr).as.mag = intern_label(label);
return expr;
}
Expr_Index fun(Symbol param, Expr_Index body)
{
Expr_Index expr = alloc_expr();
expr_slot(expr).kind = EXPR_FUN;
expr_slot(expr).as.fun.param = param;
expr_slot(expr).as.fun.body = body;
return expr;
}
Expr_Index app(Expr_Index lhs, Expr_Index rhs)
{
Expr_Index expr = alloc_expr();
expr_slot(expr).kind = EXPR_APP;
expr_slot(expr).as.app.lhs = lhs;
expr_slot(expr).as.app.rhs = rhs;
return expr;
}
void expr_display(Expr_Index expr, String_Builder *sb)
{
switch (expr_slot(expr).kind) {
case EXPR_VAR:
sb_appendf(sb, "%s", expr_slot(expr).as.var.label);
if (expr_slot(expr).as.var.tag) {
sb_appendf(sb, ":%zu", expr_slot(expr).as.var.tag);
}
break;
case EXPR_FUN:
sb_appendf(sb, "\\");
while (expr_slot(expr).kind == EXPR_FUN) {
if (expr_slot(expr).as.fun.param.tag) {
sb_appendf(sb, "%s:%zu.", expr_slot(expr).as.fun.param.label, expr_slot(expr).as.fun.param.tag);
} else {
sb_appendf(sb, "%s.", expr_slot(expr).as.fun.param.label);
}
expr = expr_slot(expr).as.fun.body;
}
expr_display(expr, sb);
break;
case EXPR_APP: {
Expr_Index lhs = expr_slot(expr).as.app.lhs;
bool lhs_paren = expr_slot(lhs).kind == EXPR_FUN;
if (lhs_paren) sb_appendf(sb, "(");
expr_display(lhs, sb);
if (lhs_paren) sb_appendf(sb, ")");
sb_appendf(sb, " ");
Expr_Index rhs = expr_slot(expr).as.app.rhs;
bool rhs_paren = expr_slot(rhs).kind != EXPR_VAR && expr_slot(rhs).kind != EXPR_MAG;
if (rhs_paren) sb_appendf(sb, "(");
expr_display(rhs, sb);
if (rhs_paren) sb_appendf(sb, ")");
} break;
case EXPR_MAG: {
sb_appendf(sb, "#%s", expr_slot(expr).as.mag);
} break;
default: UNREACHABLE("Expr_Kind");
}
}
void dump_expr_ast(Expr_Index expr)
{
static struct {
bool *items;
size_t count;
size_t capacity;
} stack = {0};
for (size_t i = 0; i < stack.count; ++i) {
if (i + 1 == stack.count) {
printf("+--");
} else {
if (stack.items[i]) {
printf("| ");
} else {
printf(" ");
}
}
}
switch (expr_slot(expr).kind) {
case EXPR_VAR:
if (expr_slot(expr).as.var.tag == 0) {
printf("[VAR] %s\n", expr_slot(expr).as.var.label);
} else {
printf("[VAR] %s:%zu\n", expr_slot(expr).as.var.label, expr_slot(expr).as.var.tag);
}
break;
case EXPR_FUN:
if (expr_slot(expr).as.fun.param.tag == 0) {
printf("[FUN] \\%s\n", expr_slot(expr).as.fun.param.label);
} else {
printf("[FUN] \\%s:%zu\n", expr_slot(expr).as.fun.param.label, expr_slot(expr).as.fun.param.tag);
}
da_append(&stack, false); {
dump_expr_ast(expr_slot(expr).as.fun.body);
} stack.count -= 1;
break;
case EXPR_APP:
printf("[APP]\n");
da_append(&stack, true); {
dump_expr_ast(expr_slot(expr).as.app.lhs);
} stack.count -= 1;
da_append(&stack, false); {
dump_expr_ast(expr_slot(expr).as.app.rhs);
} stack.count -= 1;
break;
case EXPR_MAG:
printf("[MAG] #%s\n", expr_slot(expr).as.mag);
break;
default:
UNREACHABLE("Expr_Index");
}
}
void trace_expr(Expr_Index expr)
{
static String_Builder sb = {0};
sb.count = 0;
expr_display(expr, &sb);
sb_append_null(&sb);
printf("%s", sb.items);
}
bool is_var_free_there(Symbol name, Expr_Index there)
{
switch (expr_slot(there).kind) {
case EXPR_VAR:
return symbol_eq(expr_slot(there).as.var, name);
case EXPR_FUN:
if (symbol_eq(expr_slot(there).as.fun.param, name)) return false;
return is_var_free_there(name, expr_slot(there).as.fun.body);
case EXPR_APP:
if (is_var_free_there(name, expr_slot(there).as.app.lhs)) return true;
if (is_var_free_there(name, expr_slot(there).as.app.rhs)) return true;
return false;
case EXPR_MAG:
return false;
default: UNREACHABLE("Expr_Kind");
}
}
Expr_Index replace(Symbol param, Expr_Index body, Expr_Index arg)
{
switch (expr_slot(body).kind) {
case EXPR_MAG:
return body;
case EXPR_VAR:
if (symbol_eq(expr_slot(body).as.var, param)) {
return arg;
} else {
return body;
}
case EXPR_FUN:
if (symbol_eq(expr_slot(body).as.fun.param, param)) return body;
if (!is_var_free_there(expr_slot(body).as.fun.param, arg)) {
return fun(expr_slot(body).as.fun.param, replace(param, expr_slot(body).as.fun.body, arg));
}
Symbol fresh_param_name = symbol_fresh(expr_slot(body).as.fun.param);
Expr_Index fresh_param = var(fresh_param_name);
return fun(
fresh_param_name,
replace(param,
replace(
expr_slot(body).as.fun.param,
expr_slot(body).as.fun.body,
fresh_param),
arg));
case EXPR_APP:
return app(
replace(param, expr_slot(body).as.app.lhs, arg),
replace(param, expr_slot(body).as.app.rhs, arg));
default: UNREACHABLE("Expr_Kind");
}
}
bool eval1(Expr_Index expr, Expr_Index *expr1)
{
switch (expr_slot(expr).kind) {
case EXPR_VAR:
*expr1 = expr;
return true;
case EXPR_FUN: {
Expr_Index body;
if (!eval1(expr_slot(expr).as.fun.body, &body)) return false;
if (body.unwrap != expr_slot(expr).as.fun.body.unwrap) {
*expr1 = fun(expr_slot(expr).as.fun.param, body);
} else {
*expr1 = expr;
}
return true;
}
case EXPR_APP: {
Expr_Index lhs = expr_slot(expr).as.app.lhs;
Expr_Index rhs = expr_slot(expr).as.app.rhs;
if (expr_slot(lhs).kind == EXPR_FUN) {
*expr1 = replace(
expr_slot(lhs).as.fun.param,
expr_slot(lhs).as.fun.body,
rhs);
return true;
} else if (expr_slot(lhs).kind == EXPR_MAG) {
if (expr_slot(lhs).as.mag == intern_label("trace")) {
Expr_Index new_rhs;
if (!eval1(rhs, &new_rhs)) return false;
if (new_rhs.unwrap == rhs.unwrap) {
printf("TRACE: ");
trace_expr(rhs);
printf("\n");
*expr1 = rhs;
} else {
*expr1 = app(lhs, new_rhs);
}
return true;
} else if (expr_slot(lhs).as.mag == intern_label("void")) {
Expr_Index new_rhs;
if (!eval1(rhs, &new_rhs)) return false;
if (new_rhs.unwrap == rhs.unwrap) {
*expr1 = lhs;
} else {
*expr1 = app(lhs, new_rhs);
}
return true;
} else {
printf("ERROR: unknown magic #%s\n", expr_slot(lhs).as.mag);
return false;
}
}
Expr_Index new_lhs;
if (!eval1(lhs, &new_lhs)) return false;
if (lhs.unwrap != new_lhs.unwrap) {
*expr1 = app(new_lhs, rhs);
return true;
}
Expr_Index new_rhs;
if (!eval1(rhs, &new_rhs)) return false;
if (rhs.unwrap != new_rhs.unwrap) {
*expr1 = app(lhs, new_rhs);
return true;
}
*expr1 = expr;
return true;
}
case EXPR_MAG:
*expr1 = expr;
return true;
default: UNREACHABLE("Expr_Kind");
}
}
typedef enum {
TOKEN_INVALID,
TOKEN_END,
TOKEN_OPAREN,
TOKEN_CPAREN,
TOKEN_LAMBDA,
TOKEN_DOT,
TOKEN_COLON,
TOKEN_SEMICOLON,
TOKEN_EQUALS,
TOKEN_NAME,
TOKEN_MAGIC,
} Token_Kind;
const char *token_kind_display(Token_Kind kind)
{
switch (kind) {
case TOKEN_INVALID: return "TOKEN_INVALID";
case TOKEN_END: return "TOKEN_END";
case TOKEN_OPAREN: return "TOKEN_OPAREN";
case TOKEN_CPAREN: return "TOKEN_CPAREN";
case TOKEN_LAMBDA: return "TOKEN_LAMBDA";
case TOKEN_DOT: return "TOKEN_DOT";
case TOKEN_COLON: return "TOKEN_COLON";
case TOKEN_SEMICOLON: return "TOKEN_SEMICOLON";
case TOKEN_EQUALS: return "TOKEN_EQUALS";
case TOKEN_NAME: return "TOKEN_NAME";
case TOKEN_MAGIC: return "TOKEN_MAGIC";
default: UNREACHABLE("Token_Kind");
}
}
typedef struct {
size_t pos, bol, row;
} Cur;
typedef struct {
const char *content;
size_t count;
const char *file_path;
Cur cur;
Token_Kind token;
String_Builder string;
size_t row, col;
} Lexer;
void lexer_init(Lexer *l, const char *content, size_t count, const char *file_path)
{
l->content = content;
l->count = count;
l->file_path = file_path;
memset(&l->cur, 0, sizeof(l->cur));
}
void lexer_print_loc(Lexer *l, FILE *stream)
{
if (l->file_path) fprintf(stream, "%s:", l->file_path);
fprintf(stream, "%zu:%zu: ", l->row, l->col);
}
char lexer_curr_char(Lexer *l)
{
if (l->cur.pos >= l->count) return 0;
return l->content[l->cur.pos];
}
char lexer_next_char(Lexer *l)
{
if (l->cur.pos >= l->count) return 0;
char x = l->content[l->cur.pos++];
if (x == '\n') {
l->cur.row += 1;
l->cur.bol = l->cur.pos;
}
return x;
}
void lexer_trim_left(Lexer *l)
{
while (isspace(lexer_curr_char(l))) {
lexer_next_char(l);
}
}
bool lexer_starts_with(Lexer *l, const char *prefix)
{
size_t pos = l->cur.pos;
while (pos < l->count && *prefix != '\0' && *prefix == l->content[pos]) {
pos++;
prefix++;
}
return *prefix == '\0';
}
void lexer_drop_line(Lexer *l)
{
while (l->cur.pos < l->count && lexer_next_char(l) != '\n') {}
}
bool issymbol(int x)
{
return isalnum(x) || x == '_';
}
bool lexer_next(Lexer *l)
{
for (;;) {
lexer_trim_left(l);
if (lexer_starts_with(l, "//")) lexer_drop_line(l);
else break;
}
l->row = l->cur.row + 1;
l->col = l->cur.pos - l->cur.bol + 1;
char x = lexer_next_char(l);
if (x == '\0') {
l->token = TOKEN_END;
return true;
}
switch (x) {
case '(': l->token = TOKEN_OPAREN; return true;
case ')': l->token = TOKEN_CPAREN; return true;
case '\\': l->token = TOKEN_LAMBDA; return true;
case '.': l->token = TOKEN_DOT; return true;
case ':': l->token = TOKEN_COLON; return true;
case ';': l->token = TOKEN_SEMICOLON; return true;
case '=': l->token = TOKEN_EQUALS; return true;
}
if (x == '#') {
l->token = TOKEN_MAGIC;
l->string.count = 0;
while (issymbol(lexer_curr_char(l))) {
x = lexer_next_char(l);
da_append(&l->string, x);
}
sb_append_null(&l->string);
return true;
}
if (issymbol(x)) {
l->token = TOKEN_NAME;
l->string.count = 0;
da_append(&l->string, x);
while (issymbol(lexer_curr_char(l))) {
x = lexer_next_char(l);
da_append(&l->string, x);
}
sb_append_null(&l->string);
return true;
}
l->token = TOKEN_INVALID;
lexer_print_loc(l, stderr);
fprintf(stderr, "ERROR: Unknown token starts with `%c`\n", x);
return false;
}
bool lexer_peek(Lexer *l)
{
Cur cur = l->cur;
bool result = lexer_next(l);
l->cur = cur;
return result;
}
void report_unexpected(Lexer *l, Token_Kind expected)
{
lexer_print_loc(l, stderr);
fprintf(stderr, "ERROR: Unexpected token %s. Expected %s instead.\n", token_kind_display(l->token), token_kind_display(expected));
}
bool lexer_expect(Lexer *l, Token_Kind expected)
{
if (!lexer_next(l)) return false;
if (l->token != expected) {
report_unexpected(l, expected);
return false;
}
return true;
}
bool parse_expr(Lexer *l, Expr_Index *expr);
bool parse_fun(Lexer *l, Expr_Index *expr)
{
if (!lexer_expect(l, TOKEN_NAME)) return false;
Symbol arg = symbol(l->string.items);
if (!lexer_expect(l, TOKEN_DOT)) return false;
Token_Kind a, b;
Cur cur = l->cur; {
if (!lexer_next(l)) return false;
a = l->token;
if (!lexer_next(l)) return false;
b = l->token;
} l->cur = cur;
Expr_Index body;
if (a == TOKEN_NAME && b == TOKEN_DOT) {
if (!parse_fun(l, &body)) return false;
} else {
if (!parse_expr(l, &body)) return false;
}
*expr = fun(arg, body);
return true;
}
bool parse_primary(Lexer *l, Expr_Index *expr)
{
if (!lexer_next(l)) return NULL;
switch ((int)l->token) {
case TOKEN_OPAREN: {
if (!parse_expr(l, expr)) return false;
if (!lexer_expect(l, TOKEN_CPAREN)) return false;
return true;
}
case TOKEN_LAMBDA: return parse_fun(l, expr);
case TOKEN_MAGIC:
*expr = magic(l->string.items);
return true;
case TOKEN_NAME:
*expr = var(symbol(l->string.items));
return true;
default:
lexer_print_loc(l, stderr);
fprintf(stderr, "ERROR: Unexpected token %s. Expected a primary expression instead.\n", token_kind_display(l->token));
return false;
}
}
bool parse_expr(Lexer *l, Expr_Index *expr)
{
if (!parse_primary(l, expr)) return false;
if (!lexer_peek(l)) return false;
while (
l->token != TOKEN_CPAREN &&
l->token != TOKEN_END &&
l->token != TOKEN_SEMICOLON
) {
Expr_Index rhs;
if (!parse_primary(l, &rhs)) return false;
*expr = app(*expr, rhs);
if (!lexer_peek(l)) return false;
}
return true;
}
typedef struct {
const char *name;
const char *signature;
const char *description;
} Command;
typedef struct {
Command *items;
size_t count;
size_t capacity;
} Commands;
bool command(Commands *commands, const char *input, const char *name, const char *signature, const char *description)
{
Command command = {
.name = name,
.signature = signature,
.description = description,
};
da_append(commands, command);
while (*input && *name && *input == *name) {
input++;
name++;
}
return *input == '\0';
}
void print_available_commands(Commands *commands)
{
printf("Available commands:\n");
int max_name_width = 0;
int max_sig_width = 0;
for (size_t i = 0; i < commands->count; ++i) {
Command command = commands->items[i];
int name_width = strlen(command.name);
int sig_width = strlen(command.signature);
if (name_width > max_name_width) max_name_width = name_width;
if (sig_width > max_sig_width) max_sig_width = sig_width;
}
for (size_t i = 0; i < commands->count; ++i) {
Command command = commands->items[i];
printf(" :%-*s %-*s - %s\n",
max_name_width, command.name,
max_sig_width, command.signature,
command.description);
}
}
void gc_mark(Expr_Index root)
{
if (expr_slot(root).visited) return;
expr_slot(root).visited = true;
switch (expr_slot(root).kind) {
case EXPR_MAG:
case EXPR_VAR:
break;
case EXPR_FUN:
gc_mark(expr_slot(root).as.fun.body);
break;
case EXPR_APP:
gc_mark(expr_slot(root).as.app.lhs);
gc_mark(expr_slot(root).as.app.rhs);
break;
default: UNREACHABLE("Expr_Kind");
}
}
typedef struct {
Symbol name;
Expr_Index body;
} Binding;
typedef struct {
Binding *items;
size_t count;
size_t capacity;
} Bindings;
void create_binding(Bindings *bindings, Symbol name, Expr_Index body)
{
for (size_t i = 0; i < bindings->count; ++i) {