[英]antlr4 - get left and right sibling of rule context
一个简单的问题,我在 API 文档中找不到有用的东西:有没有办法获得ParserRuleContext
左右兄弟?
说我在我的.g4
:
identifiers : identifier (',' identifier)*;
处理IdentifierContext
,我想获得对左右IdentifierContext
的引用。
我发现一个有关getRightSibling()
方法在这里。
这是我的 C# 端口:
/// <summary>
/// Returns the right sibling of the parse tree node.
/// </summary>
/// <param name="context">A node.</param>
/// <returns>Right sibling of a node, or null if no sibling is found.</returns>
public static IParseTree GetRightSibling(this ParserRuleContext context)
{
int index = GetNodeIndex(context);
return index >= 0 && index < context.Parent.ChildCount - 1
? context.Parent.GetChild(index + 1)
: null;
}
/// <summary>
/// Returns the node's index with in its parent's children array.
/// </summary>
/// <param name="context">A child node.</param>
/// <returns>Node's index or -1 if node is null or doesn't have a parent.</returns>
public static int GetNodeIndex(this ParserRuleContext context)
{
RuleContext parent = context?.Parent;
if (parent == null)
return -1;
for (int i = 0; i < parent.ChildCount; i++)
{
if (parent.GetChild(i) == context)
return i;
}
return -1;
}
获取当前子节点的索引:
int indexOfCurrentChildNode = ctx.getParent().children.indexOf(ctx);
然后你可以通过以下方式获得它的右/左兄弟:
ctx.parent.getChild(indexOfCurrentChildNode +/- 1)
[...] 有没有办法获得
ParserRuleContext
左右兄弟?
不,唉,在 ANTLR4 的核心 API 中没有直接的方法可以做到这一点。
您可以使用 infomehdi 的答案,但是在(尝试)检索左节点或右节点时,必须防止索引出界异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.