Skip to content

Commit 377a71a

Browse files
committed
feat: implement method declarations
1 parent f5e0deb commit 377a71a

5 files changed

Lines changed: 24 additions & 1 deletion

File tree

src/chunk.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ typedef enum
3838
OP_CLOSE_UPVALUE,
3939
OP_RETURN,
4040
OP_CLASS,
41+
OP_METHOD,
4142
} OpCode;
4243

4344
typedef struct

src/compiler.c

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -764,17 +764,34 @@ static void function(FunctionType type)
764764
}
765765
}
766766

767+
static void method()
768+
{
769+
consume(TOKEN_IDENTIFIER, "Expect method name.");
770+
u8 constant = identifier_constant(&parser.previous);
771+
772+
FunctionType type = TYPE_FUNCTION;
773+
function(type);
774+
775+
emit_bytes(OP_METHOD, constant);
776+
}
767777
static void class_declaration()
768778
{
769779
consume(TOKEN_IDENTIFIER, "Expect class name.");
770-
u8 name_constant = identifier_constant(&parser.previous);
780+
Token class_name = parser.previous;
781+
u8 name_constant = identifier_constant(&parser.previous);
771782
declare_variable(true);
772783

773784
emit_bytes(OP_CLASS, name_constant);
774785
define_variable(name_constant, true);
775786

787+
named_variable(class_name, false);
776788
consume(TOKEN_LEFT_BRACE, "Expected '{' after class name");
789+
while (!check(TOKEN_RIGHT_BRACE) && !check(TOKEN_EOF))
790+
{
791+
method();
792+
}
777793
consume(TOKEN_RIGHT_BRACE, "Expected '}' after class body");
794+
emit_byte(OP_POP);
778795
}
779796

780797
static void fun_declaration()

src/memory.c

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,7 @@ static void blacken_object(Obj* object)
9595
case OBJ_CLASS:
9696
ObjClass* klass = (ObjClass*)object;
9797
mark_object((Obj*)klass->name);
98+
mark_table(&klass->methods);
9899
break;
99100
case OBJ_CLOSURE:
100101
ObjClosure* closure = (ObjClosure*)object;
@@ -133,6 +134,8 @@ static void free_object(Obj* object)
133134
switch (object->type)
134135
{
135136
case OBJ_CLASS:
137+
ObjClass* klass = (ObjClass*)object;
138+
free_table(&klass->methods);
136139
FREE(ObjClass, object);
137140
break;
138141
case OBJ_CLOSURE:

src/object.c

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ ObjClass* new_class(ObjString* name)
3333
{
3434
ObjClass* klass = ALLOCATE_OBJ(ObjClass, OBJ_CLASS);
3535
klass->name = name;
36+
init_table(&klass->methods);
3637
return klass;
3738
}
3839

src/object.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,7 @@ typedef struct ObjClass
9191
{
9292
Obj obj;
9393
ObjString* name;
94+
Table methods;
9495
} ObjClass;
9596

9697
typedef struct ObjInstance

0 commit comments

Comments
 (0)