mirror of
https://github.com/fankes/moshi.git
synced 2025-10-19 07:59:21 +08:00
Reserve simple type names referenced by properties to avoid collisions (#1305)
This commit is contained in:
@@ -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)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -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
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -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)
|
||||||
|
Reference in New Issue
Block a user