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

相关推荐
AI人工智能+电脑小能手1 分钟前
【大白话说Java面试题】【Java基础篇】第38题:两个对象的hashCode()相同,则 equals()是否也一定为 true?
java·开发语言·后端·面试·hash-index
java1234_小锋2 分钟前
什么是可重入锁ReentrantLock?
java·开发语言
csbysj20204 分钟前
XSLFO 区域
开发语言
江南十四行8 分钟前
Java并发编程中的锁机制:synchronized与Lock详解
java·开发语言
SamDeepThinking9 分钟前
所有的框架源码,最怕的就是被debug
java·后端·程序员
道剑剑非道15 分钟前
FFmpeg + Qt 实现摄像头采集与 MP3 背景音乐 RTSP 推流
开发语言·qt·ffmpeg
吴声子夜歌20 分钟前
Java——字符编码
java·字符编码·char
冷小鱼21 分钟前
多线程编程深度解析:Java与Python框架实战指南
java·开发语言·python·多线程
武帝为此21 分钟前
【C语言进程与线程】
c语言·开发语言
fox_lht22 分钟前
第十一章 错误处理
开发语言·后端·rust