Skip to content

Commit

Permalink
Reserve simple type names referenced by properties to avoid collisions
Browse files Browse the repository at this point in the history
Resolves square#1277
  • Loading branch information
ZacSweers committed Feb 15, 2021
1 parent 6e5bb3a commit 3512d2b
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,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)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1363,6 +1363,16 @@ class GeneratedAdaptersTest {
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
// Compile-only test
@JsonClass(generateAdapter = true)
Expand Down

0 comments on commit 3512d2b

Please sign in to comment.