-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobject.c
More file actions
97 lines (84 loc) · 2.56 KB
/
Copy pathobject.c
File metadata and controls
97 lines (84 loc) · 2.56 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
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "memory.h"
#include "object.h"
#include "table.h"
#include "value.h"
#include "vm.h"
static uint32_t hashString(const char *string, int length) {
uint32_t hash = 2166136261u;
for (int i = 0; i < length; i++) {
hash ^= (uint8_t)string[i];
hash *= 16777619;
}
return hash;
}
static Obj * allocateObject(size_t size, ObjType type) {
Obj *object = (Obj *)reallocate(NULL, 0, size);
object->type = type;
object->next = vm.objects;
vm.objects = object;
return object;
}
#define ALLOCATE_OBJ(type, objectType) \
(type *)allocateObject(sizeof(type), objectType)
static ObjString * allocateString(char *chars, int length, uint32_t hash) {
ObjString * string = ALLOCATE_OBJ(ObjString, OBJ_STRING);
string->length = length;
string->chars = chars;
string->hash = hash;
tableSet(&vm.strings, string, NIL_VAL);
return string;
}
ObjString * copyString(const char *chars, int length) {
uint32_t hash = hashString(chars, length);
ObjString *interned = tableFindString(&vm.strings, chars, length, hash);
if (interned != NULL) {
return interned;
}
char *heapChars = ALLOCATE(char, length + 1);
memcpy(heapChars, chars, length);
heapChars[length] = '\0';
return allocateString(heapChars, length, hash);
}
ObjString * takeString(char *chars, int length) {
uint32_t hash = hashString(chars, length);
ObjString *interned = tableFindString(&vm.strings, chars, length, hash);
if (interned != NULL) {
FREE_ARRAY(char, chars, length + 1);
return interned;
}
return allocateString(chars, length, hash);
}
ObjFunction * newFunction() {
ObjFunction *function = ALLOCATE_OBJ(ObjFunction, OBJ_FUNCTION);
function->arity = 0;
function->upvalueCount = 0;
function->name = NULL;
initChunk(&function->chunk);
return function;
}
ObjClosure * newClosure(ObjFunction *function) {
ObjUpvalue **upvalues = ALLOCATE(ObjUpvalue *, function->upvalueCount);
for (int i = 0; i < function->upvalueCount; ++i) {
upvalues[i] = NULL;
}
ObjClosure *closure = ALLOCATE_OBJ(ObjClosure, OBJ_CLOSURE);
closure->function = function;
closure->upvalues = upvalues;
closure->upvalueCount = function->upvalueCount;
return closure;
}
ObjNative *newNative(NativeFn function) {
ObjNative *native = ALLOCATE_OBJ(ObjNative, OBJ_NATIVE);
native->function = function;
return native;
}
ObjUpvalue * newUpvalue(Value *slot) {
ObjUpvalue *upvalue = ALLOCATE_OBJ(ObjUpvalue, OBJ_UPVALUE);
upvalue->location = slot;
upvalue->next = NULL;
upvalue->closed = NIL_VAL;
return upvalue;
}