There are several options:
1
Put your code inside the optional pathIndex:
rule : ^(PATH (id=IDENT{parts.add($id.text);})+ (pathIndex {} )? ) ;
2
Use the boolean flag to indicate the presence (or absence) of pathIndex :
rule @init{boolean flag = false;} : ^(PATH (id=IDENT{parts.add($id.text);})+ (pathIndex {flag = true;} )? ) { if(flag) {
EDIT
You can also make pathIndex match for nothing, so you don't need to make it optional inside path :
path[Scope sc] returns [Path p] : ^(PATH (id=IDENT{parts.add($id.text);})+ pathIndex) { // code } ; pathIndex returns [int index, String pathKey] @init { $index = -1; $pathKey = ""; } : ( /* some rules here */ )? ;
PS. Understand that the expression $pathIndex.pathKey != "" likely to evaluate to false . To compare the contents of strings in Java, use their equals(...) method:
!$pathIndex.pathKey.equals("")
or if $pathIndex.pathKey can be null , you can bypass NPE by doing:
!"".equals($pathIndex.pathKey)
source share