Custom rule about lambda expressions

Hi
I am creating a custom rule in java to have an error message whenever the lamba expressions are not explained. I wrote the code like below.

import java.util.List;
import org.sonar.check.Priority;
import org.sonar.check.Rule;
import org.sonar.plugins.java.api.IssuableSubscriptionVisitor;
import org.sonar.plugins.java.api.tree.*;
import org.sonar.plugins.java.api.tree.Tree.Kind;
import com.google.common.collect.ImmutableList;

@Rule(key = "LambdaExpressionsMustBeCommented", description = "The lambda expressions must be explained in a comment.", 
priority = Priority.MAJOR)
public class LambdaExpressionsMustBeCommentedRule extends IssuableSubscriptionVisitor {
	@Override
	public List<Kind> nodesToVisit(){
 		return ImmutableList.of(Tree.Kind.LAMBDA_EXPRESSION);
	}

	@Override
	public void visitNode(Tree tree) {
		if (tree.is(Tree.Kind.LAMBDA_EXPRESSION)) {
		    LambdaExpressionTree lambdaExpression = (LambdaExpressionTree) tree;
		    String lambdaAsString = lambdaExpression.toString();
		    if (!lambdaAsString.matches(".*//.*[^\\n\\r]")) {
		    	  reportIssue(tree, "You must comment the lamda expression in order to explain it. It has to be on the same line too.");
		      }
		  }
	}
}

The issue is that the comments are not read with that rule. I fell like the list is getting only the lambda expressions and not the full line as I want.
I also tired.

 if (!lambdaAsString.contains("//") || !lambdaAsString.contains("/*")) {

Does anyone an give me an advice to help me ?

I am using sonar 10.1 and java 17.

Thank you all. Have a nice day
Gab.

Hey @Gabzouzer ,

In order to implement rules, we usually start by defining cases that we want the rule to cover, with compliant and non-compliant code examples. This helps in defining and implementing the rule.

Can you give some code examples of lambdas on which you would expect your rule to raise the issue, as well as some cases when you would expect no issue to be raised (valid commented lambdas)? This will help me guide you.

Now, regarding what you did. Using toString() is defeating the purpose of using static analysis to achieve our goal. You should not do it (rule of thumb: if you need toString(), you are making it wrong). If you look at the string that is returned, it is also most probably not what you expect (it does not render the code).

If I were you, once a lambda is reached, I would then use a BaseTreeVisitor to scan the lambda body, looking for syntax trivias (aka comments). You might want to look at the implementation of this rule (java:S128 - SwitchCaseWithoutBreakCheck) to see how it can be achieved.

Hope this helps,
Michael