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() .build()
fun prepare(typeHook: (TypeSpec) -> TypeSpec = { it }): PreparedAdapter { fun prepare(typeHook: (TypeSpec) -> TypeSpec = { it }): PreparedAdapter {
val reservedSimpleNames = mutableSetOf<String>()
for (property in nonTransientProperties) { 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) property.allocateNames(nameAllocator)
} }

View File

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

View File

@@ -1363,6 +1363,16 @@ class GeneratedAdaptersTest {
data class MultipleGenerics<A, B, C, D>(val prop: String) data class MultipleGenerics<A, B, C, D>(val prop: String)
} }
// Regression test for https://github.com/square/moshi/issues/1277
// Compile-only test
@JsonClass(generateAdapter = true)
data class OtherTestModel(val TestModel: TestModel? = null)
@JsonClass(generateAdapter = true)
data class TestModel(
val someVariable: Int,
val anotherVariable: String
)
// Regression test for https://github.com/square/moshi/issues/1022 // Regression test for https://github.com/square/moshi/issues/1022
// Compile-only test // Compile-only test
@JsonClass(generateAdapter = true) @JsonClass(generateAdapter = true)