ANTLR4 将 ParserRuleContext 树展平为数组 [英] ANTLR4 Flattening a ParserRuleContext Tree into an Array

查看:25
本文介绍了ANTLR4 将 ParserRuleContext 树展平为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将带有子树的 ParserRuleContext 扁平化为一个标记数组?ParserRuleContext.getTokens(int ttype) 看起来不错.但什么是ttype?是令牌类型吗?如果我想包含所有令牌类型,应该使用什么值?

How to flatten a ParserRuleContext with subtrees into an array of tokens? The ParserRuleContext.getTokens(int ttype) looks good. but what is ttype? Is it token type? What value to use if I want to include all token types?

推荐答案

ParserRuleContext.getTokens(int ttype) 只检索父节点的某些子节点:它不会递归地进入父树.

ParserRuleContext.getTokens(int ttype) only retrieves certain child nodes of a parent: it does not recursively go into the parent-tree.

但是,编写自己很容易:

However, it is easy enough to write yourself:

/**
 * 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);
        }
    }
}

这篇关于ANTLR4 将 ParserRuleContext 树展平为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆