8000 How to identify if a `KSTypeReference` is an aliased imported type? · Issue #2391 · google/ksp · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content
How to identify if a KSTypeReference is an aliased imported type? #2391
Open
@mcarleio

Description

@mcarleio

TLDR: How to (consistently) identify that a type is actually an aliased import?


Given the following code block

import kotlin.Double as FP

interface Mapper {
    fun fromFP(fp: FP): Int
    fun fromString(str: String?): Int?
}

And given the following simplified KSP code

ksClassDeclaration
            .getAllFunctions()
            .map {
                 isAlias(it.parameters.first().type)
            }

My current (frankly ugly and not optimal) way to identify if it is an alias:

fun isAlias(typeReference: KSTypeReference): Boolean {
    val resolvedType = typeReference.resolve()
    return typeReference.toString().takeWhile { it != '<' } != resolvedType.makeNotNullable().toString().takeWhile { it != '<' }
}

Sadly this is not working anymore since 2.1.20-1.0.32, as the typeReference is not anymore an instance of KSTypeReferenceImpl (1.0.31) but of KSTypeReferenceResolvedImpl (1.0.32), which has a different result for toString().

For fromFP:

  • With 1.0.31 the type is an instance of KSTypeReferenceImpl with toString() == "FP"
  • With 1.0.32 the type is an instance of KSTypeReferenceResolvedImpl with toString() == "Double"

I could amend the already ugly isAlias logic, but then I directly stumble upon similar problems with nullable types (see fromString) or even worse: a combination of nullable aliased import types with generics 😵

For fromString:

  • With 1.0.31 the type is an instance of KSTypeReferenceImpl with toString() == "String"
  • With 1.0.32 the type is an instance of KSTypeReferenceResolvedImpl with toString() == "String?"

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0