简体   繁体   English

如何在代码中生成ATLR G4解析器和词法分析器?

[英]How to generate antlr a g4 parser and lexer in code?

Is it possible to generate the antlr lexer and parser (from a given g4 grammar) directly within the code be it with the Antlr 4 runtime directly from the Python or C# code? 是否可以直接在Python或C#代码中使用Antlr 4运行时直接在代码内生成antlr lexer和解析器(从给定的g4语法)?

I think it would be much more convenient that calling the external tool everytime I need. 我认为每次需要时调用外部工具会更加方便。

[EDIT] [编辑]

It looks that I am looking for something similar to an in memory antlr feature with C# or Python: 看来我在寻找与C#或Python中的内存antlr功能类似的东西:

The code to parse ANTLR4 grammars and convert them to an ATN + generating the target files is written in Java. 解析ANTLR4语法并将其转换为ATN +生成目标文件的代码是用Java编写的。 This tool code is not translated to the target language (only the runtime is), so it is not possible to do the same job in other languages. 该工具代码未翻译为目标语言(仅运行时为翻译语言),因此不可能用其他语言执行相同的工作。 That inmenantlr project only uses the Java code from ANTLR4 in its own Java code to do the same thing, except for the need to run it as an external jar. 该inmenantlr项目仅将ANTLR4中的Java代码用于其自己的Java代码中,以执行相同的操作,只是需要将其作为外部jar运行。

The only way to make your wish possible would be to translate all the tool code also to the target language. 使您的愿望成为可能的唯一方法是将所有工具代码也翻译成目标语言。

However, depending on your needs there's a way to generate a parser interpreter for your target language. 但是,根据您的需要,有一种方法可以为目标语言生成解析器解释器。 I have done this in my vscode-antlr4 extension , where users can debug their ANTLR4 grammars. 我已经在我的vscode-antlr4扩展中完成了此操作,在该扩展中 ,用户可以调试其ANTLR4语法。 For that I added an export feature of the data required for the interpreter to ANTLR4 (it's available there since 4.7.2). 为此,我向ANTLR4添加了解释器所需数据的导出功能(自4.7.2起可用)。 This data can then be used to set up the lexer + parser interpreters (which are translated to the target language) to parse a file with that grammar. 然后,可以使用此数据来设置词法分析器+解析器解释器 (将翻译为目标语言)以解析具有该语法的文件。 These interpreters use the same prediction engine as the generated parsers, but do not keep parse contexts, variables etc. 这些解释器使用与生成的解析器相同的预测引擎,但不保留解析上下文,变量等。

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

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