简体   繁体   中英

antlr4 - parsing function invocations

I have the following rules:

functionInv
    : NAME paramInvList #functionInvStmt
    ;
paramInvList
    : BRO BRC
    | BRO expression (',' expression )* BRC
    ;

and an corresponding Ast class:

public class FunctionInvocationExpr implements Ast {
    private final String target;
    private final List<Ast> arguments;

    public FunctionInvocationExpr(String target, List<Ast> arguments) {
        this.target = target;
        this.arguments = arguments;
    }

    @Override
    public <T> T accept(AstVisitor<T> visitor) {
        return visitor.visitFunctionInvocationExpr(this);
    }
}

The question is, how do I go from one to the other. Googling did not help at all. Can someone point me in the right direction? I use the visitor code generation.

When you generate your lexer and parser classes, you need to add the parameter -visitor so that ANTLR will generate some default visitors for you:

java -jar antlr-4.8-complete.jar -visitor Test.g4

this will create a TestBaseVisitor<T> class for you:

public class TestBaseVisitor<T> extends AbstractParseTreeVisitor<T> implements TestVisitor<T> {

    @Override
    public T visitFunctionInvStmt(TestParser.FunctionInvStmtContext ctx) { return visitChildren(ctx); }

    @Override
    public T visitParamInvList(TestParser.ParamInvListContext ctx) { return visitChildren(ctx); }

    @Override
    public T visitExpression(TestParser.ExpressionContext ctx) { return visitChildren(ctx); }

    // ...
}

which you can extend and make it return your own Ast nodes:

class AstVisitorBuilder extends TestBaseVisitor<Ast> {

    @Override
    public Ast visitFunctionInvStmt(TestParser.FunctionInvStmtContext ctx) {

        final String functionName = ctx.NAME().getText();
        final List<Ast> arguments = new ArrayList<>();

        if (ctx.paramInvList().expression() != null) {
            for (TestParser.ExpressionContext expression : ctx.paramInvList().expression()) {
                arguments.add(this.visitExpression(expression));
            }
        }

        return new FunctionInvocationExpr(functionName, arguments);
    }

    @Override
    public Ast visitExpression(TestParser.ExpressionContext ctx) {
        return null; // TODO return your expression AST node here
    }

    // ...
}

Invoking this can be done as follows:

TestLexer lexer = new TestLexer(new ANTLRInputStream("your source code"));
TestParser parser = new TestParser(new CommonTokenStream(lexer));
Ast ast = new AstVisitorBuilder().visit(parser.functionInv());
// ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM