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

相关推荐
SimonKing36 分钟前
Workbuddy太占C盘空间了,写个迁移工具迁走10G的数据
java·后端·程序员
Hvitur1 小时前
Java - Lambda
java·开发语言·python
xiaoye-duck1 小时前
《C++ 项目:手写大模型接入 SDK》DataManager数据管理模块:SQLite持久化存储
开发语言·数据库·c++·sqlite
Evand J1 小时前
【MATLAB例程,PMSM19】永磁同步电机(PMSM)基于多速率无迹卡尔曼滤波(UKF)的转速与转子位置估计。测量缺失、状态预测与恢复性能分析
开发语言·matlab·电机·ekf·卡尔曼·电机滤波
喵了几个咪1 小时前
GoWind Flow 拆解:一个 Go 工作流引擎与它的双模式设计器
开发语言·人工智能·后端·golang
꧁细听勿语情꧂2 小时前
二叉树余题,排序、直接插入排序、希尔排序
c语言·开发语言·数据结构·算法
是main不是漫2 小时前
【C++——类和对象(上)】筑基篇:以封装奠定面向对象之基
c语言·开发语言·c++
apcipot_rain6 小时前
C++转Java日记(06)
java·开发语言
金銀銅鐵11 小时前
带您看懂字节码指令(一):一帧里有什么
java·后端·ai编程
nice_lcj52012 小时前
【从零理解 Spring AI · 14】RAG 的四个环节:加载、切分、向量化、检索
java·spring boot·embedding·向量数据库·rag·spring ai·ai应用开发