java-在ANTLR中BaseListner的方法和词法规则的关系0.5.0

java-在ANTLR中BaseListner的方法和词法规则的关系0.5.0

环境介绍

  1. java.g4
  2. idea
  3. windows10

词法规则与类方法的对应关系

随便找一个词法规则,如ClassOrInterfaceModifier,参考java.g4文件定义如下

java 复制代码
classOrInterfaceModifier
    :   annotation       // class or interface
    |   (   'public'     // class or interface
        |   'protected'  // class or interface
        |   'private'    // class or interface
        |   'static'     // class or interface
        |   'abstract'   // class or interface
        |   'final'      // class only -- does not apply to interfaces
        |   'strictfp'   // class or interface
        )
    ;

在BaseListner生成后,就会生产对应的两个方法一个enter,一个是exit如下

java 复制代码
	/**
	 * {@inheritDoc}
	 *
	 * <p>The default implementation does nothing.</p>
	 */
	@Override public void enterClassOrInterfaceModifier(JavaParser.ClassOrInterfaceModifierContext ctx) { }
	/**
	 * {@inheritDoc}
	 *
	 * <p>The default implementation does nothing.</p>
	 */
	@Override public void exitClassOrInterfaceModifier(JavaParser.ClassOrInterfaceModifierContext ctx) { }

ClassOrInterfaceModifierContext与词法对应关系

ClassOrInterfaceModifierContext在BaseListener中缩写为ctx,这个ctx就表示的整个的词法规则,因此我们可以通过如下方法访问具体的规则:

  1. 以如下类名public static class myVisitor extends HelloBaseVisitor中的public和static为例,遍历public static时会两次触发listener

  2. 访问ctx.PUBLIC(): 获取当前是否是public,如果是static就返回public,不是public,就会返回为null

  3. 访问ctx.STATIC(): 获取当前是否是static,如果是static就返回static,不是static,就会返回为null

  4. 也可以使用ctx.annotation()去访问规则的另外一个备选分支

参考

java.g4文件获取以及BaseListner的生成可以参考

https://blog.csdn.net/m0_60688978/article/details/142166606

相关推荐
少废话h8 分钟前
Flume Kafka源与汇的topic覆盖问题解决
java·linux·kafka·flume
激动的兔子20 分钟前
Geoserver修行记-连接瀚高数据库显示java.sql.SQLException: org.postgresql.util.PSQLException
java·geoserver·瀚高数据库
一 乐41 分钟前
健康打卡|健康管理|基于java+vue+的学生健康打卡系统设计与实现(源码+数据库+文档)
android·java·数据库·vue.js·spring boot·微信小程序
ghie909044 分钟前
使用Java实现用户的注册和登录流程
java·数据库·oracle
止水编程 water_proof1 小时前
JavaScript基础
开发语言·javascript·ecmascript
颜如玉1 小时前
动态拼接SQL实践备忘📝
java·sql·mybatis
952361 小时前
数据结构-堆
java·数据结构·学习·算法
by__csdn1 小时前
Spring Boot 全面解析
java·数据库·spring boot·后端·spring
她说..1 小时前
基于Redis实现的分布式唯一编号生成工具类
java·数据库·redis·分布式·springboot
西岭千秋雪_1 小时前
Kafka客户端参数(一)
java·分布式·后端·kafka·linq