For example:
String user = "Daniel";
String result = doSomething(user);
I know I can find every occurence of doSomething(user) with //MethodCall[@MethodName = "doSomething"]/ArgumentList/VariableAccess[@Name = "user"]. Is it possible to only find those occurences, where user evaluates to "Daniel" at the time the method is called?
Both
MethodCallandVariableDeclaratorare descendants of the sameBlockelement. That can be used to match the criteria//Block[//AssignmentExpression[last()][VariableAccess[@AccessType="WRITE" and @Name="user"]]/StringLiteral[@ConstValue="LMC"] or //VariableDeclarator[@Name="user"]/StringLiteral[@ConstValue="LMC"]]//MethodCall[@MethodName = "detectMe"]/ArgumentList/VariableAccess[@Name = "user"]This expresion finds
Blockelements containing a variableuser = "LMC"either only declared or last assigned.//Block[//AssignmentExpression[last()][VariableAccess[@AccessType="WRITE" and @Name="user"]]/StringLiteral[@ConstValue="LMC"] or //VariableDeclarator[@Name="user"]/StringLiteral[@ConstValue="LMC"]]Will match something like
As a general method, a test class with the relevant use case can be written and dumped with
pmdfor later XML analysispmd ast-dump --format xml --language java --file PMDSource.java > PMDSource.java.xmlthen use any XPath aware tool to test the expression
Result