88#include "memory.h"
99#include "object.h"
1010#include "table.h"
11+ #include "value.h"
1112#include "vm.h"
1213
13- #define ALLOCATE_OBJ (type , object_type ) \
14+ #define ALLOCATE_OBJ (type , object_type ) \
1415 (type*)allocate_object(sizeof(type), object_type)
1516
1617static Obj * allocate_object (size_t size , ObjType type )
@@ -28,6 +29,13 @@ static Obj* allocate_object(size_t size, ObjType type)
2829 return object ;
2930}
3031
32+ ObjClass * new_class (ObjString * name )
33+ {
34+ ObjClass * klass = ALLOCATE_OBJ (ObjClass , OBJ_CLASS );
35+ klass -> name = name ;
36+ return klass ;
37+ }
38+
3139ObjClosure * new_closure (ObjFunction * function )
3240{
3341 ObjUpvalue * * upvalues = ALLOCATE (ObjUpvalue * , function -> upvalue_count );
@@ -54,6 +62,14 @@ ObjFunction* new_function()
5462 return function ;
5563}
5664
65+ ObjInstance * new_instance (ObjClass * klass )
66+ {
67+ ObjInstance * instance = ALLOCATE_OBJ (ObjInstance , OBJ_INSTANCE );
68+ instance -> klass = klass ;
69+ init_table (& instance -> fields );
70+ return instance ;
71+ }
72+
5773ObjNative * new_native (NativeFn function )
5874{
5975 ObjNative * native = ALLOCATE_OBJ (ObjNative , OBJ_NATIVE );
@@ -68,7 +84,9 @@ static ObjString* allocate_string(char* chars, int length, u32 hash)
6884 string -> chars = chars ;
6985 string -> hash = hash ;
7086
87+ push (OBJ_VAL (string ));
7188 table_set (& vm .strings , string , NIL_VAL );
89+ pop ();
7290
7391 return string ;
7492}
@@ -138,6 +156,9 @@ void print_object(Value value)
138156
139157 switch (OBJ_TYPE (value ))
140158 {
159+ case OBJ_CLASS :
160+ printf ("%s" , AS_CLASS (value )-> name -> chars );
161+ break ;
141162 case OBJ_CLOSURE :
142163 {
143164 print_function (AS_CLOSURE (value )-> function );
@@ -148,6 +169,9 @@ void print_object(Value value)
148169 print_function (AS_FUNCTION (value ));
149170 break ;
150171 }
172+ case OBJ_INSTANCE :
173+ printf ("%s instance" , AS_INSTANCE (value )-> klass -> name -> chars );
174+ break ;
151175 case OBJ_NATIVE :
152176 {
153177 printf ("<native fn>" );
0 commit comments