All Downloads are FREE. Search and download functionalities are using the official Maven repository.

utility.MTypeReference.kt Maven / Gradle / Ivy

package com.github.fluidsonic.fluid.json.annotationprocessor

import com.github.fluidsonic.fluid.meta.*
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.KModifier
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.STAR
import com.squareup.kotlinpoet.TypeName
import com.squareup.kotlinpoet.TypeVariableName
import com.squareup.kotlinpoet.WildcardTypeName


internal fun MTypeReference.Class.forKotlinPoet(typeParameters: List): TypeName {
	val typeNames = name.withoutPackage().kotlin.split('.')

	return ClassName(
		packageName = name.packageName.kotlin,
		simpleName = typeNames.first(),
		simpleNames = *typeNames.drop(1).toTypedArray()
	)
		.let { className ->
			if (this.arguments.isNotEmpty()) {
				className.parameterizedBy(*arguments.map { it.forKotlinPoet(typeParameters = typeParameters) }.toTypedArray())
			}
			else
				className
		}
		.copy(nullable = isNullable)
}


internal fun MTypeReference.TypeParameter.forKotlinPoet(typeParameters: List): TypeName =
	typeParameters.first { it.id == id }.let { typeParameter ->
		TypeVariableName(
			name = typeParameter.name.kotlin,
			bounds = *typeParameter.upperBounds
				.map { it.forKotlinPoet(typeParameters = typeParameters) }
				.ifEmpty { listOf(KotlinpoetTypeNames.nullableAny) }
				.toTypedArray(),
			variance = typeParameter.variance.kModifier
		).copy(nullable = isNullable || typeParameter.upperBounds.all { it.isNullable })
	}


internal fun MTypeReference.forKotlinPoet(typeParameters: List): TypeName =
	when (this) {
		is MTypeReference.Class -> forKotlinPoet(typeParameters = typeParameters)
		is MTypeReference.TypeParameter -> forKotlinPoet(typeParameters = typeParameters)
		else -> error("not supported")
	}


internal fun MTypeArgument.forKotlinPoet(typeParameters: List): TypeName =
	when (this) {
		is MTypeArgument.StarProjection -> STAR
		is MTypeArgument.Type -> {
			when (variance) {
				MVariance.IN -> WildcardTypeName.consumerOf(forKotlinPoet(typeParameters = typeParameters))
				MVariance.OUT -> WildcardTypeName.producerOf(forKotlinPoet(typeParameters = typeParameters))
				MVariance.INVARIANT -> type.forKotlinPoet(typeParameters = typeParameters)
			}
		}
	}


private val MVariance.kModifier
	get() = when (this) {
		MVariance.INVARIANT -> null
		MVariance.IN -> KModifier.IN
		MVariance.OUT -> KModifier.OUT
	}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy