Fairly new to the PSI api, I’ve only used the IR a...
# detekt
t
Fairly new to the PSI api, I’ve only used the IR api so far. With type resolution enabled I’m having a pretty hard time getting a function’s return type. I’m resorting to a mishmash of mutliple different BindingContext slices to determine the type, but it seems like there must be a better way. May be a #compiler question, but there they seem to have success with just
Copy code
bindingContext.get(BindingContext.EXPRESSION_TYPE_INFO, expression)
So I’m wondering if it may be something specific to how Detekt acquires the BindingContext?
g
Have your tried that with Detekt? Is it working?
t
I have. It is returning null on a lot of different cases.
I have to check other slices and cross reference many other parts to get the full picture.
I check these slices in this order •
bindingContext.get(BindingContext.EXPRESSION_TYPE_INFO, functionExpression)
bindingContext.get(BindingContext.EXPRESSION_TYPE_INFO, functionExpression.bodyExpression)
bindingContext.get(BindingContext.EXPECTED_RETURN_TYPE, functionExpression)
• Get the type of the last expression in the block body (unwrapping certain expressions like returns to get the actual type other than Nothing) But then I get the true type, not the type of what’s downcast. • If there’s a body with no statements then I assume it’s Unit, for my purposes • If it’s still null then: if its a KtNamedFunction I assume it’s Unit, otherwise it’s returning a class that isn’t in the Detekt classpath (Android SDK). Based on what I found during testing. It works but I can’t help but think there’s a better way/
I’m writing a rule that checks for CQS. It attempts to identify side effects in Query style functions.
t
Copy code
private fun KtNamedFunction.returnType(): KotlinType? =
    (bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, this] as? FunctionDescriptor)?.returnType
👀 1
t
Works like a charm! Thank you!!