Skip to content

Commit

Permalink
Add custom implementations for toString, equals and hashCode
Browse files Browse the repository at this point in the history
  • Loading branch information
Christian Melchior committed Aug 10, 2023
1 parent 273fd31 commit f402006
Show file tree
Hide file tree
Showing 10 changed files with 454 additions and 84 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
* None.

### Enhancements
* Realm model classes now generate custom `toString`, `equals` and `hashCode` implementations. This makes it possible to compare by object reference across multiple collections. Note that two objects at different versions will not be considered equal, even
if the content is the same. Custom implementations of these methods will be respected if they are present. (Issue [#1097](https://github.com/realm/realm-kotlin/issues/1097))
* Support for performing geospatial queries using the new classes: `GeoPoint`, `GeoCircle`, `GeoBox`, and `GeoPolygon`. See `GeoPoint` documentation on how to persist locations. (Issue [#1403](https://github.com/realm/realm-kotlin/pull/1403))
* [Sync] Add support for customizing authorization headers and adding additional custom headers to all Atlas App service requests with `AppConfiguration.Builder.authorizationHeaderName()` and `AppConfiguration.Builder.addCustomRequestHeader(...)`. (Issue [#1453](https://github.com/realm/realm-kotlin/pull/1453))

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1145,6 +1145,27 @@ internal object RealmObjectHelper {
}
}

@OptIn(ExperimentalStdlibApi::class)
@Suppress("unused") // Called from generated code
internal fun realmToString(obj: BaseRealmObject): String {
// if (objReference == null) {
// return "${obj::class.qualifiedName}[Unmanaged]@${hashCode().toHexString()}"
// } else {

// }
TODO("Custom toString")
}

@Suppress("unused") // Called from generated code
internal inline fun realmEquals(obj: BaseRealmObject, other: Any?): Boolean {
TODO("BOOM")
}

@Suppress("unused") // Called from generated code
internal inline fun realmHashCode(obj: BaseRealmObject): Int {
return 42
}

private fun checkPropertyType(
obj: RealmObjectReference<out BaseRealmObject>,
propertyName: String,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
package io.realm.kotlin.compiler

import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext
import org.jetbrains.kotlin.ir.builders.irGet
import org.jetbrains.kotlin.ir.builders.irGetObject
import org.jetbrains.kotlin.ir.builders.irReturn
import org.jetbrains.kotlin.ir.declarations.IrClass
import org.jetbrains.kotlin.ir.declarations.IrProperty
import org.jetbrains.kotlin.ir.declarations.IrSimpleFunction
import org.jetbrains.kotlin.ir.expressions.impl.IrCallImpl
import org.jetbrains.kotlin.ir.types.IrType
import org.jetbrains.kotlin.ir.util.functions
import org.jetbrains.kotlin.name.Name

/**
* Class responsible for adding Realm specific logic to the default object methods like:
* - toString()
* - hashCode()
* - equals()
*/
class RealmModelDefaultMethodGeneration(private val pluginContext: IrPluginContext) {

private val realmObjectHelper: IrClass = pluginContext.lookupClassOrThrow(FqNames.REALM_OBJECT_HELPER)
private val realmToString: IrSimpleFunction = realmObjectHelper.lookupFunction(Name.identifier("realmToString"))
private val realmEquals: IrSimpleFunction = realmObjectHelper.lookupFunction(Name.identifier("realmEquals"))
private val realmHashCode: IrSimpleFunction = realmObjectHelper.lookupFunction(Name.identifier("realmHashCode"))
private lateinit var objectReferenceProperty: IrProperty
private lateinit var objectReferenceType: IrType

fun addDefaultMethods(irClass: IrClass) {
objectReferenceProperty = irClass.lookupProperty(Names.OBJECT_REFERENCE)
objectReferenceType = objectReferenceProperty.backingField!!.type

if (syntheticMethodExists(irClass, "toString")) {
addToStringMethodBody(irClass)
}
if (syntheticMethodExists(irClass, "hashCode")) {
addHashCodeMethod(irClass)
}
if (syntheticMethodExists(irClass, "equals")) {
addEqualsMethod(irClass)
}
}

/**
* Checks if a synthetic method exists in the given class. Methods in super classes
* are ignored, only methods actually declared in the class will return `true`.
*
* These methods are created by an earlier step by the Realm compiler plugin and are
* recognized by not being fake and having an empty body.ß
*/
private fun syntheticMethodExists(irClass: IrClass, methodName: String): Boolean {
return irClass.functions.firstOrNull {
!it.isFakeOverride && it.body == null && it.name == Name.identifier(methodName)
} != null
}

private fun addEqualsMethod(irClass: IrClass) {
val function: IrSimpleFunction = irClass.symbol.owner.functions.single { it.name.toString() == "equals" }
function.body = pluginContext.blockBody(function.symbol) {
+irReturn(
IrCallImpl(
startOffset = startOffset,
endOffset = endOffset,
type = pluginContext.irBuiltIns.booleanType,
symbol = realmEquals.symbol,
typeArgumentsCount = 0,
valueArgumentsCount = 2
).apply {
dispatchReceiver = irGetObject(realmObjectHelper.symbol)
putValueArgument(0, irGet(function.dispatchReceiverParameter!!.type, function.dispatchReceiverParameter!!.symbol))
putValueArgument(1, irGet(function.dispatchReceiverParameter!!.type, function.dispatchReceiverParameter!!.symbol))
}
)
}
}

private fun addHashCodeMethod(irClass: IrClass) {
val function: IrSimpleFunction = irClass.symbol.owner.functions.single { it.name.toString() == "hashCode" }
function.body = pluginContext.blockBody(function.symbol) {
+irReturn(
IrCallImpl(
startOffset = startOffset,
endOffset = endOffset,
type = pluginContext.irBuiltIns.intType,
symbol = realmHashCode.symbol,
typeArgumentsCount = 0,
valueArgumentsCount = 1
).apply {
dispatchReceiver = irGetObject(realmObjectHelper.symbol)
putValueArgument(0, irGet(function.dispatchReceiverParameter!!.type, function.dispatchReceiverParameter!!.symbol))
}
)
}
}

private fun addToStringMethodBody(irClass: IrClass) {
val function: IrSimpleFunction = irClass.symbol.owner.functions.single { it.name.toString() == "toString" }
function.body = pluginContext.blockBody(function.symbol) {
+irReturn(
IrCallImpl(
startOffset = startOffset,
endOffset = endOffset,
type = pluginContext.irBuiltIns.stringType,
symbol = realmToString.symbol,
typeArgumentsCount = 0,
valueArgumentsCount = 1
).apply {
dispatchReceiver = irGetObject(realmObjectHelper.symbol)
putValueArgument(0, irGet(function.dispatchReceiverParameter!!.type, function.dispatchReceiverParameter!!.symbol))
}
)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,10 @@ private class RealmModelLowering(private val pluginContext: IrPluginContext) : C
// Modify properties accessor to generate custom getter/setter
AccessorModifierIrGeneration(pluginContext).modifyPropertiesAndCollectSchema(irClass)

// Add custom toString, equals and hashCode methods
val methodGenerator = RealmModelDefaultMethodGeneration(pluginContext)
methodGenerator.addDefaultMethods(irClass)

// Add body for synthetic companion methods
val companion = irClass.companionObject() ?: fatalError("RealmObject without companion: ${irClass.kotlinFqName}")
generator.addCompanionFields(irClass, companion, SchemaCollector.properties[irClass])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,9 @@ package io.realm.kotlin.compiler
import io.realm.kotlin.compiler.Names.REALM_OBJECT_COMPANION_NEW_INSTANCE_METHOD
import io.realm.kotlin.compiler.Names.REALM_OBJECT_COMPANION_SCHEMA_METHOD
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.descriptors.ClassConstructorDescriptor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.DescriptorVisibilities
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor
import org.jetbrains.kotlin.descriptors.PropertyDescriptor
import org.jetbrains.kotlin.descriptors.SimpleFunctionDescriptor
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.descriptors.impl.SimpleFunctionDescriptorImpl
Expand All @@ -33,11 +30,6 @@ import org.jetbrains.kotlin.name.SpecialNames.DEFAULT_NAME_FOR_COMPANION_OBJECT
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
import org.jetbrains.kotlin.resolve.extensions.SyntheticResolveExtension
import org.jetbrains.kotlin.resolve.lazy.LazyClassContext
import org.jetbrains.kotlin.resolve.lazy.declarations.ClassMemberDeclarationProvider
import org.jetbrains.kotlin.resolve.lazy.declarations.PackageMemberDeclarationProvider
import org.jetbrains.kotlin.types.KotlinType
import java.util.ArrayList

/**
* Triggers generation of companion objects and ensures that the companion object implement the
Expand All @@ -58,48 +50,6 @@ class RealmModelSyntheticCompanionExtension : SyntheticResolveExtension {
}
}

override fun addSyntheticSupertypes(
thisDescriptor: ClassDescriptor,
supertypes: MutableList<KotlinType>
) {
}

override fun generateSyntheticClasses(
thisDescriptor: ClassDescriptor,
name: Name,
ctx: LazyClassContext,
declarationProvider: ClassMemberDeclarationProvider,
result: MutableSet<ClassDescriptor>
) {
}

override fun generateSyntheticClasses(
thisDescriptor: PackageFragmentDescriptor,
name: Name,
ctx: LazyClassContext,
declarationProvider: PackageMemberDeclarationProvider,
result: MutableSet<ClassDescriptor>
) {
}

override fun generateSyntheticProperties(
thisDescriptor: ClassDescriptor,
name: Name,
bindingContext: BindingContext,
fromSupertypes: ArrayList<PropertyDescriptor>,
result: MutableSet<PropertyDescriptor>
) {
}

override fun generateSyntheticSecondaryConstructors(
thisDescriptor: ClassDescriptor,
bindingContext: BindingContext,
result: MutableCollection<ClassConstructorDescriptor>
) {
}

override fun getSyntheticNestedClassNames(thisDescriptor: ClassDescriptor): List<Name> = emptyList()

override fun getSyntheticFunctionNames(thisDescriptor: ClassDescriptor): List<Name> {
return when {
thisDescriptor.isRealmObjectCompanion -> {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
/*
* Copyright 2020 Realm Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.realm.kotlin.compiler

import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.DescriptorVisibilities
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.descriptors.SimpleFunctionDescriptor
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.descriptors.impl.SimpleFunctionDescriptorImpl
import org.jetbrains.kotlin.descriptors.impl.ValueParameterDescriptorImpl
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
import org.jetbrains.kotlin.resolve.descriptorUtil.parents
import org.jetbrains.kotlin.resolve.extensions.SyntheticResolveExtension
import org.jetbrains.kotlin.types.SimpleType

/**
* Triggers generation of synthetic methods on Realm model classes, in particular
* `toString()`, `equals()` and `hashCode()`.
*/
class RealmModelSyntheticMethodsExtension : SyntheticResolveExtension {

override fun generateSyntheticMethods(
thisDescriptor: ClassDescriptor,
name: Name,
bindingContext: BindingContext,
fromSupertypes: List<SimpleFunctionDescriptor>,
result: MutableCollection<SimpleFunctionDescriptor>
) {
if (thisDescriptor.isRealmObject
&& !thisDescriptor.isCompanionObject /* Do not override companion object methods */
&& !thisDescriptor.isInner /* Do not override inner class methods */
&& !isNestedInRealmModelClass(thisDescriptor) /* do not override nested class methods */
&& result.isEmpty() /* = no method has been declared in the current class */
) {
when(name.identifier) {
"toString" -> {
result.add(
createMethod(
classDescriptor = thisDescriptor,
methodName = name,
arguments = emptyList(),
returnType = thisDescriptor.builtIns.stringType
)
)
}
"equals" -> {
result.add(
createMethod(
classDescriptor = thisDescriptor,
methodName = name,
arguments = listOf(Pair("other", thisDescriptor.builtIns.nullableAnyType)),
returnType = thisDescriptor.builtIns.booleanType
)
)
}
"hashCode" -> {
result.add(
createMethod(
classDescriptor = thisDescriptor,
methodName = name,
arguments = emptyList(),
returnType = thisDescriptor.builtIns.intType
)
)
}
}
}
}

private fun createMethod(
classDescriptor: ClassDescriptor,
methodName: Name,
arguments: List<Pair<String, SimpleType>>,
returnType: SimpleType
): SimpleFunctionDescriptor {
return SimpleFunctionDescriptorImpl.create(
classDescriptor,
Annotations.EMPTY,
methodName,
CallableMemberDescriptor.Kind.SYNTHESIZED,
classDescriptor.source
).apply {
initialize(
null,
classDescriptor.thisAsReceiverParameter,
emptyList(),
emptyList(),
arguments.map { (argumentName, argumentType) ->
ValueParameterDescriptorImpl(
containingDeclaration = this,
original = null,
index = 0,
annotations = Annotations.EMPTY,
name = Name.identifier(argumentName),
outType = argumentType,
declaresDefaultValue = false,
isCrossinline = false,
isNoinline = false,
varargElementType = null,
source = this.source
)
},
returnType,
Modality.OPEN,
DescriptorVisibilities.PUBLIC
)
}
}

private fun isNestedInRealmModelClass(classDescriptor: ClassDescriptor): Boolean {
return classDescriptor.parents.firstOrNull {
if (it is ClassDescriptor) {
it.isRealmObject
} else {
false
}
} != null
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,13 @@ class Registrar : ComponentRegistrar {
LoadingOrder.LAST,
project
)
// Trigger generation of Realm specific methods in model classes:
// toString(), equals() and hashCode()
getExtensionPoint(SyntheticResolveExtension.extensionPointName).registerExtension(
RealmModelSyntheticMethodsExtension(),
LoadingOrder.LAST,
project
)
// Adds RealmObjectInternal properties, rewires accessors and adds static companion
// properties and methods
getExtensionPoint(IrGenerationExtension.extensionPointName).registerExtension(
Expand Down
Loading

0 comments on commit f402006

Please sign in to comment.