[英]How to split an ANTLR grammar file into multiple ones
I have a large grammar file, and plan to split it into multiple ones, so that I can reuse some of those smaller files in another grammar file. 我有一个大的语法文件,并计划将其拆分为多个文件,以便可以在另一个语法文件中重用一些较小的文件。 I have tried doing it but failed. 我曾尝试这样做,但失败了。 Can you please tell if such a feature is available, and if so, please direct me towards an example. 您能告诉我是否有这样的功能吗?如果有,请指导我举一个例子。
If you want to split lexer and parser. 如果要拆分词法分析器和解析器。
Lexer: Lexer:
lexer grammar HelloLexer;
Hello : 'hello' ;
ID : [a-z]+ ; // match lower-case identifiers
WS : [ \t\r\n]+ -> skip ; // skip spaces, tabs, newlines
Parser: 解析器:
parser grammar HelloParser;
options { tokenVocab=HelloLexer; }
r : Hello ID ;
Remember to name the files HelloLexer.g4 and HelloParser.g4 记住将文件命名为HelloLexer.g4和HelloParser.g4
if you want to import a whole grammar, then you should use the import keyword 如果要导入整个语法,则应使用import关键字
grammar Hello;
import OtherGrammar;
Hello : 'hello' ;
ID : [a-z]+ ; // match lower-case identifiers
WS : [ \t\r\n]+ -> skip ; // skip spaces, tabs, newlines
r : Hello ID ;
You did not mention ANTLR version, so I am going to assume you are using the current one - 4.x. 您没有提到ANTLR版本,所以我假设您使用的是当前版本-4.x。 In ANTLR4 grammars can be imported with import
keyword. 在ANTLR4中,可以使用import
关键字导入语法。 Something like this: 像这样:
File: CommonLexerRules.g4 文件:CommonLexerRules.g4
lexer grammar CommonLexerRules;
ID : [a-zA-Z]+ ;
...
File: MyParser.g4 文件:MyParser.g4
grammar MyParser;
import CommonLexerRules; //includes all rules from lexer CommonLexerRules.g4
...
Rules in the “main grammar” override rules from imported grammars to implement inheritance. “主语法”中的规则会覆盖导入语法中的规则以实现继承。 See more details here: https://theantlrguy.atlassian.net/wiki/display/ANTLR4/Grammar+Structure#GrammarStructure-GrammarImports 在此处查看更多详细信息: https : //theantlrguy.atlassian.net/wiki/display/ANTLR4/Grammar+Structure#GrammarStructure-GrammarImports
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.