-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoptiscope.c
More file actions
5011 lines (4157 loc) · 161 KB
/
Copy pathoptiscope.c
File metadata and controls
5011 lines (4157 loc) · 161 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
/*
BSD 3-Clause License
Copyright (c) 2025, Louis F. Ashfield
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Header Inclusions
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
#include "optiscope.h"
#include <assert.h>
#include <errno.h>
#include <inttypes.h>
#include <limits.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Miscellaneouse Macros
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
#define ARRAY_LENGTH(array) (sizeof((array)) / sizeof((array)[0]))
#ifndef NDEBUG
#define CLEAR_MEMORY(object) memset((object), '\0', sizeof *(object))
#else
#define CLEAR_MEMORY(object) ((void)0)
#endif
#define ITERATE_ONCE(finish, before, after) \
for (bool finish = ((before), false); !finish; (after), finish = true)
#define CAT_PRIMITIVE(a, b) a##b
#define CAT(a, b) CAT_PRIMITIVE(a, b)
#define STRINGIFY_PRIMITIVE(...) #__VA_ARGS__
#define STRINGIFY(...) STRINGIFY_PRIMITIVE(__VA_ARGS__)
// Compiler Functionality Detection
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
#define STANDARD_C99_OR_HIGHER (__STDC_VERSION__ >= 199901L)
#define STANDARD_C11_OR_HIGHER (__STDC_VERSION__ >= 201112L)
#if !STANDARD_C99_OR_HIGHER
#error C99 or higher is required!
#endif
#if !defined(NDEBUG) && defined(__has_feature) // Clang
#if __has_feature(address_sanitizer)
#define COMPILER_ASAN_AVAILABLE
#endif
#elif !defined(NDEBUG) && defined(__SANITIZE_ADDRESS__) // GCC & MSVC
#define COMPILER_ASAN_AVAILABLE
#endif
#ifdef COMPILER_ASAN_AVAILABLE
#include <sanitizer/asan_interface.h>
#endif
#ifdef __GNUC__
#include <sys/mman.h>
#include <unistd.h>
#endif
// Compiler-Specific Builtins
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
#ifdef __GNUC__
// We generally trust the compiler whether or not to inline a function.
// However, we utilize a number of other attributes, to help both the human
// reader & the compiler.
// See <https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html> for
// the list of GNU C function attributes.
// Note: please, keep `.clang-format` up-to-date with the macros below.
#define COMPILER_UNUSED __attribute__((unused))
#define COMPILER_NORETURN __attribute__((noreturn))
#define COMPILER_COLD __attribute__((cold))
#define COMPILER_HOT __attribute__((hot))
#define COMPILER_FLATTEN __attribute__((flatten))
#define COMPILER_ALWAYS_INLINE __attribute__((always_inline))
#define COMPILER_RETURNS_NONNULL __attribute__((returns_nonnull))
#define COMPILER_WARN_UNUSED_RESULT __attribute__((warn_unused_result))
#ifndef __clang__
#define COMPILER_MALLOC(deallocator, ptr_index) \
__attribute__((malloc(deallocator, ptr_index)))
#endif // __clang__
#define COMPILER_FORMAT(archetype, string_index, first_to_check) \
__attribute__((format(archetype, string_index, first_to_check)))
#ifdef NDEBUG
#define COMPILER_UNREACHABLE() __builtin_unreachable()
#define COMPILER_NONNULL(...) __attribute__((nonnull(__VA_ARGS__)))
#define COMPILER_CONST __attribute__((const))
#define COMPILER_PURE __attribute__((pure))
#else
#define COMPILER_UNREACHABLE() assert(false)
#define COMPILER_NONNULL(...) /* checked by `assert` */
#define COMPILER_CONST /* may invoke side-effecting `assert` */
#define COMPILER_PURE /* may invoke side-effecting `assert` */
#endif // NDEBUG
#endif // __GNUC__
#ifdef COMPILER_ASAN_AVAILABLE
#define COMPILER_POISON_MEMORY ASAN_POISON_MEMORY_REGION
#define COMPILER_UNPOISON_MEMORY ASAN_UNPOISON_MEMORY_REGION
#define COMPILER_IS_POISONED_ADDRESS __asan_address_is_poisoned
#define COMPILER_IS_POISONED_MEMORY __asan_region_is_poisoned
#endif
#define COMPILER_IGNORE /* empty, object-like */
#define COMPILER_IGNORE_WITH_ARGS(...) /* empty, function-like */
#ifndef COMPILER_UNUSED
#define COMPILER_UNUSED COMPILER_IGNORE
#endif
#ifndef COMPILER_NORETURN
#if STANDARD_C11_OR_HIGHER
#define COMPILER_NORETURN _Noreturn
#else
#define COMPILER_NORETURN COMPILER_IGNORE
#endif
#endif
#ifndef COMPILER_COLD
#define COMPILER_COLD COMPILER_IGNORE
#endif
#ifndef COMPILER_HOT
#define COMPILER_HOT COMPILER_IGNORE
#endif
#ifndef COMPILER_FLATTEN
#define COMPILER_FLATTEN COMPILER_IGNORE
#endif
#ifndef COMPILER_ALWAYS_INLINE
#define COMPILER_ALWAYS_INLINE COMPILER_IGNORE
#endif
#ifndef COMPILER_RETURNS_NONNULL
#define COMPILER_RETURNS_NONNULL COMPILER_IGNORE
#endif
#ifndef COMPILER_WARN_UNUSED_RESULT
#define COMPILER_WARN_UNUSED_RESULT COMPILER_IGNORE
#endif
#ifndef COMPILER_MALLOC
#define COMPILER_MALLOC COMPILER_IGNORE_WITH_ARGS
#endif
#ifndef COMPILER_FORMAT
#define COMPILER_FORMAT COMPILER_IGNORE_WITH_ARGS
#endif
#ifndef COMPILER_UNREACHABLE
#define COMPILER_UNREACHABLE COMPILER_IGNORE_WITH_ARGS
#endif
#ifndef COMPILER_NONNULL
#define COMPILER_NONNULL COMPILER_IGNORE
#endif
#ifndef COMPILER_CONST
#define COMPILER_CONST COMPILER_IGNORE
#endif
#ifndef COMPILER_PURE
#define COMPILER_PURE COMPILER_IGNORE
#endif
#ifndef COMPILER_POISON_MEMORY
#define COMPILER_POISON_MEMORY COMPILER_IGNORE_WITH_ARGS
#endif
#ifndef COMPILER_UNPOISON_MEMORY
#define COMPILER_UNPOISON_MEMORY COMPILER_IGNORE_WITH_ARGS
#endif
#ifndef COMPILER_IS_POISONED_ADDRESS
#define COMPILER_IS_POISONED_ADDRESS COMPILER_IGNORE_WITH_ARGS
#endif
#ifndef COMPILER_IS_POISONED_MEMORY
#define COMPILER_IS_POISONED_MEMORY COMPILER_IGNORE_WITH_ARGS
#endif
// Debugging Assertions
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// Used for communicating logic invariants to the compiler.
#if defined(__GNUC__) && defined(NDEBUG)
#define XASSERT(condition) (!(condition) ? __builtin_unreachable() : (void)0)
#else
#define XASSERT assert
#endif
// Assertions that are checked at compile-time.
#if defined(__GNUC__) || STANDARD_C11_OR_HIGHER
#define STATIC_ASSERT(constant_expression) \
_Static_assert((constant_expression), #constant_expression)
#else
// clang-format off
#define STATIC_ASSERT(constant_expression) \
COMPILER_UNUSED /* */ \
static const char CAT(c99_static_assert_, __LINE__) \
[(constant_expression) ? 1 : -1] = {0}
// clang-format on
#endif
// File-Related I/O
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
#define IO_CALL(f, ...) (f(__VA_ARGS__) < 0 ? (perror(#f), abort()) : (void)0)
#define IO_CALL_ASSIGN(x, f, ...) \
((x = f(__VA_ARGS__)) < 0 ? (perror(#f), abort()) : (void)0)
// Logging & Panicking
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
#define PRINTER(name, stream, culmination) \
COMPILER_NONNULL(1) COMPILER_FORMAT(printf, 1, 2) /* */ \
static void \
name(const char *const restrict format, ...) { \
assert(format); \
\
va_list args; \
va_start(args, format); \
vfprintf(stream, format, args); \
fputs("\n", stream); \
va_end(args); \
\
culmination; \
}
#ifdef OPTISCOPE_ENABLE_TRACING
PRINTER(debug, stdout, /* empty */)
#else
#define debug(...) ((void)0)
#endif
COMPILER_COLD COMPILER_NORETURN //
PRINTER(panic, stderr, abort())
#undef PRINTER
// Checked Memory Allocation
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
COMPILER_MALLOC(free, 1) COMPILER_RETURNS_NONNULL COMPILER_WARN_UNUSED_RESULT //
static void *
xmalloc(const size_t size) {
XASSERT(size > 0);
void *const object = malloc(size);
if (NULL == object) { panic("Failed `xmalloc`!"); }
return object;
}
COMPILER_MALLOC(free, 1) COMPILER_RETURNS_NONNULL COMPILER_WARN_UNUSED_RESULT //
static void *
xcalloc(const size_t n, const size_t size) {
XASSERT(size > 0);
void *const object = calloc(n, size);
if (NULL == object) { panic("Failed `xcalloc`!"); }
return object;
}
COMPILER_MALLOC(free, 1) COMPILER_RETURNS_NONNULL COMPILER_WARN_UNUSED_RESULT //
static void *
xrealloc(void *restrict object, const size_t size) {
XASSERT(size > 0);
object = realloc(object, size);
if (NULL == object) { panic("Failed `xrealloc`!"); }
return object;
}
COMPILER_MALLOC(free, 1) COMPILER_RETURNS_NONNULL COMPILER_WARN_UNUSED_RESULT
COMPILER_NONNULL(1) //
static char *
xstrdup(const char *const s) {
assert(s);
char *const result = strdup(s);
if (NULL == result) { panic("Failed `xstrdup`!"); }
return result;
}
COMPILER_WARN_UNUSED_RESULT COMPILER_RETURNS_NONNULL COMPILER_NONNULL(1)
COMPILER_FORMAT(printf, 1, 2) //
static char *
format_string(const char *const format, ...) {
assert(format);
va_list args, args_copy;
va_start(args, format);
va_copy(args_copy, args);
const int length = vsnprintf(NULL, 0, format, args);
va_end(args);
char *const result = xmalloc(length + 1);
vsprintf(result, format, args_copy);
va_end(args_copy);
return result;
}
// Lambda Term Interface
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
enum lambda_term_type {
LAMBDA_TERM_APPLY,
LAMBDA_TERM_LAMBDA,
LAMBDA_TERM_VAR,
LAMBDA_TERM_CELL,
LAMBDA_TERM_UNARY_CALL,
LAMBDA_TERM_BINARY_CALL,
LAMBDA_TERM_IF_THEN_ELSE,
LAMBDA_TERM_REFERENCE,
LAMBDA_TERM_READBACK,
};
struct apply_data {
struct lambda_term *rator, *rand;
};
struct lambda_data {
struct lambda_term *body;
uint64_t nusages; // the number of times the lambda body refers to
// its binder
uint64_t **binder_ports; // the pointer to the next binder port; dynamically
// mutated
uint64_t lvl; // the de Bruijn level; dynamically mutated
};
struct unary_call_data {
uint64_t (*function)(uint64_t);
struct lambda_term *rand;
};
struct binary_call_data {
uint64_t (*function)(uint64_t, uint64_t);
struct lambda_term *lhs, *rhs;
};
struct if_then_else_data {
struct lambda_term *condition;
struct lambda_term *if_then, *if_else;
};
struct reference_data {
struct lambda_term *(*function)(void);
};
struct readback_data {
struct lambda_term *input;
};
union lambda_term_data {
struct apply_data app;
struct lambda_data *lam;
struct lambda_data **var;
uint64_t cell;
struct unary_call_data ucall;
struct binary_call_data bcall;
struct if_then_else_data ite;
struct reference_data ref;
struct readback_data rb;
};
struct lambda_term {
enum lambda_term_type ty;
union lambda_term_data data;
uint64_t fv_count; // the number of free variables in the term; assigned
// during construction
uint64_t *connect_to; // the port addresse to be connected with the
// interface; dynamically mutated
};
COMPILER_CONST COMPILER_WARN_UNUSED_RESULT //
inline static bool
is_quotable_term(const enum lambda_term_type ty) {
switch (ty) {
case LAMBDA_TERM_APPLY:
case LAMBDA_TERM_LAMBDA:
case LAMBDA_TERM_VAR: return true;
default: return false;
}
}
COMPILER_CONST COMPILER_WARN_UNUSED_RESULT //
inline static uint64_t
de_bruijn_level_to_index(const uint64_t lvl, const uint64_t var) {
return lvl - var - 1;
}
extern LambdaTerm
apply(const restrict LambdaTerm rator, const restrict LambdaTerm rand) {
assert(rator);
assert(rand);
struct lambda_term *const term = xmalloc(sizeof *term);
term->ty = LAMBDA_TERM_APPLY;
term->data.app.rator = rator;
term->data.app.rand = rand;
term->fv_count = rator->fv_count + rand->fv_count;
return term;
}
extern LambdaTerm
prelambda(void) {
struct lambda_term *const term = xmalloc(sizeof *term);
term->ty = LAMBDA_TERM_LAMBDA;
term->data.lam = xcalloc(1, sizeof *term->data.lam);
// All the data fields are zeroed out.
return term;
}
extern LambdaTerm
link_lambda_body(
const restrict LambdaTerm binder, const restrict LambdaTerm body) {
assert(binder);
assert(body);
assert(LAMBDA_TERM_LAMBDA == binder->ty);
binder->data.lam->body = body;
binder->fv_count = body->fv_count - binder->data.lam->nusages;
return binder;
}
extern LambdaTerm
var(const restrict LambdaTerm binder) {
assert(binder);
assert(LAMBDA_TERM_LAMBDA == binder->ty);
struct lambda_term *const term = xmalloc(sizeof *term);
term->ty = LAMBDA_TERM_VAR;
term->data.var = &binder->data.lam;
term->fv_count = 1;
binder->data.lam->nusages++;
return term;
}
extern LambdaTerm
cell(const uint64_t value) {
struct lambda_term *const term = xmalloc(sizeof *term);
term->ty = LAMBDA_TERM_CELL;
term->data.cell = value;
term->fv_count = 0;
return term;
}
extern LambdaTerm
unary_call(
uint64_t (*const function)(uint64_t), const restrict LambdaTerm rand) {
assert(function);
assert(rand);
struct lambda_term *const term = xmalloc(sizeof *term);
term->ty = LAMBDA_TERM_UNARY_CALL;
term->data.ucall.function = function;
term->data.ucall.rand = rand;
term->fv_count = rand->fv_count;
return term;
}
extern LambdaTerm
binary_call(
uint64_t (*const function)(uint64_t, uint64_t),
const restrict LambdaTerm lhs,
const restrict LambdaTerm rhs) {
assert(function);
assert(lhs);
assert(rhs);
struct lambda_term *const term = xmalloc(sizeof *term);
term->ty = LAMBDA_TERM_BINARY_CALL;
term->data.bcall.function = function;
term->data.bcall.lhs = lhs;
term->data.bcall.rhs = rhs;
term->fv_count = lhs->fv_count + rhs->fv_count;
return term;
}
extern LambdaTerm
if_then_else(
const restrict LambdaTerm condition,
const restrict LambdaTerm if_then,
const restrict LambdaTerm if_else) {
assert(condition);
assert(if_then);
assert(if_else);
struct lambda_term *const term = xmalloc(sizeof *term);
term->ty = LAMBDA_TERM_IF_THEN_ELSE;
term->data.ite.condition = condition;
term->data.ite.if_then = if_then;
term->data.ite.if_else = if_else;
term->fv_count =
condition->fv_count + if_then->fv_count + if_else->fv_count;
return term;
}
extern LambdaTerm
expand(struct lambda_term *(*const function)(void)) {
assert(function);
struct lambda_term *const term = xmalloc(sizeof *term);
term->ty = LAMBDA_TERM_REFERENCE;
term->data.ref.function = function;
term->fv_count = 0;
return term;
}
COMPILER_RETURNS_NONNULL COMPILER_NONNULL(1) //
static struct lambda_term *
readback(const restrict LambdaTerm input) {
assert(input);
struct lambda_term *const term = xmalloc(sizeof *term);
term->ty = LAMBDA_TERM_READBACK;
term->data.rb.input = input;
term->fv_count = input->fv_count;
return term;
}
COMPILER_NONNULL(1) COMPILER_COLD //
static void
free_lambda_term(struct lambda_term *const restrict term) {
assert(term);
switch (term->ty) {
case LAMBDA_TERM_APPLY:
free_lambda_term(term->data.app.rator);
free_lambda_term(term->data.app.rand);
break;
case LAMBDA_TERM_LAMBDA:
free_lambda_term(term->data.lam->body);
free(term->data.lam->binder_ports);
free(term->data.lam);
break;
case LAMBDA_TERM_UNARY_CALL: free_lambda_term(term->data.ucall.rand); break;
case LAMBDA_TERM_BINARY_CALL:
free_lambda_term(term->data.bcall.lhs);
free_lambda_term(term->data.bcall.rhs);
break;
case LAMBDA_TERM_IF_THEN_ELSE:
free_lambda_term(term->data.ite.condition);
free_lambda_term(term->data.ite.if_then);
free_lambda_term(term->data.ite.if_else);
break;
case LAMBDA_TERM_VAR:
case LAMBDA_TERM_CELL:
case LAMBDA_TERM_REFERENCE: break;
case LAMBDA_TERM_READBACK: free_lambda_term(term->data.rb.input); break;
default: COMPILER_UNREACHABLE();
}
free(term);
}
// Ports & Symbols Functionality
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
#define MACHINE_WORD_BITS UINT64_C(64)
#define OFFSET_METADATA_BITS UINT64_C(2)
#define PHASE_METADATA_BITS UINT64_C(2)
#define EFFECTIVE_ADDRESS_BITS \
(MACHINE_WORD_BITS - OFFSET_METADATA_BITS - PHASE_METADATA_BITS)
#define UNUSED_ADDRESS_BITS (MACHINE_WORD_BITS - EFFECTIVE_ADDRESS_BITS)
#define ADDRESS_MASK (~UINT64_C(0) >> UNUSED_ADDRESS_BITS)
#define SIGN_EXTEND(n) \
((uint64_t)((int64_t)((n) << UNUSED_ADDRESS_BITS) >> UNUSED_ADDRESS_BITS))
#define ENCODE_METADATA(offset, phase) \
((((offset) << PHASE_METADATA_BITS) | (phase)) << EFFECTIVE_ADDRESS_BITS)
#define DECODE_OFFSET_METADATA(address) \
((address) >> (EFFECTIVE_ADDRESS_BITS + PHASE_METADATA_BITS))
#define DECODE_PHASE_METADATA(address) \
(((address) << OFFSET_METADATA_BITS) >> \
(EFFECTIVE_ADDRESS_BITS + OFFSET_METADATA_BITS))
#ifdef __linux__
// The kernel returnes userspace addresses with sign-extended bits always set to
// zeroes, so they will not corrupt our metadata.
// Source:
// <https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/Documentation/arch/x86/x86_64/mm.rst>.
// Workes with both 4- & 5-level page tables.
#define ENCODE_ADDRESS(metadata, address) ((address) | (metadata))
#define DECODE_ADDRESS(address) ((uint64_t *)((address) & ADDRESS_MASK))
#else
// In the fallback case, we need to properly maske the highermost addresse bits
// to avoid metadata corruption.
#define ENCODE_ADDRESS(metadata, address) \
(((address) & ADDRESS_MASK) | (metadata))
#define DECODE_ADDRESS(address) \
((uint64_t *)(SIGN_EXTEND((address) & ADDRESS_MASK)))
#endif // __linux__
#define DECODE_ADDRESS_METADATA(address) (((address) & ~ADDRESS_MASK))
#define PORT_VALUE(offset, phase, address) \
ENCODE_ADDRESS(ENCODE_METADATA((offset), (phase)), (address))
#define SET_TARGET(address, target) \
ENCODE_ADDRESS(DECODE_ADDRESS_METADATA((address)), (target))
#define IS_PRINCIPAL_PORT(port) (0 == DECODE_OFFSET_METADATA((port)))
#define MAX_REGULAR_SYMBOL UINT64_C(63)
#define INDEX_RANGE UINT64_C(9223372036854775776)
#define MAX_DUPLICATOR_INDEX (MAX_REGULAR_SYMBOL + INDEX_RANGE)
#define MAX_DELIMITER_INDEX (MAX_DUPLICATOR_INDEX + INDEX_RANGE)
#define MAX_PORTS UINT64_C(4)
#define MAX_AUXILIARY_PORTS (MAX_PORTS - 1)
STATIC_ASSERT(CHAR_BIT == 8);
STATIC_ASSERT(sizeof(uint64_t *) == sizeof(uint64_t));
STATIC_ASSERT(sizeof(uint64_t (*)(uint64_t)) <= sizeof(uint64_t));
STATIC_ASSERT(sizeof(uint64_t (*)(uint64_t, uint64_t)) <= sizeof(uint64_t));
STATIC_ASSERT(sizeof(struct lambda_term *(*)(void)) <= sizeof(uint64_t));
STATIC_ASSERT(UINT64_MAX == UINT64_C(18446744073709551615));
STATIC_ASSERT(UINT64_MAX == MAX_DELIMITER_INDEX);
#define SYMBOL_ROOT UINT64_C(0)
#define SYMBOL_APPLICATOR UINT64_C(1)
#define SYMBOL_LAMBDA UINT64_C(2)
#define SYMBOL_ERASER UINT64_C(3) // active GC nodes that erase their targets
#define SYMBOL_ERASER_AUX UINT64_C(4) // GC nodes scheduled for deletion
#define SYMBOL_CELL UINT64_C(5)
#define SYMBOL_UNARY_CALL UINT64_C(6)
#define SYMBOL_BINARY_CALL UINT64_C(7)
#define SYMBOL_BINARY_CALL_AUX UINT64_C(8)
#define SYMBOL_IF_THEN_ELSE UINT64_C(9)
#define SYMBOL_IDENTITY_LAMBDA UINT64_C(10)
#define SYMBOL_GC_LAMBDA UINT64_C(11)
#define SYMBOL_REFERENCE UINT64_C(12)
#define SYMBOL_BARRIER UINT64_C(13)
#define SYMBOL_GC_DUPLICATOR_LEFT UINT64_C(14)
#define SYMBOL_GC_DUPLICATOR_RIGHT UINT64_C(15)
#define SYMBOL_QLAMBDA UINT64_C(16)
#define SYMBOL_QAPPLICATOR UINT64_C(17)
#define SYMBOL_QVARIABLE UINT64_C(18)
#define SYMBOL_MAPPLICATOR UINT64_C(19)
#define SYMBOL_READBACK UINT64_C(20)
#define SYMBOL_PRINTOUT UINT64_C(21)
#define SYMBOL_QLAMBDA_PRINTER UINT64_C(22)
#define SYMBOL_QAPPLICATOR_PRINTER UINT64_C(23)
#define SYMBOL_QAPPLICATOR_PRINTER_AUX UINT64_C(24)
#define SYMBOL_SEGMENT UINT64_C(25)
#define SYMBOL_DUPLICATOR(i) (MAX_REGULAR_SYMBOL + 1 + (i))
#define SYMBOL_DELIMITER(i) (MAX_DUPLICATOR_INDEX + 1 + (i))
#define IS_ANY_LAMBDA(symbol) \
(SYMBOL_LAMBDA == (symbol) || SYMBOL_IDENTITY_LAMBDA == (symbol) || \
SYMBOL_GC_LAMBDA == (symbol))
// clang-format off
#define IS_DUPLICATOR(symbol) \
((symbol) >= SYMBOL_DUPLICATOR(UINT64_C(0)) && \
(symbol) <= MAX_DUPLICATOR_INDEX)
#define IS_DELIMITER(symbol) \
((symbol) >= SYMBOL_DELIMITER(UINT64_C(0)))
// clang-format on
#define IS_GC_DUPLICATOR(symbol) \
(SYMBOL_GC_DUPLICATOR_LEFT == (symbol) || \
SYMBOL_GC_DUPLICATOR_RIGHT == (symbol))
#define IS_ANY_DUPLICATOR(symbol) \
(IS_DUPLICATOR((symbol)) || IS_GC_DUPLICATOR((symbol)))
#define IS_INTERFACE_SYMBOL(symbol) \
(IS_ANY_LAMBDA((symbol)) || SYMBOL_CELL == (symbol) || \
SYMBOL_PRINTOUT == (symbol))
COMPILER_CONST COMPILER_WARN_UNUSED_RESULT COMPILER_HOT //
inline static bool
is_atomic_symbol(const uint64_t symbol) {
switch (symbol) {
case SYMBOL_ERASER:
case SYMBOL_ERASER_AUX:
case SYMBOL_CELL:
case SYMBOL_IDENTITY_LAMBDA:
case SYMBOL_REFERENCE:
case SYMBOL_QVARIABLE:
case SYMBOL_PRINTOUT: return true;
default: return false;
}
}
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-function" // may be unused
COMPILER_CONST COMPILER_WARN_UNUSED_RESULT COMPILER_HOT //
inline static bool
is_operator_symbol(const uint64_t symbol) {
switch (symbol) {
case SYMBOL_APPLICATOR:
case SYMBOL_UNARY_CALL:
case SYMBOL_BINARY_CALL:
case SYMBOL_BINARY_CALL_AUX:
case SYMBOL_IF_THEN_ELSE:
case SYMBOL_MAPPLICATOR:
case SYMBOL_READBACK:
case SYMBOL_QLAMBDA_PRINTER:
case SYMBOL_QAPPLICATOR_PRINTER:
case SYMBOL_QAPPLICATOR_PRINTER_AUX:
case SYMBOL_SEGMENT: return true;
default: return false;
}
}
#pragma GCC diagnostic pop // "-Wunused-function"
#define SYMBOL_INDEX(symbol) \
/* Extract the symbol without branching, considering that duplicators & \
* delimiters share the same symbol range. */ \
(((symbol) - MAX_REGULAR_SYMBOL - 1) % INDEX_RANGE)
#define GOTO_INDEXED_SYMBOL(symbol, duplicator, delimiter) \
do { \
if (IS_DUPLICATOR((symbol))) goto duplicator; \
else if (IS_DELIMITER((symbol))) goto delimiter; \
else COMPILER_UNREACHABLE(); \
} while (false)
#if defined(OPTISCOPE_ENABLE_TRACING) || defined(OPTISCOPE_ENABLE_GRAPHVIZ)
COMPILER_MALLOC(free, 1) COMPILER_RETURNS_NONNULL COMPILER_WARN_UNUSED_RESULT //
static char *
print_symbol(const uint64_t symbol) {
switch (symbol) {
case SYMBOL_ROOT: return format_string("root");
case SYMBOL_APPLICATOR: return format_string("@");
case SYMBOL_LAMBDA: return format_string("λ");
case SYMBOL_ERASER: return format_string("◉");
case SYMBOL_ERASER_AUX: return format_string("◉'");
case SYMBOL_CELL: return format_string("cell");
case SYMBOL_UNARY_CALL: return format_string("unary-call");
case SYMBOL_BINARY_CALL: return format_string("binary-call");
case SYMBOL_BINARY_CALL_AUX: return format_string("binary-call-aux");
case SYMBOL_IF_THEN_ELSE: return format_string("if-then-else");
case SYMBOL_IDENTITY_LAMBDA: return format_string("identity");
case SYMBOL_GC_LAMBDA: return format_string("λ◉");
case SYMBOL_REFERENCE: return format_string("&");
case SYMBOL_BARRIER: return format_string("🚧");
case SYMBOL_GC_DUPLICATOR_LEFT: return format_string("◉δx");
case SYMBOL_GC_DUPLICATOR_RIGHT: return format_string("xδ◉");
case SYMBOL_QLAMBDA: return format_string("⌜λ⌝");
case SYMBOL_QAPPLICATOR: return format_string("⌜@⌝");
case SYMBOL_QVARIABLE: return format_string("⌜var⌝");
case SYMBOL_MAPPLICATOR: return format_string("↑@");
case SYMBOL_READBACK: return format_string("readback");
case SYMBOL_PRINTOUT: return format_string("printout");
case SYMBOL_QLAMBDA_PRINTER: return format_string("P-λ");
case SYMBOL_QAPPLICATOR_PRINTER: return format_string("P-@");
case SYMBOL_QAPPLICATOR_PRINTER_AUX: return format_string("P-@'");
case SYMBOL_SEGMENT: return format_string("segment");
default:
GOTO_INDEXED_SYMBOL(symbol, duplicator, delimiter);
duplicator:
return format_string("δ/%" PRIi64, SYMBOL_INDEX(symbol));
delimiter:
return format_string("⊔/%" PRIi64, SYMBOL_INDEX(symbol));
}
}
#endif
#define INDEX_OVERFLOW() \
panic("Maximum index of %" PRIu64 " is reached!", INDEX_RANGE - 1)
COMPILER_HOT COMPILER_ALWAYS_INLINE //
inline static uint64_t
bump_index(const uint64_t symbol, const uint64_t offset) {
XASSERT(symbol > MAX_REGULAR_SYMBOL);
if ((IS_DUPLICATOR(symbol) && offset > MAX_DUPLICATOR_INDEX - symbol) ||
(IS_DELIMITER(symbol) && offset > MAX_DELIMITER_INDEX - symbol)) {
INDEX_OVERFLOW();
}
return symbol + offset;
}
COMPILER_HOT COMPILER_ALWAYS_INLINE //
inline static uint64_t
bump_raw_index(const uint64_t index, const uint64_t offset) {
XASSERT(index < INDEX_RANGE);
if (offset > INDEX_RANGE - 1 - index) { INDEX_OVERFLOW(); }
return index + offset;
}
#undef INDEX_OVERFLOW
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-function" // may be unused
COMPILER_HOT COMPILER_ALWAYS_INLINE //
inline static uint64_t
bump_multiplicity(const uint64_t value, const uint64_t offset) {
if (value > UINT64_MAX - offset) {
panic("Maximum multiplicity of %" PRIu64 " is reached!", UINT64_MAX);
}
return value + offset;
}
#pragma GCC diagnostic pop // "-Wunused-function"
#define FOR_ALL_PORTS(node, i, seed) \
for (uint8_t i = seed; i < ports_count((node).ports[-1]); i++)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-function" // may be unused
COMPILER_CONST COMPILER_WARN_UNUSED_RESULT //
static uint8_t
ports_count(const uint64_t symbol) {
switch (symbol) {
case SYMBOL_ROOT:
case SYMBOL_ERASER:
case SYMBOL_ERASER_AUX:
case SYMBOL_CELL:
case SYMBOL_IDENTITY_LAMBDA:
case SYMBOL_REFERENCE:
case SYMBOL_QVARIABLE:
case SYMBOL_PRINTOUT: //
return 1;
case SYMBOL_UNARY_CALL:
case SYMBOL_BINARY_CALL_AUX:
case SYMBOL_GC_LAMBDA:
case SYMBOL_BARRIER:
case SYMBOL_GC_DUPLICATOR_LEFT:
case SYMBOL_GC_DUPLICATOR_RIGHT:
case SYMBOL_QLAMBDA:
case SYMBOL_READBACK:
case SYMBOL_QLAMBDA_PRINTER:
case SYMBOL_QAPPLICATOR_PRINTER_AUX:
case SYMBOL_SEGMENT:
delimiter:
return 2;
case SYMBOL_APPLICATOR:
case SYMBOL_LAMBDA:
case SYMBOL_BINARY_CALL:
case SYMBOL_QAPPLICATOR:
case SYMBOL_MAPPLICATOR:
case SYMBOL_QAPPLICATOR_PRINTER:
duplicator:
return 3;
case SYMBOL_IF_THEN_ELSE: //
return 4;
default: GOTO_INDEXED_SYMBOL(symbol, duplicator, delimiter);
}
}
#pragma GCC diagnostic pop // "-Wunused-function"
COMPILER_NONNULL(1, 2) COMPILER_HOT COMPILER_ALWAYS_INLINE //
inline static void
connect_ports(uint64_t *const restrict lhs, uint64_t *const restrict rhs) {
debug("%p 🔗 %p", (void *)lhs, (void *)rhs);
assert(lhs);
assert(rhs);
XASSERT(lhs != rhs);
*lhs = SET_TARGET(*lhs, (uint64_t)rhs);
*rhs = SET_TARGET(*rhs, (uint64_t)lhs);
}
COMPILER_PURE COMPILER_WARN_UNUSED_RESULT COMPILER_RETURNS_NONNULL
COMPILER_NONNULL(1) COMPILER_HOT COMPILER_ALWAYS_INLINE //
inline static uint64_t *
get_principal_port(uint64_t *const restrict port) {
assert(port);
return (port - DECODE_OFFSET_METADATA(port[0]));
}
#define ENCODE_PHASE(pending, closedness) ((pending) | ((closedness) << 1))
#define REVEAL_PENDING_BIT (UINT64_C(1) << EFFECTIVE_ADDRESS_BITS)
#define REVEAL_CLOSEDNESS_BIT (UINT64_C(1) << (EFFECTIVE_ADDRESS_BITS + 1))
#define DECODE_PENDING_BIT(address) \
(((address) & REVEAL_PENDING_BIT) >> EFFECTIVE_ADDRESS_BITS)
#ifdef OPTISCOPE_DISABLE_CLOSEDNESS_ANNOTATIONS
// If closednesse annotations are disabled, the closednesse bit will be intact,
// but will always be read as 0.
#define DECODE_CLOSEDNESS_BIT(address) UINT64_C(0)
#else
#define DECODE_CLOSEDNESS_BIT(address) \
(((address) & REVEAL_CLOSEDNESS_BIT) >> (EFFECTIVE_ADDRESS_BITS + 1))
#endif
// Native Function Pointers
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// Casting a function pointer to `void *` is not safe by the standard, but many
// implementations permit it because of dynamic loading (e.g., `dlopen`).
// Here, we performe a two-step conversion: we first cast the user-provided
// pointer to `void *` & then to `uint64_t`.