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?
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:
So, answering to your question - yes, it's possible to determine
b = falseandif(b)with help of ASTCST (Concrete Syntax Tree)that you receives just after parsing and before converting toASTWhat is the difference between an Abstract Syntax Tree and a Concrete Syntax Tree?
to build ast programmatically:
not sure there is an official way to do CST