I have language with optional clauses (CL1
, CL2
).
grammar rule:
func : FUNC ID "(" (CL1 (ID | CL11 ID))? ")" (CL2 (ID | CL21 ID))? EOS ;
Because of optionality, I can't even use getChild(i).getText()
since "i" becomes non-deterministic.
While running code generation, I need to pick ID
after CL1
or CL2
.
If I do not have index of CL1
, I haven't got one for ID
, that follows it.
function fnFoo () meni attrBar ;
will have different token positions compared to
function fnFoo (arg pBar) meni attrBar ;
I used another approach of:
a. first detecting if token of this type exists ctx.getTokens(LangParser.CL1)[0]
or ctx.CL1()
b. picking its tokenIndex ctx.CL1().getSymbol().tokenIndex
c. advancing tokenIndex + 1
to next locate ID
But at this point, I realize, that this tokenIndex
is not the same index used in getChild(i)
API.
And there is no API to pick token text, using tokenIndex
to begin with.
How would one handle this situation?
ps: I use nodejs runtime with visitors, using ANTLR 4.8
How about something like this:
func
: FUNC ID '(' cl1? ')' cl2? EOS
;
cl1
: CL1 CL11? ID
;
cl2
: CL2 CL21? ID
;
In the funcContext
you can then do:
if (ctx.cl1()) {
// cl1 is present
// do something with ctx.cl1().CL1() and/or ctx.cl1().ID()
}