Skip to content

Imports are not resolved for extension properties used via %M in KDocs #2189

@kevinmost

Description

@kevinmost

Describe the bug
When defining a MemberName with isExtension = true, if the only usage is in a KDoc via %M, the FQ name will get embedded rather than the simple name. If another usage of the member exists in the file, the simple name will get embedded.

To Reproduce

This works as expected:

fun main() {
  val dpFactoryFunction =
    MemberName(packageName = "androidx.compose.ui.unit", simpleName = "dp", isExtension = true)

  val properties =
    listOf(
      PropertySpec.builder("bar", com.squareup.kotlinpoet.INT)
        .initializer("42")
        .addKdoc("`42.%M`", dpFactoryFunction)
        .build(),
      PropertySpec.builder("baz", com.squareup.kotlinpoet.FLOAT)
        .initializer("42.%M.value", dpFactoryFunction)
        .build(),
    )

  val file = FileSpec.builder("foo", "Foo").addProperties(properties).build()
  file.writeTo(System.out)
}

Generating the following (correct) code:

package foo

import androidx.compose.ui.unit.dp
import kotlin.Float
import kotlin.Int

/**
 * `42.dp`
 */
public val bar: Int = 42

public val baz: Float = 42.dp.value

Removing the baz property results in the FQ name being used (incorrectly) in the remaining bar property's KDoc:

package foo

import kotlin.Int

/**
 * `42.androidx.compose.ui.unit.dp`
 */
public val bar: Int = 42

I also tried manually calling .addImport with the dpFactoryFunction on the FileSpec.Builder, but the resolution behavior does not change.

Expected behavior
Unclear to me if the usage of an extension via %M only in imports should trigger the generation of an import (I personally do prefer it that way), or if it should effectively do what %N does and just output dp in this case without being concerned about imports.

I think it could be argued that the right thing to use here is %N and not %M, but it seems unexpected to me that I get the intended behavior if another property exists in the file that triggers the import.

Additional context
Currently the workaround of just switching from %M to %N does work, but I had some code-paths that were being shared for KDoc value generation and actual code generation that worked nicely until I hit this edge-case.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions