-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathschaf.c
More file actions
3289 lines (2918 loc) · 83.6 KB
/
Copy pathschaf.c
File metadata and controls
3289 lines (2918 loc) · 83.6 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
#include <errno.h>
#include <inttypes.h>
#include <math.h>
#include <setjmp.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <libgen.h>
#include <limits.h>
#include <unistd.h>
#include "intern.h"
#include "libscary.h"
#include "schaf.h"
#include "utils.h"
//
// Types
//
// Value (uintptr_t):
// 0b......000 Pointer (Unchangeable pattern!)
// 0b........1 Integer
// 0b.......10 Symbol
// 0b0---00100 #f
// 0b0---01100 #t
// 0b0--010100 null
// 0b0--011100 EOF
// 0b0-0111100 <undef>
static const uintptr_t FLAG_NBIT_INT = 1;
static const uintptr_t FLAG_NBIT_SYM = 2;
static const uintptr_t FLAG_MASK_INT = 0b1;
static const uintptr_t FLAG_MASK_SYM = 0b11;
static const uintptr_t FLAG_MASK_IMM = 0b111; // for 64 bit machine
static const uintptr_t FLAG_INT = 0b1;
static const uintptr_t FLAG_SYM = 0b10;
const Value SCH_FALSE = 0b000100U; // 4
const Value SCH_TRUE = 0b001100U; // 12
const Value SCH_NULL = 0b010100U; // 20; the empty list
static
const Value EOF_OBJ = 0b011100U; // 28
const Value SCH_UNDEF = 0b111100U; // 60; may be an error or something internal
#define BOOL_VAL(v) ((!!(v) << 3U) | 0b100U)
static const int64_t CFUNCARG_MAX = 3;
//
// Runtime-locals (aka global variables)
//
// Environment: list of Frames
// Frame: Table of 'symbol => <value>
static Value env_toplevel, env_default, env_r5rs, env_null;
static char **symbol_names; // ("name0" "name1" ...)
Value SYM_QUOTE, SYM_QUASIQUOTE, SYM_UNQUOTE, SYM_UNQUOTE_SPLICING;
static Value SYM_ELSE, SYM_RARROW;
static const char *load_basedir;
static Source **source_data;
static jmp_buf jmp_exit;
static uint8_t exit_status; // should be <= 125 to be portable
static char errmsg[BUFSIZ];
static Value inner_winders = Qnil; // both inner_* are used in (dynamic-wind)
static Value inner_continuation = Qfalse;
// Singletons
static Value current_input_port = Qfalse, current_output_port = Qfalse;
#define INIT_SINGLETON(var, val) do { if ((var) == Qfalse) (var) = val; } while (0)
//
// value_is_*: Type Checks
//
inline bool sch_value_is_integer(Value v)
{
return v & FLAG_MASK_INT;
}
inline bool sch_value_is_symbol(Value v)
{
return (v & FLAG_MASK_SYM) == FLAG_SYM;
}
static inline bool value_is_immediate(Value v)
{
return v & FLAG_MASK_IMM;
}
static inline bool value_tag_is(Value v, ValueTag expected)
{
return !value_is_immediate(v) && VALUE_TAG(v) == expected;
}
inline bool sch_value_is_string(Value v)
{
return value_tag_is(v, TAG_STRING);
}
#define bug_invalid_tag(t) bug("got invalid tag %u", t)
static bool sch_value_is_procedure(Value v)
{
if (value_is_immediate(v))
return false;
switch (VALUE_TAG(v)) {
case TAG_CFUNC:
case TAG_SYNTAX:
case TAG_CLOSURE:
case TAG_CONTINUATION:
case TAG_CFUNC_CLOSURE:
return true;
case TAG_PAIR:
case TAG_STRING:
case TAG_VECTOR:
case TAG_PORT:
case TAG_PROMISE:
case TAG_ENV:
return false;
case TAG_ERROR:
break; // internal objects
}
bug_invalid_tag(VALUE_TAG(v));
}
inline static bool sch_value_is_vector(Value v)
{
return value_tag_is(v, TAG_VECTOR);
}
inline static bool sch_value_is_env(Value v)
{
return value_tag_is(v, TAG_ENV);
}
inline static bool sch_value_is_port(Value v)
{
return value_tag_is(v, TAG_PORT);
}
inline bool sch_value_is_pair(Value v)
{
return value_tag_is(v, TAG_PAIR);
}
inline static bool sch_value_is_promise(Value v)
{
return value_tag_is(v, TAG_PROMISE);
}
inline static bool is_error(Value v)
{
return value_tag_is(v, TAG_ERROR);
}
inline static bool is_boolean(Value v)
{
return v == Qtrue || v == Qfalse;
}
static Type immediate_type_of(Value v)
{
if (sch_value_is_integer(v))
return TYPE_INT;
if (sch_value_is_symbol(v))
return TYPE_SYMBOL;
if (is_boolean(v))
return TYPE_BOOL;
if (v == Qnil)
return TYPE_NULL;
if (v == EOF_OBJ)
return TYPE_EOF;
if (v == Qundef)
return TYPE_UNDEF;
bug("unexpected immediate: %zu", v);
}
Type sch_value_type_of(Value v)
{
if (value_is_immediate(v))
return immediate_type_of(v);
switch (VALUE_TAG(v)) {
case TAG_PAIR:
return TYPE_PAIR;
case TAG_STRING:
return TYPE_STRING;
case TAG_VECTOR:
return TYPE_VECTOR;
case TAG_PORT:
return TYPE_PORT;
case TAG_CFUNC:
case TAG_SYNTAX:
case TAG_CLOSURE:
case TAG_CONTINUATION:
case TAG_CFUNC_CLOSURE:
return TYPE_PROC;
case TAG_PROMISE:
return TYPE_PROMISE;
case TAG_ENV:
return TYPE_ENV;
case TAG_ERROR:
break; // internal objects
}
bug_invalid_tag(VALUE_TAG(v));
}
static const char *value_type_to_string(Type t)
{
switch (t) {
case TYPE_UNDEF:
return "undef";
case TYPE_NULL:
return "null";
case TYPE_EOF:
return "eof";
case TYPE_BOOL:
return "boolean";
case TYPE_INT:
return "integer";
case TYPE_SYMBOL:
return "symbol";
case TYPE_PAIR:
return "pair";
case TYPE_STRING:
return "string";
case TYPE_VECTOR:
return "vector";
case TYPE_PORT:
return "port";
case TYPE_PROC:
return "procedure";
case TYPE_PROMISE:
return "promise";
case TYPE_ENV:
return "environment";
}
UNREACHABLE();
}
const char *sch_value_to_type_name(Value v)
{
Type t = sch_value_type_of(v);
return value_type_to_string(t);
}
// *_to_<cdata>: Convert internal data to external plain C
inline int64_t sch_integer_to_cint(Value x)
{
#ifdef __x86_64__
return ((int64_t) x) >> FLAG_NBIT_INT;
#else
int64_t i = x;
return (i - 1) / (1 << FLAG_NBIT_INT);
#endif
}
inline Symbol sch_symbol_to_csymbol(Value v)
{
return (Symbol) (v >> FLAG_NBIT_SYM);
}
// symbol->string
static const char *unintern(Symbol sym)
{
size_t len = scary_length(symbol_names);
if (sym >= len) // fatal; every known symbols should have a name
bug("symbol %lu not found", sym);
return symbol_names[sym];
}
inline const char *sch_string_to_cstr(Value v)
{
return STRING(v);
}
inline const char *sch_symbol_to_cstr(Value v)
{
return unintern(sch_symbol_to_csymbol(v));
}
// define caar, cadr, ... cddddr, 28 procedures, at once
#define CXR1(f, x) f(a, x) f(d, x)
#define CXR2(f, x) CXR1(f, a ## x) CXR1(f, d ## x)
#define CXR3(f, x) CXR2(f, a ## x) CXR2(f, d ## x)
#define CXR4(f, x) CXR3(f, a) CXR3(f, d)
#define CXRS(f) CXR2(f,) CXR3(f,) CXR4(f,)
#define DEF_CXR(x, y) \
UNUSED static Value c##x##y##r(Value v) { return c##x##r(c##y##r(v)); }
CXRS(DEF_CXR)
// *_new: Convert external plain C data to internal
inline Value sch_integer_new(int64_t i)
{
Value v = i;
return v << FLAG_NBIT_INT | FLAG_INT;
}
// string->symbol
static Symbol intern(const char *name)
{
uint64_t i;
size_t len = scary_length(symbol_names);
// find
for (i = 0; i < len; i++) {
if (strcmp(symbol_names[i], name) == 0)
return i;
}
// or put at `i`
scary_push(&symbol_names, xstrdup(name));
return i;
}
inline Value sch_symbol_new(const char *s)
{
Symbol sym = intern(s);
return (((Value) sym) << FLAG_NBIT_SYM) | FLAG_SYM;
}
void *obj_new(ValueTag t, size_t size)
{
Header *h = gc_malloc(size);
h->tag = t;
h->immutable = false;
return h;
}
static Value string_new_moved(char *str)
{ // move ownership then use as is
String *s = obj_new(TAG_STRING, sizeof(String));
STRING(s) = str;
return (Value) s;
}
Value sch_string_new(const char *str)
{
return string_new_moved(xstrdup(str));
}
// General macros for error handling with some functions
static inline bool is_length_min_2(Value args)
{
return args != Qnil && cdr(args) != Qnil;
}
static inline bool is_length_2(Value args)
{
return is_length_min_2(args) && cddr(args) == Qnil;
}
static inline bool is_length_3(Value args)
{
return is_length_min_2(args) && cddr(args) != Qnil && cdddr(args) == Qnil;
}
// Trigger runtime errors
#define EXPECT_OR_RETURN(expr, err) do { if (!(expr)) return err; } while (0)
#define EXPECT(expr, ...) EXPECT_OR_RETURN((expr), runtime_error(__VA_ARGS__))
#define EXPECT_WITH_OBJ(expr, ...) EXPECT_OR_RETURN((expr), runtime_error_with_obj(__VA_ARGS__))
// Check then forward error from others
static Value push_stack_frame(Value ve, const char *name, Value loc);
#define EXPECT_ERROR_WITH_RETVAL(v, val) EXPECT_OR_RETURN(!is_error(v), (val))
#define EXPECT_ERROR(v) EXPECT_ERROR_WITH_RETVAL((v), (v))
#define EXPECT_ERROR_LOCATED(v, l) EXPECT_ERROR_WITH_RETVAL((v), ({ \
if (scary_length(ERROR(v)) == 0) \
push_stack_frame((v), NULL, (l)); \
(v); \
}))
// Check error too but the error happened at the n-th argument in the caller (list)
#define EXPECT_ERROR_LOCATED_BY_CALLER(v, n) \
EXPECT_ERROR_LOCATED(v, sch_integer_new(n))
// Trigger errors about arity
static Value arity_error(const char *op, int64_t expected, int64_t actual);
#define EXPECT_ARITY_N(expr, op, exp, act) \
EXPECT_OR_RETURN((expr), arity_error((op), (exp), (act)))
#define EXPECT_ARITY_0(args) \
EXPECT_ARITY_N((args) == Qnil, "", 0, length(args))
#define EXPECT_ARITY_1(args) \
EXPECT_ARITY_N((args) != Qnil && cdr(args) == Qnil, "", 1, length(args))
#define EXPECT_ARITY_2(args) \
EXPECT_ARITY_N(is_length_2(args), "", 2, length(args))
#define EXPECT_ARITY_3(args) \
EXPECT_ARITY_N(is_length_3(args), "", 3, length(args))
#define EXPECT_ARITY(expected, args) \
EXPECT_ARITY_N(expected < 0 || length_in_range(args, expected, expected), \
"", expected, length(args))
#define EXPECT_ARITY_RANGE(min, max, args) \
EXPECT(length_in_range(args, min, max), \
"wrong number of arguments: expected %d..%d but got %"PRId64, \
min, max, length(args))
#define EXPECT_ARITY_MIN_1(args) EXPECT_ARITY_N(args != Qnil, ">= ", 1, 0)
#define EXPECT_ARITY_MIN_2(args) EXPECT_ARITY_N(is_length_min_2(args), ">= ", 2, length(args))
// Trigger errors about types
static inline Value type_error(const char *expected, Value v);
#define EXPECT_TYPE(type, v) \
EXPECT_OR_RETURN(sch_value_is_ ## type(v), type_error(#type, v))
#define EXPECT_TYPE_TWIN(type, x, y) EXPECT_TYPE(type, x); EXPECT_TYPE(type, y)
#define EXPECT_TYPE_OR(t1, t2, v) \
EXPECT(sch_value_is_ ## t1(v) || sch_value_is_ ## t2(v), \
"expected " #t1 " or " #t2 " but got %s", sch_value_to_type_name(v))
static Value apply_cfunc_v(Value env, Value f, Value args)
{
return CFUNC(f)->f1(env, args);
}
static Value apply_cfunc_0(Value env, Value f, UNUSED Value args)
{
EXPECT_ARITY_0(args);
return CFUNC(f)->f0(env);
}
static Value apply_cfunc_1(Value env, Value f, Value args)
{
EXPECT_ARITY_1(args);
return CFUNC(f)->f1(env, car(args));
}
static Value apply_cfunc_2(Value env, Value f, Value args)
{
EXPECT_ARITY_2(args);
return CFUNC(f)->f2(env, car(args), cadr(args));
}
static Value apply_cfunc_3(Value env, Value f, Value args)
{
EXPECT_ARITY_3(args);
return CFUNC(f)->f3(env, car(args), cadr(args), caddr(args));
}
static void expect_cfunc_tag(ValueTag tag)
{
if (tag == TAG_CFUNC || tag == TAG_SYNTAX)
return;
bug_invalid_tag(tag);
}
static void expect_cfunc_arity(int64_t actual)
{
if (actual <= CFUNCARG_MAX)
return;
bug("arity too large: expected ..%"PRId64" but got %"PRId64,
CFUNCARG_MAX, actual);
}
static Value cfunc_new_internal(ValueTag tag, const char *name, void *cfunc, int64_t arity)
{
expect_cfunc_tag(tag);
expect_cfunc_arity(arity);
CFunc *f = obj_new(tag, sizeof(CFunc));
f->proc.arity = arity;
f->name = name;
f->cfunc = cfunc;
switch (arity) {
case -1:
f->proc.apply = apply_cfunc_v;
break;
case 0:
f->proc.apply = apply_cfunc_0;
break;
case 1:
f->proc.apply = apply_cfunc_1;
break;
case 2:
f->proc.apply = apply_cfunc_2;
break;
case 3:
f->proc.apply = apply_cfunc_3;
break;
default:
bug("invalid arity: %"PRId64, arity);
}
return (Value) f;
}
static Value cfunc_new(const char *name, void *cfunc, int64_t arity)
{
return cfunc_new_internal(TAG_CFUNC, name, cfunc, arity);
}
static Value syntax_new(const char *name, void *cfunc, int64_t arity)
{
return cfunc_new_internal(TAG_SYNTAX, name, cfunc, arity);
}
static Value apply_cfunc_closure_1(UNUSED Value env, Value f, Value args)
{
EXPECT_ARITY_1(args);
return CFUNC(f)->f1(CFUNC_CLOSURE(f)->data, car(args));
}
static Value cfunc_closure_new(const char *name, void *cfunc, Value data)
{
CFuncClosure *cc = obj_new(TAG_CFUNC_CLOSURE, sizeof(CFuncClosure));
cc->data = data;
CFunc *f = CFUNC(cc);
f->proc.arity = 1; // currently fixed
f->proc.apply = apply_cfunc_closure_1;
f->name = name;
f->cfunc = cfunc;
return (Value) cc;
}
static bool length_in_range(Value l, int64_t min, int64_t max)
{
int64_t len = 0;
for (Value p = l; p != Qnil; p = cdr(p)) {
len++;
if (len > max)
return false;
}
return len >= min;
}
static Value eval_body(Value env, Value body);
static Value env_inherit(Value parent);
static void env_put(Value env, Value key, Value value);
//PTR
static Value apply_closure(UNUSED Value env, Value proc, Value args)
{
EXPECT_ARITY(PROCEDURE(proc)->arity, args);
Closure *cl = CLOSURE(proc);
int64_t arity = cl->proc.arity;
Value localenv = env_inherit(cl->env);
Value params = cl->params;
if (arity == -1)
env_put(localenv, params, args);
else {
for (Value pa = args, pp = params; pa != Qnil; pa = cdr(pa), pp = cdr(pp))
env_put(localenv, car(pp), car(pa));
}
return eval_body(localenv, cl->body);
}
static Value closure_new(Value env, Value params, Value body)
{
Closure *f = obj_new(TAG_CLOSURE, sizeof(Closure));
bool headp = params == Qnil || sch_value_is_pair(params);
f->proc.arity = headp ? length(params) : -1;
f->proc.apply = apply_closure;
f->env = env;
f->params = params;
f->body = body;
return (Value) f;
}
// and `cons` is well-known name than `pair_new`
//
// Errors
//
void print_error_message(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vsnprintf(errmsg, sizeof(errmsg), fmt, ap);
va_end(ap);
}
void append_error_message_v(const char *fmt, va_list ap)
{
size_t len = strlen(errmsg);
ssize_t rest = sizeof(errmsg) - len;
vsnprintf(errmsg + len, rest, fmt, ap);
}
[[gnu::format(printf, 1, 2)]]
static void append_error_message(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
append_error_message_v(fmt, ap);
va_end(ap);
}
[[gnu::format(printf, 1, 2)]]
static Value runtime_error(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vsnprintf(errmsg, sizeof(errmsg), fmt, ap);
va_end(ap);
Error *e = obj_new(TAG_ERROR, sizeof(Error));
ERROR(e) = scary_new(sizeof(StackFrame *));
return (Value) e;
}
static Value runtime_error_with_obj(const char *message, Value obj)
{
char *objstr = sch_stringify(obj);
Value e = runtime_error("%s: %s", message, objstr);
free(objstr);
return e;
}
const char *sch_error_message(void)
{
return errmsg;
}
static inline Value arity_error(const char *op, int64_t expected, int64_t actual)
{
return runtime_error("wrong number of arguments: expected %s%"PRId64" but got %"PRId64,
op, expected, actual);
}
static inline Value type_error(const char *expected, Value v)
{
return runtime_error("expected %s but got %s",
expected, sch_value_to_type_name(v));
}
//
// Environments
//
[[gnu::nonnull(1)]]
static Value env_new(const char *name)
{
Env *e = obj_new(TAG_ENV, sizeof(Env));
e->table = NULL;
e->parent = Qfalse;
e->name = name;
return (Value) e;
}
static Value env_dup(const char *name, const Value orig)
{
if (ENV(orig)->parent != Qfalse)
bug("duplication of chained environment not permitted");
Env *e = obj_new(TAG_ENV, sizeof(Env));
e->name = name != NULL ? name : ENV(orig)->name;
const Table *t = ENV(orig)->table;
e->table = t != NULL ? table_dup(t) : NULL;
e->parent = Qfalse;
return (Value) e;
}
static Value env_inherit(Value parent)
{
Value e = env_new("tmp");
ENV(e)->parent = parent;
return e;
}
static void env_put(Value env, Value key, Value value)
{
Table *t = ENV(env)->table;
if (t == NULL)
t = ENV(env)->table = table_new();
table_put(t, SYMBOL(key), value);
}
// chained!
static bool env_set(Value env, Value key, Value value)
{
Symbol sym = SYMBOL(key);
for (Value p = env; p != Qfalse; p = ENV(p)->parent) {
Table *t = ENV(p)->table;
if (t == NULL)
continue;
if (table_set(t, sym, value))
return true;
}
return false;
}
// chained!!
static Value env_get(const Value env, Value name)
{
Symbol sym = SYMBOL(name);
for (Value p = env; p != Qfalse; p = ENV(p)->parent) {
Table *t = ENV(p)->table;
if (t == NULL)
continue;
Value v = table_get(t, sym);
if (v != TABLE_NOT_FOUND)
return v;
}
return Qundef;
}
// Note: Do not mistake this for "(define-syntax ...)" which related to macros
static void define_syntax(Value env, const char *name, void *cfunc, int64_t arity)
{
env_put(env, sch_symbol_new(name), syntax_new(name, cfunc, arity));
}
static void define_procedure(Value env, const char *name, void *cfunc, int64_t arity)
{
env_put(env, sch_symbol_new(name), cfunc_new(name, cfunc, arity));
}
//
// Evaluation
//
[[nodiscard]] static Value eval(Value env, Value v);
#define eval_loc(env, loc) ({ \
vValue R = eval((env), car(loc)); \
EXPECT_ERROR_LOCATED(R, (loc)); \
R; \
})
static Value eval_body(Value env, Value body)
{
Value last = Qfalse;
for (Value p = body; p != Qnil; p = cdr(p))
last = eval_loc(env, p);
return last;
}
static Value map_eval(Value env, Value l)
{
Value mapped = DUMMY_PAIR();
for (Value last = mapped, p = l, v; p != Qnil; p = cdr(p)) {
EXPECT_WITH_OBJ(sch_value_is_pair(p), "improper list for apply", l);
v = eval_loc(env, p);
last = PAIR(last)->cdr = list1(v);
}
return cdr(mapped);
}
static StackFrame *stack_frame_new(const char *name, Value loc)
{
StackFrame *f = xmalloc(sizeof(StackFrame));
f->func_name = name;
f->loc = loc;
return f;
}
static bool frame_should_resolve(const StackFrame *f)
{
return sch_value_is_integer(f->loc);
}
// Get LocatedPair of n-th argument in list
static Value resolve_location(StackFrame *const *f, Value list)
{
int64_t n = sch_integer_to_cint(f[0]->loc);
Value p = list; // begins with proc
for (int64_t i = 0; i < n; i++)
p = cdr(p);
return p;
}
static Value push_stack_frame(Value ve, const char *name, Value loc)
{
StackFrame **e = ERROR(ve);
if (scary_length(e) > 0 && frame_should_resolve(e[0]))
e[0]->loc = resolve_location(e, loc);
StackFrame *f = stack_frame_new(name, loc);
scary_push((void ***) &ERROR(ve), (const void *) f);
return ve;
}
[[nodiscard]]
static Value apply(Value env, Value proc, Value args)
{
return PROCEDURE(proc)->apply(env, proc, args);
}
static const char *get_func_name(Value proc)
{
ValueTag t = VALUE_TAG(proc);
if (t == TAG_CFUNC || t == TAG_SYNTAX)
return CFUNC(proc)->name;
return NULL;
}
static Value expect_proper_list(Value l)
{
for (Value p = l; p != Qnil; p = cdr(p))
EXPECT_WITH_OBJ(sch_value_is_pair(p), "improper list for apply", l);
return l;
}
static Value eval_apply(Value env, Value l)
{
Value proc = eval_loc(env, l), args = cdr(l), pargs;
if (value_tag_is(proc, TAG_SYNTAX))
pargs = expect_proper_list(args);
else
pargs = map_eval(env, args);
EXPECT_ERROR_LOCATED(pargs, l);
EXPECT_TYPE(procedure, proc);
Value ret = apply(env, proc, pargs);
if (is_error(ret)) {
const char *fname = get_func_name(proc);
return push_stack_frame(ret, fname, l);
}
return ret;
}
static Value lookup_or_error(Value env, Value v)
{
Value p = env_get(env, v);
EXPECT(p != Qundef, "unbound variable: %s", sch_symbol_to_cstr(v));
return p;
}
static Value eval(Value env, Value v)
{
if (sch_value_is_symbol(v))
return lookup_or_error(env, v);
if (!sch_value_is_pair(v))
return v;
return eval_apply(env, v);
}
static const int64_t *filename_to_newline_pos(const char *filename)
{
for (size_t i = 0, len = scary_length(source_data); i < len; i++) {
if (strcmp(source_data[i]->filename, filename) == 0)
return source_data[i]->newline_pos;
}
return NULL;
}
static void frame_to_line_col(const StackFrame *f, const int64_t *newline_pos,
int64_t *line, int64_t *col)
{
pos_to_line_col(LOCATED_PAIR(f->loc)->pos, newline_pos, line, col);
}
static void dump_line_column(const char *filename, const StackFrame *f)
{
int64_t line, col;
const int64_t *newline_pos = filename_to_newline_pos(filename);
if (newline_pos == NULL) {
append_error_message("\n\t<unknown>");
return;
}
frame_to_line_col(f, newline_pos, &line, &col);
append_error_message("\n\t%s:%"PRId64":%"PRId64" in ",
filename, line, col);
}
static bool find_pair(Value tree, Value pair)
{
for (Value p = tree; p != Qnil; p = cdr(p)) {
if (p == pair)
return true;
if (!sch_value_is_pair(p))
return false;
Value v = car(p);
if (sch_value_is_pair(v) && find_pair(v, pair))
return true;
}
return false;
}
static const char *find_filename(Value pair)
{
for (size_t i = 0, len = scary_length(source_data); i < len; i++) {
Source *src = source_data[i];
if (find_pair(src->ast, pair))
return src->filename;
}
return NULL;
}
static void dump_callee_name(const StackFrame *next)
{
if (next == NULL) {
append_error_message("<toplevel>");
return;
}
Value sym = car(next->loc);
if (sch_value_is_symbol(sym))
append_error_message("'%s'", sch_symbol_to_cstr(sym));
else
append_error_message("<unknown>");
}
static void dump_frame(const StackFrame *f, const StackFrame *next)
{
const char *filename = find_filename(f->loc);
if (filename == NULL) {
append_error_message("\n\t<unknown>");
return;
}
dump_line_column(filename, f);
dump_callee_name(next);
}
static void prepend_cfunc_name(const char *name)
{
if (name == NULL)
return;
size_t len = strlen(name) + 2;// strlen(": ")
char tmp[sizeof(errmsg) - len];
snprintf(tmp, sizeof(tmp), "%s", errmsg);
snprintf(errmsg, sizeof(errmsg), "%s: %s", name, tmp);
}
static bool ignore_lines(FILE *f, int64_t n)
{
char buf[BUFSIZ];
for (ssize_t i = 0; i < n; i++) {
if (fgets(buf, sizeof(buf), f) == NULL)
return false;
}
return true;
}
static bool dump_nth_line(const char *filename, int64_t n)
{
FILE *f = fopen(filename, "r");
if (f == NULL)
return false;
char buf[BUFSIZ];
bool ret = false;
if (!ignore_lines(f, n-1) ||
fgets(buf, sizeof(buf), f) == NULL)
goto out;
append_error_message("\n%s", buf); // `buf` includes "\n"
ret = true;
out:
fclose(f);
return ret;
}
// <space><space>...^
static void dump_column_point(int64_t col)
{
for (ssize_t i = 1; i < col; i++)
append_error_message(" ");
append_error_message("^");
}
static void dump_error_line_with_point(const StackFrame *f)
{
const char *filename = find_filename(f->loc);
if (filename == NULL)
return;
const int64_t *newline_pos = filename_to_newline_pos(filename);
if (newline_pos == NULL)
return;
int64_t line, col;
frame_to_line_col(f, newline_pos, &line, &col);
if (dump_nth_line(filename, line))
dump_column_point(col);
}
static void dump_stack_trace(StackFrame *const *call_stack)
{
size_t len = scary_length(call_stack);
if (len == 0)
return;
const StackFrame *top = call_stack[0];
prepend_cfunc_name(top->func_name);
dump_error_line_with_point(top);
for (size_t i = 0; i < len - 1; i++)
dump_frame(call_stack[i], call_stack[i+1]);
dump_frame(call_stack[len-1], NULL);
}
static void add_source(const Source *newsrc)
{
scary_push((void ***) &source_data, (const void *) newsrc);
size_t len = scary_length(source_data);
gc_add_root(&source_data[len-1]->ast);
}
Value sch_load_file(FILE *in, const char *filename)
{
Source *src = iparse(in, filename);
if (src == NULL)
return Qundef;
add_source(src);
if (setjmp(jmp_exit) != 0)
return sch_integer_new(exit_status);
Value ret = eval_body(env_toplevel, src->ast);
if (is_error(ret)) {
dump_stack_trace(ERROR(ret));
return Qundef;
}
return ret;
}
static Value iload_inner(FILE *in, const char *path)
{
Source *src = iparse(in, path);
if (src == NULL)
return Qundef;
add_source(src);
return eval_body(env_toplevel, src->ast);