如何压平一个ParserRuleContext
将子树放入令牌数组中?这ParserRuleContext.getTokens(int ttype)
看起来不错。但什么是ttype
?是token类型吗?如果我想包含所有令牌类型,应使用什么值?
ParserRuleContext.getTokens(int ttype)
仅检索父节点的某些子节点:它不会递归地进入父树。
但是,您自己编写很容易:
/**
* Retrieves all Tokens from the {@code tree} in an in-order sequence.
*
* @param tree
* the parse tee to get all tokens from.
*
* @return all Tokens from the {@code tree} in an in-order sequence.
*/
public static List<Token> getFlatTokenList(ParseTree tree) {
List<Token> tokens = new ArrayList<Token>();
inOrderTraversal(tokens, tree);
return tokens;
}
/**
* Makes an in-order traversal over {@code parent} (recursively) collecting
* all Tokens of the terminal nodes it encounters.
*
* @param tokens
* the list of tokens.
* @param parent
* the current parent node to inspect for terminal nodes.
*/
private static void inOrderTraversal(List<Token> tokens, ParseTree parent) {
// Iterate over all child nodes of `parent`.
for (int i = 0; i < parent.getChildCount(); i++) {
// Get the i-th child node of `parent`.
ParseTree child = parent.getChild(i);
if (child instanceof TerminalNode) {
// We found a leaf/terminal, add its Token to our list.
TerminalNode node = (TerminalNode) child;
tokens.add(node.getSymbol());
}
else {
// No leaf/terminal node, recursively call this method.
inOrderTraversal(tokens, child);
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)