简体   繁体   English

树评估

[英]Tree evaluation

I've build a grammar in antlr4 for json-like language. 我已经在antlr4中为类似json的语言构建了语法。

Gramar file: https://github.com/antlr/grammars-v4/tree/master/json 语法文件: https : //github.com/antlr/grammars-v4/tree/master/json

How would I traverse the tree with Visit function? 如何使用“访问”功能遍历树? So far I have code bellow, which outputs stream of tokens, but I would have to parse it again with regex rules, to get members and values. 到目前为止,我有下面的代码波纹管,它输出令牌流,但是我将不得不使用正则表达式规则再次对其进行解析,以获取成员和值。

public void Visit(IParseTree tree)
    {
        for (int i = 0; i < tree.ChildCount; i++)
        {
            if (tree.GetChild(i).ChildCount > 0)
            {
                Visit(tree.GetChild(i));

            }
            else
            {
                Console.WriteLine(tree.GetChild(i).ToString());
            }
        }
    }

I get tree with: 我得到树与:

        GramatikaLexer lexer = new GramatikaLexer(inputStream);
        CommonTokenStream commonTokenStream = new CommonTokenStream(lexer);
        GramatikaParser parser = new GramatikaParser(commonTokenStream);

        IParseTree tree = parser.start(); // start is entry point in .g4 file

There should be a GramatikaParserBaseVisitor<T> somewhere around which can be used as a base class. 应该有一个GramatikaParserBaseVisitor<T>可以用作基类。

You can then override the virtual functions like (here: T == object ) object VisitStart(StartContext context) , whose argument has a richer interface than IParseTree and you can access the children by name and they are also typed , ie of type <Child>Context instead of merely IParseTree . 然后,您可以覆盖虚拟函数,例如(这里: T == objectobject VisitStart(StartContext context) ,其参数具有比IParseTree更丰富的接口,并且您可以按名称访问子级,并且也可以输入子级 ,即类型<Child>Context而不只是IParseTree

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM