-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplan.c
3112 lines (2570 loc) · 69.5 KB
/
plan.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
// # Quine
// - ☑ Run the quine.
// - ☐ Check that the quine re-produces an identical value.
//
// Make the quine take a `main` argument, and assert that it's
// equal to the "main" binding at the end of execution.
//
// This may work with the existing Cmp, but it also may be too slow
// since we have many duplicated pins. In the latter case, we will
// need to use pin-hashing.
// # Correctness Issues
// - ✓ Bottom-safe version of the cmp jet (don't force first).
// # Minimize the Heap Layout
// - ☐ Bit-pack the nat size directly into the tag.
// - ☐ Bit-pack the law size directly into the tag.
// - ☐ Use smaller numbers for the law weights.
// - ☐ Don't store the law weights if we codegen (Law is a union type)
// # Only one mmap() region.
// - ☐ Put the JIT code directly on the laws.
// # Persist
// - ☐ Use offsets instead of pointers.
// - ☐ Second GC generation at the beginning of the mapping.
// - Don't collect from the second generation.
// - Move to the 2nd gen between evals (no stack)
// - Layout should be: [2nd] [stack] [gap]? [fst]
// - First: run normal gc to compact new data.
// - But always copy to the right.
// - Second: expand the second generation to make room for the new data.
// - Third: move new data into the 2nd gen.
// - Just traverse the 2nd gen, and move all objects.
// - Reference into the first gen are just offset by a fixed number.
// - ☐ Use a disk-backed mmap() for the 2nd gen.
// - ☐ Sync to disk after each growth of the 2nd gen.
// - ☐ Figure out how to write snapshots + restore from snapshots.
// # WASM
// - ☐ Get this to compile to WASM.
// # No Stdlib
// - ✓ Seed loader uses only system calls, no stdlib IO.
// - ✓ Trace() does not use stdlib.
// - ☐ printv does not use stdlib.
// - ☐ repl() uses only system calls, no stdlib IO.
// - ✓ Remove all uses of malloc() (including in BSDNT).
#include <fcntl.h>
#include <stdint.h>
#define __STDC_WANT_LIB_EXT2__ 1
#include <stdio.h>
#include <stdbool.h>
#include <ctype.h>
#include <stdarg.h>
#include <string.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <inttypes.h>
#include <unistd.h>
#include <stdnoreturn.h>
#include "bsdnt/nn.h"
#include <sys/mman.h>
#include "linked_list.h"
// Config //////////////////////////////////////////////////////////////////////
#define BLOCK_SIZE 65536
#define STACK_SIZE 65536
#define HEAP_LOCAL ((void*)(1ULL<<24))
#define JIT_LOCAL ((void*)(1ULL<<42))
#define TRACE_JET_MATCHES 0
#define TRACE_CALLS 0
#define TRACE_LAWS 0
#define ENABLE_GRAPHVIZ 0
#define STACK_BOUNDS_CHECK 0
#define CHECK_TAGS 0
#define CHECK_DIRECT 0
#define ENABLE_ASSERTIONS 0
#define ENABLE_VALIDATION 0
#define ENABLE_PRINTER 1
#if ENABLE_ASSERTIONS
#define ASSERT_(x) assert(x)
#else
static inline void ASSERT_(bool b) {}
#endif
// Types ///////////////////////////////////////////////////////////////////////
typedef uint64_t u64;
// Note that underlying enum number for BIG, PIN, LAW, APP are in
// sort-order.
typedef enum Type { BIG, PIN, LAW, APP, IND, MOV } Type;
typedef struct Value Value;
typedef struct Big { len_t size; } Big;
typedef struct Ind { Value *ptr; } Ind;
typedef struct Value Value;
typedef enum JetTag { J_ADD, J_SUB, J_MUL, J_DIV, J_MOD, J_DEC,
J_CMP, J_TRACE, J_NONE, } JetTag;
typedef struct Pin {
Value *item;
JetTag jet;
} Pin;
typedef struct LawWeight {
u64 n_lets, n_calls;
} LawWeight;
typedef struct Law {
Value *n; // Always a nat
Value *a; // Always a nat
Value *b;
LawWeight w;
// TODO
// void (*mach_code)(void);
// int num_cnsts;
// // store cnsts here directly
} Law;
typedef struct App { Value *f, *g; } App;
struct Value {
Type type;
union { Pin p; Law l; App a; Big n; Ind i; };
};
////////////////////////////////////////////////////////////////////////////////
// Prototypes
static len_t ByteSz (Value*);
static Value *normalize (Value*);
static JetTag jet_match (Value*);
static void mk_app (void);
static void update (u64);
static void force (void);
static bool eval (void);
static void eval_update (int);
static void force_in_place (int);
static void frag_load (Value**, u64, int*, u64*, u64**);
static bool read_exp (FILE *f);
#if ENABLE_GRAPHVIZ
static char dot_lab[1024];
static bool enable_graphviz = 0;
static const char *dot_dir_path = "./dot";
static char *p_ptr (Value*);
static void write_dot (char*);
static void write_dot_extra (char*, char*, Value*);
#endif
#if ENABLE_VALIDATION
void check_value (Value *v);
#else
#define check_value(v)
#endif
#if ENABLE_PRINTER
static void fprint_nat(FILE *, Value *);
static bool is_symbol(Value *);
static void fprintv(FILE*, Value*);
static void fprintv_internal(FILE *, Value *, int);
#else
#define fprint_nat(f,v)
#define fprintv(f,v)
#endif
// Utils ///////////////////////////////////////////////////////////////////////
noreturn void crash(char *s) { printf("Error: %s\n", s); exit(1); }
noreturn void pexit(char *s) { perror(s); exit(1); }
// Globals /////////////////////////////////////////////////////////////////////
#if TRACE_CALLS
int call_depth = 0; // for debugging traces
#endif
static char *loom = NULL;
static char *heap_start = NULL;
static char *heap_end = NULL;
static char *live_start = NULL;
static char *live_end = NULL;
static char *hp = NULL;
static Value **stack = NULL;
static Value **stack_end = NULL;
// TODO: this isn't yet used, but the idea is to be able to codegen
// calls to things like push() as direct register operations.
register Value **sp asm ("r12"); // sp[0] is the top value
static Value **printer_seed = NULL;
static Value **compiler_seed = NULL;
static Value **symbol_table = NULL;
// GC Heap /////////////////////////////////////////////////////////////////////
void rts_init (void) {
const int rwx = PROT_READ | PROT_WRITE | PROT_EXEC;
const int heap_flags = MAP_PRIVATE | MAP_ANON;
ssize_t initialLoomSz = (sizeof(Value) * STACK_SIZE) + BLOCK_SIZE;
// Find a safe place to put the heap, then release it to avoid
// massive core dumps.
loom = mmap(NULL, (1ULL<<40), rwx, heap_flags | MAP_NORESERVE, -1, 0);
if (loom == MAP_FAILED) perror("rts_init: reserve: mmap"), exit(1);
int err = munmap(loom, (1ULL<<40));
if (err != 0) perror("rts_init: munmap"), exit(1);
// Then allocate the section that we need to start with using MAP_FIXED.
loom = mmap(loom, initialLoomSz, rwx, heap_flags | MAP_FIXED, -1, 0);
if (loom == MAP_FAILED) { perror("rts_init: mmap"); exit(1); }
// Initialize the globals used for the stack/heap.
stack = (void*) loom;
stack_end = stack + STACK_SIZE;
sp = stack_end;
heap_start = (void*) stack_end;
heap_end = heap_start + BLOCK_SIZE;
live_start = heap_start;
live_end = heap_end;
hp = live_start;
}
/*
{extend_mmap} doubles the size of the mapped heap until it covers
the end of the live region.
It uses MAP_FIXED to simply grow the mapped region. We get the size
of the current heap, and simply allocate another mmap region of the
same size, immediately after the currently mapped region.
Using MAP_FIXED is simple, but not robust or portable.
This will double the heap_size *multiple times* if needed to cover
the live area (but that shouldn't actually happen in practice).
*/
void extend_mmap (void) {
const int rwx = PROT_READ | PROT_WRITE | PROT_EXEC;
const int flags = MAP_FIXED | MAP_PRIVATE | MAP_ANON;
while (live_end > heap_end) {
len_t heapSz = heap_end - heap_start;
if (heap_end != mmap(heap_end, heapSz, rwx, flags, -1, 0))
{ perror("extend_mmap: mmap"); exit(1); }
heap_end += heapSz;
}
}
/*
{heap_resize} sets the end of the live region to be twice as big as
the amount of used data (after gc), rounded up to the nearest
BLOCK_SIZE.
*/
void heap_resize (void) {
ssize_t used_bytes = hp - live_start;
ssize_t used_blocks = (((used_bytes + BLOCK_SIZE) - 1) / BLOCK_SIZE);
ssize_t new_size = BLOCK_SIZE * 2 * used_blocks;
live_end = live_start + new_size;
extend_mmap();
}
static void cheney (void);
void gc (void) {
// copy left
if (heap_start < live_start) {
hp = live_start = heap_start;
hp = live_start;
cheney();
heap_resize();
return;
}
// copy right
if (heap_start == live_start) {
ssize_t live_size = live_end - live_start;
live_start = heap_start + (live_size * 2); // leave room for left-copy
live_end = live_start + live_size;
hp = live_start;
extend_mmap();
cheney();
heap_resize();
return;
}
crash("gc: impossible: bad live_start");
}
static inline void *alloc(size_t bytes) {
again:
char *res = hp;
hp += bytes;
if (hp > live_end) { gc(); goto again; }
return res;
}
// argument is in bytes, but must be a multiple of 8.
static inline void *jit_alloc(size_t bytes) {
crash("TODO: just put this directly into the law.");
}
// Direct Nats /////////////////////////////////////////////////////////////////
// if the high bit is set, then the remaining 63 bits should be interpreted as
// a nat. this is simpler than having to modify all pointers to mask/unmask
// their high bit.
// 2^63 - high bit
# define PTR_NAT_MASK 9223372036854775808ull
# define DIRECT_ZERO ((Value*)9223372036854775808ull)
# define DIRECT_ONE ((Value*)9223372036854775809ull)
# define DIRECT_TWO ((Value*)9223372036854775810ull)
static inline bool is_direct(Value *x) {
return (((u64) x) & PTR_NAT_MASK);
}
static inline u64 get_direct(Value *x) {
return (u64) (((u64) x) & ~PTR_NAT_MASK);
}
static inline Value *DIRECT(u64 x) {
#if CHECK_DIRECT
if (x & PTR_NAT_MASK) crash("DIRECT: too big");
#endif
return (Value *) (x | PTR_NAT_MASK);
}
// Stack Operations ////////////////////////////////////////////////////////////
static inline ssize_t get_stack_size (void) {
return (stack_end - sp);
}
static inline Value *deref (Value *x) {
while (!is_direct(x) && x->type == IND) x = x->i.ptr;
return x;
}
static inline Value *pop (void) {
#if STACK_BOUNDS_CHECK
if (sp >= stack_end) crash("pop: empty stack");
#endif
Value *res = *sp;
sp++;
return res;
}
static inline Value **get_ptr (u64 idx) {
#if STACK_BOUNDS_CHECK
if (sp+idx >= stack_end) crash("get: indexed off stack");
#endif
return sp+idx;
}
static inline void push_val (Value *x) {
#if ENABLE_GRAPHVIZ
char extra[50];
char *x_p = p_ptr(x);
sprintf(extra, "i[color=red];\ni -> %s", x_p);
free(x_p);
write_dot_extra("push_val", extra, x);
#endif
sp--;
#if STACK_BOUNDS_CHECK
if (sp < stack) crash("push_val: stack overflow");
#endif
*sp = x;
}
static inline Value *pop_deref (void) { return deref(pop()); }
static inline Value *get (u64 idx) { return *get_ptr(idx); }
static inline Value *get_deref (u64 idx) { return deref(get(idx)); }
static inline void push(u64 idx) {
#if ENABLE_GRAPHVIZ
snprintf(dot_lab, 1024, "push %lu", idx);
write_dot(dot_lab);
#endif
push_val(get_deref(idx));
}
// before: ..rest x y
// after: ..rest y x
static inline void swap() {
Value *n1 = pop();
Value *n2 = pop();
push_val(n1);
push_val(n2);
}
static inline void slide (u64 count) {
#if ENABLE_GRAPHVIZ
snprintf(dot_lab, 1024, "slide %lu", count);
write_dot(dot_lab);
#endif
#if STACK_BOUNDS_CHECK
if (sp+count >= stack_end) crash("stack underflow");
#endif
sp[count] = *sp;
sp += count;
#if ENABLE_GRAPHVIZ
snprintf(dot_lab, 1024, "post slide %lu", count);
write_dot(dot_lab);
#endif
}
////////////////////////////////////////////////////////////////////////////////
// Accessors
static Value *deref(Value *x);
static inline void ck_pin(char *fn_nm, Value *x) {
char s[14];
sprintf(s, "%s not a PIN!", fn_nm);
if (x->type != PIN) crash(s);
}
// we allow PIN LAWs
static inline void ck_law(char *fn_nm, Value *x) {
char s[28];
sprintf(s, "%s not a LAW or PIN-LAW!", fn_nm);
if (x->type == LAW) return;
if (x->type == PIN) {
return ck_law(fn_nm, x->p.item);
}
crash(s);
}
static inline void ck_app(char *fn_nm, Value *x) {
char s[15];
sprintf(s, "%s not an APP!", fn_nm);
if (x->type != APP) crash(s);
}
static inline void ck_nat(char *fn_nm, Value *x) {
char s[14];
sprintf(s, "%s not a BIG!", fn_nm);
if (x->type != BIG) crash(s);
}
static inline void ck_ind(char *fn_nm, Value *x) {
char s[14];
sprintf(s, "%s not a IND!", fn_nm);
if (x->type != IND) crash(s);
}
static inline Type TY(Value *x) {
if (is_direct(x)) return BIG;
return x->type;
}
#define SI static inline
SI bool IS_NAT(Value *x) { return (is_direct(x) || x->type == BIG); }
SI bool IS_LAW(Value *x) { return (!is_direct(x) && x->type == LAW); }
SI bool IS_APP(Value *x) { return (!is_direct(x) && x->type == APP); }
static inline Value *IT(Value *x) {
x = deref(x);
#if CHECK_TAGS
ck_pin("IT", x);
#endif
return x->p.item;
};
static inline Value *NM(Value *x) {
x = deref(x);
#if CHECK_TAGS
ck_law("NM", x);
#endif
if (x->type == PIN) return NM(x->p.item);
return x->l.n;
}
static inline Value *AR(Value *x) {
x = deref(x);
#if CHECK_TAGS
ck_law("AR", x);
#endif
if (x->type == PIN) return AR(x->p.item);
return x->l.a;
}
static inline Value *BD(Value *x) {
x = deref(x);
#if CHECK_TAGS
ck_law("BD", x);
#endif
if (x->type == PIN) return BD(x->p.item);
return x->l.b;
}
static inline Law FUNC(Value *x) {
x = deref(x);
if (x->type == PIN) return FUNC(x->p.item);
return x->l;
}
static inline Value *HD(Value *x) {
x = deref(x);
#if CHECK_TAGS
ck_app("HD", x);
#endif
return x->a.f;
};
static inline Value *TL(Value *x) {
x = deref(x);
#if CHECK_TAGS
ck_app("TL", x);
#endif
return x->a.g;
};
static inline Value *IN(Value *x) {
#if CHECK_TAGS
ck_ind("IN", x);
#endif
return x->i.ptr;
};
static inline len_t WID(Value *v) {
return v->n.size;
}
static inline word_t *BUF(Value *v) {
return (void*) (&(v->n.size) + 1);
}
#define BIND_BUF_PTR(nm, v) \
word_t tmp; \
char *nm; \
if (is_direct(v)) { \
tmp = get_direct(v); \
nm = (char*) &tmp; \
} else { \
nm = (char*) BUF(v); \
}
////////////////////////////////////////////////////////////////////////////////
// Construction
/*
WARNING! It is not acceptable to allocate between
start_bignat_alloc() and end_bignat_alloc() (or abort_bignat_alloc()).
The finalizing functions *shrink* the initial allocation, and all hell
will break loose if the nat is no longer that last thing on the heap.
*/
// just allocates the space. caller must fill buf.
Value *start_bignat_alloc(size_t num_words) {
// tag size words..
Value *res = (Value *)alloc(8 * (2 + num_words));
res->type = BIG;
res->n.size = num_words;
return res;
}
static inline void abort_bignat_alloc(Value *v) {
hp -= ((2 + v->n.size) * 8);
}
// shrinks a "candidate" bignat and DECREASES THE SIZE OF THE HEAP so
// that the next thing will be allocated in the right place.
Value *end_bignat_alloc(Value *v) {
size_t old_sz = v->n.size;
size_t sz = old_sz;
word_t *buf = BUF(v);
while (sz && buf[sz - 1] == 0) sz--;
if (sz == 0) {
abort_bignat_alloc(v);
return DIRECT_ZERO;
}
if (sz == 1 && 0 == (buf[0] >> 63)) {
abort_bignat_alloc(v);
return DIRECT(buf[0]);
}
if (sz == old_sz) return v;
v->n.size = sz; // shrink size
hp -= (8 * (old_sz - sz)); // shrink heap
return v;
}
// This needs to exist for now because the JIT generates calls to it.
void push_direct(u64 x) { return push_val(DIRECT(x)); }
static inline void push_word(u64 x) {
if (!(x & PTR_NAT_MASK)) {
push_val((Value *) (x | PTR_NAT_MASK));
return;
}
Value *res = (Value *)alloc(3 * 8);
res->type = BIG;
res->n.size = 1;
BUF(res)[0] = x;
push_val(res);
}
static inline Value *a_Pin(Value *item) {
push_val(item);
Value *res = (Value *)alloc(24); // tag, item, jet_tag
item = pop();
res->type = PIN;
JetTag jet = jet_match(item);
res->p = (Pin){ .item = item, .jet = jet };
return res;
}
static inline Value *a_Law(Law l) {
push_val(l.n);
push_val(l.a);
push_val(l.b);
// tag name args body weights
Value *res = (Value *)alloc(32 + sizeof(LawWeight));
l.b = pop();
l.a = pop();
l.n = pop();
*res = (Value){ .type = LAW, .l = l };
return res;
}
////////////////////////////////////////////////////////////////////////////////
// Nat Operators
int less=0, equals=1, greater=2;
static inline int cmp_direct(u64 a, u64 b) {
if (a == b) return equals;
if (a < b) return less;
return greater;
}
static inline int big_cmp(Value *a, Value *b) {
if (WID(a) != WID(b)) {
return (WID(a) < WID(b)) ? less : greater;
}
int nnres = nn_cmp_m(BUF(a), BUF(b), WID(a));
if (nnres < 0) return less;
if (nnres == 0) return equals;
return greater;
}
int cmp_recur(Value *a, Value *b) {
tail_recur:
a=deref(a), b=deref(b);
if (is_direct(a))
return (!is_direct(b))
? less
: cmp_direct(get_direct(a), get_direct(b));
if (is_direct(b)) return greater;
if (a->type < b->type) return less;
if (a->type > b->type) return greater;
switch (a->type) {
case BIG:
return big_cmp(a, b);
case PIN:
a=IT(a); b=IT(b); goto tail_recur;
case LAW:
{
int ord;
if (b->type != LAW) return less;
ord = cmp_recur(NM(a), NM(b));
if (ord != 1) return ord;
ord = cmp_recur(AR(a), AR(b));
if (ord != 1) return ord;
a=BD(a); b=BD(b); goto tail_recur;
}
case APP:
{
int ord = cmp_recur(HD(a), HD(b));
if (ord != 1) return ord;
a=TL(a); b=TL(b); goto tail_recur;
}
default:
crash("cmp: impossible");
}
}
// fast path for direct atoms, fallback to full cmp routine.
static inline int cmp_normalized(Value *a, Value *b) {
if (is_direct(a) && is_direct(b))
return cmp_direct(get_direct(a), get_direct(b));
return cmp_recur(a,b);
}
static inline int cmp_lazy() {
tail_recur:
eval_update(0);
eval_update(1); // TODO: which order does the PLAN eval in?
Value *a = *sp++;
Value *b = *sp++;
if (a == b) return equals; // pointer-equality shortcut
int aTy=TY(a), bTy=TY(b);
if (aTy != APP) {
if (bTy != APP) return cmp_normalized(a, b);
return less;
}
if (bTy != APP) return greater;
push_val(TL(b));
push_val(TL(a));
push_val(HD(b));
push_val(HD(a));
int ord = cmp_lazy();
if (ord != 1) { sp += 2; return ord; }
goto tail_recur;
}
static inline bool LT(Value *a, Value *b) {
return cmp_normalized(a,b) == 0;
}
static inline bool GT(Value *a, Value *b) {
return cmp_normalized(a,b) == 2;
}
static inline bool LTE(Value *a, Value *b) {
return cmp_normalized(a,b) != 2;
}
static inline bool GTE(Value *a, Value *b) {
return cmp_normalized(a,b) != 0;
}
static inline bool EQ(Value *a, Value *b) {
return cmp_normalized(a,b) == 1;
}
static inline bool NEQ(Value *a, Value *b) {
return cmp_normalized(a,b) != 1;
}
static inline bool EQZ(Value *x) {
return (x == DIRECT_ZERO);
}
static inline bool EQ1(Value *x) {
return (x == DIRECT_ONE);
}
static inline bool EQ2(Value *x) {
return (x == DIRECT_TWO);
}
void WordPlusWord(u64 a, u64 b) {
if (b <= (UINT64_MAX - a)) {
push_word(a + b);
return;
}
// overflow
Value *res = start_bignat_alloc(2);
u64 *buf = BUF(res);
buf[0] = a + b;
buf[1] = 1;
push_val(res); // no need to push_val_end because never too small.
}
void BigPlusWord(u64 word, Value *big) {
u64 bigSz = WID(big);
// this is probably unnecessary, but is defensive against bad input.
if (is_direct(big)) {
WordPlusWord(word, get_direct(big));
return;
}
if (bigSz == 1) {
WordPlusWord(word, BUF(big)[0]);
return;
}
u64 newSz = bigSz + 1;
push_val(big);
Value *res = start_bignat_alloc(newSz); // gc
big = pop();
word_t carry = nn_add1(BUF(res), BUF(big), bigSz, word);
BUF(res)[bigSz] = carry;
push_val(end_bignat_alloc(res));
}
// invariant: a.size >= b.size
// stack before: ..rest b a
// stack after: ..rest (a+b)
void BigPlusBig(Value *a, Value *b) {
u64 aSize = WID(a);
u64 bSize = WID(b);
if (aSize == 1) {
if (bSize == 1) {
WordPlusWord(BUF(a)[0], BUF(b)[0]);
return;
}
BigPlusWord(BUF(a)[0], b);
return;
}
if (bSize == 1) {
BigPlusWord(BUF(b)[0], a);
return;
}
long new_size = MAX(aSize, bSize) + 1;
push_val(b);
push_val(a);
Value *res = start_bignat_alloc(new_size);
a = pop();
b = pop();
if (aSize < bSize) {
Value *tmp = a;
a = b;
b = tmp;
}
word_t *buf = BUF(res);
word_t c = nn_add_c(buf, BUF(a), a->n.size, BUF(b), b->n.size, 0);
buf[new_size - 1] = c;
push_val(end_bignat_alloc(res));
}
// arguments must both have already been evaluated and coerced into nats.
void Add() {
Value *a = pop_deref();
Value *b = pop_deref();
u64 aSmall = get_direct(a);
u64 bSmall = get_direct(b);
if (is_direct(a)) {
if (is_direct(b)) {
// no need to handle overflow, since u63 + u63 always fits in a u64.
push_word(aSmall + bSmall);
return;
}
BigPlusWord(aSmall, b);
return;
}
if (is_direct(b)) {
BigPlusWord(bSmall, a);
return;
}
BigPlusBig(a, b);
}
void BigMinusDirect(Value *big, u64 direct) {
u64 bigSz = big->n.size;
push_val(big); // save
Value *res = start_bignat_alloc(bigSz); // gc
big = pop(); // reload
word_t *buf = BUF(res);
word_t c = nn_sub1(buf, BUF(big), bigSz, direct);
// a positive borrow (nonzero `c`) should only be possible if we
// underflowed a single u64. our invariant is to convert to SMALL when we
// reach 1 u64, so we should never encounter this case.
ASSERT_ (c == 0);
push_val(end_bignat_alloc(res));
}
void Dec() {
#if ENABLE_GRAPHVIZ
write_dot_extra("<Dec>", "", NULL);
#endif
Value *v = pop_deref();
if (is_direct(v)) {
u64 n = get_direct(v);
push_val( (n == 0) ? DIRECT_ZERO : DIRECT(n - 1) );
// the result is always direct because (x/u63 - 1) is always a u63
// unless x==0.
goto end;
}
BigMinusDirect(v, 1);
end:
#if ENABLE_GRAPHVIZ
write_dot_extra("</Dec>", "", NULL);
#endif
}
void Sub() {
Value *a = pop();
Value *b = pop();
u64 aSmall = get_direct(a);
u64 bSmall = get_direct(b);
if (is_direct(a)) {
if (is_direct(b)) {
if (bSmall >= aSmall) {
push_val(DIRECT_ZERO);
return;
}
push_word(aSmall - bSmall);
return;
}
push_val(DIRECT_ZERO);
return;
}
if (is_direct(b)) {
BigMinusDirect(a, bSmall);
return;
}
u64 aSz = a->n.size;
u64 bSz = a->n.size;
if (aSz < bSz) {
push_val(DIRECT_ZERO);
return;
}
// Big - Big
push_val(b);
push_val(a);
Value *res = start_bignat_alloc(aSz); // gc
a = pop();
b = pop();
word_t *buf = BUF(res);
word_t borrow = nn_sub_c(buf, BUF(a), a->n.size, BUF(b), b->n.size, 0);
if (borrow) {
abort_bignat_alloc(res);
push_val(DIRECT_ZERO);
} else {