Java custom rule writing without exploring the Syntax Tree

Hello,

When implementing a Java custom rule, nothing forces you to use a BaseTreeVisitor or IssuableSubscriptionVisitor, you can perfectly only implement the JavaFileScanner interface, which will give you access to the content of the file:

package org.sonar.samples.java.checks;

import org.sonar.check.Rule;
import org.sonar.plugins.java.api.JavaFileScanner;
import org.sonar.plugins.java.api.JavaFileScannerContext;

@Rule(key = "MyCheck")
public class MyCheck implements JavaFileScanner {

  @Override
  public void scanFile(JavaFileScannerContext context) {
    context.getFileContent(); // to retrieve the full content of the file as a String
    context.getFileLines();   // to retrieve the content of each lines of the file, as a String
  }
}

Now, depending of what you need to do (especially if you try to be precise in the rule issue locations), not using the Tree is most probably only going to be a pain on the long run.
Identifying a variable in a whole file without information from syntax tree or semantic, but only relying on a regex, may also become quite tricky for big files.

Cheers,
Michael

Note: Regarding format of your message, please note that giving context (versions of analyzers, SQ?) and clearly expressing questions is usually quite appreciated, like usual introductions and conclusions are (greetings? thanks?)

3 Likes