Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

antlr4 - get left and right sibling of rule context

Tags:

java

antlr

antlr4

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.


1 Answers

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;
    }
like image 122
Crulex Avatar answered Dec 02 '25 16:12

Crulex