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

相关推荐
麦兜*1 小时前
Spring Boot 企业级动态权限全栈深度解决方案,设计思路,代码分析
java·spring boot·后端·spring·spring cloud·性能优化·springcloud
序属秋秋秋1 小时前
《C++初阶之内存管理》【内存分布 + operator new/delete + 定位new】
开发语言·c++·笔记·学习
ruan1145142 小时前
MySQL4种隔离级别
java·开发语言·mysql
quant_19863 小时前
R语言如何接入实时行情接口
开发语言·经验分享·笔记·python·websocket·金融·r语言
Hellyc6 小时前
基于模板设计模式开发优惠券推送功能以及对过期优惠卷进行定时清理
java·数据库·设计模式·rocketmq
lifallen6 小时前
Paimon LSM Tree Compaction 策略
java·大数据·数据结构·数据库·算法·lsm-tree
hdsoft_huge6 小时前
SpringBoot 与 JPA 整合全解析:架构优势、应用场景、集成指南与最佳实践
java·spring boot·架构
百锦再7 小时前
详细解析 .NET 依赖注入的三种生命周期模式
java·开发语言·.net·di·注入·模式·依赖
程序员的世界你不懂7 小时前
基于Java+Maven+Testng+Selenium+Log4j+Allure+Jenkins搭建一个WebUI自动化框架(2)对框架加入业务逻辑层
java·selenium·maven
风吹落叶花飘荡7 小时前
2025 Next.js项目提前编译并在服务器
服务器·开发语言·javascript