-
Notifications
You must be signed in to change notification settings - Fork 645
/
ReservedKeywords.kt
51 lines (43 loc) · 2.27 KB
/
ReservedKeywords.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package com.apollographql.apollo3.compiler
// Reference:
// https://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html
private val JAVA_RESERVED_WORDS = arrayOf(
"abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "default",
"do", "double", "else", "enum", "extends", "false", "final", "finally", "float", "for", "goto", "if", "implements",
"import", "instanceof", "int", "interface", "long", "native", "new", "null", "package", "private", "protected",
"public", "return", "short", "static", "strictfp", "super", "switch", "synchronized", "this", "throw", "throws",
"transient", "try", "true", "void", "volatile", "while"
)
private val TYPE_REGEX = "(?:type)_*".toRegex()
private val COMPANION_REGEX = "(?:Companion)_*".toRegex()
private val KOTLIN_ENUM_RESERVED_WORDS_REGEX = "(?:name|ordinal)_*".toRegex()
fun String.escapeJavaReservedWord() = if (this in JAVA_RESERVED_WORDS) "${this}_" else this
// Does nothing. KotlinPoet will add the backticks
fun String.escapeKotlinReservedWord() = this
internal fun String.escapeTypeReservedWord(): String? {
return when {
// type is forbidden because we use it as a companion property to hold the CompiledType
// See https://github.com/apollographql/apollo-kotlin/issues/4293
TYPE_REGEX.matches(this) -> "${this}_"
else -> null
}
}
private fun String.escapeCompanionReservedWord(): String? {
return when {
// Companion is forbidden because a Companion class is generated in enum and sealed classes
// See https://github.com/apollographql/apollo-kotlin/issues/4557
COMPANION_REGEX.matches(this) -> "${this}_"
else -> null
}
}
fun String.escapeKotlinReservedWordInEnum(): String {
return when {
// name and ordinal are forbidden because already used in Kotlin
// See https://kotlinlang.org/docs/enum-classes.html#working-with-enum-constants:~:text=properties%20for%20obtaining%20its%20name%20and%20position
KOTLIN_ENUM_RESERVED_WORDS_REGEX.matches(this) -> "${this}_"
else -> escapeTypeReservedWord() ?: escapeCompanionReservedWord() ?: escapeKotlinReservedWord()
}
}
fun String.escapeKotlinReservedWordInSealedClass(): String {
return escapeTypeReservedWord() ?: escapeCompanionReservedWord() ?: escapeKotlinReservedWord()
}