This repository has been archived by the owner on May 18, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathbone.c
2821 lines (2549 loc) · 75.8 KB
/
bone.c
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
/* bone.c -- The Bone Lisp interpreter.
* Copyright (C) 2016 Wolfgang Jaehrling
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#define _GNU_SOURCE 1 // for mmap()s MAP_ANONYMOUS
#include <assert.h>
#include <inttypes.h>
#include <math.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
#ifndef MAP_ANONYMOUS
#define MAP_ANONYMOUS MAP_ANON
#endif
#include "bone.h"
my any last_value; // FIXME: thread-local
my bool silence_errors = false; // FIXME: thread-local?
my void eprintf(const char *fmt, ...) {
if(!silence_errors) {
va_list args;
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
}
}
//my void eprint(any); my any L(any x) { eprint(x); puts(""); return x; } // for debugging
my void fail(const char *msg) {
eprintf("%s\n", msg);
exit(1);
}
my size_t bytes2words(size_t n) { return (n - 1) / sizeof(any) + 1; }
my const char *type_name(type_tag tag) {
switch (tag) {
case t_cons: return "cons";
case t_sym: return "sym";
case t_str: return "str";
case t_sub: return "sub";
case t_num: return "num";
case t_other: default: abort(); // never called with t_other
}
}
#define HASH_SLOT_UNUSED UNIQ(100)
#define HASH_SLOT_DELETED UNIQ(101)
#define READER_LIST_END UNIQ(102)
#define BINDING_DEFINED UNIQ(103)
#define BINDING_EXISTS UNIQ(104)
#define BINDING_DECLARED UNIQ(105)
bool is_nil(any x) { return x == NIL; }
bool is(any x) { return x != BFALSE; }
any to_bool(bool x) { return x ? BTRUE : BFALSE; }
my void eprint(any x);
my void backtrace();
my void basic_error(const char *fmt, ...) {
if(!silence_errors) {
eprintf("ERR: ");
va_list args;
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
eprintf("\n");
backtrace();
}
throw();
}
my void generic_error(const char *msg, any x) {
eprintf("ERR: %s: ", msg);
eprint(x);
eprintf("\n");
backtrace();
throw();
}
my void type_error(any x, type_tag t) {
eprintf("ERR: typecheck failed: (%s? ", type_name(t));
eprint(x);
eprintf(")\n");
backtrace();
throw();
}
my type_tag tag_of(any x) { return x & 7; }
my bool is_tagged(any x, type_tag t) { return tag_of(x) == t; }
void check(any x, type_tag t) {
if(!is_tagged(x, t))
type_error(x, t);
}
my any tag(any x, type_tag t) { return x | t; }
my any untag(any x) { return x & ~7; }
my any untag_check(any x, type_tag t) {
check(x, t);
return untag(x);
}
type_other_tag get_other_type(any x) {
any *p = (any *)untag_check(x, t_other);
return p[0];
}
my bool is_num(any x) { return is_tagged(x, t_num); }
my type_num_tag get_num_type(any x) {
check(x, t_num);
return (x >> 3) & 1;
}
int64_t any2int(any x) {
if(get_num_type(x) != t_num_int)
generic_error("ERR: expected integer type", x);
#if (-1 >> 1) == -1 /* Does bit shifting preserve the sign? */
return (int64_t)x >> 4;
#else
return ((int64_t)x < 0)
? (~((~((int64_t)x)) >> 4)) /* Negate before and after */
: ((int64_t)x >> 4);
#endif
}
any int2any(int64_t n) {
if(n < BONE_INT_MIN || n > BONE_INT_MAX)
basic_error("ERR: integer out of allowed range: %" PRId64, n);
return tag((n << 4) | (t_num_int << 3), t_num);
}
typedef union {
float f;
uint32_t ui32;
} float_or_uint32;
float any2float(any x) {
if(get_num_type(x) != t_num_float)
generic_error("ERR: expected float type", x);
float_or_uint32 u;
u.ui32 = ((uint64_t)x) >> 32;
return u.f;
}
any float2any(float f) {
float_or_uint32 u;
u.f = f;
any r = t_num | (t_num_float << 3) | (((uint64_t)u.ui32) << 32);
return r;
}
my float anynum2float(any x) {
switch (get_num_type(x)) {
case t_num_int: return (float)any2int(x);
case t_num_float: return any2float(x);
default: abort();
}
}
//////////////// regions ////////////////
#define ALLOC_BLOCKS_AT_ONCE 16
my size_t blocksize; // in bytes
my size_t blockwords; // words per block
my any blockmask; // to get the block an `any` belongs to; is not actually an object!
my any **free_block;
// A block begins with a pointer to the previous block that belongs to the region.
// The metadata of a region (i.e. this struct) is stored in its first block.
typedef struct reg { any **current_block, **allocp; } *reg;
// This code is in FORTH-style.
my any **block(any *x) { return (any **)(blockmask & (any)x); } // get ptr to start of block that x belongs to.
my any **blocks_alloc(int n) { return mmap(NULL, blocksize * n, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); }
my void block_point_to_next(any **p, int i) { p[i * blockwords] = (any *)&p[(i + 1) * blockwords]; }
my void blocks_init(any **p, int n) { n--; for(int i = 0; i < n; i++) block_point_to_next(p, i); p[n * blockwords] = NULL; }
my any **fresh_blocks() { any **p = blocks_alloc(ALLOC_BLOCKS_AT_ONCE); blocks_init(p, ALLOC_BLOCKS_AT_ONCE); return p; }
my void ensure_free_block() { if(!free_block) free_block = fresh_blocks(); }
my any **block_new(any **next) { ensure_free_block(); any **r = free_block; free_block = (any **)r[0]; r[0] = (any *)next; return r; }
my void reg_init(reg r, any **b) { r->current_block = b; r->allocp = (any **)&r[1]; }
my reg reg_new() { any **b = block_new(NULL); reg r = (reg)&b[1]; reg_init(r, b); return r; }
my void reg_free(reg r) { block((any *)r)[0] = (any *)free_block; free_block = r->current_block; }
my void blocks_sysfree(any **b) { if(!b) return; any **next = (any **)b[0]; munmap(b, blocksize); blocks_sysfree(next); }
my void reg_sysfree(reg r) { blocks_sysfree(r->current_block); }
my reg permanent_reg; // FIXME: thread-local
my reg *reg_stack;
my int reg_pos, reg_allocated;
my any **allocp, **current_block; // from currently used reg.
my void load_reg(reg r) { allocp = r->allocp; current_block = r->current_block; }
my void store_reg(reg r) { r->allocp = allocp; r->current_block = current_block; }
my void inc_regs() {
if(reg_pos == reg_allocated) {
reg_allocated *= 2;
reg_stack = realloc(reg_stack, reg_allocated * sizeof(struct reg));
}
reg_pos++;
}
#define curr_reg reg_stack[reg_pos]
my void reg_push(reg r) { store_reg(curr_reg); inc_regs(); curr_reg = r; load_reg(curr_reg); }
my reg reg_pop() { store_reg(curr_reg); reg r = curr_reg; reg_pos--; load_reg(curr_reg); return r; }
#undef curr_reg
my void reg_permanent() { reg_push(permanent_reg); }
my void in_reg() { reg_push(reg_new()); }
my void end_in_reg() { reg_free(reg_pop()); }
my void rollback_reg_sp(int pos) {
while(pos != reg_pos)
reg_free(reg_pop());
}
any *reg_alloc(int n) {
any *res = (any *)allocp;
allocp += n;
if(block((any *)allocp) == current_block)
return res; // normal case
current_block = block_new(current_block);
allocp = (any **)¤t_block[1];
return reg_alloc(n);
}
my any copy(any x);
my any copy_back(any x) {
reg_push(reg_stack[reg_pos-1]);
any y = copy(x);
reg_pop();
return y;
}
//////////////// exceptions ////////////////
// FIXME: thread-local
my struct exc_buf {
jmp_buf buf;
int reg_pos;
} *exc_bufs;
my int exc_num;
my int exc_allocated;
jmp_buf *begin_try_() {
if(exc_allocated == exc_num) {
exc_allocated *= 2;
exc_bufs = realloc(exc_bufs, exc_allocated * sizeof(struct exc_buf));
}
exc_bufs[exc_num].reg_pos = reg_pos;
return &exc_bufs[exc_num++].buf;
}
my void exc_buf_nonempty() {
if(!exc_num)
fail("internal error: throw/catch mismatch");
}
jmp_buf *throw_() {
exc_buf_nonempty();
exc_num--;
rollback_reg_sp(exc_bufs[exc_num].reg_pos);
return &exc_bufs[exc_num].buf;
}
void end_try_() {
exc_buf_nonempty();
exc_num--;
}
//////////////// conses / lists ////////////////
// no tag() needed as t_cons==0
any cons(any a, any d) {
any *p = reg_alloc(2);
p[0] = a;
p[1] = d;
return (any)p;
}
any far(any x) { return ((any *)x)[0]; } // fast, no typecheck
any fdr(any x) { return ((any *)x)[1]; } // likewise
any car(any x) {
check(x, t_cons);
return far(x);
}
any cdr(any x) {
check(x, t_cons);
return fdr(x);
}
void set_far(any cell, any x) { ((any *)cell)[0] = x; }
void set_fdr(any cell, any x) { ((any *)cell)[1] = x; }
bool is_cons(any x) { return is_tagged(x, t_cons); }
bool is_single(any x) { return is_cons(x) && is_nil(fdr(x)); }
any single(any x) { return cons(x, NIL); }
any list2(any a, any b) { return cons(a, single(b)); }
any list3(any a, any b, any c) { return cons(a, cons(b, single(c))); }
my any pcons(any a, any d) {
reg_permanent();
any res = cons(a, d);
reg_pop();
return res;
}
my any pcopy(any x) {
reg_permanent();
any res = copy(x);
reg_pop();
return res;
}
listgen listgen_new() { listgen res = {NIL, NIL}; return res; }
void listgen_add(listgen *lg, any x) {
if(is_nil(lg->xs))
lg->xs = lg->last = single(x);
else {
any new = single(x);
set_fdr(lg->last, new);
lg->last = new;
}
}
my void listgen_add_list(listgen *lg, any xs) {
foreach(x, xs)
listgen_add(lg, x);
}
my void listgen_set_tail(listgen *lg, any x) {
if(is_nil(lg->xs))
lg->xs = lg->last = x;
else
set_fdr(lg->last, x);
}
my any duplist(any xs) {
listgen lg = listgen_new();
listgen_add_list(&lg, xs);
return lg.xs;
}
int64_t len(any x) {
int64_t n = 0;
foreach_cons(e, x) n++;
return n;
}
my any reverse(any xs) {
any res = NIL;
foreach(x, xs)
res = cons(x, res);
return res;
}
my bool is_member(any a, any xs) {
foreach(x, xs)
if(x == a)
return true;
return false;
}
my any assoc(any obj, any xs) {
foreach(x, xs)
if(car(x) == obj)
return fdr(x);
return BFALSE;
}
my any assoc_entry(any obj, any xs) {
foreach(x, xs)
if(car(x) == obj)
return x;
return BFALSE;
}
my any cat2(any a, any b) {
if(is_nil(a))
return b;
listgen lg = listgen_new();
foreach(x, a)
listgen_add(&lg, x);
listgen_set_tail(&lg, b);
return lg.xs;
}
my any move_last_to_rest_x(any xs) {
if(is_single(xs))
return far(xs);
foreach_cons(pair, xs)
if(is_single(fdr(pair))) {
set_fdr(pair, far(fdr(pair)));
break;
}
return xs;
}
my any merge_sort(any bigger_p, any hd) {
if(is_nil(hd))
return NIL;
hd = duplist(hd);
int64_t area = 1; // size of a part we currently process
while(1) {
any p = hd;
hd = NIL;
any tl = NIL;
int64_t merge_cnt = 0;
while(!is_nil(p)) {
merge_cnt++;
any q = p;
int64_t len_of_p = 0;
for(int64_t i = 0; i < area; i++) {
len_of_p++;
q = fdr(q);
if(is_nil(q))
break;
}
int64_t len_of_q = area;
while(len_of_p > 0 || (len_of_q > 0 && !is_nil(q))) {
// determine source of next element:
bool from_p;
if(len_of_p == 0)
from_p = false;
else if(len_of_q == 0 || is_nil(q))
from_p = true;
else {
call2(bigger_p, far(p), far(q));
from_p = !is(last_value);
}
any e;
if(from_p) {
len_of_p--;
e = p;
p = fdr(p);
} else {
len_of_q--;
e = q;
q = fdr(q);
}
if(!is_nil(tl))
set_fdr(tl, e);
else
hd = e;
tl = e;
}
p = q;
}
set_fdr(tl, NIL);
if(merge_cnt <= 1)
return hd;
area *= 2;
}
}
my bool is_zero(any x) {
switch (get_num_type(x)) {
case t_num_int: return any2int(x) == 0;
case t_num_float: return any2float(x) == 0.0;
default: abort();
}
}
//////////////// strs ////////////////
bool is_str(any x) { return is_tagged(x, t_str); }
my any str(any chrs) {
any *p = reg_alloc(1);
*p = chrs;
return tag((any)p, t_str);
}
my any unstr(any s) { return *(any *)untag_check(s, t_str); }
// FIXME: for short strings only
my any charp2list(const char *p) {
return !*p ? NIL : cons(int2any(*p), charp2list(p + 1));
}
any charp2str(const char *p) { return str(charp2list(p)); }
my char *list2charp(any x) {
char *res = malloc(len(x)*4 + 1); // maximum length for UTF-8
char *p = res;
try {
foreach(c, x) {
*p = any2int(c);
p++;
}
} catch {
free(res);
throw();
}
*p = '\0';
return res;
}
char *str2charp(any x) { return list2charp(unstr(x)); }
my bool str_eql(any s1, any s2) {
s1 = unstr(s1);
s2 = unstr(s2);
foreach(chr, s1) {
if(is_nil(s2) || chr != far(s2))
return false;
s2 = fdr(s2);
}
return is_nil(s2);
}
my any num2str(any n) {
char buf[32];
switch (get_num_type(n)) {
case t_num_int: snprintf(buf, sizeof(buf), "%" PRId64, any2int(n)); break;
case t_num_float: snprintf(buf, sizeof(buf), "%g", (double)any2float(n)); break;
default: abort();
}
return charp2str(buf);
}
//////////////// hash tables ////////////////
#define MAXLOAD 175 // value between 0 and 255
typedef struct hash {
size_t size, taken_slots;
any *keys, *vals;
any default_value;
} *hash;
my hash hash_new(size_t initsize, any default_val) {
hash h = malloc(sizeof(*h));
h->size = initsize;
h->taken_slots = 0;
h->default_value = default_val;
h->keys = malloc(initsize * sizeof(any));
h->vals = malloc(initsize * sizeof(any));
for(size_t i = 0; i != initsize; i++)
h->keys[i] = HASH_SLOT_UNUSED;
return h;
}
my void hash_free(hash h) {
free(h->keys);
free(h->vals);
free(h);
}
/* Find the entry in H with KEY and provide the entry number in *POS.
Return true if there is an entry with this key already. If there
is none, *POS will contain the position of the slot we can use to
add it. */
my bool find_slot(hash h, any key, size_t *pos) {
bool found_deleted = false;
size_t first_deleted = 0;
*pos = key % h->size;
while(1) {
if(h->keys[*pos] == key)
return true;
if(h->keys[*pos] == HASH_SLOT_UNUSED) {
if(found_deleted)
*pos = first_deleted;
return false;
}
if(h->keys[*pos] == HASH_SLOT_DELETED) {
if(!found_deleted) {
found_deleted = true;
first_deleted = *pos;
}
}
if(++(*pos) == h->size)
*pos = 0;
}
}
my void hash_set(hash h, any key, any val);
my bool slot_used(any x) {
return x != HASH_SLOT_UNUSED && x != HASH_SLOT_DELETED;
}
my void enlarge_table(hash h) {
hash new = hash_new(h->size * 2 + 1, NIL);
for(size_t i = 0; i != h->size; i++)
if(slot_used(h->keys[i]))
hash_set(new, h->keys[i], h->vals[i]);
free(h->keys);
free(h->vals);
h->size = new->size;
h->keys = new->keys;
h->vals = new->vals;
free(new);
}
my void hash_set(hash h, any key, any val) {
size_t pos;
if(!find_slot(h, key, &pos)) { // adding a new entry
h->taken_slots++;
if(((h->taken_slots << 8) / h->size) > MAXLOAD) {
enlarge_table(h);
find_slot(h, key, &pos);
}
}
h->keys[pos] = key;
h->vals[pos] = val;
}
my any hash_get(hash h, any key) {
size_t pos;
return find_slot(h, key, &pos) ? h->vals[pos] : h->default_value;
}
my void hash_rm(hash h, any key) {
size_t pos;
if(find_slot(h, key, &pos)) {
h->keys[pos] = HASH_SLOT_DELETED;
h->taken_slots--;
}
}
#if 0 // FIXME: hash_iter
my void hash_each(hash h, hash_iter fn, void *hook) {
for(size_t i = 0; i != h->size; i++)
if(slot_used(h->keys[i])) fn(hook, h->keys[i], h->vals[i]);
}
my void hash_print(hash h) { // useful for debugging
for(size_t i = 0; i != h->size; i++)
if(slot_used(h->keys[i])) {
print(h->keys[i]); bputc(':'); print(h->vals[i]); bputc('\n');
}
}
#endif
//////////////// syms ////////////////
my bool is_sym(any x) { return is_tagged(x, t_sym); }
my hash sym_ht;
my any string_hash(const char *s, size_t *len) { // This is the djb2 algorithm.
int32_t hash = 5381;
*len = 0;
while(*s) {
(*len)++;
hash = ((hash << 5) + hash) + *(s++);
}
return int2any(hash);
}
char *symtext(any sym) { return (char *)untag_check(sym, t_sym); }
// `name` must be interned
my any as_sym(char *name) {
return tag((any)name, t_sym);
}
my any add_sym(const char *name, size_t len, any id) {
reg_permanent();
char *new = (char *)reg_alloc(bytes2words(len + 1));
reg_pop();
memcpy(new, name, len + 1);
hash_set(sym_ht, id, (any) new);
return as_sym(new);
}
any intern(const char *name) {
size_t len;
any id = string_hash(name, &len);
while(1) {
char *candidate = (char *)hash_get(sym_ht, id);
if(candidate == NULL)
return add_sym(name, len, id);
if(!strcmp(candidate, name))
return as_sym(candidate);
id++;
}
}
my any intern_from_chars(any chrs) {
char *s = list2charp(chrs);
any res = intern(s);
free(s);
return res;
}
my any gensym() {
static int gensyms = 0; // FIXME: multiple threads?
reg_permanent();
char *new = (char *)reg_alloc(1);
reg_pop();
snprintf(new, sizeof(any), "_g%05d", gensyms++);
return as_sym(new);
}
my any sym2str(any sym) { return charp2str(symtext(sym)); }
my any s_quote, s_quasiquote, s_unquote, s_unquote_splicing, s_lambda, s_with,
s_if, s_list, s_cat, s_dot, s_do, s_arg, s_env;
#define x(name) s_##name = intern(#name)
my void init_syms() {
x(quote); x(quasiquote); x(unquote); s_unquote_splicing = intern("unquote-splicing");
x(lambda); x(with); x(if); x(do); x(list); x(cat); s_dot = intern(".");
x(arg); x(env);
}
#undef x
//////////////// subs ////////////////
typedef struct sub_code { // fields are in the order in which we access them.
int argc; // number of required args
int take_rest; // accepting rest args? 0=no, 1=yes
int extra_localc; // the ones introduced by `with`
any name; // sym for backtraces
int size_of_env; // so that we can copy subs
any ops[1]; // can be longer
} *sub_code;
my char *sub_allocp;
my size_t sub_alloc_left; // in bytes!
my void ensure_sub_alloc(size_t size) {
if(size > sub_alloc_left) {
int additional_blocks = size / blocksize; // to allow extremely large subs
int blocks = ALLOC_BLOCKS_AT_ONCE + additional_blocks;
sub_allocp = (char*)blocks_alloc(blocks);
sub_alloc_left = blocks * blocksize;
}
}
my sub_code sub_alloc(size_t codeword_cnt) {
size_t size = (codeword_cnt-1)*sizeof(any) + sizeof(struct sub_code);
ensure_sub_alloc(size);
sub_code res = (sub_code)sub_allocp;
sub_allocp += size;
sub_alloc_left -= size;
return res;
}
my sub_code make_sub_code(int argc, int take_rest, int extra_localc, int size_of_env, int code_size) {
sub_code code = sub_alloc(code_size);
code->argc = argc;
code->take_rest = take_rest;
code->extra_localc = extra_localc;
code->size_of_env = size_of_env;
code->name = BFALSE;
return code;
}
my int count_locals(sub_code sc) {
return sc->argc + sc->take_rest + sc->extra_localc;
}
typedef struct sub {
sub_code code;
any env[0];
} *sub;
my bool is_sub(any x) { return is_tagged(x, t_sub); }
my any sub2any(sub s) { return tag((any)s, t_sub); }
my sub any2sub(any x) { return (sub)untag_check(x, t_sub); }
my any copy_sub(any x) {
sub s = any2sub(x);
int envsize = s->code->size_of_env;
any *p = reg_alloc(1 + envsize);
any res = tag((any)p, t_sub);
*p++ = (any)s->code;
for(int i = 0; i != envsize; i++)
*p++ = s->env[i] == x ? res : copy(s->env[i]); // allow recursive subs
return res;
}
my void name_sub(sub subr, any name) {
if(!is(subr->code->name))
subr->code->name = name;
}
//////////////// bindings ////////////////
my any get_dyn_val(any name);
my void check_overwrite(hash namespace, any name) {
any prev = hash_get(namespace, name);
if(is(prev) && far(prev) == BINDING_DEFINED && !is(get_dyn_val(intern("_*allow-overwrites*"))))
generic_error("already defined", name);
}
my void add_name(hash namespace, any name, bool overwritable, any val) {
check_overwrite(namespace, name);
if(is_sub(val))
name_sub(any2sub(val), name);
hash_set(namespace, name, pcons(overwritable ? BINDING_EXISTS : BINDING_DEFINED, pcopy(val)));
}
my hash bindings; // FIXME: does it need mutex protection? -> yes, but we use it only at compile-time anyway
my any get_binding(any name) { return hash_get(bindings, name); }
my void bind(any name, bool overwritable, any subr) {
add_name(bindings, name, overwritable, subr);
}
my bool is_bound(any name) { return get_binding(name) != BFALSE; }
my void declare_binding(any name) {
check_overwrite(bindings, name);
hash_set(bindings, name, pcons(BINDING_DECLARED, BFALSE));
}
my hash macros; // FIXME: needs mutex protection, see above
my void mac_bind(any name, bool overwritable, any subr) {
add_name(macros, name, overwritable, subr);
}
my any get_mac(any name) { return hash_get(macros, name); }
my bool is_mac_bound(any name) { return get_mac(name) != BFALSE; }
my hash readers; // FIXME: needs mutex protection, see above
my void reader_bind(any name, bool overwritable, any subr) {
add_name(readers, name, overwritable, subr);
}
my any get_reader(any name) { return hash_get(readers, name); }
my bool is_reader_bound(any name) { return get_reader(name) != BFALSE; }
my hash dynamics; // this is shared by threads, it just contains numbers as values
my any dynamic_vals[256]; // FIXME: thread-local, resize
my int dyn_cnt = 0;
my any get_dyn(any name) { return hash_get(dynamics, name); }
my bool is_dyn_bound(any name) { return is(get_dyn(name)); }
my void check_dyn_bound(any x, any name) { if(!is(x)) generic_error("dynamic var unbound", name); }
my void set_dyn_val(any name, any x) {
any n = get_dyn(name);
check_dyn_bound(n, name);
dynamic_vals[any2int(n)] = x;
}
my void create_dyn(any name, any x) {
if(is_dyn_bound(name) && !is(get_dyn_val(intern("_*allow-overwrites*"))))
generic_error("dynamic var bound twice", name);
hash_set(dynamics, name, int2any(dyn_cnt));
dynamic_vals[dyn_cnt] = x;
dyn_cnt++;
}
my any get_existing_dyn(any name) {
any x = get_dyn(name);
check_dyn_bound(x, name); // if this fails, it's an internal error
return x;
}
my any get_dyn_val(any name) {
return dynamic_vals[any2int(get_existing_dyn(name))];
}
//////////////// UTF-8 ////////////////
#define BITEST(val, one, zero) ((((val) & one) == one) && ((((val) ^ zero) & zero) == zero))
my void invalid_utf8(const char *msg) { basic_error("utf-8 I/O: %s", msg); }
typedef int (*utf8_reader)(void *hook);
// read UTF-8 according to RFC 3629.
my int utf8_read(utf8_reader reader, void *hook) {
int val = reader (hook);
if(val == EOF) return val;
if(BITEST(val, 0, 0x80)) return val; // ASCII range
int how_many_more = 0;
if(BITEST(val, 0xC0, 0x20)) {
val &= 0x1F; // keep only code point relevant bits
how_many_more = 1;
}
else if(BITEST(val, 0xE0, 0x10)) {
val &= 0x0F; // see above
how_many_more = 2;
}
else if(BITEST(val, 0xF0, 0x08)) {
val &= 0x07; // see above
how_many_more = 3;
}
else invalid_utf8("unexpected continuation byte");
for(int i = 0; i < how_many_more; i++) {
int next = reader(hook);
if(next == EOF) invalid_utf8("EOF where continuation byte was expected");
if(!BITEST(next, 0x80, 0x40)) invalid_utf8("missing continuation byte");
val <<= 6;
val |= (next & 0x3F);
}
// overlong & out-of-range encodings.
#define not_overlong(min) if(!(val >= (min))) invalid_utf8("overlong encoding is forbidden")
switch (how_many_more) {
case 1: not_overlong(0x80); break;
case 2: not_overlong(0x800); break;
case 3:
not_overlong(0x10000);
if(val >= 0x10FFFF) invalid_utf8("character out of range specified in RFC 3629");
break;
#undef not_overlong
}
return val;
}
my int from_strp(const char **sp) {
char c = **sp;
(*sp)++;
return c;
}
my int utf8from_strp(const char **sp) {
return utf8_read ((utf8_reader) &from_strp, sp);
}
my int utf8getc(FILE *fp) {
return utf8_read((utf8_reader) &getc, fp);
}
typedef void (*utf8_writer)(int c, void *hook);
my void utf8_write(utf8_writer writer, int c, void *hook)
{
#define emit(x) writer(x, hook)
if(c < 0x80) { // ASCII range
emit(c);
return;
}
// extract and mask.
#define CONT_BYTE(x) (((x) & 0x3F) | 0x80)
if(c < 0x800) {
emit((c >> 6) | 0xC0);
emit(CONT_BYTE(c));
}
else if(c < 0x10000) {
emit((c >> 12) | 0xE0);
emit(CONT_BYTE(c >> 6));
emit(CONT_BYTE(c));
}
else if(c < 0x110000) {
emit((c >> 18) | 0xF0);
emit(CONT_BYTE(c >> 12));
emit(CONT_BYTE(c >> 6));
emit(CONT_BYTE(c));
}
else invalid_utf8("character out of range specified in RFC 3629");
#undef CONT_BYTE
#undef emit
}
my void to_strp(int c, char **sp) {
**sp = c;
(*sp)++;
}
my void utf8to_strp(int c, char **sp) {
utf8_write((utf8_writer)to_strp, c, sp);
}
my void utf8putc(int c, FILE *fp) {
utf8_write((utf8_writer)putc, c, fp);
}
//////////////// srcs and dsts ////////////////
typedef struct io {
type_other_tag t;
FILE *fp;
any name;
int line;
} *io;
my any fp2any(FILE *fp, type_other_tag t, any name) {
io res = (io)reg_alloc(bytes2words(sizeof(*res)));
res->t = t;
res->fp = fp;
res->name = name;
res->line = 1;
return tag((any)res, t_other);
}