问题描述
是否可以使用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
它似乎不适用于ANTLR 4.我正在考虑使用
It does not seem to be applicable to ANTLR 4.I am thinking of having something like
,就像我们可以拥有的
推荐答案
使用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()
访客看起来像...
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解析树中存储行号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!