Hello,
we are currently developing a SonarQube plgin with custom rules in Java to be integrated on our server and to be used in the Eclipse SonarLint checks. The checks we are implementing are code style checks which are contained in checkstyle. According to what I found out third party analyzers (such as Checkstyle) are not supported in SonarLint plugin that’s why we decided to re-implement them with the Sonar API which (as far as I know works in SonarLint).
One of the checks deals with whitespaces after a certain token (in Checkstyle: “WhitespaceAfter”-Check). When writing the code we are able to get the certain tree element based on the node kinds defined in #nodesToVisit.
For example I’m checking if a “return”-statement is followed by a whitespace or not:
return ("a" + "b"); // compliant
return("a" + "b"); // non-compliant because no whitespace after "return"
I know how to get to the “ReturnStatementTree” and how to get the “returnKeyword” of the tree but I do NOT know how to get the whole statement to check if the return key word is followed by a whitespace. It is the same for other kinds, too.
Code Snippet:
@Rule(key = "WhitespaceAfterCheck")
public class WhitespaceAfterCheck extends IssuableSubscriptionVisitor {
@Override
public List<Kind> nodesToVisit() {
return List.of(Kind.RETURN_STATEMENT, Kind.PARENTHESIZED_EXPRESSION);
}
@Override
public void visitNode(Tree pTree) {
if (pTree instanceof ReturnStatementTree) {
ReturnStatementTree returnTree = (ReturnStatementTree) pTree;
String text = returnTree.returnKeyword().text();
}
// also tried it with ParenthesizedTree
if (pTree instanceof ParenthesizedTree) {
ParenthesizedTree parenthesizedTree = (ParenthesizedTree) pTree;
SyntaxToken openParenToken = parenthesizedTree.openParenToken();
SyntaxToken string = parenthesizedTree.expression().firstToken();
}
}
}
Can you help?
Thank you in advance!
Duc