File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -38,6 +38,7 @@ typedef enum
3838 OP_CLOSE_UPVALUE ,
3939 OP_RETURN ,
4040 OP_CLASS ,
41+ OP_METHOD ,
4142} OpCode ;
4243
4344typedef struct
Original file line number Diff line number Diff 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+ }
767777static 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
780797static void fun_declaration ()
Original file line number Diff line number Diff 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 :
Original file line number Diff line number Diff 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
Original file line number Diff line number Diff line change @@ -91,6 +91,7 @@ typedef struct ObjClass
9191{
9292 Obj obj ;
9393 ObjString * name ;
94+ Table methods ;
9495} ObjClass ;
9596
9697typedef struct ObjInstance
You can’t perform that action at this time.
0 commit comments