在 ANTLR 解析树中存储行号 [英] Storing line number in ANTLR Parse Tree
问题描述
有没有办法使用 ANTLR 4 在创建的解析树中存储行号?我遇到了 这篇 文章,它确实做到了,但我认为它适用于较旧的 ANTLR 版本,因为
Is there any way of storing line numbers in the created parse tree, using ANTLR 4? I came across this article, which does it but I think it's for older ANTLR version, because
parser.setASTFactory(工厂);
parser.setASTFactory(factory);
它似乎不适用于 ANTLR 4.我正在考虑像
It does not seem to be applicable to ANTLR 4. I am thinking of having something like
treenode.getLine()
treenode.getLine()
,就像我们可以有
treenode.getChild()
treenode.getChild()
推荐答案
使用 Antlr4,您通常可以实现侦听器或访问者.
With Antlr4, you normally implement either a listener or a visitor.
两者都为您提供了一个上下文,您可以在其中找到令牌的位置.
Both give you a context where you find the location of the tokens.
例如(对于访问者),我想保留由大写标识符(我的令牌定义中的 UCASE_ID)定义的分配位置.
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).
您感兴趣的是...
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;
}
}
我是 Antlr4 的新手,发现这对开始使用听众和访问者很有用...https://github.com/JakubDziworski/AntlrListenerVisitorComparison/
I was new to Antlr4 and found this useful to get started with listeners and visitors ... https://github.com/JakubDziworski/AntlrListenerVisitorComparison/
这篇关于在 ANTLR 解析树中存储行号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!