Java Code Style Checks Checking For Whitespaces after Keywords (Custom SonarQube Plugin Development)


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 {

	public List<Kind> nodesToVisit() {

	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!


1 Like

Hey @nhu_duc ,

Relying on the text is not going to help to solve your case. However, from each SyntaxToken, you can access the Range.

The range is composed of a start() and end() position. The Position itself contains a line and column.

Looking at the position of two subsequent tokens should allow you to check that there is one character difference between each other.

Finally, note that it is possible that some tokens won’t be available through the java analyzer API, especially if we never had the need to write a rule targeting them.

Good luck,


Hey Michael,

thank you for the input. That helped a lot!