├── CNAME ├── intellij.png ├── .editorconfig ├── _config.yml ├── gradle.properties ├── docs └── mutable-utils │ ├── scripts │ ├── sourceset_dependencies.js │ ├── clipboard.js │ ├── symbol-parameters-wrapper_deferred.js │ ├── navigation-loader.js │ └── pages.json │ ├── styles │ ├── logo-styles.css │ ├── jetbrains-mono.css │ ├── font-jb-sans-auto.css │ ├── prism.css │ └── main.css │ ├── images │ ├── arrow_down.svg │ ├── footer-go-to-link.svg │ ├── copy-icon.svg │ ├── copy-successful-icon.svg │ ├── go-to-top-icon.svg │ ├── burger.svg │ ├── nav-icons │ │ ├── exception-class.svg │ │ ├── field-value.svg │ │ ├── enum.svg │ │ ├── interface.svg │ │ ├── field-variable.svg │ │ ├── interface-kotlin.svg │ │ ├── enum-kotlin.svg │ │ ├── typealias-kotlin.svg │ │ ├── class.svg │ │ ├── object.svg │ │ ├── class-kotlin.svg │ │ ├── function.svg │ │ ├── abstract-class.svg │ │ ├── annotation.svg │ │ ├── abstract-class-kotlin.svg │ │ └── annotation-kotlin.svg │ ├── logo-icon.svg │ ├── anchor-copy-button.svg │ └── theme-toggle.svg │ ├── mutable-utils │ ├── package-list │ └── at.kopyk │ │ ├── clear-then-add-all-not-null.html │ │ ├── remove-values-unless-instance-of.html │ │ └── mutate-all.html │ ├── index.html │ └── navigation.html ├── gradle ├── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties └── libs.versions.toml ├── kopykat-ksp ├── src │ ├── main │ │ ├── resources │ │ │ └── META-INF │ │ │ │ └── services │ │ │ │ └── com.google.devtools.ksp.processing.SymbolProcessorProvider │ │ └── kotlin │ │ │ └── at │ │ │ └── kopyk │ │ │ ├── utils │ │ │ ├── lang │ │ │ │ ├── Nullables.kt │ │ │ │ ├── TypeExtensions.kt │ │ │ │ ├── JoinWithWhen.kt │ │ │ │ └── SequenceScopedOperators.kt │ │ │ ├── HasAnnotation.kt │ │ │ ├── Visibility.kt │ │ │ ├── ClassNameExtensions.kt │ │ │ ├── GeneratedMarker.kt │ │ │ ├── TypeSubstitution.kt │ │ │ ├── TypeCategory.kt │ │ │ └── KspExtensions.kt │ │ │ ├── KopyKatProvider.kt │ │ │ ├── CopyMap.kt │ │ │ ├── KopyKatOptions.kt │ │ │ ├── KopyKatProcessor.kt │ │ │ ├── FileCompileScope.kt │ │ │ ├── MutableCopy.kt │ │ │ └── CopyConstructors.kt │ └── test │ │ └── kotlin │ │ └── at │ │ └── kopyk │ │ ├── ValueCopyTest.kt │ │ ├── ValueCopyMapTest.kt │ │ ├── Compiler.kt │ │ ├── MutableCollectionCopyTest.kt │ │ ├── NestedMutableCopyTest.kt │ │ ├── PackageTest.kt │ │ ├── CopyFromParentTest.kt │ │ ├── HierarchyCopyTest.kt │ │ ├── AnnotationTest.kt │ │ ├── CopyConstructorsWithValueTest.kt │ │ ├── CopyMapTest.kt │ │ ├── MutableCopyTest.kt │ │ └── CopyConstructorsTest.kt └── build.gradle.kts ├── jitpack.yml ├── renovate.json ├── kopykat-annotations ├── build.gradle.kts └── src │ └── main │ └── kotlin │ └── at │ └── kopyk │ ├── CopyExtensions.kt │ └── Copy.kt ├── .idea └── vcs.xml ├── mutable-utils ├── src │ ├── test │ │ └── kotlin │ │ │ └── at │ │ │ └── kopyk │ │ │ ├── utils │ │ │ └── Lang.kt │ │ │ ├── TestMutation.kt │ │ │ ├── MutableSetTest.kt │ │ │ ├── MutableListTest.kt │ │ │ ├── MutableCollectionTest.kt │ │ │ └── MutableMapTest.kt │ └── main │ │ └── kotlin │ │ └── at │ │ └── kopyk │ │ ├── MutableMap.kt │ │ └── MutableCollection.kt └── build.gradle.kts ├── utils ├── kotlin-poet │ ├── build.gradle.kts │ └── src │ │ └── main │ │ └── kotlin │ │ └── at │ │ └── kopyk │ │ └── poet │ │ ├── TypeName.kt │ │ ├── FunSpec.kt │ │ ├── TypeSpec.kt │ │ └── KotlinPoetExtensions.kt └── compiletesting │ ├── build.gradle.kts │ └── src │ └── main │ └── kotlin │ └── at │ └── kopyk │ └── compiletesting │ └── Compilation.kt ├── settings.gradle.kts ├── .github └── workflows │ ├── release.yml │ └── pull_request.yml ├── .gitignore ├── gradlew.bat └── _layouts └── default.html /CNAME: -------------------------------------------------------------------------------- 1 | kopyk.at -------------------------------------------------------------------------------- /intellij.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kopykat-kt/kopykat/HEAD/intellij.png -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*.kt] 4 | indent_size = 2 5 | 6 | [*.kts] 7 | indent_size = 4 -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | remote_theme: pages-themes/hacker@v0.2.0 2 | plugins: 3 | - jekyll-remote-theme 4 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | kotlin.code.style=official 2 | kotlin.mpp.enableCompatibilityMetadataVariant=true 3 | -------------------------------------------------------------------------------- /docs/mutable-utils/scripts/sourceset_dependencies.js: -------------------------------------------------------------------------------- 1 | sourceset_dependencies='{":mutable-utils:dokkaHtml/main":[]}' 2 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kopykat-kt/kopykat/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /kopykat-ksp/src/main/resources/META-INF/services/com.google.devtools.ksp.processing.SymbolProcessorProvider: -------------------------------------------------------------------------------- 1 | at.kopyk.KopyKatProvider -------------------------------------------------------------------------------- /jitpack.yml: -------------------------------------------------------------------------------- 1 | # https://jitpack.io/docs/BUILDING/ 2 | 3 | # https://jitpack.io/docs/BUILDING/#java-version 4 | jdk: 5 | - openjdk11 6 | -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://docs.renovatebot.com/renovate-schema.json", 3 | "extends": [ 4 | "config:base" 5 | ] 6 | } 7 | -------------------------------------------------------------------------------- /kopykat-ksp/src/main/kotlin/at/kopyk/utils/lang/Nullables.kt: -------------------------------------------------------------------------------- 1 | package at.kopyk.utils.lang 2 | 3 | internal inline fun T?.orElse(block: () -> T): T = this ?: block() 4 | -------------------------------------------------------------------------------- /kopykat-annotations/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | buildsrc.conventions.`kotlin-jvm` 3 | buildsrc.conventions.`maven-publish` 4 | buildsrc.conventions.dokka 5 | } 6 | -------------------------------------------------------------------------------- /kopykat-ksp/src/main/kotlin/at/kopyk/utils/lang/TypeExtensions.kt: -------------------------------------------------------------------------------- 1 | package at.kopyk.utils.lang 2 | 3 | internal inline fun Any?.takeIfInstanceOf(): T? = this as? T 4 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /kopykat-annotations/src/main/kotlin/at/kopyk/CopyExtensions.kt: -------------------------------------------------------------------------------- 1 | package at.kopyk 2 | 3 | @Target(AnnotationTarget.CLASS, AnnotationTarget.TYPEALIAS) 4 | @Retention(AnnotationRetention.SOURCE) 5 | public annotation class CopyExtensions 6 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /mutable-utils/src/test/kotlin/at/kopyk/utils/Lang.kt: -------------------------------------------------------------------------------- 1 | package at.kopyk.utils 2 | 3 | /** 4 | * Makes sure the type is cast to the expected type, or fail 5 | */ 6 | internal inline fun assumingCast(crossinline block: T.() -> Any): T.() -> T = { block() as T } 7 | -------------------------------------------------------------------------------- /utils/kotlin-poet/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | buildsrc.conventions.`kotlin-jvm` 3 | buildsrc.conventions.`maven-publish` 4 | } 5 | 6 | dependencies { 7 | implementation(libs.ksp) 8 | api(libs.kotlinPoet) 9 | api(libs.kotlinPoet.ksp) 10 | } 11 | -------------------------------------------------------------------------------- /mutable-utils/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | buildsrc.conventions.`kotlin-jvm` 3 | buildsrc.conventions.`maven-publish` 4 | buildsrc.conventions.dokka 5 | } 6 | 7 | dependencies { 8 | testImplementation(libs.kotest.assertions.core) 9 | testImplementation(kotlin("test")) 10 | } 11 | -------------------------------------------------------------------------------- /docs/mutable-utils/styles/logo-styles.css: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014-2023 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. 3 | */ 4 | 5 | :root { 6 | --dokka-logo-image-url: url('../images/logo-icon.svg'); 7 | --dokka-logo-height: 50px; 8 | --dokka-logo-width: 50px; 9 | } 10 | -------------------------------------------------------------------------------- /kopykat-ksp/src/main/kotlin/at/kopyk/utils/lang/JoinWithWhen.kt: -------------------------------------------------------------------------------- 1 | package at.kopyk.utils.lang 2 | 3 | internal fun Sequence.joinWithWhen( 4 | subject: String = "this", 5 | transform: (A) -> String = { it.toString() }, 6 | ) = joinToString(prefix = "when ($subject) {\n", separator = "\n", postfix = "\n}", transform = transform) 7 | -------------------------------------------------------------------------------- /docs/mutable-utils/images/arrow_down.svg: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | enableFeaturePreview("TYPESAFE_PROJECT_ACCESSORS") 2 | 3 | rootProject.name = "kopykat" 4 | 5 | apply(from = "./buildSrc/repositories.settings.gradle.kts") 6 | 7 | include( 8 | ":kopykat-annotations", 9 | ":kopykat-ksp", 10 | ":utils:compiletesting", 11 | ":utils:kotlin-poet", 12 | ":mutable-utils", 13 | ) 14 | -------------------------------------------------------------------------------- /mutable-utils/src/test/kotlin/at/kopyk/TestMutation.kt: -------------------------------------------------------------------------------- 1 | package at.kopyk 2 | 3 | import io.kotest.matchers.types.shouldBeSameInstanceAs 4 | 5 | internal fun testMutation( 6 | given: T, 7 | whenWe: T.() -> T, 8 | then: (T) -> Unit, 9 | ) { 10 | val result = given.whenWe() 11 | then(given) 12 | then(result) 13 | given shouldBeSameInstanceAs result 14 | } 15 | -------------------------------------------------------------------------------- /docs/mutable-utils/images/footer-go-to-link.svg: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /docs/mutable-utils/images/copy-icon.svg: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /kopykat-ksp/src/main/kotlin/at/kopyk/utils/HasAnnotation.kt: -------------------------------------------------------------------------------- 1 | package at.kopyk.utils 2 | 3 | import com.google.devtools.ksp.KspExperimental 4 | import com.google.devtools.ksp.getAnnotationsByType 5 | import com.google.devtools.ksp.symbol.KSAnnotated 6 | 7 | @OptIn(KspExperimental::class) 8 | internal inline fun KSAnnotated.hasAnnotation(): Boolean = getAnnotationsByType(T::class).firstOrNull() != null 9 | -------------------------------------------------------------------------------- /docs/mutable-utils/images/copy-successful-icon.svg: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /docs/mutable-utils/images/go-to-top-icon.svg: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /kopykat-ksp/src/main/kotlin/at/kopyk/utils/Visibility.kt: -------------------------------------------------------------------------------- 1 | package at.kopyk.utils 2 | 3 | import com.google.devtools.ksp.symbol.Visibility 4 | 5 | private fun Visibility.min(other: Visibility): Visibility = 6 | when { 7 | this == other -> this 8 | this == Visibility.PUBLIC -> other 9 | other == Visibility.PUBLIC -> this 10 | else -> Visibility.PRIVATE 11 | } 12 | 13 | internal fun List.minimal(): Visibility = reduce(Visibility::min) 14 | -------------------------------------------------------------------------------- /kopykat-ksp/src/main/kotlin/at/kopyk/KopyKatProvider.kt: -------------------------------------------------------------------------------- 1 | package at.kopyk 2 | 3 | import com.google.devtools.ksp.processing.SymbolProcessor 4 | import com.google.devtools.ksp.processing.SymbolProcessorEnvironment 5 | import com.google.devtools.ksp.processing.SymbolProcessorProvider 6 | 7 | public class KopyKatProvider : SymbolProcessorProvider { 8 | override fun create(environment: SymbolProcessorEnvironment): SymbolProcessor = KopyKatProcessor(ProcessorScope(environment)) 9 | } 10 | -------------------------------------------------------------------------------- /docs/mutable-utils/images/burger.svg: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /kopykat-ksp/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | buildsrc.conventions.`kotlin-jvm` 3 | buildsrc.conventions.`maven-publish` 4 | } 5 | 6 | dependencies { 7 | implementation(libs.ksp) 8 | implementation(projects.utils.kotlinPoet) 9 | implementation(projects.kopykatAnnotations) 10 | implementation(libs.apache.commons.io) 11 | 12 | testImplementation(projects.utils.compiletesting) 13 | testImplementation(kotlin("test")) 14 | testImplementation(libs.junit.jupiter.params) 15 | 16 | testRuntimeOnly(projects.kopykatKsp) 17 | } 18 | -------------------------------------------------------------------------------- /docs/mutable-utils/images/nav-icons/exception-class.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /docs/mutable-utils/images/nav-icons/field-value.svg: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /docs/mutable-utils/images/nav-icons/enum.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /docs/mutable-utils/images/nav-icons/interface.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /utils/kotlin-poet/src/main/kotlin/at/kopyk/poet/TypeName.kt: -------------------------------------------------------------------------------- 1 | package at.kopyk.poet 2 | 3 | import com.squareup.kotlinpoet.ParameterizedTypeName 4 | import com.squareup.kotlinpoet.TypeName 5 | import com.squareup.kotlinpoet.TypeVariableName 6 | 7 | public fun TypeVariableName.makeInvariant(): TypeVariableName = TypeVariableName(name, bounds, null) 8 | 9 | public fun TypeName.makeInvariant(): TypeName = 10 | when (this) { 11 | is TypeVariableName -> TypeVariableName(name, bounds, null) 12 | is ParameterizedTypeName -> 13 | copy( 14 | typeArguments = typeArguments.map { it.makeInvariant() }, 15 | ) 16 | else -> this 17 | } 18 | -------------------------------------------------------------------------------- /docs/mutable-utils/images/nav-icons/field-variable.svg: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /kopykat-ksp/src/test/kotlin/at/kopyk/ValueCopyTest.kt: -------------------------------------------------------------------------------- 1 | package at.kopyk 2 | 3 | import org.junit.jupiter.api.Test 4 | 5 | class ValueCopyTest { 6 | @Test 7 | fun `simple test`() { 8 | """ 9 | |@JvmInline 10 | |value class Age(val age: Int) 11 | | 12 | |val a1 = Age(1) 13 | |val a2 = a1.copy { age++ } 14 | |val r = a2.age 15 | """.evals("r" to 2) 16 | } 17 | 18 | @Test 19 | fun `empty copy does nothing`() { 20 | """ 21 | |@JvmInline 22 | |value class Age(val age: Int) 23 | | 24 | |val a1 = Age(1) 25 | |val a2 = a1.copy { } 26 | |val r = a2.age 27 | """.evals("r" to 1) 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /utils/kotlin-poet/src/main/kotlin/at/kopyk/poet/FunSpec.kt: -------------------------------------------------------------------------------- 1 | package at.kopyk.poet 2 | 3 | import com.squareup.kotlinpoet.FunSpec 4 | import com.squareup.kotlinpoet.ParameterSpec 5 | import com.squareup.kotlinpoet.TypeName 6 | 7 | public fun FunSpec.Builder.addReturn( 8 | expr: String, 9 | vararg args: Any?, 10 | ): FunSpec.Builder = addCode("return $expr", args) 11 | 12 | public fun FunSpec.Builder.addParameter( 13 | name: String, 14 | type: TypeName, 15 | defaultValue: String? = null, 16 | ) { 17 | addParameter( 18 | ParameterSpec.builder(name = name, type = type).apply { 19 | if (defaultValue != null) defaultValue(defaultValue) 20 | }.build(), 21 | ) 22 | } 23 | -------------------------------------------------------------------------------- /kopykat-ksp/src/test/kotlin/at/kopyk/ValueCopyMapTest.kt: -------------------------------------------------------------------------------- 1 | package at.kopyk 2 | 3 | import org.junit.jupiter.api.Test 4 | 5 | class ValueCopyMapTest { 6 | @Test 7 | fun `simple test`() { 8 | """ 9 | |@JvmInline 10 | |value class Age(val age: Int) 11 | | 12 | |val a1 = Age(1) 13 | |val a2 = a1.copyMap { it + 1 } 14 | |val r = a2.age 15 | """.evals("r" to 2) 16 | } 17 | 18 | @Test 19 | fun `empty copyMap does nothing`() { 20 | """ 21 | |@JvmInline 22 | |value class Age(val age: Int) 23 | | 24 | |val a1 = Age(1) 25 | |val a2 = a1.copyMap() 26 | |val r = a2.age 27 | """.evals("r" to 1) 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /docs/mutable-utils/images/logo-icon.svg: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /docs/mutable-utils/images/nav-icons/interface-kotlin.svg: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /kopykat-ksp/src/main/kotlin/at/kopyk/utils/ClassNameExtensions.kt: -------------------------------------------------------------------------------- 1 | package at.kopyk.utils 2 | 3 | import at.kopyk.poet.flattenWithSuffix 4 | import com.squareup.kotlinpoet.ClassName 5 | import com.squareup.kotlinpoet.ParameterizedTypeName 6 | import com.squareup.kotlinpoet.TypeName 7 | 8 | internal val ClassName.mutable: ClassName get() = flattenWithSuffix("Mutable") 9 | internal val ParameterizedTypeName.mutable: ParameterizedTypeName get() = flattenWithSuffix("Mutable") 10 | internal val ClassName.dslMarker: ClassName get() = flattenWithSuffix("DslMarker") 11 | 12 | internal val TypeName.mutable: TypeName? 13 | get() = 14 | when (this) { 15 | is ClassName -> this.mutable 16 | is ParameterizedTypeName -> this.mutable 17 | else -> null 18 | } 19 | -------------------------------------------------------------------------------- /utils/compiletesting/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | buildsrc.conventions.`kotlin-jvm` 3 | buildsrc.conventions.`maven-publish` 4 | } 5 | 6 | dependencies { 7 | implementation(kotlin("test")) 8 | implementation(libs.kotest.assertions.core) 9 | implementation(libs.classgraph) 10 | implementation(libs.kotlinCompileTesting) { 11 | exclude( 12 | group = libs.classgraph.get().module.group, 13 | module = libs.classgraph.get().module.name, 14 | ) 15 | exclude( 16 | group = libs.kotlin.stdlibJDK8.get().module.group, 17 | module = libs.kotlin.stdlibJDK8.get().module.name, 18 | ) 19 | } 20 | implementation(libs.kotlinCompileTestingKsp) 21 | implementation(libs.ksp) 22 | } 23 | -------------------------------------------------------------------------------- /docs/mutable-utils/images/nav-icons/enum-kotlin.svg: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /docs/mutable-utils/images/nav-icons/typealias-kotlin.svg: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /kopykat-ksp/src/main/kotlin/at/kopyk/utils/GeneratedMarker.kt: -------------------------------------------------------------------------------- 1 | package at.kopyk.utils 2 | 3 | import com.google.devtools.ksp.symbol.KSFile 4 | import com.google.devtools.ksp.symbol.KSPropertyDeclaration 5 | import com.squareup.kotlinpoet.KModifier.PRIVATE 6 | import com.squareup.kotlinpoet.PropertySpec 7 | import com.squareup.kotlinpoet.asTypeName 8 | 9 | internal fun FileCompilerScope.addGeneratedMarker() { 10 | file.addProperty( 11 | PropertySpec.builder(Marker, UnitTypeName).addModifiers(PRIVATE).initializer("Unit").build(), 12 | ) 13 | } 14 | 15 | internal fun KSFile.hasGeneratedMarker(): Boolean = declarations.filterIsInstance().any { it.baseName == Marker } 16 | 17 | @Suppress("PropertyName") 18 | private const val Marker = "generatedByKopyKat" 19 | 20 | @Suppress("PropertyName") 21 | private val UnitTypeName = Unit::class.asTypeName() 22 | -------------------------------------------------------------------------------- /docs/mutable-utils/images/anchor-copy-button.svg: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /kopykat-ksp/src/test/kotlin/at/kopyk/Compiler.kt: -------------------------------------------------------------------------------- 1 | package at.kopyk 2 | 3 | import at.kopyk.compiletesting.compilesWith 4 | import at.kopyk.compiletesting.evals 5 | import at.kopyk.compiletesting.failsWith 6 | 7 | internal fun String.failsWith( 8 | providerArgs: Map = emptyMap(), 9 | check: (String) -> Boolean, 10 | ) { 11 | failsWith(KopyKatProvider(), providerArgs, check) 12 | } 13 | 14 | internal fun String.compilesWith( 15 | providerArgs: Map = emptyMap(), 16 | check: (String) -> Boolean, 17 | ) { 18 | compilesWith(KopyKatProvider(), providerArgs, check) 19 | } 20 | 21 | internal fun String.evalsWithArgs( 22 | providerArgs: Map = emptyMap(), 23 | vararg things: Pair, 24 | ) { 25 | evals(KopyKatProvider(), providerArgs, *things) 26 | } 27 | 28 | internal fun String.evals(vararg things: Pair) { 29 | evals(KopyKatProvider(), emptyMap(), *things) 30 | } 31 | -------------------------------------------------------------------------------- /docs/mutable-utils/images/nav-icons/class.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /kopykat-ksp/src/test/kotlin/at/kopyk/MutableCollectionCopyTest.kt: -------------------------------------------------------------------------------- 1 | package at.kopyk 2 | 3 | import org.junit.jupiter.api.Test 4 | 5 | /** 6 | * @author: xiaozhikang 7 | * @create: 2023/7/3 8 | */ 9 | class MutableCollectionCopyTest { 10 | @Test 11 | fun `copy property in collection`() { 12 | """ 13 | data class Group(val p: List) 14 | data class Person(val age: Int) 15 | 16 | val g1 = Group(listOf(Person(1), Person(2))) 17 | val g2 = g1.copy { p[1].age ++ } 18 | val age = g2.p[1].age 19 | """.trimIndent().evals("age" to 3) 20 | } 21 | 22 | @Test 23 | fun `copy property in collection with generic type`() { 24 | """ 25 | data class Group(val p: List>) 26 | data class Person(val mark: T) 27 | 28 | val g1 = Group(listOf(Person("old"), Person("old"))) 29 | val g2 = g1.copy { p[1].mark = "new" } 30 | val mark = g2.p[1].mark 31 | """.trimIndent().evals("mark" to "new") 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /docs/mutable-utils/images/theme-toggle.svg: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Publish package to Maven Central 2 | on: 3 | release: 4 | types: [created] 5 | 6 | jobs: 7 | publish: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: actions/checkout@v4 11 | with: 12 | fetch-depth: 0 13 | 14 | - name: Set up Java 15 | uses: actions/setup-java@v4 16 | with: 17 | distribution: 'temurin' 18 | java-version: 17 19 | 20 | - name: Validate Gradle wrapper 21 | uses: gradle/wrapper-validation-action@v1 22 | 23 | - name: Publish package 24 | uses: gradle/gradle-build-action@v2 25 | with: 26 | arguments: publish 27 | env: 28 | MAVEN_USERNAME: ${{ secrets.OSSRH_USERNAME }} 29 | MAVEN_PASSWORD: ${{ secrets.OSSRH_TOKEN }} 30 | RELEASE_TAG: ${{ github.ref_name }} 31 | ORG_GRADLE_PROJECT_signingKey: ${{ secrets.PGP_SECRET }} 32 | ORG_GRADLE_PROJECT_signingPassword: ${{ secrets.PGP_PASSPHRASE }} -------------------------------------------------------------------------------- /docs/mutable-utils/images/nav-icons/object.svg: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /kopykat-ksp/src/main/kotlin/at/kopyk/utils/lang/SequenceScopedOperators.kt: -------------------------------------------------------------------------------- 1 | package at.kopyk.utils.lang 2 | 3 | /** 4 | * Alias of [forEach] with the item as the receiver. 5 | */ 6 | internal inline fun Sequence.forEachRun(block: A.() -> Unit) { 7 | forEach(block) 8 | } 9 | 10 | /** 11 | * Alias of [flatMap] with the item as the receiver. 12 | */ 13 | internal inline fun Sequence.flatMapRun(crossinline block: A.() -> Sequence) = flatMap { it.block() } 14 | 15 | /** 16 | * Alias of [onEach] with the item as the receiver. 17 | */ 18 | internal fun Sequence.onEachRun(block: A.() -> Unit) = onEach(block) 19 | 20 | /** 21 | * Alias of [map] with the item as the receiver. 22 | */ 23 | internal fun Sequence.mapRun(block: A.() -> R) = map(block) 24 | 25 | /** 26 | * Filters instances of [T] as long as they pass the provided [predicate] 27 | */ 28 | internal inline fun Sequence<*>.filterIsInstance(noinline predicate: T.() -> Boolean): Sequence = 29 | filterIsInstance().filter(predicate) 30 | -------------------------------------------------------------------------------- /docs/mutable-utils/images/nav-icons/class-kotlin.svg: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /docs/mutable-utils/images/nav-icons/function.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /docs/mutable-utils/styles/jetbrains-mono.css: -------------------------------------------------------------------------------- 1 | @font-face{ 2 | font-family: 'JetBrains Mono'; 3 | src: url('https://raw.githubusercontent.com/JetBrains/JetBrainsMono/master/fonts/web/JetBrainsMono-Regular.eot') format('embedded-opentype'), 4 | url('https://raw.githubusercontent.com/JetBrains/JetBrainsMono/master/fonts/webfonts/JetBrainsMono-Regular.woff2') format('woff2'), 5 | url('https://raw.githubusercontent.com/JetBrains/JetBrainsMono/master/fonts/ttf/JetBrainsMono-Regular.ttf') format('truetype'); 6 | font-weight: normal; 7 | font-style: normal; 8 | } 9 | 10 | @font-face{ 11 | font-family: 'JetBrains Mono'; 12 | src: url('https://raw.githubusercontent.com/JetBrains/JetBrainsMono/master/fonts/web/JetBrainsMono-Bold.eot') format('embedded-opentype'), 13 | url('https://raw.githubusercontent.com/JetBrains/JetBrainsMono/master/fonts/webfonts/JetBrainsMono-Bold.woff2') format('woff2'), 14 | url('https://raw.githubusercontent.com/JetBrains/JetBrainsMono/master/fonts/ttf/JetBrainsMono-Bold.ttf') format('truetype'); 15 | font-weight: bold; 16 | font-style: bold; 17 | } -------------------------------------------------------------------------------- /kopykat-annotations/src/main/kotlin/at/kopyk/Copy.kt: -------------------------------------------------------------------------------- 1 | package at.kopyk 2 | 3 | import kotlin.reflect.KClass 4 | 5 | /** 6 | * Marks type or typealias to generate copy constructors. 7 | * This is the equivalent of using [CopyFrom] and [CopyTo] together. 8 | * 9 | * Both the subject of this annotation and the provided type 10 | * have to have the same constructor properties. 11 | */ 12 | @Repeatable 13 | @Target(AnnotationTarget.CLASS, AnnotationTarget.TYPEALIAS) 14 | @Retention(AnnotationRetention.SOURCE) 15 | public annotation class Copy(val type: KClass<*>) 16 | 17 | /** 18 | * Marks type or typealias to generate copy constructor from 19 | * the provided [type] to the subject of this annotation. 20 | * 21 | * Both the subject of this annotation and the provided type 22 | * have to have the same constructor properties. 23 | */ 24 | @Repeatable 25 | @Target(AnnotationTarget.CLASS, AnnotationTarget.TYPEALIAS) 26 | @Retention(AnnotationRetention.SOURCE) 27 | public annotation class CopyFrom(val type: KClass<*>) 28 | 29 | /** 30 | * Marks type or typealias to generate copy constructor from 31 | * the subject of this annotation to the provided [type]. 32 | * 33 | * Both the subject of this annotation and the provided type 34 | * have to have the same constructor properties. 35 | */ 36 | @Repeatable 37 | @Target(AnnotationTarget.CLASS, AnnotationTarget.TYPEALIAS) 38 | @Retention(AnnotationRetention.SOURCE) 39 | public annotation class CopyTo(val type: KClass<*>) 40 | -------------------------------------------------------------------------------- /docs/mutable-utils/images/nav-icons/abstract-class.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /mutable-utils/src/test/kotlin/at/kopyk/MutableSetTest.kt: -------------------------------------------------------------------------------- 1 | package at.kopyk 2 | 3 | import at.kopyk.utils.assumingCast 4 | import io.kotest.matchers.collections.shouldContainExactly 5 | import org.junit.jupiter.api.Test 6 | 7 | class MutableSetTest { 8 | @Test 9 | fun `can mutate all items`() = 10 | testMutation( 11 | given = mutableSetOf("a", "b", "c"), 12 | whenWe = { mutateAll { it + it } }, 13 | then = { it shouldContainExactly listOf("aa", "bb", "cc") }, 14 | ) 15 | 16 | @Test 17 | fun `can mutate all items indexed`() = 18 | testMutation( 19 | given = mutableSetOf("a", "b", "c"), 20 | whenWe = { mutateAllIndexed { index, value -> value + index } }, 21 | then = { it shouldContainExactly listOf("a0", "b1", "c2") }, 22 | ) 23 | 24 | @Test 25 | fun `removes null mutations`() = 26 | testMutation( 27 | given = mutableSetOf("a", "b", "c"), 28 | whenWe = { mutateAllNotNull { value -> value.takeUnless { it == "b" } } }, 29 | then = { it shouldContainExactly listOf("a", "c") }, 30 | ) 31 | 32 | @Test 33 | fun `removes null mutations with index`() = 34 | testMutation( 35 | given = mutableSetOf("a", "b", "c"), 36 | whenWe = { mutateAllIndexedNotNull { i, v -> v.takeUnless { it == "b" }?.plus("$i") } }, 37 | then = { it shouldContainExactly listOf("a0", "c2") }, 38 | ) 39 | 40 | @Test 41 | fun `keep instances of a given type`() = 42 | testMutation( 43 | given = mutableSetOf("a", 10, "c"), 44 | whenWe = assumingCast { removeUnlessInstanceOf().mutateAll { it + it } }, 45 | then = { it shouldContainExactly listOf("aa", "cc") }, 46 | ) 47 | } 48 | -------------------------------------------------------------------------------- /mutable-utils/src/test/kotlin/at/kopyk/MutableListTest.kt: -------------------------------------------------------------------------------- 1 | package at.kopyk 2 | 3 | import at.kopyk.utils.assumingCast 4 | import io.kotest.matchers.collections.shouldContainExactly 5 | import org.junit.jupiter.api.Test 6 | 7 | class MutableListTest { 8 | @Test 9 | fun `can mutate all items`() = 10 | testMutation( 11 | given = mutableListOf("a", "b", "c"), 12 | whenWe = { mutateAll { it + it } }, 13 | then = { it shouldContainExactly listOf("aa", "bb", "cc") }, 14 | ) 15 | 16 | @Test 17 | fun `can mutate all items indexed`() = 18 | testMutation( 19 | given = mutableListOf("a", "b", "c"), 20 | whenWe = { mutateAllIndexed { index, value -> value + index } }, 21 | then = { it shouldContainExactly listOf("a0", "b1", "c2") }, 22 | ) 23 | 24 | @Test 25 | fun `removes null mutations`() = 26 | testMutation( 27 | given = mutableListOf("a", "b", "c"), 28 | whenWe = { mutateAllNotNull { value -> value.takeUnless { it == "b" } } }, 29 | then = { it shouldContainExactly listOf("a", "c") }, 30 | ) 31 | 32 | @Test 33 | fun `removes null mutations with index`() = 34 | testMutation( 35 | given = mutableListOf("a", "b", "c"), 36 | whenWe = { mutateAllIndexedNotNull { i, v -> v.takeUnless { it == "b" }?.plus("$i") } }, 37 | then = { it shouldContainExactly listOf("a0", "c2") }, 38 | ) 39 | 40 | @Test 41 | fun `keep instances of a given type`() = 42 | testMutation( 43 | given = mutableListOf("a", 10, "c"), 44 | whenWe = assumingCast { removeUnlessInstanceOf().mutateAll { it + it } }, 45 | then = { it shouldContainExactly listOf("aa", "cc") }, 46 | ) 47 | } 48 | -------------------------------------------------------------------------------- /utils/kotlin-poet/src/main/kotlin/at/kopyk/poet/TypeSpec.kt: -------------------------------------------------------------------------------- 1 | package at.kopyk.poet 2 | 3 | import com.squareup.kotlinpoet.ClassName 4 | import com.squareup.kotlinpoet.FileSpec 5 | import com.squareup.kotlinpoet.FunSpec 6 | import com.squareup.kotlinpoet.KModifier 7 | import com.squareup.kotlinpoet.PropertySpec 8 | import com.squareup.kotlinpoet.TypeName 9 | import com.squareup.kotlinpoet.TypeSpec 10 | 11 | public fun TypeSpec.Builder.primaryConstructor(block: FunSpec.Builder.() -> Unit) { 12 | primaryConstructor(FunSpec.constructorBuilder().apply(block).build()) 13 | } 14 | 15 | public fun FileSpec.Builder.addClass( 16 | className: ClassName, 17 | block: TypeSpec.Builder.() -> Unit, 18 | ) { 19 | addType(TypeSpec.classBuilder(className).apply(block).build()) 20 | } 21 | 22 | public fun TypeSpec.Builder.addProperty( 23 | name: String, 24 | type: TypeName, 25 | modifiers: Iterable = emptyList(), 26 | initializer: String? = null, 27 | ) { 28 | addProperty(name, type, modifiers, initializer) { mutable(false) } 29 | } 30 | 31 | public fun TypeSpec.Builder.addMutableProperty( 32 | name: String, 33 | type: TypeName, 34 | modifiers: Iterable = emptyList(), 35 | initializer: String? = null, 36 | ) { 37 | addProperty(name, type, modifiers, initializer) { mutable(true) } 38 | } 39 | 40 | private fun TypeSpec.Builder.addProperty( 41 | name: String, 42 | type: TypeName, 43 | modifiers: Iterable = emptyList(), 44 | initializer: String? = null, 45 | block: PropertySpec.Builder.() -> Unit = { }, 46 | ) { 47 | addProperty( 48 | PropertySpec.builder(name = name, type = type).apply { 49 | if (initializer != null) initializer(initializer) 50 | addModifiers(modifiers) 51 | }.apply(block).build(), 52 | ) 53 | } 54 | -------------------------------------------------------------------------------- /mutable-utils/src/test/kotlin/at/kopyk/MutableCollectionTest.kt: -------------------------------------------------------------------------------- 1 | package at.kopyk 2 | 3 | import at.kopyk.utils.assumingCast 4 | import io.kotest.matchers.collections.shouldContainExactly 5 | import org.junit.jupiter.api.Test 6 | 7 | class MutableCollectionTest { 8 | @Test 9 | fun `can mutate all items`() = 10 | testMutation>( 11 | given = mutableListOf("a", "b", "c"), 12 | whenWe = { mutateAll { it + it } }, 13 | then = { it shouldContainExactly listOf("aa", "bb", "cc") }, 14 | ) 15 | 16 | @Test 17 | fun `can mutate all items indexed`() = 18 | testMutation>( 19 | given = mutableListOf("a", "b", "c"), 20 | whenWe = { mutateAllIndexed { index, value -> value + index } }, 21 | then = { it shouldContainExactly listOf("a0", "b1", "c2") }, 22 | ) 23 | 24 | @Test 25 | fun `removes null mutations`() = 26 | testMutation>( 27 | given = mutableListOf("a", "b", "c"), 28 | whenWe = { mutateAllNotNull { value -> value.takeUnless { it == "b" } } }, 29 | then = { it shouldContainExactly listOf("a", "c") }, 30 | ) 31 | 32 | @Test 33 | fun `removes null mutations with index`() = 34 | testMutation>( 35 | given = mutableListOf("a", "b", "c"), 36 | whenWe = { mutateAllIndexedNotNull { i, v -> v.takeUnless { it == "b" }?.plus("$i") } }, 37 | then = { it shouldContainExactly listOf("a0", "c2") }, 38 | ) 39 | 40 | @Test 41 | fun `keep instances of a given type`() = 42 | testMutation>( 43 | given = mutableListOf("a", 10, "c"), 44 | whenWe = assumingCast { removeUnlessInstanceOf().mutateAll { it + it } }, 45 | then = { it shouldContainExactly listOf("aa", "cc") }, 46 | ) 47 | } 48 | -------------------------------------------------------------------------------- /docs/mutable-utils/styles/font-jb-sans-auto.css: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014-2023 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. 3 | */ 4 | 5 | /* Light weight */ 6 | @font-face { 7 | font-family: 'JetBrains Sans'; 8 | src: url('https://resources.jetbrains.com/storage/jetbrains-sans/JetBrainsSans-Light.woff2') format('woff2'), url('https://resources.jetbrains.com/storage/jetbrains-sans/JetBrainsSans-Light.woff') format('woff'); 9 | font-weight: 300; 10 | font-style: normal; 11 | } 12 | /* Regular weight */ 13 | @font-face { 14 | font-family: 'JetBrains Sans'; 15 | src: url('https://resources.jetbrains.com/storage/jetbrains-sans/JetBrainsSans-Regular.woff2') format('woff2'), url('https://resources.jetbrains.com/storage/jetbrains-sans/JetBrainsSans-Regular.woff') format('woff'); 16 | font-weight: 400; 17 | font-style: normal; 18 | } 19 | /* SemiBold weight */ 20 | @font-face { 21 | font-family: 'JetBrains Sans'; 22 | src: url('https://resources.jetbrains.com/storage/jetbrains-sans/JetBrainsSans-SemiBold.woff2') format('woff2'), url('https://resources.jetbrains.com/storage/jetbrains-sans/JetBrainsSans-SemiBold.woff') format('woff'); 23 | font-weight: 600; 24 | font-style: normal; 25 | } 26 | 27 | @supports (font-variation-settings: normal) { 28 | @font-face { 29 | font-family: 'JetBrains Sans'; 30 | src: url('https://resources.jetbrains.com/storage/jetbrains-sans/JetBrainsSans.woff2') format('woff2 supports variations'), 31 | url('https://resources.jetbrains.com/storage/jetbrains-sans/JetBrainsSans.woff2') format('woff2-variations'), 32 | url('https://resources.jetbrains.com/storage/jetbrains-sans/JetBrainsSans.woff') format('woff-variations'); 33 | font-weight: 100 900; 34 | font-style: normal; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /kopykat-ksp/src/test/kotlin/at/kopyk/NestedMutableCopyTest.kt: -------------------------------------------------------------------------------- 1 | package at.kopyk 2 | 3 | import org.junit.jupiter.api.Test 4 | 5 | class NestedMutableCopyTest { 6 | @Test 7 | fun `mutate nested property`() { 8 | """ 9 | |data class Person(val name: String, val job: Job) 10 | |data class Job(val title: String) 11 | | 12 | |val p1 = Person("Alex", Job("Developer")) 13 | |val p2 = p1.copy { job.title = "Señor Developer" } 14 | |val r = p2.job.title 15 | """.evals("r" to "Señor Developer") 16 | } 17 | 18 | @Test 19 | fun `mutate nested property with value type`() { 20 | """ 21 | |data class Person(val name: String, val job: Job) 22 | |data class Job(val title: String, val level: Level) 23 | |@JvmInline value class Level(val value: Int) 24 | | 25 | |val p1 = Person("Alex", Job("Developer", Level(1))) 26 | |val p2: Person = p1.copy { job.level.value++ } 27 | |val r = p2.job.level.value 28 | """.evals("r" to 2) 29 | } 30 | 31 | @Test 32 | fun `mutate list property`() { 33 | """ 34 | |data class Person(val name: String, val job: Job) 35 | |data class Job(val title: String, val teams: List) 36 | | 37 | |val p1 = Person("Alex", Job("Developer", listOf("A"))) 38 | |val p2 = p1.copy { 39 | | job.title = "Señor Developer" 40 | | job.teams.add("B") 41 | |} 42 | |val r1 = p2.job.title 43 | |val r2 = p2.job.teams 44 | """.evals("r1" to "Señor Developer", "r2" to listOf("A", "B")) 45 | } 46 | 47 | @Test 48 | fun `mutate nested`() { 49 | """ 50 | |data class Person(val name: String, val passport: Passport?) 51 | |data class Passport(val id: String, val countryCode: String) 52 | """.compilesWith { 53 | true 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /docs/mutable-utils/images/nav-icons/annotation.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /kopykat-ksp/src/test/kotlin/at/kopyk/PackageTest.kt: -------------------------------------------------------------------------------- 1 | package at.kopyk 2 | 3 | import org.junit.jupiter.api.Test 4 | 5 | class PackageTest { 6 | @Test 7 | fun `copyMap, simple test`() { 8 | """ 9 | |package kopykat.tests 10 | | 11 | |data class Person(val name: String, val age: Int) 12 | | 13 | |val p1 = Person("Alex", 1) 14 | |val p2 = p1.copyMap(age = { it + 1 }) 15 | |val r = p2.age 16 | """.evals("r" to 2) 17 | } 18 | 19 | @Test 20 | fun `copyMap, works on generic classes`() { 21 | """ 22 | |package kopykat.tests 23 | | 24 | |data class Person(val name: String, val age: A) 25 | | 26 | |val p1: Person = Person("Alex", 1) 27 | |val p2 = p1.copyMap(age = { it + 1 }) 28 | |val r = p2.age 29 | """.evals("r" to 2) 30 | } 31 | 32 | @Test 33 | fun `mutate one property`() { 34 | """ 35 | |package kopykat.tests 36 | | 37 | |data class Person(val name: String, val age: Int) 38 | | 39 | |val p1 = Person("Alex", 1) 40 | |val p2 = p1.copy { age = age + 1 } 41 | |val r = p2.age 42 | """.evals("r" to 2) 43 | } 44 | 45 | @Test 46 | fun `access the old value`() { 47 | """ 48 | |package kopykat.tests 49 | | 50 | |data class Person(val name: String, val age: Int) 51 | | 52 | |val p1 = Person("Alex", 1) 53 | |val p2 = p1.copy { 54 | | age++ 55 | | age = old.age 56 | | } 57 | |val r = p2.age 58 | """.evals("r" to 1) 59 | } 60 | 61 | @Test 62 | fun `value copy, simple test`() { 63 | """ 64 | |package kopykat.tests 65 | | 66 | |@JvmInline 67 | |value class Age(val age: Int) 68 | | 69 | |val a1 = Age(1) 70 | |val a2 = a1.copy { age++ } 71 | |val r = a2.age 72 | """.evals("r" to 2) 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /mutable-utils/src/main/kotlin/at/kopyk/MutableMap.kt: -------------------------------------------------------------------------------- 1 | package at.kopyk 2 | 3 | /** 4 | * Applies [transform] to each entry in the map, 5 | * reusing the same structure to keep them. 6 | * 7 | * The mutable equivalent to [Map.mapValues]. 8 | */ 9 | public inline fun MutableMap.mutateValues(transform: (entry: Map.Entry) -> V): MutableMap = 10 | mutateValuesNotNull(transform) 11 | 12 | /** 13 | * Applies [transform] to each entry in the map, 14 | * reusing the same structure to keep them. 15 | * 16 | * The mutable equivalent to [Map.mapValues]. 17 | */ 18 | public inline fun MutableMap.mutateValues(transform: (key: K, value: V) -> V): MutableMap = 19 | mutateValuesNotNull(transform) 20 | 21 | /** 22 | * Applies [transform] to each entry in the map, 23 | * removing the item if `null` is returned. 24 | */ 25 | public inline fun MutableMap.mutateValuesNotNull(transform: (entry: Map.Entry) -> V?): MutableMap = 26 | apply { 27 | with(iterator()) { 28 | while (hasNext()) { 29 | next().apply { 30 | transform(this)?.also(::setValue) ?: remove() 31 | } 32 | } 33 | } 34 | } 35 | 36 | /** 37 | * Applies [transform] to each entry in the map, 38 | * removing the item if `null` is returned. 39 | */ 40 | public inline fun MutableMap.mutateValuesNotNull(transform: (key: K, value: V) -> V?): MutableMap = 41 | mutateValuesNotNull { (key, value) -> transform(key, value) } 42 | 43 | /** 44 | * Removes any values in the map that are not type [V] and 45 | * returns a [MutableMap]<[K], [V]> with the remaining entries. 46 | */ 47 | @Suppress("UNCHECKED_CAST") 48 | public inline fun MutableMap.removeValuesUnlessInstanceOf(): MutableMap = 49 | (this as MutableMap).mutateValuesNotNull { (_, value) -> value as? V } as MutableMap 50 | -------------------------------------------------------------------------------- /docs/mutable-utils/images/nav-icons/abstract-class-kotlin.svg: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /docs/mutable-utils/images/nav-icons/annotation-kotlin.svg: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /mutable-utils/src/test/kotlin/at/kopyk/MutableMapTest.kt: -------------------------------------------------------------------------------- 1 | package at.kopyk 2 | 3 | import at.kopyk.utils.assumingCast 4 | import io.kotest.matchers.maps.shouldContainExactly 5 | import org.junit.jupiter.api.Test 6 | 7 | class MutableMapTest { 8 | @Test 9 | fun `can mutate all entries`() = 10 | testMutation( 11 | given = mutableMapOf(12 to "a", 15 to "b"), 12 | whenWe = { mutateValues { (k, v) -> "$k -> $v" } }, 13 | then = { it shouldContainExactly mapOf(12 to "12 -> a", 15 to "15 -> b") }, 14 | ) 15 | 16 | @Test 17 | fun `can mutate all items deconstructed`() = 18 | testMutation( 19 | given = mutableMapOf(12 to "a", 15 to "b"), 20 | whenWe = { mutateValues { k, v -> "$k -> $v" } }, 21 | then = { it shouldContainExactly mapOf(12 to "12 -> a", 15 to "15 -> b") }, 22 | ) 23 | 24 | @Test 25 | fun `removes null mutations`() = 26 | testMutation( 27 | given = mutableMapOf(12 to "a", 15 to "b", 10 to "c"), 28 | whenWe = { mutateValuesNotNull { (k, v) -> "$k -> $v".takeUnless { v == "b" } } }, 29 | then = { it shouldContainExactly mapOf(12 to "12 -> a", 10 to "10 -> c") }, 30 | ) 31 | 32 | @Test 33 | fun `removes null mutations deconstructed`() = 34 | testMutation( 35 | given = mutableMapOf(12 to "a", 15 to "b", 10 to "c"), 36 | whenWe = { mutateValuesNotNull { k, v -> "$k -> $v".takeUnless { v == "b" } } }, 37 | then = { it shouldContainExactly mapOf(12 to "12 -> a", 10 to "10 -> c") }, 38 | ) 39 | 40 | @Test 41 | fun `keep values of a given type`() = 42 | testMutation>( 43 | given = mutableMapOf(12 to "a", 15 to 5, 10 to "c"), 44 | whenWe = 45 | assumingCast { 46 | removeValuesUnlessInstanceOf<_, String>().mutateValues { (k, v) -> "$k -> $v" } 47 | }, 48 | then = { it shouldContainExactly mapOf(12 to "12 -> a", 10 to "10 -> c") }, 49 | ) 50 | } 51 | -------------------------------------------------------------------------------- /gradle/libs.versions.toml: -------------------------------------------------------------------------------- 1 | [versions] 2 | kotlin = "1.9.21" 3 | dokka = "1.9.10" 4 | kspVersion = "1.9.21-1.0.16" 5 | kotlinPoet = "1.15.3" 6 | kotlinCompileTesting = "0.4.0" 7 | kotest = "5.8.0" 8 | classgraph = "4.8.165" 9 | commonsIo = "2.15.1" 10 | ktlint = "12.0.3" 11 | junit = "5.10.1" 12 | 13 | [libraries] 14 | kotlin-bom = { module = "org.jetbrains.kotlin:kotlin-bom", version.ref = "kotlin" } 15 | kotlin-stdlibCommon = { module = "org.jetbrains.kotlin:kotlin-stdlib-common" } 16 | kotlin-stdlibJDK8 = { module = "org.jetbrains.kotlin:kotlin-stdlib-jdk8" } 17 | kotlinPoet = { module = "com.squareup:kotlinpoet", version.ref = "kotlinPoet" } 18 | kotlinPoet-ksp = { module = "com.squareup:kotlinpoet-ksp", version.ref = "kotlinPoet" } 19 | ksp = { module = "com.google.devtools.ksp:symbol-processing-api", version.ref = "kspVersion" } 20 | kotlinCompileTesting = { module = "dev.zacsweers.kctfork:core", version.ref = "kotlinCompileTesting" } 21 | kotlinCompileTestingKsp = { module = "dev.zacsweers.kctfork:ksp", version.ref = "kotlinCompileTesting" } 22 | kotest-assertions-core = { module = "io.kotest:kotest-assertions-core", version.ref = "kotest" } 23 | classgraph = { module = "io.github.classgraph:classgraph", version.ref = "classgraph" } 24 | apache-commons-io = { module = "commons-io:commons-io", version.ref = "commonsIo" } 25 | junit-jupiter-params = { module = "org.junit.jupiter:junit-jupiter-params", version.ref = "junit" } 26 | 27 | ### Plugins ### 28 | # the *Maven coodinates* of Gradle plugins. Use in ./buildSrc/build.gradle.kts. 29 | 30 | gradlePlugin-kotlinJvm = { module = "org.jetbrains.kotlin:kotlin-gradle-plugin", version.ref = "kotlin" } 31 | gradlePlugin-ktLint = { module = "org.jlleitschuh.gradle:ktlint-gradle", version.ref = "ktlint" } 32 | gradlePlugin-dokka = { module = "org.jetbrains.dokka:dokka-gradle-plugin", version.ref = "dokka" } 33 | 34 | [plugins] 35 | 36 | # import plugins using Maven coordinates (see above), not the Gradle plugin ID 37 | -------------------------------------------------------------------------------- /kopykat-ksp/src/main/kotlin/at/kopyk/CopyMap.kt: -------------------------------------------------------------------------------- 1 | package at.kopyk 2 | 3 | import at.kopyk.poet.addParameter 4 | import at.kopyk.poet.addReturn 5 | import at.kopyk.poet.append 6 | import at.kopyk.poet.asTransformLambda 7 | import at.kopyk.utils.TypeCategory.Known.Data 8 | import at.kopyk.utils.TypeCategory.Known.Sealed 9 | import at.kopyk.utils.TypeCategory.Known.Value 10 | import at.kopyk.utils.TypeCompileScope 11 | import at.kopyk.utils.addGeneratedMarker 12 | import at.kopyk.utils.baseName 13 | import at.kopyk.utils.fullName 14 | import at.kopyk.utils.lang.joinWithWhen 15 | import at.kopyk.utils.lang.mapRun 16 | import at.kopyk.utils.lang.onEachRun 17 | import at.kopyk.utils.typeCategory 18 | import com.squareup.kotlinpoet.FileSpec 19 | import com.squareup.kotlinpoet.ksp.toKModifier 20 | 21 | internal val TypeCompileScope.copyMapFunctionKt: FileSpec 22 | get() = 23 | buildFile(fileName = target.append("CopyMap").reflectionName()) { 24 | val parameterized = target.parameterized 25 | addGeneratedMarker() 26 | addInlinedFunction(name = "copyMap", receives = parameterized, returns = parameterized) { 27 | visibility.toKModifier()?.let { addModifiers(it) } 28 | properties 29 | .onEachRun { 30 | addParameter( 31 | name = baseName, 32 | type = typeName.asTransformLambda(receiver = parameterized), 33 | defaultValue = "{ it }", 34 | ) 35 | } 36 | .mapRun { "$baseName = $baseName(this, this.$baseName)" } 37 | .run { addReturn(repeatOnSubclasses(joinToString(), "copy")) } 38 | } 39 | } 40 | 41 | private fun TypeCompileScope.repeatOnSubclasses( 42 | line: String, 43 | functionName: String, 44 | ): String = 45 | when (typeCategory) { 46 | Value -> "$fullName($line)" 47 | Data -> "$functionName($line)" 48 | Sealed -> sealedTypes.joinWithWhen { "is ${it.fullName} -> $functionName($line)" } 49 | else -> error("Unknown type category for ${target.canonicalName}") 50 | } 51 | -------------------------------------------------------------------------------- /kopykat-ksp/src/main/kotlin/at/kopyk/KopyKatOptions.kt: -------------------------------------------------------------------------------- 1 | package at.kopyk 2 | 3 | import com.google.devtools.ksp.processing.KSPLogger 4 | 5 | internal sealed interface KopyKatGenerate { 6 | data object Error : KopyKatGenerate 7 | 8 | data object Annotated : KopyKatGenerate 9 | 10 | sealed interface NotAnnotated : KopyKatGenerate 11 | 12 | data object All : NotAnnotated 13 | 14 | data class Packages(val patterns: List) : NotAnnotated 15 | 16 | companion object { 17 | const val ALL = "all" 18 | const val ANNOTATED = "annotated" 19 | const val PACKAGES_PREFIX = "packages" 20 | 21 | fun fromKspOptions( 22 | logger: KSPLogger, 23 | generate: String?, 24 | ): KopyKatGenerate = 25 | when { 26 | generate == null -> All 27 | generate == ALL -> All 28 | generate == ANNOTATED -> Annotated 29 | generate.startsWith(PACKAGES_PREFIX) -> 30 | Packages(generate.split(':').drop(1)) 31 | else -> { 32 | logger.error("Unrecognized value for 'generate'", null) 33 | Error // return something, although the error is reported 34 | } 35 | } 36 | } 37 | } 38 | 39 | internal data class KopyKatOptions( 40 | val copyMap: Boolean, 41 | val mutableCopy: Boolean, 42 | val hierarchyCopy: Boolean, 43 | val generate: KopyKatGenerate, 44 | ) 45 | 46 | @Suppress("FunctionName") 47 | internal fun KopyKatOptions( 48 | logger: KSPLogger, 49 | options: Map, 50 | ) = KopyKatOptions( 51 | copyMap = options.parseBoolOrTrue(COPY_MAP), 52 | mutableCopy = options.parseBoolOrTrue(MUTABLE_COPY), 53 | hierarchyCopy = options.parseBoolOrTrue(HIERARCHY_COPY), 54 | generate = KopyKatGenerate.fromKspOptions(logger, options[GENERATE]), 55 | ) 56 | 57 | private const val COPY_MAP = "copyMap" 58 | private const val MUTABLE_COPY = "mutableCopy" 59 | private const val HIERARCHY_COPY = "hierarchyCopy" 60 | private const val GENERATE = "generate" 61 | 62 | private fun Map.parseBoolOrTrue(key: String) = this[key]?.lowercase()?.toBooleanStrictOrNull() ?: true 63 | -------------------------------------------------------------------------------- /docs/mutable-utils/scripts/clipboard.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014-2023 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. 3 | */ 4 | 5 | window.addEventListener('load', () => { 6 | document.querySelectorAll('span.copy-icon').forEach(element => { 7 | element.addEventListener('click', (el) => copyElementsContentToClipboard(element)); 8 | }) 9 | 10 | document.querySelectorAll('span.anchor-icon').forEach(element => { 11 | element.addEventListener('click', (el) => { 12 | if(element.hasAttribute('pointing-to')){ 13 | const location = hrefWithoutCurrentlyUsedAnchor() + '#' + element.getAttribute('pointing-to') 14 | copyTextToClipboard(element, location) 15 | } 16 | }); 17 | }) 18 | }) 19 | 20 | const copyElementsContentToClipboard = (element) => { 21 | const selection = window.getSelection(); 22 | const range = document.createRange(); 23 | range.selectNodeContents(element.parentNode.parentNode); 24 | selection.removeAllRanges(); 25 | selection.addRange(range); 26 | 27 | copyAndShowPopup(element, () => selection.removeAllRanges()) 28 | } 29 | 30 | const copyTextToClipboard = (element, text) => { 31 | var textarea = document.createElement("textarea"); 32 | textarea.textContent = text; 33 | textarea.style.position = "fixed"; 34 | document.body.appendChild(textarea); 35 | textarea.select(); 36 | 37 | copyAndShowPopup(element, () => document.body.removeChild(textarea)) 38 | } 39 | 40 | const copyAndShowPopup = (element, after) => { 41 | try { 42 | document.execCommand('copy'); 43 | element.nextElementSibling.classList.add('active-popup'); 44 | setTimeout(() => { 45 | element.nextElementSibling.classList.remove('active-popup'); 46 | }, 1200); 47 | } catch (e) { 48 | console.error('Failed to write to clipboard:', e) 49 | } 50 | finally { 51 | if(after) after() 52 | } 53 | } 54 | 55 | const hrefWithoutCurrentlyUsedAnchor = () => window.location.href.split('#')[0] 56 | 57 | -------------------------------------------------------------------------------- /kopykat-ksp/src/test/kotlin/at/kopyk/CopyFromParentTest.kt: -------------------------------------------------------------------------------- 1 | package at.kopyk 2 | 3 | import org.junit.jupiter.api.Test 4 | 5 | class CopyFromParentTest { 6 | @Test 7 | fun `simple test`() { 8 | """ 9 | |import at.kopyk.CopyFrom 10 | | 11 | |interface Person { 12 | | val name: String 13 | | val age: Int 14 | |} 15 | | 16 | |@CopyFrom(Person::class) 17 | |data class Person1(override val name: String, override val age: Int): Person 18 | | 19 | |@CopyFrom(Person::class) 20 | |data class Person2(override val name: String, override val age: Int): Person 21 | | 22 | |val p1 = Person1("Alex", 1) 23 | |val p2 = Person2(p1) 24 | |val r = p2.age 25 | """.evals("r" to 1) 26 | } 27 | 28 | @Test 29 | fun `simple test, non-data class`() { 30 | """ 31 | |import at.kopyk.CopyFrom 32 | | 33 | |interface Person { 34 | | val name: String 35 | | val age: Int 36 | |} 37 | | 38 | |@CopyFrom(Person::class) 39 | |class Person1(override val name: String, override val age: Int): Person 40 | | 41 | |@CopyFrom(Person::class) 42 | |data class Person2(override val name: String, override val age: Int): Person 43 | | 44 | |val p1 = Person1("Alex", 1) 45 | |val p2 = Person2(p1) 46 | |val r = p2.age 47 | """.evals("r" to 1) 48 | } 49 | 50 | @Test 51 | fun `missing field should not create`() { 52 | """ 53 | |import at.kopyk.CopyFrom 54 | | 55 | |interface Person { 56 | | val name: String 57 | |} 58 | | 59 | |@CopyFrom(Person::class) 60 | |data class Person1(override val name: String, val age: Int): Person 61 | | 62 | |@CopyFrom(Person::class) 63 | |data class Person2(override val name: String, val age: Int): Person 64 | | 65 | |val p1 = Person1("Alex", 1) 66 | |val p2 = Person2(p1) 67 | |val r = p2.age 68 | """.failsWith { 69 | it.contains("Person1 must have the same constructor properties as Person") 70 | it.contains("Person2 must have the same constructor properties as Person") 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /kopykat-ksp/src/main/kotlin/at/kopyk/utils/TypeSubstitution.kt: -------------------------------------------------------------------------------- 1 | package at.kopyk.utils 2 | 3 | import com.google.devtools.ksp.symbol.KSClassDeclaration 4 | import com.google.devtools.ksp.symbol.KSName 5 | import com.google.devtools.ksp.symbol.KSReferenceElement 6 | import com.google.devtools.ksp.symbol.KSType 7 | import com.google.devtools.ksp.symbol.KSTypeAlias 8 | import com.google.devtools.ksp.symbol.KSTypeArgument 9 | import com.google.devtools.ksp.symbol.KSTypeParameter 10 | import com.google.devtools.ksp.symbol.KSTypeReference 11 | import com.google.devtools.ksp.symbol.Variance 12 | 13 | internal typealias TypeSubstitution = Map 14 | 15 | /** 16 | * This function needs to "jump" across type aliases 17 | * to get the type parameters applied to the "real" type 18 | */ 19 | internal fun KSTypeAlias.unravelTypeParameters(): TypeSubstitution { 20 | val resolvedType = type.resolve() // this is expensive, we don't want to do it twice 21 | return when (val resolvedDeclaration = resolvedType.declaration) { 22 | is KSClassDeclaration -> { 23 | val typeParameterNames = resolvedDeclaration.typeParameters.map { it.name } 24 | val typeArguments = resolvedType.arguments.map { it.type?.resolve() } 25 | // keep only those type parameters for which we know the substituted type 26 | typeParameterNames.zip(typeArguments) { typeParamName, typeArgument -> 27 | typeArgument?.let { typeParamName to it } 28 | }.filterNotNull().toMap() 29 | } 30 | // implement for type aliases referencing other aliases 31 | else -> emptyMap() 32 | } 33 | } 34 | 35 | internal fun KSType.substitute(subst: TypeSubstitution): KSType = 36 | when (val declaration = declaration) { 37 | is KSTypeParameter -> subst[declaration.name] ?: this 38 | else -> replace(arguments.map { it.substitute(subst) }) 39 | } 40 | 41 | internal fun KSTypeArgument.substitute(subst: TypeSubstitution): KSTypeArgument { 42 | val previous: KSTypeArgument = this 43 | return object : KSTypeArgument by previous { 44 | override val variance = Variance.INVARIANT 45 | override val type = previous.type?.substitute(subst) 46 | } 47 | } 48 | 49 | internal fun KSTypeReference.substitute(subst: TypeSubstitution): KSTypeReference { 50 | val previous: KSTypeReference = this 51 | return object : KSTypeReference by previous { 52 | override val element: KSReferenceElement? = null 53 | 54 | override fun resolve(): KSType = previous.resolve().substitute(subst) 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /kopykat-ksp/src/main/kotlin/at/kopyk/utils/TypeCategory.kt: -------------------------------------------------------------------------------- 1 | package at.kopyk.utils 2 | 3 | import at.kopyk.utils.TypeCategory.Known 4 | import at.kopyk.utils.TypeCategory.Unknown 5 | import com.google.devtools.ksp.isAbstract 6 | import com.google.devtools.ksp.isPublic 7 | import com.google.devtools.ksp.symbol.KSClassDeclaration 8 | import com.google.devtools.ksp.symbol.KSDeclaration 9 | import com.google.devtools.ksp.symbol.KSTypeAlias 10 | import com.google.devtools.ksp.symbol.Modifier 11 | import com.google.devtools.ksp.symbol.Modifier.SEALED 12 | 13 | internal val KSDeclaration.typeCategory: TypeCategory 14 | get() = 15 | when (this) { 16 | is KSTypeAlias -> 17 | when (val result = type.resolve().declaration.typeCategory) { 18 | is Unknown -> Unknown(this) 19 | else -> result 20 | } 21 | is KSClassDeclaration -> 22 | when { 23 | isDataClass() -> Known.Data 24 | isValueClass() -> Known.Value 25 | isSealedDataHierarchy() -> Known.Sealed 26 | isConstructable() -> Known.Class 27 | else -> Unknown(this) 28 | } 29 | else -> Unknown(this) 30 | } 31 | 32 | internal val KSTypeAlias.ultimateDeclaration: KSClassDeclaration? get() = 33 | when (val oneStep = type.resolve().declaration) { 34 | is KSClassDeclaration -> oneStep 35 | is KSTypeAlias -> oneStep.ultimateDeclaration 36 | else -> null 37 | } 38 | 39 | internal inline fun TypeCompileScope.onKnownCategory(block: (Known) -> Unit) { 40 | (typeCategory as? Known)?.apply(block) ?: logger.error("Type $fullName is not supported by KopyKat") 41 | } 42 | 43 | internal sealed interface TypeCategory { 44 | sealed interface Known : TypeCategory { 45 | object Sealed : Known 46 | 47 | object Value : Known 48 | 49 | object Data : Known 50 | 51 | object Class : Known 52 | } 53 | 54 | @JvmInline value class Unknown(val original: KSDeclaration) : TypeCategory 55 | } 56 | 57 | internal fun KSClassDeclaration.isConstructable() = primaryConstructor?.isPublic() == true 58 | 59 | private fun KSClassDeclaration.isDataClass() = isConstructable() && Modifier.DATA in modifiers 60 | 61 | private fun KSClassDeclaration.isValueClass() = isConstructable() && Modifier.VALUE in modifiers 62 | 63 | private fun KSClassDeclaration.isSealedDataHierarchy() = SEALED in modifiers && isAbstract() && hasOnlyDataClassChildren() 64 | 65 | private fun KSClassDeclaration.hasOnlyDataClassChildren() = sealedTypes.any() && sealedTypes.all { it.isDataClass() || it.isValueClass() } 66 | -------------------------------------------------------------------------------- /kopykat-ksp/src/main/kotlin/at/kopyk/KopyKatProcessor.kt: -------------------------------------------------------------------------------- 1 | package at.kopyk 2 | 3 | import at.kopyk.utils.TypeCategory.Known.Data 4 | import at.kopyk.utils.TypeCategory.Known.Sealed 5 | import at.kopyk.utils.TypeCategory.Known.Value 6 | import at.kopyk.utils.TypeCompileScope 7 | import at.kopyk.utils.hasAnnotation 8 | import at.kopyk.utils.lang.filterIsInstance 9 | import at.kopyk.utils.lang.flatMapRun 10 | import at.kopyk.utils.lang.forEachRun 11 | import at.kopyk.utils.lang.mapRun 12 | import at.kopyk.utils.lang.onEachRun 13 | import at.kopyk.utils.typeCategory 14 | import com.google.devtools.ksp.processing.KSPLogger 15 | import com.google.devtools.ksp.processing.Resolver 16 | import com.google.devtools.ksp.processing.SymbolProcessor 17 | import com.google.devtools.ksp.processing.SymbolProcessorEnvironment 18 | import com.google.devtools.ksp.symbol.KSAnnotated 19 | import com.google.devtools.ksp.symbol.KSClassDeclaration 20 | 21 | internal interface LoggerScope { 22 | val logger: KSPLogger 23 | } 24 | 25 | internal interface OptionsScope { 26 | val options: KopyKatOptions 27 | } 28 | 29 | internal class ProcessorScope( 30 | environment: SymbolProcessorEnvironment, 31 | ) : LoggerScope, OptionsScope { 32 | val codegen = environment.codeGenerator 33 | override val logger = environment.logger 34 | override val options = KopyKatOptions(environment.logger, environment.options) 35 | } 36 | 37 | internal class KopyKatProcessor( 38 | private val scope: ProcessorScope, 39 | ) : SymbolProcessor { 40 | override fun process(resolver: Resolver): List { 41 | scope.processFiles(resolver) { 42 | // add copy functions for data, value classes, and type aliases 43 | if (options.copyMap || options.mutableCopy) { 44 | (classes.mapRun { classScope } + typeAliases.mapRun { typealiasScope }) 45 | .filter { it.canHaveCopyFunctions(options.hierarchyCopy) } 46 | .onEachRun { logger.logging("Processing ${simpleName.asString()}") } 47 | .forEachRun { 48 | if (options.copyMap) copyMapFunctionKt.write() 49 | if (options.mutableCopy) mutableCopyKt.write() 50 | } 51 | } 52 | // add isomorphic copies 53 | declarations 54 | .filterIsInstance { hasCopyAnnotation() } 55 | .flatMapRun { classScope.allCopies } 56 | .distinctBy { it.name } 57 | .let { others -> others.mapNotNull { fileSpec(others, it) } } 58 | .forEachRun { write() } 59 | } 60 | return emptyList() 61 | } 62 | 63 | private fun TypeCompileScope.canHaveCopyFunctions(hierarchyCopy: Boolean) = 64 | typeCategory in listOf(Data, Value) || typeCategory is Sealed && hierarchyCopy 65 | } 66 | 67 | private fun KSClassDeclaration.hasCopyAnnotation() = hasAnnotation() || hasAnnotation() || hasAnnotation() 68 | -------------------------------------------------------------------------------- /.github/workflows/pull_request.yml: -------------------------------------------------------------------------------- 1 | name: "pull_request" 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | branches: 9 | - main 10 | 11 | 12 | env: 13 | GRADLE_OPTS: -Dorg.gradle.daemon=false -Dorg.gradle.parallel=false -Dorg.gradle.jvmargs="-Xmx5g -XX:+UseParallelGC -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8" 14 | 15 | jobs: 16 | build: 17 | runs-on: ${{ matrix.os }} 18 | 19 | strategy: 20 | matrix: 21 | os: [ 'macos-latest', 'ubuntu-latest', 'windows-latest' ] 22 | 23 | steps: 24 | - name: Checkout 25 | uses: actions/checkout@v4 26 | with: 27 | fetch-depth: 0 28 | 29 | - name: Set up Java 30 | uses: actions/setup-java@v4 31 | with: 32 | distribution: 'temurin' 33 | java-version: 17 34 | 35 | - name: build 36 | uses: gradle/gradle-build-action@v2 37 | with: 38 | arguments: --full-stacktrace build 39 | 40 | - name: Upload reports 41 | uses: actions/upload-artifact@v4 42 | with: 43 | name: 'reports-${{ matrix.os }}' 44 | path: '**/build/reports/**' 45 | 46 | - name: Stop Gradle daemons 47 | run: ./gradlew --stop 48 | 49 | ktlint: 50 | runs-on: ubuntu-latest 51 | timeout-minutes: 60 52 | 53 | steps: 54 | - uses: actions/checkout@v4 55 | with: 56 | fetch-depth: 0 57 | 58 | - name: Set up Java 59 | uses: actions/setup-java@v4 60 | with: 61 | distribution: 'temurin' 62 | java-version: 17 63 | 64 | - name: Format 65 | uses: gradle/gradle-build-action@v2 66 | with: 67 | arguments: ktlintFormat 68 | 69 | - name: Stop Gradle daemons 70 | run: ./gradlew --stop 71 | 72 | - name: "Commit formatted files" 73 | uses: stefanzweifel/git-auto-commit-action@v5 74 | with: 75 | commit_message: Format files using ktlint 76 | file_pattern: "**/*.kt" 77 | 78 | update-docs: 79 | runs-on: ubuntu-latest 80 | timeout-minutes: 60 81 | 82 | steps: 83 | - uses: actions/checkout@v4 84 | with: 85 | fetch-depth: 0 86 | 87 | - name: Set up Java 88 | uses: actions/setup-java@v4 89 | with: 90 | distribution: 'temurin' 91 | java-version: 17 92 | 93 | - name: Checkout 94 | run: rm -rf docs 95 | 96 | - name: Format 97 | uses: gradle/gradle-build-action@v2 98 | with: 99 | arguments: :mutable-utils:dokkaHtml 100 | 101 | - name: Stop Gradle daemons 102 | run: ./gradlew --stop 103 | 104 | - name: "Commit formatted files" 105 | uses: stefanzweifel/git-auto-commit-action@v5 106 | with: 107 | commit_message: Update documentation 108 | file_pattern: "docs/*" 109 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by https://www.gitignore.io/api/android,intellij 2 | 3 | ### Android ### 4 | # Built application files 5 | *.apk 6 | *.ap_ 7 | 8 | # Files for the ART/Dalvik VM 9 | *.dex 10 | 11 | # Java class files 12 | *.class 13 | 14 | # Generated files 15 | bin/ 16 | gen/ 17 | out/ 18 | 19 | # Gradle files 20 | .gradle/ 21 | build/ 22 | 23 | # dokka + ank apidocs merge to sources 24 | apidocs/ 25 | 26 | # Local configuration file (sdk path, etc) 27 | local.properties 28 | 29 | # Proguard folder generated by Eclipse 30 | proguard/ 31 | 32 | # Log Files 33 | *.log 34 | 35 | # Android Studio Navigation editor temp files 36 | .navigation/ 37 | 38 | # Android Studio captures folder 39 | captures/ 40 | 41 | # Intellij 42 | *.iml 43 | .idea/* 44 | !.idea/vcs.xml 45 | 46 | # Keystore files 47 | *.jks 48 | 49 | # External native build folder generated in Android Studio 2.2 and later 50 | .externalNativeBuild 51 | 52 | # Google Services (e.g. APIs or Firebase) 53 | google-services.json 54 | 55 | # Freeline 56 | freeline.py 57 | freeline/ 58 | freeline_project_description.json 59 | 60 | ### Android Patch ### 61 | gen-external-apklibs 62 | 63 | ### Intellij ### 64 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm 65 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 66 | 67 | # User-specific stuff: 68 | .idea/**/workspace.xml 69 | .idea/**/tasks.xml 70 | 71 | # Sensitive or high-churn files: 72 | .idea/**/dataSources/ 73 | .idea/**/dataSources.ids 74 | .idea/**/dataSources.xml 75 | .idea/**/dataSources.local.xml 76 | .idea/**/sqlDataSources.xml 77 | .idea/**/dynamic.xml 78 | .idea/**/uiDesigner.xml 79 | 80 | # Gradle: 81 | .idea/**/gradle.xml 82 | .idea/**/libraries 83 | 84 | #Kotlintest 85 | **/.kotlintest 86 | 87 | # Mongo Explorer plugin: 88 | .idea/**/mongoSettings.xml 89 | 90 | ## File-based project format: 91 | *.iws 92 | 93 | ## Plugin-specific files: 94 | 95 | # IntelliJ 96 | /out/ 97 | 98 | # mpeltonen/sbt-idea plugin 99 | .idea_modules/ 100 | 101 | # JIRA plugin 102 | atlassian-ide-plugin.xml 103 | 104 | # Crashlytics plugin (for Android Studio and IntelliJ) 105 | com_crashlytics_export_strings.xml 106 | crashlytics.properties 107 | crashlytics-build.properties 108 | fabric.properties 109 | 110 | # Jekyll 111 | _site 112 | .sass-cache 113 | vendor 114 | .bundle 115 | 116 | # Ruby 117 | Gemfile.lock 118 | 119 | ### Intellij Patch ### 120 | # Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 121 | 122 | # *.iml 123 | # modules.xml 124 | # .idea/misc.xml 125 | # *.ipr 126 | 127 | ###################### 128 | 129 | reports/ 130 | 131 | # End of https://www.gitignore.io/api/android,intellij 132 | /.idea/misc.xml 133 | 134 | .DS_Store 135 | 136 | target/ 137 | 138 | .bash_profile 139 | **/.kotlintest/ 140 | 141 | 142 | _site/ 143 | .sass-cache/ 144 | .jekyll-cache/ 145 | .jekyll-metadata 146 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /docs/mutable-utils/scripts/symbol-parameters-wrapper_deferred.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014-2023 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. 3 | */ 4 | 5 | // helps with some corner cases where starts working already, 6 | // but the signature is not yet long enough to be wrapped 7 | (function() { 8 | const leftPaddingPx = 60; 9 | 10 | function createNbspIndent() { 11 | let indent = document.createElement("span"); 12 | indent.append(document.createTextNode("\u00A0\u00A0\u00A0\u00A0")); 13 | indent.classList.add("nbsp-indent"); 14 | return indent; 15 | } 16 | 17 | function wrapSymbolParameters(entry) { 18 | const symbol = entry.target; 19 | const symbolBlockWidth = entry.borderBoxSize && entry.borderBoxSize[0] && entry.borderBoxSize[0].inlineSize; 20 | 21 | // Even though the script is marked as `defer` and we wait for `DOMContentLoaded` event, 22 | // or if this block is a part of hidden tab, it can happen that `symbolBlockWidth` is 0, 23 | // indicating that something hasn't been loaded. 24 | // In this case, observer will be triggered onсe again when it will be ready. 25 | if (symbolBlockWidth > 0) { 26 | const node = symbol.querySelector(".parameters"); 27 | 28 | if (node) { 29 | // if window resize happened and observer was triggered, reset previously wrapped 30 | // parameters as they might not need wrapping anymore, and check again 31 | node.classList.remove("wrapped"); 32 | node.querySelectorAll(".parameter .nbsp-indent") 33 | .forEach(indent => indent.remove()); 34 | 35 | const innerTextWidth = Array.from(symbol.children) 36 | .filter(it => !it.classList.contains("block")) // blocks are usually on their own (like annotations), so ignore it 37 | .map(it => it.getBoundingClientRect().width) 38 | .reduce((a, b) => a + b, 0); 39 | 40 | // if signature text takes up more than a single line, wrap params for readability 41 | if (innerTextWidth > (symbolBlockWidth - leftPaddingPx)) { 42 | node.classList.add("wrapped"); 43 | node.querySelectorAll(".parameter").forEach(param => { 44 | // has to be a physical indent so that it can be copied. styles like 45 | // paddings and `::before { content: " " }` do not work for that 46 | param.prepend(createNbspIndent()); 47 | }); 48 | } 49 | } 50 | } 51 | } 52 | 53 | const symbolsObserver = new ResizeObserver(entries => entries.forEach(wrapSymbolParameters)); 54 | 55 | function initHandlers() { 56 | document.querySelectorAll("div.symbol").forEach(symbol => symbolsObserver.observe(symbol)); 57 | } 58 | 59 | if (document.readyState === 'loading') window.addEventListener('DOMContentLoaded', initHandlers); 60 | else initHandlers(); 61 | 62 | // ToDo: Add `unobserve` if dokka will be SPA-like: 63 | // https://github.com/w3c/csswg-drafts/issues/5155 64 | })(); 65 | -------------------------------------------------------------------------------- /kopykat-ksp/src/main/kotlin/at/kopyk/utils/KspExtensions.kt: -------------------------------------------------------------------------------- 1 | package at.kopyk.utils 2 | 3 | import com.google.devtools.ksp.symbol.KSClassDeclaration 4 | import com.google.devtools.ksp.symbol.KSDeclaration 5 | import com.google.devtools.ksp.symbol.KSDeclarationContainer 6 | import com.google.devtools.ksp.symbol.KSPropertyDeclaration 7 | 8 | internal val KSDeclaration.baseName: String 9 | get() = simpleName.asString().sanitize() 10 | 11 | internal val KSDeclaration.fullName: String 12 | get() = qualifiedName?.asString() ?: simpleName.asString() 13 | 14 | internal val KSClassDeclaration.sealedTypes get() = getSealedSubclasses() 15 | 16 | internal fun KSDeclarationContainer.allNestedDeclarations(): Sequence = 17 | declarations + 18 | declarations 19 | .filterIsInstance() 20 | .flatMap { it.allNestedDeclarations() } 21 | 22 | /** 23 | * Obtains those properties which are defined in the primary constructor, 24 | * or in every primary constructor of their children. 25 | */ 26 | internal fun KSClassDeclaration.getPrimaryConstructorProperties() = 27 | getAllProperties().filter { property -> 28 | hasPrimaryProperty(property) || (sealedTypes.any() && sealedTypes.all { it.hasPrimaryProperty(property) }) 29 | } 30 | 31 | private fun KSClassDeclaration.hasPrimaryProperty(property: KSPropertyDeclaration) = 32 | primaryConstructor?.parameters.orEmpty().any { param -> 33 | (param.isVal || param.isVar) && param.name?.asString() == property.baseName 34 | } 35 | 36 | /** 37 | * Sanitizes each delimited section if it matches with Kotlin reserved keywords. 38 | */ 39 | private fun String.sanitize( 40 | delimiter: String = ".", 41 | prefix: String = "", 42 | ) = splitToSequence(delimiter).joinToString(delimiter, prefix) { if (it in KOTLIN_KEYWORDS) "`$it`" else it } 43 | 44 | private val KOTLIN_KEYWORDS = 45 | setOf( 46 | // Hard keywords 47 | "as", 48 | "break", 49 | "class", 50 | "continue", 51 | "do", 52 | "else", 53 | "false", 54 | "for", 55 | "fun", 56 | "if", 57 | "in", 58 | "interface", 59 | "is", 60 | "null", 61 | "object", 62 | "package", 63 | "return", 64 | "super", 65 | "this", 66 | "throw", 67 | "true", 68 | "try", 69 | "typealias", 70 | "typeof", 71 | "val", 72 | "var", 73 | "when", 74 | "while", 75 | // Soft keywords 76 | "by", 77 | "catch", 78 | "constructor", 79 | "delegate", 80 | "dynamic", 81 | "field", 82 | "file", 83 | "finally", 84 | "get", 85 | "import", 86 | "init", 87 | "param", 88 | "property", 89 | "receiver", 90 | "set", 91 | "setparam", 92 | "where", 93 | // Modifier keywords 94 | "actual", 95 | "abstract", 96 | "annotation", 97 | "companion", 98 | "const", 99 | "crossinline", 100 | "data", 101 | "enum", 102 | "expect", 103 | "external", 104 | "final", 105 | "infix", 106 | "inline", 107 | "inner", 108 | "internal", 109 | "lateinit", 110 | "noinline", 111 | "open", 112 | "operator", 113 | "out", 114 | "override", 115 | "private", 116 | "protected", 117 | "public", 118 | "reified", 119 | "sealed", 120 | "suspend", 121 | "tailrec", 122 | "value", 123 | "vararg", 124 | // These aren't keywords anymore but still break some code if unescaped. 125 | // https://youtrack.jetbrains.com/issue/KT-52315 126 | "header", 127 | "impl", 128 | // Other reserved keywords 129 | "yield", 130 | ) 131 | -------------------------------------------------------------------------------- /kopykat-ksp/src/test/kotlin/at/kopyk/HierarchyCopyTest.kt: -------------------------------------------------------------------------------- 1 | package at.kopyk 2 | 3 | import org.junit.jupiter.api.Test 4 | 5 | class HierarchyCopyTest { 6 | @Test 7 | fun `open property`() { 8 | """ 9 | |sealed abstract class User(open val name: String) 10 | |data class Person(override val name: String, val age: Int): User(name) 11 | |data class Company(override val name: String, val address: String): User(name) 12 | | 13 | |val p1: User = Person("Alex", 1) 14 | |val p2 = p1.copy(name = "Pepe") 15 | |val r = (p2 as Person).name 16 | """.evals("r" to "Pepe") 17 | } 18 | 19 | @Test 20 | fun `open property, nested`() { 21 | """ 22 | |sealed abstract class User(open val name: String) { 23 | | data class Person(override val name: String, val age: Int): User(name) 24 | | data class Company(override val name: String, val address: String): User(name) 25 | |} 26 | | 27 | |val p1: User = User.Person("Alex", 1) 28 | |val p2 = p1.copy(name = "Pepe") 29 | |val r = (p2 as User.Person).name 30 | """.evals("r" to "Pepe") 31 | } 32 | 33 | @Test 34 | fun `abstract property`() { 35 | """ 36 | |sealed abstract class User { 37 | | abstract val name: String 38 | | abstract val other: Int 39 | |} 40 | |data class Person(override val name: String, val age: Int): User() { 41 | | override val other = 1 42 | |} 43 | |data class Company(override val name: String, val address: String): User() { 44 | | override val other = 2 45 | |} 46 | | 47 | |val p1: User = Person("Alex", 1) 48 | |val p2 = p1.copy(name = "Pepe") 49 | |val r = (p2 as Person).name 50 | """.evals("r" to "Pepe") 51 | } 52 | 53 | @Test 54 | fun `interface`() { 55 | """ 56 | |sealed interface User { 57 | | val name: String 58 | |} 59 | |data class Person(override val name: String, val age: Int): User 60 | |data class Company(override val name: String, val address: String): User 61 | | 62 | |val p1: User = Person("Alex", 1) 63 | |val p2 = p1.copy(name = "Pepe") 64 | |val r = (p2 as Person).name 65 | """.evals("r" to "Pepe") 66 | } 67 | 68 | @Test 69 | fun `open property, mutable`() { 70 | """ 71 | |sealed abstract class User(open val name: String) 72 | |data class Person(override val name: String, val age: Int): User(name) 73 | |data class Company(override val name: String, val address: String): User(name) 74 | | 75 | |val p1: User = Person("Alex", 1) 76 | |val p2 = p1.copy { name = "Pepe" } 77 | |val r = (p2 as Person).name 78 | """.evals("r" to "Pepe") 79 | } 80 | 81 | @Test 82 | fun `open property, mapping`() { 83 | """ 84 | |sealed abstract class User(open val name: String) 85 | |data class Person(override val name: String, val age: Int): User(name) 86 | |data class Company(override val name: String, val address: String): User(name) 87 | | 88 | |val p1: User = Person("Alex", 1) 89 | |val p2 = p1.copyMap(name = { it.lowercase() }) 90 | |val r = (p2 as Person).name 91 | """.evals("r" to "alex") 92 | } 93 | 94 | @Test 95 | fun `field which is not everywhere`() { 96 | """ 97 | |sealed abstract class User(open val name: String) 98 | |data class Person(override val name: String, val age: Int): User(name) 99 | |data class Company(override val name: String, val address: String): User(name) 100 | | 101 | |val p1: User = Person("Alex", 1) 102 | |val p2 = p1.copy(age = 2) 103 | """.failsWith { 104 | it.contains("Cannot find a parameter with this name: age") 105 | } 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /kopykat-ksp/src/test/kotlin/at/kopyk/AnnotationTest.kt: -------------------------------------------------------------------------------- 1 | package at.kopyk 2 | 3 | import org.junit.jupiter.api.Test 4 | 5 | class AnnotationTest { 6 | @Test 7 | fun `generates with annotation`() { 8 | """ 9 | |import at.kopyk.CopyExtensions 10 | | 11 | |@CopyExtensions 12 | |data class Person(val name: String, val age: Int) 13 | | 14 | |val p1 = Person("Alex", 1) 15 | |val p2 = p1.copyMap(age = { it + 1 }) 16 | |val r = p2.age 17 | """.evalsWithArgs(mapOf("generate" to KopyKatGenerate.ANNOTATED), "r" to 2) 18 | } 19 | 20 | @Test 21 | fun `doesn't generate without annotation`() { 22 | """ 23 | |data class Person(val name: String, val age: Int) 24 | | 25 | |val p1 = Person("Alex", 1) 26 | |val p2 = p1.copyMap(age = { it + 1 }) 27 | |val r = p2.age 28 | """.failsWith(mapOf("generate" to KopyKatGenerate.ANNOTATED)) { 29 | it.contains("Unresolved reference: copyMap") 30 | } 31 | } 32 | 33 | @Test 34 | fun `warning for unused annotation, implicit generateAll`() { 35 | """ 36 | |import at.kopyk.CopyExtensions 37 | | 38 | |@CopyExtensions 39 | |data class Person(val name: String, val age: Int) 40 | | 41 | |val p1 = Person("Alex", 1) 42 | |val p2 = p1.copyMap(age = { it + 1 }) 43 | |val r = p2.age 44 | """.compilesWith { 45 | it.contains("Unused '@CopyExtensions' annotation") 46 | } 47 | } 48 | 49 | @Test 50 | fun `warning for unused annotation, explicit generateAll`() { 51 | """ 52 | |import at.kopyk.CopyExtensions 53 | | 54 | |@CopyExtensions 55 | |data class Person(val name: String, val age: Int) 56 | | 57 | |val p1 = Person("Alex", 1) 58 | |val p2 = p1.copyMap(age = { it + 1 }) 59 | |val r = p2.age 60 | """.compilesWith(mapOf("generate" to KopyKatGenerate.ALL)) { 61 | it.contains("Unused '@CopyExtensions' annotation") 62 | } 63 | } 64 | 65 | @Test 66 | fun `warning for application to non-data class`() { 67 | """ 68 | |import at.kopyk.CopyExtensions 69 | | 70 | |@CopyExtensions 71 | |class Person(val name: String, val age: Int) 72 | """.failsWith { 73 | it.contains("'@CopyExtensions' may only be used") 74 | } 75 | } 76 | 77 | @Test 78 | fun `generates in the given package`() { 79 | """ 80 | |package A 81 | | 82 | |data class Person(val name: String, val age: Int) 83 | | 84 | |val p1 = Person("Alex", 1) 85 | |val p2 = p1.copyMap(age = { it + 1 }) 86 | |val r = p2.age 87 | """.failsWith( 88 | mapOf("generate" to "${KopyKatGenerate.PACKAGES_PREFIX}A"), 89 | ) { 90 | it.contains("Unresolved reference: copyMap") 91 | } 92 | } 93 | 94 | @Test 95 | fun `generates in the given package, pattern`() { 96 | """ 97 | |package A 98 | | 99 | |data class Person(val name: String, val age: Int) 100 | | 101 | |val p1 = Person("Alex", 1) 102 | |val p2 = p1.copyMap(age = { it + 1 }) 103 | |val r = p2.age 104 | """.failsWith( 105 | mapOf("generate" to "${KopyKatGenerate.PACKAGES_PREFIX}?"), 106 | ) { 107 | it.contains("Unresolved reference: copyMap") 108 | } 109 | } 110 | 111 | @Test 112 | fun `doesn't generate in other package`() { 113 | """ 114 | |package B 115 | | 116 | |data class Person(val name: String, val age: Int) 117 | | 118 | |val p1 = Person("Alex", 1) 119 | |val p2 = p1.copyMap(age = { it + 1 }) 120 | |val r = p2.age 121 | """.failsWith( 122 | mapOf("generate" to "${KopyKatGenerate.PACKAGES_PREFIX}A"), 123 | ) { 124 | it.contains("Unresolved reference: copyMap") 125 | } 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /docs/mutable-utils/scripts/navigation-loader.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014-2023 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. 3 | */ 4 | 5 | navigationPageText = fetch(pathToRoot + "navigation.html").then(response => response.text()) 6 | 7 | displayNavigationFromPage = () => { 8 | navigationPageText.then(data => { 9 | document.getElementById("sideMenu").innerHTML = data; 10 | }).then(() => { 11 | document.querySelectorAll(".overview > a").forEach(link => { 12 | link.setAttribute("href", pathToRoot + link.getAttribute("href")); 13 | }) 14 | }).then(() => { 15 | document.querySelectorAll(".sideMenuPart").forEach(nav => { 16 | if (!nav.classList.contains("hidden")) 17 | nav.classList.add("hidden") 18 | }) 19 | }).then(() => { 20 | revealNavigationForCurrentPage() 21 | }).then(() => { 22 | scrollNavigationToSelectedElement() 23 | }) 24 | document.querySelectorAll('.footer a[href^="#"]').forEach(anchor => { 25 | anchor.addEventListener('click', function (e) { 26 | e.preventDefault(); 27 | document.querySelector(this.getAttribute('href')).scrollIntoView({ 28 | behavior: 'smooth' 29 | }); 30 | }); 31 | }); 32 | } 33 | 34 | revealNavigationForCurrentPage = () => { 35 | let pageId = document.getElementById("content").attributes["pageIds"].value.toString(); 36 | let parts = document.querySelectorAll(".sideMenuPart"); 37 | let found = 0; 38 | do { 39 | parts.forEach(part => { 40 | if (part.attributes['pageId'].value.indexOf(pageId) !== -1 && found === 0) { 41 | found = 1; 42 | if (part.classList.contains("hidden")) { 43 | part.classList.remove("hidden"); 44 | part.setAttribute('data-active', ""); 45 | } 46 | revealParents(part) 47 | } 48 | }); 49 | pageId = pageId.substring(0, pageId.lastIndexOf("/")) 50 | } while (pageId.indexOf("/") !== -1 && found === 0) 51 | }; 52 | revealParents = (part) => { 53 | if (part.classList.contains("sideMenuPart")) { 54 | if (part.classList.contains("hidden")) 55 | part.classList.remove("hidden"); 56 | revealParents(part.parentNode) 57 | } 58 | }; 59 | 60 | scrollNavigationToSelectedElement = () => { 61 | let selectedElement = document.querySelector('div.sideMenuPart[data-active]') 62 | if (selectedElement == null) { // nothing selected, probably just the main page opened 63 | return 64 | } 65 | 66 | let hasIcon = selectedElement.querySelectorAll(":scope > div.overview span.nav-icon").length > 0 67 | 68 | // for instance enums also have children and are expandable, but are not package/module elements 69 | let isPackageElement = selectedElement.children.length > 1 && !hasIcon 70 | if (isPackageElement) { 71 | // if package is selected or linked, it makes sense to align it to top 72 | // so that you can see all the members it contains 73 | selectedElement.scrollIntoView(true) 74 | } else { 75 | // if a member within a package is linked, it makes sense to center it since it, 76 | // this should make it easier to look at surrounding members 77 | selectedElement.scrollIntoView({ 78 | behavior: 'auto', 79 | block: 'center', 80 | inline: 'center' 81 | }) 82 | } 83 | } 84 | 85 | /* 86 | This is a work-around for safari being IE of our times. 87 | It doesn't fire a DOMContentLoaded, presumabely because eventListener is added after it wants to do it 88 | */ 89 | if (document.readyState == 'loading') { 90 | window.addEventListener('DOMContentLoaded', () => { 91 | displayNavigationFromPage() 92 | }) 93 | } else { 94 | displayNavigationFromPage() 95 | } 96 | -------------------------------------------------------------------------------- /docs/mutable-utils/mutable-utils/package-list: -------------------------------------------------------------------------------- 1 | $dokka.format:html-v1 2 | $dokka.linkExtension:html 3 | $dokka.location:at.kopyk////PointingToDeclaration/mutable-utils/at.kopyk/index.html 4 | $dokka.location:at.kopyk//clearThenAddAllNotNull/TypeParam(bounds=[kotlin.collections.MutableCollection[TypeParam(bounds=[kotlin.Any?])]])#kotlin.Function1[TypeParam(bounds=[kotlin.Any?]),TypeParam(bounds=[kotlin.Any?])?]/PointingToDeclaration/mutable-utils/at.kopyk/clear-then-add-all-not-null.html 5 | $dokka.location:at.kopyk//mutateAll/TypeParam(bounds=[kotlin.collections.MutableCollection[TypeParam(bounds=[kotlin.Any?])]])#kotlin.Function1[TypeParam(bounds=[kotlin.Any?]),TypeParam(bounds=[kotlin.Any?])]/PointingToDeclaration/mutable-utils/at.kopyk/mutate-all.html 6 | $dokka.location:at.kopyk//mutateAllIndexed/TypeParam(bounds=[kotlin.collections.MutableCollection[TypeParam(bounds=[kotlin.Any?])]])#kotlin.Function2[kotlin.Int,TypeParam(bounds=[kotlin.Any?]),TypeParam(bounds=[kotlin.Any?])]/PointingToDeclaration/mutable-utils/at.kopyk/mutate-all-indexed.html 7 | $dokka.location:at.kopyk//mutateAllIndexedNotNull/TypeParam(bounds=[kotlin.collections.MutableCollection[TypeParam(bounds=[kotlin.Any?])]])#kotlin.Function2[kotlin.Int,TypeParam(bounds=[kotlin.Any?]),TypeParam(bounds=[kotlin.Any?])?]/PointingToDeclaration/mutable-utils/at.kopyk/mutate-all-indexed-not-null.html 8 | $dokka.location:at.kopyk//mutateAllNotNull/TypeParam(bounds=[kotlin.collections.MutableCollection[TypeParam(bounds=[kotlin.Any?])]])#kotlin.Function1[TypeParam(bounds=[kotlin.Any?]),TypeParam(bounds=[kotlin.Any?])?]/PointingToDeclaration/mutable-utils/at.kopyk/mutate-all-not-null.html 9 | $dokka.location:at.kopyk//mutateAllNotNull/kotlin.collections.MutableList[TypeParam(bounds=[kotlin.Any?])]#kotlin.Function1[TypeParam(bounds=[kotlin.Any?]),TypeParam(bounds=[kotlin.Any?])?]/PointingToDeclaration/mutable-utils/at.kopyk/mutate-all-not-null.html 10 | $dokka.location:at.kopyk//mutateValues/kotlin.collections.MutableMap[TypeParam(bounds=[kotlin.Any?]),TypeParam(bounds=[kotlin.Any?])]#kotlin.Function1[kotlin.collections.Map.Entry[TypeParam(bounds=[kotlin.Any?]),TypeParam(bounds=[kotlin.Any?])],TypeParam(bounds=[kotlin.Any?])]/PointingToDeclaration/mutable-utils/at.kopyk/mutate-values.html 11 | $dokka.location:at.kopyk//mutateValues/kotlin.collections.MutableMap[TypeParam(bounds=[kotlin.Any?]),TypeParam(bounds=[kotlin.Any?])]#kotlin.Function2[TypeParam(bounds=[kotlin.Any?]),TypeParam(bounds=[kotlin.Any?]),TypeParam(bounds=[kotlin.Any?])]/PointingToDeclaration/mutable-utils/at.kopyk/mutate-values.html 12 | $dokka.location:at.kopyk//mutateValuesNotNull/kotlin.collections.MutableMap[TypeParam(bounds=[kotlin.Any?]),TypeParam(bounds=[kotlin.Any?])]#kotlin.Function1[kotlin.collections.Map.Entry[TypeParam(bounds=[kotlin.Any?]),TypeParam(bounds=[kotlin.Any?])],TypeParam(bounds=[kotlin.Any?])?]/PointingToDeclaration/mutable-utils/at.kopyk/mutate-values-not-null.html 13 | $dokka.location:at.kopyk//mutateValuesNotNull/kotlin.collections.MutableMap[TypeParam(bounds=[kotlin.Any?]),TypeParam(bounds=[kotlin.Any?])]#kotlin.Function2[TypeParam(bounds=[kotlin.Any?]),TypeParam(bounds=[kotlin.Any?]),TypeParam(bounds=[kotlin.Any?])?]/PointingToDeclaration/mutable-utils/at.kopyk/mutate-values-not-null.html 14 | $dokka.location:at.kopyk//removeUnlessInstanceOf/kotlin.collections.MutableCollection[*]#/PointingToDeclaration/mutable-utils/at.kopyk/remove-unless-instance-of.html 15 | $dokka.location:at.kopyk//removeUnlessInstanceOf/kotlin.collections.MutableList[*]#/PointingToDeclaration/mutable-utils/at.kopyk/remove-unless-instance-of.html 16 | $dokka.location:at.kopyk//removeUnlessInstanceOf/kotlin.collections.MutableSet[*]#/PointingToDeclaration/mutable-utils/at.kopyk/remove-unless-instance-of.html 17 | $dokka.location:at.kopyk//removeValuesUnlessInstanceOf/kotlin.collections.MutableMap[TypeParam(bounds=[kotlin.Any?]),*]#/PointingToDeclaration/mutable-utils/at.kopyk/remove-values-unless-instance-of.html 18 | at.kopyk 19 | 20 | -------------------------------------------------------------------------------- /_layouts/default.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | {% include head-custom.html %} 9 | 10 | {% seo %} 11 | 12 | 53 | 54 | 55 | 56 | 57 | 58 |
59 |
60 | 61 |

😺 → 😺 → 😺 KopyKat 😺 ← 😺 ← 😺

62 |
63 |

{{ site.description | default: site.github.project_tagline }}

64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 |
72 |
73 | 74 | 100 | 101 |
102 |
103 | {{ content }} 104 |
105 |
106 | 107 | 108 | -------------------------------------------------------------------------------- /kopykat-ksp/src/main/kotlin/at/kopyk/FileCompileScope.kt: -------------------------------------------------------------------------------- 1 | package at.kopyk 2 | 3 | import at.kopyk.poet.writeTo 4 | import at.kopyk.utils.ClassCompileScope 5 | import at.kopyk.utils.TypeAliasCompileScope 6 | import at.kopyk.utils.TypeCategory.Known 7 | import at.kopyk.utils.allNestedDeclarations 8 | import at.kopyk.utils.hasAnnotation 9 | import at.kopyk.utils.hasGeneratedMarker 10 | import at.kopyk.utils.lang.filterIsInstance 11 | import at.kopyk.utils.typeCategory 12 | import com.google.devtools.ksp.KspExperimental 13 | import com.google.devtools.ksp.isAnnotationPresent 14 | import com.google.devtools.ksp.processing.CodeGenerator 15 | import com.google.devtools.ksp.processing.Resolver 16 | import com.google.devtools.ksp.symbol.KSClassDeclaration 17 | import com.google.devtools.ksp.symbol.KSDeclaration 18 | import com.google.devtools.ksp.symbol.KSFile 19 | import com.google.devtools.ksp.symbol.KSTypeAlias 20 | import com.squareup.kotlinpoet.FileSpec 21 | import org.apache.commons.io.FilenameUtils 22 | 23 | internal fun ProcessorScope.processFiles( 24 | resolver: Resolver, 25 | block: FileCompileScope.() -> Unit, 26 | ) { 27 | val files = resolver.getAllFiles() 28 | if (files.none(KSFile::hasGeneratedMarker)) { 29 | block(FileCompileScope(files, this)) 30 | } 31 | } 32 | 33 | internal class FileCompileScope( 34 | files: Sequence, 35 | scope: ProcessorScope, 36 | ) : LoggerScope by scope, OptionsScope by scope { 37 | private val codegen: CodeGenerator = scope.codegen 38 | 39 | val declarations = 40 | files 41 | .flatMap { it.allNestedDeclarations() } 42 | .onEach { it.isKnownWithCopyExtension() } 43 | .onEach { it.checkRedundantAnnotation() } 44 | .filter { it.typeCategory is Known } 45 | 46 | val typeAliases = 47 | declarations 48 | .filterIsInstance { isKnownWithCopyExtension() } 49 | 50 | val classes = 51 | declarations 52 | .filterIsInstance() 53 | .filter { it.shouldGenerate() } 54 | 55 | val KSClassDeclaration.classScope: ClassCompileScope 56 | get() = ClassCompileScope(this, classes, logger) 57 | 58 | val KSTypeAlias.typealiasScope: TypeAliasCompileScope 59 | get() = TypeAliasCompileScope(this, classes, logger) 60 | 61 | private fun KSDeclaration.isKnownWithCopyExtension() = 62 | hasAnnotation() 63 | .also { isCopyExtension -> 64 | if (isCopyExtension && (typeCategory !is Known || typeCategory is Known.Class)) { 65 | logger.error( 66 | """ 67 | '@CopyExtensions' may only be used in data or value classes, 68 | sealed hierarchies of those, or type aliases of those. 69 | """.trimIndent(), 70 | this, 71 | ) 72 | } 73 | } 74 | 75 | fun FileSpec.write() { 76 | writeTo(codegen) 77 | } 78 | 79 | @OptIn(KspExperimental::class) 80 | private fun KSDeclaration.checkRedundantAnnotation() { 81 | if (isAnnotationPresent(CopyExtensions::class) && options.generate is KopyKatGenerate.NotAnnotated) { 82 | logger.warn( 83 | """ 84 | Unused '@CopyExtensions' annotation, the plug-in is configured to process all classes. 85 | Add 'arg("annotatedOnly", "true")' to your KSP configuration to change this option. 86 | More info at https://kopyk.at/#enable-only-for-selected-classes. 87 | """.trimIndent(), 88 | this, 89 | ) 90 | } 91 | } 92 | 93 | @OptIn(KspExperimental::class) 94 | private fun KSDeclaration.shouldGenerate(): Boolean = 95 | when (options.generate) { 96 | is KopyKatGenerate.Error -> 97 | false 98 | 99 | is KopyKatGenerate.All -> 100 | true 101 | 102 | is KopyKatGenerate.Annotated -> 103 | isAnnotationPresent(CopyExtensions::class) 104 | 105 | is KopyKatGenerate.Packages -> { 106 | val pkg = packageName.asString() 107 | options.generate.patterns.any { pattern -> 108 | FilenameUtils.wildcardMatch(pkg, pattern) 109 | } 110 | } 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /kopykat-ksp/src/test/kotlin/at/kopyk/CopyConstructorsWithValueTest.kt: -------------------------------------------------------------------------------- 1 | package at.kopyk 2 | 3 | import org.junit.jupiter.api.Test 4 | import org.junit.jupiter.params.ParameterizedTest 5 | import org.junit.jupiter.params.provider.Arguments 6 | import org.junit.jupiter.params.provider.MethodSource 7 | import java.util.stream.Stream 8 | 9 | class CopyConstructorsWithValueTest { 10 | companion object { 11 | @JvmStatic 12 | fun cases(): Stream = 13 | Stream.of( 14 | Arguments.of("value", ""), 15 | Arguments.of("value", "data"), 16 | Arguments.of("value", "value"), 17 | Arguments.of("", "value"), 18 | Arguments.of("data", "value"), 19 | ) 20 | } 21 | 22 | @ParameterizedTest(name = "{0} class CopyFrom {1} class") 23 | @MethodSource("cases") 24 | fun copyFrom( 25 | annotatedModifiers: String, 26 | targetModifiers: String, 27 | ) { 28 | """ 29 | |import at.kopyk.CopyFrom 30 | | 31 | |${if (targetModifiers == "value") "@JvmInline" else ""} 32 | |$targetModifiers class Person(val name: String) 33 | | 34 | |@CopyFrom(Person::class) 35 | |${if (annotatedModifiers == "value") "@JvmInline" else ""} 36 | |$annotatedModifiers class LocalPerson(val name: String) 37 | | 38 | |val p1 = Person("Alex") 39 | |val p2 = LocalPerson(p1) 40 | |val r = p2.name 41 | """.evals("r" to "Alex") 42 | } 43 | 44 | @ParameterizedTest(name = "{0} class CopyTo {1} class") 45 | @MethodSource("cases") 46 | fun copyTo( 47 | annotatedModifiers: String, 48 | targetModifiers: String, 49 | ) { 50 | """ 51 | |import at.kopyk.CopyTo 52 | | 53 | |${if (targetModifiers == "value") "@JvmInline" else ""} 54 | |$targetModifiers class Person(val name: String) 55 | | 56 | |@CopyTo(Person::class) 57 | |${if (annotatedModifiers == "value") "@JvmInline" else ""} 58 | |$annotatedModifiers class LocalPerson(val name: String) 59 | | 60 | |val p1 = LocalPerson("Alex") 61 | |val p2 = Person(p1) 62 | |val r = p2.name 63 | """.evals("r" to "Alex") 64 | } 65 | 66 | @ParameterizedTest(name = "{0} class Copy {1} class") 67 | @MethodSource("cases") 68 | fun copy( 69 | annotatedModifiers: String, 70 | targetModifiers: String, 71 | ) { 72 | """ 73 | |import at.kopyk.Copy 74 | | 75 | |${if (targetModifiers == "value") "@JvmInline" else ""} 76 | |$targetModifiers class Person(val name: String) 77 | | 78 | |@Copy(Person::class) 79 | |${if (annotatedModifiers == "value") "@JvmInline" else ""} 80 | |$annotatedModifiers class LocalPerson(val name: String) 81 | | 82 | |val p1 = LocalPerson("Alex") 83 | |val p2 = Person(p1) 84 | |val p3 = LocalPerson(p2) 85 | |val r = p3.name 86 | """.evals("r" to "Alex") 87 | } 88 | 89 | @Test 90 | fun `@Copy, missing field should fail compilation`() { 91 | """ 92 | |import at.kopyk.Copy 93 | | 94 | |class Person() 95 | | 96 | |@JvmInline 97 | |@Copy(Person::class) 98 | |value class LocalPerson(val name: String) 99 | | 100 | |val p1 = Person() 101 | |val p2 = LocalPerson(p1) 102 | |val r = p2.name 103 | """.failsWith { 104 | it.contains("LocalPerson must have the same constructor properties as Person") 105 | } 106 | } 107 | 108 | @Test 109 | fun `@CopyFrom, missing field should fail compilation`() { 110 | """ 111 | |import at.kopyk.CopyFrom 112 | | 113 | |class Person() 114 | | 115 | |@JvmInline 116 | |@CopyFrom(Person::class) 117 | |value class LocalPerson(val name: String) 118 | | 119 | |val p1 = Person() 120 | |val p2 = LocalPerson(p1) 121 | |val r = p2.name 122 | """.failsWith { 123 | it.contains("LocalPerson must have the same constructor properties as Person") 124 | } 125 | } 126 | 127 | @Test 128 | fun `@CopyTo, missing field should fail compilation`() { 129 | """ 130 | |import at.kopyk.CopyTo 131 | | 132 | |class Person() 133 | | 134 | |@JvmInline 135 | |@CopyTo(Person::class) 136 | |data class LocalPerson(val name: String) 137 | | 138 | |val p1 = Person() 139 | |val p2 = LocalPerson(p1) 140 | |val r = p2.age 141 | """.failsWith { 142 | it.contains("Person must have the same constructor properties as LocalPerson") 143 | } 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /kopykat-ksp/src/test/kotlin/at/kopyk/CopyMapTest.kt: -------------------------------------------------------------------------------- 1 | package at.kopyk 2 | 3 | import org.junit.jupiter.api.Test 4 | 5 | class CopyMapTest { 6 | @Test 7 | fun `simple test`() { 8 | """ 9 | |data class Person(val name: String, val age: Int) 10 | | 11 | |val p1 = Person("Alex", 1) 12 | |val p2 = p1.copyMap(age = { it + 1 }) 13 | |val r = p2.age 14 | """.evals("r" to 2) 15 | } 16 | 17 | @Test 18 | fun `simple test, nullable type`() { 19 | """ 20 | |data class Person(val name: String, val age: Int?) 21 | | 22 | |val p1 = Person("Alex", 1) 23 | |val p2 = p1.copyMap(age = { n -> n?.let { it + 1 } }) 24 | |val r = p2.age 25 | """.evals("r" to 2) 26 | } 27 | 28 | @Test 29 | fun `simple test on nested class`() { 30 | """ 31 | |class Things { 32 | | data class Person(val name: String, val age: Int) 33 | |} 34 | | 35 | |val p1 = Things.Person("Alex", 1) 36 | |val p2 = p1.copyMap(age = { it + 1 }) 37 | |val r = p2.age 38 | """.evals("r" to 2) 39 | } 40 | 41 | @Test 42 | fun `empty transform does nothing`() { 43 | """ 44 | |data class Person(val name: String, val age: Int) 45 | | 46 | |val p1 = Person("Alex", 1) 47 | |val p2 = p1.copyMap() 48 | |val r = p2.age 49 | """.evals("r" to 1) 50 | } 51 | 52 | @Test 53 | fun `works on generic classes, 1`() { 54 | """ 55 | |data class Person(val name: String, val age: A) 56 | | 57 | |val p1: Person = Person("Alex", 1) 58 | |val p2 = p1.copyMap(age = { it + 1 }) 59 | |val r = p2.age 60 | """.evals("r" to 2) 61 | } 62 | 63 | @Test 64 | fun `works on generic classes, 2`() { 65 | """ 66 | |data class Person(val name: String, val infos: List) 67 | | 68 | |val p1: Person = Person("Alex", listOf(1, 2)) 69 | |val p2 = p1.copyMap(infos = { it.map { i -> i + 1 } }) 70 | |val r = p2.infos 71 | """.evals("r" to listOf(2, 3)) 72 | } 73 | 74 | @Test 75 | fun `not generated for regular classes`() { 76 | """ 77 | |class Person(val name: String, val age: Int) 78 | | 79 | |val p1 = Person("Alex", 1) 80 | |val p2 = p1.copyMap() 81 | |val r = p2.age 82 | """.failsWith { 83 | it.contains("Unresolved reference: copyMap") 84 | } 85 | } 86 | 87 | @Test 88 | fun `simple test with additional property`() { 89 | """ 90 | |data class Person(val name: String, val age: Int) { 91 | | public var address: String = "" 92 | |} 93 | | 94 | |val p1 = Person("Alex", 1) 95 | |val p2 = p1.copyMap(age = { it + 1 }) 96 | |val r = p2.age 97 | """.evals("r" to 2) 98 | } 99 | 100 | @Test 101 | fun `generic classes and variance, issue #48`() { 102 | """ 103 | |data class Node( 104 | | val current: T, 105 | | val paths: List>, 106 | |) 107 | | 108 | |val n1: Node = Node(1, paths = listOf(Node(2, emptyList()))) 109 | |val n2 = n1.copyMap(current = { it + 1 }) 110 | |val r = n2.current 111 | """.evals("r" to 2) 112 | } 113 | 114 | @Test 115 | fun `uses a different field`() { 116 | """ 117 | |data class Person(val name: String, val age: Int) 118 | | 119 | |val p1 = Person("Alex", 1) 120 | |val p2 = p1.copyMap(age = { name.count() }) 121 | |val r = p2.age 122 | """.evals("r" to 4) 123 | } 124 | 125 | @Test 126 | fun `typealias test`() { 127 | """ 128 | |import at.kopyk.CopyExtensions 129 | | 130 | |@CopyExtensions 131 | |typealias Person = Pair 132 | | 133 | |val p1 = "Alex" to 1 134 | |val p2 = p1.copyMap(second = { it + 1 }) 135 | |val r = p2.second 136 | """.evals("r" to 2) 137 | } 138 | 139 | @Test 140 | fun `typealias test, full generic`() { 141 | """ 142 | |import at.kopyk.CopyExtensions 143 | | 144 | |@CopyExtensions 145 | |typealias Pareja = Pair 146 | | 147 | |val p1: Pareja = "Alex" to 1 148 | |val p2 = p1.copyMap(second = { it + 1 }) 149 | |val r = p2.second 150 | """.evals("r" to 2) 151 | } 152 | 153 | @Test 154 | fun `typealias test, half generic`() { 155 | """ 156 | |import at.kopyk.CopyExtensions 157 | | 158 | |@CopyExtensions 159 | |typealias Named = Pair 160 | | 161 | |val p1: Named = "Alex" to 1 162 | |val p2 = p1.copyMap(second = { it + 1 }) 163 | |val r = p2.second 164 | """.evals("r" to 2) 165 | } 166 | } 167 | -------------------------------------------------------------------------------- /docs/mutable-utils/scripts/pages.json: -------------------------------------------------------------------------------- 1 | [{"name":"inline fun MutableCollection<*>.removeUnlessInstanceOf(): MutableCollection","description":"at.kopyk.removeUnlessInstanceOf","location":"mutable-utils/at.kopyk/remove-unless-instance-of.html","searchKeys":["removeUnlessInstanceOf","inline fun MutableCollection<*>.removeUnlessInstanceOf(): MutableCollection","at.kopyk.removeUnlessInstanceOf"]},{"name":"inline fun MutableList<*>.removeUnlessInstanceOf(): MutableList","description":"at.kopyk.removeUnlessInstanceOf","location":"mutable-utils/at.kopyk/remove-unless-instance-of.html","searchKeys":["removeUnlessInstanceOf","inline fun MutableList<*>.removeUnlessInstanceOf(): MutableList","at.kopyk.removeUnlessInstanceOf"]},{"name":"inline fun MutableList.mutateAllNotNull(transform: (A) -> A?): MutableList","description":"at.kopyk.mutateAllNotNull","location":"mutable-utils/at.kopyk/mutate-all-not-null.html","searchKeys":["mutateAllNotNull","inline fun MutableList.mutateAllNotNull(transform: (A) -> A?): MutableList","at.kopyk.mutateAllNotNull"]},{"name":"inline fun MutableSet<*>.removeUnlessInstanceOf(): MutableSet","description":"at.kopyk.removeUnlessInstanceOf","location":"mutable-utils/at.kopyk/remove-unless-instance-of.html","searchKeys":["removeUnlessInstanceOf","inline fun MutableSet<*>.removeUnlessInstanceOf(): MutableSet","at.kopyk.removeUnlessInstanceOf"]},{"name":"inline fun MutableMap.removeValuesUnlessInstanceOf(): MutableMap","description":"at.kopyk.removeValuesUnlessInstanceOf","location":"mutable-utils/at.kopyk/remove-values-unless-instance-of.html","searchKeys":["removeValuesUnlessInstanceOf","inline fun MutableMap.removeValuesUnlessInstanceOf(): MutableMap","at.kopyk.removeValuesUnlessInstanceOf"]},{"name":"inline fun MutableMap.mutateValues(transform: (entry: Map.Entry) -> V): MutableMap","description":"at.kopyk.mutateValues","location":"mutable-utils/at.kopyk/mutate-values.html","searchKeys":["mutateValues","inline fun MutableMap.mutateValues(transform: (entry: Map.Entry) -> V): MutableMap","at.kopyk.mutateValues"]},{"name":"inline fun MutableMap.mutateValues(transform: (key: K, value: V) -> V): MutableMap","description":"at.kopyk.mutateValues","location":"mutable-utils/at.kopyk/mutate-values.html","searchKeys":["mutateValues","inline fun MutableMap.mutateValues(transform: (key: K, value: V) -> V): MutableMap","at.kopyk.mutateValues"]},{"name":"inline fun MutableMap.mutateValuesNotNull(transform: (entry: Map.Entry) -> V?): MutableMap","description":"at.kopyk.mutateValuesNotNull","location":"mutable-utils/at.kopyk/mutate-values-not-null.html","searchKeys":["mutateValuesNotNull","inline fun MutableMap.mutateValuesNotNull(transform: (entry: Map.Entry) -> V?): MutableMap","at.kopyk.mutateValuesNotNull"]},{"name":"inline fun MutableMap.mutateValuesNotNull(transform: (key: K, value: V) -> V?): MutableMap","description":"at.kopyk.mutateValuesNotNull","location":"mutable-utils/at.kopyk/mutate-values-not-null.html","searchKeys":["mutateValuesNotNull","inline fun MutableMap.mutateValuesNotNull(transform: (key: K, value: V) -> V?): MutableMap","at.kopyk.mutateValuesNotNull"]},{"name":"inline fun , A> T.clearThenAddAllNotNull(transform: (A) -> A?): T","description":"at.kopyk.clearThenAddAllNotNull","location":"mutable-utils/at.kopyk/clear-then-add-all-not-null.html","searchKeys":["clearThenAddAllNotNull","inline fun , A> T.clearThenAddAllNotNull(transform: (A) -> A?): T","at.kopyk.clearThenAddAllNotNull"]},{"name":"inline fun , A> T.mutateAll(transform: (A) -> A): T","description":"at.kopyk.mutateAll","location":"mutable-utils/at.kopyk/mutate-all.html","searchKeys":["mutateAll","inline fun , A> T.mutateAll(transform: (A) -> A): T","at.kopyk.mutateAll"]},{"name":"inline fun , A> T.mutateAllIndexed(transform: (index: Int, value: A) -> A): T","description":"at.kopyk.mutateAllIndexed","location":"mutable-utils/at.kopyk/mutate-all-indexed.html","searchKeys":["mutateAllIndexed","inline fun , A> T.mutateAllIndexed(transform: (index: Int, value: A) -> A): T","at.kopyk.mutateAllIndexed"]},{"name":"inline fun , A> T.mutateAllIndexedNotNull(transform: (index: Int, value: A) -> A?): T","description":"at.kopyk.mutateAllIndexedNotNull","location":"mutable-utils/at.kopyk/mutate-all-indexed-not-null.html","searchKeys":["mutateAllIndexedNotNull","inline fun , A> T.mutateAllIndexedNotNull(transform: (index: Int, value: A) -> A?): T","at.kopyk.mutateAllIndexedNotNull"]},{"name":"inline fun , A> T.mutateAllNotNull(transform: (A) -> A?): T","description":"at.kopyk.mutateAllNotNull","location":"mutable-utils/at.kopyk/mutate-all-not-null.html","searchKeys":["mutateAllNotNull","inline fun , A> T.mutateAllNotNull(transform: (A) -> A?): T","at.kopyk.mutateAllNotNull"]}] 2 | -------------------------------------------------------------------------------- /utils/compiletesting/src/main/kotlin/at/kopyk/compiletesting/Compilation.kt: -------------------------------------------------------------------------------- 1 | @file:OptIn(ExperimentalCompilerApi::class) 2 | 3 | package at.kopyk.compiletesting 4 | 5 | import com.google.devtools.ksp.processing.SymbolProcessorProvider 6 | import com.tschuchort.compiletesting.CompilationResult 7 | import com.tschuchort.compiletesting.KotlinCompilation 8 | import com.tschuchort.compiletesting.KotlinCompilation.ExitCode.OK 9 | import com.tschuchort.compiletesting.SourceFile 10 | import com.tschuchort.compiletesting.kspArgs 11 | import com.tschuchort.compiletesting.kspSourcesDir 12 | import com.tschuchort.compiletesting.symbolProcessorProviders 13 | import io.kotest.matchers.shouldBe 14 | import io.kotest.matchers.shouldNotBe 15 | import org.jetbrains.kotlin.compiler.plugin.ExperimentalCompilerApi 16 | import java.io.File 17 | import java.net.URLClassLoader 18 | import java.nio.file.Files 19 | import java.nio.file.Paths 20 | 21 | private const val SOURCE_FILENAME = "Source.kt" 22 | 23 | public fun String.failsWith( 24 | provider: SymbolProcessorProvider, 25 | providerArgs: Map = emptyMap(), 26 | check: (String) -> Boolean, 27 | ) { 28 | val compilationResult = compile(this, provider, providerArgs) 29 | compilationResult.exitCode shouldNotBe OK 30 | check(compilationResult.messages) shouldBe true 31 | } 32 | 33 | public fun String.compilesWith( 34 | provider: SymbolProcessorProvider, 35 | providerArgs: Map = emptyMap(), 36 | check: (String) -> Boolean, 37 | ) { 38 | val compilationResult = compile(this, provider, providerArgs) 39 | 40 | compilationResult.exitCode shouldBe OK 41 | check(compilationResult.messages) shouldBe true 42 | } 43 | 44 | public fun String.evals( 45 | provider: SymbolProcessorProvider, 46 | providerArgs: Map = emptyMap(), 47 | vararg things: Pair, 48 | ) { 49 | val compilationResult = compile(this, provider, providerArgs) 50 | compilationResult.exitCode shouldBe OK 51 | val classesDirectory = compilationResult.outputDirectory 52 | things.forEach { (variable, output) -> 53 | eval(variable, classesDirectory) shouldBe output 54 | } 55 | } 56 | 57 | // UTILITY FUNCTIONS COPIED FROM META-TEST 58 | // ======================================= 59 | 60 | internal data class FullCompilationResult( 61 | val mainResult: CompilationResult, 62 | val additionalMessages: String?, 63 | ) { 64 | val exitCode = mainResult.exitCode 65 | val outputDirectory = mainResult.outputDirectory 66 | val messages = 67 | when (additionalMessages) { 68 | null -> mainResult.messages 69 | else -> listOf(additionalMessages, mainResult.messages).joinToString(separator = "\n") 70 | } 71 | } 72 | 73 | private fun CompilationResult.pass1Result() = FullCompilationResult(this, null) 74 | 75 | private fun CompilationResult.pass2Result(additionalMessages: String) = FullCompilationResult(this, additionalMessages) 76 | 77 | internal fun compile( 78 | text: String, 79 | provider: SymbolProcessorProvider, 80 | providerArgs: Map = emptyMap(), 81 | ): FullCompilationResult { 82 | val compilation = buildCompilation(text, provider, providerArgs) 83 | // fix problems with double compilation and KSP 84 | // as stated in https://github.com/tschuchortdev/kotlin-compile-testing/issues/72 85 | val pass1 = compilation.compile() 86 | // if the first pass was unsuccessful, return it 87 | if (pass1.exitCode != OK) return pass1.pass1Result() 88 | // return the results of second pass 89 | return buildCompilation(text, provider) 90 | .apply { 91 | sources = compilation.sources + compilation.kspGeneratedSourceFiles 92 | symbolProcessorProviders = emptyList() 93 | } 94 | .compile() 95 | .pass2Result(pass1.messages) 96 | } 97 | 98 | private fun buildCompilation( 99 | text: String, 100 | provider: SymbolProcessorProvider, 101 | providerArgs: Map = emptyMap(), 102 | ) = KotlinCompilation().apply { 103 | symbolProcessorProviders = listOf(provider) 104 | kspArgs.putAll(providerArgs) 105 | sources = listOf(SourceFile.kotlin(SOURCE_FILENAME, text.trimMargin())) 106 | inheritClassPath = true 107 | } 108 | 109 | private val KotlinCompilation.kspGeneratedSourceFiles: List 110 | get() = 111 | kspSourcesDir 112 | .resolve("kotlin") 113 | .walk() 114 | .filter { it.isFile } 115 | .map { SourceFile.fromPath(it.absoluteFile) } 116 | .toList() 117 | 118 | private fun eval( 119 | expression: String, 120 | classesDirectory: File, 121 | ): Any? { 122 | val classLoader = URLClassLoader(arrayOf(classesDirectory.toURI().toURL())) 123 | val fullClassName = getFullClassName(classesDirectory) 124 | val field = classLoader.loadClass(fullClassName).getDeclaredField(expression) 125 | field.isAccessible = true 126 | return field.get(Object()) 127 | } 128 | 129 | private fun getFullClassName(classesDirectory: File): String = 130 | Files.walk(Paths.get(classesDirectory.toURI())) 131 | .filter { it.toFile().name == "SourceKt.class" } 132 | .toArray()[0] 133 | .toString() 134 | .removePrefix(classesDirectory.absolutePath + File.separator) 135 | .removeSuffix(".class") 136 | .replace(File.separator, ".") 137 | -------------------------------------------------------------------------------- /docs/mutable-utils/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | mutable-utils 6 | 7 | 8 | 9 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 |
38 | 59 |
60 | 63 |
64 |
65 | 66 |
67 |

mutable-utils

68 |
69 |

Packages

70 |
71 |
72 |
73 |
74 |
75 | 76 | 77 |
Link copied to clipboard
78 |
79 |
80 |
81 | 82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 | 95 |
96 |
97 |
98 | 99 | 100 | -------------------------------------------------------------------------------- /docs/mutable-utils/styles/prism.css: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014-2023 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. 3 | */ 4 | 5 | /* 6 | * Custom Dokka styles 7 | */ 8 | code .token { 9 | white-space: pre; 10 | } 11 | 12 | /** 13 | * Styles based on webhelp's prism.js styles 14 | * Changes: 15 | * - Since webhelp's styles are in .pcss, they use nesting which is not achievable in native CSS 16 | * so nested css blocks have been unrolled (like dark theme). 17 | * - Webhelp uses "Custom Class" prism.js plugin, so all of their prism classes are prefixed with "--prism". 18 | * Dokka doesn't seem to need this plugin at the moment, so all "--prism" prefixes have been removed. 19 | * - Removed all styles related to `pre` and `code` tags. Kotlinlang's resulting styles are so spread out and complicated 20 | * that it's difficult to gather in one place. Instead use code styles defined in the main Dokka styles, 21 | * which at the moment looks fairly similar. 22 | * 23 | * Based on prism.js default theme 24 | * Based on dabblet (http://dabblet.com) 25 | * @author Lea Verou 26 | */ 27 | 28 | .token.comment, 29 | .token.prolog, 30 | .token.doctype, 31 | .token.cdata { 32 | color: #8c8c8c; 33 | } 34 | 35 | .token.punctuation { 36 | color: #999; 37 | } 38 | 39 | .token.namespace { 40 | opacity: 0.7; 41 | } 42 | 43 | .token.property, 44 | .token.tag, 45 | .token.boolean, 46 | .token.number, 47 | .token.constant, 48 | .token.symbol, 49 | .token.deleted { 50 | color: #871094; 51 | } 52 | 53 | .token.selector, 54 | .token.attr-name, 55 | .token.string, 56 | .token.char, 57 | .token.builtin, 58 | .token.inserted { 59 | color: #067d17; 60 | } 61 | 62 | .token.operator, 63 | .token.entity, 64 | .token.url, 65 | .language-css .token.string, 66 | .style .token.string { 67 | color: #9a6e3a; 68 | /* This background color was intended by the author of this theme. */ 69 | background: hsla(0, 0%, 100%, 0.5); 70 | } 71 | 72 | .token.atrule, 73 | .token.attr-value, 74 | .token.keyword { 75 | font-size: inherit; /* to override .keyword */ 76 | color: #0033b3; 77 | } 78 | 79 | .token.function { 80 | color: #00627a; 81 | } 82 | 83 | .token.class-name { 84 | color: #000000; 85 | } 86 | 87 | .token.regex, 88 | .token.important, 89 | .token.variable { 90 | color: #871094; 91 | } 92 | 93 | .token.important, 94 | .token.bold { 95 | font-weight: bold; 96 | } 97 | .token.italic { 98 | font-style: italic; 99 | } 100 | 101 | .token.entity { 102 | cursor: help; 103 | } 104 | 105 | .token.operator { 106 | background: none; 107 | } 108 | 109 | /* 110 | * DARK THEME 111 | */ 112 | :root.theme-dark .token.comment, 113 | :root.theme-dark .token.prolog, 114 | :root.theme-dark .token.cdata { 115 | color: #808080; 116 | } 117 | 118 | :root.theme-dark .token.delimiter, 119 | :root.theme-dark .token.boolean, 120 | :root.theme-dark .token.keyword, 121 | :root.theme-dark .token.selector, 122 | :root.theme-dark .token.important, 123 | :root.theme-dark .token.atrule { 124 | color: #cc7832; 125 | } 126 | 127 | :root.theme-dark .token.operator, 128 | :root.theme-dark .token.punctuation, 129 | :root.theme-dark .token.attr-name { 130 | color: #a9b7c6; 131 | } 132 | 133 | :root.theme-dark .token.tag, 134 | :root.theme-dark .token.tag .punctuation, 135 | :root.theme-dark .token.doctype, 136 | :root.theme-dark .token.builtin { 137 | color: #e8bf6a; 138 | } 139 | 140 | :root.theme-dark .token.entity, 141 | :root.theme-dark .token.number, 142 | :root.theme-dark .token.symbol { 143 | color: #6897bb; 144 | } 145 | 146 | :root.theme-dark .token.property, 147 | :root.theme-dark .token.constant, 148 | :root.theme-dark .token.variable { 149 | color: #9876aa; 150 | } 151 | 152 | :root.theme-dark .token.string, 153 | :root.theme-dark .token.char { 154 | color: #6a8759; 155 | } 156 | 157 | :root.theme-dark .token.attr-value, 158 | :root.theme-dark .token.attr-value .punctuation { 159 | color: #a5c261; 160 | } 161 | 162 | :root.theme-dark .token.attr-value .punctuation:first-child { 163 | color: #a9b7c6; 164 | } 165 | 166 | :root.theme-dark .token.url { 167 | text-decoration: underline; 168 | 169 | color: #287bde; 170 | background: transparent; 171 | } 172 | 173 | :root.theme-dark .token.function { 174 | color: #ffc66d; 175 | } 176 | 177 | :root.theme-dark .token.regex { 178 | background: #364135; 179 | } 180 | 181 | :root.theme-dark .token.deleted { 182 | background: #484a4a; 183 | } 184 | 185 | :root.theme-dark .token.inserted { 186 | background: #294436; 187 | } 188 | 189 | :root.theme-dark .token.class-name { 190 | color: #a9b7c6; 191 | } 192 | 193 | :root.theme-dark .token.function { 194 | color: #ffc66d; 195 | } 196 | 197 | :root.theme-darkcode .language-css .token.property, 198 | :root.theme-darkcode .language-css, 199 | :root.theme-dark .token.property + .token.punctuation { 200 | color: #a9b7c6; 201 | } 202 | 203 | code.language-css .token.id { 204 | color: #ffc66d; 205 | } 206 | 207 | :root.theme-dark code.language-css .token.selector > .token.class, 208 | :root.theme-dark code.language-css .token.selector > .token.attribute, 209 | :root.theme-dark code.language-css .token.selector > .token.pseudo-class, 210 | :root.theme-dark code.language-css .token.selector > .token.pseudo-element { 211 | color: #ffc66d; 212 | } 213 | 214 | :root.theme-dark .language-plaintext .token { 215 | /* plaintext code should be colored as article text */ 216 | color: inherit !important; 217 | } 218 | -------------------------------------------------------------------------------- /kopykat-ksp/src/main/kotlin/at/kopyk/MutableCopy.kt: -------------------------------------------------------------------------------- 1 | package at.kopyk 2 | 3 | import at.kopyk.poet.addClass 4 | import at.kopyk.poet.addMutableProperty 5 | import at.kopyk.poet.addParameter 6 | import at.kopyk.poet.addProperty 7 | import at.kopyk.poet.addReturn 8 | import at.kopyk.poet.asReceiverConsumer 9 | import at.kopyk.poet.makeInvariant 10 | import at.kopyk.poet.parameterModifiers 11 | import at.kopyk.poet.primaryConstructor 12 | import at.kopyk.poet.propertyModifiers 13 | import at.kopyk.utils.FileCompilerScope 14 | import at.kopyk.utils.TypeCategory.Known 15 | import at.kopyk.utils.TypeCategory.Known.Data 16 | import at.kopyk.utils.TypeCategory.Known.Sealed 17 | import at.kopyk.utils.TypeCategory.Known.Value 18 | import at.kopyk.utils.TypeCompileScope 19 | import at.kopyk.utils.addGeneratedMarker 20 | import at.kopyk.utils.baseName 21 | import at.kopyk.utils.dslMarker 22 | import at.kopyk.utils.fullName 23 | import at.kopyk.utils.lang.forEachRun 24 | import at.kopyk.utils.lang.joinWithWhen 25 | import at.kopyk.utils.mutable 26 | import at.kopyk.utils.onKnownCategory 27 | import at.kopyk.utils.typeCategory 28 | import com.squareup.kotlinpoet.FileSpec 29 | import com.squareup.kotlinpoet.FunSpec 30 | import com.squareup.kotlinpoet.KModifier 31 | import com.squareup.kotlinpoet.ksp.toKModifier 32 | 33 | internal val TypeCompileScope.mutableCopyKt: FileSpec 34 | get() = 35 | buildFile(target.mutable.reflectionName()) { 36 | addGeneratedMarker() 37 | addDslMarkerClass() 38 | addMutableCopy() 39 | addFreezeFunction() 40 | addToMutateFunction() 41 | addCopyClosure() 42 | 43 | if (typeCategory is Sealed) { 44 | addRetrofittedCopyFunction() 45 | } 46 | } 47 | 48 | internal fun FileCompilerScope.addMutableCopy() { 49 | with(element) { 50 | file.addClass(target.mutable) { 51 | visibility.toKModifier()?.let { addModifiers(it) } 52 | addAnnotation(target.dslMarker) 53 | addTypeVariables(typeVariableNames.map { it.makeInvariant() }) 54 | primaryConstructor { 55 | mutationInfo.forEach { (property, mutationInfo) -> 56 | with(property) { 57 | addParameter( 58 | name = baseName, 59 | type = mutationInfo.className, 60 | modifiers = parameterModifiers, 61 | ) 62 | addMutableProperty( 63 | name = baseName, 64 | type = mutationInfo.className, 65 | modifiers = propertyModifiers, 66 | initializer = baseName, 67 | ) 68 | } 69 | } 70 | addParameter(name = "old", type = target.parameterized) 71 | addProperty(name = "old", type = target.parameterized, initializer = "old") 72 | } 73 | } 74 | } 75 | } 76 | 77 | internal fun FileCompilerScope.addFreezeFunction() { 78 | with(element) { 79 | onKnownCategory { category -> 80 | addFunction(name = "freeze", receives = target.mutable.parameterized, returns = target.parameterized) { 81 | visibility.toKModifier()?.let { addModifiers(it) } 82 | addReturn( 83 | when (category) { 84 | Known.Class -> error("Plain classes are not supported as mutable") 85 | Data, Value -> "${target.canonicalName}(${mutationInfo.joinAsAssignmentsWithMutation { freeze(it) }})" 86 | Sealed -> 87 | sealedTypes.joinWithWhen(subject = "old") { type -> 88 | "is ${type.fullName} -> old.copy(${mutationInfo.joinAsAssignmentsWithMutation { freeze(it) }})" 89 | } 90 | }, 91 | ) 92 | } 93 | } 94 | } 95 | } 96 | 97 | internal fun FileCompilerScope.addToMutateFunction() { 98 | with(element) { 99 | val parameterized = target.mutable.parameterized 100 | addFunction(name = "toMutable", receives = target.parameterized, returns = parameterized) { 101 | visibility.toKModifier()?.let { addModifiers(it) } 102 | addReturn("$parameterized(old = this, ${mutationInfo.joinAsAssignmentsWithMutation { toMutable(it) }})") 103 | } 104 | } 105 | } 106 | 107 | internal fun FileCompilerScope.addCopyClosure() { 108 | with(element) { 109 | val parameterized = target.mutable.parameterized 110 | addCopyFunction { 111 | addParameter(name = "block", type = parameterized.asReceiverConsumer()) 112 | addReturn("toMutable().apply(block).freeze()") 113 | } 114 | } 115 | } 116 | 117 | private fun FileCompilerScope.addRetrofittedCopyFunction() { 118 | with(element) { 119 | addCopyFunction { 120 | properties.forEachRun { addParameter(name = baseName, type = typeName, defaultValue = "this.$baseName") } 121 | addReturn( 122 | sealedTypes.joinWithWhen { type -> 123 | "is ${type.fullName} -> this.copy(${properties.joinToString { "${it.baseName} = ${it.baseName}" }})" 124 | }, 125 | ) 126 | } 127 | } 128 | } 129 | 130 | internal fun FileCompilerScope.addCopyFunction(block: FunSpec.Builder.() -> Unit) { 131 | with(element) { 132 | addInlinedFunction(name = "copy", receives = target.parameterized, returns = target.parameterized) { 133 | visibility.toKModifier()?.let { addModifiers(it) } 134 | block() 135 | } 136 | } 137 | } 138 | 139 | private fun FileCompilerScope.addDslMarkerClass() { 140 | file.addClass(element.target.dslMarker) { 141 | addAnnotation(DslMarker::class) 142 | addModifiers(KModifier.ANNOTATION) 143 | } 144 | } 145 | -------------------------------------------------------------------------------- /utils/kotlin-poet/src/main/kotlin/at/kopyk/poet/KotlinPoetExtensions.kt: -------------------------------------------------------------------------------- 1 | package at.kopyk.poet 2 | 3 | import com.google.devtools.ksp.processing.CodeGenerator 4 | import com.google.devtools.ksp.symbol.KSClassDeclaration 5 | import com.google.devtools.ksp.symbol.KSDeclaration 6 | import com.google.devtools.ksp.symbol.KSName 7 | import com.google.devtools.ksp.symbol.KSPropertyDeclaration 8 | import com.google.devtools.ksp.symbol.Modifier 9 | import com.squareup.kotlinpoet.ClassName 10 | import com.squareup.kotlinpoet.FileSpec 11 | import com.squareup.kotlinpoet.KModifier 12 | import com.squareup.kotlinpoet.LambdaTypeName 13 | import com.squareup.kotlinpoet.ParameterizedTypeName 14 | import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy 15 | import com.squareup.kotlinpoet.TypeName 16 | import com.squareup.kotlinpoet.UNIT 17 | import com.squareup.kotlinpoet.ksp.toKModifier 18 | import com.squareup.kotlinpoet.ksp.writeTo 19 | 20 | private val notWantedModifiers: List = 21 | listOf(Modifier.OVERRIDE, Modifier.OPEN, Modifier.ABSTRACT) 22 | 23 | private val modifiersAllowedInParams: List = 24 | listOf(Modifier.VARARG, Modifier.NOINLINE, Modifier.CROSSINLINE) 25 | 26 | public val KSPropertyDeclaration.propertyModifiers: List 27 | get() = modifiers.mapNotNull { it.takeIf { it !in notWantedModifiers }?.toKModifier() } 28 | 29 | public val KSPropertyDeclaration.parameterModifiers: List 30 | get() = modifiers.mapNotNull { it.takeIf { it in modifiersAllowedInParams }?.toKModifier() } 31 | 32 | public fun ClassName.parameterizedWhenNotEmpty(typeArguments: List): TypeName = 33 | takeIf { typeArguments.isNotEmpty() }?.parameterizedBy(typeArguments)?.copy(nullable = this.isNullable) ?: this 34 | 35 | public fun FileSpec.writeTo(codeGenerator: CodeGenerator) { 36 | writeTo(codeGenerator = codeGenerator, aggregating = false) 37 | } 38 | 39 | public fun ClassName.map(name: (String) -> String): ClassName = ClassName(packageName, simpleNames.run { dropLast(1) + name(last()) }) 40 | 41 | public fun ClassName.append(name: String): ClassName = ClassName(packageName, simpleNames + name) 42 | 43 | public val KSDeclaration.className: ClassName 44 | get() = 45 | when (val parent = parentDeclaration) { 46 | is KSClassDeclaration -> parent.className.append(simpleName.asString()) 47 | else -> ClassName(packageName = packageName.asStringQuoted(), simpleName.asString()) 48 | } 49 | 50 | public fun KSName.asStringQuoted(): String = 51 | asString().split('.').joinToString(separator = ".") { 52 | when (it) { 53 | in KEYWORDS -> "`$it`" 54 | else -> it 55 | } 56 | } 57 | 58 | public fun TypeName.asTransformLambda(): LambdaTypeName = LambdaTypeName.get(parameters = arrayOf(this), returnType = this) 59 | 60 | public fun TypeName.asTransformLambda(receiver: TypeName): LambdaTypeName = 61 | LambdaTypeName.get(receiver = receiver, parameters = arrayOf(this), returnType = this) 62 | 63 | public fun TypeName.asReceiverConsumer(): LambdaTypeName = LambdaTypeName.get(receiver = this, returnType = UNIT) 64 | 65 | public fun ClassName.flattenWithSuffix(suffix: String): ClassName { 66 | val mutableSimpleName = (simpleNames + suffix).joinToString(separator = "$") 67 | return ClassName(packageName, mutableSimpleName).copy(this.isNullable, emptyList(), emptyMap()) 68 | } 69 | 70 | public fun ParameterizedTypeName.flattenWithSuffix(suffix: String): ParameterizedTypeName { 71 | val mutableSimpleName = (rawType.simpleNames + suffix).joinToString(separator = "$") 72 | return ClassName( 73 | rawType.packageName, 74 | mutableSimpleName, 75 | ).copy(this.isNullable, emptyList(), emptyMap()).parameterizedBy(this.typeArguments) 76 | } 77 | 78 | // https://kotlinlang.org/docs/reference/keyword-reference.html 79 | private val KEYWORDS = 80 | setOf( 81 | // Hard keywords 82 | "as", 83 | "break", 84 | "class", 85 | "continue", 86 | "do", 87 | "else", 88 | "false", 89 | "for", 90 | "fun", 91 | "if", 92 | "in", 93 | "interface", 94 | "is", 95 | "null", 96 | "object", 97 | "package", 98 | "return", 99 | "super", 100 | "this", 101 | "throw", 102 | "true", 103 | "try", 104 | "typealias", 105 | "typeof", 106 | "val", 107 | "var", 108 | "when", 109 | "while", 110 | // Soft keywords 111 | "by", 112 | "catch", 113 | "constructor", 114 | "delegate", 115 | "dynamic", 116 | "field", 117 | "file", 118 | "finally", 119 | "get", 120 | "import", 121 | "init", 122 | "param", 123 | "property", 124 | "receiver", 125 | "set", 126 | "setparam", 127 | "where", 128 | // Modifier keywords 129 | "actual", 130 | "abstract", 131 | "annotation", 132 | "companion", 133 | "const", 134 | "crossinline", 135 | "data", 136 | "enum", 137 | "expect", 138 | "external", 139 | "final", 140 | "infix", 141 | "inline", 142 | "inner", 143 | "internal", 144 | "lateinit", 145 | "noinline", 146 | "open", 147 | "operator", 148 | "out", 149 | "override", 150 | "private", 151 | "protected", 152 | "public", 153 | "reified", 154 | "sealed", 155 | "suspend", 156 | "tailrec", 157 | "value", 158 | "vararg", 159 | // These aren't keywords anymore but still break some code if unescaped. https://youtrack.jetbrains.com/issue/KT-52315 160 | "header", 161 | "impl", 162 | // Other reserved keywords 163 | "yield", 164 | ) 165 | -------------------------------------------------------------------------------- /docs/mutable-utils/styles/main.css: -------------------------------------------------------------------------------- 1 | /*! 2 | * Copyright 2014-2023 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. 3 | */#pages-search{cursor:pointer;border:none;border-radius:50%;background:transparent;fill:#fff;fill:var(--dark-mode-and-search-icon-color)}#pages-search:focus{outline:none}#pages-search:hover{background:var(--white-10)}.search,.search [data-test=ring-select],.search [data-test=ring-tooltip],.search [data-test=ring-select_focus],.search #pages-search{display:inline-block;padding:0;margin:0;font-size:0;line-height:0}.search-hotkey-popup{background-color:var(--background-color) !important;padding:4px}.popup-wrapper{min-width:calc(100% - 322px) !important;border:1px solid rgba(255,255,255,.2) !important;background-color:#27282c !important}.popup-wrapper [class^=filterWrapper]{border-bottom:1px solid rgba(255,255,255,.2)}.popup-wrapper input{color:rgba(255,255,255,.8) !important;font-weight:normal !important}.popup-wrapper span[data-test-custom=ring-select-popup-filter-icon]{color:#fff}.popup-wrapper button[data-test=ring-input-clear]{color:#fff !important}@media screen and (max-width: 759px){.popup-wrapper{min-width:100% !important}}.template-wrapper{display:grid;height:32px;grid-template-columns:auto auto}.template-wrapper strong{color:rgba(255,255,255,.8)}.template-wrapper span{color:rgba(255,255,255,.8);line-height:32px}.template-wrapper span.template-description{color:rgba(255,255,255,.6);justify-self:end}@media screen and (max-width: 759px){.template-wrapper{display:flex;flex-direction:column;height:auto}.template-wrapper span{line-height:unset}}.template-name{justify-self:start}[class^=fade]{display:none}[class*=hover]{background-color:rgba(255,255,255,.1) !important} 4 | /* stylelint-disable color-no-hex */ 5 | 6 | :root { 7 | --ring-unit: 8px; 8 | 9 | /* Element */ 10 | --ring-line-color: #dfe5eb; 11 | --ring-dark-line-color: #475159; 12 | --ring-borders-color: #b8d1e5; 13 | --ring-dark-borders-color: #406380; 14 | --ring-icon-color: var(--ring-borders-color); 15 | --ring-icon-secondary-color: #999; 16 | --ring-border-disabled-color: #dbdbdb; 17 | --ring-icon-disabled-color: #bbb; 18 | --ring-border-hover-color: #80c6ff; 19 | --ring-dark-border-hover-color: #70b1e6; 20 | --ring-icon-hover-color: var(--ring-link-hover-color); 21 | --ring-main-color: #008eff; 22 | --ring-main-hover-color: #007ee5; 23 | --ring-icon-error-color: #db5860; 24 | --ring-icon-warning-color: #eda200; 25 | --ring-icon-success-color: #59a869; 26 | --ring-pale-control-color: #cfdbe5; 27 | --ring-popup-border-components: 0, 42, 76; 28 | --ring-popup-border-color: rgba(var(--ring-popup-border-components), 0.1); 29 | --ring-popup-shadow-color: rgba(var(--ring-popup-border-components), 0.15); 30 | --ring-message-shadow-color: rgba(var(--ring-popup-border-components), 0.3); 31 | --ring-pinned-shadow-color: #737577; 32 | 33 | /* Text */ 34 | --ring-search-color: #669ecc; 35 | --ring-hint-color: #406380; 36 | --ring-link-color: #0f5b99; 37 | --ring-link-hover-color: #ff008c; 38 | --ring-error-color: #c22731; 39 | --ring-warning-color: #cc8b00; 40 | --ring-success-color: #1b8833; 41 | --ring-text-color: #1f2326; 42 | --ring-dark-text-color: #fff; 43 | --ring-heading-color: var(--ring-text-color); 44 | --ring-secondary-color: #737577; 45 | --ring-dark-secondary-color: #888; 46 | --ring-disabled-color: #999; 47 | --ring-dark-disabled-color: #444; 48 | --ring-dark-active-color: #ccc; 49 | 50 | /* Background */ 51 | --ring-content-background-color: #fff; 52 | --ring-popup-background-color: #fff; 53 | --ring-sidebar-background-color: #f7f9fa; 54 | --ring-selected-background-color: #d4edff; 55 | --ring-hover-background-color: #ebf6ff; 56 | --ring-dark-selected-background-color: #002a4d; 57 | --ring-message-background-color: #111314; 58 | --ring-navigation-background-color: #000; 59 | --ring-tag-background-color: #e6ecf2; 60 | --ring-removed-background-color: #ffd5cb; 61 | --ring-warning-background-color: #faeccd; 62 | --ring-added-background-color: #bce8bb; 63 | 64 | /* Code */ 65 | --ring-code-background-color: var(--ring-content-background-color); 66 | --ring-code-color: #000; 67 | --ring-code-comment-color: #707070; 68 | --ring-code-meta-color: #707070; 69 | --ring-code-keyword-color: #000080; 70 | --ring-code-tag-background-color: #efefef; 71 | --ring-code-tag-color: var(--ring-code-keyword-color); 72 | --ring-code-tag-font-weight: bold; 73 | --ring-code-field-color: #660e7a; 74 | --ring-code-attribute-color: #00f; 75 | --ring-code-number-color: var(--ring-code-attribute-color); 76 | --ring-code-string-color: #007a00; 77 | --ring-code-addition-color: #aadeaa; 78 | --ring-code-deletion-color: #c8c8c8; 79 | 80 | /* Metrics */ 81 | --ring-border-radius: 3px; 82 | --ring-border-radius-small: 2px; 83 | --ring-font-size-larger: 14px; 84 | --ring-font-size: 13px; 85 | --ring-font-size-smaller: 12px; 86 | --ring-line-height-taller: 21px; 87 | --ring-line-height: 20px; 88 | --ring-line-height-lower: 18px; 89 | --ring-line-height-lowest: 16px; 90 | --ring-ease: 0.3s ease-out; 91 | --ring-fast-ease: 0.15s ease-out; 92 | --ring-font-family: system-ui, Arial, sans-serif; 93 | --ring-font-family-monospace: 94 | Menlo, 95 | "Bitstream Vera Sans Mono", 96 | "Ubuntu Mono", 97 | Consolas, 98 | "Courier New", 99 | Courier, 100 | monospace; 101 | 102 | /* Common z-index-values */ 103 | 104 | /* Invisible element is an absolutely positioned element which should be below */ 105 | /* all other elements on the page */ 106 | --ring-invisible-element-z-index: -1; 107 | 108 | /* z-index for position: fixed elements */ 109 | --ring-fixed-z-index: 1; 110 | 111 | /* Elements that should overlay all other elements on the page */ 112 | --ring-overlay-z-index: 5; 113 | 114 | /* Alerts should de displayed above overlays */ 115 | --ring-alert-z-index: 6; 116 | } 117 | 118 | /*! 119 | * Copyright 2014-2023 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. 120 | *//*! 121 | * Copyright 2014-2023 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. 122 | */html,.app-root{height:100%}.search-root{margin:0;padding:0;background:var(--ring-content-background-color);font-family:var(--ring-font-family);font-size:var(--ring-font-size);line-height:var(--ring-line-height)}.search-content{z-index:8} 123 | 124 | /*# sourceMappingURL=main.css.map*/ -------------------------------------------------------------------------------- /kopykat-ksp/src/test/kotlin/at/kopyk/MutableCopyTest.kt: -------------------------------------------------------------------------------- 1 | package at.kopyk 2 | 3 | import org.junit.jupiter.api.Test 4 | 5 | class MutableCopyTest { 6 | @Test 7 | fun `mutate one property`() { 8 | """ 9 | |data class Person(val name: String, val age: Int) 10 | | 11 | |val p1 = Person("Alex", 1) 12 | |val p2 = p1.copy { age = age + 1 } 13 | |val r = p2.age 14 | """.evals("r" to 2) 15 | } 16 | 17 | @Test 18 | fun `mutate one property, internal`() { 19 | """ 20 | |internal data class Person(val name: String, val age: Int) 21 | | 22 | |internal val p1 = Person("Alex", 1) 23 | |internal val p2 = p1.copy { age = age + 1 } 24 | |val r = p2.age 25 | """.evals("r" to 2) 26 | } 27 | 28 | @Test 29 | fun `weird package name, issue #78`() { 30 | """ 31 | |package `this`.`in`.other 32 | | 33 | |data class Person(val name: String, val age: Int) 34 | | 35 | |val p1 = Person("Alex", 1) 36 | |val p2 = p1.copy { age = age + 1 } 37 | |val r = p2.age 38 | """.evals("r" to 2) 39 | } 40 | 41 | @Test 42 | fun `mutate one property, nested class`() { 43 | """ 44 | |class Things { 45 | | data class Person(val name: String, val age: Int) 46 | |} 47 | | 48 | |val p1 = Things.Person("Alex", 1) 49 | |val p2 = p1.copy { age = age + 1 } 50 | |val r = p2.age 51 | """.evals("r" to 2) 52 | } 53 | 54 | @Test 55 | fun `mutate one property, nullable type`() { 56 | """ 57 | |data class Person(val name: String, val age: Int?) 58 | | 59 | |val p1 = Person("Alex", 1) 60 | |val p2 = p1.copy { age = age?.let { it + 1 } } 61 | |val r = p2.age 62 | """.evals("r" to 2) 63 | } 64 | 65 | @Test 66 | fun `mutate one property, nullable type, set to null`() { 67 | """ 68 | |data class Person(val name: String, val age: Int?) 69 | | 70 | |val p1 = Person("Alex", 1) 71 | |val p2 = p1.copy { age = null } 72 | |val r = p2.age 73 | """.evals("r" to null) 74 | } 75 | 76 | @Test 77 | fun `mutate two properties`() { 78 | """ 79 | |data class Person(val name: String, val age: Int) 80 | | 81 | |val p1 = Person("Alex", 1) 82 | |val p2 = p1.copy { 83 | | name = name + " Serrano" 84 | | age = age + 1 85 | |} 86 | |val r = p2.age 87 | |val n = p2.name 88 | """.evals("r" to 2, "n" to "Alex Serrano") 89 | } 90 | 91 | @Test 92 | fun `mutate two properties (advanced)`() { 93 | """ 94 | |data class Person(val name: String, val age: Int) 95 | | 96 | |val p1 = Person("Alex", 1) 97 | |val p2 = p1.copy { 98 | | name = "${"\$"}name Serrano" 99 | | age++ 100 | |} 101 | |val r = p2.age 102 | |val n = p2.name 103 | """.evals("r" to 2, "n" to "Alex Serrano") 104 | } 105 | 106 | @Test 107 | fun `empty transform does nothing`() { 108 | """ 109 | |data class Person(val name: String, val age: Int) 110 | | 111 | |val p1 = Person("Alex", 1) 112 | |val p2 = p1.copy { } 113 | |val r = p2.age 114 | """.evals("r" to 1) 115 | } 116 | 117 | @Test 118 | fun `access the old value`() { 119 | """ 120 | |data class Person(val name: String, val age: Int) 121 | | 122 | |val p1 = Person("Alex", 1) 123 | |val p2 = p1.copy { 124 | | age++ 125 | | age = old.age 126 | | } 127 | |val r = p2.age 128 | """.evals("r" to 1) 129 | } 130 | 131 | @Test 132 | fun `works on generic classes`() { 133 | """ 134 | |data class Person(val name: String, val age: A) 135 | | 136 | |val p1: Person = Person("Alex", 1) 137 | |val p2 = p1.copy { age = age + 1 } 138 | |val r = p2.age 139 | """.evals("r" to 2) 140 | } 141 | 142 | @Test 143 | fun `each for lists`() { 144 | """ 145 | |data class Person(val name: String, val age: Int, val anns: List) 146 | | 147 | |val p1: Person = Person("Alex", 1, listOf(1, 10)) 148 | |val p2 = p1.copy { anns.forEachIndexed { i, v -> anns[i] = v + 1 } } 149 | |val r = p2.anns 150 | """.evals("r" to listOf(2, 11)) 151 | } 152 | 153 | @Test 154 | fun `each for maps`() { 155 | """ 156 | |data class Person(val name: String, val age: Int, val things: Map) 157 | | 158 | |val p1: Person = Person("Alex", 1, mapOf("chair" to 1, "pencil" to 10)) 159 | |val p2 = p1.copy { things.forEach { (k, v) -> things[k] = v + 1 } } 160 | |val r = p2.things 161 | """.evals("r" to mapOf("chair" to 2, "pencil" to 11)) 162 | } 163 | 164 | @Test 165 | fun `typealias test`() { 166 | """ 167 | |import at.kopyk.CopyExtensions 168 | | 169 | |@CopyExtensions 170 | |typealias Person = Pair 171 | | 172 | |val p1 = "Alex" to 1 173 | |val p2 = p1.copy { second++ } 174 | |val r = p2.second 175 | """.evals("r" to 2) 176 | } 177 | 178 | @Test 179 | fun `typealias test, full generic`() { 180 | """ 181 | |import at.kopyk.CopyExtensions 182 | | 183 | |@CopyExtensions 184 | |typealias Pareja = Pair 185 | | 186 | |val p1: Pareja = "Alex" to 1 187 | |val p2 = p1.copy { second++ } 188 | |val r = p2.second 189 | """.evals("r" to 2) 190 | } 191 | 192 | @Test 193 | fun `typealias test, half generic`() { 194 | """ 195 | |import at.kopyk.CopyExtensions 196 | | 197 | |@CopyExtensions 198 | |typealias Named = Pair 199 | | 200 | |val p1: Named = "Alex" to 1 201 | |val p2 = p1.copy { second++ } 202 | |val r = p2.second 203 | """.evals("r" to 2) 204 | } 205 | 206 | @Test 207 | fun `issue #83, check null`() { 208 | """ 209 | |data class Person(val d: List? = null) 210 | | 211 | |val p = Person(listOf("e")) 212 | |val p2 = p.copy { d = null } 213 | |val r = p2.d 214 | """.evals("r" to null) 215 | } 216 | 217 | @Test 218 | fun `issue #83, check add`() { 219 | """ 220 | |data class Person(val d: List? = null) 221 | | 222 | |val p = Person(listOf("e")) 223 | |val p2 = p.copy { d?.add("f") ; Unit } 224 | |val r = p2.d 225 | """.evals("r" to listOf("e", "f")) 226 | } 227 | } 228 | -------------------------------------------------------------------------------- /mutable-utils/src/main/kotlin/at/kopyk/MutableCollection.kt: -------------------------------------------------------------------------------- 1 | package at.kopyk 2 | 3 | /** 4 | * Applies [transform] to each element in the collection, 5 | * reusing the same structure to keep them. 6 | * 7 | * The mutable equivalent to [Collection.map]. 8 | * 9 | * ```kotlin 10 | * val p = Person(name = "John", job = Job("Developer", listOf("Kotlin", "Training"))) 11 | * val newP = p.copy { // mutates the job.teams collection in-place 12 | * job.teams.mutateAll { it.capitalize() } 13 | * } 14 | * ``` 15 | * 16 | * _Note_: this function removes in-place only if [A] is a [MutableList], 17 | * otherwise it clears the collection and re-adds the values. 18 | */ 19 | public inline fun , A> T.mutateAll(transform: (A) -> A): T = mutateAllNotNull(transform) 20 | 21 | /** 22 | * Applies [transform] to each element in the collection with the current item index, 23 | * reusing the same structure to keep them. 24 | * 25 | * The mutable equivalent to [Collection.mapIndexed]. 26 | * 27 | * ```kotlin 28 | * val p = Person(name = "John", job = Job("Developer", listOf("Kotlin", "Training"))) 29 | * val newP = p.copy { // mutates the job.teams collection in-place 30 | * job.teams.mutateAllIndexed { i, team -> "${i + 1}." + team } 31 | * } 32 | * ``` 33 | * 34 | * _Note_: this function removes in-place only if [A] is a [MutableList], 35 | * otherwise it clears the collection and re-adds the values. 36 | */ 37 | public inline fun , A> T.mutateAllIndexed(transform: (index: Int, value: A) -> A): T = 38 | mutateAllIndexedNotNull(transform) 39 | 40 | /** 41 | * Applies [transform] to each element in the collection, 42 | * removing the item if `null` is returned. 43 | * 44 | * The mutable equivalent to [Collection.mapNotNull]. 45 | * 46 | * _Note_: this function removes in-place only if [A] is a [MutableList], 47 | * otherwise it clears the collection and re-adds the values. 48 | */ 49 | @Suppress("UNCHECKED_CAST") // Ah, good old erasure 50 | public inline fun , A> T.mutateAllNotNull( 51 | transform: (A) -> A?, 52 | ): T = 53 | apply { 54 | (this as? MutableList)?.mutateAllNotNull(transform) ?: clearThenAddAllNotNull(transform) 55 | } 56 | 57 | /** 58 | * Applies [transform] to each element in the list, 59 | * removing the item if `null` is returned. 60 | * 61 | * The mutable equivalent to [List.mapNotNull]. 62 | * 63 | * ```kotlin 64 | * val p = Person(name = "John", job = Job("Developer", listOf("Kotlin", "Training"))) 65 | * val newP = p.copy { // mutates the job.teams collection in-place 66 | * job.teams.mutateAllNotNull { it.takeUnless { it.startsWith("admin-") } } 67 | * } 68 | * ``` 69 | */ 70 | public inline fun MutableList.mutateAllNotNull(transform: (A) -> A?): MutableList = 71 | apply { 72 | with(listIterator()) { while (hasNext()) transform(next())?.let(::set) ?: remove() } 73 | } 74 | 75 | /** 76 | * Removes all elements in a collection and transforms them, 77 | * leaving out any that are transformed to `null`. 78 | */ 79 | public inline fun , A> T.clearThenAddAllNotNull(transform: (A) -> A?): T = 80 | apply { 81 | val remaining = mapNotNull(transform) 82 | clear() 83 | addAll(remaining) 84 | } 85 | 86 | /** 87 | * Applies [transform] to each element in the list with the current item index, 88 | * removing the value if `null` is returned. 89 | * 90 | * The mutable equivalent to [Collection.mapIndexedNotNull]. 91 | * 92 | * ```kotlin 93 | * val p = Person(name = "John", job = Job("Developer", listOf("Kotlin", "Training"))) 94 | * val newP = p.copy { // mutates the job.teams collection in-place 95 | * job.teams.mutateAllIndexedNotNull { i, team -> team.takeIf { i % 2 == 0 } } 96 | * } 97 | * ``` 98 | * 99 | * _Note_: this function removes in-place only if [A] is a [MutableList], 100 | * otherwise it clears the collection and re-adds the values. 101 | */ 102 | public inline fun , A> T.mutateAllIndexedNotNull(transform: (index: Int, value: A) -> A?): T { 103 | var index = 0 104 | return mutateAllNotNull { transform(index++, it) } 105 | } 106 | 107 | /** 108 | * Removes any items in the list that are not type [A] and 109 | * returns a [MutableCollection]<[A]> with the remaining items. 110 | * 111 | * The mutable equivalent to [Collection.filterIsInstance]. 112 | * 113 | * _Note_: this function removes in-place only if [A] is a [MutableList], 114 | * otherwise it clears the collection and re-adds the values. 115 | */ 116 | @Suppress("UNCHECKED_CAST") // The one time that type erasure is not annoying 117 | public inline fun MutableCollection<*>.removeUnlessInstanceOf(): MutableCollection = 118 | (this as MutableCollection).mutateAllNotNull { it as? A } as MutableCollection 119 | 120 | /** 121 | * Removes any items in the list that are not type [A] and 122 | * returns a [MutableList]<[A]> with the remaining items. 123 | * 124 | * The mutable equivalent to [List.filterIsInstance]. 125 | * 126 | * ```kotlin 127 | * sealed interface Item { 128 | * data class SoldOut(val name: String) : Item 129 | * data class Available(val name: String, val remaining: Int) : Item 130 | * } 131 | * 132 | * data class Catalog(val items: List) 133 | * 134 | * fun filterAvailable(catalog: Catalog) = 135 | * catalog.copy { 136 | * items.removeUnlessInstanceOf() 137 | * } 138 | * ``` 139 | * 140 | * The returned value is a typed mutable collection 141 | * where we can do further modifications with the right type, 142 | * saving you having to do further type checks. 143 | * 144 | * ```kotlin 145 | * items.removeUnlessInstanceOf() 146 | * .mutateAll { item -> item.remaining-- } 147 | * ``` 148 | */ 149 | @Suppress("UNCHECKED_CAST") // The one time that type erasure is not annoying 150 | public inline fun MutableList<*>.removeUnlessInstanceOf(): MutableList = 151 | (this as MutableList).mutateAllNotNull { it as? A } as MutableList 152 | 153 | /** 154 | * Removes any items in the list that are not type [A] and 155 | * returns a [MutableSet]<[A]> with the remaining items. 156 | * 157 | * The mutable equivalent to [Set.filterIsInstance]. 158 | */ 159 | @Suppress("UNCHECKED_CAST") // The one time that type erasure is not annoying 160 | public inline fun MutableSet<*>.removeUnlessInstanceOf(): MutableSet = 161 | (this as MutableSet).mutateAllNotNull { it as? A } as MutableSet 162 | -------------------------------------------------------------------------------- /docs/mutable-utils/mutable-utils/at.kopyk/clear-then-add-all-not-null.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | clearThenAddAllNotNull 6 | 7 | 8 | 9 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 |
38 | 59 |
60 | 63 |
64 |
65 | 66 |
67 |

clearThenAddAllNotNull

68 |
69 |
inline fun <T : MutableCollection<A>, A> T.clearThenAddAllNotNull(transform: (A) -> A?): T

Removes all elements in a collection and transforms them, leaving out any that are transformed to null.

70 |
71 | 76 |
77 |
78 |
79 | 80 | 81 | -------------------------------------------------------------------------------- /docs/mutable-utils/mutable-utils/at.kopyk/remove-values-unless-instance-of.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | removeValuesUnlessInstanceOf 6 | 7 | 8 | 9 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 |
38 | 59 |
60 | 63 |
64 |
65 | 66 |
67 |

removeValuesUnlessInstanceOf

68 |
69 |

Removes any values in the map that are not type V and returns a MutableMap<K, V> with the remaining entries.

70 |
71 | 76 |
77 |
78 |
79 | 80 | 81 | -------------------------------------------------------------------------------- /kopykat-ksp/src/main/kotlin/at/kopyk/CopyConstructors.kt: -------------------------------------------------------------------------------- 1 | package at.kopyk 2 | 3 | import at.kopyk.poet.addReturn 4 | import at.kopyk.poet.append 5 | import at.kopyk.poet.className 6 | import at.kopyk.utils.ClassCompileScope 7 | import at.kopyk.utils.TypeCompileScope 8 | import at.kopyk.utils.addGeneratedMarker 9 | import at.kopyk.utils.baseName 10 | import at.kopyk.utils.fullName 11 | import at.kopyk.utils.getPrimaryConstructorProperties 12 | import at.kopyk.utils.lang.takeIfInstanceOf 13 | import at.kopyk.utils.minimal 14 | import com.google.devtools.ksp.getVisibility 15 | import com.google.devtools.ksp.symbol.KSAnnotated 16 | import com.google.devtools.ksp.symbol.KSAnnotation 17 | import com.google.devtools.ksp.symbol.KSClassDeclaration 18 | import com.google.devtools.ksp.symbol.KSPropertyDeclaration 19 | import com.google.devtools.ksp.symbol.KSType 20 | import com.squareup.kotlinpoet.FileSpec 21 | import com.squareup.kotlinpoet.ksp.toKModifier 22 | 23 | internal data class CopyPair( 24 | val self: TypeCompileScope, 25 | val from: KSClassDeclaration, 26 | val to: KSClassDeclaration, 27 | ) 28 | 29 | internal val ClassCompileScope.allCopies: Sequence 30 | get() = 31 | sequence { 32 | val copyFromTargets = typesFor() + typesFor() 33 | val copyToTargets = typesFor() + typesFor() 34 | 35 | val self = this@allCopies 36 | 37 | fun pair( 38 | from: KSClassDeclaration, 39 | to: KSClassDeclaration, 40 | ) = CopyPair(self, from, to) 41 | yieldAll(copyFromTargets.map { other -> pair(other, self) }) 42 | yieldAll(copyToTargets.map { other -> pair(self, other) }) 43 | } 44 | 45 | internal val CopyPair.name get() = nameFor(from, to) 46 | 47 | internal fun nameFor( 48 | from: KSClassDeclaration, 49 | to: KSClassDeclaration, 50 | ) = from.className.append(to.baseName).reflectionName() 51 | 52 | internal fun fileSpec( 53 | others: Sequence, 54 | copyPair: CopyPair, 55 | ): FileSpec? = 56 | with(copyPair) { 57 | when { 58 | from.isIsomorphicOf(others, to) -> self.copyConstructorFileSpec(copyPair, others) 59 | else -> self.reportMismatchedProperties(copyPair) 60 | } 61 | } 62 | 63 | private fun TypeCompileScope.copyConstructorFileSpec( 64 | copyPair: CopyPair, 65 | others: Sequence, 66 | ): FileSpec = 67 | with(copyPair) { 68 | buildFile(fileName = name) { 69 | addGeneratedMarker() 70 | addInlinedFunction(name = to.baseName, receives = null, returns = to.className.parameterized) { 71 | addParameter(name = "from", type = from.className) 72 | val visibilities = listOf(from.getVisibility()) + from.getAllProperties().map { it.getVisibility() } 73 | visibilities.minimal().toKModifier()?.let { addModifiers(it) } 74 | val propertyAssignments = 75 | to.properties.toList().zipByName(from.getAllProperties().toList()) { to, from -> 76 | propertyDefinition(others, from, to) 77 | }.filterNotNull() 78 | addReturn("${to.baseName}(${propertyAssignments.joinToString()})") 79 | } 80 | } 81 | } 82 | 83 | private fun TypeCompileScope.reportMismatchedProperties(copyPair: CopyPair): Nothing? = 84 | with(copyPair) { 85 | val message = "${to.fullName} must have the same constructor properties as ${from.fullName}" 86 | logger.error(message = message, symbol = self) 87 | null 88 | } 89 | 90 | private fun propertyDefinition( 91 | others: Sequence, 92 | from: KSPropertyDeclaration, 93 | to: KSPropertyDeclaration, 94 | ): String? { 95 | val fromType = from.typeDeclaration 96 | val toType = to.typeDeclaration 97 | val propertyName = from.baseName 98 | return when { 99 | fromType == null || toType == null -> null 100 | others.hasCopyConstructor(fromType, toType) -> "$propertyName = ${toType.baseName}(from.$propertyName)" 101 | else -> "$propertyName = from.$propertyName" 102 | } 103 | } 104 | 105 | private val KSPropertyDeclaration.typeDeclaration 106 | get() = type.resolve().declaration.takeIfInstanceOf() 107 | 108 | private fun KSClassDeclaration.isIsomorphicOf( 109 | copies: Sequence, 110 | other: KSClassDeclaration, 111 | ): Boolean { 112 | val properties = getAllProperties().toSet() 113 | val otherProperties = other.getPrimaryConstructorProperties().toSet() 114 | if (properties.size != otherProperties.size) return false 115 | if (properties.names.toSet() != otherProperties.names.toSet()) return false 116 | otherProperties.zipByName(properties) { property, otherProperty -> 117 | if (!property.isCopiableTo(copies, otherProperty)) return@isIsomorphicOf false 118 | } 119 | return true 120 | } 121 | 122 | private val Iterable.names get() = map { it.baseName } 123 | 124 | private fun KSPropertyDeclaration.isCopiableTo( 125 | copies: Sequence, 126 | other: KSPropertyDeclaration, 127 | ): Boolean { 128 | val thisDecl = typeDeclaration 129 | val otherDecl = other.typeDeclaration 130 | return when { 131 | thisDecl == null || otherDecl == null -> false 132 | else -> copies.hasCopyConstructor(thisDecl, otherDecl) || isAssignableFrom(other) 133 | } 134 | } 135 | 136 | private fun KSPropertyDeclaration.isAssignableFrom(other: KSPropertyDeclaration) = type.resolve().isAssignableFrom(other.type.resolve()) 137 | 138 | private fun Sequence.hasCopyConstructor( 139 | from: KSClassDeclaration, 140 | to: KSClassDeclaration, 141 | ): Boolean { 142 | val name = nameFor(from, to) 143 | return any { it.name == name } 144 | } 145 | 146 | internal inline fun ClassCompileScope.typesFor() = 147 | annotationsOf().mapNotNull { it.type?.declaration }.filterIsInstance() 148 | 149 | private val KSAnnotation.type 150 | get() = arguments.firstOrNull { it.name?.getShortName() == "type" }?.value as? KSType 151 | 152 | private inline fun KSAnnotated.annotationsOf(): Sequence = 153 | annotations.filter { 154 | it.shortName.getShortName() == T::class.simpleName && it.annotationType.resolve().declaration 155 | .qualifiedName?.asString() == T::class.qualifiedName 156 | } 157 | 158 | private inline fun Iterable.zipByName( 159 | other: Iterable, 160 | transform: (KSPropertyDeclaration, KSPropertyDeclaration) -> A, 161 | ): List = 162 | map { thisProp -> 163 | val otherProp = 164 | other.first { otherProp -> 165 | thisProp.baseName == otherProp.baseName 166 | } 167 | transform(thisProp, otherProp) 168 | } 169 | -------------------------------------------------------------------------------- /docs/mutable-utils/navigation.html: -------------------------------------------------------------------------------- 1 |
2 | 3 |
4 | 5 | 8 |
9 | 10 |
11 |
12 | 13 |
14 | 17 |
18 | 19 |
20 |
21 | 22 |
23 | 26 | 29 | 32 |
33 |
34 | 35 | -------------------------------------------------------------------------------- /kopykat-ksp/src/test/kotlin/at/kopyk/CopyConstructorsTest.kt: -------------------------------------------------------------------------------- 1 | package at.kopyk 2 | 3 | import org.junit.jupiter.api.Test 4 | import org.junit.jupiter.params.ParameterizedTest 5 | import org.junit.jupiter.params.provider.Arguments 6 | import org.junit.jupiter.params.provider.MethodSource 7 | import java.util.stream.Stream 8 | 9 | class CopyConstructorsTest { 10 | companion object { 11 | @JvmStatic 12 | fun cases(): Stream = 13 | Stream.of( 14 | Arguments.of("", ""), 15 | Arguments.of("", "data"), 16 | Arguments.of("data", ""), 17 | Arguments.of("data", "data"), 18 | ) 19 | } 20 | 21 | @ParameterizedTest(name = "{0} class CopyFrom {1} class") 22 | @MethodSource("cases") 23 | fun copyFrom( 24 | annotatedModifiers: String, 25 | targetModifiers: String, 26 | ) { 27 | """ 28 | |import at.kopyk.CopyFrom 29 | | 30 | |$targetModifiers class Person(val name: String, val age: Int) 31 | | 32 | |@CopyFrom(Person::class) 33 | |$annotatedModifiers class LocalPerson(val name: String, val age: Int) 34 | | 35 | |val p1 = Person("Alex", 1) 36 | |val p2 = LocalPerson(p1) 37 | |val r = p2.age 38 | """.evals("r" to 1) 39 | } 40 | 41 | @ParameterizedTest(name = "{0} class CopyTo {1} class") 42 | @MethodSource("cases") 43 | fun copyTo( 44 | annotatedModifiers: String, 45 | targetModifiers: String, 46 | ) { 47 | """ 48 | |import at.kopyk.CopyTo 49 | | 50 | |$targetModifiers class Person(val name: String, val age: Int) 51 | | 52 | |@CopyTo(Person::class) 53 | |$annotatedModifiers class LocalPerson(val name: String, val age: Int) 54 | | 55 | |val p1 = LocalPerson("Alex", 1) 56 | |val p2 = Person(p1) 57 | |val r = p2.age 58 | """.evals("r" to 1) 59 | } 60 | 61 | @ParameterizedTest(name = "{0} class Copy {1} class") 62 | @MethodSource("cases") 63 | fun copy( 64 | annotatedModifiers: String, 65 | targetModifiers: String, 66 | ) { 67 | """ 68 | |import at.kopyk.Copy 69 | | 70 | |$targetModifiers class Person(val name: String, val age: Int) 71 | | 72 | |@Copy(Person::class) 73 | |$annotatedModifiers class LocalPerson(val name: String, val age: Int) 74 | | 75 | |val p1 = LocalPerson("Alex", 1) 76 | |val p2 = Person(p1) 77 | |val p3 = LocalPerson(p2) 78 | |val r = p3.age 79 | """.evals("r" to 1) 80 | } 81 | 82 | @ParameterizedTest(name = "{0} class Copy {1} class, change of order") 83 | @MethodSource("cases") 84 | fun copyOrderChange( 85 | annotatedModifiers: String, 86 | targetModifiers: String, 87 | ) { 88 | """ 89 | |import at.kopyk.Copy 90 | | 91 | |$targetModifiers class Person(val name: String, val age: Int) 92 | | 93 | |@Copy(Person::class) 94 | |$annotatedModifiers class LocalPerson(val age: Int, val name: String) 95 | | 96 | |val p1 = LocalPerson(1, "Alex") 97 | |val p2 = Person(p1) 98 | |val p3 = LocalPerson(p2) 99 | |val r = p3.age 100 | """.evals("r" to 1) 101 | } 102 | 103 | @Test 104 | fun `@Copy, missing field should fail compilation`() { 105 | """ 106 | |import at.kopyk.Copy 107 | | 108 | |data class Person(val name: String) 109 | | 110 | |@Copy(Person::class) 111 | |data class LocalPerson(val name: String, val age: Int) 112 | | 113 | |val p1 = Person("Alex", 1) 114 | |val p2 = LocalPerson(p1) 115 | |val r = p2.age 116 | """.failsWith { 117 | it.contains("LocalPerson must have the same constructor properties as Person") 118 | } 119 | } 120 | 121 | @Test 122 | fun `@CopyFrom, missing field should fail compilation`() { 123 | """ 124 | |import at.kopyk.CopyFrom 125 | | 126 | |data class Person(val name: String) 127 | | 128 | |@CopyFrom(Person::class) 129 | |data class LocalPerson(val name: String, val age: Int) 130 | | 131 | |val p1 = Person("Alex", 1) 132 | |val p2 = LocalPerson(p1) 133 | |val r = p2.age 134 | """.failsWith { 135 | it.contains("LocalPerson must have the same constructor properties as Person") 136 | } 137 | } 138 | 139 | @Test 140 | fun `@CopyTo, missing field should fail compilation`() { 141 | """ 142 | |import at.kopyk.CopyTo 143 | | 144 | |data class Person(val name: String) 145 | | 146 | |@CopyTo(Person::class) 147 | |data class LocalPerson(val name: String, val age: Int) 148 | | 149 | |val p1 = Person("Alex", 1) 150 | |val p2 = LocalPerson(p1) 151 | |val r = p2.age 152 | """.failsWith { 153 | it.contains("Person must have the same constructor properties as LocalPerson") 154 | } 155 | } 156 | 157 | @Test 158 | fun `@Copy duplicated annotation`() { 159 | """ 160 | |import at.kopyk.Copy 161 | | 162 | |@Copy(LocalPerson::class) 163 | |data class Person(val name: String, val age: Int) 164 | | 165 | |@Copy(Person::class) 166 | |data class LocalPerson(val name: String, val age: Int) 167 | | 168 | |val p1 = Person("Alex", 1) 169 | |val p2 = LocalPerson(p1) 170 | |val r = p2.age 171 | """.evals("r" to 1) 172 | } 173 | 174 | @Test 175 | fun `nested copy constructors`() { 176 | """ 177 | |import at.kopyk.Copy 178 | | 179 | |data class Person(val name: String, val job: Job) 180 | | 181 | |data class Job(val title: String, val department: Department) 182 | | 183 | |@JvmInline 184 | |value class Department(val name: String) 185 | | 186 | |@Copy(Person::class) 187 | |data class LocalPerson(val name: String, val job: LocalJob) 188 | | 189 | |@Copy(Job::class) 190 | |data class LocalJob(val title: String, val department: LocalDepartment) 191 | | 192 | |@Copy(Department::class) 193 | |@JvmInline 194 | |value class LocalDepartment(val name: String) 195 | | 196 | |val p1 = LocalPerson("Alex", LocalJob("Developer", LocalDepartment("Engineering"))) 197 | |val p2 = Person(p1) 198 | |val n = p2.name 199 | |val t = p2.job.title 200 | |val d = p2.job.department.name 201 | """.evals( 202 | "n" to "Alex", 203 | "t" to "Developer", 204 | "d" to "Engineering", 205 | ) 206 | } 207 | 208 | @Test 209 | fun `multiple constructors`() { 210 | """ 211 | |import at.kopyk.Copy 212 | | 213 | |@Copy(LocalPerson::class) 214 | |@Copy(RemotePerson::class) 215 | |data class Person(val name: String, val age: Int) 216 | | 217 | |data class LocalPerson(val name: String, val age: Int) 218 | | 219 | |data class RemotePerson(val name: String, val age: Int) 220 | | 221 | |val p1 = LocalPerson("Alex", 1) 222 | |val p2 = Person(p1) 223 | |val p3 = RemotePerson(p2) 224 | |val a = p3.age 225 | """.evals("a" to 1) 226 | } 227 | } 228 | -------------------------------------------------------------------------------- /docs/mutable-utils/mutable-utils/at.kopyk/mutate-all.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | mutateAll 6 | 7 | 8 | 9 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 |
38 | 59 |
60 | 63 |
64 |
65 | 66 |
67 |

mutateAll

68 |
69 |
inline fun <T : MutableCollection<A>, A> T.mutateAll(transform: (A) -> A): T

Applies transform to each element in the collection, reusing the same structure to keep them.

The mutable equivalent to Collection.map.

val p = Person(name = "John", job = Job("Developer", listOf("Kotlin", "Training")))
val newP = p.copy { // mutates the job.teams collection in-place
job.teams.mutateAll { it.capitalize() }
}

Note: this function removes in-place only if A is a MutableList, otherwise it clears the collection and re-adds the values.

70 |
71 | 76 |
77 |
78 |
79 | 80 | 81 | --------------------------------------------------------------------------------