Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Resolve enum constants when emitting types #1235

Merged
merged 5 commits into from Apr 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 12 additions & 4 deletions kotlinpoet/src/main/java/com/squareup/kotlinpoet/CodeWriter.kt
Expand Up @@ -505,7 +505,7 @@ internal class CodeWriter constructor(
}

/**
* Returns the class referenced by `simpleName`, using the current nesting context and
* Returns the class or enum value referenced by `simpleName`, using the current nesting context and
* imports.
*/
// TODO(jwilson): also honor superclass members when resolving names.
Expand All @@ -518,9 +518,17 @@ internal class CodeWriter constructor(
}
}

// Match the top-level class.
if (typeSpecStack.size > 0 && typeSpecStack[0].name == simpleName) {
return ClassName(packageName, simpleName)
if (typeSpecStack.size > 0) {
val typeSpec = typeSpecStack[0]
if (typeSpec.name == simpleName) {
// Match the top-level class.
return ClassName(packageName, simpleName)
}
if (typeSpec.isEnum && typeSpec.enumConstants.keys.contains(simpleName)) {
// Match a top level enum value.
// Enum values are not proper classes but can still be modeled using ClassName.
return ClassName(packageName, typeSpec.name!!).nestedClass(simpleName)
}
}

// Match an imported type.
Expand Down
30 changes: 30 additions & 0 deletions kotlinpoet/src/test/java/com/squareup/kotlinpoet/TypeSpecTest.kt
Expand Up @@ -5056,6 +5056,36 @@ class TypeSpecTest {
)
}

// https://github.com/square/kotlinpoet/issues/1234
@Test fun `enum constants are resolved`() {
val file = FileSpec.builder("com.example", "test")
.addType(
TypeSpec.enumBuilder("Foo")
.addProperty(
PropertySpec.builder("rawValue", String::class)
.initializer("%S", "")
.build()
)
.addEnumConstant("String")
.build()
)
.build()

assertThat(file.toString()).isEqualTo(
"""
package com.example

public enum class Foo {
String,
;

public val rawValue: kotlin.String = ""
}

""".trimIndent()
)
}

companion object {
private const val donutsPackage = "com.squareup.donuts"
}
Expand Down