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

相关推荐
Aliano2173 分钟前
TestNGException ClassCastException SAXParserFactoryImpl是Java自带的Xerces解析器——解决办法
java·开发语言·python
漫谈网络7 分钟前
回调函数应用示例
开发语言·python·回调函数
进击的小白菜14 分钟前
用Java实现单词搜索(LeetCode 79)——回溯算法详解
java·算法·leetcode
亚林瓜子22 分钟前
pyenv简单的Python版本管理器(macOS版)
开发语言·python·macos·pyenv
夜松云22 分钟前
Qt信号槽机制与UI设计完全指南:从基础原理到实战应用
开发语言·qt·ui·qt designer·布局管理·参数传递·qt信号槽
越来越无动于衷31 分钟前
手写tomcat:基本功能实现(3)
java·tomcat
Uranus^33 分钟前
使用Spring Boot和Spring Security构建安全的RESTful API
java·spring boot·spring security·jwt·restful api
珂朵莉MM33 分钟前
2024 睿抗机器人开发者大赛CAIP-编程技能赛-专科组(国赛)解题报告 | 珂学家
开发语言·人工智能·算法·leetcode·职场和发展·深度优先·图论
qq_5432485234 分钟前
Tomcat的调优
java·tomcat
菥菥爱嘻嘻38 分钟前
JS手写代码篇---手写 new 操作符
开发语言·javascript·原型模式