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

org.jetbrains.kotlin.backend.common.Mappings.kt Maven / Gradle / Ivy

There is a newer version: 2.0.0
Show newest version
/*
 * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
 * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
 */

package org.jetbrains.kotlin.backend.common

import org.jetbrains.kotlin.ir.declarations.*
import kotlin.reflect.KMutableProperty0
import kotlin.reflect.KProperty

interface Mapping {
    val defaultArgumentsDispatchFunction: Delegate
    val defaultArgumentsOriginalFunction: Delegate
    val suspendFunctionToCoroutineConstructor: Delegate
    val lateInitFieldToNullableField: Delegate
    val inlineClassMemberToStatic: Delegate
    val capturedFields: Delegate>
    val capturedConstructors: Delegate
    val reflectedNameAccessor: Delegate

    abstract class Delegate {
        abstract operator fun get(key: K): V?

        abstract operator fun set(key: K, value: V?)

        operator fun getValue(thisRef: K, desc: KProperty<*>): V? = get(thisRef)

        operator fun setValue(thisRef: K, desc: KProperty<*>, value: V?) {
            set(thisRef, value)
        }
    }
}

open class DefaultMapping : Mapping {

    override val defaultArgumentsDispatchFunction: Mapping.Delegate = newMapping()
    override val defaultArgumentsOriginalFunction: Mapping.Delegate = newMapping()
    override val suspendFunctionToCoroutineConstructor: Mapping.Delegate = newMapping()
    override val lateInitFieldToNullableField: Mapping.Delegate = newMapping()
    override val inlineClassMemberToStatic: Mapping.Delegate = newMapping()
    override val capturedFields: Mapping.Delegate> = newMapping()
    override val capturedConstructors: Mapping.Delegate = newMapping()
    override val reflectedNameAccessor: Mapping.Delegate = newMapping()

    protected open fun  newMapping() = object : Mapping.Delegate() {
        private val map: MutableMap = mutableMapOf()

        override operator fun get(key: K): V? {
            return map[key]
        }

        override operator fun set(key: K, value: V?) {
            if (value == null) {
                map.remove(key)
            } else {
                map[key] = value
            }
        }
    }
}

fun  KMutableProperty0.getOrPut(fn: () -> V) = this.get() ?: fn().also {
    this.set(it)
}

fun  Mapping.Delegate.getOrPut(key: K, fn: () -> V) = this[key] ?: fn().also {
    this[key] = it
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy