Skip to content

Commit

Permalink
Fix type argument mapping when processing typealiases with KSP
Browse files Browse the repository at this point in the history
  • Loading branch information
Egorand committed Apr 21, 2022
1 parent 72a4fa0 commit abbcc17
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 4 deletions.
36 changes: 34 additions & 2 deletions interop/ksp/src/main/kotlin/com/squareup/kotlinpoet/ksp/ksTypes.kt
Expand Up @@ -75,9 +75,17 @@ internal fun KSType.toTypeName(
} else {
decl.typeParameters.toTypeParameterResolver(typeParamResolver)
}
val mappedArgs = arguments.map { it.toTypeName(typeParamResolver) }

val abbreviatedType = decl.type.resolve()
val resolvedType = decl.type.resolve()
val mappedArgs = mapTypeAliasArgsToAbbreviatedTypeArgs(
typeParamResolver = typeParamResolver,
typeAliasTypeParams = decl.typeParameters,
typeAliasTypeArgs = arguments,
abbreviatedTypeParams = resolvedType.declaration.typeParameters,
abbreviatedTypeArgs = resolvedType.arguments,
)

This comment has been minimized.

Copy link
@ting-yuan

ting-yuan Apr 21, 2022

This might need to be done recursively.

typealias A1<T1, T2> = A2<T2, T1>
typealias A2<T2, T3> = Map<T3, T2>

val abbreviatedType = resolvedType
.toTypeName(extraResolver)
.copy(nullable = isMarkedNullable)
.rawType()
Expand All @@ -95,6 +103,30 @@ internal fun KSType.toTypeName(
return type.copy(nullable = isMarkedNullable)
}

@KotlinPoetKspPreview
private fun mapTypeAliasArgsToAbbreviatedTypeArgs(
typeParamResolver: TypeParameterResolver,
typeAliasTypeParams: List<KSTypeParameter>,
typeAliasTypeArgs: List<KSTypeArgument>,
abbreviatedTypeParams: List<KSTypeParameter>,
abbreviatedTypeArgs: List<KSTypeArgument>,
): List<TypeName> {
val orderedAbbreviatedTypeArgs = if (typeAliasTypeParams.size < 2) {
// egor: If there's only one type parameter, KSP might use different names for it in typealias vs abbreviated type
// (not sure why), so we'll return early - order doesn't matter when there are less than 2 parameters.
abbreviatedTypeArgs
} else {
abbreviatedTypeParams
.map { abbreviatedTypeParam ->
typeAliasTypeParams.indexOfFirst { typeAliasTypeParam ->
abbreviatedTypeParam.name.asString() == typeAliasTypeParam.name.asString()
}
}
.map(typeAliasTypeArgs::get)

This comment has been minimized.

Copy link
@ting-yuan

ting-yuan Apr 21, 2022

Probably need to fallback to abbreviatedTypeArgs for -1s from indexOfFirst():

typealias T1Unused<T1, T2> = Map<T2, String>
}
return orderedAbbreviatedTypeArgs.map { it.toTypeName(typeParamResolver) }
}

/**
* Returns a [TypeVariableName] representation of this [KSTypeParameter].
*
Expand Down
Expand Up @@ -300,8 +300,8 @@ class TestProcessorTest {
public class Example {
public fun aliases(
aliasedName: String,
genericAlias: List,
genericMapAlias: Map<String, Int>,
genericAlias: List<String>,
genericMapAlias: Map<Int, String>,
): Unit {
}
}
Expand Down

0 comments on commit abbcc17

Please sign in to comment.