An easy question, on which I cannot find something useful in the API docs: is there a way to get the left and right sibling of a ParserRuleContext?
Say I have in my .g4:
identifiers : identifier (',' identifier)*;
When handling a IdentifierContext, I would like to get a reference to the left and the right IdentifierContext.
I've found a relevant getRightSibling() method here.
Here is my C# port:
/// <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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With