Reserve simple type names referenced by properties to avoid collisions (#1305)

This commit is contained in:
Zac Sweers
2021-02-15 13:02:28 -05:00
committed by GitHub
parent 6b09dc443d
commit 99ebab66c0
3 changed files with 23 additions and 1 deletions

View File

@@ -160,7 +160,15 @@ internal class AdapterGenerator(
.build()
fun prepare(typeHook: (TypeSpec) -> TypeSpec = { it }): PreparedAdapter {
val reservedSimpleNames = mutableSetOf<String>()
for (property in nonTransientProperties) {
// Allocate names for simple property types first to avoid collisions
// See https://github.com/square/moshi/issues/1277
property.target.type.findRawType()?.simpleName?.let { simpleNameToReserve ->
if (reservedSimpleNames.add(simpleNameToReserve)) {
nameAllocator.newName(simpleNameToReserve)
}
}
property.allocateNames(nameAllocator)
}

View File

@@ -39,10 +39,14 @@ import com.squareup.kotlinpoet.WildcardTypeName
import com.squareup.kotlinpoet.asTypeName
internal fun TypeName.rawType(): ClassName {
return findRawType() ?: throw IllegalArgumentException("Cannot get raw type from $this")
}
internal fun TypeName.findRawType(): ClassName? {
return when (this) {
is ClassName -> this
is ParameterizedTypeName -> rawType
else -> throw IllegalArgumentException("Cannot get raw type from $this")
else -> null
}
}