Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix warnings of single-subclass sealed classes #3067

Merged
merged 2 commits into from
Jul 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -75,18 +75,39 @@ typealias NullableFocus = Focus.Nullable
sealed class Focus {

companion object {
operator fun invoke(fullName: String, paramName: String, refinedType: KSType? = null): Focus =
operator fun invoke(
fullName: String,
paramName: String,
refinedType: KSType? = null,
onlyOneSealedSubclass: Boolean = false,
): Focus =
when {
fullName.endsWith("?") -> Nullable(fullName, paramName, refinedType)
fullName.startsWith("`arrow`.`core`.`Option`") -> Option(fullName, paramName, refinedType)
else -> NonNull(fullName, paramName, refinedType)
fullName.endsWith("?") -> Nullable(
fullName,
paramName,
refinedType,
onlyOneSealedSubclass = onlyOneSealedSubclass,
)
fullName.startsWith("`arrow`.`core`.`Option`") -> Option(
fullName,
paramName,
refinedType,
onlyOneSealedSubclass = onlyOneSealedSubclass,
)
else -> NonNull(
fullName,
paramName,
refinedType,
onlyOneSealedSubclass = onlyOneSealedSubclass,
)
}
}

abstract val className: String
abstract val paramName: String
// only used for type-refining prisms
abstract val refinedType: KSType?
abstract val onlyOneSealedSubclass: Boolean

val refinedArguments: List<String>
get() = refinedType?.arguments?.filter {
Expand All @@ -96,15 +117,17 @@ sealed class Focus {
data class Nullable(
override val className: String,
override val paramName: String,
override val refinedType: KSType?
override val refinedType: KSType?,
override val onlyOneSealedSubclass: Boolean,
) : Focus() {
val nonNullClassName = className.dropLast(1)
}

data class Option(
override val className: String,
override val paramName: String,
override val refinedType: KSType?
override val refinedType: KSType?,
override val onlyOneSealedSubclass: Boolean,
) : Focus() {
val nestedClassName =
Regex("`arrow`.`core`.`Option`<(.*)>$").matchEntire(className)!!.groupValues[1]
Expand All @@ -113,7 +136,8 @@ sealed class Focus {
data class NonNull(
override val className: String,
override val paramName: String,
override val refinedType: KSType?
override val refinedType: KSType?,
override val onlyOneSealedSubclass: Boolean,
) : Focus()
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
package arrow.optics.plugin.internals

import com.google.devtools.ksp.symbol.KSTypeParameter

internal fun generatePrisms(ele: ADT, target: PrismTarget) =
Snippet(
`package` = ele.packageName,
Expand All @@ -26,12 +24,16 @@ private fun processElement(ele: ADT, foci: List<Focus>): String {
"${ele.visibilityModifierName} inline fun $angledTypeParameters ${ele.sourceClassName}.Companion.${focus.paramName}(): $Prism<$sourceClassNameWithParams, ${focus.className}>"
}

val elseBranch = if (focus.onlyOneSealedSubclass) "" else """
| else -> ${ele.sourceName}.left()
""".trimMargin()

"""
|$firstLine = $Prism(
| getOrModify = { ${ele.sourceName}: $sourceClassNameWithParams ->
| when (${ele.sourceName}) {
| is ${focus.className} -> ${ele.sourceName}.right()
| else -> ${ele.sourceName}.left()
| $elseBranch
| }
| },
| reverseGet = ::identity
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,14 +75,17 @@ internal fun evalAnnotatedPrismElement(
logger: KSPLogger
): List<Focus> =
when {
element.isSealed ->
element.getSealedSubclasses().map {
element.isSealed -> {
val sealedSubclasses = element.getSealedSubclasses().toList()
sealedSubclasses.map {
Focus(
it.primaryConstructor?.returnType?.resolve()?.qualifiedString() ?: it.qualifiedNameOrSimpleName,
it.simpleName.asString().replaceFirstChar { c -> c.lowercase(Locale.getDefault()) },
it.superTypes.first().resolve()
it.superTypes.first().resolve(),
onlyOneSealedSubclass = sealedSubclasses.size == 1
)
}.toList()
}
}
else -> {
logger.error(errorMessage, element)
emptyList()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ fun String.compilationFails() {
Assertions.assertThat(compilationResult.exitCode).isNotEqualTo(KotlinCompilation.ExitCode.OK)
}

fun String.compilationSucceeds() {
val compilationResult = compile(this)
fun String.compilationSucceeds(allWarningsAsErrors: Boolean = false) {
val compilationResult = compile(this, allWarningsAsErrors = allWarningsAsErrors)
Assertions.assertThat(compilationResult.exitCode).isEqualTo(KotlinCompilation.ExitCode.OK)
}

Expand All @@ -42,8 +42,8 @@ fun String.evals(thing: Pair<String, Any?>) {
// UTILITY FUNCTIONS COPIED FROM META-TEST
// =======================================

internal fun compile(text: String): KotlinCompilation.Result {
val compilation = buildCompilation(text)
internal fun compile(text: String, allWarningsAsErrors: Boolean = false): KotlinCompilation.Result {
val compilation = buildCompilation(text, allWarningsAsErrors = allWarningsAsErrors)
// fix problems with double compilation and KSP
// as stated in https://github.com/tschuchortdev/kotlin-compile-testing/issues/72
val pass1 = compilation.compile()
Expand All @@ -58,7 +58,7 @@ internal fun compile(text: String): KotlinCompilation.Result {
.compile()
}

fun buildCompilation(text: String) = KotlinCompilation().apply {
fun buildCompilation(text: String, allWarningsAsErrors: Boolean = false) = KotlinCompilation().apply {
classpaths = listOf(
"arrow-annotations:$arrowVersion",
"arrow-core:$arrowVersion",
Expand All @@ -67,6 +67,7 @@ fun buildCompilation(text: String) = KotlinCompilation().apply {
symbolProcessorProviders = listOf(OpticsProcessorProvider())
sources = listOf(SourceFile.kotlin(SOURCE_FILENAME, text.trimMargin()))
verbose = false
this.allWarningsAsErrors = allWarningsAsErrors
}

private fun classpathOf(dependency: String): File {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,7 @@ class PrismTests {
| companion object
|}
|val i: Prism<PrismSealed, PrismSealed.PrismSealed1> = PrismSealed.prismSealed1
|val r = i != null
""".evals("r" to true)
""".compilationSucceeds(allWarningsAsErrors = true)
}

@Test
Expand All @@ -32,8 +31,21 @@ class PrismTests {
| companion object
|}
|val i: Prism<PrismSealed<String, String>, PrismSealed.PrismSealed1> = PrismSealed.prismSealed1()
|val r = i != null
""".evals("r" to true)
""".compilationSucceeds(allWarningsAsErrors = true)
}

@Test
fun `Prism will be generated without warning for sealed class with only one subclass`() {
"""
|$`package`
|$imports
|@optics
|sealed class PrismSealed(val field: String, val nullable: String?) {
| data class PrismSealed1(private val a: String?) : PrismSealed("", a)
| companion object
|}
|val i: Prism<PrismSealed, PrismSealed.PrismSealed1> = PrismSealed.prismSealed1
""".compilationSucceeds(allWarningsAsErrors = true)
}

@Test
Expand Down