2.antlr4开发

2.antlr4开发

上一篇:1.ANTLR4 helloworld基础开发与IDEA插件使用

获取源码

antlr4.7.2

1.通过MyHelloVisitor实现HelloVisitor

package wang.xiaolei.lei;

import org.antlr.v4.runtime.tree.ErrorNode;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.RuleNode;
import org.antlr.v4.runtime.tree.TerminalNode;

/**
 * 作者: wangxiaolei
 * 时间: 2019/12/12
 * 微信公众号:从入门到精通
 * 微信:chinesedream2
 */

public class MyHelloVisitor implements HelloVisitor {
     
    @Override
    public Object visitR(HelloParser.RContext ctx) {
     
        return null;
    }

    @Override
    public Object visit(ParseTree tree) {
     
        return null;
    }

    @Override
    public Object visitChildren(RuleNode node) {
     
        return null;
    }

    @Override
    public Object visitTerminal(TerminalNode node) {
     
        return null;
    }

    @Override
    public Object visitErrorNode(ErrorNode node) {
     
        return null;
    }
}

2.编写main函数

package wang.xiaolei.lei;

import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;

/**
 * 作者: wangxiaolei
 * 时间: 2019/12/12
 * 微信公众号:从入门到精通
 * 微信:chinesedream2
 */

public class HelloMain {
     
    public static void main(String ...args) {
     

        CharStream input = CharStreams.fromString("hello\tworld");

        // 构造词法分析器
        HelloLexer lexer=new HelloLexer(input);

        CommonTokenStream tokens = new CommonTokenStream(lexer);

        // 实例化解析器
        HelloParser parser = new HelloParser(tokens);

        ParseTree tree = parser.r();

        MyHelloVisitor myHelloVisitor = new MyHelloVisitor();

        myHelloVisitor.visit(tree);

    }
}

运行 HelloMain
2.antlr4开发_第1张图片

3.如果改变输入如 hell\tworld就会检测出问题

2.antlr4开发_第2张图片
上一篇:1.ANTLR4 helloworld基础开发与IDEA插件使用

获取源码

你可能感兴趣的:(编译原理,ANTLR,ANLTR,ANLTR4,编译原理,解析器)