Storing line number in ANTLR Parse Tree

一笑奈何 提交于 2019-12-13 05:31:37

问题


Is there any way of storing line numbers in the created parse tree, using ANTLR 4? I came across this article: http://puredanger.github.io/tech.puredanger.com/2007/02/01/recovering-line-and-column-numbers-in-your-antlr-ast/ ,which does it but i think it's for older ANTLR version, because

parser.setASTFactory(factory);

does not seem to be applicable for ANTLR 4. I am thinking of having something like

treenode.getLine()

, just like we can have

treenode.getChild()


回答1:


With Antlr4, you normally implement either a listener or a visitor.

Both give you a context where you find the location of the tokens.

For example (with a visitor), I want to keep the location of an assignment defined by a Uppercase identifier (UCASE_ID in my token definition).

The bit you're interested in is ...

ctx.UCASE_ID().getSymbol().getLine()

The visitor looks like ...

static class TypeAssignmentVisitor extends ASNBaseVisitor<TypeAssignment> {
    @Override
    public TypeAssignment visitTypeAssignment(TypeAssignmentContext ctx) {
        String reference = ctx.UCASE_ID().getText();
        int line = ctx.UCASE_ID().getSymbol().getLine();
        int column = ctx.UCASE_ID().getSymbol().getCharPositionInLine()+1;

        Type type = ctx.type().accept(new TypeVisitor());
        TypeAssignment typeAssignment = new TypeAssignment();
        typeAssignment.setReference(reference);
        typeAssignment.setReferenceToken(new Token(ctx.UCASE_ID().getSymbol().getLine(), ctx.UCASE_ID().getSymbol().getCharPositionInLine()+1));
        typeAssignment.setType(type);
        return typeAssignment;
    }
}

I was new to Antlr4 and found this useful to get started with listeners and visitors ... https://github.com/JakubDziworski/AntlrListenerVisitorComparison/



来源:https://stackoverflow.com/questions/49630314/storing-line-number-in-antlr-parse-tree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!