Prompt:
@Test
    fun `closureSequence on empty list`() {
        assertSame(
            emptySequence(), listOf<Node>().closureSequence<Node> { it.children },
            "Expected no Set being allocated on empty closure"
        )
    }

    @Test
    fun `closure - on list - no edges`() {
        assertSame(

Response:
emptySet(), listOf(Node("a"), Node("b")).closure<Node> { it.children },
            "Expected no Set being allocated on empty closure"
        )
    }

    @Test
    fun `closureSequence - on list - no edges`() {
        assertEquals(<|endoftext|>


Prompt:
return "kotlin.jvm.internal.markers.KMappedMarker"
            } else if (mapping.kotlinMutable == classId) {
                return "kotlin.jvm.internal.markers.K" + classId.relativeClassName.asString()

Response:
.replace("MutableEntry", "Entry") // kotlin.jvm.internal.markers.KMutableMap.Entry for some reason
                    .replace(".", "$")
            }
        }

        return null
    }
}

private val PsiQualifiedReference.nameFromSource: String?
    get() {
        val name = referenceName ?: return null<|endoftext|>


Prompt:
NATIVE_TARGETS_ALIAS, "Comma-separated list of hardware targets", mandatory = false
) {
    override fun parse(rawValue: String, onError: (reason: String) -> Nothing): Option<List<KonanTarget>> {
        val targetNames = rawValue.split(',')
        if (targetNames.isEmpty()) onError("No hardware targets specified: $rawValue")

Response:
val targets = targetNames.mapTo(HashSet()) { targetName ->
            predefinedTargets[targetName] ?: onError("Unknown hardware target: $targetName")
        }.sortedBy { it.name }

        return Option(this, targets)
    }
}<|endoftext|>


Prompt:
fun <L> flow(block: suspend FlowCollector<L>.() -> Unit): Flow<L> = Flow(block)

class Flow<out R>(private val block: suspend FlowCollector<R>.() -> Unit)

fun <R> select(vararg x: R) = x[0]

fun poll0(): Flow<String> {
    return flow {

Response:
val inv = select(::bar, ::foo)
        inv()
    }
}

fun poll01(): Flow<String> {
    return flow {
        val inv = select(::bar2, ::foo2)
        inv()
    }
}

fun poll02(): Flow<String> {
    return flow {
        val inv = select(::bar3, ::foo3)
        inv()
    }<|endoftext|>


Prompt: // _Arrays.kt:... box: $i$f$foo\1\64:int=0:int, array\1:java.lang.Integer[]=java.lang.Integer[], myClass\1:MyClass=MyClass, $this$map\25:java.lang.Object[]=java.lang.Integer[], $i$f$map\25\459:int=0:int,

Response: $this$mapTo\26:java.lang.Object[]=java.lang.Integer[], destination\26:java.util.Collection=java.util.ArrayList, $i$f$mapTo\26\451:int=0:int, item\26:java.lang.Object=java.lang.Integer<|endoftext|>


Prompt:
private fun Project.registerPackageGeneration(
    taskNamePrefix: String,
    swiftApiModuleName: Provider<String>,
    swiftApiLibraryName: Provider<String>,
    kotlinStaticLibraryName: Provider<String>,
    swiftExportTask: TaskProvider<SwiftExportTask>,
    staticLibrary: StaticLibrary,
    syntheticBuildRoot: Provider<Directory>,

Response:
): TaskProvider<GenerateSPMPackageFromSwiftExport> {
    val spmPackageGenTaskName = taskNamePrefix + "GenerateSPMPackage"
    val packageGenerationTask = locateOrRegisterTask<GenerateSPMPackageFromSwiftExport>(spmPackageGenTaskName) { task ->
        task.group = BasePlugin.BUILD_GROUP<|endoftext|>


Prompt:
val metrics = ArrayList<MetricsContainer>()
        MetricsContainer.readFromFile(statFile) {
            metrics.add(it)
        }

        assertEquals(2, metrics.size, "Invalid number of MerticContainers was read")
        assertEquals(
            "true",
            metrics[0].getMetric(StringMetrics.USE_FIR)?.getValue()

Response:
)

        assertEquals(
            "1.2.3",
            metrics[0].getMetric(StringMetrics.KOTLIN_COMPILER_VERSION)?.getValue()
        )

        assertEquals(
            null,
            metrics[1].getMetric(StringMetrics.KOTLIN_COMPILER_VERSION)?.getValue()
        )
    }<|endoftext|>


Prompt:
// We consider these methods fast enough, so don't switch thread state to Native.
        ret(genSendMessage(returnType, valueParameterTypes, instance, nsNumberInitSelector, value))
    }

    setObjCExportTypeInfo(boxClass, converter.toConstPointer())
}

private fun ObjCExportCodeGenerator.generateContinuationToRetainedCompletionConverter(

Response:
blockGenerator: BlockGenerator
): LlvmCallable = with(blockGenerator) {
    generateWrapKotlinObjectToRetainedBlock(
            BlockType(numberOfParameters = 2, returnsVoid = true),
            convertName = "convertContinuation",
            invokeName = "invokeCompletion"
    ) { continuation, arguments ->
        check(arguments.size == 2)<|endoftext|>


Prompt:
contextReceivers.forEach { it.accept(visitor, data) }
        controlFlowGraphReference?.accept(visitor, data)
        valueParameters.forEach { it.accept(visitor, data) }
        body?.accept(visitor, data)
        contractDescription?.accept(visitor, data)
        annotations.forEach { it.accept(visitor, data) }

Response:
typeParameters.forEach { it.accept(visitor, data) }
    }

    override fun <D> transformChildren(transformer: FirTransformer<D>, data: D): FirSimpleFunctionImpl {
        transformStatus(transformer, data)
        transformReturnTypeRef(transformer, data)
        transformReceiverParameter(transformer, data)<|endoftext|>


Prompt:
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Float & kotlin.Float?")!>b<!>.funNullableAny()
        if (x == null == true || (c != null && !<!DEBUG_INFO_SMARTCAST!>c<!>)) {

        } else {

Response:
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?")!>x<!>
            <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?"), DEBUG_INFO_SMARTCAST!>x<!>.equals(null)<|endoftext|>


Prompt:
val lhs = expression.statements[0] as IrVariable
                val rhsStatement = expression.statements[1]
                val rhs = when (rhsStatement) {
                    is IrBlock -> {
                        if (rhsStatement.statements.size == 2) {
                            val target = rhsStatement.statements[1]
                            when (target) {
                                is IrVariable -> target.initializer

Response:
else -> target
                            }
                        } else rhsStatement
                    }
                    else -> {
                        rhsStatement
                    }
                } as? IrWhen
                val call = rhs?.let { it.branches.last().result as? IrCall }
                if (call == null) {
                    expression.statements.printJoin("\n")
                    return
                }<|endoftext|>


Prompt:
<!INCOMPATIBLE_THROWS_INHERITED!>@Throws(Exception1::class) override fun foo() {}<!>
}

class OverrideIncompatibleThrowsOnFakeOverride2 : IncompatibleThrowsOnFakeOverride {
    <!INCOMPATIBLE_THROWS_INHERITED!>@Throws(Exception2::class) override fun foo() {}<!>
}

Response:
class InheritIncompatibleThrowsOnFakeOverride : IncompatibleThrowsOnFakeOverride {
    <!INCOMPATIBLE_THROWS_INHERITED!>override fun foo() {}<!>
}

<!THROWS_LIST_EMPTY!>@Throws<!>
suspend fun suspendThrowsNothing() {}

interface SuspendFun {
    suspend fun foo()
}<|endoftext|>


Prompt:
dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND.convert(), 0),
                Continuator.wrap({ println("In queue ${dispatch_get_current_queue()}")}) {
            println("After in queue ${dispatch_get_current_queue()}: $index")
        })

        appDelegate.canClick = false

Response:
// Fetch URL in the background on the button click.
        httpDelegate.fetchUrl("https://jsonplaceholder.typicode.com/todos/${index++}")
    }

    @ObjCAction
    fun onQuit() {
        NSApplication.sharedApplication().stop(this)
    }

    @ObjCAction
    fun onRequest() {<|endoftext|>


Prompt:
import org.jetbrains.kotlin.test.KotlinTestUtils
import org.jetbrains.kotlin.test.TestJdkKind
import org.jetbrains.kotlin.test.testFramework.RunAll
import org.jetbrains.kotlin.utils.PathUtil
import org.junit.Assert
import java.io.File

Response:
import java.nio.file.Files
import kotlin.reflect.KClass
import kotlin.script.experimental.annotations.KotlinScript
import kotlin.script.experimental.api.*
import kotlin.script.experimental.host.*
import kotlin.script.experimental.jvm.*<|endoftext|>


Prompt:
assertFailsWith<IndexOutOfBoundsException> {
            arr.getULongAt(-1)
        }
        assertFailsWith<IndexOutOfBoundsException> {
            arr.getULongAt(Int.MAX_VALUE)
        }
        assertFailsWith<IndexOutOfBoundsException> {
            arr.getULongAt(Int.MIN_VALUE)
        }
    }

Response:
@Test fun setULongOutOfBounds() {
        val arr = ByteArray(10) { 0 }
        arr.setULongAt(0, 1U)
        arr.setULongAt(2, 1U)
        assertFailsWith<IndexOutOfBoundsException> {
            arr.setULongAt(3, 1U)
        }<|endoftext|>


Prompt:
public inline fun <C : MutableCollection<in Float>> FloatArray.filterIndexedTo(destination: C, predicate: (index: Int, Float) -> Boolean): C {
    forEachIndexed { index, element ->
        if (predicate(index, element)) destination.add(element)
    }
    return destination
}

/**

Response:
* Appends all elements matching the given [predicate] to the given [destination].
 * @param [predicate] function that takes the index of an element and the element itself
 * and returns the result of predicate evaluation on the element.
 *
 * @sample samples.collections.Collections.Filtering.filterIndexedTo
 */<|endoftext|>


Prompt:
assertEquals(expected, string.replaceFirstChar { it.lowercase() })
        }
        testDecapitalize("a", "A")
        testDecapitalize("a", "a")
        testDecapitalize("abcd", "abcd")
        testDecapitalize("abcd", "Abcd")
        testDecapitalize("uRL", "URL")
    }

Response:
@Test fun slice() {
        val iter = listOf(4, 3, 0, 1)
        // abcde
        // 01234
        assertEquals("bcd", "abcde".substring(1..3))
        assertEquals("dcb", "abcde".slice(3 downTo 1))
        assertEquals("edab", "abcde".slice(iter))
    }<|endoftext|>


Prompt:
typealias Experimental0 = <!OPT_IN_CAN_ONLY_BE_USED_AS_ANNOTATION!>RequiresOptIn<!>
typealias OptIn0 = <!OPT_IN_CAN_ONLY_BE_USED_AS_ANNOTATION!>OptIn<!>
fun f3(e: Experimental0 /* TODO */) {}

Response:
fun f4(u: OptIn0 /* TODO */) {}

// Usages as ::class literals should be errors

annotation class VarargKClasses(vararg val k: KClass<*>)

@VarargKClasses(
    <!OPT_IN_CAN_ONLY_BE_USED_AS_ANNOTATION!>RequiresOptIn<!>::class,<|endoftext|>


Prompt:
return fir.convertWithOffsets { startOffset, endOffset ->
            Fir2IrLazyProperty(
                c, startOffset, endOffset, originForProperty, fir, firContainingClass, symbols, lazyParent, isFakeOverride
            )
        }
    }

    fun createIrLazyConstructor(
        fir: FirConstructor,
        symbol: IrConstructorSymbol,

Response:
declarationOrigin: IrDeclarationOrigin,
        lazyParent: IrDeclarationParent,
    ): Fir2IrLazyConstructor = fir.convertWithOffsets { startOffset, endOffset ->
        Fir2IrLazyConstructor(c, startOffset, endOffset, declarationOrigin, fir, symbol, lazyParent)
    }

    fun createIrLazyClass(
        firClass: FirRegularClass,<|endoftext|>


Prompt:
// SKIP_WHEN_OUT_OF_CONTENT_ROOT
// MODULE: dep
// FILE: issue/pack/RowIcon.kt
package issue.pack;

class RowIcon {
    class RClass
}

// MODULE: main(dep)
// FILE: usage.kt
package usage

fun testJavaNestedClass(alignment: <expr>issue.pack.RowIcon.RClass</expr>) {

Response: }<|endoftext|>


Prompt:
fun t4(<!UNUSED_PARAMETER!>a<!>: A) {
    <!UNUSED_VALUE!><!VAL_REASSIGNMENT!>a<!> =<!> A()
}

// ------------------------------------------------
// reassigned vals

fun t1() {
    val <!UNUSED_VARIABLE!>a<!> : Int = 1

Response:
<!UNUSED_VALUE!><!VAL_REASSIGNMENT!>a<!> =<!> 2

    var <!ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE!>b<!> : Int = 1
    <!UNUSED_VALUE!>b =<!> 3
}

enum class ProtocolState {
  WAITING {<|endoftext|>


Prompt:
fun writeJsCodeIntoModuleCache(outputJsFile: File, outputJsMapFile: File?): CompilationOutputsBuiltForCache {
        sourceMap?.let { outputJsMapFile?.writeText(it) }
        outputJsFile.writeText(rawJsCode)
        return CompilationOutputsBuiltForCache(outputJsFile, outputJsMapFile, this)
    }
}

Response:
class CompilationOutputsCached(
    private val jsCodeFile: File,
    private val sourceMapFile: File?,
    private val tsDefinitionsFile: File?
) : CompilationOutputs() {
    override val tsDefinitions: TypeScriptFragment?
        get() = tsDefinitionsFile?.let { TypeScriptFragment(it.readText()) }

    override val jsProgram: JsProgram?<|endoftext|>


Prompt:
val diff = expectedDeclarations - actualDeclarations
    assert(diff.isEmpty()) {
        val expectedDeclarationsString = expectedDeclarations.joinToString(separator = "\n", prefix = "Expected declarations:\n")
        val actualDeclarationsString = actualDeclarations.joinToString(separator = "\n", prefix = "Actual declarations:\n")

Response:
"$expectedDeclarationsString\n\n$actualDeclarationsString"
    }
}<|endoftext|>


Prompt:
IdSignatureValues._byte, IdSignatureValues._short, IdSignatureValues._int,
                IdSignatureValues.uByte, IdSignatureValues.uShort, IdSignatureValues.uInt, IdSignatureValues.uLong,
                IdSignatureValues._float, IdSignatureValues._double,
                -> false
                else -> true
            }
        }

Response:
private fun IrExpression.explicitlyConvertedToString(): IrExpression {
        assert(type.shouldExplicitlyConvertToString)

        return if (type.isNullable()) {
            JsIrBuilder.buildCall(context.ir.symbols.extensionToString).apply {
                extensionReceiver = this@explicitlyConvertedToString
            }
        } else {<|endoftext|>


Prompt:
assertEquals("NativeFooNWrapper(nativeFooN=null) (object)", describeNativeFooNWrapperN(NativeFooNWrapper(null)))
    assertEquals("null (object)", describeNativeFooNWrapperN(null))
}

external var intWrapper: IntWrapper
external var intWrapperN: IntWrapper?
external var intNWrapper: IntNWrapper

Response:
external var intNWrapperN: /*boxed*/ IntNWrapper?
external var fooWrapper: FooWrapper
external var fooWrapperN: FooWrapper?
external var fooNWrapper: FooNWrapper
external var fooNWrapperN: /*boxed*/ FooNWrapper?
external var nativeFooWrapper: NativeFooWrapper
external var nativeFooWrapperN: NativeFooWrapper?<|endoftext|>


Prompt:
import org.jetbrains.kotlin.ir.builders.*
import org.jetbrains.kotlin.ir.builders.declarations.addValueParameter
import org.jetbrains.kotlin.ir.builders.declarations.buildFun
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.declarations.impl.IrFunctionImpl

Response:
import org.jetbrains.kotlin.ir.expressions.*
import org.jetbrains.kotlin.ir.expressions.impl.IrGetValueImpl
import org.jetbrains.kotlin.ir.expressions.impl.IrTypeOperatorCallImpl
import org.jetbrains.kotlin.ir.symbols.IrFieldSymbol<|endoftext|>


Prompt:
JvmProtoBufUtil.readClassDataFrom(data, strings)
        } ?: return null
        val source = KotlinJvmBinarySourceElement(
            kotlinClass, kotlinClass.incompatibility, kotlinClass.isPreReleaseInvisible, kotlinClass.abiStability
        )

Response:
return ClassData(nameResolver, classProto, kotlinClass.classHeader.metadataVersion, source)
    }

    fun createKotlinPackagePartScope(descriptor: PackageFragmentDescriptor, kotlinClass: KotlinJvmBinaryClass): MemberScope? {<|endoftext|>


Prompt:
}?.let { SMAPAndMethodNode(it, SMAP(listOf())) }

internal fun generateInlineIntrinsic(
    descriptor: FunctionDescriptor,
    asmMethod: Method,
    typeSystem: TypeSystemCommonBackendContext
): SMAPAndMethodNode? {
    return generateInlineIntrinsicForIr(descriptor) ?: when {

Response:
isSpecialEnumMethod(descriptor) ->
            createSpecialEnumMethodBody(descriptor.name.asString(), descriptor.original.typeParameters.single(), typeSystem)
        TypeOfChecker.isTypeOf(descriptor) ->
            typeSystem.createTypeOfMethodBody(descriptor.original.typeParameters.single())
        descriptor.isBuiltinAlwaysEnabledAssert() -><|endoftext|>


Prompt:
) : KtIntegerLiteralType(), KtFirType {
    override val token: KtLifetimeToken get() = builder.token

    override val isUnsigned: Boolean get() = withValidityAssertion { coneType.isUnsigned }

    override val value: Long get() = withValidityAssertion { coneType.value }

Response:
override val possibleTypes: List<KtClassType> by cached {
        coneType.possibleTypes.map { possibleType ->
            builder.typeBuilder.buildKtType(possibleType) as KtClassType
        }
    }

    override val annotationsList: KtAnnotationsList by cached {
        KtFirAnnotationListForType.create(coneType, builder)
    }<|endoftext|>


Prompt:
<!DEBUG_INFO_EXPRESSION_TYPE("tests.case3.B")!>B()<!>
    <!DEBUG_INFO_CALL("fqName: tests.case3.B.B; typeCall: function")!>B()<!>
}

// FILE: Lib3.kt
package lib.case3

//fun A() : String = ""

object A {

Response:
/*operator*/ fun invoke() : Int = 1
}<|endoftext|>


Prompt:
fun <T: String> isNotEqualNullableUnboxedRight(s: A<T>?, t: A<T>) = s != t

fun box(): String {
    if (!isNotNullVacuousLeft(A(""))) return "Fail 1"
    if (!isNotNullVacuousRight(A(""))) return "Fail 2"

Response:
if (!isNotNullLeft(A(""))) return "Fail 3"
    if (!isNotNullRight(A(""))) return "Fail 4"
    if (isNotNullLeft<String>(null)) return "Fail 5"
    if (isNotNullRight<String>(null)) return "Fail 6"
    if (isNotEqualSame(A(""), A(""))) return "Fail 7"<|endoftext|>


Prompt:
override val kFunctionClass = builtIns.getBuiltInClassByFqName(FqName("kotlin.reflect.KFunction")).toIrSymbol()

    override val annotationClass: IrClassSymbol = builtIns.annotation.toIrSymbol()
    override val annotationType: IrType = builtIns.annotationType.toIrType()

Response:
override fun getKPropertyClass(mutable: Boolean, n: Int): IrClassSymbol = when (n) {
        0 -> if (mutable) kMutableProperty0Class else kProperty0Class
        1 -> if (mutable) kMutableProperty1Class else kProperty1Class
        2 -> if (mutable) kMutableProperty2Class else kProperty2Class<|endoftext|>


Prompt:
package org.jetbrains.kotlin.gradle.native

import org.gradle.testkit.runner.BuildResult
import org.gradle.util.GradleVersion
import org.jetbrains.kotlin.gradle.testbase.*
import org.junit.jupiter.api.DisplayName

@DisplayName("Tests for K/N builds with embeddable compiler jar")

Response:
@NativeGradlePluginTests
internal class NativeEmbeddableCompilerJarIT : KGPBaseTest() {

    private fun String.isRegularJar() = this.endsWith("/kotlin-native.jar")
    private fun String.isEmbeddableJar() = this.endsWith("/kotlin-native-compiler-embeddable.jar")<|endoftext|>


Prompt:
class B : A() {
                @Throws(RuntimeException::class)
                override fun foo() = Unit
            }
            class C : B() {
                @Throws(IndexOutOfBoundsException::class)
                override fun foo() = Unit
            }
            """.trimIndent()
        )

        analyze(file) {

Response:
val fooA = file.getClassOrFail("A").getMemberScope().getFunctionOrFail("foo")
            assertEquals(listOf("IllegalStateException"), fooA.effectiveThrows.mapName())
            assertEquals(listOf("IllegalStateException"), fooA.definedThrows.mapName())<|endoftext|>


Prompt:
existingContext.dropElement()
            context = existingContext
        }
    }

    @OptIn(PrivateForInline::class)
    inline fun <R> withLabelAndReceiverType(
        labelName: Name?,
        owner: FirDeclaration,
        type: ConeKotlinType?,
        block: () -> R
    ): R {

Response:
val (implicitReceiverValue, implicitCompanionValues) = context.sessionHolder.collectImplicitReceivers(type, owner)
        val existingContext = context
        implicitCompanionValues.forEach { value ->
            context = context.addImplicitReceiver(null, value)
        }
        implicitReceiverValue?.let {
            context = context.addImplicitReceiver(labelName, it)<|endoftext|>


Prompt: // library.kt:57 box: $i$f$foo\1\64:int=0:int, array\1:java.lang.Integer[]=java.lang.Integer[], myClass\1:MyClass=MyClass, this_\12:MyClass=MyClass, $i$f$f1\12\436:int=0:int,

Response: $i$a$-f1-LibraryKt$foo$3\14\439\1:int=0:int, $i$f$test\15\436:int=0:int<|endoftext|>


Prompt:
* @throws NoSuchElementException if the char sequence is empty.
 */
@SinceKotlin("1.4")
@OptIn(kotlin.experimental.ExperimentalTypeInference::class)
@OverloadResolutionByLambdaReturnType
@kotlin.internal.InlineOnly

Response:
public inline fun <R> CharSequence.minOfWith(comparator: Comparator<in R>, selector: (Char) -> R): R {
    if (isEmpty()) throw NoSuchElementException()
    var minValue = selector(this[0])
    for (i in 1..lastIndex) {
        val v = selector(this[i])<|endoftext|>


Prompt:
// test.kt:11 box: map:java.util.Map=java.util.Collections$SingletonMap
// test.kt:9 box: map:java.util.Map=java.util.Collections$SingletonMap

Response:
// test.kt:14 box: map:java.util.Map=java.util.Collections$SingletonMap, e:java.util.Map$Entry=java.util.AbstractMap$SimpleImmutableEntry
// test.kt:11 box: map:java.util.Map=java.util.Collections$SingletonMap<|endoftext|>


Prompt:
return js("jsInInlineFunctionInnerBox()") as String
}

fun testCaptureVariables(param1: String = "parameter"): String {
    val STR1 = "local variable"

    js("""
        function testCaptureVariablesInnerBox() {
            if (param$LIB_INT != 'parameter') { return "Not OK parameter"; }

Response:
if ($STR$LIB_INT != 'local variable') { return "Not OK local variable"; }

            return "OK";
        }
    """)
    return js("testCaptureVariablesInnerBox()") as String
}

inline fun jsInInlineFunctionCaptureVariables(param1: String = "parameter") {
    val STR1 = "local variable"

    js("""<|endoftext|>


Prompt:
classOrObject.body?.declarations?.forEach { declaration ->
            when (declaration) {
                is KtConstructor<*> -> addDeclaration(memberDeserializer.loadConstructor(declaration, classOrObject, this))
                is KtNamedFunction -> addDeclaration(memberDeserializer.loadFunction(declaration, symbol, session))

Response:
is KtProperty -> addDeclaration(memberDeserializer.loadProperty(declaration, symbol))
                is KtEnumEntry -> addDeclaration(memberDeserializer.loadEnumEntry(declaration, symbol, classId))
                is KtClassOrObject -> {
                    val name = declaration.name ?: errorWithAttachment("Class doesn't have name $declaration") {<|endoftext|>


Prompt:
import org.jetbrains.kotlin.asJava.elements.KtLightField
import org.jetbrains.kotlin.asJava.elements.KtLightMethod
import org.jetbrains.kotlin.asJava.elements.KtUltraLightModifierList
import org.jetbrains.kotlin.asJava.toLightClass

Response:
import org.jetbrains.kotlin.backend.common.CodegenUtil
import org.jetbrains.kotlin.backend.common.DataClassMethodGenerator
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.builtins.StandardNames<|endoftext|>


Prompt:
fun <K> foo(x: K) {}
val x1 = foo<(<!UNRESOLVED_REFERENCE!>unresolved<!>) -> Float> { <!DEBUG_INFO_ELEMENT_WITH_ERROR_TYPE!>it<!>.<!DEBUG_INFO_MISSING_UNRESOLVED!>toFloat<!>() }

Response: val x2 = foo<(<!UNRESOLVED_REFERENCE!>unresolved<!>) -> Float> { <!CANNOT_INFER_PARAMETER_TYPE!>it<!> -> <!DEBUG_INFO_ELEMENT_WITH_ERROR_TYPE!>it<!>.<!DEBUG_INFO_MISSING_UNRESOLVED!>toFloat<!>() }<|endoftext|>


Prompt:
expectedReturnType: ConeKotlinType?,
    isPassedAsFunctionArgument: Boolean,
    returnExpressions: Collection<FirAnonymousFunctionReturnExpressionInfo>,
): ConeKotlinType {
    val expandedExpectedReturnType = expectedReturnType?.fullyExpandedType(session)
    val unitType = session.builtinTypes.unitType.type
    if (isLambda) {

Response:
if (expandedExpectedReturnType?.isUnitOrFlexibleUnit == true) {
            // If the expected type is Unit or flexible Unit, always infer the lambda's type to Unit.
            // If a return statement in a lambda has a different type, RETURN_TYPE_MISMATCH will be reported for that return statement
            // by FirFunctionReturnTypeMismatchChecker.
            //
            // For example:<|endoftext|>


Prompt:
assertEquals(listOf(0..2, 4..3, 5..7), "abc--def".rangesDelimitedBy('-').toList())
        assertEquals(listOf(0..2, 5..7, 9..10), "abc--def-xy".rangesDelimitedBy("--", "-").toList())

Response:
assertEquals(listOf(0..2, 7..9, 14..16), "123
456
789".rangesDelimitedBy("
", ignoreCase = true).toList())
        assertEquals(listOf(2..2, 4..6), "a=b=c=d".rangesDelimitedBy("=", startIndex = 2, limit = 2).toList())<|endoftext|>


Prompt:
fun testRelocatablePluginClasspath() {
        initProject(LibraryDependency.JVM_FULL_RUNTIME)

        //create lib
        val libraryName = "module1-1.0-SNAPSHOT"
        val libraryJar = MockLibraryUtilExt.compileJvmLibraryToJar(workDir.resolve("non-existent-folder").absolutePath, libraryName)

Response:
val module1Lib = this.workDir.resolve("lib").resolve("$libraryName.jar")
        Files.createDirectories(module1Lib.parentFile.toPath())
        Files.copy(libraryJar.toPath(), module1Lib.toPath(), StandardCopyOption.REPLACE_EXISTING)
        assert(module1Lib.exists())

        // Add facet<|endoftext|>


Prompt:
with(analysisSession) { unsubstitutedKtSignature.substitute(substitutor) },
                fir.dispatchReceiver?.toKtReceiverValue(),
                fir.extensionReceiver?.toKtReceiverValue()
            )
        } else {

Response:
KtPartiallyAppliedSymbol(unsubstitutedKtSignature, _dispatchReceiver = null, _extensionReceiver = null)
        }

        return when (fir) {
            is FirAnnotationCall -> {
                if (unsubstitutedKtSignature.symbol !is KtConstructorSymbol) return null<|endoftext|>


Prompt:
): FirSimpleFunctionBuilder {
        return FirSimpleFunctionBuilder().apply {
            moduleData = session.moduleData
            origin = FirDeclarationOrigin.Synthetic.FakeFunction
            this.symbol = symbol
            this.name = name
            status = FirDeclarationStatusImpl(Visibilities.Public, Modality.FINAL)
            returnTypeRef = returnType

Response:
resolvePhase = FirResolvePhase.BODY_RESOLVE
        }
    }

    private fun FirResolvedTypeRef.toValueParameter(
        nameAsString: String, functionSymbol: FirFunctionSymbol<*>, isVararg: Boolean = false
    ): FirValueParameter {
        val name = Name.identifier(nameAsString)
        return buildValueParameter {<|endoftext|>


Prompt:
val result = resolveUserTypeToSymbol(typeRef, scopeClassDeclaration, useSiteFile, supertypeSupplier, resolveDeprecations)
                val resolvedType = resolveUserType(
                    typeRef,
                    result,
                    areBareTypesAllowed,
                    scopeClassDeclaration.topContainer ?: scopeClassDeclaration.containingDeclarations.lastOrNull(),
                    isOperandOfIsOperator,
                )

Response:
FirTypeResolutionResult(resolvedType, (result as? TypeResolutionResult.Resolved)?.typeCandidate?.diagnostic)
            }
            is FirFunctionTypeRef -> createFunctionType(typeRef)
            is FirDynamicTypeRef -> {
                val attributes = typeRef.annotations.computeTypeAttributes(
                    session,
                    shouldExpandTypeAliases = true
                )<|endoftext|>


Prompt:
@file:Suppress("UNRESOLVED_REFERENCE", "ANNOTATION_ARGUMENT_MUST_BE_CONST", "NON_CONST_VAL_USED_IN_CONSTANT_EXPRESSION", "UNSUPPORTED_FEATURE")
import java.util.Calendar
import kotlin.reflect.KClass

typealias Coocoo = ABC

Response:
typealias Coocoo2<T> = ABC<T>
typealias Coocoo3<X> = ABC<String, X>

typealias Nested1 = ABC
typealias Nested2 = Nested1

@Anno(Blah::class, arrayOf(NoFoo1::class, NoBar1::class), [NoFoo2::class, String::class], Boolean::class, NoBar3::class)<|endoftext|>


Prompt:
toolRunner.run(buildFirstStageArgs(intermediateKlib))
            logger.info("Start second stage")
            toolRunner.run(buildSecondStageArgs(intermediateKlib))
        } else {
            toolRunner.run(buildSingleStageArgs())
        }
    }
}

Response:
abstract class KonanCompileNativeBinary @Inject constructor(layout: ProjectLayout) : KonanCompileTask(layout) {
    @Input
    override var enableTwoStageCompilation: Boolean = false
}

abstract class KonanCompileProgramTask @Inject constructor(layout: ProjectLayout): KonanCompileNativeBinary(layout) {<|endoftext|>


Prompt:
// MODULE: lib
// FILE: A.kt
// VERSION: 1

open class X {
    fun foo(): String = "final method"
    val bar: String = "final property"
}

class Y: X()

// FILE: B.kt
// VERSION: 2

open class X {
    open fun foo(): String = "open method"
    open val bar: String = "open property"
}

Response:
class Y: X() {
    override fun foo(): String = "derived method"
    override val bar: String = "derived property"
}

// MODULE: mainLib(lib)
// FILE: mainLib.kt

class Z: X()

fun lib(): String = when {
    X().foo() != "open method" -> "fail 1"<|endoftext|>


Prompt:
// As far as protected members can't be accessed outside of the class hierarchy, we need special accessors.
    fun protectedToPublicOverriddenFunctionAccess() = protectedToPublicOverriddenFunction()
    fun protectedToInternalOverriddenFunctionAccess() = protectedToInternalOverriddenFunction()
    fun protectedToInternalPAOverriddenFunctionAccess() = protectedToInternalPAOverriddenFunction()

Response:
fun protectedToPrivateOverriddenFunctionAccess() = protectedToPrivateOverriddenFunction()

    // Functions that accedentally start to override/conflict with functions added to Container since version v2:
    public fun newPublicFunction() = "ContainerImpl.newPublicFunction"
    public fun newOpenPublicFunction() = "ContainerImpl.newOpenPublicFunction"
    protected fun newProtectedFunction() = "ContainerImpl.newProtectedFunction"<|endoftext|>


Prompt:
@Test fun maxValueToMinValue() {
        doTest(MaxI..MinI, MaxI, MinI, 1, listOf())
        doTest(MaxB..MinB, MaxB.toInt(), MinB.toInt(), 1, listOf())
        doTest(MaxS..MinS, MaxS.toInt(), MinS.toInt(), 1, listOf())

Response:
doTest(MaxL..MinL, MaxL, MinL, 1L, listOf())

        doTest(MaxC..MinC, MaxC, MinC, 1, listOf())

        doTest(MaxUI..MinUI, MaxUI, MinUI, 1, listOf())
        doTest(MaxUL..MinUL, MaxUL, MinUL, 1L, listOf())
    }<|endoftext|>


Prompt:
// and not enter it later even though we explicitly depend on it in D's module-info
        val a = module("moduleA")
        val b = module("moduleB", listOf(a))
        val c = module("moduleC", listOf(a, b))
        module("moduleD", listOf(c, b, a))
    }

Response:
fun testInheritedDeclarationFromTwiceTransitiveDependency() {
        // module A <-t- module B <-t- module C <--- module D

        // Java: class A { String ok() { /* ... */ } }
        val a = module("moduleA")

        // Java: class B extends A
        val b = module("moduleB", listOf(a))<|endoftext|>


Prompt:
<!INCOMPATIBLE_MODIFIERS!>private<!> <!INCOMPATIBLE_MODIFIERS!>open<!> fun self() : D = this
}

class E : D() {
    internal <!NOTHING_TO_OVERRIDE!>override<!> fun self() = this

    fun test() {
        val s : E = self()
    }

Response:
}

//------------
open class F {
    protected open fun protected_fun() {}
}

class G : F() {
    override fun protected_fun() {}
}

fun test_fun_stays_protected(g: G) {
    g.<!INVISIBLE_REFERENCE!>protected_fun<!>()
}

//------------
open class H {<|endoftext|>


Prompt:
fun testVarArgs() {
        doTest("annotationArguments/varargs.kt")
    }

    fun testSourceRetainedAnnotation() {
        doTest("sourceRetainedAnnotation.kt")
    }

    fun testBinaryRetainedAnnotation() {
        doTest("binaryRetainedAnnotation.kt")
    }

    fun testPropertyAccessorAnnotations() {

Response:
doTest("propertyAccessorAnnotations.kt")
    }
}<|endoftext|>


Prompt:
package org.jetbrains.kotlin.commonizer.mergedtree

import org.jetbrains.kotlin.commonizer.TargetDependent
import org.jetbrains.kotlin.commonizer.cir.CirEntityId
import org.jetbrains.kotlin.commonizer.utils.CommonizerMap

class CirKnownClassifiers(

Response:
val classifierIndices: TargetDependent<CirClassifierIndex>,
    val targetDependencies: TargetDependent<CirProvidedClassifiers>,
    val commonizedNodes: CirCommonizedClassifierNodes,
    val commonDependencies: CirProvidedClassifiers,
    val associatedIdsResolver: AssociatedClassifierIdsResolver =<|endoftext|>


Prompt:
// FIR_IDENTICAL
//KT-580 Type inference failed

package whats.the.difference

import java.util.*

fun iarray(vararg a : String) = a // BUG

fun main() {
    val vals = iarray("789", "678", "567")
    val diffs = ArrayList<Int>()
    for (i in vals.indices) {

Response:
for (j in i..vals.lastIndex())  // Type inference failed
             diffs.add(vals[i].length - vals[j].length)
        for (j in i..vals.lastIndex)  // Type inference failed
             diffs.add(vals[i].length - vals[j].length)
    }
}

fun <T> Array<T>.lastIndex() = size - 1<|endoftext|>


Prompt:
public fun <@OnlyInputTypes T> assertContentEquals(expected: Set<T>?, actual: Set<T>?, message: String? = null): Unit =
    assertContentEquals(expected, actual?.asIterable(), message)

/**
 * Asserts that the [expected] sequence is *structurally* equal to the [actual] sequence, with an optional [message].
 *

Response:
* Two sequences are considered structurally equal if they have the same size,
 * and elements at corresponding positions, following the iteration order, are equal.
 * Elements are compared for equality using the [equals][Any.equals] function.
 * For floating point numbers, this means `NaN` is equal to itself and `-0.0` is not equal to `0.0`.
 *<|endoftext|>


Prompt: // library.kt:21 box: m:int=1:int, $i$f$foo\8\45:int=0:int, fooVar\8:int=100:int, x1Var\9:int=1:int, $i$f$x1\9\127:int=0:int, y1\9:int=1:int, x3Var\11:int=3:int,

Response: $i$f$x3\11\134:int=0:int<|endoftext|>


Prompt:
existingAnnotation.annotationTypeRef.coneType,
                        classSymbol.defaultType(),
                        this
                    )
                }
            }
        }
    }

    private fun FirAnnotation.hasSameArguments(other: FirAnnotation, session: FirSession): Boolean {
        val m1 = argumentMapping.mapping
        val m2 = other.argumentMapping.mapping

Response:
if (m1.keys != m2.keys) return false
        for ((key, v1) in m1) {
            val v2 = m2.getValue(key)
            if (!v1.isEqualTo(v2, session)) return false
        }
        return true
    }

    private fun FirExpression.isEqualTo(other: FirExpression, session: FirSession): Boolean {<|endoftext|>


Prompt:
setObjCExportTypeInfo(irClass, typeAdapter = typeAdapter)
                } else {
                    // Optimization: avoid generating huge initializers;
                    // handled with "Kotlin_ObjCExport_initTypeAdapters" below.
                }
            }
        }

        fun emitSortedAdapters(nameToAdapter: Map<String, ConstPointer>, prefix: String) {

Response:
val sortedAdapters = nameToAdapter.toList().sortedBy { it.first }.map {
                it.second
            }

            if (sortedAdapters.isNotEmpty()) {
                val type = sortedAdapters.first().llvmType
                val sortedAdaptersPointer = staticData.placeGlobalConstArray("", type, sortedAdapters)<|endoftext|>


Prompt:
return path.hashCode() xor id
    }

    override fun equals(other: Any?): Boolean {
        return other is KotlinSourceFile && other.path == path && other.id == id
    }

    // for debugging purposes only
    override fun toString(): String = "${File(path).name}${if (id != 0) ".$id" else ""}"

    companion object {

Response:
fun fromProtoStream(input: CodedInputStream): KotlinSourceFile {
            val path = input.readString()
            val fileIndex = input.readInt32()
            return KotlinSourceFile(path, fileIndex)
        }

        /**
         * Source file paths in one module may clash;
         * for example, common and platform parts of the module could have files with the same root paths.<|endoftext|>


Prompt: at DefaultJsAsserter.failWithMessage_0 (/Users/user/repos/check-kotlin-js-test/build/js/packages_imported/kotlin-test/1.3.0-SNAPSHOT/src/main/kotlin/kotlin/test/DefaultJsAsserter.kt:80:18 <-

Response: /Users/user/repos/check-kotlin-js-test/build/js/packages/check-kotlin-js-test-test/adapter.js:1569:13)<|endoftext|>


Prompt:
}
    }
    for (child in stub.childrenStubs) {
        builder.append("\n").append("  ".repeat(level))
        extractAdditionInfo(child, builder, level + 1)
    }
}

private fun appendFlexibleTypeInfo(builder: StringBuilder, typeBean: KotlinTypeBean) {
    when (typeBean) {

Response:
is KotlinClassTypeBean -> {
            builder.append(typeBean.classId.asFqNameString())
            val arguments = typeBean.arguments
            if (arguments.isNotEmpty()) {
                builder.append("<")
                arguments.forEachIndexed { index, arg ->
                    if (index > 0) builder.append(", ")<|endoftext|>


Prompt:
JvmKt.foo(-1);
        JvmKt.foo(5, 5);
        return "OK";
    }
}

// FILE: jvm.kt

import kotlin.test.assertEquals

@JvmOverloads
actual fun foo(j: Int, i: Int) {
    assertEquals(j, i)
}

fun box(): String {

Response:
foo(-1)
    foo(5, 5)
    return J.test();
}<|endoftext|>


Prompt:
if (name == INVOKE_SUSPEND_METHOD_NAME && desc == "(Ljava/lang/Object;)Ljava/lang/Object;") {
                        return null
                    }

                    return object : MethodNode(Opcodes.API_VERSION, access, name, desc, signature, exceptions) {

Response:
override fun visitMethodInsn(opcode: Int, owner: String, name: String, desc: String, itf: Boolean) {
                            val methodCall = MethodInfo(owner, name, desc)
                            if (inlinedMethods.contains(methodCall)) {
                                val fromCall = MethodInfo(className, this.name, this.desc)

                                //skip delegation to interface DefaultImpls from child class<|endoftext|>


Prompt:
}

    @OptIn(SymbolInternals::class)
    private fun createJsPlainObjectsFunction(
        callableId: CallableId,
        parent: FirClassSymbol<*>,
        jsPlainObjectInterface: FirRegularClassSymbol,
        getParameterDefaultValueFromProperty: FirPropertySymbol.() -> FirExpression?
    ): FirSimpleFunction {

Response:
val jsPlainObjectProperties = session.jsPlainObjectPropertiesProvider.getJsPlainObjectsPropertiesForClass(jsPlainObjectInterface)

        val functionTarget = FirFunctionTarget(null, isLambda = false)
        val jsPlainObjectInterfaceDefaultType = jsPlainObjectInterface.defaultType()

        return buildSimpleFunction {
            moduleData = jsPlainObjectInterface.moduleData<|endoftext|>


Prompt:
selectorCall = receiverInfo.selectorCall
        )

        addResolvedKtPrimitive(resolvedAtom)
    } else {
        var convertedTypeAfterSubtyping: UnwrappedType? = null
        csBuilder.runTransaction {
            val resolvedAtom = resolveKtPrimitive(
                csBuilder,
                argument,
                expectedType,
                this@resolveKotlinArgument,

Response:
receiverInfo,
                convertedArgument?.unknownIntegerType?.unwrap(),
                inferenceSession
            )

            if (!hasContradiction) {
                addResolvedKtPrimitive(resolvedAtom)
                return@runTransaction true
            }

            convertedTypeAfterSubtyping =
                TypeConversions.performCompositeConversionAfterSubtyping(<|endoftext|>


Prompt:
fun <T : Float> concatNFloat(x: T?) = "[[$x]]"
fun <T : Double> concatNDouble(x: T?) = "[[$x]]"

fun box(): String {
    assertEquals("[[true]]", concatNBoolean(true))
    assertEquals("[[0]]", concatNByte(0.toByte()))

Response:
assertEquals("[[1]]", concatNShort(1.toShort()))
    assertEquals("[[2]]", concatNInt(2))
    assertEquals("[[3]]", concatNLong(3L))
    assertEquals("[[4.4]]", concatNFloat(4.4f))<|endoftext|>


Prompt:
val javaLangReflectFieldSetAccessible: IrSimpleFunctionSymbol =
        javaLangReflectField.functionByName("setAccessible")

    val javaLangReflectMethodSetAccessible: IrSimpleFunctionSymbol =
        javaLangReflectMethod.functionByName("setAccessible")

    val javaLangReflectConstructorSetAccessible: IrSimpleFunctionSymbol =

Response:
javaLangReflectConstructor.functionByName("setAccessible")

    val getDeclaredField: IrSimpleFunctionSymbol =
        context.ir.symbols.javaLangClass.functionByName("getDeclaredField")

    val getDeclaredMethod: IrSimpleFunctionSymbol =
        context.ir.symbols.javaLangClass.functionByName("getDeclaredMethod")<|endoftext|>


Prompt:
}

    class B {
        val a = 1

        companion object CO {
            fun bar(a: /*p:foo p:foo.A p:foo.A.B p:foo.A.B.CO p:foo.A.Companion*/Int) {}
        }
    }

    inner class C

    companion object {
        val a = 1
        fun baz() {}

Response:
}

    object O {
        var v = "vvv"
    }
}

/*p:foo*/interface I {
    var a: /*p:foo p:foo.I*/Int
    fun foo()

    class NI
}

/*p:foo*/object Obj : /*p:foo*/I {
    override var a = 1
    override fun foo() {}
    val b = 1<|endoftext|>


Prompt:
fun getInternalPackageFqn(classSimpleName: String): FqName =
    SerializationPackages.internalPackageFqName.child(Name.identifier(classSimpleName))

fun ModuleDescriptor.getClassFromInternalSerializationPackage(classSimpleName: String) =
    requireNotNull(
        findClassAcrossModuleDependencies(
            ClassId(
                SerializationPackages.internalPackageFqName,

Response:
Name.identifier(classSimpleName)
            )
        )
    ) { "Can't locate class $classSimpleName from package ${SerializationPackages.internalPackageFqName}" }

fun ModuleDescriptor.getClassFromSerializationDescriptorsPackage(classSimpleName: String) =
    requireNotNull(
        findClassAcrossModuleDependencies(
            ClassId(<|endoftext|>


Prompt:
generateSequence(this) { it.outerClassId }.drop(classesToDrop).firstOrNull()

    /**
     * @return How many qualifiers needs to be dropped from [wholeType] to get [nestedType].
     *
     * Example: to get `foo.bar` from `foo.bar.Baz.Inner`, you need to drop 2 qualifiers (`Inner` and `Baz`).

Response:
*/
    private fun countQualifiersToDrop(wholeType: KtUserType, nestedType: KtUserType): Int {
        val qualifierIndex = generateSequence(wholeType) { it.qualifier }.indexOf(nestedType)
        require(qualifierIndex != -1) { "Whole type $wholeType should contain $nestedType, but it didn't" }
        return qualifierIndex<|endoftext|>


Prompt:
abstract override val annotations: List<FirAnnotation>
    abstract val classTypeRef: FirTypeRef

    override fun <R, D> accept(visitor: FirVisitor<R, D>, data: D): R =
        visitor.visitClassReferenceExpression(this, data)

    @Suppress("UNCHECKED_CAST")

Response:
override fun <E : FirElement, D> transform(transformer: FirTransformer<D>, data: D): E =
        transformer.transformClassReferenceExpression(this, data) as E

    abstract override fun replaceConeTypeOrNull(newConeTypeOrNull: ConeKotlinType?)

    abstract override fun replaceAnnotations(newAnnotations: List<FirAnnotation>)<|endoftext|>


Prompt:
// MODULE: context

// FILE: lib.kt
package lib

@Target(AnnotationTarget.FUNCTION)
annotation class Anno(val x: String = "foo")

// FILE: context.kt
import lib.Anno

@Anno
fun foo(): Int = 5

@Anno(x = "bar")
fun bar(): Int = 10

fun test() {

Response:
<caret_context>val x = 0
}

// MODULE: main
// MODULE_KIND: CodeFragment
// CONTEXT_MODULE: context

// FILE: fragment.kt
// CODE_FRAGMENT_KIND: EXPRESSION
foo() + bar()<|endoftext|>


Prompt:
transformResult(transformer, data)
        transformOtherChildren(transformer, data)
        return this
    }

    override fun <D> transformCondition(transformer: FirTransformer<D>, data: D): FirWhenBranchImpl {
        condition = condition.transform(transformer, data)
        return this
    }

Response:
override fun <D> transformResult(transformer: FirTransformer<D>, data: D): FirWhenBranchImpl {
        result = result.transform(transformer, data)
        return this
    }

    override fun <D> transformOtherChildren(transformer: FirTransformer<D>, data: D): FirWhenBranchImpl {
        return this
    }
}<|endoftext|>


Prompt: fun <K : Foo<Foo<<!UNDERSCORE_USAGE_WITHOUT_BACKTICKS!>_<!>>>, <!UNDERSCORE_IS_RESERVED!>_<!>> foo9(): Foo<Foo<<!UNDERSCORE_USAGE_WITHOUT_BACKTICKS!>_<!>>>

Response: {<!NO_RETURN_IN_FUNCTION_WITH_BLOCK_BODY!><|endoftext|>


Prompt:
override val isContextReceiver: Boolean
        get() = true
}

class ContextReceiverValueForCallable(
    boundSymbol: FirCallableSymbol<*>,
    type: ConeKotlinType,
    labelName: Name?,
    useSiteSession: FirSession,
    scopeSession: ScopeSession,
    mutable: Boolean = true,
    contextReceiverNumber: Int,

Response:
) : ContextReceiverValue<FirCallableSymbol<*>>(
    boundSymbol, type, labelName, useSiteSession, scopeSession, mutable, contextReceiverNumber
) {
    override fun createSnapshot(keepMutable: Boolean): ContextReceiverValue<FirCallableSymbol<*>> =<|endoftext|>


Prompt:
if (expr is JsNameRef && (expr.name?.let { tracker.isReferenceToRemovableCandidate(it) } ?: false)) return true

        val staticRef = name?.staticRef
        return staticRef != null && staticRef == expr && isFunctionReference(expr)
    }
}

Response:
// For RHS of `var a = b;` checks whether *b* is a reference to a function or a closure instantiation, direct or indirect.
private fun isFunctionReference(expr: JsExpression): Boolean {
    val qualifier = when (expr) {
        // `var tmp = foo(closure)`, where `foo` is a closure constructor.
        is JsInvocation -> expr.qualifier<|endoftext|>


Prompt:
publishingConfiguration.code()

    val components = publishingConfiguration
        .modules
        .mapValues { (_, module) -> project.createModulePublication(module) }

    val componentsWithExternals = publishingConfiguration
        .modules
        .filter { (_, module) -> module.includes.isNotEmpty() }
        .mapValues { (moduleName, module) ->

Response:
val mainComponent = components[moduleName] ?: error("Component with name $moduleName wasn't created")
            val externalComponents = module.includes
                .map { components[it.name] ?: error("Component with name ${it.name} wasn't created") }
                .toSet()
            ComponentWithExternalVariants(mainComponent, externalComponents)
        }<|endoftext|>


Prompt:
listOf(), listOf(File("compiler/testData/kotlinClassFinder/nestedClass.kt")), tmpdir, testRootDisposable, null
        )

        val environment = createEnvironment(tmpdir)
        val project = environment.project

        val classFinder = createClassFinder(project)

        val className = "test.A.B.C"

Response:
val classId = ClassId(FqName("test"), FqName("A.B.C"), isLocal = false)
        val found = classFinder.findClass(classId)
        assertNotNull(found, "Class not found for $className")

        val binaryClass = VirtualFileFinder.SERVICE.getInstance(project).findKotlinClass(found, JvmMetadataVersion.INSTANCE)<|endoftext|>


Prompt:
fun createErrorScope(kind: ErrorScopeKind, throwExceptions: Boolean, vararg formatParams: String): ErrorScope =
        if (throwExceptions) ThrowingScope(kind, *formatParams) else ErrorScope(kind, *formatParams)

    @JvmStatic
    fun createErrorType(kind: ErrorTypeKind, vararg formatParams: String): ErrorType =

Response:
createErrorTypeWithArguments(kind, emptyList(), *formatParams)

    fun createErrorType(kind: ErrorTypeKind, typeConstructor: TypeConstructor, vararg formatParams: String): ErrorType =
        createErrorTypeWithArguments(kind, emptyList(), typeConstructor, *formatParams)<|endoftext|>


Prompt:
.replaceText("XCFramework(\"other\")", "XCFramework()")

            buildAndFail("tasks") {
                assertOutputContains("Cannot add task 'assembleSharedReleaseXCFramework' as a task with that name already exists.")
            }
        }
    }

    @DisplayName("K/N project with XCFramework, that contains frameworks with different names")

Response:
@GradleTest
    fun shouldCheckConfigurationErrorForXCFrameworkWithDifferentFrameworksNames(gradleVersion: GradleVersion) {
        project("appleXCFramework", gradleVersion) {
            subProject("shared")
                .buildGradleKts
                .replaceFirst("baseName = \"shared\"", "baseName = \"awesome\"")

            buildAndFail("tasks") {<|endoftext|>


Prompt:
import org.jetbrains.kotlin.ir.util.DumpIrTreeOptions
import org.jetbrains.kotlin.ir.util.allOverridden
import org.jetbrains.kotlin.ir.util.dump
import org.jetbrains.kotlin.ir.util.dumpTreesFromLineNumber
import org.jetbrains.kotlin.name.ClassId

Response:
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.test.Constructor
import org.jetbrains.kotlin.test.backend.ir.IrBackendInput
import org.jetbrains.kotlin.test.directives.CodegenTestDirectives<|endoftext|>


Prompt:
import org.jetbrains.kotlin.psi.KtSimpleNameExpression
import org.jetbrains.org.objectweb.asm.Label
import org.jetbrains.org.objectweb.asm.Opcodes
import org.jetbrains.org.objectweb.asm.Type
import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter

Response:
class InFloatingPointRangeLiteralExpressionGenerator(
    operatorReference: KtSimpleNameExpression,
    private val rangeLiteral: BoundedValue,
    private val comparisonGenerator: ComparisonGenerator,
    private val frameMap: FrameMap
) : InExpressionGenerator {
    init {<|endoftext|>


Prompt:
// This file was generated automatically. See compiler/fir/tree/tree-generator/Readme.md.
// DO NOT MODIFY IT MANUALLY.

package org.jetbrains.kotlin.fir.types

import org.jetbrains.kotlin.KtSourceElement
import org.jetbrains.kotlin.fir.FirElement

Response:
import org.jetbrains.kotlin.fir.expressions.FirAnnotation
import org.jetbrains.kotlin.fir.visitors.FirTransformer
import org.jetbrains.kotlin.fir.visitors.FirVisitor

/**<|endoftext|>


Prompt:
class EnumEntriesListTest {

    enum class EmptyEnum

    enum class NonEmptyEnum {
        A, B, C
    }

    @Test
    fun testCannotBeCasted() {
        val list = enumEntries(EmptyEnum::values)
        assertTrue { list !is MutableList<*> }
    }

    @Test

Response:
fun testForEmptyEnum() {
        val list = enumEntries(EmptyEnum::values)
        assertTrue(list.isEmpty())
        assertEquals(0, list.size)
        assertFalse { list is MutableList<*> }
        assertFailsWith<IndexOutOfBoundsException> { list[0] }<|endoftext|>


Prompt:
return maxWithOrNull(comparator)
}

@Deprecated("Use maxWithOrNull instead.", ReplaceWith("this.maxWithOrNull(comparator)"))
@DeprecatedSinceKotlin(warningSince = "1.4", errorSince = "1.5", hiddenSince = "1.6")
@SinceKotlin("1.3")
@ExperimentalUnsignedTypes

Response:
@Suppress("CONFLICTING_OVERLOADS")
public fun UShortArray.maxWith(comparator: Comparator<in UShort>): UShort? {
    return maxWithOrNull(comparator)
}

@Deprecated("Use minOrNull instead.", ReplaceWith("this.minOrNull()"))<|endoftext|>


Prompt:
val lexicalScope = context.trace.bindingContext[BindingContext.LEXICAL_SCOPE, kotlinCall.psiCall.callElement]
            val nearestScopeDescriptor = lexicalScope?.ownerDescriptor
            // Don't need to store lambda psi element if it can be accessed though unmarked `this`

Response:
nearestScopeDescriptor != null && nearestScopeDescriptor != (receiver as? ExtensionReceiver)?.declarationDescriptor
        }

        if (receiverType != newReceiverType) {
            val typeVariables = substitutionMap.map { it.key as NewTypeVariableConstructor }<|endoftext|>


Prompt:
UNDEFINED(Character.DIRECTIONALITY_UNDEFINED.toInt()),

    /**
     * Strong bidirectional character type "L" in the Unicode specification.
     */
    LEFT_TO_RIGHT(Character.DIRECTIONALITY_LEFT_TO_RIGHT.toInt()),

    /**
     * Strong bidirectional character type "R" in the Unicode specification.

Response:
*/
    RIGHT_TO_LEFT(Character.DIRECTIONALITY_RIGHT_TO_LEFT.toInt()),

    /**
     * Strong bidirectional character type "AL" in the Unicode specification.
     */
    RIGHT_TO_LEFT_ARABIC(Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC.toInt()),

    /**<|endoftext|>


Prompt:
if (arg != null) {
            this.putValueArgument(it.index, arg)
        }
    }
}

val IrField.hasNonConstInitializer: Boolean
    get() = initializer?.expression.let { it != null && it !is IrConst<*> && it !is IrConstantValue }

Response:
fun IrExpression.isNullConst() = this is IrConst<*> && this.kind == IrConstKind.Null

fun IrExpression.isTrueConst() = this is IrConst<*> && this.kind == IrConstKind.Boolean && this.value == true

fun IrExpression.isFalseConst() = this is IrConst<*> && this.kind == IrConstKind.Boolean && this.value == false<|endoftext|>


Prompt:
// !LANGUAGE: +UnrestrictedBuilderInference
// !DIAGNOSTICS: -UNUSED_PARAMETER -UNCHECKED_CAST -DEPRECATION -OPT_IN_IS_NOT_ENABLED -UNUSED_VARIABLE
// WITH_STDLIB

// FILE: Test.java

class Test {
    static <T> T foo(T x) { return x; }

Response:
}

// FILE: main.kt
import kotlin.experimental.ExperimentalTypeInference

@OptIn(ExperimentalTypeInference::class)
fun <R1> build(block: TestInterface<R1>.() -> Unit): R1 = TODO()

@OptIn(ExperimentalTypeInference::class)<|endoftext|>


Prompt:
private fun List<Annotation>.item(): Item? =
    firstOrNull { it.name == "ComposableTarget" }?.let { Token(it.value) }
        ?: firstOrNull { it.name == "ComposableOpenTarget" }?.let { Open(it.value.toInt()) }

val composable = listOf(Annotation("Composable"))

Response:
val uiTarget = listOf(Annotation("ComposableTarget", "UI"))
val vectorTarget = listOf(Annotation("ComposableTarget", "Vector"))
fun composableLambda() = FunctionType("lambda", annotations = composable)
fun call(name: String, vararg args: Node) = Call(Ref(name), arguments = args.toList())<|endoftext|>


Prompt:
function is IrConstructor && function.constructedClass.isMultiFieldValueClass ->
                JvmLoweredDeclarationOrigin.STATIC_MULTI_FIELD_VALUE_CLASS_CONSTRUCTOR

            else -> replacementOrigin
        }
        name =
            if (function.isLocal && (function !is IrSimpleFunction || function.overriddenSymbols.isEmpty())) function.name

Response:
else InlineClassAbi.mangledNameFor(context, function, mangleReturnTypes = false, useOldMangleRules = false)
    }

    private fun makeAndAddGroupedValueParametersFrom(
        sourceFunction: IrFunction,
        includeDispatcherReceiver: Boolean,
        substitutionMap: Map<IrTypeParameterSymbol, IrType>,
        targetFunction: IrFunction,<|endoftext|>


Prompt:
package org.jetbrains.kotlin.wasm.test.tools

import org.jetbrains.kotlin.platform.wasm.BinaryenConfig
import org.jetbrains.kotlin.utils.addToStdlib.runIf
import java.io.File
import kotlin.test.fail

sealed interface WasmOptimizer {

Response:
fun run(wasmInput: ByteArray, withText: Boolean = false): OptimizationResult

    data class OptimizationResult(val wasm: ByteArray, val wat: String?)

    object Binaryen : WasmOptimizer {
        private val binaryenPath = System.getProperty("binaryen.path")

        override fun run(wasmInput: ByteArray, withText: Boolean): OptimizationResult {<|endoftext|>


Prompt:
val res1 = atomicIntArr.compareAndSet(2, 20, 222) // success
        assertTrue(res1 && atomicIntArr[2] == 222, "compareAndSet: FAIL 1")
        val res2 = atomicIntArr.compareAndSet(2, 222, 2222) // success

Response:
assertTrue(res2 && atomicIntArr[2] == 2222, "compareAndSet: FAIL 2")
        val res3 = atomicIntArr.compareAndSet(2, 223, 22222) // should fail
        assertTrue(!res3 && atomicIntArr[2] == 2222, "compareAndSet: FAIL 3")<|endoftext|>


Prompt:
* [shortenedReference] will be "bar" when we shorten:
 * ```
 * import my.package.foo as bar
 * ... my.package.fo<caret>o ... // -> we can replace this with `bar`.
 * ```
 */
public data class QualifierToShortenInfo(
    val qualifierToShorten: SmartPsiElementPointer<KtDotQualifiedExpression>,

Response:
val shortenedReference: String?,
)

/**
 * A class with a reference to [KtThisExpression] with a label qualifier ([KtThisExpression.labelQualifier]) that can be safely removed
 * without changing the semantics of the code.
 */
public data class ThisLabelToShortenInfo(
    val labelToShorten: SmartPsiElementPointer<KtThisExpression>,
)<|endoftext|>


Prompt:
description = """Transform '(' and ')' in method names to some other character sequence.
This mode can BREAK BINARY COMPATIBILITY and should only be used as a workaround for
problems with parentheses in identifiers on certain platforms."""
    )
    var sanitizeParentheses = false
        set(value) {
            checkFrozen()
            field = value
        }

    @Argument(

Response:
value = "-Xfriend-paths",
        valueDescription = "<path>",
        description = "Paths to output directories for friend modules (modules whose internals should be visible)."
    )
    var friendPaths: Array<String>? = null
        set(value) {
            checkFrozen()
            field = value
        }

    @Argument(<|endoftext|>


Prompt:
"(a, b)",
            """
                @UnsafeNumber(["a: kotlin.UInt", "b: kotlin.ULong"])
                typealias X = UInt
            """.trimIndent()
        )
    }

    fun `test ULong and UByte - typealias`() {
        val result = commonize {
            outputTarget("(a, b)")

Response:
setting(OptimisticNumberCommonizationEnabledKey, true)
            registerFakeStdlibIntegersDependency("(a, b)")
            simpleSingleSourceTarget("a", "typealias X = ULong")
            simpleSingleSourceTarget("b", "typealias X = UByte")
        }

        result.assertCommonized(
            "(a, b)",
            """<|endoftext|>


Prompt:
recordLambdasInvocations(trace, moduleDescriptor)
        recordResultInfo(trace, moduleDescriptor)
    }

    private fun ResolvedCall<*>.recordResultInfo(trace: BindingTrace, moduleDescriptor: ModuleDescriptor) {
        if (this !is NewResolvedCallImpl) return

Response:
val resultDFIfromES = effectSystem.getDataFlowInfoForFinishedCall(this, trace, moduleDescriptor)
        this.updateResultingDataFlowInfo(resultDFIfromES)
    }

    private fun ResolvedCall<*>.recordLambdasInvocations(trace: BindingTrace, moduleDescriptor: ModuleDescriptor) {<|endoftext|>


Prompt:
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.DescriptorUtils.isEnumClass
import org.jetbrains.kotlin.resolve.DescriptorUtils.isEnumEntry
import org.jetbrains.kotlin.resolve.constants.CompileTimeConstant

Response:
import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator
import org.jetbrains.kotlin.resolve.descriptorUtil.classId
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeUtils<|endoftext|>


Prompt:
get() = if (!shouldSaveDeserializationState) error("File deserialization state are not cached inside the instance because `shouldSaveDeserializationState` was set as `false`") else field

    protected val moduleReversedFileIndex = hashMapOf<IdSignature, FileDeserializationState>()

    override val moduleDependencies by lazy {
        moduleDescriptor.allDependencyModules

Response:
.filter { it != moduleDescriptor }
            .map { linker.resolveModuleDeserializer(it, null) }
    }

    override fun fileDeserializers(): Collection<IrFileDeserializer> {
        return fileToDeserializerMap.values.filterNot { strategyResolver(it.file.fileEntry.name).onDemand }
    }<|endoftext|>


Prompt:
value class A(val x1: Any, val x2: Any) {
    var nonNullTest: Z
        get() = Z(global.x1 + this.x1 as UInt, global.x2 + this.x2 as Int)
        set(value) {
            global = Z(this.x1 as UInt + value.x1, this.x2 as Int + value.x2)
        }

Response:
var nullableTest: Z?
        get() = Z(global.x1 + this.x1 as UInt, global.x2 + this.x2 as Int)
        set(value) {
            global = Z(this.x1 as UInt + value!!.x1, this.x2 as Int + value!!.x2)
        }

}

fun box(): String {<|endoftext|>


Prompt:
//                JsIrBuilder.buildCall(isCharSymbol).apply { dispatchReceiver = argument }

            private fun generateSuspendFunctionCheck(argument: IrExpression, toType: IrType): IrExpression {
                val arity = (toType.classifierOrFail.owner as IrClass).typeParameters.size - 1 // drop return type

                val irBuiltIns = context.irBuiltIns

Response:
return JsIrBuilder.buildCall(isSuspendFunctionSymbol, irBuiltIns.booleanType).apply {
                    putValueArgument(0, argument)
                    putValueArgument(1, JsIrBuilder.buildInt(irBuiltIns.intType, arity))
                }
            }

            private fun generateTypeOfCheck(argument: IrExpression, toType: IrType): IrExpression {<|endoftext|>


Prompt:
*   2. `unit` is a tail-call function.
     *
     * When `unit` is a not tail-call function, calling `resumeWith` on its continuation will resume `unit`,
     * it will hit { GETSTATIC Unit; ARETURN } and this Unit will be the result of the suspend call. `unit`'s continuation will then call

Response:
* `main` continuation's `resumeWith`, passing the Unit instance. The continuation in turn will resume `main` and the Unit will be
     * the result of `unit()` call. This result will then printed.
     *
     * However, when `unit` is a tail-call function, there is no continuation, generated for it. This is the point of tail-call<|endoftext|>


Prompt:
<!DEBUG_INFO_EXPRESSION_TYPE("Class? & Class")!>x<!>.prop_8
        <!DEBUG_INFO_EXPRESSION_TYPE("Class? & Class")!>x<!>.prop_8.prop_8
        <!DEBUG_INFO_EXPRESSION_TYPE("Class? & Class")!>x<!>.prop_8.prop_8.prop_8

Response:
<!DEBUG_INFO_EXPRESSION_TYPE("Class? & Class")!>x<!>.prop_8.prop_8.prop_8.prop_8
    }
}

// TESTCASE NUMBER: 2
fun case_2(x: Class?) {
    if (x?.prop_8?.prop_8?.prop_8?.prop_8 !== null) {<|endoftext|>


Prompt:
/* Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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
 *

Response:
*     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.
 */<|endoftext|>


Prompt:
return@Predicate fqName.isRoot || fqName.pathSegments().first() in packagesNames
            }

            if (checkTypeEnabled && descriptor.name in NAMES_OF_CHECK_TYPE_HELPER) return@Predicate false

            true
        }

        return RECURSIVE.filterRecursion(stepIntoFilter)

Response:
.withValidationStrategy(DescriptorValidator.ValidationVisitor.errorTypesAllowed())
            .checkFunctionContracts(true)
    }

    private fun getTopLevelPackagesFromFileList(files: List<KtFile>): Set<Name> =
        files.mapTo(LinkedHashSet<Name>()) { file -><|endoftext|>


Prompt:
rootCause.causingTypes,
                rootCause.kind,
                isError = rootCause.isError
            )

            is AdaptedCallableReferenceIsUsedWithReflection -> FirErrors.ADAPTED_CALLABLE_REFERENCE_AGAINST_REFLECTION_TYPE.createOn(
                qualifiedAccessSource
            )

            // Reported later
            is TypeParameterAsExpression -> null

Response:
is AmbiguousInterceptedSymbol -> FirErrors.PLUGIN_AMBIGUOUS_INTERCEPTED_SYMBOL.createOn(source, rootCause.pluginNames)

            is MissingInnerClassConstructorReceiver -> FirErrors.INNER_CLASS_CONSTRUCTOR_NO_RECEIVER.createOn(
                qualifiedAccessSource ?: source,
                rootCause.candidateSymbol
            )<|endoftext|>


Prompt:
)
}

private fun linkAllDependencies(generationState: NativeGenerationState, generatedBitcodeFiles: List<String>) {
    val (runtimeModules, additionalModules) = collectLlvmModules(generationState, generatedBitcodeFiles)
    // TODO: Possibly slow, maybe to a separate phase?

Response:
val optimizedRuntimeModules = RuntimeLinkageStrategy.pick(generationState, runtimeModules).run()

    // When the main module `generationState.llvmModule` is very large it is much faster to
    // link all the auxiliary modules together first before linking with the main module.
    val linkedModules = (optimizedRuntimeModules + additionalModules).reduceOrNull { acc, module -><|endoftext|>


Prompt:
@DisplayName("Should ignore if verification mode is 'ignore' and kotlin and java targets are different")
    @GradleTest
    internal fun shouldNotPrintAnythingIfJavaAndKotlinJvmTargetsAreDifferent(
        gradleVersion: GradleVersion
    ) {
        project(
            projectName = "kotlinJavaProject".fullProjectName,
            gradleVersion = gradleVersion
        ) {

Response:
setJavaCompilationCompatibility(JavaVersion.VERSION_1_8)
            useToolchainToCompile(11)
            //language=properties
            gradleProperties.append(
                """
                # suppress inspection "UnusedProperty"
                kotlin.jvm.target.validation.mode = ignore
                """.trimIndent()
            )

            build("assemble") {<|endoftext|>


Prompt:
if (node.tokenType == KtNodeTypes.LABEL_QUALIFIER) {
                return super.mark(node, startOffset, endOffset - 1, tree)
            }
            if (node.tokenType == KtNodeTypes.PACKAGE_DIRECTIVE) {
                val referenceExpression = tree.findLastDescendant(node) {

Response:
it.tokenType == KtNodeTypes.REFERENCE_EXPRESSION
                }
                if (referenceExpression != null) {
                    return markElement(referenceExpression, startOffset, endOffset, tree, node)
                }
            }
            return DEFAULT.mark(node, startOffset, endOffset, tree)
        }
    }<|endoftext|>


Prompt:
wrapper.read()
        }
    }

    @Test
    fun incorrectPadding() {
        for (base64 in listOf(Base64, Base64.Mime)) {
            val inputStream = "Zm9vZm=9v".byteInputStream()
            val wrapper = inputStream.decodingWith(base64)

            wrapper.use {

Response:
assertEquals('f'.code, it.read())
                assertEquals('o'.code, it.read())
                assertEquals('o'.code, it.read())

                // the second group is incorrectly padded
                assertFailsWith<IllegalArgumentException> {
                    it.read()
                }
            }

            // closed
            assertFailsWith<IOException> {
                wrapper.read()<|endoftext|>


Prompt:
val loadedInProjects = multipleProjectsHolder.getAffectedProjects(project, kotlinPluginVersion)!!
                    if (PropertiesProvider(project).ignorePluginLoadedInMultipleProjects != true) {
                        project.logger.warn("\n$MULTIPLE_KOTLIN_PLUGINS_LOADED_WARNING")
                        project.logger.warn(

Response:
MULTIPLE_KOTLIN_PLUGINS_SPECIFIC_PROJECTS_WARNING + loadedInProjects.joinToString(limit = 4) { "'$it'" }
                        )
                    }
                    project.logger.info(
                        "$MULTIPLE_KOTLIN_PLUGINS_SPECIFIC_PROJECTS_INFO: " +<|endoftext|>


Prompt:
testR1xE1()
    testR1xE2()
    testR1xE3()
    testR1xE4()
    return "OK"
}

fun testR0xE0() {
    // with possible local optimizations
    if (0u in 1u..<3u != range0.contains(0u)) throw AssertionError()

Response:
if (0u !in 1u..<3u != !range0.contains(0u)) throw AssertionError()
    if (!(0u in 1u..<3u) != !range0.contains(0u)) throw AssertionError()
    if (!(0u !in 1u..<3u) != range0.contains(0u)) throw AssertionError()<|endoftext|>


Prompt:
public inline fun UIntArray.reversedArray(): UIntArray {
    return UIntArray(storage.reversedArray())
}

/**
 * Returns an array with elements of this array in reversed order.
 */
@SinceKotlin("1.3")
@ExperimentalUnsignedTypes
@kotlin.internal.InlineOnly
public inline fun ULongArray.reversedArray(): ULongArray {

Response:
return ULongArray(storage.reversedArray())
}

/**
 * Returns an array with elements of this array in reversed order.
 */
@SinceKotlin("1.3")
@ExperimentalUnsignedTypes
@kotlin.internal.InlineOnly
public inline fun UByteArray.reversedArray(): UByteArray {
    return UByteArray(storage.reversedArray())
}

/**<|endoftext|>


Prompt:
return desc == Type.getMethodDescriptor(ownerType, *multiFieldValueClassUnboxInfo.unboxedTypes.toTypedArray())
}

private fun MethodInsnNode.isInlineClassUnboxingMethodDescriptor(state: GenerationState): Boolean {
    if (name != KotlinTypeMapper.UNBOX_JVM_METHOD_NAME) return false

Response:
val ownerType = Type.getObjectType(owner)
    val unboxedType = unboxedTypeOfInlineClass(ownerType, state) ?: return false
    return desc == Type.getMethodDescriptor(unboxedType)
}

private fun MethodInsnNode.isMultiFieldValueClassUnboxingMethodDescriptor(state: GenerationState): Boolean {<|endoftext|>


Prompt:
class Example {
    <!INAPPLICABLE_INFIX_MODIFIER!>infix<!> fun e8(s: String, a: Int = 0) {}
    <!INAPPLICABLE_INFIX_MODIFIER!>infix<!> fun e9(s: String, a: Int) {}

Response:
<!INAPPLICABLE_INFIX_MODIFIER!>infix<!> fun e10() {}
}<|endoftext|>


Prompt:
package org.jetbrains.kotlin.kotlinp.jvm.test

import com.intellij.openapi.Disposable
import com.intellij.openapi.util.Disposer
import org.jetbrains.kotlin.test.util.KtTestUtil
import org.junit.Test
import org.junit.runner.RunWith

Response:
import org.junit.runners.Parameterized
import java.io.File

@RunWith(Parameterized::class)
class KotlinpCompilerTestDataTest(private val file: File) {
    private class TestDisposable : Disposable {
        override fun dispose() {}
    }

    @Test
    fun doTest() {<|endoftext|>


Prompt:
internal fun ReflectionState.asProxy(callInterceptor: CallInterceptor): ReflectionProxy {
            return when (this) {
                is KPropertyState -> when {
                    this.isKMutableProperty0() -> KMutableProperty0Proxy(this, callInterceptor)
                    this.isKProperty0() -> KProperty0Proxy(this, callInterceptor)

Response:
this.isKMutableProperty1() -> KMutableProperty1Proxy(this, callInterceptor)
                    this.isKProperty1() -> KProperty1Proxy(this, callInterceptor)
                    this.isKMutableProperty2() -> KMutableProperty2Proxy(this, callInterceptor)
                    this.isKProperty2() -> KProperty2Proxy(this, callInterceptor)
                    else -> TODO()
                }<|endoftext|>


Prompt:
// test.kt:71 $N.<init>
// test.kt:67 $N.<init> (16, 8)
// test.kt:68 $N.<init>
// test.kt:16 $box (4, 6, 6, 6, 6, 4, 4)
// test.kt:73 $O.<init> (16, 16)

Response:
// test.kt:17 $box (4, 6, 9, 9, 9, 9, 4)
// test.kt:74 $O.<init> (36, 31)
// test.kt:75 $O.<init>
// test.kt:18 $box<|endoftext|>


Prompt:
package one.two

class Foo

fun Foo.ext() {}

/**
 * [<caret_1>one.two.ext]
 * [one.<caret_2>two.ext]
 *
 * [<caret_3>Foo.ext]
 * [one.two.<caret_4>Foo.ext]
 *

Response:
* [<caret_5>one.two.Foo.ext]
 * [one.<caret_6>two.Foo.ext]
 */
fun usage() {}<|endoftext|>


Prompt:
require(args.size == 2) { "The call to ${callSite.symbol.owner.name.asString()} expects 2 value arguments." }
        val address = arrayGetElementAddress(callSite, args[0], args[1])

Response:
return loadSlot(callSite.llvmReturnType, address, isVar = true, resultSlot, memoryOrder = LLVMAtomicOrdering.LLVMAtomicOrderingSequentiallyConsistent)
    }

    private fun FunctionGenerationContext.transformArgsForAtomicArray(callSite: IrCall, args: List<LLVMValueRef>): List<LLVMValueRef> {<|endoftext|>


Prompt:
return Pair(first, second)
}

/**
 * Splits the original array into pair of lists,
 * where *first* list contains elements for which [predicate] yielded `true`,
 * while *second* list contains elements for which [predicate] yielded `false`.
 *
 * @sample samples.collections.Arrays.Transformations.partitionArrayOfPrimitives
 */

Response:
public inline fun LongArray.partition(predicate: (Long) -> Boolean): Pair<List<Long>, List<Long>> {
    val first = ArrayList<Long>()
    val second = ArrayList<Long>()
    for (element in this) {
        if (predicate(element)) {
            first.add(element)
        } else {
            second.add(element)
        }
    }<|endoftext|>


Prompt:
package org.jetbrains.benchmarksLauncher

import org.jetbrains.report.BenchmarkResult

interface AbstractBenchmarkEntry {
    open val useAutoEvaluatedNumberOfMeasure: Boolean
}

open class BenchmarkEntryWithInit(val ctor: ()->Any, val lambda: (Any) -> Any?): AbstractBenchmarkEntry {
    companion object {

Response:
inline fun <T: Any> create(noinline ctor: ()->T, crossinline lambda: T.() -> Any?) = BenchmarkEntryWithInit(ctor) { (it as T).lambda() }
    }

    override val useAutoEvaluatedNumberOfMeasure: Boolean = true
}<|endoftext|>


Prompt:
testR1xE15()
    testR1xE16()
    testR1xE17()
    testR1xE18()
    testR1xE19()
    testR1xE20()
    testR1xE21()
    testR1xE22()
    testR1xE23()
    testR2xE0()
    testR2xE1()

Response:
testR2xE2()
    testR2xE3()
    testR2xE4()
    testR2xE5()
    testR2xE6()
    testR2xE7()
    testR2xE8()
    testR2xE9()
    testR2xE10()
    testR2xE11()
    testR2xE12()<|endoftext|>


Prompt:
// FIR_IDENTICAL

// MODULE: a
// FILE: A.kt

//class FirstClass : SecondClass()
//
//open class SecondClass

class ConfigurationTarget(@ConfigField val target: String)

@Retention(AnnotationRetention.RUNTIME)
annotation class ConfigField()

// MODULE: b
// FILE: B.kt

@Retention(AnnotationRetention.RUNTIME)

Response:
annotation class ConfigField()

class ConfigurationTarget(@ConfigField val target: String)<|endoftext|>


Prompt:
if (z != null) {
            <!DEBUG_INFO_EXPRESSION_TYPE("case_25.`<anonymous>`.`<no name provided>` & case_25.`<anonymous>`.`<no name provided>`?"), DEBUG_INFO_SMARTCAST!>z<!>.a

Response: <!DEBUG_INFO_EXPRESSION_TYPE("case_25.`<anonymous>`.`<no name provided>` & case_25.`<anonymous>`.`<no name provided>`?"), DEBUG_INFO_SMARTCAST!>z<!>.a.equals(null)<|endoftext|>


Prompt:
<!DEBUG_INFO_EXPRESSION_TYPE("Out<kotlin.Number?> & Out<kotlin.Number?>?"), DEBUG_INFO_SMARTCAST!>x<!>.propAny
        <!DEBUG_INFO_EXPRESSION_TYPE("Out<kotlin.Number?> & Out<kotlin.Number?>?")!>x<!>.propNullableT

Response:
<!DEBUG_INFO_EXPRESSION_TYPE("Out<kotlin.Number?> & Out<kotlin.Number?>?")!>x<!>.propNullableAny
        <!DEBUG_INFO_EXPRESSION_TYPE("Out<kotlin.Number?> & Out<kotlin.Number?>?"), DEBUG_INFO_SMARTCAST!>x<!>.funT()<|endoftext|>


Prompt:
fun buildConstructorCall(
        target: IrConstructorSymbol,
        typeArguments: List<IrType?>? = null,
        constructorTypeArguments: List<IrType?>? = null,
        origin: IrStatementOrigin = JsStatementOrigins.SYNTHESIZED_STATEMENT
    ): IrConstructorCall {
        val owner = target.owner

Response:
val irClass = owner.parentAsClass

        return IrConstructorCallImpl(
            UNDEFINED_OFFSET,
            UNDEFINED_OFFSET,
            owner.returnType,
            target,
            typeArgumentsCount = irClass.typeParameters.size,
            constructorTypeArgumentsCount = owner.typeParameters.size,
            valueArgumentsCount = owner.valueParameters.size,<|endoftext|>


Prompt:
// TARGET_BACKEND: JVM

var capturedLambda: ((Int) -> Int)? = null

fun captureLambda(): Boolean {
    val lambda = { x: Int -> x + 1 }
    if (capturedLambda == null) {
        capturedLambda = lambda
    } else if (capturedLambda !== lambda) {
        return false
    }
    return true
}

Response:
fun box(): String {
    captureLambda()
    if (!captureLambda())
        return "FAIL"
    return "OK"
}<|endoftext|>


Prompt:
assertEquals("${'a'.toChar()}", ('a'.toChar() as Char?).toString(), "char template failed")

    for(b in 0..255) {
        assertEquals("${b.toByte()}", (b.toByte() as Byte?).toString(), "byte conversion failed")
    }

Response:
assertEquals(23.21.myToString(), 23.21.toString(), "23.21 failed")

    assertEquals(Double.MIN_VALUE.myToString(), Double.MIN_VALUE.toString(), "Double.MIN_VALUE failed")
    assertEquals(Double.MAX_VALUE.myToString(), Double.MAX_VALUE.toString(), "Double.MAX_VALUE failed")<|endoftext|>


Prompt:
*     which will be substituted with actual parameters used in the call being updated. The imports used in the file
 *     containing the deprecated function or property are NOT accessible; if the replacement expression refers
 *     on any of those imports, they need to be specified explicitly in the [imports] parameter.
 * @property imports the qualified names that need to be imported in order for the references in the
 *     replacement expression to be resolved correctly.
 */

Response:
@Target()
@Retention(BINARY)
@MustBeDocumented
public annotation class ReplaceWith(val expression: String, vararg val imports: String)

/**
 * Possible levels of a deprecation. The level specifies how the deprecated element usages are reported in code.
 *
 * @see Deprecated
 */
public enum class DeprecationLevel {
    /** Usage of the deprecated element will be reported as a warning. */<|endoftext|>


Prompt:
return doAnalyze(psiFile, importedScripts, codeLine.addNo(priority))
    }

    protected fun runAnalyzer(linePsi: KtFile, importedScripts: List<KtFile>): TopDownAnalysisContext {
        return topDownAnalyzer.analyzeDeclarations(topDownAnalysisContext.topDownAnalysisMode, listOf(linePsi) + importedScripts)
    }

Response:
private fun doAnalyze(linePsi: KtFile, importedScripts: List<KtFile>, codeLine: SourceCodeByReplLine): ReplLineAnalysisResult {
        scriptDeclarationFactory.setDelegateFactory(
            FileBasedDeclarationProviderFactory(resolveSession.storageManager, listOf(linePsi) + importedScripts)
        )
        replState.submitLine(linePsi)<|endoftext|>


Prompt:
return result
}

/**
 * Create binary search for when that emit when expressions in leafs
 * when (a) {
 *   123 -> expr1
 *   456 -> expr2
 *   else -> elseExpr
 * }
 * crates binary search linked to index of branch
 * BLOCK
 *   IF (a < 456) {
 *      IF (a == 123)
 *        #expr1

Response:
*        GOTO END BLOCK
 *      END IF
 *   ELSE
 *      IF (1 == 456)
 *        #expr2
 *        GOTO END BLOCK
 *      END IF
 *   END IF
 *   elseExpr
 * END BLOCK
 * }
*/
private fun BodyGenerator.createBinaryTable(
    selectorLocal: WasmLocal,<|endoftext|>


Prompt:
val argumentType = mycType.arguments.single().type!!
        if (!argumentType.isMarkedNullable)
            return "Fail on $fn: argument type should be seen as nullable"

        val annotations = argumentType.annotations
        if (annotations.toString() != "[@Anno(value=OK)]")
            return "Fail on $fn: $annotations"
    }

Response:
return "OK"
}<|endoftext|>


Prompt:
fun <K: T> foo1(x: T?, y: Bar<K>) {}
    fun <K: T> foo2(x: K?, y: Bar<T>) {}
}

fun <K> foo14(x: K?, y: Bar<K>) where K: Comparable<K>, K: CharSequence {}

Response:
fun <K: T?, T> foo15(x: T, y: Bar<K>) {}
fun <K: T?, T> foo16(x: K, y: Bar<T>) {}
fun <K: T?, T> Bar<K>.foo18(x: T) {}

fun <K> foo21(x: K?, y: Foo<Foo<OutBar<K>>>) {}<|endoftext|>


Prompt:
*     companion object Key : AbstractCoroutineContextKey<BaseElement, DerivedElement>(BaseElement, { it as? DerivedElement })
 * }
 * // Now it is possible to query both `BaseElement` and `DerivedElement`
 * someContext[BaseElement] // Returns BaseElement?, non-null both for BaseElement and DerivedElement instances

Response:
* someContext[DerivedElement] // Returns DerivedElement?, non-null only for DerivedElement instance
 * ```
 * @param B base class of a polymorphic element
 * @param baseKey an instance of base key
 * @param E element type associated with the current key
 * @param safeCast a function that can safely cast abstract [CoroutineContext.Element] to the concrete [E] type<|endoftext|>


Prompt:
abstract fun <T1> run(method: KProperty0<T1>, fn: (T1) -> Boolean): String
}

fun box(): String {
    var result = ( object : Checker() {
        override fun <T1> run(method: KProperty0<T1>, fn: (T1) -> Boolean): String {
            return "OK"
        }
    } ).check()

Response:
return result
}<|endoftext|>


Prompt:
override fun processHiddenParameters() {
        if (!DescriptorAsmUtil.isStaticMethod((sourceCompiler as PsiSourceCompilerForInline).context.contextKind, functionDescriptor)) {
            hiddenParameters += invocationParamBuilder.addNextParameter(methodOwner, false, actualDispatchReceiver) to
                    codegen.frameMap.enterTemp(methodOwner)
        }

Response:
for (param in jvmSignature.valueParameters) {
            if (param.kind == JvmMethodParameterKind.VALUE) {
                break
            }
            hiddenParameters += invocationParamBuilder.addNextParameter(param.asmType, false) to
                    codegen.frameMap.enterTemp(param.asmType)
        }
        // TODO: Add context receivers as hiddenParameters
    }<|endoftext|>


Prompt:
// Also, EnhancedTypeAnnotationDescriptor is not a "real" annotation descriptor, there's no corresponding ClassDescriptor, etc.
        if (extensions.enhancedNullability.hasEnhancedNullability(kotlinType)) {
            irAnnotations.addIfNotNull(extensions.generateEnhancedNullabilityAnnotationCall())
        }

        if (flexibleType.isNullabilityFlexible()) {

Response:
irAnnotations.addIfNotNull(extensions.generateFlexibleNullabilityAnnotationCall())
        }
        if (flexibleType.isMutabilityFlexible()) {
            irAnnotations.addIfNotNull(extensions.generateFlexibleMutabilityAnnotationCall())
        }

        if (flexibleType is RawType) {<|endoftext|>


Prompt:
import org.jetbrains.kotlin.scripting.resolve.KotlinScriptDefinitionFromAnnotatedTemplate
import org.jetbrains.kotlin.test.ConfigurationKind
import org.jetbrains.kotlin.test.KotlinTestUtils
import org.jetbrains.kotlin.test.TestJdkKind

Response:
import org.jetbrains.kotlin.test.util.KtTestUtil
import org.jetbrains.org.objectweb.asm.Opcodes
import java.io.File
import kotlin.script.experimental.jvm.defaultJvmScriptingHostConfiguration
import kotlin.script.templates.ScriptTemplateDefinition

class ScriptGenTest : CodegenTestCase() {
    companion object {<|endoftext|>


Prompt:
package org.jetbrains.kotlin.fir.scopes

import org.jetbrains.kotlin.fir.declarations.FirCallableDeclaration
import org.jetbrains.kotlin.fir.originalForSubstitutionOverride
import org.jetbrains.kotlin.fir.symbols.impl.FirCallableSymbol

Response:
import org.jetbrains.kotlin.fir.symbols.impl.FirIntersectionCallableSymbol
import org.jetbrains.kotlin.fir.symbols.impl.FirNamedFunctionSymbol
import org.jetbrains.kotlin.fir.symbols.impl.FirPropertySymbol
import org.jetbrains.kotlin.name.Name<|endoftext|>


Prompt:
}

fun foo() {
    <!OVERLOADS_LOCAL!>@kotlin.jvm.JvmOverloads<!> fun quux(s: String = "OK") {
    }

    class D {
        <!OVERLOADS_LOCAL!>@kotlin.jvm.JvmOverloads<!> fun foo(s: String = "OK") {
        }
    }

Response:
val x = object {
        <!OVERLOADS_LOCAL!>@kotlin.jvm.JvmOverloads<!> fun foo(s: String = "OK") {
        }
    }
}<|endoftext|>


Prompt:
classPath.joinToString(File.pathSeparator, transform = { File(it.toURI()).absolutePath }),
        ) + mainClassAndArguments

        val process = ProcessBuilder(command).start()

        // Extract the chosen port from the output of the newly started java process.
        // The java process prints a line with the format:
        //

Response:
//      Listening for transport dt_socket at address: <port number>
        val port = process.inputStream.bufferedReader().readLine().split("address:").last().trim().toInt()

        // Attach debugger to the separate java process, setup initial event requests,
        // and run the debugger loop to step through the program.
        val virtualMachine = attachDebugger(port)<|endoftext|>


Prompt:
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.fir.*
import org.jetbrains.kotlin.fir.declarations.*
import org.jetbrains.kotlin.fir.declarations.synthetic.FirSyntheticProperty

Response:
import org.jetbrains.kotlin.fir.declarations.synthetic.FirSyntheticPropertyAccessor
import org.jetbrains.kotlin.fir.declarations.utils.isLocal
import org.jetbrains.kotlin.fir.resolve.providers.firProvider
import org.jetbrains.kotlin.fir.resolve.providers.symbolProvider<|endoftext|>


Prompt:
// |) or |<EOF> - add an empty node.
        if (lexemes.lookBack == Lexer.CHAR_VERTICAL_BAR) {
            children.add(EmptySet(fSet))
        }

        // Restore flags.
        if (flags != savedFlags && !saveChangedFlags) {
            flags = savedFlags
            lexemes.restoreFlags(flags)
        }

Response:
when (ch) {
            Lexer.CHAR_NONCAP_GROUP -> return NonCapturingJointSet(children, fSet)
            Lexer.CHAR_POS_LOOKAHEAD -> return PositiveLookAheadSet(children, fSet)
            Lexer.CHAR_NEG_LOOKAHEAD -> return NegativeLookAheadSet(children, fSet)<|endoftext|>


Prompt:
override fun indexOf(element: T): Int {
        @Suppress("SENSELESS_COMPARISON")
        if (element === null) return -1 // WA for JS IR bug
        // Check identity due to UnsafeVariance
        val ordinal = element.ordinal
        val target = entries.getOrNull(ordinal)
        return if (target === element) ordinal else -1
    }

Response:
override fun lastIndexOf(element: T): Int = indexOf(element)

    @Suppress("unused")
    private fun writeReplace(): Any {
        // Used for Java serialization: EESP ensures that deserialized object **always** reflects the state of the enum on the target classpath
        return EnumEntriesSerializationProxy(entries)
    }
}<|endoftext|>


Prompt:
val SVG_ZOOMANDPAN_DISABLE: Short
        val SVG_ZOOMANDPAN_MAGNIFY: Short
        val ELEMENT_NODE: Short
        val ATTRIBUTE_NODE: Short
        val TEXT_NODE: Short
        val CDATA_SECTION_NODE: Short
        val ENTITY_REFERENCE_NODE: Short

Response:
val ENTITY_NODE: Short
        val PROCESSING_INSTRUCTION_NODE: Short
        val COMMENT_NODE: Short
        val DOCUMENT_NODE: Short
        val DOCUMENT_TYPE_NODE: Short
        val DOCUMENT_FRAGMENT_NODE: Short
        val NOTATION_NODE: Short
        val DOCUMENT_POSITION_DISCONNECTED: Short<|endoftext|>


Prompt:
if (w != null || <!SENSELESS_COMPARISON!>this.w != null<!>) this.w.funT()
        if (w != null || <!SENSELESS_COMPARISON!>this.w != null<!>) this.w.funAny()

Response:
if (w != null || <!SENSELESS_COMPARISON!>this.w != null<!>) this.w.funNullableT()
        if (w != null || <!SENSELESS_COMPARISON!>this.w != null<!>) this.w.funNullableAny()<|endoftext|>


Prompt:
<!DEBUG_INFO_SMARTCAST!>x<!>.length
}

fun test_2(foo: Foo, x: Any) {
    foo.assertIs<String>(x)
    <!DEBUG_INFO_SMARTCAST!>x<!>.length
}

fun test_3(foo: Foo): Int {
    val x: Int
    foo.myRun {
        x = 1

Response:
}
    return x + 1
}<|endoftext|>


Prompt:
if (!aptCache.updateCache(processors, failedToAnalyzeSources)) {
            javaCache.invalidateAll()
            return
        }
        // Compilation is fully incremental, record types defined in generated .class files
        processors.forEach { processor ->
            processor.getGeneratedClassFilesToTypes().forEach { (classFile, type) ->

Response:
val classFileStructure = ClassFileStructure(classFile.toURI(), type)
                javaCache.addSourceStructure(classFileStructure)
            }
        }
    }

    /**
     * From set of changed sources, get list of files to recompile using structural information and dependency information from
     * annotation processing.
     */
    fun invalidateAndGetDirtyFiles(<|endoftext|>


Prompt:
wildcard(type) { argument ->
            assertEquals(emptyList(), argument.lowerBounds.toList())
            val bound = argument.upperBounds.singleOrNull() ?: fail("Type is not an extends-wildcard: $type (${type::class.java.name})")
            block(bound)
        }
    }

    // ? super ...

Response:
private fun wildcardSuper(type: Type, block: (lowerBound: Type) -> Unit) {
        wildcard(type) { argument ->
            assertEquals(listOf(Any::class.java), argument.upperBounds.toList())
            val bound = argument.lowerBounds.singleOrNull() ?: fail("Type is not a super-wildcard: $type (${type::class.java.name})")<|endoftext|>


Prompt:
/* pio4 */     7.85398163397448278999e-01,    /* 3FE921FB, 54442D18 */
/* pio4lo */     3.06161699786838301793e-17    /* 3C81A626, 33145C07 */
)
private val one = xxx[13]
private val pio4 = xxx[14]

Response:
private val pio4lo = xxx[15]
private val T = xxx
/* INDENT ON */

internal fun __kernel_tan(_x: Double, _y: Double, iy: Int): Double {
    var x: Double = _x
    var y: Double = _y
    var z: Double
    var r: Double
    var v: Double
    var w: Double
    var s: Double<|endoftext|>


Prompt:
* UNEXPECTED BEHAVIOUR
 * ISSUES: KT-28329
 */
fun case_10(x: Any?) {
    if (<!DEPRECATED_IDENTITY_EQUALS!>!!(x !is Interface3) === true<!> && true) else {
        <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any?")!>x<!>

Response:
<!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any?")!>x<!>.<!UNRESOLVED_REFERENCE!>itest<!>()
        <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Any?")!>x<!>.<!UNRESOLVED_REFERENCE!>itest3<!>()
    }
}<|endoftext|>


Prompt:
}

        return ExitCode.OK
    }

    private fun prepareEnvironment(
            arguments: K2NativeCompilerArguments,
            configuration: CompilerConfiguration,
            rootDisposable: Disposable
    ): KotlinCoreEnvironment {
        val environment = KotlinCoreEnvironment.createForProduction(rootDisposable,
                configuration, EnvironmentConfigFiles.NATIVE_CONFIG_FILES)

Response:
configuration.put(CLIConfigurationKeys.FLEXIBLE_PHASE_CONFIG, createFlexiblePhaseConfig(arguments))

        /* Set default version of metadata version */
        val metadataVersionString = arguments.metadataVersion
        if (metadataVersionString == null) {
            configuration.put(CommonConfigurationKeys.METADATA_VERSION, KlibMetadataVersion.INSTANCE)
        }<|endoftext|>


Prompt:
if (l.removeAt(0) != "abc") return "fail 2"

    val anyList: MutableList<Any?> = a as MutableList<Any?>
    if (anyList.removeAt(0) != "abc") return "fail 3"

    val container: Container = a
    if (container.removeAt(0) != "abc") return "fail 4"

Response:
return "OK"
}<|endoftext|>


Prompt:
// WITH_STDLIB

import kotlin.test.assertEquals

fun <T : Collection<*>> sumIndices(c: T): Int {
    var sum = 0
    for (i in c.indices) {
        sum += i
    }
    return sum
}

fun box(): String {
    val list = listOf(0, 0, 0, 0)

Response:
val sum = sumIndices(list)
    assertEquals(6, sum)

    return "OK"
}<|endoftext|>


Prompt:
fun TestFunctionVsDelegatedPrimaryConstructorCall() {}

    class TestFunctionVsDelegatedPrimaryConstructorCallReverse constructor(placeholder: UserKlass) {
        constructor() : this(UserKlass())
    }
    @Deprecated(message = "", level = DeprecationLevel.HIDDEN) fun TestFunctionVsDelegatedPrimaryConstructorCallReverse() {}

Response:
open class SuperConstructorSource constructor(placeholder: UserKlass)

    class TestFunctionVsDelegatedSuperConstructorCall: SuperConstructorSource {
        @Deprecated(message = "", level = DeprecationLevel.HIDDEN) constructor() : super(UserKlass())
    }
    fun TestFunctionVsDelegatedSuperConstructorCall() {}<|endoftext|>


Prompt:
container.findMethodBySignature(jvmSignature.methodName, jvmSignature.methodDesc) as Member?
            }
            is JavaMethod -> jvmSignature.method as Member
            is JavaConstructor -> jvmSignature.constructor as Member
            is FakeJavaAnnotationConstructor -> {
                val methods = jvmSignature.methods

Response:
return@caller AnnotationConstructorCaller(container.jClass, methods.map { it.name }, POSITIONAL_CALL, JAVA, methods)
            }
        }

        when (member) {
            is Constructor<*> ->
                createConstructorCaller(member, descriptor, false)
            is Method -> when {
                !Modifier.isStatic(member.modifiers) -><|endoftext|>


Prompt:
hashCode = 31 * hashCode + getArgument(i).hashCode(stringIndexes, fqNameIndexes, typeById)
    }

    if (hasNullable()) {
        hashCode = 31 * hashCode + nullable.hashCode()
    }

    if (hasFlexibleTypeCapabilitiesId()) {
        hashCode = 31 * hashCode + stringIndexes(flexibleTypeCapabilitiesId)

Response:
}

    if (hasFlexibleUpperBound()) {
        hashCode = 31 * hashCode + flexibleUpperBound.hashCode(stringIndexes, fqNameIndexes, typeById)
    }

    if (hasFlexibleUpperBoundId()) {<|endoftext|>


Prompt:
@kotlin.SinceKotlin(version = "1.3")
@kotlin.ExperimentalUnsignedTypes
@kotlin.internal.InlineOnly

Response: public inline fun <C : kotlin.collections.MutableCollection<in kotlin.UShort>> kotlin.UShortArray.filterIndexedTo(destination: C, predicate: (index: kotlin.Int, kotlin.UShort) -> kotlin.Boolean): C<|endoftext|>


Prompt:
.toMutableSet()
        .apply {
            add(outputDirectory.resolve("META-INF/$moduleName.kotlin_module").relativeTo(outputDirectory))
        }
    val notDeclaredFiles = hashSetOf<Path>()
    for (file in outputDirectory.walk()) {
        if (!file.isRegularFile()) continue
        val currentFile = file.relativeTo(outputDirectory)

Response:
filesLeft.remove(currentFile).also { wasPreviously ->
            if (!wasPreviously) notDeclaredFiles.add(currentFile)
        }
    }
    assert(filesLeft.isEmpty()) {
        "The following files were declared as expected, but not actually produced: $filesLeft"
    }
    assert(notDeclaredFiles.isEmpty()) {<|endoftext|>


Prompt:
append(if (fqName.isRoot) "root package" else renderFqName(fqName))

            if (withSourceFileForTopLevel &&
                containingDeclaration is PackageFragmentDescriptor &&
                descriptor is DeclarationDescriptorWithSource
            ) {
                descriptor.source.containingFile.name?.let { sourceFileName ->

Response:
append(" ").append(renderMessage("in file")).append(" ").append(sourceFileName)
                }
            }
        }
    }

    private fun StringBuilder.renderAnnotations(annotated: Annotated, target: AnnotationUseSiteTarget? = null) {
        if (DescriptorRendererModifier.ANNOTATIONS !in modifiers) return<|endoftext|>


Prompt:
public operator fun <K, V> Map<out K, V>.plus(pairs: Sequence<Pair<K, V>>): Map<K, V> =
    LinkedHashMap(this).apply { putAll(pairs) }.optimizeReadOnlyMap()

/**
 * Creates a new read-only map by replacing or adding entries to this map from another [map].
 *

Response:
* The returned map preserves the entry iteration order of the original map.
 * Those entries of another [map] that are missing in this map are iterated in the end in the order of that [map].
 */
public operator fun <K, V> Map<out K, V>.plus(map: Map<out K, V>): Map<K, V> =
    LinkedHashMap(this).apply { putAll(map) }<|endoftext|>


Prompt:
1 -> fun() {}
        2 -> fun(): Int { return 1 }
        3 -> fun(): () -> Unit { return fun() {} }
        4 -> fun_1
    }
}

// TESTCASE NUMBER: 19
fun case_19(value_1: Int): Any {
    val lambda_1 = { 0 }

    return when (value_1) {
        1 -> lambda_1

Response:
2 -> { { {} } }
        else -> { -> (Int)
            { arg: Int -> { { println(arg) } } }
        }
    }
}

// TESTCASE NUMBER: 20
fun case_20(value_1: Int) {
    val object_1 = object {
        val prop_1 = 1
    }

    when (value_1) {<|endoftext|>


Prompt:
public var isInstanceType: KmType? = null

    /**
     * Arguments of an `&&`-expression. If this list is non-empty, the resulting effect expression is a conjunction of this expression
     * and elements of the list.
     */
    public val andArguments: MutableList<KmEffectExpression> = ArrayList(0)

    /**

Response:
* Arguments of an `||`-expression. If this list is non-empty, the resulting effect expression is a disjunction of this expression
     * and elements of the list.
     */
    public val orArguments: MutableList<KmEffectExpression> = ArrayList(0)
}

/**
 * Represents a constant value used in an effect expression.
 *<|endoftext|>


Prompt:
abstract fun KtAnalysisSession.collectSymbols(ktFile: KtFile, testServices: TestServices): SymbolsData

    override fun doTestByMainFile(mainFile: KtFile, mainModule: KtTestModule, testServices: TestServices) {
        val directives = mainModule.testModule.directives

Response:
val directiveToIgnoreSymbolRestore = directives.doNotCheckSymbolRestoreDirective()
        val directiveToIgnoreNonPsiSymbolRestore = directives.doNotCheckNonPsiSymbolRestoreDirective()

        val prettyRenderer = buildList {
            addIfNotNull(defaultRendererOption)
            addAll(directives[PRETTY_RENDERER_OPTION])<|endoftext|>


Prompt:
leftClass.functions.single { it.isEquals() }
                    }
                    +irCall(newEquals).apply {
                        dispatchReceiver = leftArgument
                        putValueArgument(0, rightArgument)
                    }.transform(this@JvmMultiFieldValueClassLowering, null)
                } else if (rightNode != null) {
                    // left one is boxed, right one is unboxed

Response:
if (leftArgument.isNullConst()) {
                        // left argument is always null, right one is unboxed
                        val hasPureFlattenedGetters = rightNode.mapLeaves { it.hasPureUnboxMethod }.all { it }
                        if (hasPureFlattenedGetters) {
                            val rightExpressions = flattenExpression(rightArgument)<|endoftext|>


Prompt:
var c: Continuation<Any>? = null

suspend fun <T> suspendMe(): T = suspendCoroutine {
    @Suppress("UNCHECKED_CAST")
    c = it as Continuation<Any>
}

abstract class ResultReceiver<T> {
    abstract suspend fun receive(result: Result<T>)
}

Response:
inline fun <T> ResultReceiver(crossinline f: (Result<T>) -> Unit): ResultReceiver<T> =
    object : ResultReceiver<T>() {
        override suspend fun receive(result: Result<T>) {
            f(result)
        }
    }

fun test() {
    var invoked = false
    val receiver = ResultReceiver<String> { result -><|endoftext|>


Prompt:
@file:Suppress("unused")  // Used by compiler

package kotlin.wasm.internal

internal const val TYPE_INFO_ELEMENT_SIZE = 4

internal const val TYPE_INFO_TYPE_PACKAGE_NAME_LENGTH_OFFSET = 0

Response:
internal const val TYPE_INFO_TYPE_PACKAGE_NAME_ID_OFFSET = TYPE_INFO_TYPE_PACKAGE_NAME_LENGTH_OFFSET + TYPE_INFO_ELEMENT_SIZE
internal const val TYPE_INFO_TYPE_PACKAGE_NAME_PRT_OFFSET = TYPE_INFO_TYPE_PACKAGE_NAME_ID_OFFSET + TYPE_INFO_ELEMENT_SIZE<|endoftext|>