Skip to content

Commit d76316c

Browse files
committed
Added preliminary error detection with line numbers
I override the syntax_error() function within the Parser class to print out Parse Errors with line numbers. I also use a boolean flag to report when errors are detected, so that we do not parse the AST which will have null pointers.
1 parent 0f05f31 commit d76316c

2 files changed

Lines changed: 17 additions & 5 deletions

File tree

‎MiniJavaCompiler.java‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,12 @@ public static void main(String[] args)
3030

3131
if(program != null)
3232
{
33-
//Visit the tree starting at root (program)
34-
Visitor v = new PrettyPrintVisitor();
35-
v.visit(program);
33+
if(parser.errorDetected == false)
34+
{
35+
//Visit the tree starting at root (program)
36+
Visitor v = new PrettyPrintVisitor();
37+
v.visit(program);
38+
}
3639
}
3740
else
3841
{

‎Parser.cup‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,12 @@ import visitor.*;
1111
/* Preliminaries to use the scanner. */
1212
scan with {: return lexer.next_token(); :};
1313
parser code {: Lexer lexer;
14-
public Parser(Lexer lex) { super(lex); lexer = lex; } :};
14+
boolean errorDetected;
15+
public Parser(Lexer lex) { super(lex); lexer = lex; errorDetected = false; }
16+
public void syntax_error(Symbol cur_token) {
17+
errorDetected = true;
18+
System.err.println("Parse error at line " + cur_token.left + ", column " + cur_token.right); }
19+
:};
1520

1621
/* Terminals */
1722
terminal PERIOD, COMMA, SEMICOLON, LEFTCURLY, RIGHTCURLY, LEFTPAREN, RIGHTPAREN, LEFTBRACKET, RIGHTBRACKET;
@@ -173,7 +178,11 @@ statement ::= LEFTCURLY statementChain:sc RIGHTCURLY
173178
{: RESULT = new Assign(id, e1); :}
174179
|
175180
identifier:id LEFTBRACKET expression:e1 RIGHTBRACKET ASSIGNMENT expression:e2 SEMICOLON
176-
{: RESULT = new ArrayAssign(id, e1, e2); :};
181+
{: RESULT = new ArrayAssign(id, e1, e2); :}
182+
|
183+
error SEMICOLON:s
184+
{: :}
185+
;
177186

178187
statementChain ::= statement:stmt statementChain:sc
179188
{: if(sc == null)

0 commit comments

Comments
 (0)