简体   繁体   English

从ANTLR语法创建树

[英]Creating a Tree from an ANTLR Grammar

I have written an ANTLR Grammar file and now i need to generate an adjacency matrix telling me which rule in grammar is associated with which one. 我已经编写了ANTLR语法文件,现在我需要生成一个邻接矩阵,告诉我语法中的哪个规则与哪个规则相关。 for ex :- start : ('show' | 'give' | 'get') 'me' ('all')? 例如:-开始:(“显示” |“给定” |“获取”)“我”(“全部”)? phrase | 词组| 'I' 'would' 'like' ('all')? “我”,“想要”,“喜欢”(“全部”)? phrase | 词组| phrase; 短语;

phrase : constructPhrase (('and')? constructPhrase)* | 短语:constructPhrase((和)?constructPhrase)* | constructPhrase 'and' ('its' | 'their') constructPhrase | ConstructPhrase'和'('其'|'他们的') constructPhrase functionPhrase | ConstructPhrase功能 functionPhrase ; functionPhrase;

Here we have I would like associated with each other..so i need to read the grammar file and generate an adjacency matrix. 在这里,我们希望彼此关联。所以我需要阅读语法文件并生成一个邻接矩阵。

I have created a project on github https://github.com/julianthome/inmemantlr that takes the g4 grammar definition and a text file that contains the actual content to parse. 我在github https://github.com/julianthome/inmemantlr上创建了一个项目,该项目采用g4语法定义和一个文本文件,其中包含要解析的实际内容。 It will automatically generate an AST for you where the nodes do contain the parsing rules and the token associated with that rule. 它会自动为您生成一个AST,其中节点确实包含解析规则和与该规则关联的令牌。 It might be useful for your purpose. 这可能对您有用。

It is written in Java -- you could plug in any g4 file you like ... the parser generation and AST generation is done automatically. 它是用Java编写的-您可以插入任何您喜欢的g4文件...解析器生成和AST生成是自动完成的。 Code examples can be found in the test cases. 在测试案例中可以找到代码示例。

Best wishes and kind regards Julian 最好的祝愿和亲切的问候朱利安

Parsing an ANTLR grammar is not difficult. 解析ANTLR语法并不困难。 I have done this as part of my code completion implementation in MySQL Workbench . 在MySQL Workbench中,这是我的代码完成实现的一部分。

You need the ANTLR meta grammar and generate a parser from it. 您需要ANTLR元语法并从中生成一个解析器。 Then use that to load you own grammar into a structure you can use to generate the matrix from. 然后使用它将您自己的语法加载到可用于生成矩阵的结构中。

As a head start you could use the ANTLR grammar parser I have created , but that is for a C/C++ target, not Java. 首先,您可以使用我创建的ANTLR语法解析器 ,但这是针对C / C ++目标而不是Java。 So, you have to get the ANTLR3.g file from the ANTLR homepage and create your own parser from it. 因此,您必须从ANTLR主页获取ANTLR3.g文件,并从中创建自己的解析器。

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

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