Skip to content

Commit

Permalink
Resolve enum constants when emitting types (#1235)
Browse files Browse the repository at this point in the history
* resolve enum constants

* reuse ClassName

* yikes, fix typo

* better comments

* Update kotlinpoet/src/main/java/com/squareup/kotlinpoet/CodeWriter.kt

Co-authored-by: Egor Andreevich <github@egorand.dev>

Co-authored-by: Egor Andreevich <github@egorand.dev>
  • Loading branch information
martinbonnin and Egorand committed Apr 19, 2022
1 parent 6d919af commit 7c2d9f4
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 4 deletions.
16 changes: 12 additions & 4 deletions kotlinpoet/src/main/java/com/squareup/kotlinpoet/CodeWriter.kt
Expand Up @@ -518,7 +518,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 @@ -531,9 +531,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

0 comments on commit 7c2d9f4

Please sign in to comment.