@@ -115,8 +115,10 @@ static int resolveLocal(BytecodeGen* gen, const char* name) {
115115}
116116
117117static void addLocal (BytecodeGen * gen , const char * name ) {
118+ if (gen -> hadError ) return ;
118119 if (gen -> compiler -> localCount == 256 ) {
119120 fprintf (stderr , "Too many local variables.\n" );
121+ gen -> hadError = true;
120122 return ;
121123 }
122124 Local * local = & gen -> compiler -> locals [gen -> compiler -> localCount ++ ];
@@ -125,10 +127,12 @@ static void addLocal(BytecodeGen* gen, const char* name) {
125127}
126128
127129static void emitConstant (BytecodeGen * gen , Value value , int line ) {
130+ if (gen -> hadError ) return ;
128131 int constant = addConstant (gen -> chunk , value );
129132 if (constant > 255 ) {
130133 writeChunk (gen -> chunk , OP_CONSTANT , line );
131134 fprintf (stderr , "Too many constants.\n" );
135+ gen -> hadError = true;
132136 } else {
133137 writeChunk (gen -> chunk , OP_CONSTANT , line );
134138 writeChunk (gen -> chunk , (uint8_t )constant , line );
@@ -768,18 +772,19 @@ static void genStmt(BytecodeGen* gen, Stmt* stmt) {
768772 }
769773}
770774
771- void generateBytecode (StmtList * statements , Chunk * chunk ) {
775+ bool generateBytecode (StmtList * statements , Chunk * chunk ) {
772776 BytecodeGen gen ;
773777 Compiler compiler ;
774778
775779 gen .compiler = & compiler ;
776780 gen .chunk = chunk ;
781+ gen .hadError = false;
777782
778783 compiler .enclosing = NULL ;
779784 compiler .function = newFunction ();
780785 compiler .function -> chunk = * chunk ;
781786
782- compiler .type = COMP_SCRIPT ;
787+ compiler .type = COMP_SCRIPT ;
783788 compiler .localCount = 0 ;
784789 compiler .scopeDepth = 0 ;
785790 compiler .loop = NULL ;
@@ -790,9 +795,12 @@ void generateBytecode(StmtList* statements, Chunk* chunk) {
790795 if (statements ) {
791796 for (int i = 0 ; i < statements -> count ; i ++ ) {
792797 genStmt (& gen , statements -> items [i ]);
798+ if (gen .hadError ) break ;
793799 }
794800 }
795801
796802 writeChunk (gen .chunk , OP_NIL , 0 );
797803 writeChunk (gen .chunk , OP_RETURN , 0 );
804+
805+ return !gen .hadError ;
798806}
0 commit comments