Ghiloufi
Ghiloufi

Reputation: 321

How to get the declared variables ANTLR

I have the following parser rule

study: 'study' '(' ( assign* | ( assign (',' assign)*) ) ')' NEWLINE;
assign: ID '=' (INT  | DATA );
INT :   [0-9]+ ;
DATA    : '"' ID '"' | '"' INT '"';
ID  :   [a-zA-Z]+ ;

my problem now how I can retrieve the variables defined in the study in the entryStudy method

@Override
    public void enterStudy(StudyParser.StudyContext ctx) {
        // get the declared variables
       // study(hello = "hello",world = "world")
       // study(hello = "hello",world = "world",name = "name")
        System.out.println("enterStudy");
    }

Upvotes: 1

Views: 286

Answers (1)

vbezhenar
vbezhenar

Reputation: 12316

Add the following snippet to your grammar:

@members {
    public final java.util.List<java.util.Map.Entry<String, String>> parameters = new java.util.ArrayList<>();
}

Modify your assign rule:

assign: name=ID '=' value=(INT  | DATA ) {
    parameters.add(new java.util.AbstractMap.SimpleImmutableEntry($name.text, $value.text));
};

Now you can use StudyParser.parameters field to access required information:

StudyParser parser = ...;
parser.study();
System.out.println(parser.parameters);

Also please note that your grammar probably is slightly wrong, because it allows the following input: study(x=1y=2).

Upvotes: 1

Related Questions