File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -10,6 +10,7 @@ typedef enum
1010 OP_NIL ,
1111 OP_TRUE ,
1212 OP_FALSE ,
13+ OP_POP ,
1314 OP_EQUAL ,
1415 OP_GREATER ,
1516 OP_LESS ,
Original file line number Diff line number Diff line change @@ -352,16 +352,55 @@ static void expression()
352352
353353// ---------------------- statements --------------------------
354354
355+ static void expression_statement ()
356+ {
357+ expression ();
358+ consume (TOKEN_SEMICOLON , "Expect ';' after expression." );
359+ emit_byte (OP_POP );
360+ }
361+
355362static void print_statement ()
356363{
357364 expression ();
358- consume (TOKEN_SEMICOLON , "Expect ';' at the end of print statement" );
365+ consume (TOKEN_SEMICOLON , "Expect ';' at the end of print statement. " );
359366 emit_byte (OP_PRINT );
360367}
361368
369+ static void synchronize ()
370+ {
371+ parser .panic_mode = false;
372+
373+ while (parser .current .type != TOKEN_EOF )
374+ {
375+ if (parser .previous .type == TOKEN_SEMICOLON )
376+ return ;
377+
378+ switch (parser .current .type )
379+ {
380+ case TOKEN_CLASS :
381+ case TOKEN_FUN :
382+ case TOKEN_VAR :
383+ case TOKEN_FOR :
384+ case TOKEN_IF :
385+ case TOKEN_WHILE :
386+ case TOKEN_PRINT :
387+ case TOKEN_RETURN :
388+ return ;
389+
390+ default :
391+ // do nothings
392+ ;
393+ }
394+ advance ();
395+ }
396+ }
397+
362398static void declaration ()
363399{
364400 statement ();
401+
402+ if (parser .panic_mode )
403+ synchronize ();
365404}
366405
367406static void statement ()
@@ -370,6 +409,10 @@ static void statement()
370409 {
371410 print_statement ();
372411 }
412+ else
413+ {
414+ expression_statement ();
415+ }
373416}
374417
375418static inline void init_parser ()
Original file line number Diff line number Diff line change @@ -42,6 +42,8 @@ int disassemble_instruction(Chunk* chunk, int offset)
4242 return simple_instruction ("OP_FALSE" , offset );
4343 case OP_TRUE :
4444 return simple_instruction ("OP_TRUE" , offset );
45+ case OP_POP :
46+ return simple_instruction ("OP_POP" , offset );
4547 case OP_EQUAL :
4648 return simple_instruction ("OP_EQUAL" , offset );
4749 case OP_GREATER :
Original file line number Diff line number Diff line change @@ -132,6 +132,9 @@ static InterpretResult run()
132132 case OP_FALSE :
133133 push (BOOL_VAL (false));
134134 break ;
135+ case OP_POP :
136+ pop ();
137+ break ;
135138 case OP_EQUAL :
136139 {
137140 Value v2 = pop ();
You can’t perform that action at this time.
0 commit comments