Class JavaAstVisitor

  • All Implemented Interfaces:
    JavaLanguageParserVisitor<DetailAstImpl>, org.antlr.v4.runtime.tree.ParseTreeVisitor<DetailAstImpl>

    public final class JavaAstVisitor
    extends JavaLanguageParserBaseVisitor<DetailAstImpl>
    Visitor class used to build Checkstyle's Java AST from the parse tree produced by JavaLanguageParser. In each visit... method, we visit the children of a node (which correspond to subrules) or create terminal nodes (tokens), and return a subtree as a result.

    Example:

    The following package declaration:

     package com.puppycrawl.tools.checkstyle;
     

    Will be parsed by the packageDeclaration rule from JavaLanguageParser.g4:

     packageDeclaration
         : annotations[true] LITERAL_PACKAGE qualifiedName SEMI
         ;
     

    We override the visitPackageDeclaration method generated by ANTLR in JavaLanguageParser at visitPackageDeclaration(JavaLanguageParser.PackageDeclarationContext) to create a subtree based on the subrules and tokens found in the packageDeclaration subrule accordingly, thus producing the following AST:

     PACKAGE_DEF -> package
     |--ANNOTATIONS -> ANNOTATIONS
     |--DOT -> .
     |   |--DOT -> .
     |   |   |--DOT -> .
     |   |   |   |--IDENT -> com
     |   |   |   `--IDENT -> puppycrawl
     |   |   `--IDENT -> tools
     |   `--IDENT -> checkstyle
     `--SEMI -> ;
     

    See https://github.com/checkstyle/checkstyle/pull/10434 for a good example of how to make changes to Checkstyle's grammar and AST.

    The order of visit... methods in JavaAstVisitor.java and production rules in JavaLanguageParser.g4 should be consistent to ease maintenance.