我正在使用ANTLR解析scala文件.
我在这里找到了scala langage的语法: https://github.com/antlr/grammars-v4/blob/master/scala/Scala.g4
感谢antlr4—maven—plugin,我从语法生成了ANTLR类.
<plugin>
<groupId>org.antlr</groupId>
<artifactId>antlr4-maven-plugin</artifactId>
<version>4.13.1</version>
<executions>
<execution>
<id>antlr-generate</id>
<phase>generate-sources</phase>
<goals>
<goal>antlr4</goal>
</goals>
</execution>
</executions>
<configuration>
<sourceDirectory>src/main/antlr4</sourceDirectory>
<outputDirectory>target/generated-sources/antlr4</outputDirectory>
<listener>true</listener>
<visitor>true</visitor>
</configuration>
</plugin>
我对运行时有依赖性:
<dependency>
<groupId>org.antlr</groupId>
<artifactId>antlr4-runtime</artifactId>
<version>4.13.1</version>
</dependency>
下面是我解析scala文件的代码:
public class Main {
public static void main(String[] args) throws IOException {
Path filePath = Paths.get(args[0]);
CharStream charStream = CharStreams.fromPath(filePath , StandardCharsets.UTF_8);
ScalaLexer lexer = new ScalaLexer(charStream);
CommonTokenStream tokens = new CommonTokenStream(lexer);
ScalaParser parser = new ScalaParser(tokens);
ParseTree tree = parser.compilationUnit();
ParseTreeWalker.DEFAULT.walk(new ScalaBaseListener(), tree);
}
}
我成功地使用了这个scala文件test. scala作为输入:
object replace extends RewriteRule {
def transform(node: Node): Seq[Node] = node match {
case <abc:name>{ value @ _* }</abc:name> => <abc:surname>{ value }</abc:surname>
case _ => node
}
}
然而,添加了override
个关键字的输入失败:
object replace extends RewriteRule {
override def transform(node: Node): Seq[Node] = node match {
case <abc:name>{ value @ _* }</abc:name> => <abc:surname>{ value }</abc:surname>
case _ => node
}
}
stderr说它发现了意想不到的字符,比如<abc:name>
中的:
.
line 3:13 extraneous input ':' expecting {'-', 'null', 'this', 'super', '(', '_', Id, BooleanLiteral, CharacterLiteral, SymbolLiteral, IntegerLiteral, StringLiteral, FloatingPointLiteral, Varid, NL}
line 3:19 extraneous input '{' expecting {'-', 'null', 'this', 'super', '(', '_', Id, BooleanLiteral, CharacterLiteral, SymbolLiteral, IntegerLiteral, StringLiteral, FloatingPointLiteral, Varid, NL}
line 3:27 mismatched input '@' expecting {'=>', 'if'}
line 3:30 extraneous input '*' expecting {'-', 'null', 'this', 'super', '(', '{', '}', 'type', 'val', '_', 'implicit', 'if', 'while', 'try', 'do', 'for', 'throw', 'return', '+', '~', '!', 'new', 'lazy', 'case', '@', 'var', 'override', 'abstract', 'final', 'sealed', 'private', 'protected', 'import', 'def', 'class', 'object', 'trait', Id, BooleanLiteral, CharacterLiteral, SymbolLiteral, IntegerLiteral, StringLiteral, FloatingPointLiteral}
scala文件是正确的,它是我想要解析的文件的简化版本,它可以编译.
我需要在语法中修正什么?