扩展 ANTLR3 AST
使用 ANTLR2,您可以在语法定义文件中定义类似的内容:
options
{
language = "CSharp";
namespace = "Extended.Tokens";
}
tokens {
TOKEN<AST=Extended.Tokens.TokenNode>;
}
然后,您可以创建一个类:
public class TokenNode: antlr.BaseAST
{
...
}
如果可以使用类似的内容,有什么想法吗(将类创建委托给 AST 工厂,而不是我手动进行树复制)?它不仅仅通过简单的语法定义从旧格式复制到新格式来工作,我尝试在他们的网站和示例中搜索类似的内容。有什么提示吗?
编辑
我不是想创建自定义令牌,而是创建自定义“节点解析器”。
为了“执行”一棵树,你有两个选择(据我所知):
- 创建一个“树访问者”并处理值,或者
- 通过“几乎复制”语法定义来创建一个树解析器。
在 v2 的情况下,我可以将树节点装饰为我想要的任何方法,然后在解析器运行后通过从根节点调用“执行”之类的方法来调用它们。
With ANTLR2, you could define something like this in grammar definition file:
options
{
language = "CSharp";
namespace = "Extended.Tokens";
}
tokens {
TOKEN<AST=Extended.Tokens.TokenNode>;
}
And then, you could create a class:
public class TokenNode: antlr.BaseAST
{
...
}
Any ideea if something like this can be used (delegate class creation to AST factory instead of me doing the tree replication manually)? It's not working just by simple grammar definition copy from old to new format, and I tried to search their site and samples for somthing similar. Any hints?
EDIT
I'm not trying to create custom tokens, but custom 'node parsers'.
In order to 'execute' a tree you have 2 choices (as far as I understood):
- create a 'tree visitor' and handle values, or
- create a tree parser by 'almost-duplicating' the grammar definition.
In v2 case, I could decorate the tree node to whateveer method I would have liked and then call them after the parser ran by just calling something like 'execute' from root node.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我对C#了解很少,但与Java目标应该没有太大区别。
您可以通过在
options { ... }
部分中设置ASTLabelType
来创建并让 ANTLR 使用自定义树(XTree
本例):Tg
然后,您创建一个扩展
CommonTree
的自定义类:demo/XTree.java
,当您创建
TParser
的实例时,您必须创建并设置一个习惯TreeAdaptor
用于创建XTree
的实例:demo/Main.java
运行演示:
将打印:
有关详细信息,请参阅:http://www.antlr.org/wiki/display/ANTLR3/Tree+construction
I know little C#, but there shouldn't be much difference with the Java target.
You can create - and let ANTLR use - a custom tree by setting the
ASTLabelType
in theoptions { ... }
section (anXTree
in this case):T.g
You then create a custom class which extends a
CommonTree
:demo/XTree.java
and when you create an instance of your
TParser
, you must create and set a customTreeAdaptor
which creates instances of yourXTree
:demo/Main.java
Running the demo:
will print:
For more info, see: http://www.antlr.org/wiki/display/ANTLR3/Tree+construction