Hi Ivan! That's actually a nice idea for a detekt ...
# detekt
s
Hi Ivan! That's actually a nice idea for a detekt rule! Without the source code it's very hard to help you. Can you post a link to your source code please?
a
Methods
visitReturnExpression
and
visitUnaryExpression
don’t work for unary expressions, whose result is not used. That expressions simply do not get visited by those methods (or I’m doing something wrong). So I tried to parse code like strings, but that is very fragile way to solve this case. I wonder, if there is a way to detect unary expressions with unused result, using methods from
org.jetbrains.kotlin.psi
.
Snippet with parsing code as string can be found here https://pastebin.com/3jz2J9Ps
s
What's your test code? Can you give one example where
visitUnaryExpression
is not called? You are right. You will run into false positives with your approach.
a
Yep, here it is https://pastebin.com/xPyXdR6L .
+ variableWithVeryVeryVeryVeryVeryVeryLongName
is unary expression, but
visitUnaryExpression
did not get called for it.
s
I took the time to try your rule locally. Actually
+ variableWithVeryVeryVeryVeryVeryVeryLongName
is a separate PsiElement.
The type of this element is
KtPrefixExpression
.
I used the IntelliJ debugger and went through the abstract syntax tree. With this trick you get to know the types and elements of a specific code snippet.
Weirdly though, the following code snippet yields 1 for the variable x.
Copy code
val x = 1
     + 2
I think there is also an issue in the repo.
a
Thnx for trying to figure out how to solve this issue. x has value of 1, because “+2” is separate expression, and its result is not used. If plus was in the end of line:
Copy code
val x = 1 +
        2
It will behave as expected.