Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

added DisableToStringGeneration annotation #231

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# Poko

drewhamilton marked this conversation as resolved.
Show resolved Hide resolved
[![](https://github.com/drewhamilton/Poko/workflows/CI/badge.svg?branch=main)](https://github.com/drewhamilton/Poko/actions?query=workflow%3ACI+branch%3Amain)

Poko is a Kotlin compiler plugin that makes writing and maintaining data model classes for public
Expand All @@ -8,7 +9,9 @@ generates `toString`, `equals`, and `hashCode` functions. Poko is compatible wit
Multiplatform targets.

## Use

Mark your class as a `@Poko class` instead of a `data class`:

```kotlin
@Poko class MyData(
val int: Int,
Expand All @@ -28,6 +31,7 @@ is not recommended, and if they are used, it is recommended to override `equals`
manually.

### Arrays

By default, Poko does nothing to inspect the contents of array properties. [This aligns with data
classes](https://blog.jetbrains.com/kotlin/2015/09/feedback-request-limitations-on-data-classes/#Appendix.Comparingarrays).

Expand All @@ -44,14 +48,24 @@ mutating data can affect the results of `equals` and `hashCode` over time, which
unexpected. For this reason, `@ArrayContentBased` should only be used in very performance-sensitive
APIs.

### Disable `toString` generation

You can disable `toString` generation on per-class basis with `DisableToStringGeneration`
annotation.

Generated `toString` implementations add to the string pool, and can't be removed by optimizers like
`R8` due to the general widely-used nature of toString. For this reason it is desirable in some
contexts to skip `toString` and only generate `equals` and `hashCode` for internal value types.

### Annotation

By default, the `dev.drewhamilton.poko.Poko` annotation is used to mark classes for Poko generation.
If you prefer, you can create a different annotation and supply it to the Gradle plugin.
If you prefer, you can create a different annotation and supply it to the Gradle plugin.

```groovy
apply plugin: "dev.drewhamilton.poko"
poko {
pokoAnnotation.set "com.example.MyDataAnnotation"
pokoAnnotation.set "com.example.MyDataAnnotation"
}
```

Expand Down Expand Up @@ -87,6 +101,7 @@ Snapshots of the development version are available in [Sonatype's Snapshots
repository](https://oss.sonatype.org/#view-repositories;snapshots~browsestorage).

To use Poko, apply the Gradle plugin in your project:

```kotlin
// Root project:
plugins {
Expand All @@ -102,14 +117,16 @@ plugins {
\*Versions prior to 0.7.0 use plugin name `dev.drewhamilton.extracare`.

## To-do

* Generate an inner Builder class
* Propagate the constructor default values to the Builder
* Propagate the constructor default values to the Builder
* Mark the constructor as private
* Generate a top-level DSL initializer
* Write an IDE plugin?
* Multiplatform support?

## License

```
Copyright 2020 Drew Hamilton

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package dev.drewhamilton.poko

/**
* Declares that a [Poko] class will not have [Any.toString] method generated.
*/
@Retention(AnnotationRetention.SOURCE)
@Target(AnnotationTarget.CLASS)
public annotation class DisableToStringGeneration
drewhamilton marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -56,14 +56,15 @@ internal class PokoMembersTransformer(
)
}

declaration.isToString() -> declaration.convertToGenerated { properties ->
generateToStringMethodBody(
irClass = declarationParent,
functionDeclaration = declaration,
classProperties = properties,
messageCollector = messageCollector,
)
}
declaration.isToString() && !declarationParent.hasDisableToStringGenerationAnnotation() ->
declaration.convertToGenerated { properties ->
generateToStringMethodBody(
irClass = declarationParent,
functionDeclaration = declaration,
classProperties = properties,
messageCollector = messageCollector,
)
}
}
}
}
Expand All @@ -72,7 +73,7 @@ internal class PokoMembersTransformer(
}

private fun IrClass.isPokoClass(): Boolean = when {
!hasAnnotation(pokoAnnotationName.asSingleFqName()) -> {
!hasPokoClassAnnotation() -> {
messageCollector.log("Not Poko class")
false
}
Expand Down Expand Up @@ -173,4 +174,8 @@ internal class PokoMembersTransformer(
parent = this@mutateWithNewDispatchReceiverParameterForParentClass
}
}

private fun IrClass.hasPokoClassAnnotation(): Boolean {
return hasAnnotation(pokoAnnotationName.asSingleFqName())
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -134,3 +134,11 @@ internal fun IrClassSymbol.createArrayType(): IrSimpleType {
}
return createType(hasQuestionMark = false, arguments = typeArguments)
}

private val disableToStringGenerationnAnnotationFqName = ClassId(
FqName("dev.drewhamilton.poko"),
Name.identifier("DisableToStringGeneration"),
).asSingleFqName()

internal fun IrClass.hasDisableToStringGenerationAnnotation(): Boolean =
hasAnnotation(disableToStringGenerationnAnnotationFqName)
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@ package dev.drewhamilton.poko
import assertk.all
import assertk.assertThat
import assertk.assertions.contains
import assertk.assertions.doesNotContain
import assertk.assertions.isEqualTo
import assertk.assertions.isNotEqualTo
import assertk.assertions.prop
import assertk.assertions.startsWith
import com.google.testing.junit.testparameterinjector.TestParameter
import com.google.testing.junit.testparameterinjector.TestParameterInjector
import com.tschuchort.compiletesting.KotlinCompilation
Expand Down Expand Up @@ -32,10 +34,42 @@ class PokoCompilerPluginTest(

//region Primitives
@Test fun `compilation of valid class succeeds`() {
testCompilation("api/Primitives")
testCompilation("api/Primitives") { result ->
val testClass = result.classLoader.loadClass("api.Primitives")
val primaryTestInstance = testClass.declaredConstructors[0].newInstance(
"a", 1f, 2.0, 3L, 4, 5.toShort(), 6.toByte(), true
)
val cloneOfPrimaryTestInstance = testClass.declaredConstructors[0].newInstance(
"a", 1f, 2.0, 3L, 4, 5.toShort(), 6.toByte(), true
)
val otherTestInstance = testClass.declaredConstructors[0].newInstance(
"b", 8f, 9.0, 11L, 4, 9.toShort(), 1.toByte(), false
)

assertThat(primaryTestInstance).all {
prop(Any::toString).isEqualTo("Primitives(string=a, float=1.0, double=2.0, long=3, int=4, short=5, byte=6, boolean=true)")
prop(Any::hashCode).isNotEqualTo(System.identityHashCode(primaryTestInstance))

isEqualTo(primaryTestInstance)
isEqualTo(cloneOfPrimaryTestInstance)
isNotEqualTo(otherTestInstance)
}
}
}
//endregion

//region ToStringGenerationDisabled
@Test fun `compilation of valid class with disabled to string generation succeeds`() {
testCompilation("api/ToStringGenerationDisabled") { result ->
val testClass = result.classLoader.loadClass("api.ToStringGenerationDisabled")
val testInstance = testClass.declaredConstructors[0].newInstance("hello world")
// note @ at the end of assumed toString value, it indicates that default toString was used
assertThat(testInstance.toString()).startsWith("api.ToStringGenerationDisabled@")
}
}
//endregion


//region data class
@Test fun `compilation of data class fails`() {
testCompilation(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package api

import dev.drewhamilton.poko.DisableToStringGeneration
import dev.drewhamilton.poko.Poko

@DisableToStringGeneration
@Poko class ToStringGenerationDisabled(
val argument: String
)