turtlologist turtlologist - 3 months ago 8
Java Question

How to get the value of the arguments of the sonar tree

I'm writing a custom rule for SonarQube for java, I want to check if the value of an argument is qualified. For example, I want to know if the String fit the specific pattern. I can only test if the argument is a String, but I can not get the exact value. Does the API allows me to do so?

For example, for the code below

log.error("errorID:210134 It's an error");


Can I get the argument and test if the string contains errorID?

Besides, can I get what variable did the method invocation?

For example, for the code below

log.error("errorID:210134 It's an error");


How can I know that log is an Object of the class Logger?

Answer

The following should do the trick:

  • When looking at the argument of the method invocation, check if it's kind is a STRING_LITERAL, then cast the argument into a LiteralTree. From there, you will be able to access its value, as a String (Note that it will contains the double quotation marks).
  • To check if the invocation was done on a variable, get the methodSelect() expression tree from the method invocation. If it's kind is a MEMBER_SELECT, cast it to MemberSelectExpressionTree. From there, check if the kind of the expression() is an IDENTIFIER. if it's the case, then you will be able to get the IdentifierTree and its associated symbol. You will then be able to say if the symbol calling the method is a variable or not, check its type, etc.
Comments