0
votes

I am writing a simple "language" in ANTLR4/JavaScript which can associate numbers to variables and print them. This works fine but after extending the print statement to take one or many variables I don't figure out how to get the count of them. (I am using a visitor, not listener, but am interested for both.)

Grammar:

print   : 'print' ID (',' ID)* ';' ;

How do I find out how many ID tokens there are?

Currently I hacked something together as follows:

visitPrint( ctx ) {
    let i = 0;
    let c = undefined;

    while( (c = ctx.ID(i)) ) {
        let val = ctx.ID(i++).getText();
        print( this.variables[val] );
    } 
}

Shouldn't there be a better way to do this, like some count() method?

Thanks for your response!

2

2 Answers

0
votes

If you create an id parser rule:

id
 : ID
 ;

and then use this id rule in all other parser rules instead of the ID token, then you can override the visitId function:

visitId(ctx) {
    // Check ctx.ID() here
}
0
votes

In your visitPrint method you get a PrintContext with a member ID(). This returns an array and you can simply use context.ID().length to get the ID count (note: no parameter).