@@ -53,8 +53,17 @@ typedef struct
5353 bool is_immutable ;
5454} Local ;
5555
56+ typedef enum
57+ {
58+ TYPE_FUNCTION ,
59+ TYPE_SCRIPT ,
60+ } FunctionType ;
61+
5662typedef struct
5763{
64+ ObjFunction * function ;
65+ FunctionType type ;
66+
5867 Local locals [UINT8_COUNT ];
5968 int local_count ;
6069 int scope_depth ;
@@ -63,12 +72,12 @@ typedef struct
6372static bool immutable_globals [UINT8_MAX ];
6473
6574Parser parser ;
66- Compiler * current ;
75+ Compiler * current = NULL ;
6776Chunk * compiling_chunk ;
6877
6978static Chunk * current_chunk ()
7079{
71- return compiling_chunk ;
80+ return & current -> function -> chunk ;
7281}
7382
7483static inline void error_at (Token * token , const char * message )
@@ -201,20 +210,33 @@ static void patch_jump(int offset)
201210 current_chunk ()-> code [offset ] = (jump >> 8 ) & 0xff ;
202211 current_chunk ()-> code [offset + 1 ] = jump & 0xff ;
203212}
204- static void init_compiler (Compiler * compiler )
213+ static void init_compiler (Compiler * compiler , FunctionType type )
205214{
215+ compiler -> function = NULL ;
216+ compiler -> type = type ;
206217 compiler -> local_count = 0 ;
207218 compiler -> scope_depth = 0 ;
208219 current = compiler ;
220+
221+ Local * local = & current -> locals [current -> local_count ++ ];
222+ local -> depth = 0 ;
223+ local -> name .start = "" ;
224+ local -> name .length = 0 ;
209225}
210226
211- static void end_compiler ()
227+ static ObjFunction * end_compiler ()
212228{
213229 emit_return ();
230+ ObjFunction * function = current -> function ;
231+
214232#ifdef DEBUG_PRINT_CODE
215233 if (!parser .had_error )
216- disassemble_chunk (current_chunk (), "code" );
234+ disassemble_chunk (current_chunk (), function -> name != NULL
235+ ? function -> name -> chars
236+ : "<script>" );
217237#endif
238+
239+ return function ;
218240}
219241
220242static void begin_scope ()
@@ -615,7 +637,7 @@ static void expression_statement()
615637 emit_byte (OP_POP );
616638}
617639
618- static void for_satement ()
640+ static void for_statement ()
619641{
620642 begin_scope ();
621643 consume (TOKEN_LEFT_PAREN , "Expect '(' after 'for'" );
@@ -779,11 +801,11 @@ static inline void init_parser()
779801 parser .panic_mode = false;
780802}
781803
782- bool compile (const char * source , Chunk * chunk )
804+ ObjFunction * compile (const char * source , Chunk * chunk )
783805{
784806 init_scanner (source );
785807 Compiler compiler ;
786- init_compiler (& compiler );
808+ init_compiler (& compiler , TYPE_SCRIPT );
787809 compiling_chunk = chunk ;
788810 init_parser ();
789811
@@ -794,5 +816,6 @@ bool compile(const char* source, Chunk* chunk)
794816 }
795817
796818 end_compiler ();
797- return !parser .had_error ;
819+ ObjFunction * function = end_compiler ();
820+ return parser .had_error ? NULL : function ;
798821}
0 commit comments