I am using Antlr 4.7.2. I am trying to implement an "if else" statement:
Main problem is that optional rule is not being included on ParseTree, for this reason I think I am not getting the syntax's errors on that optional rule.
Ones of my current grammar definition are:
prog : stat+ ;
stat : func_declaration #rFuncDeclStat
| if_stat #rIfStat
| while_stat #rWhileStat
| for_stat #rForStat
| 'return' expr? STAT_END #rReturnStat
| LET ID ('=' expr)? STAT_END #rVarDeclStat
| var_reference '=' expr STAT_END #rAssignStat
| print_stat #rPrintStat
| expr STAT_END #rFuncCallStat
;
block_stat : '{' stat* '}' ;
if_stat : if '(' expr ')' (stat | block_stat) else_stat?;
else_stat : ELSE (stat | block_stat) ;
Everything work good when and I write the code correct syntactically and run grammar using "org.antlr.v4.gui.TestRig":
if (2==2){
let a = 4;
}
else{
let b = 5; //var declaration
}
But when I wrote next code, "else_stat" rule is not included on the ParseTree result and Antlr4 doesn't report any syntactic error.
if (2==2){
let a = 4;
}
else{
let b = 5;
If I remove "?" from "else_stat" rule (making it mandatory), Antlr4 include "else_stat" at ParseTree and is able to identify the error and show the corresponding message: "Missing '}'".
Please, anybody could guide me in the right address? I need to know how to make Antlr4 show the syntactic error regardless it happens on optional rules or if I need to fix my grammar definition or something else.
Thanks.