在IDEA中安装使用Antlr

  1. 在Settings-Plugins中安装ANTLR v4 grammar plugin,注意这里的版本是当前最高的版本

装1.8.4版本,可以看到这里支持ANTLR 4.7.8

这里写图片描述

装1.8版本,可以看到这里支持ANTLR 4.5.1

这里写图片描述

装1.6版本,可以看到这里支持ANTLR 4.5这里我们装这个

这里写图片描述

IDEA插件地址http://plugins.jetbrains.com/plugin/7358-antlr-v4-grammar-plugin

  1. 新建一个Maven项目,在pom.xml文件中添加ANTLR4插件和运行库的依赖。注意一定要用最新版的,依赖,不知道最新版本号的可以自己google一下maven antlr4。

然后要添加依赖

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.lcc.jdk.source</groupId>
    <artifactId>JdkSource</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.antlr</groupId>
            <artifactId>antlr4-runtime</artifactId>
            <version>4.5.3</version>
        </dependency>

    </dependencies>



    <build>
        <plugins>
            <plugin>
                <groupId>org.antlr</groupId>
                <artifactId>antlr4-maven-plugin</artifactId>
                <version>4.3</version>
                <executions>
                    <execution>
                        <id>antlr</id>
                        <goals>
                            <goal>antlr4</goal>
                        </goals>
                        <phase>none</phase>
                    </execution>
                </executions>
                <configuration>
                    <outputDirectory>src/test/java</outputDirectory>
                    <listener>true</listener>
                    <treatWarningsAsErrors>true</treatWarningsAsErrors>
                </configuration>
            </plugin>
        </plugins>
    </build>

注意:plugin必须加上,不然会出错

新建一个Demo.g4文件

这里写图片描述

内容如下

grammar Demo;

//parser
prog:stat
;
stat:expr|NEWLINE
;

expr:multExpr(('+'|'-')multExpr)*
;
multExpr:atom(('*'|'/')atom)*
;
atom:'('expr')'
    |INT
    |ID
;

//lexer
ID:('a'..'z'|'A'..'Z')+;
INT:'0'..'9'+;
NEWLINE:'\r'?'\n';
WS:(' '|'\t'|'\n'|'\r')+{skip();};

在IDEA中配置文件,右击文件 -> Configure ANTLR…,如下图所示:

这里写图片描述

(注意要勾选generate parse tree visitor,后来的程序要用到)
1. 第一个是要生成的父路径。
2. 第二个是父路径下的out

配置完成后右键文件 -> Generate ANNTLR Recognizer,可以看到生成一堆文件

然后测试

package com.antlr;


import com.antlr.out.DemoLexer;
import com.antlr.out.DemoParser;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;


/**
 * @author lcc
 */
public class MyCalculator {

    public static void run(String expr) throws Exception{

        //对每一个输入的字符串,构造一个 ANTLRStringStream 流 in
        ANTLRInputStream in = new ANTLRInputStream(expr);

        //用 in 构造词法分析器 lexer,词法分析的作用是产生记号
        DemoLexer lexer = new DemoLexer(in);

        //用词法分析器 lexer 构造一个记号流 tokens
        CommonTokenStream tokens = new CommonTokenStream(lexer);

        //再使用 tokens 构造语法分析器 parser,至此已经完成词法分析和语法分析的准备工作
        DemoParser parser = new DemoParser(tokens);

        //最终调用语法分析器的规则 prog,完成对表达式的验证
        parser.prog();
    }

    public static void main(String[] args) throws Exception{

        String[] testStr={
                "2",
                "a+b+3",
                "(a-b)+3",
                "a+(b*3"
        };

        for (String s:testStr){
            System.out.println("Input expr:"+s);
            run(s);
        }
    }
}

运行

Input expr:2
ANTLR Tool version 4.7 used for code generation does not match the current runtime version 4.6Exception in thread "main" java.lang.ExceptionInInitializerError
    at com.antlr.MyCalculator.run(MyCalculator.java:21)
    at com.antlr.MyCalculator.main(MyCalculator.java:44)
Caused by: java.lang.UnsupportedOperationException: java.io.InvalidClassException: org.antlr.v4.runtime.atn.ATN; Could not deserialize ATN with UUID 59627784-3be5-417a-b9eb-8131a7286089 (expected aadb8d7e-aeef-4415-ad2b-8204d6cf042e or a legacy UUID).
    at org.antlr.v4.runtime.atn.ATNDeserializer.deserialize(ATNDeserializer.java:129)
    at com.antlr.out.DemoLexer.<clinit>(DemoLexer.java:133)
    ... 2 more
Caused by: java.io.InvalidClassException: org.antlr.v4.runtime.atn.ATN; Could not deserialize ATN with UUID 59627784-3be5-417a-b9eb-8131a7286089 (expected aadb8d7e-aeef-4415-ad2b-8204d6cf042e or a legacy UUID).
    ... 4 more

Process finished with exit code 1

版本是Idea插件 1.8.4 maven引入是4.6 说这里版本不对。
最后经过测试,原来是Configure ANTLR…的时候,使用的是4.7生成的,但是运行却是4.6

版本是Idea插件 1.8.4 maven引入是4.6 报错如下。

Input expr:2
ANTLR Tool version 4.5 used for code generation does not match the current runtime version 4.6ANTLR Tool version 4.5 used for code generation does not match the current runtime version 4.6Input expr:a+b+3
Input expr:(a-b)+3
Input expr:a+(b*3
line 1:6 missing ')' at '<EOF>'

最后经过测试,原来是Configure ANTLR…的时候,使用的是4.6生成的,但是运行却是4.5
最后修改maven如下

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.lcc.jdk.source</groupId>
    <artifactId>JdkSource</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>

        <!-- https://mvnrepository.com/artifact/org.eclipse.core/org.eclipse.core.runtime -->
        <dependency>
            <groupId>org.eclipse.core</groupId>
            <artifactId>org.eclipse.core.runtime</artifactId>
            <version>3.7.0</version>
        </dependency>



        <!-- https://mvnrepository.com/artifact/org.antlr/antlr4 -->
        <dependency>
            <groupId>org.antlr</groupId>
            <artifactId>antlr4</artifactId>
            <version>4.5.3</version>
        </dependency>

        <dependency>
            <groupId>org.antlr</groupId>
            <artifactId>antlr4-runtime</artifactId>
            <version>4.5.3</version>
        </dependency>


        <!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>25.0-jre</version>
        </dependency>




    </dependencies>



    <build>
        <plugins>
            <plugin>
                <groupId>org.antlr</groupId>
                <artifactId>antlr4-maven-plugin</artifactId>
                <version>4.5.3</version>
                <executions>
                    <execution>
                        <id>antlr</id>
                        <goals>
                            <goal>antlr4</goal>
                        </goals>
                        <phase>none</phase>
                    </execution>
                </executions>
                <configuration>
                    <outputDirectory>src/test/java</outputDirectory>
                    <listener>true</listener>
                    <treatWarningsAsErrors>true</treatWarningsAsErrors>
                </configuration>
            </plugin>
        </plugins>
    </build>


</project>

最终运行完美

Input expr:2
Input expr:a+b+3
Input expr:(a-b)+3
Input expr:a+(b*3
line 1:6 missing ')' at '<EOF>'

Process finished with exit code 0

猜你喜欢

转载自blog.csdn.net/qq_21383435/article/details/80814618