-
-
Notifications
You must be signed in to change notification settings - Fork 46
/
runtime.c
8892 lines (8220 loc) · 266 KB
/
runtime.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
/**
* Cyclone Scheme
* https://github.com/justinethier/cyclone
*
* Copyright (c) 2014-2016, Justin Ethier
* All rights reserved.
*
* This file contains the C runtime used by compiled programs.
*/
#include <ck_hs.h>
#include <ck_ht.h>
#include <ck_pr.h>
#include "cyclone/types.h"
#include "cyclone/runtime.h"
#include "cyclone/ck_ht_hash.h"
#include <errno.h>
#include <limits.h>
#include <ctype.h>
//#include <signal.h> // only used for debugging!
#include <sys/select.h>
#include <sys/stat.h>
#include <float.h>
static const int MAX_DEPTH = 512;
static uint32_t Cyc_utf8_decode(uint32_t * state, uint32_t * codep,
uint32_t byte);
static int Cyc_utf8_count_code_points_and_bytes(uint8_t * s,
char_type * codepoint,
int *cpts, int *bytes);
/* Error checking section - type mismatch, num args, etc */
/* Type names to use for error messages */
const char *tag_names[] = {
/*closure0_tag */ "procedure"
/*closure1_tag */ , "procedure"
/*closureN_tag */ , "procedure"
/*macro_tag */ , "macro"
/*boolean_tag */ , "boolean"
/*bytevector_tag */ , "bytevector"
/*c_opaque_tag */ , "opaque"
/*cond_var_tag */ , "condition variable"
/*cvar_tag */ , "C primitive"
/*double_tag */ , "double"
/*eof_tag */ , "eof"
/*forward_tag */ , ""
/*integer_tag */ , "number"
/*bignum_tag */ , "bignum"
/*mutex_tag */ , "mutex"
/*pair_tag */ , "pair"
/*port_tag */ , "port"
/*primitive_tag */ , "primitive"
/*string_tag */ , "string"
/*symbol_tag */ , "symbol"
/*vector_tag */ , "vector"
/*complex_num_tag */ , "complex number"
/*atomic_tag */ , "atomic"
/*void_tag */ , "void"
/*record_tag */ , "record"
, "Reserved for future use"
};
void Cyc_invalid_type_error(void *data, int tag, object found)
{
char buf[256];
#if GC_DEBUG_TRACE
// Object address can be very useful for GC debugging
snprintf(buf, 255, "Invalid type: expected %s, found (%p) ", tag_names[tag],
found);
#else
snprintf(buf, 255, "Invalid type: expected %s, found ", tag_names[tag]);
#endif
Cyc_rt_raise2(data, buf, found);
}
void Cyc_immutable_obj_error(void *data, object obj)
{
Cyc_rt_raise2(data, "Unable to modify immutable object ", obj);
}
void Cyc_mutable_obj_error(void *data, object obj)
{
Cyc_rt_raise2(data, "Expected immutable object ", obj);
}
void Cyc_check_obj(void *data, int tag, object obj)
{
if (!is_object_type(obj)) {
Cyc_invalid_type_error(data, tag, obj);
}
}
void Cyc_check_bounds(void *data, const char *label, int len, int index)
{
if (index < 0 || index >= len) {
char buf[128];
snprintf(buf, 127, "%s - invalid index %d", label, index);
Cyc_rt_raise_msg(data, buf);
}
}
/* END error checking */
#ifdef CYC_HIGH_RES_TIMERS
/* High resolution timers */
#include <time.h>
long long hrt_get_current()
{
struct timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
long long jiffy = (now.tv_sec) * 1000000LL + now.tv_nsec / 1000; // nano->microseconds
return jiffy;
}
long long hrt_cmp_current(long long tstamp)
{
long long now = hrt_get_current();
return (now - tstamp);
}
void hrt_log_delta(const char *label, long long tstamp)
{
static long long initial = 1;
static long long initial_tstamp;
if (initial == 1) {
initial = 0;
initial_tstamp = hrt_get_current();
}
long long total = hrt_cmp_current(initial_tstamp);
long long delta = hrt_cmp_current(tstamp);
fprintf(stderr, "%s, %llu, %llu\n", label, total, delta);
}
/* END High resolution timers */
#endif
/* These macros are hardcoded here to support functions in this module. */
#define closcall1(td, clo, buf) \
if (obj_is_not_closure(clo)) { \
Cyc_apply(td, clo, 1, buf ); \
} else { \
((clo)->fn)(td, clo, 1, buf); \
;\
}
#define return_closcall1(td, clo,a1) { \
char top; \
object buf[1]; buf[0] = a1;\
if (stack_overflow(&top, (((gc_thread_data *)data)->stack_limit))) { \
GC(td, clo, buf, 1); \
return; \
} else {\
closcall1(td, (closure) (clo), buf); \
return;\
} \
}
#define _return_closcall1(td, clo,a1) { \
char top; \
object buf[1]; buf[0] = a1;\
if (stack_overflow(&top, (((gc_thread_data *)data)->stack_limit))) { \
GC(td, clo, buf, 1); \
return NULL; \
} else {\
closcall1(td, (closure) (clo), buf); \
return NULL;\
} \
}
#define closcall2(td, clo, buf) \
if (obj_is_not_closure(clo)) { \
Cyc_apply(td, clo, 2, buf ); \
} else { \
((clo)->fn)(td, clo, 2, buf); \
;\
}
#define return_closcall2(td, clo,a1,a2) { \
char top; \
object buf[2]; buf[0] = a1;buf[1] = a2;\
if (stack_overflow(&top, (((gc_thread_data *)data)->stack_limit))) { \
GC(td, clo, buf, 2); \
return; \
} else {\
closcall2(td, (closure) (clo), buf); \
return;\
} \
}
#define _return_closcall2(td, clo,a1,a2) { \
char top; \
object buf[2]; buf[0] = a1;buf[1] = a2;\
if (stack_overflow(&top, (((gc_thread_data *)data)->stack_limit))) { \
GC(td, clo, buf, 2); \
return NULL; \
} else {\
closcall2(td, (closure) (clo), buf); \
return NULL;\
} \
}
/*END closcall section */
/* Global variables. */
object Cyc_global_variables = NULL;
int _cyc_argc = 0;
char **_cyc_argv = NULL;
static symbol_type __EOF = { {0}, eof_tag, "" }; // symbol_type in lieu of custom type
static symbol_type __VOID = { {0}, void_tag, "" }; // symbol_type in lieu of custom type
static symbol_type __RECORD = { {0}, record_tag, "" }; // symbol_type in lieu of custom type
const object Cyc_EOF = &__EOF;
const object Cyc_VOID = &__VOID;
const object Cyc_RECORD_MARKER = &__RECORD;
static ck_hs_t lib_table;
static ck_hs_t symbol_table;
static int symbol_table_initial_size = 4096;
static pthread_mutex_t symbol_table_lock;
char **env_variables = NULL;
char **get_env_variables()
{
return env_variables;
}
void pack_env_variables(void *data, object k)
{
char **env = env_variables;
object tail;
object head = NULL;
tail = head;
for (; *env != NULL; env++) {
char *e = *env, *eqpos = strchr(e, '=');
pair_type *p = alloca(sizeof(pair_type));
pair_type *tmp = alloca(sizeof(pair_type));
string_type *sval = alloca(sizeof(string_type));
string_type *svar = alloca(sizeof(string_type));
svar->hdr.mark = gc_color_red;
svar->hdr.grayed = 0;
svar->hdr.immutable = 0;
svar->tag = string_tag;
svar->len = eqpos - e;
svar->str = alloca(sizeof(char) * (svar->len));
strncpy(svar->str, e, svar->len);
(svar->str)[svar->len] = '\0';
svar->num_cp = Cyc_utf8_count_code_points((uint8_t *) svar->str);
if (eqpos) {
eqpos++;
}
sval->hdr.mark = gc_color_red;
sval->hdr.grayed = 0;
sval->hdr.immutable = 0;
sval->tag = string_tag;
sval->len = strlen(eqpos);
svar->num_cp = Cyc_utf8_count_code_points((uint8_t *) eqpos);
sval->str = eqpos;
set_pair(tmp, svar, sval);
set_pair(p, tmp, NULL);
if (head == NULL) {
tail = head = p;
} else {
cdr(tail) = p;
tail = p;
}
}
return_closcall1(data, k, head);
}
void set_env_variables(char **vars)
{
env_variables = vars;
}
// Functions to support concurrency kit hashset
// These are specifically for a table of symbols
static void *hs_malloc(size_t r)
{
return malloc(r);
}
static void hs_free(void *p, size_t b, bool r)
{
free(p);
}
static struct ck_malloc my_allocator = {
.malloc = hs_malloc,
.free = hs_free
};
static unsigned long hs_hash(const void *object, unsigned long seed)
{
const symbol_type *c = object;
unsigned long h;
h = (unsigned long)MurmurHash64A(c->desc, strlen(c->desc), seed);
return h;
}
static bool hs_compare(const void *previous, const void *compare)
{
return strcmp(symbol_desc(previous), symbol_desc(compare)) == 0;
}
static void *set_get(ck_hs_t * hs, const void *value)
{
unsigned long h;
void *v;
h = CK_HS_HASH(hs, hs_hash, value);
v = ck_hs_get(hs, h, value);
return v;
}
static bool set_insert(ck_hs_t * hs, const void *value)
{
unsigned long h;
h = CK_HS_HASH(hs, hs_hash, value);
return ck_hs_put(hs, h, value);
}
// End hashset supporting functions
/**
* @brief Perform one-time heap initializations for the program
* @param heap_size Unused
*/
void gc_init_heap(long heap_size)
{
if (!ck_hs_init(&lib_table,
CK_HS_MODE_OBJECT | CK_HS_MODE_SPMC,
hs_hash, hs_compare, &my_allocator, 32, 43423)) {
fprintf(stderr, "Unable to initialize library table\n");
exit(1);
}
if (!ck_hs_init(&symbol_table,
CK_HS_MODE_OBJECT | CK_HS_MODE_SPMC,
hs_hash, hs_compare,
&my_allocator, symbol_table_initial_size, 43423)) {
fprintf(stderr, "Unable to initialize symbol table\n");
exit(1);
}
if (pthread_mutex_init(&(symbol_table_lock), NULL) != 0) {
fprintf(stderr, "Unable to initialize symbol_table_lock mutex\n");
exit(1);
}
//ht_test(); // JAE - DEBUGGING!!
}
object cell_get(object cell)
{
// Always use unsafe car here, since cell_get calls are computed by compiler
return car(cell);
}
object Cyc_global_set(void *thd, object identifier, object * glo, object value)
{
gc_mut_update((gc_thread_data *) thd, *glo, value);
if (*glo != value) {
*(glo) = value;
}
((gc_thread_data *) thd)->globals_changed = 1;
return value;
}
static void Cyc_global_set_cps_gc_return(void *data, object cont, int argc, object * args) //object glo_obj, object val, object next)
{
object glo_obj = args[0];
object val = args[1];
object next = args[2];
object *glo = (object *) glo_obj;
if (*glo != val) {
*(glo) = val;
}
closcall1(data, (closure) next, val);
}
object Cyc_global_set_cps(void *thd, object cont, object identifier,
object * glo, object value)
{
int do_gc = 0;
value = transport_stack_value(thd, NULL, value, &do_gc); // glo cannot be thread-local!
gc_mut_update((gc_thread_data *) thd, *glo, value);
if (do_gc) {
// Ensure global is a root. We need to do this here to ensure
// global and all its children are relocated to the heap.
cvar_type cv = { {0}, cvar_tag, glo };
gc_thread_data *data = (gc_thread_data *) thd;
data->mutations = vpbuffer_add(data->mutations,
&(data->mutation_buflen),
data->mutation_count, &cv);
data->mutation_count++;
// Run GC, then do the actual assignment with heap objects
mclosure0(clo, (function_type) Cyc_global_set_cps_gc_return);
object buf[3];
buf[0] = (object) glo;
buf[1] = value;
buf[2] = cont;
GC(data, &clo, buf, 3);
}
if (*glo != value) {
*(glo) = value; // Already have heap objs, do assignment now
}
return value;
}
static boolean_type t_boolean = { {0}, boolean_tag, "t" };
static boolean_type f_boolean = { {0}, boolean_tag, "f" };
static symbol_type Cyc_void_symbol = { {0}, symbol_tag, "" };
const object boolean_t = &t_boolean;
const object boolean_f = &f_boolean;
const object quote_void = &Cyc_void_symbol;
/* Stack Traces */
/**
* @brief Print the contents of the given thread's stack trace buffer.
* @param data Thread data object
* @param out Output stream
*/
void Cyc_st_print(void *data, FILE * out)
{
/* print to stream, note it is possible that
some traces could be on the stack after a GC.
not sure what to do about it, may need to
detect that case and stop printing.
or, with the tbl being so small, maybe it will
not be an issue in practice? a bit risky to ignore though
*/
gc_thread_data *thd = (gc_thread_data *) data;
int n = 1;
int i = (thd->stack_trace_idx - 1);
if (i < 0) {
i = MAX_STACK_TRACES - 1;
}
while (i != thd->stack_trace_idx) {
if (thd->stack_traces[i]) {
fprintf(out, "[%d] %s\n", n++, thd->stack_traces[i]);
}
i = (i - 1);
if (i < 0) {
i = MAX_STACK_TRACES - 1;
}
}
}
/* END Stack Traces section */
/* Symbol Table */
/* Notes for the symbol table
string->symbol can:
- lookup symbol in the table
- if found, return that pointer
- otherwise, allocate symbol in table and return ptr to it
For now, GC of symbols is missing. long-term it probably would be desirable
*/
static char *_strdup(const char *s)
{
char *d = malloc(strlen(s) + 1);
if (d) {
strcpy(d, s);
}
return d;
}
static object find_symbol_by_name(const char *name)
{
symbol_type tmp = { {0}, symbol_tag, name };
object result = set_get(&symbol_table, &tmp);
return result;
}
object add_symbol(symbol_type * psym)
{
pthread_mutex_lock(&symbol_table_lock); // Only 1 "writer" allowed
bool inserted = set_insert(&symbol_table, psym);
pthread_mutex_unlock(&symbol_table_lock);
if (!inserted) {
object sym = find_symbol_by_name(psym->desc);
free((char *)(psym->desc));
free(psym);
return sym;
} else {
return psym;
}
}
static object add_symbol_by_name(const char *name)
{
symbol_type sym = { {0}, symbol_tag, _strdup(name) };
symbol_type *psym = malloc(sizeof(symbol_type));
memcpy(psym, &sym, sizeof(symbol_type));
return add_symbol(psym);
}
object find_or_add_symbol(const char *name)
{
object sym = find_symbol_by_name(name);
if (sym) {
return sym;
} else {
return add_symbol_by_name(name);
}
}
/* END symbol table */
/* Library table */
object is_library_loaded(const char *name)
{
symbol_type tmp = { {0}, symbol_tag, name };
object result = set_get(&lib_table, &tmp);
if (result)
return boolean_t;
return boolean_f;
}
object register_library(const char *name)
{
symbol_type sym = { {0}, symbol_tag, _strdup(name) };
symbol_type *psym = malloc(sizeof(symbol_type));
memcpy(psym, &sym, sizeof(symbol_type));
// Reuse mutex since lib inserts will be rare
pthread_mutex_lock(&symbol_table_lock); // Only 1 "writer" allowed
set_insert(&lib_table, psym);
pthread_mutex_unlock(&symbol_table_lock);
return boolean_t;
}
/* END Library table */
/* Global table */
list global_table = NULL;
void add_global(const char *identifier, object * glo)
{
// Tried using a vpbuffer for this and the benchmark
// results were the same or worse.
global_table = malloc_make_pair(mcvar(glo), global_table);
}
void debug_dump_globals()
{
list l = global_table;
for (; l != NULL; l = cdr(l)) {
cvar_type *c = (cvar_type *) car(l);
//gc_mark(h, *(c->pvar)); // Mark actual object the global points to
printf("DEBUG %p ", c->pvar);
if (*c->pvar) {
printf("mark = %d ", mark(*c->pvar));
if (mark(*c->pvar) == gc_color_red) {
printf("obj = ");
// TODO: no data param: Cyc_display(*c->pvar, stdout);
}
printf("\n");
} else {
printf(" is NULL\n");
}
}
}
void Cyc_set_globals_changed(gc_thread_data * thd)
{
thd->globals_changed = 1;
}
/* END Global table */
/** new write barrier
* This function determines if a mutation introduces a pointer to a stack
* object from a heap object, and if so, either copies the object to the
* heap or lets the caller know a minor GC must be performed.
*
* @param data Current thread's data object
* @param var Object being mutated
* @param value New value being associated to var
* @param run_gc OUT parameter, returns 1 if minor GC needs to be invoked
* @return Pointer to `var` object
*/
object transport_stack_value(gc_thread_data * data, object var, object value,
int *run_gc)
{
char tmp;
int inttmp, *heap_grown = &inttmp;
gc_heap_root *heap = data->heap;
// Nothing needs to be done unless we are mutating
// a heap variable to point to a stack var.
if (!gc_is_stack_obj(&tmp, data, var) && gc_is_stack_obj(&tmp, data, value)) {
// Must move `value` to the heap to allow use by other threads
switch (type_of(value)) {
case string_tag:
case bytevector_tag:
if (immutable(value)) {
// Safe to transport now
object hp =
gc_alloc(heap, gc_allocated_bytes(value, NULL, NULL), value, data,
heap_grown);
return hp;
}
// Need to GC if obj is mutable, EG: a string could be mutated so we can't
// have multiple copies of the object running around
*run_gc = 1;
return value;
case double_tag:
case port_tag:
case c_opaque_tag:
case complex_num_tag:{
// These objects are immutable, transport now
object hp =
gc_alloc(heap, gc_allocated_bytes(value, NULL, NULL), value, data,
heap_grown);
return hp;
}
// Objs w/children force minor GC to guarantee everything is relocated:
case cvar_tag:
case closure0_tag:
case closure1_tag:
case closureN_tag:
case pair_tag:
case vector_tag:
*run_gc = 1;
return value;
default:
// Other object types are not stack-allocated so should never get here
printf("Invalid shared object type %d\n", type_of(value));
exit(1);
}
}
return value;
}
/* Mutation table functions
*
* Keep track of mutations (EG: set-car!) so we can avoid having heap
* objects that point to old stack objects. We need to transport any
* such stack objects to the heap during minor GC.
*
* Note these functions and underlying data structure are only used by
* the calling thread, so locking is not required.
*/
void add_mutation(void *data, object var, int index, object value)
{
gc_thread_data *thd = (gc_thread_data *) data;
char tmp;
// No need to track for minor GC purposes unless we are mutating
// a heap variable to point to a stack var.
//
// If var is on stack we'll get it anyway in minor GC, and if value
// is on heap we don't care (no chance of heap pointing to nursery)
//
// There is one special case. For large vectors we use stack objects
// as a container to store "real" stack values that must be moved
// by the collector. In this case we pass -2 to force collection of
// these objects regardless of whether var is on the heap.
if ((!gc_is_stack_obj(&tmp, data, var) &&
gc_is_stack_obj(&tmp, data, value)) || index == -2) {
thd->mutations = vpbuffer_add(thd->mutations,
&(thd->mutation_buflen),
thd->mutation_count, var);
thd->mutation_count++;
if (index >= 0) {
// For vectors only, add index as another var. That way
// the write barrier only needs to inspect the mutated index.
thd->mutations = vpbuffer_add(thd->mutations,
&(thd->mutation_buflen),
thd->mutation_count, obj_int2obj(index));
thd->mutation_count++;
}
}
}
void clear_mutations(void *data)
{
// Not clearing memory, just resetting count
gc_thread_data *thd = (gc_thread_data *) data;
thd->mutation_count = 0;
}
/* END mutation table */
/* Runtime globals */
object Cyc_glo_call_cc = NULL;
object Cyc_glo_eval_from_c = NULL;
/**
* @brief The default exception handler
* @param data Thread data object
* @param _ Unused, just here to maintain calling convention
* @param argc Unused, just here to maintain calling convention
* @param args Argument buffer, index 0 is object containing data for the error
*/
object Cyc_default_exception_handler(void *data, object _, int argc,
object * args)
{
object err = args[0];
int is_msg = 1;
fprintf(stderr, "Error: ");
if ((err == NULL) || is_value_type(err) || type_of(err) != pair_tag) {
Cyc_display(data, err, stderr);
} else {
// Error is list of form (type arg1 ... argn)
err = cdr(err); // skip type field
for (; (err != NULL); err = cdr(err)) { // output with no enclosing parens
if (is_msg && is_object_type(car(err)) && type_of(car(err)) == string_tag) {
is_msg = 0;
Cyc_display(data, car(err), stderr);
if (cdr(err)) {
fprintf(stderr, ": ");
}
} else {
Cyc_write(data, car(err), stderr);
fprintf(stderr, " ");
}
}
}
fprintf(stderr, "\nCall history, most recent first:\n");
Cyc_st_print(data, stderr);
fprintf(stderr, "\n");
//raise(SIGINT); // break into debugger, unix only
exit(1);
return NULL;
}
/**
* @brief Return the current exception handler
* @param data Thread data object
* @return Object registered as the exception handler, or the default if none.
*/
object Cyc_current_exception_handler(void *data)
{
gc_thread_data *thd = (gc_thread_data *) data;
if (thd->exception_handler_stack == NULL) {
return primitive_Cyc_91default_91exception_91handler;
} else {
return car(thd->exception_handler_stack);
}
}
/**
* @brief Raise an exception from the runtime code
* @param data Thread data object
* @param err Data for the error
*/
void Cyc_rt_raise(void *data, object err)
{
make_pair(c2, err, NULL);
make_pair(c1, boolean_f, &c2);
make_pair(c0, &c1, NULL);
apply(data, NULL, Cyc_current_exception_handler(data), &c0);
// Should never get here
fprintf(stderr, "Internal error in Cyc_rt_raise\n");
exit(1);
}
/**
* @brief Raise an exception from the runtime code
* @param data Thread data object
* @param msg A message describing the error
* @param err Data for the error
*/
void Cyc_rt_raise2(void *data, const char *msg, object err)
{
make_utf8_string(data, s, msg);
make_pair(c3, err, NULL);
make_pair(c2, &s, &c3);
make_pair(c1, boolean_f, &c2);
make_pair(c0, &c1, NULL);
apply(data, NULL, Cyc_current_exception_handler(data), &c0);
// Should never get here
fprintf(stderr, "Internal error in Cyc_rt_raise2\n");
exit(1);
}
/**
* @brief Raise an exception from the runtime code
* @param data Thread data object
* @param err A message describing the error
*/
void Cyc_rt_raise_msg(void *data, const char *err)
{
make_utf8_string(data, s, err);
Cyc_rt_raise(data, &s);
}
/* END exception handler */
object _equalp(object x, object y, int depth);
static int equal(object x, object y, int depth)
{
if (x == y)
return 1;
if (x == NULL)
return (y == NULL);
if (y == NULL)
return (x == NULL);
if (obj_is_char(x))
return obj_is_char(y) && x == y;
if (obj_is_int(x))
return (obj_is_int(y) && x == y) ||
(is_object_type(y) &&
((type_of(y) == integer_tag && integer_value(y) == obj_obj2int(x)) ||
(type_of(y) == bignum_tag
&& Cyc_bignum_cmp(MP_EQ, x, -1, y, bignum_tag))
));
switch (type_of(x)) {
case string_tag:
return (is_object_type(y) &&
type_of(y) == string_tag &&
strcmp(((string_type *) x)->str, ((string_type *) y)->str) == 0);
case double_tag:
return (is_object_type(y) &&
type_of(y) == double_tag &&
((double_type *) x)->value == ((double_type *) y)->value);
case vector_tag:
if (is_object_type(y) &&
type_of(y) == vector_tag &&
((vector) x)->num_elements == ((vector) y)->num_elements) {
int i;
if (x == y)
return 1;
for (i = 0; i < ((vector) x)->num_elements; i++) {
if (_equalp
(((vector) x)->elements[i], ((vector) y)->elements[i],
depth + 1) == boolean_f)
return 0;
}
return 1;
}
return 0;
case bytevector_tag:
if (is_object_type(y) &&
type_of(y) == bytevector_tag &&
((bytevector) x)->len == ((bytevector) y)->len) {
int i;
for (i = 0; i < ((bytevector) x)->len; i++) {
if (((bytevector) x)->data[i] != ((bytevector) y)->data[i]) {
return 0;
}
}
return 1;
}
return 0;
case bignum_tag:{
int ty = -1;
if (is_value_type(y)) {
if (!obj_is_int(y)) {
return 0;
}
} else {
ty = type_of(y);
}
return Cyc_bignum_cmp(MP_EQ, x, bignum_tag, y, ty);
// return (is_object_type(y) &&
// type_of(y) == bignum_tag &&
// MP_EQ == mp_cmp(&bignum_value(x), &bignum_value(y)));
}
//case integer_tag:
// return (obj_is_int(y) && obj_obj2int(y) == integer_value(x)) ||
// (is_object_type(y) &&
// type_of(y) == integer_tag &&
// ((integer_type *) x)->value == ((integer_type *) y)->value);
case complex_num_tag:
return (is_object_type(y) &&
type_of(y) == complex_num_tag &&
((complex_num_type *) x)->value == ((complex_num_type *) y)->value);
default:
return x == y;
}
}
//object Cyc_car(void *data, object lis)
//{
// Cyc_check_pair(data, lis);
// return car(lis);
//}
//
//object Cyc_cdr(void *data, object lis)
//{
// Cyc_check_pair(data, lis);
// return cdr(lis);
//}
object Cyc_get_global_variables()
{
return Cyc_global_variables;
}
object Cyc_get_cvar(object var)
{
if (is_object_type(var) && type_of(var) == cvar_tag) {
return *(((cvar_type *) var)->pvar);
}
return var;
}
object Cyc_set_cvar(object var, object value)
{
if (is_object_type(var) && type_of(var) == cvar_tag) {
*(((cvar_type *) var)->pvar) = value;
}
return var;
}
object Cyc_has_vector_cycle(object vec)
{
int i;
// TODO: this is not generic enough
for (i = 0; i < ((vector) vec)->num_elements; i++) {
if (((vector) vec)->elements[i] == vec) {
return boolean_t;
}
}
return boolean_f;
}
object Cyc_has_cycle(object lst)
{
object slow_lst, fast_lst;
if ((lst == NULL) || is_value_type(lst)) {
return boolean_f;
} else if (is_object_type(lst) && type_of(lst) == vector_tag) {
return Cyc_has_vector_cycle(lst);
} else if (is_object_type(lst) && type_of(lst) != pair_tag) {
return boolean_f;
}
slow_lst = lst;
fast_lst = cdr(lst);
while (1) {
if (fast_lst == NULL)
return boolean_f;
if (Cyc_is_pair(fast_lst) == boolean_f)
return boolean_f;
if ((cdr(fast_lst)) == NULL)
return boolean_f;
if (Cyc_is_pair(cdr(fast_lst)) == boolean_f)
return boolean_f;
if (slow_lst == fast_lst)
return boolean_t;
slow_lst = cdr(slow_lst);
fast_lst = cddr(fast_lst);
}
}
/**
* Predicate - is the object a proper list?
* Based on `Cyc_has_cycle` so it is safe to call on circular lists.
*/
object Cyc_is_list(object lst)
{
object slow_lst, fast_lst;
if (lst == NULL) {
return boolean_t;
} else if (is_value_type(lst)) {
return boolean_f;
} else if (is_object_type(lst) && type_of(lst) != pair_tag) {
return boolean_f;
}
slow_lst = lst;
fast_lst = cdr(lst);
while (1) {
if (fast_lst == NULL)
return boolean_t;
if (Cyc_is_pair(fast_lst) == boolean_f)
return boolean_f; // Improper list
if ((cdr(fast_lst)) == NULL)
return boolean_t;
if (Cyc_is_pair(cdr(fast_lst)) == boolean_f)
return boolean_f; // Improper
if (slow_lst == fast_lst)
return boolean_t; // Cycle; we have a list
slow_lst = cdr(slow_lst);
fast_lst = cddr(fast_lst);
}
}
/**
* Write string representation of a double to a buffer.
* Added code from Chibi Scheme to print a ".0" if the
* double is a whole number (EG: 3.0) to avoid confusion
* in the output (EG: was "3").
*/
int double2buffer(char *buf, int buf_size, double num)
{
if (num == INFINITY) {
return snprintf(buf, buf_size, "+inf.0");
} else if (num == -INFINITY) {
return snprintf(buf, buf_size, "-inf.0");