Skip to content

Commit

Permalink
Do not use 'header' as a enum value name as it breaks the Kotlin comp…
Browse files Browse the repository at this point in the history
…iler (#4086)

* Do not use 'header' as a value nama as it breaks the Kotlin compiler

* also add impl

* better fix

* be robust against schemas defining both name and name_ (and possibly others)

Thanks @ephemient!
  • Loading branch information
martinbonnin committed May 9, 2022
1 parent ae8f840 commit 9dab1f3
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 6 deletions.
Expand Up @@ -10,14 +10,17 @@ private val JAVA_RESERVED_WORDS = arrayOf(
"transient", "try", "true", "void", "volatile", "while"
)


// Reference:
// https://kotlinlang.org/docs/enum-classes.html#working-with-enum-constants:~:text=properties%20for%20obtaining%20its%20name%20and%20position
private val KOTLIN_RESERVED_ENUM_VALUE_NAMES = arrayOf("name", "ordinal")

fun String.escapeJavaReservedWord() = if (this in JAVA_RESERVED_WORDS) "${this}_" else this

// Does nothing. KotlinPoet will add the backticks
fun String.escapeKotlinReservedWord() = this

fun String.escapeKotlinReservedEnumValueNames() = if (this in KOTLIN_RESERVED_ENUM_VALUE_NAMES) "${this}_" else this
fun String.escapeKotlinReservedEnumValueNames() : String {
return when {
// https://kotlinlang.org/docs/enum-classes.html#working-with-enum-constants:~:text=properties%20for%20obtaining%20its%20name%20and%20position
"(?:name|ordinal)_*".toRegex().matches(this) -> "${this}_"
// "header" and "impl" are added to this list because of https://youtrack.jetbrains.com/issue/KT-52315
this in arrayOf("header", "impl") -> "`${this}`"
else -> this
}
}
1 change: 1 addition & 0 deletions tests/enums/src/main/graphql/operation.graphql
@@ -1,4 +1,5 @@
query GetEnums {
direction
gravity
foo
}
7 changes: 7 additions & 0 deletions tests/enums/src/main/graphql/schema.graphqls
@@ -1,6 +1,7 @@
type Query {
direction: Direction
gravity: Gravity
foo: Foo
}

enum Direction {
Expand Down Expand Up @@ -29,3 +30,9 @@ enum Gravity {
name,
ordinal,
}

# See https://youtrack.jetbrains.com/issue/KT-52315
enum Foo {
header,
footer,
}
6 changes: 6 additions & 0 deletions tests/enums/src/test/kotlin/test/EnumsTest.kt
@@ -1,6 +1,7 @@
package test

import enums.type.Direction
import enums.type.Foo
import enums.type.Gravity
import org.junit.Test
import kotlin.test.assertEquals
Expand All @@ -24,6 +25,11 @@ class EnumsTest {
assertEquals(Gravity.ordinal, Gravity.safeValueOf("ordinal"))
}

@Test
fun headerAndImpl() {
assertEquals(Foo.header.rawValue, "header")
}

@Test
fun sealedClassesKnownValues() {
// Order is important
Expand Down

0 comments on commit 9dab1f3

Please sign in to comment.