prompt
stringlengths
1
924
completion
stringlengths
14
937
outerClass = outerClass.findInnerClass(Name.identifier(it)) ?: return null } return outerClass.apply { classifiers[classId] = this } } val kotlinClassifier = kotlinClasses[classId] ?: return null return createMockKotlinClassifier(kotlinClassifier, null, classId) }
} class MockKotlinClassifier(override val classId: ClassId, private val classOrObject: KtClassOrObject?, private val ktFile: KtFile?, private val cache: KotlinClassifiersCache, private val javac: JavacWrapper) : JavaClassWithClassId { override val fqName: FqName<|endoftext|>
// TODO: do not keep direct links val type = providedProperty.type.toIrType() val valueParameter = context.symbolTable.descriptorExtension.declareValueParameter( UNDEFINED_OFFSET, UNDEFINED_OFFSET, IrDeclarationOrigin.SCRIPT_PROVIDED_PROPERTY, parameter, type ) { symbol ->
context.irFactory.createValueParameter( startOffset = UNDEFINED_OFFSET, endOffset = UNDEFINED_OFFSET, origin = IrDeclarationOrigin.SCRIPT_PROVIDED_PROPERTY, name = descriptor.name, type = type, isAssignable = false, symbol = symbol, index = parametersIndex,<|endoftext|>
declarations.forEach(action) } internal val FirDeclaration.isDeclarationContainer: Boolean get() = this is FirRegularClass || this is FirScript || this is FirFile internal inline fun FirDeclaration.forEachDeclaration(action: (FirDeclaration) -> Unit) { when (this) { is FirRegularClass -> forEachDeclaration(action)
is FirScript -> forEachDeclaration(action) is FirFile -> forEachDeclaration(action) else -> errorWithFirSpecificEntries("Unsupported declarations container", fir = this) } } /** * Some "local" declarations are not local from the lazy resolution perspective. */ internal val FirCallableSymbol<*>.isLocalForLazyResolutionPurposes: Boolean<|endoftext|>
get() = SimpleFileSnapshotProviderImpl() @Test fun testExternalizer() { val file = File(workingDir, "1.txt") file.writeText("test") val snapshot = fileSnapshotProvider[file] val deserializedSnapshot = saveAndReadBack(snapshot) assertEquals(snapshot, deserializedSnapshot) }
@Test fun testEqualityNoChanges() { val file = File(workingDir, "1.txt").apply { writeText("file") } val oldSnapshot = fileSnapshotProvider[file] val newSnapshot = fileSnapshotProvider[file] assertEquals(oldSnapshot, newSnapshot) } @Test fun testEqualityDifferentFile() {<|endoftext|>
import kotlin.reflect.KProperty class Delegate { var inner = Derived() operator fun getValue(t: Any?, p: KProperty<*>): Derived { inner = Derived(inner.a + "-get") return inner }
operator fun setValue(t: Any?, p: KProperty<*>, i: Base) { inner = Derived(inner.a + "-" + i.a + "-set") } } class A { var prop: Derived by Delegate() } fun box(): String { val c = A()<|endoftext|>
assertTrue { "com/example/lib/KotlinClassInJava.class" in entries } } } private val targetName = when (HostManager.host) { KonanTarget.LINUX_X64 -> "linux64" KonanTarget.MACOS_X64 -> "macos64" KonanTarget.MACOS_ARM64 -> "macosArm64"
KonanTarget.MINGW_X64 -> "mingw64" else -> fail("Unsupported host") } @Test fun testLibWithTests() = doTestLibWithTests(transformNativeTestProject("new-mpp-lib-with-tests", gradleVersion)) @Test<|endoftext|>
// !LANGUAGE: +SuspendConversion // WITH_STDLIB // WITH_COROUTINES import helpers.* import kotlin.coroutines.* import kotlin.coroutines.intrinsics.* fun runSuspend(c: suspend () -> Unit) { c.startCoroutine(EmptyContinuation) }
fun foo(s: String): String = s + "K" inline suspend fun invokeSuspend(fn: suspend (String) -> String, arg: String) = fn.invoke(arg) fun box(): String { var test = "failed" runSuspend { test = invokeSuspend(::foo, "O") } return test }<|endoftext|>
null, ConstantValueKind.Boolean, (protoValue?.intValue?.toInt() ?: sourceValue) != 0, setType = true ) "STRING", "Ljava/lang/String;" -> buildLiteralExpression( null, ConstantValueKind.String,
protoValue?.stringValue?.let { nameResolver.getString(it) } ?: sourceValue as String, setType = true ) else -> null } } fun CallableId.replaceName(newName: Name): CallableId { return CallableId(this.packageName, this.className, newName) }<|endoftext|>
) : KtAbstractFirDiagnostic<PsiElement>(firDiagnostic, token), KtFirDiagnostic.CyclicConstructorDelegationCall internal class PrimaryConstructorDelegationCallExpectedImpl( firDiagnostic: KtPsiDiagnostic, token: KtLifetimeToken,
) : KtAbstractFirDiagnostic<PsiElement>(firDiagnostic, token), KtFirDiagnostic.PrimaryConstructorDelegationCallExpected internal class ProtectedConstructorNotInSuperCallImpl( override val symbol: KtSymbol, firDiagnostic: KtPsiDiagnostic, token: KtLifetimeToken,<|endoftext|>
// library.kt:18 box: $i$f$flaf:int=0:int, flafVar$iv:int=0:int, fooParam\1$iv:int=0:int, $i$f$foo\1\12:int=0:int, fooVar\1$iv:int=0:int, it\2$iv:int=42:int,
$i$a$-foo-LibraryKt$flaf$1\2\25\0$iv:int=0:int, x\2$iv:int=1:int, fooParam\5$iv:int=2:int, $i$f$foo\5\17:int=0:int, fooVar\5$iv:int=0:int, it\6$iv:int=42:int,<|endoftext|>
irVararg(enumClass.defaultType, enumClass.enumEntries.memoryOptimizedMap { irCall(it.getInstanceFun!!) }) } private val IrClass.enumEntries: List<IrEnumEntry> get() = declarations.filterIsInstance<IrEnumEntry>() // Should be applied recursively
class EnumClassRemoveEntriesLowering(val context: JsCommonBackendContext) : DeclarationTransformer { override fun transformFlat(declaration: IrDeclaration): List<IrDeclaration>? { // Remove IrEnumEntry nodes from class declarations. Replace them with corresponding class declarations (if they have them).<|endoftext|>
@Deprecated("Direct conversion to Char is deprecated. Use toInt().toChar() or Char constructor instead.", ReplaceWith("this.toInt().toChar()")) @DeprecatedSinceKotlin(warningSince = "1.5", errorSince = "2.3") @kotlin.internal.IntrinsicConstEvaluation public override fun toChar(): Char /**
* Converts this [Long] value to [Short]. * * If this value is in [Short.MIN_VALUE]..[Short.MAX_VALUE], the resulting `Short` value represents * the same numerical value as this `Long`. * * The resulting `Short` value is represented by the least significant 16 bits of this `Long` value. */<|endoftext|>
final class AbstractClassImpl4 : AbstractClass() { final override val abstractVal get() = "" final override val openVal get() = "" final override var abstractVar get() = "" set(_) = Unit final override var openVar get() = "" set(_) = Unit final override fun abstractFun() = "" final override fun openFun() = "" } interface Interface1 {
val abstractVal1: String val openVal1: String get() = "" fun abstractFun1(): String fun openFun1(): String = "" } interface Interface2 { val abstractVal2: String val openVal2: String get() = "" fun abstractFun2(): String fun openFun2(): String = "" }<|endoftext|>
companion object { val foo: String ="FOO" } } class OnlyFooParamExported(val foo: String) : ExportedInterface { @JsExport.Ignore constructor() : this("TEST") override val baz = "Baz" override fun inter(): String = "Inter" @JsExport.Ignore
val bar = "Bar" @JsExport.Ignore inline fun <A, reified B> A.notExportableReified(): Boolean = this is B @JsExport.Ignore suspend fun notExportableSuspend(): String = "SuspendResult" @JsExport.Ignore fun notExportableReturn(): List<String> = listOf("1", "2")<|endoftext|>
import org.jetbrains.kotlin.fir.analysis.diagnostics.jvm.FirJvmErrors import org.jetbrains.kotlin.fir.declarations.isJavaOrEnhancement import org.jetbrains.kotlin.fir.expressions.FirFunctionCall import org.jetbrains.kotlin.fir.expressions.resolvedArgumentMapping
import org.jetbrains.kotlin.fir.originalOrSelf import org.jetbrains.kotlin.fir.references.toResolvedCallableSymbol import org.jetbrains.kotlin.fir.resolve.substitution.substitutorByMap import org.jetbrains.kotlin.fir.symbols.impl.FirFunctionSymbol<|endoftext|>
open class X(var s: ()-> Unit) open class C(val f: X) { fun test() { f.s() } } class B(var x: Int) { fun foo() { object : C(object: X({x = 3}) {}) {}.test() } } fun box() : String { val b = B(1)
b.foo() return if (b.x != 3) "fail: b.x = ${b.x}" else "OK" }<|endoftext|>
if (z != null) <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int? & kotlin.Int")!>z<!>.propT if (z != null) <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int? & kotlin.Int")!>z<!>.propAny
if (z != null) <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int? & kotlin.Int")!>z<!>.propNullableT if (z != null) <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int? & kotlin.Int")!>z<!>.propNullableAny<|endoftext|>
import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.util.getCall import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.resolve.calls.util.getCalleeExpressionIfAny import org.jetbrains.kotlin.resolve.calls.util.createLookupLocation<|endoftext|>
* Ensures that this value is not greater than the specified [maximumValue]. * * @return this value if it's less than or equal to the [maximumValue] or the [maximumValue] otherwise. * * @sample samples.comparisons.ComparableOps.coerceAtMostUnsigned */ @SinceKotlin("1.5") @WasExperimental(ExperimentalUnsignedTypes::class)
public fun UByte.coerceAtMost(maximumValue: UByte): UByte { return if (this > maximumValue) maximumValue else this } /** * Ensures that this value is not greater than the specified [maximumValue]. * * @return this value if it's less than or equal to the [maximumValue] or the [maximumValue] otherwise. *<|endoftext|>
function.isJavaOrEnhancement -> IrDeclarationOrigin.IR_EXTERNAL_JAVA_DECLARATION_STUB else -> function.computeIrOrigin( predefinedOrigin, parentOrigin = (irParent as? IrDeclaration)?.origin, fakeOverrideOwnerLookupTag ) } if (irParent.isExternalParent()) {
require(function is FirSimpleFunction) if (!allowLazyDeclarationsCreation) { error("Lazy functions should be processed in Fir2IrDeclarationStorage") } @OptIn(UnsafeDuringIrConstructionAPI::class) if (symbol.isBound) return symbol.owner return lazyDeclarationsGenerator.createIrLazyFunction(function, symbol, irParent, updatedOrigin)<|endoftext|>
@kotlin.internal.IntrinsicConstEvaluation public operator fun compareTo(other: Int): Int /** * Compares this value with the specified value for order. * Returns zero if this value is equal to the specified other value, a negative number if it's less than other, * or a positive number if it's greater than other. */
@kotlin.internal.IntrinsicConstEvaluation public operator fun compareTo(other: Long): Int /** * Compares this value with the specified value for order. * Returns zero if this value is equal to the specified other value, a negative number if it's less than other, * or a positive number if it's greater than other. */<|endoftext|>
} else { /* x < 0 */ if (hy >= 0 || hx > hy || ((hx == hy) && (lx > ly))) {/* x < y, x -= ulp */ if (lx == 0U) hx -= 1 lx -= 1U } else { /* x > y, x += ulp */ lx += 1U
if (lx == 0U) hx += 1 } } hy = hx and 0x7ff00000 if (hy >= 0x7ff00000) return x + x /* overflow */ if (hy < 0x00100000) { /* underflow */ y = x * x if (y != x) { /* raise underflow flag */<|endoftext|>
putObjectOrClassInstanceOnStack(parcelerType, parcelerAsmType, typeMapper, v) // -> parcel, parceler v.swap() // -> parceler, parcel v.invokeinterface(PARCELER_TYPE.internalName, "create", "(Landroid/os/Parcel;)Ljava/lang/Object;") // -> obj unboxTypeIfNeeded(v)
v.castIfNeeded(asmType) } private fun handleSpecialBoxingCases(v: InstructionAdapter): Type? { assert(asmType.sort != Type.METHOD) if (asmType.sort == Type.OBJECT || asmType.sort == Type.ARRAY) { return null } if (asmType == Type.VOID_TYPE) {<|endoftext|>
val countBefore = nodes.size visitor.accept(this) val countAfter = nodes.size if (countAfter == countBefore) break } return nodes } fun List<CoroutineBlock>.replaceCoroutineFlowStatements(context: CoroutineTransformationContext) { val blockIndexes = withIndex().associate { (index, block) -> Pair(block, index) }
val blockReplacementVisitor = object : JsVisitorWithContextImpl() { override fun endVisit(x: JsDebugger, ctx: JsContext<in JsStatement>) { val target = x.targetBlock if (target != null) { val lhs = JsNameRef(context.metadata.stateName, JsAstUtils.stateMachineReceiver())<|endoftext|>
value_2 > 1000 -> 1 value_2 > 100 -> 2 else -> 3 } -> {} when (value_3) { true -> 1 false -> 2 null -> 3 } -> {} when (value_3!!) { true -> 1 false -> 2 } -> {} } } // TESTCASE NUMBER: 6
fun case_6(value_1: Int, value_2: Int) { when (value_1) { if (value_2 > 1000) 1 else 2 -> {} if (value_2 < 100) 1 else if (value_2 < 10) 2 else 3 -> {} } } // TESTCASE NUMBER: 7<|endoftext|>
return block() } inline fun <T> directRun(block: () -> T): T { contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) } return block() } fun bad(): String { val x: String? = null x?.myRun { return "" }
<!NO_RETURN_IN_FUNCTION_WITH_BLOCK_BODY!>}<!> fun ok(): String { val x: String? = null x?.run { return "non-null" } ?: return "null" } fun ok2(): String { directRun { return "nonNull" } }<|endoftext|>
} } */ override fun atomicfuArrayLoopBody(atomicArrayClass: IrClassSymbol, valueType: IrType, valueParameters: List<IrValueParameter>) = irBlockBody { val atomicHandler = valueParameters[0] val index = valueParameters[1] val action = valueParameters[2] +irWhile().apply { condition = irTrue()
body = irBlock { val cur = createTmpVariable( atomicGetArrayElement(atomicArrayClass, valueType, irGet(atomicHandler), irGet(index)), "atomicfu\$cur", false ) +irCall(atomicSymbols.invoke1Symbol).apply { dispatchReceiver = irGet(action) putValueArgument(0, irGet(cur))<|endoftext|>
renderSeparated(contextReceivers, visitor) print(")") if (lineBreakAfterContextReceivers) { printer.newLine() } else { print(" ") } } private fun List<FirTypeParameterRef>.renderTypeParameters() { if (isNotEmpty()) { print("<")
renderSeparated(this, visitor) print(">") } } private fun List<FirTypeProjection>.renderTypeArguments() { if (isNotEmpty()) { print("<") renderSeparated(this, visitor) print(">") } } private fun print(s: Any) {<|endoftext|>
package samples.misc import samples.* class Builtins { @Sample fun inc() { val a = 3 val b = a.inc() assertPrints(a, "3") assertPrints(b, "4") var x = 3 val y = x++ assertPrints(x, "4")
assertPrints(y, "3") val z = ++x assertPrints(x, "5") assertPrints(z, "5") } @Sample fun dec() { val a = 3 val b = a.dec() assertPrints(a, "3") assertPrints(b, "2") var x = 3<|endoftext|>
public external interface OverconstrainedErrorEventInit : EventInit { var error: dynamic /* = null */ get() = definedExternally set(value) = definedExternally } @Suppress("INVISIBLE_REFERENCE", "INVISIBLE_MEMBER") @kotlin.internal.InlineOnly
public inline fun OverconstrainedErrorEventInit(error: dynamic = null, bubbles: Boolean? = false, cancelable: Boolean? = false, composed: Boolean? = false): OverconstrainedErrorEventInit { val o = js("({})") o["error"] = error o["bubbles"] = bubbles o["cancelable"] = cancelable o["composed"] = composed return o<|endoftext|>
"&Ccedil;" to 199, "&Ccedil" to 199, "&ccedil;" to 231, "&ccedil" to 231, "&Ccirc;" to 264, "&ccirc;" to 265, "&Cconint;" to 8752, "&ccups;" to 10828, "&ccupssm;" to 10832,
"&Cdot;" to 266, "&cdot;" to 267, "&cedil;" to 184, "&cedil" to 184, "&Cedilla;" to 184, "&cemptyv;" to 10674, "&cent;" to 162, "&cent" to 162, "&centerdot;" to 183,<|endoftext|>
expectFailure(linkage("Constructor 'Foo.<init>' can not be called: No constructor found for symbol '/ClassToEnum.Foo.<init>'")) { getClassToEnumFooAsAny() }
expectFailure(linkage("Constructor 'Foo.<init>' can not be called: No constructor found for symbol '/ClassToEnum.Foo.<init>'")) { getClassToEnumFooAsAnyInline() }<|endoftext|>
commonThrow(Exception("OK")) suspendWithValue("456") } catch (e: RuntimeException) { suspendWithValue("fail") throw RuntimeException("fail 7") } } builder { try { suspendWithValue("123") commonThrow(Exception("M3")) suspendWithValue("456")
} catch (e: RuntimeException) { suspendWithValue("fail") throw RuntimeException("fail 8") } catch (e: Exception) { if (e.message != "M3") throw Exception("fail 9: ${e.message}") wasCalled = true suspendWithValue("OK") } } return globalResult }<|endoftext|>
const val lengthPropName = <!CONST_VAL_WITH_NON_CONST_INITIALIZER!>String::length.name<!> const val errorAccess = <!CONST_VAL_WITH_NON_CONST_INITIALIZER!>SomeClassWithName(1)::property.name<!>
const val errorPlus = <!CONST_VAL_WITH_NON_CONST_INITIALIZER!>"" + SomeClassWithName(1)::property<!><|endoftext|>
val actual = getResult() assertEquals(expected, actual, initCode) } fun box(): String { test(EXPECTED, "kotlin.kotlin.io.NodeJsOutput(outputStream)") { buffer } test(EXPECTED_NEWLINE_FOR_EACH, "kotlin.kotlin.io.OutputToConsoleLog()") {
buffer } test(EXPECTED, "kotlin.kotlin.io.BufferedOutput()") { eval("kotlin.kotlin.io.output.buffer") as String } test(EXPECTED, "kotlin.kotlin.io.BufferedOutputToConsoleLog()") { buffer } return "OK" }<|endoftext|>
) : KtAbstractFirDiagnostic<KtExpression>(firDiagnostic, token), KtFirDiagnostic.NoCompanionObject internal class ExpressionExpectedPackageFoundImpl( firDiagnostic: KtPsiDiagnostic, token: KtLifetimeToken,
) : KtAbstractFirDiagnostic<KtExpression>(firDiagnostic, token), KtFirDiagnostic.ExpressionExpectedPackageFound internal class ErrorInContractDescriptionImpl( override val reason: String, firDiagnostic: KtPsiDiagnostic, token: KtLifetimeToken,<|endoftext|>
/** * Creates a modification tracker which is incremented every time libraries in the project are changed. * * @see ModificationTracker */ public abstract fun createLibrariesWideModificationTracker(): ModificationTracker public companion object { public fun getInstance(project: Project): KotlinModificationTrackerFactory = project.getService(KotlinModificationTrackerFactory::class.java)
} } /** * Creates an **OOBM** tracker which is incremented every time there is an OOB change in some source project module. * * See [KotlinModificationTrackerFactory.createProjectWideOutOfBlockModificationTracker] for the definition of **OOBM**. * @see ModificationTracker */ public fun Project.createProjectWideOutOfBlockModificationTracker(): ModificationTracker =<|endoftext|>
if (r3 != "1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16;") return "FAIL3: $r3" var r4 = builder { var i = 1 result = bar( bar(foo(i++), foo(i++), foo(i++), foo(i++)),
bar(foo(i++), foo(i++), foo(i++), foo(i++)), bar(foo(i++), foo(i++), foo(i++), foo(i++)), bar(foo(i++), foo(i++), foo(i++), foo(i++)) ) }<|endoftext|>
val allConditionsReadsSameValue = !extractedBranches.all { branch -> branch.conditions.all { whenCondition -> (whenCondition.condition.getValueArgument(0) as? IrGetValue)?.symbol == subjectValue } } if (allConditionsReadsSameValue) return false // Check all kinds are the same
for (branch in extractedBranches) { //TODO: Support all primitive types if (!branch.conditions.all { it.const.kind.equals(IrConstKind.Int) }) return false } val intBranches = extractedBranches.map { branch -> @Suppress("UNCHECKED_CAST") branch as ExtractedWhenBranch<Int> }<|endoftext|>
if (<!SENSELESS_COMPARISON!>v != null<!> || <!SENSELESS_COMPARISON!>this.v != null<!>) <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?"), DEBUG_INFO_SMARTCAST!>v<!>.propT
if (<!SENSELESS_COMPARISON!>v != null<!> || <!SENSELESS_COMPARISON!>this.v != null<!>) <!DEBUG_INFO_EXPRESSION_TYPE("kotlin.Int & kotlin.Int?"), DEBUG_INFO_SMARTCAST!>v<!>.propAny<|endoftext|>
open fun visitReceiverParameter(receiverParameter: FirReceiverParameter, data: D): R = visitElement(receiverParameter, data) open fun visitProperty(property: FirProperty, data: D): R = visitElement(property, data) open fun visitField(field: FirField, data: D): R = visitElement(field, data)
open fun visitEnumEntry(enumEntry: FirEnumEntry, data: D): R = visitElement(enumEntry, data) open fun visitFunctionTypeParameter(functionTypeParameter: FirFunctionTypeParameter, data: D): R = visitElement(functionTypeParameter, data) open fun visitClassLikeDeclaration(classLikeDeclaration: FirClassLikeDeclaration, data: D): R =<|endoftext|>
import org.jetbrains.kotlin.backend.jvm.JvmLoweredStatementOrigin import org.jetbrains.kotlin.backend.jvm.ir.defaultValue import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.ir.expressions.IrExpression
import org.jetbrains.kotlin.ir.expressions.IrFunctionReference import org.jetbrains.kotlin.ir.types.IrType @PhaseDescription( name = "Tailrec", description = "Handle tailrec calls" ) internal class JvmTailrecLowering(context: JvmBackendContext) : TailrecLowering(context) {<|endoftext|>
// MODULE: base // FILE: A.kt // VERSION: 1 open class X // FILE: B.kt // VERSION: 2 open class X { open fun foo(): String = "new member" } // MODULE: child(base) // FILE: C.kt class Y: X() // MODULE: lib(child) // FILE: D.kt
// VERSION: 1 fun qux(): String = "no foo() exists in ${Y()}" // FILE: E.kt // VERSION: 2 fun qux(): String = Y().foo() // MODULE: mainLib(lib) // FILE: mainLib.kt fun lib(): String = when { qux() != "new member" -> "fail 1" else -> "OK"<|endoftext|>
assertEquals("1.2.3-m2", StringAnonymizationPolicy.ComponentVersionAnonymizer().anonymize("1.2.3.M2")) assertEquals("1.2.3-rc", StringAnonymizationPolicy.ComponentVersionAnonymizer().anonymize("1.2.3-RC"))
assertEquals("1.2.3-rc5", StringAnonymizationPolicy.ComponentVersionAnonymizer().anonymize("1.2.3-RC5")) assertEquals("1.2.3", StringAnonymizationPolicy.ComponentVersionAnonymizer().anonymize("1.2.3.unknown suffix"))<|endoftext|>
import org.jetbrains.kotlin.analysis.api.components.buildClassType import org.jetbrains.kotlin.analysis.api.symbols.KtFunctionSymbol import org.jetbrains.kotlin.analysis.api.symbols.markers.isPrivateOrPrivateToThis
import org.jetbrains.kotlin.analysis.api.symbols.pointers.KtSymbolPointer import org.jetbrains.kotlin.analysis.api.types.KtTypeNullability import org.jetbrains.kotlin.asJava.classes.lazyPub<|endoftext|>
buildErrorType(typeRef, resolvedType, diagnostic, scopeClassDeclaration) } else -> { buildResolvedTypeRef { source = typeRef.source type = resolvedType annotations += typeRef.annotations delegatedTypeRef = typeRef } } } } private fun buildErrorType( typeRef: FirTypeRef,
resolvedType: ConeKotlinType, diagnostic: ConeDiagnostic, scopeClassDeclaration: ScopeClassDeclaration, ): FirErrorTypeRef { return buildErrorTypeRef { val typeRefSourceKind = typeRef.source?.kind val diagnosticSource = (diagnostic as? ConeUnexpectedTypeArgumentsError)?.source<|endoftext|>
fun finalFun(): String = "RemovedAbstractClass.finalFun" abstract val abstractVal: String open val openVal: String get() = "RemovedAbstractClass.openVal" val finalVal: String get() = "RemovedAbstractClass.finalVal" } open class RemovedOpenClass { open fun openFun(): String = "RemovedOpenClass.openFun"
fun finalFun(): String = "RemovedOpenClass.finalFun" open val openVal: String get() = "RemovedOpenClass.openVal" val finalVal: String get() = "RemovedOpenClass.finalVal" } abstract class AbstractClassWithChangedConstructorSignature(name: String) { val greeting = "Hello, $name!" }<|endoftext|>
val thisSize = size val arraySize = elements.size val result = java.util.Arrays.copyOf(this, thisSize + arraySize) System.arraycopy(elements, 0, result, thisSize, arraySize) return result } /** * Returns an array containing all elements of the original array and then all elements of the given [elements] array. */
public actual operator fun ShortArray.plus(elements: ShortArray): ShortArray { val thisSize = size val arraySize = elements.size val result = java.util.Arrays.copyOf(this, thisSize + arraySize) System.arraycopy(elements, 0, result, thisSize, arraySize) return result } /**<|endoftext|>
import org.jetbrains.kotlin.types.expressions.OperatorConventions import org.jetbrains.kotlin.util.OperatorNameConventions import org.jetbrains.kotlin.utils.addToStdlib.runIf class LightTreeRawFirExpressionBuilder( session: FirSession, tree: FlyweightCapableTreeStructure<LighterASTNode>,
private val declarationBuilder: LightTreeRawFirDeclarationBuilder, context: Context<LighterASTNode> = Context(), ) : AbstractLightTreeRawFirBuilder(session, tree, context) { inline fun <reified R : FirExpression> getAsFirExpression( expression: LighterASTNode?, errorReason: String = "",<|endoftext|>
override val receiverParameter: KtReceiverParameterSymbol? get() = withValidityAssertion { descriptor.extensionReceiverParameter?.toKtReceiverParameterSymbol(analysisContext) } override fun createPointer(): KtSymbolPointer<KtPropertyGetterSymbol> = withValidityAssertion {
KtPsiBasedSymbolPointer.createForSymbolFromSource<KtPropertyGetterSymbol>(this) ?: KtFe10NeverRestoringSymbolPointer() } override fun equals(other: Any?): Boolean = isEqualTo(other) override fun hashCode(): Int = calculateHashCode() }<|endoftext|>
override fun visitSpreadElement(spread: IrSpreadElement, data: ScriptToClassTransformerContext): IrSpreadElement = spread.apply { transformChildren(this@ScriptToClassTransformer, data) } override fun visitExpression(expression: IrExpression, data: ScriptToClassTransformerContext): IrExpression = expression.apply { type = type.remapType()
transformChildren(this@ScriptToClassTransformer, data) } override fun visitClassReference(expression: IrClassReference, data: ScriptToClassTransformerContext): IrClassReference = expression.apply { type = type.remapType() classType = classType.remapType() transformChildren(this@ScriptToClassTransformer, data) }<|endoftext|>
/* @sample samples.contracts.callsInPlaceAtMostOnceContract * @sample samples.contracts.callsInPlaceAtLeastOnceContract * @sample samples.contracts.callsInPlaceExactlyOnceContract * @sample samples.contracts.callsInPlaceUnknownContract */
@ContractsDsl public fun <R> callsInPlace(lambda: Function<R>, kind: InvocationKind = InvocationKind.UNKNOWN): CallsInPlace } /** * Specifies how many times a function invokes its function parameter in place. * * See [ContractBuilder.callsInPlace] for the details of the call-in-place function contract. */ @ContractsDsl<|endoftext|>
// !JVM_DEFAULT_MODE: disable // FILE: main.kt interface Derived : Foo { override fun toOverride(): String { return "O" } } class DerivedClass : Derived fun box(): String { checkMethodExists(DerivedClass::class.java, "toOverride")
checkNoMethod(DerivedClass::class.java, "nonOverride") val value = DerivedClass() return value.toOverride() + value.nonOverride() } fun checkNoMethod(clazz: Class<*>, name: String, vararg parameterTypes: Class<*>) { try { clazz.getDeclaredMethod(name, *parameterTypes) }<|endoftext|>
import org.jetbrains.kotlin.incremental.storage.* import org.jetbrains.kotlin.inline.InlineFunction import org.jetbrains.kotlin.inline.InlineFunctionOrAccessor import org.jetbrains.kotlin.inline.InlinePropertyAccessor import org.jetbrains.kotlin.load.kotlin.header.KotlinClassHeader
import org.jetbrains.kotlin.load.kotlin.incremental.components.IncrementalCache import org.jetbrains.kotlin.load.kotlin.incremental.components.JvmPackagePartProto import org.jetbrains.kotlin.metadata.ProtoBuf<|endoftext|>
suspend operator fun invoke(): IC = suspendMe() } fun box(): String { builder { val getResult = GetResult() getResult() } c?.resumeWithException(IllegalStateException("OK")) if (result != "OK") return "FAIL 1 $result" result = "FAIL 2" builder { val getResult = GetResult()
getResult.invoke() } c?.resumeWithException(IllegalStateException("OK")) if (result != "OK") return "FAIL 2 $result" result = "FAIL 3" builder { GetResult()() } c?.resumeWithException(IllegalStateException("OK"))<|endoftext|>
) } fun runJSCompiler(args: K2JSCompilerArguments, env: JpsCompilerEnvironment): ExitCode? { val argsArray = ArgumentUtils.convertArgumentsToStringList(args).toTypedArray() val stream = ByteArrayOutputStream() val out = PrintStream(stream)
val exitCode = CompilerRunnerUtil.invokeExecMethod(K2JSCompiler::class.java.name, argsArray, env, out) val reader = BufferedReader(StringReader(stream.toString())) CompilerOutputParser.parseCompilerMessagesFromReader(env.messageCollector, reader, env.outputItemsCollector) return exitCode as? ExitCode }<|endoftext|>
private val allowErrorTypeInAnnotations: Boolean, ) { protected abstract fun extractAnnotationOffsets(annotationDescriptor: AnnotationDescriptor): Pair<Int, Int> protected abstract fun extractAnnotationParameterOffsets(annotationDescriptor: AnnotationDescriptor, argumentName: Name): Pair<Int, Int>
private fun KotlinType.toIrType() = typeTranslator.translateType(this) fun generateConstantValueAsExpression( startOffset: Int, endOffset: Int, constantValue: ConstantValue<*>, ): IrExpression = // Assertion is safe here because annotation calls and class literals are not allowed in constant initializers<|endoftext|>
) val propertiesOrderFromExtension = classProto.getPropertyOrderFromMetadataExtension() addDeclarations( classProto.propertiesInOrder(versionRequirements, propertiesOrderFromExtension).map { propertyProto -> classDeserializer.loadProperty(propertyProto, classProto, symbol).also { property -> if (propertyProto.name in propertiesOrderFromExtension) {
property.registeredInSerializationPluginMetadataExtension = true } } } ) addDeclarations( classProto.constructorList.map { classDeserializer.loadConstructor(it, classProto, this) } ) addDeclarations( classProto.nestedClassNameList.mapNotNull { nestedNameId -><|endoftext|>
return f.call(value) } fun <T> IC.extensionValue(): T = value as T fun <T> normalValue(ic: IC): T = ic.value as T OPTIONAL_JVM_INLINE_ANNOTATION value class IC(val value: String) { fun <T> dispatchValue(): T = value as T } fun box(): String {
var res = underlying<String>(IC("O")) + "K" if (res != "OK") return "FAIL 1: $res" res = extension<String>(IC("O")) + "K" if (res != "OK") return "FAIL 2: $res" res = dispatch<String>(IC("O")) + "K"<|endoftext|>
<!INSTANCE_ACCESS_BEFORE_SUPER_CALL!>b<!>() ) class Nested { companion object { const val CONST = 2 } } inner class Inner interface Interface { companion object { const val CONST = 3 } } val a = 1
fun b() = 2 companion object { const val CONST = 1 fun foo(): Nested = null!! } }<|endoftext|>
): IrProperty = convertCatching(property) { val origin = when { !predefinedOrigin.isExternal && property.isStatic && property.name in Fir2IrDeclarationStorage.ENUM_SYNTHETIC_NAMES -> IrDeclarationOrigin.ENUM_CLASS_SPECIAL_MEMBER else -> property.computeIrOrigin( predefinedOrigin,
parentOrigin = (irParent as? IrDeclaration)?.origin, fakeOverrideOwnerLookupTag ) } // See similar comments in createIrFunction above val parentIsExternal = irParent.isExternalParent() if (parentIsExternal) { if (!allowLazyDeclarationsCreation) { error("Lazy properties should be processed in Fir2IrDeclarationStorage") }<|endoftext|>
public fun getVisibilityModifier(analysisSession: KtAnalysisSession, symbol: KtSymbolWithVisibility): KtModifierKeywordToken? public fun onlyIf( condition: KtAnalysisSession.(symbol: KtSymbolWithVisibility) -> Boolean ): KtRendererVisibilityModifierProvider { val self = this
return object : KtRendererVisibilityModifierProvider { override fun getVisibilityModifier(analysisSession: KtAnalysisSession, symbol: KtSymbolWithVisibility): KtModifierKeywordToken? = if (condition(analysisSession, symbol)) self.getVisibilityModifier(analysisSession, symbol) else null } }<|endoftext|>
"ClassList.copyManual" to BenchmarkEntryWithInit.create(::ClassListBenchmark, { copyManual() }), "ClassList.filterAndCount" to BenchmarkEntryWithInit.create(::ClassListBenchmark, { filterAndCount() }),
"ClassList.filterAndCountWithLambda" to BenchmarkEntryWithInit.create(::ClassListBenchmark, { filterAndCountWithLambda() }), "ClassList.filterWithLambda" to BenchmarkEntryWithInit.create(::ClassListBenchmark, { filterWithLambda() }),<|endoftext|>
protected abstract fun getMemberScope(typeSubstitution: TypeSubstitution, kotlinTypeRefiner: KotlinTypeRefiner): MemberScope protected abstract fun getMemberScope(typeArguments: List<TypeProjection>, kotlinTypeRefiner: KotlinTypeRefiner): MemberScope companion object { internal fun ClassDescriptor.getRefinedUnsubstitutedMemberScopeIfPossible(
kotlinTypeRefiner: KotlinTypeRefiner ): MemberScope = (this as? ModuleAwareClassDescriptor)?.getUnsubstitutedMemberScope(kotlinTypeRefiner) ?: this.unsubstitutedMemberScope internal fun ClassDescriptor.getRefinedMemberScopeIfPossible( typeSubstitution: TypeSubstitution,<|endoftext|>
import kotlinx.atomicfu.* import kotlin.test.* class LoopTest { private val a = atomic(0) private val a1 = atomic(1) private val b = atomic(true) private val l = atomic(5000000000) private val r = atomic<A>(A("aaaa")) private val rs = atomic<String>("bbbb")
class A(val s: String) fun atomicfuIntLoopTest() { a.loop { value -> if (a.compareAndSet(value, 777)) { assertEquals(777, a.value) return } } } fun atomicfuBooleanLoopTest() { b.loop { value -> assertTrue(value)<|endoftext|>
* The inserted characters go in the same order as in the [value] character sequence, starting at [index]. * * @param index the position in this string builder to insert at. * @param value the character sequence from which characters are inserted. If [value] is `null`, then the four characters `"null"` are inserted. *
* @throws IndexOutOfBoundsException if [index] is less than zero or greater than the length of this string builder. */ @SinceKotlin("1.4") public fun insert(index: Int, value: CharSequence?): StringBuilder /** * Inserts the string representation of the specified object [value] into this string builder at the specified [index] and returns this instance.<|endoftext|>
@TypedIntrinsic(IntrinsicType.SIGNED_DIV) public external operator fun div(other: Float): Float /** Divides this value by the other value. */ @kotlin.internal.IntrinsicConstEvaluation public inline operator fun div(other: Double): Double = this.toDouble() / other /**
* Calculates the remainder of truncating division of this value (dividend) by the other value (divisor). * * The result is either zero or has the same sign as the _dividend_ and has the absolute value less than the absolute value of the divisor. */ @SinceKotlin("1.1") @kotlin.internal.IntrinsicConstEvaluation<|endoftext|>
// FILE: Calendar.java public class Calendar { public void setTimeInMillis(long millis) {} public long getTimeInMillis() { return 1; } } // FILE: 1.kt class A var A.timeInMillis: String get() = "" set(v) {} fun a(c: Calendar) { A().apply { c.apply {
timeInMillis = 5 // synthesized variable for get|setTimeInMillis timeInMillis = <!ASSIGNMENT_TYPE_MISMATCH!>""<!> } timeInMillis = "" } }<|endoftext|>
storage.remove(key) changesCollector.collectProtoChanges(oldValue.toProtoData(), newData = null) } operator fun get(className: JvmClassName): SerializedJavaClass? = storage[className.internalName] operator fun contains(className: JvmClassName): Boolean = className.internalName in storage
override fun dumpValue(value: SerializedJavaClass): String = java.lang.Long.toHexString(value.proto.toByteArray().md5()) } // todo: reuse code with InlineFunctionsMap? private inner class ConstantsMap( storageFile: File, icContext: IncrementalCompilationContext, ) :<|endoftext|>
emit(1) emit(null) val x = get() if (x == null) { x.equals("") } "" } val ret402 = build { emit(1) emit(null) val x = get() if (x == null) {
x.<!NONE_APPLICABLE!>toString<!>("") } "" } val ret403 = build { emit(1) emit(null) val x = get() if (x == null) { x.test() } "" } val ret404 = build { emit(1)<|endoftext|>
private fun registerScriptExtensions(session: LLFirSession, file: KtFile) { FirSessionConfigurator(session).apply { val hostConfiguration = ScriptingHostConfiguration(defaultJvmScriptingHostConfiguration) {} val scriptDefinition = file.findScriptDefinition() ?: errorWithAttachment("Cannot load script definition") { withVirtualFileEntry("file", file.virtualFile) }
val compilerArguments = makeScriptCompilerArguments(scriptDefinition.compilerOptions.toList()) val commandLineProcessors = listOf(AssignmentCommandLineProcessor()) val compilerConfiguration = CompilerConfiguration() processCompilerPluginsOptions( compilerConfiguration, compilerArguments.pluginOptions?.asIterable() ?: emptyList(), commandLineProcessors )<|endoftext|>
import org.jetbrains.kotlin.analysis.api.fir.KtFirAnalysisSession import org.jetbrains.kotlin.analysis.api.fir.annotations.KtFirAnnotationListForDeclaration import org.jetbrains.kotlin.analysis.api.fir.contracts.coneEffectDeclarationToAnalysisApi
import org.jetbrains.kotlin.analysis.api.fir.findPsi import org.jetbrains.kotlin.analysis.api.fir.symbols.pointers.* import org.jetbrains.kotlin.analysis.api.fir.symbols.pointers.FirCallableSignature<|endoftext|>
import org.jetbrains.kotlin.lexer.KtTokens.* import java.util.* enum class Compatibility { // modifier pair is compatible: ok (default) COMPATIBLE, // second is redundant to first: warning REDUNDANT, // first is redundant to second: warning REVERSE_REDUNDANT, // error
REPEATED, // pair is deprecated, will become incompatible: warning DEPRECATED, // pair is incompatible: error INCOMPATIBLE, // same but only for functions / properties: error COMPATIBLE_FOR_CLASSES_ONLY } val compatibilityTypeMap = hashMapOf<Pair<KtKeywordToken, KtKeywordToken>, Compatibility>()<|endoftext|>
@Test fun testIfElseWithCallsInBranch(): Unit = controlFlow( """ @NonRestartableComposable @Composable fun Example(x: Int) { // Composable calls in the result blocks, so we can determine static number of // groups executed. This means we put a group around the "then" and the // "else" blocks
if (x > 0) { A(a) } else { A(b) } } """ ) @Test fun testIfWithCallInCondition(): Unit = controlFlow( """ @NonRestartableComposable @Composable fun Example(x: Int) {<|endoftext|>
@file:OptIn(UnsafeDuringIrConstructionAPI::class) package androidx.compose.compiler.plugins.kotlin.lower import androidx.compose.compiler.plugins.kotlin.ComposeFqNames import androidx.compose.compiler.plugins.kotlin.lower.decoys.DecoyFqNames
import org.jetbrains.kotlin.backend.common.FileLoweringPass import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext import org.jetbrains.kotlin.ir.declarations.IrFile import org.jetbrains.kotlin.ir.declarations.IrModuleFragment<|endoftext|>
to.makePerFileCache = from.makePerFileCache to.manifestFile = from.manifestFile to.manifestNativeTargets = from.manifestNativeTargets?.copyOf() to.memoryModel = from.memoryModel to.moduleName = from.moduleName to.nativeLibraries = from.nativeLibraries?.copyOf()
to.noObjcGenerics = from.noObjcGenerics to.nodefaultlibs = from.nodefaultlibs to.noendorsedlibs = from.noendorsedlibs to.nomain = from.nomain to.nopack = from.nopack to.nostdlib = from.nostdlib<|endoftext|>
enabledTargets(platformManager).associateBy(keySelector = { it.visibleName }, valueTransform = { project.tasks.register("${it}${name}Tests") { description = "Runs all $name tests for $it" group = VERIFICATION_TASK_GROUP } }) } /**
* A group of source files that will be compiled together. * * There are 3 well known source sets: `main`, `testFixtures` and `test`. */ abstract class SourceSet @Inject constructor( private val owner: CompileToBitcodeExtension, private val module: Module, private val name: String, private val _target: TargetWithSanitizer,<|endoftext|>
open class A<T> { open fun foo(t: T, vararg xs: Int) = "A" } open class B : A<String>() class Z : B() { override fun foo(t: String, vararg xs: Int) = "Z" } fun box(): String { val z = Z() val b: B = z
val a: A<String> = z return when { z.foo("") != "Z" -> "Fail #1" b.foo("") != "Z" -> "Fail #2" a.foo("") != "Z" -> "Fail #3" else -> "OK" } }<|endoftext|>
get() = COMPOUND_CONSTRAINT_POSITION val positions: Collection<ConstraintPosition> = positions.flatMap { (it as? CompoundConstraintPosition)?.positions ?: listOf(it) }.toSet() override fun isStrong() = positions.any { it.isStrong() }
override fun toString() = "$kind(${positions.joinToString()})" } fun ConstraintPosition.derivedFrom(kind: ConstraintPositionKind): Boolean { return if (this !is CompoundConstraintPosition) this.kind == kind else positions.any { it.kind == kind } } class ValidityConstraintForConstituentType(<|endoftext|>
import org.jetbrains.kotlin.ir.symbols.IrClassSymbol import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.resolve.descriptorUtil.isEffectivelyExternal import org.jetbrains.kotlin.resolve.isValueClass
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedClassDescriptor import org.jetbrains.kotlin.types.KotlinType val ParameterDescriptor.indexOrMinusOne: Int get() = if (this is ValueParameterDescriptor) index else -1<|endoftext|>
import org.jetbrains.kotlin.metadata.deserialization.type import org.jetbrains.kotlin.metadata.deserialization.receiverType class ClsContractBuilder(private val c: ClsStubBuilderContext, private val typeStubBuilder: TypeClsStubBuilder) :
ProtoBufContractDeserializer<KotlinTypeBean, Nothing?, ProtoBuf.Function>() { fun loadContract(proto: ProtoBuf.Function): List<KtEffectDeclaration<KotlinTypeBean, Nothing?>>? { return proto.contract.effectList.map { loadPossiblyConditionalEffect(it, proto) ?: return null } }<|endoftext|>
else -> error("Unknown subclass of IrBody: $this") } val IrClass.defaultType: IrSimpleType get() = this.thisReceiver!!.type as IrSimpleType fun IrClass.isSubclassOf(ancestor: IrClass): Boolean { val alreadyVisited = mutableSetOf<IrClass>()
fun IrClass.hasAncestorInSuperTypes(): Boolean = when { this === ancestor -> true this in alreadyVisited -> false else -> { alreadyVisited.add(this) superTypes.mapNotNull { ((it as? IrSimpleType)?.classifier as? IrClassSymbol)?.owner }.any { it.hasAncestorInSuperTypes() } } }<|endoftext|>
returns("T?") body { """ var index = lastIndex if (index < 0) return null var accumulator = get(index--) while (index >= 0) { accumulator = operation(index, get(index), accumulator) --index } return accumulator """ } }
val f_reduceRightIndexedOrNullSuper = fn("reduceRightIndexedOrNull(operation: (index: Int, T, acc: S) -> S)") { include(Lists, ArraysOfObjects) } builder { since("1.4") inline() doc { reduceDoc("reduceRightIndexedOrNull") }<|endoftext|>
assertEquals(-1, "".indexOf("a", -3)) assertEquals(0, "".indexOf("", 0)) } @Test fun indexOfChar() { assertEquals(-1, "bcedef".indexOf('e', 5)) assertEquals(-1, "".indexOf('a', -3))
assertEquals(-1, "".indexOf('a', 10)) assertEquals(-1, "".indexOf(0.toChar(), -3)) assertEquals(-1, "".indexOf(0.toChar(), 10)) } @Test fun equalsIgnoreCase() { assertTrue("hello".equals("HElLo", true))<|endoftext|>
val file = File(this).absoluteFile var parent = file.parent config.configuration.get(KonanConfigKeys.DEBUG_PREFIX_MAP)?.let { debugPrefixMap -> for ((key, value) in debugPrefixMap) { if (parent.startsWith(key)) { parent = value + parent.removePrefix(key) } }
} return FileAndFolder(file.name, parent) } internal fun alignTo(value: Long, align: Long): Long = (value + align - 1) / align * align internal fun setupBridgeDebugInfo(generationState: NativeGenerationState, function: LlvmCallable): LocationInfo? { if (!generationState.shouldContainLocationDebugInfo()) { return null }<|endoftext|>
@OverloadResolutionByLambdaReturnType @kotlin.internal.InlineOnly public inline fun FloatArray.minOfOrNull(selector: (Float) -> Double): Double? { if (isEmpty()) return null var minValue = selector(this[0]) for (i in 1..lastIndex) { val v = selector(this[i])
minValue = minOf(minValue, v) } return minValue } /** * Returns the smallest value among all values produced by [selector] function * applied to each element in the array or `null` if there are no elements. * * If any of values produced by [selector] function is `NaN`, the returned result is `NaN`. */<|endoftext|>
fun UnwrappedType.anySuperTypeConstructor(predicate: (TypeConstructor) -> Boolean) = createClassicTypeCheckerState(isErrorTypeEqualsToAnything = false).anySupertype(lowerIfFlexible(), { require(it is SimpleType) predicate(it.constructor) }, { SupertypesPolicy.LowerIfFlexible }) /**
* ClassType means that type constructor for this type is type for real class or interface */ val SimpleType.isClassType: Boolean get() = constructor.declarationDescriptor is ClassDescriptor /** * SingleClassifierType is one of the following types: * - classType * - type for type parameter * - captured type *<|endoftext|>
val resolvedClassTypeRef = getReferencedType().toFirResolvedTypeRef(session, javaTypeParameterStack, source) val resolvedTypeRef = buildResolvedTypeRef { type = StandardClassIds.KClass.constructClassLikeType(arrayOf(resolvedClassTypeRef.type), false) } argumentList = buildUnaryArgumentList( buildClassReferenceExpression {
classTypeRef = resolvedClassTypeRef coneTypeOrNull = resolvedTypeRef.coneType } ) coneTypeOrNull = resolvedTypeRef.coneType } is JavaAnnotationAsAnnotationArgument -> getAnnotation().toFirAnnotationCall(session, source) else -> buildErrorExpression {<|endoftext|>
val mangleChecker = ManglerChecker(JsManglerIr, Ir2DescriptorManglerAdapter(JsManglerDesc)) if (verifySignatures) { moduleFragment.acceptVoid(mangleChecker) } if (configuration.getBoolean(JSConfigurationKeys.FAKE_OVERRIDE_VALIDATOR)) {
val fakeOverrideChecker = FakeOverrideChecker(JsManglerIr, JsManglerDesc) irLinker.modules.forEach { fakeOverrideChecker.check(it) } } if (verifySignatures) { irBuiltIns.knownBuiltins.forEach { it.acceptVoid(mangleChecker) } } return IrModuleInfo(<|endoftext|>
val returnType = if (parseReturnType) parseType(desc, begin = begin + 1, end = desc.length) else null return FunctionJvmDescriptor(result, returnType) } private fun parseType(desc: String, begin: Int, end: Int): Class<*> = when (desc[begin]) {
'L' -> jClass.safeClassLoader.loadClass(desc.substring(begin + 1, end - 1).replace('/', '.')) '[' -> parseType(desc, begin + 1, end).createArrayType() 'V' -> Void.TYPE 'Z' -> Boolean::class.java 'C' -> Char::class.java 'B' -> Byte::class.java<|endoftext|>
array[end - 1] = frontLeadingChar array[front] = endLeadingChar array[front + 1] = endTrailingChar frontLeadingChar = array[front + 2] endTrailingChar = array[end - 2] front++ end-- } !surrogateAtFront && !surrogateAtEnd -> {
// Neither surrogates - exchange only front/end. array[end] = frontLeadingChar array[front] = endTrailingChar frontLeadingChar = frontTrailingChar endTrailingChar = endLeadingChar } surrogateAtFront && !surrogateAtEnd -> { // Surrogate only at the front -<|endoftext|>
takeFnToParameter { <!UNRESOLVED_REFERENCE!>unresolved<!>() } takeFnToParameter { if (true) <!UNRESOLVED_REFERENCE!>unresolved<!>() } <!NEW_INFERENCE_NO_INFORMATION_FOR_PARAMETER!>takeFnToParameter<!> {
if (true) <!UNRESOLVED_REFERENCE!>unresolved<!>() else <!UNRESOLVED_REFERENCE!>unresolved<!>() } takeFnToParameter(fun() = Unit) takeFnToParameter(fun() {}) takeFnToParameter(fun() { return })<|endoftext|>
/** * Builds a new read-only [Map] by populating a [MutableMap] using the given [builderAction] * and returning a read-only map with the same key-value pairs. * * The map passed as a receiver to the [builderAction] is valid only inside that function. * Using it outside of the function produces an unspecified behavior. *
* [capacity] is used to hint the expected number of pairs added in the [builderAction]. * * Entries of the map are iterated in the order they were added by the [builderAction]. * * The returned map is serializable (JVM). * * @throws IllegalArgumentException if the given [capacity] is negative. * * @sample samples.collections.Builders.Maps.buildMapSample */<|endoftext|>
declaration.superTypeRefs.filter { it.isInConstructorCallee() } } } private fun isProhibitedPrivateDeclaration(declaration: FirMemberDeclaration): Boolean { return declaration !is FirConstructor && declaration !is FirPropertyAccessor && Visibilities.isPrivate(declaration.visibility) }
private fun isProhibitedEnumConstructor(declaration: FirMemberDeclaration, lastClass: FirClass?): Boolean { return declaration is FirConstructor && lastClass?.classKind == ClassKind.ENUM_CLASS } private fun isProhibitedDeclarationWithBody(declaration: FirMemberDeclaration): Boolean { return declaration is FirFunction && declaration.hasBody }<|endoftext|>
override fun TypeConstructorMarker.getPrimitiveType(): PrimitiveType? = getClassFqNameUnsafe()?.let(StandardNames.FqNames.fqNameToPrimitiveType::get) override fun TypeConstructorMarker.getPrimitiveArrayType(): PrimitiveType? =
getClassFqNameUnsafe()?.let(StandardNames.FqNames.arrayClassFqNameToPrimitiveType::get) override fun TypeConstructorMarker.isUnderKotlinPackage(): Boolean = getClassFqNameUnsafe()?.startsWith(StandardClassIds.BASE_KOTLIN_PACKAGE.shortName()) == true<|endoftext|>
creatorVar != null -> typeMapper.mapTypeSafe(creatorVar.type, forceBoxed = true) clazz.isParcelize -> Type.getObjectType(asmType.internalName + "\$Creator") else -> null }
creatorAsmType?.let { wrapToNullAwareIfNeeded(type, EfficientParcelableParcelSerializer(asmType, creatorAsmType)) } ?: GenericParcelableParcelSerializer(asmType, context.containerClassType) } else { GenericParcelableParcelSerializer(asmType, context.containerClassType) } }<|endoftext|>
val baseTypeClassId = baseType.fullyExpandedType(session).lookupTag.classId.let { it.readOnlyToMutable() ?: it } if (candidateTypeClassId != baseTypeClassId) return false if (candidateTypeClassId == StandardClassIds.Array) { assert(candidateType.typeArguments.size == 1) {
"Array type with unexpected number of type arguments: $candidateType" } assert(baseType.typeArguments.size == 1) { "Array type with unexpected number of type arguments: $baseType" } return isEqualArrayElementTypeProjections( candidateType.typeArguments.single(), baseType.typeArguments.single(), substitutor )<|endoftext|>
val original = this val superClass = irClass.superClass val classThisSymbol = irClass.thisReceiver!!.symbol return factory.buildConstructor { updateFrom(original) isPrimary = true returnType = original.returnType origin = IrDeclarationOrigin.DEFINED }.also { constructor -> constructor.copyAnnotationsFrom(original)
constructor.copyParameterDeclarationsFrom(original) constructor.parent = irClass if (irClass.isExported(context)) { constructor.annotations = original.annotations.withoutFirst { it.isAnnotation(JsAnnotations.jsExportIgnoreFqn) } } val boxParameter = constructor.boxParameter<|endoftext|>
private fun resolveJvmSourceSets(sourceSet: KotlinSourceSet): Iterable<IdeaKotlinDependency> { return IdeBinaryDependencyResolver( binaryType = IdeaKotlinBinaryDependency.KOTLIN_COMPILE_BINARY_TYPE,
artifactResolutionStrategy = IdeBinaryDependencyResolver.ArtifactResolutionStrategy.PlatformLikeSourceSet( setupPlatformResolutionAttributes = { sourceSet.internal.compilations.filter { it.platformType == KotlinPlatformType.jvm } .map { compilation -> compilation.internal.configurations.compileDependencyConfiguration.attributes }<|endoftext|>
IrDynamicOperator.POSTFIX_DECREMENT -> postfixOperation(JsUnaryOperator.DEC, expression, data) IrDynamicOperator.BINARY_PLUS -> binaryOperation(JsBinaryOperator.ADD, expression, data) IrDynamicOperator.BINARY_MINUS -> binaryOperation(JsBinaryOperator.SUB, expression, data)
IrDynamicOperator.MUL -> binaryOperation(JsBinaryOperator.MUL, expression, data) IrDynamicOperator.DIV -> binaryOperation(JsBinaryOperator.DIV, expression, data) IrDynamicOperator.MOD -> binaryOperation(JsBinaryOperator.MOD, expression, data) IrDynamicOperator.GT -> binaryOperation(JsBinaryOperator.GT, expression, data)<|endoftext|>