根据这个问题,我通过HomeBrew:安装了ANTLR
brew install antlr
它安装在:上
/usr/local/Cellar/antlr/<version>/
并通过安装了Python运行时
pip3 install antlr4-python3-runtime
在这里,我运行
export CLASSPATH=".:/usr/local/Cellar/antlr/<version>/antlr-<version>-complete.jar:$CLASSPATH"
但是当我运行命令时
grun <grammarName> <inputFile>
我收到臭名昭著的错误消息:
无法加载<grammarName>作为lexer或解析器
如果你能帮我知道这个问题以及如何解决它,我将不胜感激。
p。S.这应该没关系,但你可以在这里看到我正在编写的代码。
此错误消息表明TestRig(grun
别名使用的(在类路径中找不到Parser(或Lexer(类。如果您已经将生成的Parser放在一个包中,您可能需要考虑包名称,但最重要的是生成的(和编译的(类在类路径中。
此外。。TestRig将grammarName
和startRule
作为参数,并期望您的输入来自stdin。
我克隆了你的回购,以便更仔细地研究你的问题。
grun为什么给你这个问题的直接问题是你在语法文件中指定了你的目标语言(看起来我需要收回关于它在你的语法中没有任何内容的评论(。通过在语法中指定python作为目标语言,您没有生成TestRig
类(由grun
别名使用(需要执行的*.java类。
我从语法中删除了目标语言选项,并能够针对您的示例输入运行grun命令。为了使其正确解析,我随意修改了语法中的几个内容:
- 删除了目标语言(通常最好在antlr命令行上指定目标语言,这样语法就可以保持语言无关性(如果你想使用TestRig/grun实用程序来测试东西,这也是至关重要的,因为你需要Java目标(
- 将
SectionName
lexer规则更改为section
解析器规则(带有标记的替代项。使用像'Body ' Integer
这样的lexer规则将为您提供一个同时包含body关键字和整数的令牌,然后您必须稍后将其拆开(它还强制"body"和整数之间只有一个空格( - 将
NewLine
令牌设置为-> skip
(这对我来说有点假设,但不跳过NewLine
将需要修改更多的解析规则,以指定所有NewLine
都是有效令牌的位置。( - 删除了
StatementEnd
lexer规则,因为Iskip
已删除NewLine
令牌 - 将
Integer
和Float
的内容重写为两个不同的令牌,以便我可以在section
解析器规则中使用Integer
令牌 - 还有一些小的调整,只是为了让这个骨架处理您的样例输入
我使用的结果语法是:
grammar ElmerSolver;
// Parser Rules
// eostmt: ';' | CR;
statement: ';';
statement_list: statement*;
sections: section+ EOF;
// section: SectionName /* statement_list */ End;
// Lexer Rules
fragment DIGIT: [0-9];
Integer: DIGIT+;
Float:
[+-]? (DIGIT+ ([.]DIGIT*)? | [.]DIGIT+) ([Ee][+-]? DIGIT+)?;
section:
'Header' statement_list End # headerSection
| 'Simulation' statement_list End # simulatorSection
| 'Constants' statement_list End # constantsSection
| 'Body ' Integer statement_list End # bodySection
| 'Material ' Integer statement_list End # materialSection
| 'Body Force ' Integer statement_list End # bodyForceSection
| 'Equation ' Integer statement_list End # equationSection
| 'Solver ' Integer statement_list End # solverSection
| 'Boundary Condition ' Integer statement_list End # boundaryConditionSection
| 'Initial Condition ' Integer statement_list End # initialConditionSection
| 'Component' Integer statement_list End # componentSection;
End: 'End';
// statementEnd: ';' NewLine*;
NewLine: ('r'? 'n' | 'n' | 'r') -> skip;
LineJoining:
'\' WhiteSpace? ('r'? 'n' | 'r' | 'f') -> skip;
WhiteSpace: [ trn]+ -> skip;
LineComment: '#' ~( 'r' | 'n')* -> skip;
有了这些变化,我运行了
➜ antlr4 ElmerSolver.g4
javac *.java
grun ElmerSolver sections -tree < examples/ex001.sif
并得到输出:
(sections (section Simulation statement_list End) (section Equation 1 statement_list End) <EOF>)