-
Notifications
You must be signed in to change notification settings - Fork 1
/
odd.hpp
5346 lines (4625 loc) · 158 KB
/
odd.hpp
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
// odd.hpp - scheme in (almost) one header
// Copyright (c) 2011-2012 ioddly
// Website: <http://ioddly.com/projects/odd/>
// Released under the Boost Software License:
// <http://www.boost.org/LICENSE_1_0.txt>
// Welcome to Odd Scheme!
// You can use the following "table of contents" to navigate the source code.
// 1. (PRELUDE) Preprocessor definitions and miscellaneous utilities
// 2. (OBJ) Object representation - How Scheme types are represented in C++
// 3. (GC) Garbage collector
// 4. (RT) Runtime
// 5. (READ) Expression reader and source code tracking
// 6. (CC) Compiler
// 7. (VM) Virtual Machine
// 8. (UTIL) Utilities
// 9. (STD) Standard Scheme functions implemented in C++
// (PRELUDE)
#ifndef ODD_HPP
#define ODD_HPP
#include <assert.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include <limits>
#include <fstream>
#include <iostream>
#include <set>
#include <sstream>
#include <vector>
#if defined(_LP64)
# define ODD_64_BIT 1
#else
# define ODD_64_BIT 0
#endif
// Assertions. Since these can be quite expensive, they're only enabled when
// ODD_DEBUG is explicitly defined.
#ifdef ODD_DEBUG
# define ODD_ASSERT(x) (assert(x))
#else
# define ODD_ASSERT(x) ((void)0)
#endif
// Try to give a graceful error message when internal errors occur
#define ODD_FAIL(desc) { std::cerr << desc << std::endl; ODD_ASSERT(!"failure"); }
// Checking for exceptions
#define ODD_CHECK(x) if((x)->active_exception()) return (x);
// Trace messages
#ifdef ODD_TRACE
# define ODD_GC_MSG(x) if(trace) std::cout << "GC: " << x << std::endl
# define ODD_CC_MSG(x) \
if(state.trace) { \
for(size_t _x = (depth); _x; _x--) \
std::cout << '>'; std::cout << "CC: " << x << std::endl; \
}
# define ODD_CC_VMSG(x) if(state.trace) ODD_CC_MSG(x)
# define ODD_CC_EMIT(x) if(state.trace) ODD_CC_MSG((last_insn) << ": " << x)
# define ODD_VM_MSG(x) \
if(trace) { \
for(size_t _x = (vm_depth); _x != 1; _x--) \
std::cout << '>'; \
std::cout << "VM: " << x << std::endl; \
}
# define ODD_VM_VMSG(y) ODD_VM_MSG("(stack: " << f.si << ") " << y)
// Execute a particular instruction, includes instruction offset
# define ODD_VM_MSG_INSN(y) ODD_VM_MSG("INSN: " << ip-1 << " (stack: " << f.si << ") " << y)
#else
# define ODD_GC_MSG(x)
# define ODD_CC_MSG(x)
# define ODD_CC_VMSG(x)
# define ODD_CC_EMIT(x)
# define ODD_VM_MSG(x)
# define ODD_VM_VMSG(x)
#endif
// Heap alignment is both the default size of the heap and the threshold for
// allocating large objects separate from the normal heap
#ifndef ODD_HEAP_ALIGNMENT
# define ODD_HEAP_ALIGNMENT 4096 // 4KB
#endif
// The "load factor" is a percentage used to determine when to grow the heap.
// When the live objects in memory after a collection exceed this percentage,
// the heap is grown.
#ifndef ODD_LOAD_FACTOR
# define ODD_LOAD_FACTOR 77
#endif
namespace odd {
struct State;
struct Value;
struct String;
struct Symbol;
struct VectorStorage;
struct Table;
std::ostream& operator<<(std::ostream& os, odd::Value* x);
std::ostream& print_table(std::ostream& os, Table* t);
///// UTILITIES
// Align size along boundary (eg align(4,3) => 4, align(4,5) => 8)
inline size_t align(size_t boundary, size_t size) {
return ((((size - 1) / (boundary)) + 1) * boundary);
}
// Print a byte count in a readable format (eg 4096 => 4K etc)
struct FriendlySize {
size_t s;
FriendlySize(size_t s_): s(s_) {}
};
inline std::ostream& operator<<(std::ostream& os, FriendlySize f) {
char ending = 'b';
if(f.s >= 1024) { f.s /= 1024; ending = 'K'; }
if(f.s >= 1024) { f.s /= 1024; ending = 'M'; }
if(f.s >= 1024) { f.s /= 1024; ending = 'G'; }
return os << f.s << ending;
}
// Warning: do not change structure without changing how compiler encodes debuginfo
struct SourceInfo {
SourceInfo(): file(0), line(0) {}
unsigned file, line;
};
typedef std::pair<unsigned, SourceInfo> debug_t;
///// (OBJ) Object representation
// <--
// The first thing a language implementation needs to do is determine how to
// represent the language's values in memory. It's hard to interact with
// objects when you don't even know what they look like!
// So how do we represent a Scheme object (dynamically typed) with a C++
// structure? The easiest way would be to take advantage of C++'s polymorphism.
// But I've decided to go in a different direction, for performance reasons.
// Odd values can be either immediate (they are contained directly within an
// integer) or heap-allocated (they are referenced by a pointer). In any case,
// these values are generally represented and passed around as "Value*".
// Why would we want to have "immediate" values? To save on allocating and
// dereferencing pointers when dealing with basic constants (such as boolean
// values, or most numbers). The downside of this approach is that pointers
// cannot be safely dereferenced without checking types first, but since we're
// dealing with dynamic objects, we generally have to check types before doing
// anything anyway.
// How do we determine an object's type? First, we have to check its bits. Each
// Value* has the following bit layout
// 0000 0000 - False, or #f
// .... ..10 - For constants
// .... ...1 - For fixed-point numbers
// .... ..00 - For real pointers
// In addition, heap-allocated objects have a type field. This is all handled
// by methods within the Value class. (Oddly enough, though we can't
// dereference a Value* safely, we can execute methods on it)
// Beyond that, objects are largely represented just like you'd think they
// would be. For instance, a Pair contains two pointers.
// -->
// Cast with assertions (will cause double evaluation; do not give an argument
// with side effects)
#define ODD_CAST(klass, x) (ODD_ASSERT((x)->get_type() == odd::klass ::CLASS_TYPE), (klass *) (x))
// Constant values
#define ODD_FALSE ((odd::Value*) 0)
#define ODD_TRUE ((odd::Value*) 2)
#define ODD_NULL ((odd::Value*) 6)
#define ODD_EOF ((odd::Value*) 10)
#define ODD_UNSPECIFIED ((odd::Value*) 18)
// C++ object types (which may not match up exactly with Scheme predicates)
// NOTE: Adding a type requires several modifications; search for "TYPENOTE"
enum Type {
TRANSIENT,
PAIR,
VECTOR,
VECTOR_STORAGE,
BLOB,
STRING,
SYMBOL,
EXCEPTION,
BOX,
// Functions
PROTOTYPE,
CLOSURE,
UPVALUE,
NATIVE_FUNCTION,
// Other
TABLE,
SYNCLO,
// Immediate values
FIXNUM,
CONSTANT,
};
std::ostream& operator<<(std::ostream& os, Type& t);
struct Value {
// The space that's been allocated for this object, for the garbage
// collector.
size_t size;
// The 'header' field contains an object's type, the garbage collector mark,
// and other information that can be represented with a bit or two (such as
// whether a Pair has source code information attached)
unsigned int header;
// Headers have the following format
// SSSS SSSM TTTT TTTT
// Where S is 0 or an object-specific flag
// M is the garbage collector mark
// T is the object's type
// The following methods deal with size and type and are mostly for internal
// use
// Get the bits of a Value*
ptrdiff_t bits() const { return (ptrdiff_t) this; }
// Type predicates
// Check for ...1
bool fixnump() const { return bits() & 1; }
// Check for 0 or ..10
bool constantp() const { return ((ptrdiff_t) this) == 0 || (bits() & 3) == 2; }
// Check for ..00 (and not null)
bool pointerp() const { return ((ptrdiff_t) this != 0) && (bits() & 3) == 0; }
// Anything that isn't a pointer is immediate
bool immediatep() const { return !pointerp(); }
bool applicablep() const {
switch(get_type()) {
case CLOSURE:
case PROTOTYPE:
case NATIVE_FUNCTION: return true;
default: return false;
}
}
// Methods for interacting with the header safely
int get_header_bit(Type type, int bit) const {
ODD_ASSERT(pointerp()); ODD_ASSERT(get_type() == type);
return header & bit;
}
void set_header_bit(Type type, int bit) {
ODD_ASSERT(get_type() == type);
header += bit;
}
void unset_header_bit(Type type, int bit) {
ODD_ASSERT(get_type() == type);
header -= bit;
}
// Set the header's type and mark (for the garbage collector)
void set_header_unsafe(unsigned char type, bool mark, size_t mark_bit) {
header = (mark ? (mark_bit << 8) : (!mark_bit << 8)) + type;
}
// Interacting with marks and types
int get_mark_unsafe() const { return (header & (1 << 8)) != 0; }
size_t get_size_unsafe() const { return size; }
void set_size_unsafe(size_t size_) { size = size_; }
void flip_mark_unsafe() { header += get_mark_unsafe() ? -256 : 256; }
void set_type_unsafe(int type) { header = (get_mark_unsafe() << 8) + type; }
// Get the type of a heap-allocated object
unsigned char get_type_unsafe() const { return header & 255; };
// Safely determine the type of an object
Type get_type() const {
return fixnump() ? FIXNUM :
(constantp() ? CONSTANT : static_cast<Type>(get_type_unsafe()));
}
// Type specific methods: simple getters and setters, object flags
static Value* to_boolean(bool i) { return i ? ODD_TRUE : ODD_FALSE; }
// Fixnums
static Value* make_fixnum(ptrdiff_t n) { return (Value*) ((n << 1) + 1); }
ptrdiff_t fixnum_value() const { return bits() >> 1; }
// Pairs
// True when the Pair has source code information attached
static const int PAIR_HAS_SOURCE_BIT = 1 << 15;
bool pair_has_source() const {
return get_header_bit(PAIR, PAIR_HAS_SOURCE_BIT);
}
Value* car() const;
Value* cdr() const;
Value* caar() const;
Value* cadr() const;
Value* cddr() const;
Value* cdar() const;
Value* caadr() const;
Value* cdadr() const;
Value* caddr() const;
Value* list_ref(size_t i) const;
bool memq(Value* x);
void set_car(Value*);
void set_cdr(Value*);
// Vectors
Value** vector_data();
Value* vector_ref(size_t i);
void vector_set(size_t, Value*);
size_t vector_length() const;
VectorStorage* vector_storage() const;
bool vector_memq(Value* x);
// Vector storage
Value** vector_storage_data() const;
// Blobs
const char* blob_data() const;
unsigned blob_length() const;
// Templated functions for dealing with structured data within blobs
template <class T> unsigned blob_length() const;
template <class T> T blob_ref(unsigned) const;
template <class T> void blob_set(unsigned, T& value) const;
// Strings
const char* string_data() const;
unsigned string_length() const;
// Symbols
Value* symbol_name() const;
Value* symbol_value() const;
// Exceptions
// True when an exception is active and should be passed on
static const int EXCEPTION_ACTIVE_BIT = 1 << 15;
bool active_exception() const {
return get_type() == EXCEPTION && (header & EXCEPTION_ACTIVE_BIT);
}
Symbol* exception_tag() const;
String* exception_message() const;
Value* exception_irritants() const;
// Boxes
// True when a box contains source code information
static const int BOX_HAS_SOURCE_BIT = 1 << 15;
bool box_has_source() const {
return get_header_bit(BOX, BOX_HAS_SOURCE_BIT);
}
Value* box_value() const;
// Prototypes
static const int PROTOTYPE_VARIABLE_ARITY_BIT = 1 << 15;
bool prototype_variable_arity() const {
return get_header_bit(PROTOTYPE, PROTOTYPE_VARIABLE_ARITY_BIT);
}
const char* prototype_name() const;
// Upvalues
static const int UPVALUE_CLOSED_BIT = 1 << 15;
bool upvalue_closed() const {
return get_header_bit(UPVALUE, UPVALUE_CLOSED_BIT);
}
Value* upvalue() const;
void upvalue_set(Value*);
void upvalue_close();
// Native functions
static const int NATIVE_FUNCTION_VARIABLE_ARITY_BIT = 1 << 15;
bool native_function_variable_arity() const {
return get_header_bit(NATIVE_FUNCTION, NATIVE_FUNCTION_VARIABLE_ARITY_BIT);
}
// Syntactic closures
Value* synclo_expr() const;
Table* synclo_env() const;
Value* synclo_vars() const;
};
struct Pair : Value {
Value *car, *cdr;
// Source code information; only available when pair_has_source() is true
SourceInfo src;
static const Type CLASS_TYPE = PAIR;
};
Value* Value::car() const {
ODD_ASSERT(get_type() == PAIR);
return static_cast<const Pair*>(this)->car;
}
Value* Value::cdr() const {
ODD_ASSERT(get_type() == PAIR);
return static_cast<const Pair*>(this)->cdr;
}
Value* Value::caar() const {
ODD_ASSERT(get_type() == PAIR);
return static_cast<const Pair*>(this)->car->car();
}
Value* Value::cadr() const {
ODD_ASSERT(get_type() == PAIR);
return static_cast<const Pair*>(this)->cdr->car();
}
Value* Value::cddr() const {
ODD_ASSERT(get_type() == PAIR);
return static_cast<const Pair*>(this)->cdr->cdr();
}
Value* Value::cdar() const {
ODD_ASSERT(get_type() == PAIR);
return static_cast<const Pair*>(this)->car->cdr();
}
Value* Value::cdadr() const {
ODD_ASSERT(get_type() == PAIR);
return static_cast<const Pair*>(this)->cdr->car()->cdr();
}
Value* Value::caadr() const {
ODD_ASSERT(get_type() == PAIR);
return static_cast<const Pair*>(this)->cdr->car()->car();
}
Value* Value::caddr() const {
ODD_ASSERT(get_type() == PAIR);
return static_cast<const Pair*>(this)->cdr->cdr()->car();
}
Value* Value::list_ref(size_t i) const {
ODD_ASSERT(get_type() == PAIR);
const Value* lst = this;
while(i--) {
lst = lst->cdr();
}
return lst ? lst->car() : ODD_FALSE;
}
bool Value::memq(Value* x) {
Value* lst = this;
while(lst->get_type() == PAIR) {
if(lst->car() == x) return true;
lst = lst->cdr();
}
return false;
}
void Value::set_car(Value* car_) {
ODD_ASSERT(get_type() == PAIR);
static_cast<Pair*>(this)->car = car_;
}
void Value::set_cdr(Value* cdr_) {
ODD_ASSERT(get_type() == PAIR);
static_cast<Pair*>(this)->cdr = cdr_;
}
struct VectorStorage : Value {
unsigned length;
Value* data[1];
static const Type CLASS_TYPE = VECTOR_STORAGE;
};
Value** Value::vector_storage_data() const {
ODD_ASSERT(get_type() == VECTOR_STORAGE);
return (Value**)static_cast<const VectorStorage*>(this)->data;
}
struct Vector : Value {
VectorStorage* storage;
unsigned capacity;
static const Type CLASS_TYPE = VECTOR;
};
VectorStorage* Value::vector_storage() const {
ODD_ASSERT(get_type() == VECTOR);
return static_cast<const Vector*>(this)->storage;
}
Value** Value::vector_data() { return vector_storage()->data; }
Value* Value::vector_ref(size_t i) { return vector_storage()->data[i]; }
void Value::vector_set(size_t i, Value* v) { vector_storage()->data[i] = v; }
size_t Value::vector_length() const { return vector_storage()->length; }
bool Value::vector_memq(Value* x) {
if(get_type() != VECTOR) return false;
for(size_t i = 0; i != vector_length(); i++) {
if(vector_ref(i) == x) return true;
}
return false;
}
struct Blob : Value {
unsigned length;
char data[1];
static const Type CLASS_TYPE = BLOB;
};
const char* Value::blob_data() const {
ODD_ASSERT(get_type() == BLOB); return static_cast<const Blob*>(this)->data;
}
unsigned Value::blob_length() const {
ODD_ASSERT(get_type() == BLOB);
return static_cast<const Blob*>(this)->length;
}
template <class T>
unsigned Value::blob_length() const {
ODD_ASSERT(get_type() == BLOB);
return static_cast<const Blob*>(this)->length / sizeof(T);
}
template <class T>
T Value::blob_ref(unsigned i) const {
ODD_ASSERT(get_type() == BLOB); return ((T*)
static_cast<const Blob*>(this)->data)[i];
}
template <class T>
void Value::blob_set(unsigned i, T& val) const {
ODD_ASSERT(get_type() == BLOB);
((T*) static_cast<const Blob*>(this)->data)[i] = val;
}
struct String : Blob {
static const Type CLASS_TYPE = STRING;
};
const char* Value::string_data() const {
ODD_ASSERT(get_type() == STRING); return static_cast<const String*>(this)->data;
}
unsigned Value::string_length() const {
ODD_ASSERT(get_type() == STRING);
return static_cast<const String*>(this)->length;
}
struct Symbol : Value {
Value *name, *value;
static const Type CLASS_TYPE = SYMBOL;
};
Value* Value::symbol_name() const {
ODD_ASSERT(get_type() == SYMBOL);
return static_cast<const Symbol*>(this)->name;
}
Value* Value::symbol_value() const {
ODD_ASSERT(get_type() == SYMBOL);
return static_cast<const Symbol*>(this)->value;
}
struct Exception : Value {
Symbol* tag;
String* message;
Value* irritants;
static const Type CLASS_TYPE = EXCEPTION;
};
Symbol* Value::exception_tag() const {
ODD_ASSERT(get_type() == EXCEPTION);
return static_cast<const Exception*>(this)->tag;
};
String* Value::exception_message() const {
ODD_ASSERT(get_type() == EXCEPTION);
return static_cast<const Exception*>(this)->message;
};
Value* Value::exception_irritants() const {
ODD_ASSERT(get_type() == EXCEPTION);
return static_cast<const Exception*>(this)->irritants;
};
struct Box : Value {
Value* value;
SourceInfo src;
static const Type CLASS_TYPE = BOX;
};
Value* Value::box_value() const {
ODD_ASSERT(get_type() == BOX);
return static_cast<const Box*>(this)->value;
};
// Prototype for a function containing constants, code, and debugging
// information. May be executed directly if the function does not reference
// free variables.
struct Prototype : Value {
Vector* constants;
Blob* code;
Blob* debuginfo;
// A list of local free variables referenced by other functions, which will
// be converted into upvalues when the function ends
Blob* local_free_variables;
// A list of upvalues, which will be used to turn this into a closure if
// necessary
Blob* upvalues;
// The function's name, if available, or #f if not
String* name;
unsigned stack_max;
unsigned locals;
unsigned local_free_variable_count;
unsigned arguments;
static const Type CLASS_TYPE = PROTOTYPE;
};
const char* Value::prototype_name() const {
ODD_ASSERT(get_type() == PROTOTYPE);
return static_cast<const Prototype*>(this)->name
? static_cast<const Prototype*>(this)->name->string_data() : "anonymous";
}
// A closure, aka a function which references free variables
struct Closure : Value {
Prototype* prototype;
// Vector containing Upvalues
VectorStorage* upvalues;
static const Type CLASS_TYPE = CLOSURE;
};
// A reference to a free variable; used to support closures
struct Upvalue : Value {
union {
Value** local;
Value* converted;
};
static const Type CLASS_TYPE = UPVALUE;
};
Value* Value::upvalue() const {
Upvalue* u = ODD_CAST(Upvalue, this);
return upvalue_closed() ? u->converted : *(u->local);
}
void Value::upvalue_set(Value* v) {
Upvalue* u = ODD_CAST(Upvalue, this);
if(upvalue_closed())
u->converted = v;
else
(*u->local) = v;
}
void Value::upvalue_close() {
Upvalue* u = ODD_CAST(Upvalue, this);
set_header_bit(UPVALUE, UPVALUE_CLOSED_BIT);
u->converted = *u->local;
}
struct NativeFunction : Value {
typedef Value* (*ptr_t)(State&, unsigned, Value* args[], VectorStorage*);
VectorStorage* closure;
unsigned arguments;
ptr_t pointer;
static const Type CLASS_TYPE = NATIVE_FUNCTION;
};
struct Table : Value {
static const int LOAD_FACTOR = 70;
// Chain format: vector of lists, where lists are ((key . value) ...)
// With as many key/value pairs as necessary for collisions
VectorStorage* chains;
unsigned char size_log2;
unsigned entries, max_entries;
static const Type CLASS_TYPE = TABLE;
};
// Syntactic closures
struct Synclo : Value {
Table* env;
Value* vars;
Value* expr;
static const Type CLASS_TYPE = SYNCLO;
};
Value* Value::synclo_expr() const {
ODD_ASSERT(get_type() == SYNCLO);
return static_cast<const Synclo*>(this)->expr;
}
Table* Value::synclo_env() const {
ODD_ASSERT(get_type() == SYNCLO);
return static_cast<const Synclo*>(this)->env;
}
Value* Value::synclo_vars() const {
ODD_ASSERT(get_type() == SYNCLO);
return static_cast<const Synclo*>(this)->vars;
}
///// GARBAGE COLLECTOR TRACKING
// Garbage-collector tracked vector
typedef std::vector<Value*> value_vector_t;
struct SafeVector : std::vector<value_vector_t> {
SafeVector(State& state);
~SafeVector();
State& state;
};
// Handles are auto-tracked heap-allocated pointers
template <class T>
struct Handle {
Handle(State& state_): state(state_), ref(0) {
initialize();
}
Handle(State& state_, T* ref_): state(state_), ref(ref_) {
initialize();
}
void initialize();
~Handle();
State& state;
T* ref;
Handle<Value> *previous, *next;
T* operator*() const { return ref; }
T* operator->() const { return ref; }
void operator=(T* ref_) { ref = ref_; }
void swap(Value*& other) {
Value* s = ref;
ref = (T*) other;
other = s;
}
};
// This structure is used in the GC tracking macros to take a normal
// pointer to a Odd value of any type and obtain a Value** pointer to it
struct FrameHack {
// TYPENOTE
#define ODD_(t) FrameHack(t *& ref): ref((Value**) &ref) {}
ODD_(Value)
ODD_(Pair)
ODD_(Blob)
ODD_(Symbol)
ODD_(Vector)
ODD_(VectorStorage)
ODD_(String)
ODD_(Exception)
ODD_(Box)
ODD_(Prototype)
ODD_(Closure)
ODD_(Upvalue)
ODD_(NativeFunction)
ODD_(Synclo)
ODD_(Table)
#undef ODD_
~FrameHack() {}
Value** ref;
};
// Frames are are stack-allocated vectors of variables that push and
// pop themselves along with the program stack.
struct Frame {
Frame(State&, FrameHack*, size_t);
~Frame();
State& state;
Value*** roots;
size_t root_count;
Frame* previous;
};
// Frame with explicit state argument
#define ODD_E_FRAME(state, ...) \
odd::FrameHack __odd_frame_hacks[] = { __VA_ARGS__ }; \
odd::Frame __odd_frame((state), (FrameHack*) __odd_frame_hacks, \
sizeof(__odd_frame_hacks) / sizeof(odd::FrameHack))
// For general use
// Assumes there is a variable State& state
#define ODD_FRAME(...) ODD_E_FRAME((state), __VA_ARGS__)
#define ODD_S_FRAME(...) ODD_E_FRAME((*this), __VA_ARGS__)
// Some forward declarations for state
#define ODD_FUNCTION(name) \
inline Value* name (State& state, unsigned argc, Value* args[], \
VectorStorage* closure)
ODD_FUNCTION(apply_macro);
struct State {
struct VMFrame;
///// (GC) Garbage collector
// <--
// Odd's garbage collector is a mark-and-don't-sweep collector. The allocator
// is a first-fit allocator: it allocates memory from the first appropriately
// sized free chunk of memory it can find. It marks every chunk of memory it
// sweeps over (or, if the chunk is already marked, it skips it). When the
// allocator reaches the end of the heap, the meaning of the mark bit is
// flipped, and the entire heap is considered garbage. Then the collector
// immediately marks all live memory, and we know which objects are marked.
// The benefit of a mark-and-don't-sweep collector is that the work is spread
// out amongst allocations and should (in most cases) result in no large
// pauses to the program. It requires no external data structures; the only
// overhead being that each object needs a "size" and "mark" field (and in
// Odd's case, the mark field is stored alongside type and other flags in a
// space efficient manner). The main downside is fragmentation.
// How does Odd mark live memory? It starts with the program's "roots" and
// marks all their children and so on. But how do we find the roots? They are
// explicitly registered with the garbage collector using two methods: Frames
// and Handles. A Frame is a stack-allocated structure that keeps track of as
// many variables as needed. You create a frame in each function you want to
// track variables in like so: ODD_FRAME(var1, var2). A Handle is a
// heap-allocated structure that keeps track of one variable, and is useful
// when your variables have lifetimes beyond the execution of a single
// function.
// How does Odd get memory from the operating system? It starts by using a
// small amount of memory (4 kilobytes). If, after a collection, more than a
// certain amount of memory is in use (the "load factor", by default 77%), it
// allocates twice as much memory to avoid collecting too often. It can also
// allocate more memory if a very large object (over 4kb) is allocated.
// In addition to normal collection, Odd has support for doing a full
// compaction on the heap, reducing fragmentation to 0. Currently, this can
// only be used manually and only at the top-level of program execution. So
// although it might not benefit a normal program's execution, it could be
// used eg while a game is loading levels to prevent fragmentation over time
// -->
static const size_t POINTER_ALIGNMENT = sizeof(void*);
struct Block {
size_t size;
char *begin, *end;
Block(size_t size, bool mark, int mark_bit) {
begin = (char*) malloc(size);
end = begin + size;
((Value*) begin)->set_header_unsafe(TRANSIENT, mark, mark_bit);
((Value*) begin)->set_size_unsafe(size);
}
~Block() {
free(begin);
}
};
// Actual heap
std::vector<Block*> blocks;
// Garbage collector root set
Handle<Value>* handle_list;
std::set<SafeVector*> safe_vectors;
std::vector<VMFrame*> vm_frames;
Frame* frame_list;
// Print a bunch of messages about compiler, virtual machine, etc, only works with ODD_DEBUG
bool trace;
// Does exactly what it says. Helpful for flushing out garbage collector bugs. Expensive.
bool collect_before_every_allocation;
// If false, will not optimize tail calls. Handy for debugging purposes.
bool optimize_tail_calls;
// Garbage collector data
int mark_bit;
size_t heap_size, block_cursor, live_at_last_collection, collections;
char* sweep_cursor;
bool markedp(Value* x) {
return x->get_mark_unsafe() == mark_bit;
}
void recursive_mark(Value* x) {
// TYPENOTE
// Done in a while loop to save stack space
while(x->pointerp() && !markedp(x)) {
live_at_last_collection += x->get_size_unsafe();
x->flip_mark_unsafe();
switch(x->get_type_unsafe()) {
// Note that in order to save a little redunancy, objects are marked
// based on their structure (eg all objects with two pointers are
// marked as though they were pairs)
// Atomic
case STRING: case BLOB:
return;
// One pointer
case NATIVE_FUNCTION: case TABLE: case VECTOR: case BOX:
x = static_cast<Box*>(x)->value;
continue;
// Two pointers
case CLOSURE: case PAIR: case SYMBOL:
recursive_mark(static_cast<Pair*>(x)->cdr);
x = static_cast<Pair*>(x)->car;
continue;
// Three pointers
case SYNCLO:
case EXCEPTION:
recursive_mark(static_cast<Exception*>(x)->tag);
recursive_mark(static_cast<Exception*>(x)->message);
x = static_cast<Exception*>(x)->irritants;
continue;
// Four pointers
case PROTOTYPE:
recursive_mark(static_cast<Prototype*>(x)->code);
recursive_mark(static_cast<Prototype*>(x)->debuginfo);
recursive_mark(static_cast<Prototype*>(x)->local_free_variables);
recursive_mark(static_cast<Prototype*>(x)->upvalues);
recursive_mark(static_cast<Prototype*>(x)->name);
x = static_cast<Prototype*>(x)->constants;
continue;
// Special types
case VECTOR_STORAGE: {
VectorStorage* s = static_cast<VectorStorage*>(x);
if(s->length) {
for(size_t i = 0; i != s->length - 1; i++) {
recursive_mark(s->data[i]);
}
x = s->data[s->length - 1];
}
continue;
}
case UPVALUE: {
x = x->upvalue();
continue;
}
default:
ODD_FAIL("recursive_mark got bad type " << x->get_type());
}
}
}
// This really is the meat of the garbage collector. It's just a
// first fit allocator that makes sure things are appropriately marked.
char* findfree(size_t required) {
char* address = NULL;
Value* sweep_cursor_v = NULL, *address_v = NULL;
Block* block = NULL;
while(block_cursor != blocks.size()) {
block = blocks[block_cursor];
ODD_ASSERT(sweep_cursor >= block->begin && sweep_cursor <= block->end);
while(sweep_cursor != block->end) {
sweep_cursor_v = (Value*) sweep_cursor;
// If this space is used, skip it
if(markedp(sweep_cursor_v)) {
sweep_cursor += sweep_cursor_v->get_size_unsafe();
sweep_cursor_v = (Value*) sweep_cursor;
// Should never go past the end of the heap