-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathobject.c
94 lines (76 loc) · 2.31 KB
/
object.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
//
// Created by Fabian Simon on 03.10.23.
//
#include <stdio.h>
#include <string.h>
#include "memory.h"
#include "object.h"
#include "value.h"
#include "vm.h"
#include "table.h"
#define ALLOCATE_OBJ(type, object_type) \
(type*)allocate_object(sizeof(type), object_type)
static Obj* allocate_object(size_t size, ObjType type) {
Obj* object = (Obj*) reallocate(NULL, 0, size);
object->type = type;
object->next = vm.objects;
vm.objects = object;
return object;
}
ObjFunction* new_function() {
ObjFunction* function = ALLOCATE_OBJ(ObjFunction, OBJ_FUNCTION);
function->arity = 0;
function->name = NULL;
init_chunk(&function->chunk);
return function;
}
static ObjString* allocate_string(char* chars, int length, uint32_t hash) {
ObjString* string = ALLOCATE_OBJ(ObjString, OBJ_STRING);
string->length = length;
string->chars = chars;
string->hash = hash;
table_set(&vm.strings, string, NIL_VAL);
return string;
}
static uint32_t hash_string(const char* key, int length) {
uint32_t hash = 2166136261u;
for (int i = 0; i < length; i++) {
hash ^= (uint8_t) key[i];
hash *= 16777619;
}
return hash;
}
ObjString* take_string(const char* chars, int length) {
uint32_t hash = hash_string(chars, length);
ObjString* interned = table_find_string(&vm.strings, chars, length, hash);
if (interned != NULL) {
FREE_ARRAY(char, chars, length+1);
return interned;
}
return allocate_string(chars, length, hash);
}
ObjString* copy_string(const char* chars, int length) {
uint32_t hash = hash_string(chars, length);
ObjString* interned = table_find_string(&vm.strings, 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 allocate_string(heap_chars, length, hash);
}
static void print_function(ObjFunction* function) {
if (function->name == NULL) {
printf("<script>");
return;
}
printf("<fn %s", function->name->chars);
}
void print_object(Value val) {
switch (OBJ_TYPE(val)) {
case OBJ_FUNCTION:
print_function(AS_FUNCTION(val));
case OBJ_STRING:
printf("%s", AS_CSTRING(val));
break;
}
}