I'm trying to implement arrays in antlr4 and I'm lost as to how I can get the multiple elements of the array when it is initialized like so:
int array[] = {1, 2};
I was thinking of placing them in a HashMap like this, the key being the index:
public Map<Integer, Value> array_memory = new HashMap<Integer, Value>();
Below is the grammar I'm following:
grammar GaleugParserNew;
/*
* PARSER RULES
*/
declare_var
: INTEGER ID '[' (INT)? ']' (ASSIGN '{' array_init '}')? SCOL
;
array_init
: INT ',' array_init
| INT
;
/*
* LEXER RULES
*/
SCOL : ';';
ASSIGN : '=';
INTEGER : 'int';
INT : [0-9]+;
I have a variable that would count how many times declare_var has visited array_init for the index. But I don't know how to visit array_init with multiple elements.
This is my declare_var visitor:
@Override
public Value visitDeclareArray(GaleugParserNewParser.DeclareArrayContext ctx){
String id = ctx.ID().getText(); //gets array name
String size = ctx.INT().getText(); //get string version of array size
int x = Integer.parseInt(size); //convert size(String) to int
Value elem = this.visit(ctx.array_init());
return Value.VOID;
}
And this is my array_init visitor:
@Override
public Value visitArray_init(GaleugParserNewParser.Array_initContext ctx){
index += 1;
return new Value(Double.valueOf(ctx.getText()));
}
If you have any suggestions as to how I can visit array_init in reference to the number of variables I'd like to hear them. Thank you!
Why? A
List<Value>
would do as well, right? No need to keep track of the index yourself.You're making thinks more complicated by recursively calling the
array_init
rule:I would do it like this instead:
You can then do something like this:
And if you run this
Main
class, the following will be printed to your console:EDIT
Easy as 1-2-3, define you grammar like this:
and then do something like this:
which will print: