How to resolve variable values using CodeNarc or Groovy AST classes?

37 Views Asked by At

I am writing some custom rules for the CodeNarc Groovy Linter.

I want to create/ extend a rule that is similar to the ConstantIfExpressionRule but covers cases where the constant may be inferred.

For example:

def final b = false;

// later
if (b) {
  doSomething()
}

I want to make a rule that will detect that the code block of the if statement is never reachable.

Arguably, this might not be static analysis but it's not far off as it only involves a lookup of a defined variable. I have seen similar linting in IDEs for Java code so I assume it shouldn't require dynamic running of code.

Being new to CodeNarc and the Groovy AST I don't know if there is any existing support in either library to determine the value of b while checking the if statement. Is this possible?

1

There are 1 best solutions below

1
daggett On

ast/cst could give you a syntax tree after parsing class/script

you can use groovyconsole "inspect cst" to run parser, visualize generated tree, and understand complexity of your goal :)

the following syntax tree corresponds to a code in your question:

enter image description here

So, answering to your question - yes, it's possible to determine b = false and if(b) with help of AST


CST (Concrete Syntax Tree) that you receives just after parsing and before converting to AST

What is the difference between an Abstract Syntax Tree and a Concrete Syntax Tree?


to build ast programmatically:

import org.codehaus.groovy.ast.builder.AstBuilder
import org.codehaus.groovy.control.CompilePhase

def script = """
def final b = false;

// later
if (b) {
  doSomething()
}
"""

def astList = new AstBuilder().buildFromString(CompilePhase.CONVERSION, script)

astList[0].statements.each{ println it }

not sure there is an official way to do CST