Skip to content

Commit 5916661

Browse files
committed
feat: synchronize after finding an error to find all errors at one compile not fixing bugs after each compile
1 parent 57dbc00 commit 5916661

4 files changed

Lines changed: 50 additions & 1 deletion

File tree

src/chunk.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff 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,

src/compiler.c

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff 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+
355362
static 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+
362398
static void declaration()
363399
{
364400
statement();
401+
402+
if (parser.panic_mode)
403+
synchronize();
365404
}
366405

367406
static void statement()
@@ -370,6 +409,10 @@ static void statement()
370409
{
371410
print_statement();
372411
}
412+
else
413+
{
414+
expression_statement();
415+
}
373416
}
374417

375418
static inline void init_parser()

src/debug.c

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff 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:

src/vm.c

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff 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();

0 commit comments

Comments
 (0)