<commit_before>/*
 * Copyright 2019 the original author or authors.
 *
 * 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 org.gradle.instantexecution.serialization

import org.gradle.instantexecution.extensions.uncheckedCast
import org.gradle.internal.classpath.ClassPath
import org.gradle.internal.classpath.DefaultClassPath
import org.gradle.internal.serialize.BaseSerializerFactory
import org.gradle.internal.serialize.Decoder
import org.gradle.internal.serialize.Encoder
import org.gradle.internal.serialize.Serializer

import java.io.File

import java.util.ArrayDeque

import kotlin.coroutines.Continuation
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.coroutineContext
import kotlin.coroutines.startCoroutine
import kotlin.coroutines.suspendCoroutine


internal
fun <T> singleton(value: T): Codec<T> =
    SingletonCodec(value)


internal
inline fun <reified T> ownerService() =
    codec<T>({ }, { readOwnerService() })


internal
inline fun <reified T : Any> unsupported(): Codec<T> = codec(
    encode = { value ->
        logUnsupported(T::class, value.javaClass)
    },
    decode = {
        logUnsupported(T::class)
        null
    }
)


internal
fun <T> codec(
    encode: suspend WriteContext.(T) -> Unit,
    decode: suspend ReadContext.() -> T?
): Codec<T> = object : Codec<T> {
    override suspend fun WriteContext.encode(value: T) = encode(value)
    override suspend fun ReadContext.decode(): T? = decode()
}


private
inline fun <reified T> ReadContext.readOwnerService() =
    isolate.owner.service<T>()


internal
fun <T : Any> reentrant(codec: Codec<T>): Codec<T> = object : Codec<T> {

    val encodeStack = ArrayDeque<EncodeFrame<T>>()

    val decodeStack = ArrayDeque<DecodeFrame<T?>>()

    override suspend fun WriteContext.encode(value: T) {
        when {
            encodeStack.isEmpty() -> {
                encodeStack.push(EncodeFrame(value, null))
                encodeLoop(coroutineContext)
            }
            else -> suspendCoroutine<Unit> { k ->
                encodeStack.push(EncodeFrame(value, k))
            }
        }
    }

    override suspend fun ReadContext.decode(): T? =
        when {
            decodeStack.isEmpty() -> {
                decodeStack.push(DecodeFrame(null))
                decodeLoop(coroutineContext)
            }
            else -> suspendCoroutine { k ->
                decodeStack.push(DecodeFrame(k))
            }
        }

    private
    fun ReadContext.decodeLoop(coroutineContext: CoroutineContext): T? {
        var result: T? = null
        do {
            suspend {
                codec.run {
                    decode()
                }
            }.startCoroutine(Continuation(coroutineContext) {
                when (val k = decodeStack.pop().k) {
                    null -> result = it.getOrThrow()
                    else -> k.resumeWith(it)
                }
            })
        } while (decodeStack.isNotEmpty())
        return result
    }

    private
    fun WriteContext.encodeLoop(coroutineContext: CoroutineContext) {
        do {
            val frame = encodeStack.peek()
            suspend {
                codec.run {
                    encode(frame.value)
                }
            }.startCoroutine(Continuation(coroutineContext) {
                require(encodeStack.peek() === frame)
                encodeStack.pop()
                frame.k?.resumeWith(it) ?: it.getOrThrow()
            })<commit_msg>Polish the `reentrant` combinator<commit_after>/*
 * Copyright 2019 the original author or authors.
 *
 * 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 org.gradle.instantexecution.serialization

import org.gradle.instantexecution.extensions.uncheckedCast
import org.gradle.internal.classpath.ClassPath
import org.gradle.internal.classpath.DefaultClassPath
import org.gradle.internal.serialize.BaseSerializerFactory
import org.gradle.internal.serialize.Decoder
import org.gradle.internal.serialize.Encoder
import org.gradle.internal.serialize.Serializer

import java.io.File

import java.util.ArrayDeque

import kotlin.coroutines.Continuation
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.coroutineContext
import kotlin.coroutines.startCoroutine
import kotlin.coroutines.suspendCoroutine


internal
fun <T> singleton(value: T): Codec<T> =
    SingletonCodec(value)


internal
inline fun <reified T> ownerService() =
    codec<T>({ }, { readOwnerService() })


internal
inline fun <reified T : Any> unsupported(): Codec<T> = codec(
    encode = { value ->
        logUnsupported(T::class, value.javaClass)
    },
    decode = {
        logUnsupported(T::class)
        null
    }
)


internal
fun <T> codec(
    encode: suspend WriteContext.(T) -> Unit,
    decode: suspend ReadContext.() -> T?
): Codec<T> = object : Codec<T> {
    override suspend fun WriteContext.encode(value: T) = encode(value)
    override suspend fun ReadContext.decode(): T? = decode()
}


private
inline fun <reified T> ReadContext.readOwnerService() =
    isolate.owner.service<T>()


internal
fun <T : Any> reentrant(codec: Codec<T>): Codec<T> = object : Codec<T> {

    val encodeStack = ArrayDeque<EncodeFrame<T>>()

    val decodeStack = ArrayDeque<DecodeFrame<T?>>()

    override suspend fun WriteContext.encode(value: T) {
        when {
            encodeStack.isEmpty() -> {
                encodeStack.push(EncodeFrame(value, null))
                encodeLoop(coroutineContext)
            }
            else -> suspendCoroutine<Unit> { k ->
                encodeStack.push(EncodeFrame(value, k))
            }
        }
    }

    override suspend fun ReadContext.decode(): T? =
        when {
            decodeStack.isEmpty() -> {
                decodeStack.push(DecodeFrame(null))
                decodeLoop(coroutineContext)
            }
            else -> suspendCoroutine { k ->
                decodeStack.push(DecodeFrame(k))
            }
        }

    private
    fun ReadContext.decodeLoop(coroutineContext: CoroutineContext): T? {
        var result: T? = null
        do {
            suspend {
                codec.run {
                    decode()
                }
            }.startCoroutine(Continuation(coroutineContext) {
                when (val k = decodeStack.pop().k) {
                    null -> result = it.getOrThrow()
                    else -> k.resumeWith(it)
                }
            })
        } while (decodeStack.isNotEmpty())
        return result
    }

    private
    fun WriteContext.encodeLoop(coroutineContext: CoroutineContext) {
        do {
            val frame = encodeStack.peek()
            suspend {
                codec.run {
                    encode(frame.value)
                }
            }.startCoroutine(Continuation(coroutineContext) {
                encodeStack.pop().k?.resumeWith(it) ?: it.getOrThrow()
            })
{'fraction_non_alphanumeric': 0.10040465351542742, 'fraction_numerical': 0.0020232675771370764, 'mean_word_length': 2.381359555365541, 'pattern_counts': {'":': 0, '<': 43, '<?xml version=': 0, '>': 65, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '836266', 'n_tokens_mistral': 2239, 'n_tokens_neox': 2163, 'n_words': 536}