'ANTLR function to retrieve text from a single node in a parse tree
I want to retrieve text from a parse tree's node but when i use getText(), it retrieves all the text from that node's children. I have searched but i don't find any ANTLR function that can retrieve only the node's text or a function to delete a node's children (so that i can use getText() on that node once i have deleted his children). Any help is welcomed.
Solution 1:[1]
That would be because a “node” (and particularly, it’s text) includes it’s children. If you define it as the text that’s not part of a child, you’re left with just to tokens (leaf nodes) in that parser rule, and that’s probably a bit less than useful (some text with holes where other rules kick in).
Maybe you have a situation where something like this would be useful. If so, you might want to elaborate. We might, then propose something more specific.
To address your comment, here's the implementation of getText()
for RuleContext
public String getText() {
if (getChildCount() == 0) {
return "";
}
StringBuilder builder = new StringBuilder();
for (int i = 0; i < getChildCount(); i++) {
builder.append(getChild(i).getText());
}
return builder.toString();
}
So, technically, the text of a node is nothing but the concatenation of the texts of it's children. By that definition, there'd be no text of a parent that's not child text.
Perhaps the definition of children nodes you mean is "children nodes that are RuleNode
s" (as opposed to ErrorNode
s or TerminalNode
s). You could implement a getText()
that ignored ParserRuleContext
, but that would return a rather odd concatenation of tokens that could have occurred before, after, or between, your RuleNode
s.
I don't think there's any generalized solution to what you're asking for. You'll need to pull out the specific text you want for parent nodes context by context.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |