如何手动重写 Antlr4 解析树? [英] How to rewrite Antlr4 Parse Tree manually?

查看:54
本文介绍了如何手动重写 Antlr4 解析树?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个简单的 Xquery 处理器并使用 Antlr4 来解析语法.我使用访问者模式遍历解析树.现在,如果查询满足某个条件,我想重写一个查询.如果查询直接使用诸如join"之类的关键字并满足join"语法,则处理器现在可以处理查询.

I am working on a simple Xquery processor and using Antlr4 to parse the grammar. I use the visitor pattern to walk through the parse tree. Now I want to rewrite a query if the query meet the some condition. The processor now can process a query if the query directly use the keyword like "join" and meet the "join" grammar.

如果查询可以更改为连接查询,我想首先重写解析树,否则什么都不做.有没有办法手动操作解析树?喜欢添加规则上下文或构建新的解析树?

I want to first rewrite the parse tree if the query can be changed to a join query or do nothing if not. Is there a way to manually manipulate the parse tree? Like adding a rule context or construct a new parse tree?

推荐答案

对于 Antlr4,惯用的方法是用分析产品装饰树节点,而不是改变树结构.也就是说,可以使用一个或多个树遍历来识别和标记可以合并为连接和最终遍历以输出结果的节点.

For Antlr4, the idiomatic approach is to decorate tree nodes with analysis products, rather than mutating the tree structure. That is, one or more tree walks can be uses to identify and mark the nodes that could be merged into a join and a final walk to output the results.

当然,可以遍历解析树以生成单独的 AST,反过来,可以遍历并进一步修改结构.Antlr4 不支持这种 AST 的构建和遍历.

Of course, the parse-tree could be walked to generate a separate AST that, in turn, could be walked and further structurally modified. Antlr4 does not provide support for the building and walking of such an AST.

这篇关于如何手动重写 Antlr4 解析树?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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