square / kotlinpoet

A Kotlin API for generating .kt source files.
https://square.github.io/kotlinpoet/
Apache License 2.0
3.88k stars 286 forks source link

CodeWriter generates wrong nullable type in function body #1759

Open Tapchicoma opened 9 months ago

Tapchicoma commented 9 months ago

Describe the bug

Consider I want to generate the following code:

class Test {
    fun doSomething(): Test? { 
        // do something
        return something as Test?
    }
}

kotlinpoet actually generates the following code:

class Test {
    fun doSomething(): Test? {
        // do something
        return something as ?Test
    }
}

I highly suspect that this line should be also called on !deferred condition. Otherwise ? is emitted immediately and the type is emitted somewhat later.

To Reproduce

I failed to reproduce this issue with unit test – it seems I lack the knowledge when deferred can be in true state and it is not happening in the simple case.

Please use the following steps to reproduce on a real project:

To debug generator run ./gradlew generateAPI -Dorg.gradle.debug=true and after build start attach debugger.

Egorand commented 9 months ago

I cloned the project and followed the steps to generate the code, but I can't seem to spot any broken type names in the files you mentioned, this is strange.. Would you be able to temporarily un-gitignore generated code folders on your machine and push that code to a separate branch? I'm really curious to take a look at the codegen code and try to reproduce this with a test!

Tapchicoma commented 9 months ago

@Egorand please pull additional commit from the same branch.