How to write ANTLR grammar translator to return a java class with methods?

javaseeker :

I am trying to write an ANTLR grammar that outputs a java method. i.e. I wrote grammar for the below formula:

expr("L") + expr("R")

I want my grammar translator to return a java class with below method after translation like below:

public class FormulaExecutor(){

    public Double formula1234(FormulaAPI apiReference) {
        return apiReference.evaluateResult("L") + apiReference.evaluateResult("R") ;
    }
}

i.e. translation of expr("L") should generate the line apiReference.evaluateResult("L") and expr("R")should generate apiReference.evaluateResult("R") and the output should be like a class with an executable method as above.

How to achieve this during translation? I have seen translator returning double value or string value, but not anything like translator returning a class itself with an executable method.

The idea is that this class that translator returns will be compiled to byte code to be used by the program which consumes it.

Extra information: The class FormulaAPI referred in the above code is like this. This class will be defined outside of grammar already.

public class FormulaAPI(){

     public Double evaluateResult(String input){
        Double d = <value obtained from DB based on input string>;
        return d;
     }
}
Maurice Perry :

It sounds like you want to use some kind of expression grammar (there are many examples online), and generate:

1) the beginning of class declaration:

public class FormulaExecutor{

    public Double formula1234(FormulaAPI apiReference) {
        return 

2) the translated expression

3) the end of the class declaration:

;
    }
}

The translated expression is identical to the input expression, except for expr(<subexpression>) that would be translated to apiReference.evaluateResult(<subexpression>).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=227817&siteId=1