-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathloxvm.c
3074 lines (2726 loc) · 80.3 KB
/
loxvm.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
// MIT License
//
// Copyright (c) 2020 Victor Gomes
// Copyright (c) 2015 Robert Nystrom (http://craftinginterpreters.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <assert.h>
#include <ctype.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define DECLARE(name) \
struct name; \
typedef struct name name
#define UNUSED __attribute__((unused))
// #define DEBUG_PRINT_CODE
// #define DEBUG_TRACE_EXECUTION
// #define DEBUG_STRESS_GC
// #define DEBUG_LOG_GC
// Constants
#define FRAMES_MAX 64
#define STACK_MAX (FRAMES_MAX * (UINT8_MAX + 1))
#define TABLE_MAX_LOAD 0.75
#define GC_HEAP_GROW_FACTOR 2
// Runtime objects and values.
DECLARE(Class);
DECLARE(Closure);
DECLARE(Function);
DECLARE(Instance);
DECLARE(Method);
DECLARE(Native);
DECLARE(Object);
DECLARE(String);
DECLARE(Upvalue);
DECLARE(Value);
DECLARE(ValueArray);
// Hashtable.
DECLARE(Entry);
DECLARE(Table);
// VM
DECLARE(Chunk);
DECLARE(VM);
struct Table {
int count; // Includes tombstones.
int capacity;
Entry *entries;
};
struct ValueArray {
int count;
int capacity;
Value *values;
};
struct Chunk {
int count;
int capacity;
uint8_t *code;
int *lines;
ValueArray constants;
};
typedef Value (*NativeFn)(int arg_count, Value *args);
typedef enum {
VAL_BOOL,
VAL_NIL,
VAL_NUMBER,
VAL_OBJECT,
} ValueType;
typedef enum {
OBJ_CLASS,
OBJ_CLOSURE,
OBJ_FUNCTION,
OBJ_INSTANCE,
OBJ_METHOD,
OBJ_NATIVE,
OBJ_STRING,
OBJ_UPVALUE
} ObjectType;
typedef enum {
TYPE_FUNCTION,
TYPE_METHOD,
TYPE_INIT,
TYPE_SCRIPT,
} FunctionType;
struct Object {
ObjectType type;
bool is_marked;
Object *next;
};
struct String {
Object obj;
int length;
const char *chars;
uint32_t hash;
};
struct Value {
ValueType type;
union {
bool boolean;
double number;
Object *object;
} as;
};
struct Function {
Object obj;
int arity;
int upvalue_count;
Chunk chunk;
String *name;
};
struct Upvalue {
Object obj;
Value *location;
Value closed;
Upvalue *next;
};
struct Closure {
Object obj;
Function *function;
Upvalue **upvalues;
int upvalue_count;
};
struct Class {
Object obj;
String *name;
Table methods;
};
struct Instance {
Object obj;
Class *class;
Table fields;
};
struct Method {
Object obj;
Value receiver;
Closure *method;
};
struct Native {
Object obj;
NativeFn function;
};
typedef enum {
INTERPRET_OK,
INTERPRET_COMPILE_ERROR,
INTERPRET_RUNTIME_ERROR,
} InterpretResult;
typedef enum {
// Single-character tokens.
TK_LPAREN,
TK_RPAREN,
TK_LBRACE,
TK_RBRACE,
TK_COMMA,
TK_DOT,
TK_MINUS,
TK_PLUS,
TK_SEMI,
TK_SLASH,
TK_STAR,
// One or two character tokens.
TK_BANG,
TK_BANG_EQUAL,
TK_EQUAL,
TK_EQUAL_EQUAL,
TK_GREATER,
TK_GREATER_EQUAL,
TK_LESS,
TK_LESS_EQUAL,
// Literals.
TK_ID,
TK_STRING,
TK_NUMBER,
// Keywords.
TK_AND,
TK_CLASS,
TK_ELSE,
TK_FALSE,
TK_FOR,
TK_FUN,
TK_IF,
TK_NIL,
TK_OR,
TK_PRINT,
TK_RETURN,
TK_SUPER,
TK_THIS,
TK_TRUE,
TK_VAR,
TK_WHILE,
// Misc.
TK_ERROR,
TK_EOF
} TokenType;
typedef struct {
TokenType type;
const char *start;
int length;
int line;
} Token;
typedef enum {
// Literals
OP_CONST,
OP_NIL,
OP_TRUE,
OP_FALSE,
// Getters/Setters
OP_SET_LOCAL,
OP_GET_LOCAL,
OP_SET_GLOBAL,
OP_GET_GLOBAL,
OP_GET_PROP,
OP_SET_PROP,
OP_GET_SUPER,
OP_SET_UPVALUE,
OP_GET_UPVALUE,
// Arithmetic operations
OP_NEG,
OP_ADD,
OP_SUB,
OP_MUL,
OP_DIV,
// Comparisons
OP_NOT,
OP_EQUAL,
OP_GREATER,
OP_LESS,
// Jumps
OP_JMP,
OP_JMP_IF_FALSE,
OP_LOOP,
OP_CALL,
// Fast calls (Invokes)
OP_SUPER_INVOKE, // OP_GET_SUPER + OP_CALL
OP_INVOKE, // OP_GET_PROPERTY + OP_CALL
// Closures
OP_CLOSURE,
OP_CLOSE_UPVALUE,
// Class
OP_CLASS,
OP_INHERIT,
OP_METHOD,
// Misc
OP_DEFINE_GLOBAL,
OP_POP,
OP_PRINT,
OP_RET,
OP_CODE_SIZE
} OpCode;
static_assert(OP_CODE_SIZE < 256, "Maximum number of possible bytecodes.");
// Object constructors
#define BOOL(value) ((Value){VAL_BOOL, {.boolean = value}})
#define NIL ((Value){VAL_NIL, {.number = 0}})
#define NUMBER(value) ((Value){VAL_NUMBER, {.number = value}})
#define OBJECT(value) ((Value){VAL_OBJECT, {.object = (Object *)value}})
// Object casting
#define AS_OBJECT(value) ((value).as.object)
#define AS_CLASS(value) ((Class *)AS_OBJECT(value))
#define AS_INSTANCE(value) ((Instance *)AS_OBJECT(value))
#define AS_METHOD(value) ((Method *)AS_OBJECT(value))
#define AS_CLOSURE(value) ((Closure *)AS_OBJECT(value))
#define AS_FUNCTION(value) ((Function *)AS_OBJECT(value))
#define AS_NATIVE(value) ((Native *)AS_OBJECT(value))->function
#define AS_STRING(value) ((String *)AS_OBJECT(value))
// Check value types
#define IS_BOOL(value) ((value).type == VAL_BOOL)
#define IS_NIL(value) ((value).type == VAL_NIL)
#define IS_NUMBER(value) ((value).type == VAL_NUMBER)
#define IS_OBJECT(value) ((value).type == VAL_OBJECT)
#define IS_CLASS(value) (object_is_type(value, OBJ_CLASS))
#define IS_INSTANCE(value) (object_is_type(value, OBJ_INSTANCE))
#define IS_METHOD(value) (object_is_type(value, OBJ_METHOD);
#define IS_CLOSURE(value) (object_is_type(value, OBJ_CLOSURE))
#define IS_FUNCTION(value) (object_is_type(value, OBJ_FUNCTION))
#define IS_NATIVE(value) (object_is_type(value, OBJ_NATIVE))
#define IS_STRING(value) (object_is_type(value, OBJ_STRING))
// Memory
#define ALLOCATE(type, count) \
(type *)reallocate(NULL, 0, sizeof(type) * (count))
#define FREE(type, pointer) reallocate(pointer, sizeof(type), 0)
static void *reallocate(void *prev, size_t old_size, size_t new_size);
// Array
#define ARRAY_GROW(prev, type, old_count, count) \
(type *)reallocate(prev, sizeof(type) * (old_count), sizeof(type) * (count))
#define ARRAY_FREE(type, pointer, old_count) \
reallocate(pointer, sizeof(type) * (old_count), 0)
static inline int array_grow_capacity(int capacity);
// Runtime objects
static Object *object_allocate(size_t size, ObjectType type);
#define OBJECT_ALLOCATE(type, obj_type) \
(type *)object_allocate(sizeof(type), obj_type)
static void object_free(Object *object);
static void object_mark(Object *object);
// Object constructors
static Class *class_new(String *name);
static Closure *closure_new(Function *function);
static Function *function_new();
static Instance *instance_new(Class *class);
static Method *method_new(Value receiver, Closure *method);
static Native *native_new(NativeFn function);
static Upvalue *upvalue_new(Value *slot);
// String
static String *string_take(const char *chars, int length);
static String *string_copy(const char *chars, int length);
// Value
static bool value_equals(Value a, Value b);
static void value_print(Value value);
static void value_mark(Value value);
// Array of Values
static void value_array_init(ValueArray *array);
static void value_array_free(ValueArray *array);
static void value_array_write(ValueArray *array, Value value);
// HashTable of Values
static void table_init(Table *table);
static void table_free(Table *table);
static bool table_get(Table *table, String *key, Value *value);
static bool table_set(Table *table, String *key, Value value);
static bool table_delete(Table *table, String *key);
static void table_add_all(Table *from, Table *to);
static String *table_find_string(Table *table, const char *chars, int length,
uint32_t hash);
static void table_mark(Table *table);
// Chunk of instructions
static void chunk_init(Chunk *chunk);
static void chunk_free(Chunk *chunk);
static void chunk_write(Chunk *chunk, uint8_t byte, int line);
static int chunk_add_constant(Chunk *chunk, Value value);
// Disassembly
UNUSED static void disassemble_chunk(Chunk *chunk, const char *name);
static int disassemble_instruction(Chunk *chunk, int offset);
// Scanner
static void scanner_init(const char *source);
static Token scan_token();
// Parser
static void parser_error(const char *message);
static void parse();
// Emitter
static void emit_byte(uint8_t byte);
static void emit_bytes(uint8_t byte1, uint8_t byte2);
static void emit_constant(Value value);
static void emit_define_variable(uint8_t global);
static int emit_jump(uint8_t instruction);
static void emit_patch_jump(int offset);
static void emit_loop(int loop_start);
static void emit_return();
// Scope
static void scope_begin();
static void scope_end();
static int scope_depth();
static void scope_add_local(Token name);
static bool scope_is_declared(Token *name);
static int scope_resolve_local(Token *name);
static int scope_resolve_upvalue(Token *name);
static void scope_mark_initialized();
static bool scope_identifiers_equal(Token *a, Token *b);
// Compiler
static Chunk *current_chunk();
static bool compiler_is_script();
static bool compiler_is_init();
static uint8_t compiler_make_constant(Value value);
static void compile_function(FunctionType type);
static Function *compile(const char *source);
static void compiler_mark_roots();
// VM
static void vm_init();
static void vm_free();
static void vm_push(Value value);
static Value vm_pop();
static InterpretResult vm_interpret(const char *source);
static void vm_add_object(Object *object);
static void vm_add_internal_string(String *string);
static String *vm_get_internal_string(const char *chars, int length,
uint32_t hash);
static void vm_define_native(const char *name, NativeFn function);
// GC
static void gc_init();
static void gc();
// Native functions
static Value native_clock(int arg_count, Value *args);
//=======================================================================//
// Array
//=======================================================================//
static inline int array_grow_capacity(int capacity) {
return capacity < 8 ? 8 : 2 * capacity;
}
//=======================================================================//
// Object
//=======================================================================//
static Object *object_allocate(size_t size, ObjectType type) {
Object *object = (Object *)reallocate(NULL, 0, size);
object->type = type;
vm_add_object(object);
#ifdef DEBUG_LOG_GC
printf("%p allocate %ld for %d\n", (void *)object, size, type);
#endif
return object;
}
static void object_free(Object *object) {
#ifdef DEBUG_LOG_GC
printf("%p free type %d\n", (void *)object, object->type);
#endif
switch (object->type) {
case OBJ_CLASS: {
Class *class = (Class *)object;
table_free(&class->methods);
FREE(Class, object);
break;
}
case OBJ_CLOSURE: {
Closure *closure = (Closure *)object;
ARRAY_FREE(Upvalue *, closure->upvalues, closure->upvalue_count);
FREE(Closure, object);
break;
}
case OBJ_FUNCTION: {
Function *function = (Function *)object;
chunk_free(&function->chunk);
FREE(Function, object);
break;
}
case OBJ_INSTANCE: {
Instance *instance = (Instance *)object;
table_free(&instance->fields);
FREE(Instance, object);
break;
}
case OBJ_METHOD:
FREE(Method, object);
break;
case OBJ_NATIVE:
FREE(Native, object);
break;
case OBJ_STRING: {
String *string = (String *)object;
ARRAY_FREE(char, (char *)string->chars, string->length + 1);
FREE(String, object);
break;
}
case OBJ_UPVALUE:
FREE(Upvalue, object);
break;
}
}
static inline bool object_is_type(Value value, ObjectType type) {
return IS_OBJECT(value) && AS_OBJECT(value)->type == type;
}
static void function_print(Function *function) {
if (function->name == NULL) {
printf("<script>");
return;
}
printf("<fn %s>", function->name->chars);
}
static void object_print(Value value) {
switch (AS_OBJECT(value)->type) {
case OBJ_CLASS:
printf("%s", AS_CLASS(value)->name->chars);
break;
case OBJ_CLOSURE:
function_print(AS_CLOSURE(value)->function);
break;
case OBJ_FUNCTION:
function_print(AS_FUNCTION(value));
break;
case OBJ_INSTANCE:
printf("%s instance", AS_INSTANCE(value)->class->name->chars);
break;
case OBJ_METHOD:
function_print(AS_METHOD(value)->method->function);
break;
case OBJ_NATIVE:
printf("<native fn>");
break;
case OBJ_STRING:
printf("%s", (AS_STRING(value))->chars);
break;
case OBJ_UPVALUE:
printf("upvalue");
break;
}
}
//=======================================================================//
// Object constructors
//=======================================================================//
static Class *class_new(String *name) {
Class *class = OBJECT_ALLOCATE(Class, OBJ_CLASS);
class->name = name;
table_init(&class->methods);
return class;
}
static Closure *closure_new(Function *function) {
Upvalue **upvalues = ALLOCATE(Upvalue *, function->upvalue_count);
for (int i = 0; i < function->upvalue_count; i++) {
upvalues[i] = NULL;
}
Closure *closure = OBJECT_ALLOCATE(Closure, OBJ_CLOSURE);
closure->function = function;
closure->upvalues = upvalues;
closure->upvalue_count = function->upvalue_count;
return closure;
}
static Function *function_new() {
Function *function = OBJECT_ALLOCATE(Function, OBJ_FUNCTION);
function->arity = 0;
function->upvalue_count = 0;
function->name = NULL;
chunk_init(&function->chunk);
return function;
}
static Instance *instance_new(Class *class) {
Instance *instance = OBJECT_ALLOCATE(Instance, OBJ_INSTANCE);
instance->class = class;
table_init(&instance->fields);
return instance;
}
static Method *method_new(Value receiver, Closure *method) {
Method *bound = OBJECT_ALLOCATE(Method, OBJ_METHOD);
bound->receiver = receiver;
bound->method = method;
return bound;
}
static Native *native_new(NativeFn function) {
Native *native = OBJECT_ALLOCATE(Native, OBJ_NATIVE);
native->function = function;
return native;
}
static Upvalue *upvalue_new(Value *slot) {
Upvalue *upvalue = OBJECT_ALLOCATE(Upvalue, OBJ_UPVALUE);
upvalue->closed = NIL;
upvalue->location = slot;
upvalue->next = NULL;
return upvalue;
}
//=======================================================================//
// String
//=======================================================================//
// FNV-1a
static uint32_t string_hash(const char *key, int length) {
uint32_t hash = 2166136261u;
for (int i = 0; i < length; i++) {
hash ^= key[i];
hash *= 16777619;
}
return hash;
}
static String *string_allocate(const char *chars, int length, uint32_t hash) {
String *str = OBJECT_ALLOCATE(String, OBJ_STRING);
str->length = length;
str->chars = chars;
str->hash = hash;
vm_add_internal_string(str);
return str;
}
static String *string_take(const char *chars, int length) {
uint32_t hash = string_hash(chars, length);
String *interned = vm_get_internal_string(chars, length, hash);
if (interned != NULL) {
ARRAY_FREE(char, (char *)chars, length + 1);
return interned;
}
return string_allocate(chars, length, hash);
}
static String *string_copy(const char *chars, int length) {
uint32_t hash = string_hash(chars, length);
String *interned = vm_get_internal_string(chars, length, hash);
if (interned != NULL) return interned;
char *heap_chars = ALLOCATE(char, length + 1);
memcpy(heap_chars, chars, length);
heap_chars[length] = 0;
return string_allocate(heap_chars, length, hash);
}
//=======================================================================//
// Value
//=======================================================================//
static bool value_equals(Value a, Value b) {
if (a.type != b.type) return false;
switch (a.type) {
case VAL_BOOL:
return a.as.boolean == b.as.boolean;
case VAL_NIL:
return true;
case VAL_NUMBER:
return a.as.number == b.as.number;
case VAL_OBJECT:
return a.as.object == b.as.object;
}
}
static void value_print(Value value) {
switch (value.type) {
case VAL_BOOL:
printf(value.as.boolean ? "true" : "false");
break;
case VAL_NIL:
printf("nil");
break;
case VAL_NUMBER:
printf("%g", value.as.number);
break;
case VAL_OBJECT:
object_print(value);
break;
}
}
static void value_mark(Value value) {
if (!IS_OBJECT(value)) return;
object_mark(AS_OBJECT(value));
}
//=======================================================================//
// Value arrays
//=======================================================================//
static void value_array_init(ValueArray *array) {
array->count = 0;
array->capacity = 0;
array->values = NULL;
}
static void value_array_free(ValueArray *array) {
ARRAY_FREE(uint8_t, array->values, array->capacity);
value_array_init(array);
}
static void value_array_write(ValueArray *array, Value value) {
if (array->capacity < array->count + 1) {
int old_capacity = array->capacity;
array->capacity = array_grow_capacity(old_capacity);
array->values =
ARRAY_GROW(array->values, Value, old_capacity, array->capacity);
}
array->values[array->count++] = value;
}
//=======================================================================//
// HashTable of Values
//=======================================================================//
struct Entry {
String *key;
Value value;
};
static void table_init(Table *table) {
table->count = 0;
table->capacity = 0;
table->entries = NULL;
}
static void table_free(Table *table) {
ARRAY_FREE(Entry, table->entries, table->capacity);
table_init(table);
}
static Entry *table_find_entry(Entry *entries, int capacity, String *key) {
uint32_t index = key->hash % capacity;
Entry *tombstone = NULL;
for (;;) {
Entry *entry = &entries[index];
if (entry->key == NULL) {
if (IS_NIL(entry->value)) {
return tombstone != NULL ? tombstone : entry;
} else {
// We found a tombstone
if (tombstone == NULL) tombstone = entry;
}
} else if (entry->key == key) {
return entry;
}
index = (index + 1) % capacity;
}
}
static void table_adjust_capacity(Table *table, int capacity) {
Entry *entries = ALLOCATE(Entry, capacity);
for (int i = 0; i < capacity; i++) {
entries[i].key = NULL;
entries[i].value = NIL;
}
table->count = 0;
for (int i = 0; i < table->capacity; i++) {
Entry *entry = &table->entries[i];
if (entry->key == NULL) continue;
Entry *dest = table_find_entry(entries, capacity, entry->key);
dest->key = entry->key;
dest->value = entry->value;
table->count++;
}
ARRAY_FREE(Entry, table->entries, table->capacity);
table->entries = entries;
table->capacity = capacity;
}
static bool table_get(Table *table, String *key, Value *value) {
if (table->count == 0) return false;
Entry *entry = table_find_entry(table->entries, table->capacity, key);
if (entry->key == NULL) return false;
*value = entry->value;
return true;
}
static bool table_set(Table *table, String *key, Value value) {
if (table->count + 1 > table->capacity * TABLE_MAX_LOAD) {
int capacity = array_grow_capacity(table->capacity);
table_adjust_capacity(table, capacity);
}
Entry *entry = table_find_entry(table->entries, table->capacity, key);
bool is_new_key = entry->key == NULL;
if (is_new_key && IS_NIL(entry->value)) table->count++;
entry->key = key;
entry->value = value;
return is_new_key;
}
static bool table_delete(Table *table, String *key) {
if (table->count == 0) return false;
Entry *entry = table_find_entry(table->entries, table->capacity, key);
if (entry->key == NULL) return false;
// Place a tombstone in the entry.
entry->key = NULL;
entry->value = BOOL(true);
return true;
}
static void table_add_all(Table *from, Table *to) {
for (int i = 0; i < from->capacity; i++) {
Entry *entry = &from->entries[i];
if (entry->key != NULL) {
table_set(to, entry->key, entry->value);
}
}
}
static String *table_find_string(Table *table, const char *chars, int length,
uint32_t hash) {
if (table->count == 0) return NULL;
uint32_t index = hash % table->capacity;
for (;;) {
Entry *entry = &table->entries[index];
if (entry->key == NULL && IS_NIL(entry->value)) {
return NULL;
} else if (entry->key->length == length && entry->key->hash == hash &&
strncmp(entry->key->chars, chars, length) == 0) {
return entry->key;
}
index = (index + 1) % table->capacity;
}
}
static void table_mark(Table *table) {
for (int i = 0; i < table->capacity; i++) {
Entry *entry = &table->entries[i];
object_mark((Object *)entry->key);
value_mark(entry->value);
}
}
//=======================================================================//
// Chunk of Instructions
//=======================================================================//
static void chunk_init(Chunk *chunk) {
chunk->count = 0;
chunk->capacity = 0;
chunk->code = NULL;
chunk->lines = NULL;
value_array_init(&chunk->constants);
}
static void chunk_free(Chunk *chunk) {
ARRAY_FREE(uint8_t, chunk->code, chunk->capacity);
ARRAY_FREE(int, chunk->lines, chunk->capacity);
value_array_free(&chunk->constants);
chunk_init(chunk);
}
static void chunk_write(Chunk *chunk, uint8_t byte, int line) {
if (chunk->capacity < chunk->count + 1) {
int old_capacity = chunk->capacity;
chunk->capacity = array_grow_capacity(old_capacity);
chunk->code =
ARRAY_GROW(chunk->code, uint8_t, old_capacity, chunk->capacity);
chunk->lines = ARRAY_GROW(chunk->lines, int, old_capacity, chunk->capacity);
}
chunk->code[chunk->count] = byte;
chunk->lines[chunk->count] = line;
chunk->count += 1;
}
static int chunk_add_constant(Chunk *chunk, Value value) {
vm_push(value);
value_array_write(&chunk->constants, value);
vm_pop();
assert(chunk->constants.count <= 256);
return chunk->constants.count - 1;
}
//=======================================================================//
// Disassembly
//=======================================================================//
static int disassemble_simple_instruction(const char *name, int offset) {
printf("%s\n", name);
return offset + 1;
}
static int disassemble_constant_instruction(const char *name, Chunk *chunk,
int offset) {
uint8_t constant = chunk->code[offset + 1];
printf("%-16s %4d '", name, constant);
value_print(chunk->constants.values[constant]);
printf("'\n");
return offset + 2;
}
static int disassemble_byte_instruction(const char *name, Chunk *chunk,
int offset) {
uint8_t slot = chunk->code[offset + 1];
printf("%-16s %4d\n", name, slot);
return offset + 2;
}
static int disassemble_jmp_instruction(const char *name, int sign, Chunk *chunk,
int offset) {
uint16_t jump = (uint16_t)(chunk->code[offset + 1] << 8);
jump |= chunk->code[offset + 2];
printf("%-16s %4d -> %d\n", name, offset, offset + 3 + sign * jump);
return offset + 3;
}
static int disassemble_invoke_instruction(const char *name, Chunk *chunk,
int offset) {
uint8_t constant = chunk->code[offset + 1];
uint8_t arg_count = chunk->code[offset + 2];
printf("%-16s (%d args) %4d '", name, arg_count, constant);
value_print(chunk->constants.values[constant]);
printf("'\n");
return offset + 3;
}
static int disassemble_instruction(Chunk *chunk, int offset) {
printf("%04d ", offset);
if (offset > 0 && chunk->lines[offset] == chunk->lines[offset - 1]) {
printf(" | ");
} else {
printf("%4d ", chunk->lines[offset]);
}
uint8_t instruction = chunk->code[offset];
#define CASE_BYTE(label) \
case label: \
return disassemble_byte_instruction(#label, chunk, offset)
#define CASE_CONST(label) \
case label: \
return disassemble_constant_instruction(#label, chunk, offset)
#define CASE_INVOKE(label) \
case label: \
return disassemble_invoke_instruction(#label, chunk, offset)
#define CASE_JMP(label, sign) \
case label: \
return disassemble_jmp_instruction(#label, sign, chunk, offset)
#define CASE_SIMPLE(label) \
case label: \
return disassemble_simple_instruction(#label, offset)
switch (instruction) {
// Literals
CASE_CONST(OP_CONST);
CASE_SIMPLE(OP_NIL);
CASE_SIMPLE(OP_TRUE);
CASE_SIMPLE(OP_FALSE);
// Getters/Setters
CASE_BYTE(OP_GET_LOCAL);
CASE_BYTE(OP_SET_LOCAL);
CASE_CONST(OP_GET_GLOBAL);
CASE_CONST(OP_SET_GLOBAL);
CASE_CONST(OP_GET_PROP);
CASE_CONST(OP_SET_PROP);
CASE_CONST(OP_GET_SUPER);
CASE_BYTE(OP_GET_UPVALUE);
CASE_BYTE(OP_SET_UPVALUE);
// Arithmetic operations
CASE_SIMPLE(OP_NEG);
CASE_SIMPLE(OP_ADD);
CASE_SIMPLE(OP_SUB);
CASE_SIMPLE(OP_MUL);
CASE_SIMPLE(OP_DIV);
// Comparisons
CASE_SIMPLE(OP_NOT);
CASE_SIMPLE(OP_EQUAL);
CASE_SIMPLE(OP_GREATER);