javaantlrantlr4antlr3antlrworks

antlr return values as key-value


I want to parse the sentence "i am looking for a java developer from india". The output i need is language=java and place=india

I created a grammar file as follows.

grammar Job;

eval returns [String value]
    :    output=jobExp {System.out.println($output.text); $value = $output.text;}
    ;


jobExp returns [String value]
    :    ind=indro whitespace var1=language ' developer from ' var2=place 
                            {
                            System.out.println($var1.text);
                            System.out.println($var2.text);
                            $value = $var1.text+$var2.text; }
    ;

indro
    :
    'i am looking for a'
    |
    'i am searching for a'
    ;

language :
    'java' | 'python' | 'cpp'
    ;

place :
    'india' | 'america' | 'africa'
    ;

whitespace :
    (' '|'\t')+
    ;

inside jobExp i am getting the values for place and language. And I am just returning only those two variables. But in eval i am getting the whole sentence(i am looking for a java developer from india). What should i need to get the exact matching output in eval ? Is it possible to get the output as json or hashMap in antlr?

My java class for testing the grammar as follows:

import org.antlr.runtime.*;

public class JobTest {
    public static void main(String[] args) throws Exception {
        ANTLRStringStream in = new ANTLRStringStream("i am looking for a java developer from india" );
        JobLexer lexer = new JobLexer(in);
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        JobParser parser = new JobParser(tokens);
        System.out.println(parser.eval()); // print the value
    }
}

Solution

  • You can have a @header block in your grammar to add it to the generated parser file.

    grammar Job;
    
    @header {
        import java.util.HashMap;
    }
    

    You can further on your grammar file use the HashMap class just as you're using String.

    There's also the @members block to define private fields of the parser. You can check an example using both blocks to define an expression evaluator in this tutorial.