text
stringlengths
0
3.9M
package com.android.tools.idea.tests.gui.benchmark import com.android.flags.junit.FlagRule import com.android.sdklib.AndroidVersion import com.android.tools.idea.flags.StudioFlags import com.android.tools.idea.npw.benchmark.BenchmarkModuleType import com.android.tools.idea.tests.gui.framework.GuiTestRule import com.android.tools.idea.tests.gui.framework.fixture.npw.NewModuleWizardFixture import com.android.tools.idea.tests.gui.kotlin.JavaToKotlinConversionTest import com.android.tools.idea.tests.util.WizardUtils import com.android.tools.idea.wizard.template.Language.Java import com.android.tools.idea.wizard.template.Language.Kotlin import com.google.common.truth.Truth.assertThat import com.intellij.testGuiFramework.framework.GuiTestRemoteRunner import org.fest.swing.timing.Wait import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import java.util.concurrent.TimeUnit @RunWith(GuiTestRemoteRunner::class) class AddBenchmarkModuleTest { @get:Rule val guiTest = GuiTestRule().withTimeout(10, TimeUnit.MINUTES) @get:Rule val flagRule = FlagRule(StudioFlags.NPW_NEW_MACRO_BENCHMARK_MODULE, true) @Before @Throws(java.lang.Exception::class) fun setUp() { val ideFrame = guiTest.importProjectAndWaitForProjectSyncToFinish("SimpleAndroidxApplication") assertThat(guiTest.ideFrame().invokeProjectMake().isBuildSuccessful).isTrue() //Clearing notifications present on the screen. ideFrame.clearNotificationsPresentOnIdeFrame() guiTest.waitForAllBackgroundTasksToBeCompleted() } /** * Verifies that user is able to add a Benchmark Module through the * new module wizard. * * <pre> * Test steps: * 1. Import simple application project * 2. Go to File -> New module to open the new module dialog wizard. * 3. Choose Benchmark Module and click next. * 4. Select Microbenchmark as the benchmark module type. * 5. Select Java as the source language. * 6. Complete the wizard and wait for the build to complete. * Verify: * 1. The new Benchmark Module is shown in the project explorer pane. * 2. Open the Benchmark Module manifest and check that "android:debuggable" and * is set to false. * 3. Open build.gradle and check that it applies: * - both com.android.library and androidx.benchmark plugins * - testBuildType set to "release" * - the test runner * - the benchmark library added as an androidTest dependency. */ @Test @Throws(Exception::class) fun addJavaMicrobenchmarkModule() { NewModuleWizardFixture.find(guiTest.ideFrame().invokeMenuPath("File", "New", "New Module\u2026")) .clickNextToBenchmarkModule() .selectBenchmarkType(BenchmarkModuleType.MICROBENCHMARK) .selectMinimumSdkApi(AndroidVersion.VersionCodes.P) .setSourceLanguage(Java) .wizard() .clickFinishAndWaitForSyncToFinish(Wait.seconds(150)) guiTest.getProjectFileText("benchmark/src/androidTest/AndroidManifest.xml").run { assertThat(this).contains("""android:debuggable="false"""") } guiTest.getProjectFileText("benchmark/build.gradle").run { assertThat(this).contains("""id 'com.android.library'""") assertThat(this).contains("""id 'androidx.benchmark'""") assertThat(this).contains("""testBuildType = "release"""") assertThat(this).contains("""testInstrumentationRunner 'androidx.benchmark.junit4.AndroidBenchmarkRunner'""") assertThat(this).contains("""androidTestImplementation 'androidx.benchmark:benchmark-junit4:""") } } /** * Verifies that user is able to add a Benchmark Module through the * new module wizard. * * <pre> * Test steps: * 1. Import simple application project * 2. Go to File -> New module to open the new module dialog wizard. * 3. Choose Benchmark Module and click next. * 4. Select Microbenchmark as the benchmark module type. * 5. Select Kotlin as the source language. * 6. Complete the wizard and wait for the build to complete. * Verify: * 1. The new Benchmark Module is shown in the project explorer pane. * 2. Open the Benchmark Module manifest and check that "android:debuggable" and * is set to false. * 3. Open build.gradle and check that it applies: * - both com.android.library and androidx.benchmark plugins * - testBuildType set to "release" * - the test runner * - the benchmark library added as an androidTest dependency. */ @Test @Throws(Exception::class) fun addKotlinMicrobenchmarkModule() { NewModuleWizardFixture.find(guiTest.ideFrame().invokeMenuPath("File", "New", "New Module\u2026")) .clickNextToBenchmarkModule() .selectBenchmarkType(BenchmarkModuleType.MICROBENCHMARK) .selectMinimumSdkApi(AndroidVersion.VersionCodes.P) .setSourceLanguage(Kotlin) .wizard() .clickFinishAndWaitForSyncToFinish(Wait.seconds(150)) guiTest.getProjectFileText("benchmark/src/androidTest/AndroidManifest.xml").run { assertThat(this).contains("""android:debuggable="false"""") } guiTest.getProjectFileText("benchmark/build.gradle").run { assertThat(this).contains("""id 'com.android.library'""") assertThat(this).contains("""id 'androidx.benchmark'""") assertThat(this).contains("""testBuildType = "release"""") assertThat(this).contains("""testInstrumentationRunner 'androidx.benchmark.junit4.AndroidBenchmarkRunner'""") assertThat(this).contains("""androidTestImplementation 'androidx.benchmark:benchmark-junit4:""") } } /** * Verifies that user is able to add a Java Macrobenchmark Module through the * new module wizard. * * <pre> * Test steps: * 1. Import simple application project * 2. Go to File -> New module to open the new module dialog wizard. * 3. Choose Benchmark Module and click next. * 4. Select Macrobenchmark as the benchmark module type. * 5. Select Java as the source language. * 6. Complete the wizard and wait for the build to complete. * Verify: * 1. The new Marobenchmark Module is shown in the project explorer pane. * 2. Open the Macrobenchmark Module main manifest and check that: * - Query for target application is declared * - android.permission.WRITE_EXTERNAL_STORAGE is declared * 3. Open build.gradle and check that: * - com.android.test plugin is applied * - the macrobenchmark library added as an implementation dependency * - targetProjectPath is set to :app * - The android.experimental.self-instrumenting property is set to true */ @Test @Throws(Exception::class) fun addJavaMacrobenchmarkModule() { NewModuleWizardFixture.find(guiTest.ideFrame().invokeMenuPath("File", "New", "New Module\u2026")) .clickNextToBenchmarkModule() .selectBenchmarkType(BenchmarkModuleType.MACROBENCHMARK) .enterPackageName("com.example.macrobenchmark") .selectTargetApplicationModule("SimpleAndroidxApplication.app") .selectMinimumSdkApi(AndroidVersion.VersionCodes.Q) .setSourceLanguage(Java) .wizard() .clickFinishAndWaitForSyncToFinish(Wait.seconds(150)) guiTest.getProjectFileText("benchmark/src/main/AndroidManifest.xml") guiTest.getProjectFileText("benchmark/build.gradle").run { assertThat(this).contains("""id 'com.android.test'""") assertThat(this).contains("""implementation 'androidx.benchmark:benchmark-macro-junit4:""") assertThat(this).contains("""experimentalProperties["android.experimental.self-instrumenting"] = true""") assertThat(this).contains("""targetProjectPath = ":app"""") } } /** * Verifies that user is able to add a Kotlin Macrobenchmark Module through the * new module wizard. * * <pre> * Test steps: * 1. Import simple application project * 2. Go to File -> New module to open the new module dialog wizard. * 3. Choose Benchmark Module and click next. * 4. Select Macrobenchmark as the benchmark module type. * 5. Select Java as the source language. * 6. Complete the wizard and wait for the build to complete. * Verify: * 1. The new Marobenchmark Module is shown in the project explorer pane. * 2. Open the Macrobenchmark Module main manifest and check that: * - Query for target application is declared * - android.permission.WRITE_EXTERNAL_STORAGE is declared * 3. Open build.gradle and check that: * - com.android.test plugin is applied * - the macrobenchmark library added as an implementation dependency * - targetProjectPath is set to :app * - The android.experimental.self-instrumenting property is set to true */ @Test @Throws(Exception::class) fun addKotlinMacrobenchmarkModule() { NewModuleWizardFixture.find(guiTest.ideFrame().invokeMenuPath("File", "New", "New Module\u2026")) .clickNextToBenchmarkModule() .selectBenchmarkType(BenchmarkModuleType.MACROBENCHMARK) .enterPackageName("com.example.macrobenchmark") .selectTargetApplicationModule("SimpleAndroidxApplication.app") .selectMinimumSdkApi(AndroidVersion.VersionCodes.Q) .setSourceLanguage(Kotlin) .wizard() .clickFinishAndWaitForSyncToFinish(Wait.seconds(150)) guiTest.getProjectFileText("benchmark/src/main/AndroidManifest.xml") guiTest.getProjectFileText("benchmark/build.gradle").run { assertThat(this).contains("""id 'com.android.test'""") assertThat(this).contains("""implementation 'androidx.benchmark:benchmark-macro-junit4:""") assertThat(this).contains("""experimentalProperties["android.experimental.self-instrumenting"] = true""") assertThat(this).contains("""targetProjectPath = ":app"""") } } }
package model import org.jetbrains.dokka.analysis.kotlin.markdown.MARKDOWN_ELEMENT_FILE_NAME import org.jetbrains.dokka.model.* import org.jetbrains.dokka.model.doc.* import org.jetbrains.dokka.model.doc.P import kotlin.test.Test import utils.* class ConstructorsTest : AbstractModelTest("/src/main/kotlin/constructors/Test.kt", "constructors") { @Test fun `should have documentation for @constructor tag without parameters`() { val expectedRootDescription = Description( CustomDocTag( emptyList(), params = emptyMap(), name = MARKDOWN_ELEMENT_FILE_NAME ) ) val expectedConstructorTag = Constructor( CustomDocTag( listOf( P( listOf( Text("some doc"), ) ) ), params = emptyMap(), name = MARKDOWN_ELEMENT_FILE_NAME ) ) val expectedDescriptionTag = Description( CustomDocTag( listOf( P( listOf( Text("some doc"), ) ) ), params = emptyMap(), name = MARKDOWN_ELEMENT_FILE_NAME ) ) inlineModelTest( """ |/** |* @constructor some doc |*/ |class A """.trimMargin() ) { val classlike = packages.flatMap { it.classlikes }.first() as DClass classlike.name equals "A" classlike.documentation.values.single() equals DocumentationNode(listOf(expectedRootDescription, expectedConstructorTag)) val constructor = classlike.constructors.single() constructor.documentation.values.single() equals DocumentationNode(listOf(expectedDescriptionTag)) } } @Test fun `should have documentation for @constructor tag`() { val expectedRootDescription = Description( CustomDocTag( emptyList(), params = emptyMap(), name = MARKDOWN_ELEMENT_FILE_NAME ) ) val expectedConstructorTag = Constructor( CustomDocTag( listOf( P( listOf( Text("some doc"), ) ) ), params = emptyMap(), name = MARKDOWN_ELEMENT_FILE_NAME ) ) val expectedDescriptionTag = Description( CustomDocTag( listOf( P( listOf( Text("some doc"), ) ) ), params = emptyMap(), name = MARKDOWN_ELEMENT_FILE_NAME ) ) inlineModelTest( """ |/** |* @constructor some doc |*/ |class A(a: Int) """.trimMargin() ) { val classlike = packages.flatMap { it.classlikes }.first() as DClass classlike.name equals "A" classlike.documentation.values.single() equals DocumentationNode(listOf(expectedRootDescription, expectedConstructorTag)) val constructor = classlike.constructors.single() constructor.documentation.values.single() equals DocumentationNode(listOf(expectedDescriptionTag)) } } @Test fun `should ignore documentation in @constructor tag for a secondary constructor`() { val expectedRootDescription = Description( CustomDocTag( emptyList(), params = emptyMap(), name = MARKDOWN_ELEMENT_FILE_NAME ) ) val expectedConstructorTag = Constructor( CustomDocTag( listOf( P( listOf( Text("some doc"), ) ) ), params = emptyMap(), name = MARKDOWN_ELEMENT_FILE_NAME ) ) inlineModelTest( """ |/** |* @constructor some doc |*/ |class A { | constructor(a: Int) |} """.trimMargin() ) { val classlike = packages.flatMap { it.classlikes }.first() as DClass classlike.name equals "A" classlike.documentation.values.single() equals DocumentationNode(listOf(expectedRootDescription, expectedConstructorTag)) val constructor = classlike.constructors.single() constructor.documentation.isEmpty() equals true } } @Test fun `should have KMP documentation for @constructor tag`() { val expectedDescriptionTag = Description( CustomDocTag( listOf( P( listOf( Text("some doc"), ) ) ), params = emptyMap(), name = MARKDOWN_ELEMENT_FILE_NAME ) ) val configuration = dokkaConfiguration { sourceSets { val common = sourceSet { name = "common" displayName = "common" analysisPlatform = "common" sourceRoots = listOf("src/main/kotlin/common/Test.kt") } sourceSet { name = "jvm" displayName = "jvm" analysisPlatform = "jvm" sourceRoots = listOf("src/main/kotlin/jvm/Test.kt") dependentSourceSets = setOf(common.value.sourceSetID) } } } testInline( """ |/src/main/kotlin/common/Test.kt |package multiplatform | |expect class A() | |/src/main/kotlin/jvm/Test.kt |package multiplatform |/** ||* @constructor some doc |*/ |actual class A() """.trimMargin(), configuration ) { documentablesMergingStage = { val classlike = it.packages.flatMap { it.classlikes }.first() as DClass classlike.name equals "A" val actualConstructor = classlike.constructors.first { it.sourceSets.single().displayName == "jvm" } actualConstructor.documentation.values.single() equals DocumentationNode(listOf(expectedDescriptionTag)) val expectConstructor = classlike.constructors.first { it.sourceSets.single().displayName == "common" } expectConstructor.documentation.isEmpty() equals true } } } @Test fun `should have actual constructor`() { val configuration = dokkaConfiguration { sourceSets { val common = sourceSet { name = "common" displayName = "common" analysisPlatform = "common" sourceRoots = listOf("src/main/kotlin/common/Test.kt") } sourceSet { name = "jvm" displayName = "jvm" analysisPlatform = "jvm" sourceRoots = listOf("src/main/kotlin/jvm/Test.kt") dependentSourceSets = setOf(common.value.sourceSetID) } } } testInline( """ |/src/main/kotlin/common/Test.kt |package multiplatform | |expect class A() | |/src/main/kotlin/jvm/Test.kt |package multiplatform |actual class A{ | actual constructor(){} |} """.trimMargin(), configuration ) { preMergeDocumentablesTransformationStage = { val actualClasslike = it.first { it.sourceSets.single().displayName == "common" }.packages.flatMap { it.classlikes }.first() as DClass actualClasslike.name equals "A" val actualConstructor = actualClasslike.constructors.first { it.sourceSets.single().displayName == "common" } actualConstructor.isExpectActual equals true val expectClasslike = it.first { it.sourceSets.single().displayName == "jvm" }.packages.flatMap { it.classlikes }.first() as DClass expectClasslike.name equals "A" val expectConstructor = expectClasslike.constructors.first { it.sourceSets.single().displayName == "jvm" } expectConstructor.isExpectActual equals true } documentablesMergingStage = { val classlike = it.packages.flatMap { it.classlikes }.first() as DClass classlike.name equals "A" val constructor = classlike.constructors.single() constructor.isExpectActual equals true constructor.sourceSets counts 2 } } } }
package com.android.tools.idea.compose import com.android.tools.idea.project.DefaultModuleSystem import com.android.tools.idea.projectsystem.getModuleSystem import com.android.tools.idea.testing.AndroidProjectRule import com.android.tools.idea.testing.NamedExternalResource import com.android.tools.idea.testing.TestLoggerRule import com.intellij.openapi.project.Project import com.intellij.testFramework.fixtures.CodeInsightTestFixture import org.jetbrains.android.compose.stubComposableAnnotation import org.jetbrains.android.compose.stubPreviewAnnotation import org.junit.rules.RuleChain import org.junit.rules.TestRule import org.junit.runner.Description import org.junit.runners.model.Statement /** [TestRule] that implements the [before] and [after] setup specific for Compose unit tests. */ private class ComposeProjectRuleImpl(private val projectRule: AndroidProjectRule) : NamedExternalResource() { override fun before(description: Description) { (projectRule.module.getModuleSystem() as? DefaultModuleSystem)?.let { it.usesCompose = true } projectRule.fixture.stubComposableAnnotation() projectRule.fixture.stubPreviewAnnotation() } override fun after(description: Description) {} } /** * A [TestRule] providing the same behaviour as [AndroidProjectRule] but with the correct setup for * testing Compose preview elements. */ class ComposeProjectRule( private val projectRule: AndroidProjectRule = AndroidProjectRule.inMemory() ) : TestRule { val project: Project get() = projectRule.project val fixture: CodeInsightTestFixture get() = projectRule.fixture private val delegate = RuleChain.outerRule(TestLoggerRule()) .around(projectRule) .around(ComposeProjectRuleImpl(projectRule)) override fun apply(base: Statement, description: Description): Statement = delegate.apply(base, description) }
interface A interface B class Inv<T>(e: T) fun <S> intersection(x: Inv<in S>, y: Inv<in S>): S = TODO() fun <K> use(k: K, f: K.(K) -> K) {} fun <K> useNested(k: K, f: Inv<K>.(Inv<K>) -> Inv<K>) {} fun <T> createDelegate(f: () -> T): Delegate<T> = Delegate() class Delegate<T> { operator fun getValue(thisRef: Any?, property: kotlin.reflect.KProperty<*>): T = TODO() operator fun setValue(thisRef: Any?, property: kotlin.reflect.KProperty<*>, value: T) {} } fun test(a: Inv<A>, b: Inv<B>) { val intersectionType = intersection(a, b) use(intersectionType) { intersectionType } useNested(intersectionType) { Inv(intersectionType) } var d by createDelegate { intersectionType } }
package org.jetbrains.kotlin.ir.util import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.descriptors.PropertyDescriptor import org.jetbrains.kotlin.ir.declarations.* import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedContainerSource import org.jetbrains.kotlin.types.KotlinType interface DeserializableClass { fun loadIr(): Boolean } open class StubGeneratorExtensions { open fun computeExternalDeclarationOrigin(descriptor: DeclarationDescriptor): IrDeclarationOrigin? = null open fun generateFacadeClass( irFactory: IrFactory, deserializedSource: DeserializedContainerSource, stubGenerator: DeclarationStubGenerator, ): IrClass? = null // Extension point for the JVM Debugger IDEA plug-in: it compiles fragments // (conditions on breakpoints, "Evaluate expression...", watches, etc...) // in the context of an open intellij project that is being debugged. These // classes are supplied to the fragment evaluator as PSI, not class files, // as the old backend assumes for external declarations. Hence, we need to // intercept and supply "fake" deserialized sources. open fun getContainerSource(descriptor: DeclarationDescriptor): DeserializedContainerSource? = null // Extension point for the JVM Debugger IDEA plug-in: to replace accesses // to private properties _without_ accessor implementations, the fragment // compiler needs to predict the compilation output for properties. // To do this, we need to know whether the property accessors have explicit // bodies, information that is _not_ present in the IR structure, but _is_ // available in the corresponding PSI. See `CodeFragmentCompiler` in the // plug-in for the implementation. open fun isAccessorWithExplicitImplementation(accessor: IrSimpleFunction): Boolean = false open fun isPropertyWithPlatformField(descriptor: PropertyDescriptor): Boolean = false open fun isStaticFunction(descriptor: FunctionDescriptor): Boolean = false open fun deserializeClass( irClass: IrClass, stubGenerator: DeclarationStubGenerator, parent: IrDeclarationParent, ): Boolean = false open val enhancedNullability: EnhancedNullability get() = EnhancedNullability open class EnhancedNullability { open fun hasEnhancedNullability(kotlinType: KotlinType): Boolean = false open fun stripEnhancedNullability(kotlinType: KotlinType): KotlinType = kotlinType companion object Instance : EnhancedNullability() } open val irDeserializationEnabled: Boolean = false open val flexibleNullabilityAnnotationConstructor: IrConstructor? get() = null open val flexibleMutabilityAnnotationConstructor: IrConstructor? get() = null open val enhancedNullabilityAnnotationConstructor: IrConstructor? get() = null open val rawTypeAnnotationConstructor: IrConstructor? get() = null companion object { @JvmField val EMPTY = StubGeneratorExtensions() } }
package one class SimpleClass { @Anno @get:Anno @set:Anno @setparam:Anno var memberVariableWithAnnotations: Long = 0L } annotation class Anno // MODULE: main(lib) // FILE: usage.kt fun usage(instance: one.SimpleClass) { instance.memberV<caret>ariableWithAnnotations }
package com.maddyhome.idea.vim.vimscript.model import java.lang.invoke.MethodHandles import java.lang.invoke.MethodType /** * Abstract class representing a lazily loaded instance of a specified class. The class is dynamically * loaded and instantiated at runtime, using the provided class name and class loader. This approach is * useful for deferring the loading and instantiation of a class until it is actually needed, reducing * initial memory footprint and startup time. */ public abstract class LazyInstance<T>(private val className: String, private val classLoader: ClassLoader) { public open val instance: T by lazy { val aClass = classLoader.loadClass(className) val lookup = MethodHandles.privateLookupIn(aClass, MethodHandles.lookup()) val instance = lookup.findConstructor(aClass, MethodType.methodType(Void.TYPE)).invoke() @Suppress("UNCHECKED_CAST") instance as T } }
package mui.material import seskar.js.JsValue import seskar.js.JsVirtual @Suppress( "NESTED_CLASS_IN_EXTERNAL_INTERFACE", ) @JsVirtual sealed external interface DividerVariant { companion object { @JsValue("fullWidth") val fullWidth: DividerVariant @JsValue("inset") val inset: DividerVariant @JsValue("middle") val middle: DividerVariant } } @Suppress( "NESTED_CLASS_IN_EXTERNAL_INTERFACE", ) @JsVirtual sealed external interface DividerTextAlign { companion object { @JsValue("center") val center: DividerTextAlign @JsValue("right") val right: DividerTextAlign @JsValue("left") val left: DividerTextAlign } }
package org.jetbrains.kotlin.analysis.test.framework.project.structure import com.intellij.openapi.project.Project import com.intellij.psi.PsiFile import com.intellij.psi.PsiFileSystemItem import com.intellij.psi.PsiJavaFile import org.jetbrains.kotlin.analysis.api.standalone.base.project.structure.StandaloneProjectFactory.findJvmRootsForJavaFiles import org.jetbrains.kotlin.analysis.project.structure.KtBinaryModule import org.jetbrains.kotlin.analysis.project.structure.KtModule import org.jetbrains.kotlin.analysis.test.framework.test.configurators.TestModuleKind import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.test.model.TestModule import org.jetbrains.kotlin.test.services.TestModuleStructure import kotlin.collections.addAll import kotlin.collections.filterIsInstance import kotlin.collections.flatMap import kotlin.collections.mapTo /** * [KtTestModule] describes a [KtModule] originating from a [TestModule] with any number of associated [PsiFile]s. It is used to describe * the module structure configured by Analysis API tests. */ class KtTestModule( val moduleKind: TestModuleKind, val testModule: TestModule, val ktModule: KtModule, val files: List<PsiFile>, ) { val ktFiles: List<KtFile> get() = files.filterIsInstance<KtFile>() } /** * A module structure of [KtTestModule]s, and additional [KtBinaryModule]s not originating from test modules. This module structure * is created by [AnalysisApiTestConfigurator.createModules][org.jetbrains.kotlin.analysis.test.framework.test.configurators.AnalysisApiTestConfigurator.createModules]. * * [mainModules] are created from the configured [TestModule]s and must be in the same order as [testModuleStructure]'s * [modules][TestModuleStructure.modules]. */ class KtTestModuleStructure( val testModuleStructure: TestModuleStructure, val mainModules: List<KtTestModule>, val binaryModules: Iterable<KtBinaryModule>, ) { private val mainModulesByName: Map<String, KtTestModule> = mainModules.associateBy { it.testModule.name } val project: Project get() = mainModules.first().ktModule.project val allMainKtFiles: List<KtFile> get() = mainModules.flatMap { it.ktFiles } val mainAndBinaryKtModules: List<KtModule> get() = buildList { mainModules.mapTo(this) { it.ktModule } addAll(binaryModules) } val allSourceFiles: List<PsiFileSystemItem> get() = buildList { val files = mainModules.flatMap { it.files } addAll(files) addAll(findJvmRootsForJavaFiles(files.filterIsInstance<PsiJavaFile>())) } fun getKtTestModule(moduleName: String): KtTestModule { return mainModulesByName.getValue(moduleName) } fun getKtTestModule(testModule: TestModule): KtTestModule { return mainModulesByName[testModule.name] ?: mainModulesByName.getValue(testModule.files.single().name) } }
@file:Suppress( "NESTED_CLASS_IN_EXTERNAL_INTERFACE", ) package web.cssom import seskar.js.JsValue import seskar.js.JsVirtual @JsVirtual sealed external interface OffsetRotate { companion object { @JsValue("reverse") val reverse: OffsetRotate } }
fun test() { val buildee = build { setTypeVariable(TargetType()) extensionSetOutProjectedTypeVariable(DifferentType()) } // exact type equality check — turns unexpected compile-time behavior into red code // considered to be non-user-reproducible code for the purposes of these tests checkExactType<Buildee<TargetType>>(buildee) } class TargetType class DifferentType class Buildee<TV> { fun setTypeVariable(value: TV) { storage = value } private var storage: TV = null!! } fun <ETV> Buildee<out ETV>.extensionSetOutProjectedTypeVariable(value: ETV) {} fun <PTV> build(instructions: Buildee<PTV>.() -> Unit): Buildee<PTV> { return Buildee<PTV>().apply(instructions) }
import java.util.HashSet interface A : Set<String> class B : A, HashSet<String>() { override fun clone(): B = throw AssertionError() } fun box(): String { return try { B().clone() "Fail 1" } catch (e: AssertionError) { try { val hs: HashSet<String> = B() hs.clone() "Fail 2" } catch (e: AssertionError) { "OK" } } }
package org.jetbrains.kotlin.buildtools.api.tests.compilation.scenario import org.jetbrains.kotlin.buildtools.api.jvm.IncrementalJvmCompilationConfiguration import org.jetbrains.kotlin.buildtools.api.jvm.JvmCompilationConfiguration import org.jetbrains.kotlin.buildtools.api.tests.compilation.model.Module interface Scenario { /** * Creates a module for a scenario. * * Modules with the same combination of [Module.scenarioDslCacheKey], [compilationOptionsModifier], and [incrementalCompilationOptionsModifier] are compiled initially only once per tests run. * * In the case you are using custom values for [compilationOptionsModifier] or [incrementalCompilationOptionsModifier], consider sharing the same lambda between tests for better cacheability results. * * @param moduleName The name of the module. * @param dependencies (optional) The list of scenario modules that this module depends on. Defaults to an empty list. * @param additionalCompilationArguments (optional) The list of additional compilation arguments for this module. Defaults to an empty list. * @param compilationOptionsModifier (optional) A function that can be used to modify the compilation configuration for this module. * @param incrementalCompilationOptionsModifier (optional) A function that can be used to modify the incremental compilation configuration for this module. * @return The created scenario module in the compiled state. */ fun module( moduleName: String, dependencies: List<ScenarioModule> = emptyList(), additionalCompilationArguments: List<String> = emptyList(), compilationOptionsModifier: ((JvmCompilationConfiguration) -> Unit)? = null, incrementalCompilationOptionsModifier: ((IncrementalJvmCompilationConfiguration<*>) -> Unit)? = null, ): ScenarioModule }
import helpers.* // TREAT_AS_ONE_FILE import kotlin.coroutines.* import kotlin.coroutines.intrinsics.* suspend fun suspendHere(): String = suspendCoroutineUninterceptedOrReturn { x -> x.resume("OK") } fun builder(c: suspend () -> Unit) { c.startCoroutine(EmptyContinuation) } val nonConstOne = 1 fun box(): String { var result = "fail 1" builder { // Initialize var with Int value for (i in 1..nonConstOne) { if ("".length > 0) continue } // This variable should take the same slot as 'i' had var s: String // We should not spill 's' to continuation field because it's not initialized // More precisely it contains a value of wrong type (it conflicts with contents of local var table), // so an attempt of spilling may lead to problems on Android if (suspendHere() == "OK") { s = "OK" } else { s = "fail 2" } result = s } return result } // 1 LOCALVARIABLE i I L.* 2 // 0 PUTFIELD VarValueConflictsWithTableKt\$box\$1.I\$0 : I /* 2 loads in cycle */ // 2 ILOAD 2 // JVM_IR_TEMPLATES // 1 LOCALVARIABLE s Ljava/lang/String; L.* 2 // JVM_TEMPLATES // 2 LOCALVARIABLE s Ljava/lang/String; L.* 2
fun bar(x: Int) = x + 1 fun foo() { val x: Int? = null if (x != null) { bar(x) if (<!SENSELESS_COMPARISON!>x != null<!>) { bar(x) if (1 < 2) bar(x) if (1 > 2) bar(x) } if (<!SENSELESS_COMPARISON!>x == null<!>) { bar(x) } if (<!SENSELESS_COMPARISON!>x == null<!>) bar(x) else bar(x) bar(bar(x)) } else if (<!SENSELESS_COMPARISON!><!DEBUG_INFO_CONSTANT!>x<!> == null<!>) { bar(<!DEBUG_INFO_CONSTANT, TYPE_MISMATCH!>x<!>) if (<!SENSELESS_COMPARISON!><!DEBUG_INFO_CONSTANT!>x<!> != null<!>) { bar(x) if (<!SENSELESS_COMPARISON!>x == null<!>) bar(x) if (<!SENSELESS_COMPARISON!>x == null<!>) bar(x) else bar(x) bar(bar(x) + bar(x)) } else if (<!SENSELESS_COMPARISON!><!DEBUG_INFO_CONSTANT!>x<!> == null<!>) { bar(<!DEBUG_INFO_CONSTANT, TYPE_MISMATCH!>x<!>) } } }
package com.maddyhome.idea.vim.action.window import com.intellij.vim.annotations.CommandOrMotion import com.intellij.vim.annotations.Mode import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.command.Command import com.maddyhome.idea.vim.command.OperatorArguments import com.maddyhome.idea.vim.handler.VimActionHandler /** * @author Alex Plate */ @CommandOrMotion(keys = ["<C-N>"], modes = [Mode.INSERT]) public class LookupDownAction : VimActionHandler.SingleExecution() { private val keySet = parseKeysSet("<C-N>") override val type: Command.Type = Command.Type.OTHER_READONLY override fun execute( editor: VimEditor, context: ExecutionContext, cmd: Command, operatorArguments: OperatorArguments, ): Boolean { val activeLookup = injector.lookupManager.getActiveLookup(editor) if (activeLookup != null) { activeLookup.down(editor.primaryCaret(), context) } else { val keyStroke = keySet.first().first() val actions = injector.keyGroup.getKeymapConflicts(keyStroke) for (action in actions) { if (injector.actionExecutor.executeAction(editor, action, context)) break } } return true } }
package a fun IntArray.forEachNoInline(block: (Int) -> Unit) = this.forEach { block(it) } inline fun fold(initial: Int, values: IntArray, crossinline block: (Int, Int) -> Int): Int { var res = initial values.forEachNoInline { res = block(res, it) } return res } // MODULE: main(lib) // FILE: main.kt import a.* import kotlin.test.* fun box(): String { assertEquals(6, fold(0, intArrayOf(1, 2, 3)) { x, y -> x + y }) return "OK" }
public interface Condition { boolean value(boolean t); } // FILE: Foo.java public class Foo { public Foo(Condition filter) {} } // FILE: main.kt fun test() { Foo { it } }
class C<T>(val x: T, vararg ys: UInt) { val y0 = ys[0] } fun box(): String { val c = C("a", 42u) if (c.y0 != 42u) throw AssertionError() return "OK" }
package test public interface UseParameterInUpperBound { public interface Super { public fun <A, B: List<A>> foo(a: A, b: B) } public interface Sub: Super { override fun <B, A: List<B>> foo(a: B, b: A) } }
class Final<T> open class Base<T> class Derived<T> : Base<T>() class FinalWithOverride<T> { override fun equals(other: Any?): Boolean { // some custom implementation return this === other } } fun testFinal(x: Final<*>, y: Final<Int>) { if (x == y) { takeIntFinal(x) // OK } if (x === y) { takeIntFinal(x) // OK } } fun testBase(x: Base<*>, y: Base<Int>) { if (x == y) { takeIntBase(<!ARGUMENT_TYPE_MISMATCH!>x<!>) // Error } if (x === y) { takeIntBase(x) // OK } } fun testDerived(x: Derived<*>, y: Derived<Int>) { if (x == y) { takeIntDerived(x) // OK } if (x === y) { takeIntDerived(x) // OK } } fun testFinalWithOverride(x: FinalWithOverride<*>, y: FinalWithOverride<Int>) { if (x == y) { takeIntFinalWithOverride(<!ARGUMENT_TYPE_MISMATCH!>x<!>) // Error } if (x === y) { takeIntFinalWithOverride(x) // OK } } fun takeIntFinal(x: Final<Int>) {} fun takeIntBase(x: Base<Int>) {} fun takeIntDerived(x: Derived<Int>) {} fun takeIntFinalWithOverride(x: FinalWithOverride<Int>) {}
package com.google.samples.apps.iosched.ui.schedule.day import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.google.samples.apps.iosched.model.Session import com.google.samples.apps.iosched.model.userdata.UserEvent import com.google.samples.apps.iosched.shared.data.userevent.UserEventDataSource import com.google.samples.apps.iosched.shared.data.userevent.UserEventResult import com.google.samples.apps.iosched.shared.data.userevent.UserEventsResult import com.google.samples.apps.iosched.shared.domain.users.ReservationRequestAction import com.google.samples.apps.iosched.shared.domain.users.ReservationRequestAction.CancelAction import com.google.samples.apps.iosched.shared.domain.users.ReservationRequestAction.RequestAction import com.google.samples.apps.iosched.shared.domain.users.StarUpdatedStatus import com.google.samples.apps.iosched.shared.domain.users.StarUpdatedStatus.STARRED import com.google.samples.apps.iosched.shared.domain.users.StarUpdatedStatus.UNSTARRED import com.google.samples.apps.iosched.shared.domain.users.SwapRequestAction import com.google.samples.apps.iosched.shared.result.Result import com.google.samples.apps.iosched.test.data.TestData class TestUserEventDataSource( private val userEventsResult: MutableLiveData<UserEventsResult> = MutableLiveData(), private val userEventResult: MutableLiveData<UserEventResult> = MutableLiveData() ) : UserEventDataSource { override fun getObservableUserEvents(userId: String): LiveData<UserEventsResult> { userEventsResult.postValue(UserEventsResult(TestData.userEvents)) return userEventsResult } override fun getObservableUserEvent( userId: String, eventId: String ): LiveData<UserEventResult> { userEventResult.postValue(UserEventResult(TestData.userEvents .find { it.id == eventId } ?: TestData.userEvents[0])) return userEventResult } override fun starEvent( userId: String, userEvent: UserEvent ): LiveData<Result<StarUpdatedStatus>> { val result = MutableLiveData<Result<StarUpdatedStatus>>() result.postValue( Result.Success( if (userEvent.isStarred) STARRED else UNSTARRED ) ) return result } override fun requestReservation( userId: String, session: Session, action: ReservationRequestAction ): LiveData<Result<ReservationRequestAction>> { val result = MutableLiveData<Result<ReservationRequestAction>>() result.postValue( Result.Success( if (action is RequestAction) RequestAction() else CancelAction() ) ) return result } override fun getUserEvents(userId: String): List<UserEvent> = TestData.userEvents override fun swapReservation( userId: String, fromSession: Session, toSession: Session ): LiveData<Result<SwapRequestAction>> { val result = MutableLiveData<Result<SwapRequestAction>>() result.postValue(Result.Success(SwapRequestAction())) return result } override fun clearSingleEventSubscriptions() {} }
package org.jetbrains.letsPlot.commons.intern.json object JsonSupport { fun parseJson(jsonString: String): MutableMap<String, Any?> { @Suppress("UNCHECKED_CAST") return JsonParser(jsonString).parseJson() as MutableMap<String, Any?> } // Do not add parameter 'pretty' with a default value because of JS compatibility: // No function found for symbol 'org.jetbrains.letsPlot.commons.intern.json/JsonSupport.formatJson|formatJson(kotlin.Any){}[0]' fun formatJson(o: Any): String { return JsonFormatter(pretty = false).formatJson(o) } fun formatJson(o: Any, pretty: Boolean = false): String { return JsonFormatter(pretty).formatJson(o) } } // Useful resources: // https://www.ietf.org/rfc/rfc4627.txt // https://github.com/nst/JSONTestSuite internal enum class Token { LEFT_BRACE, RIGHT_BRACE, LEFT_BRACKET, RIGHT_BRACKET, COMMA, COLON, STRING, NUMBER, TRUE, FALSE, NULL, } internal val SPECIAL_CHARS = mapOf( '"' to '"', '\\' to '\\', '/' to '/', 'b' to '\b', 'f' to '\u000C', 'n' to '\n', 'r' to '\r', 't' to '\t' ) private val CONTROL_CHARS = (0 until 0x20).map(Int::toChar).toSet() fun String.escape(): String { var output: StringBuilder? = null var i = 0 fun appendOutput(str: String) { output = (output ?: StringBuilder(substring(0, i))).append(str) } while (i < length) { when (val ch = get(i)) { '\\' -> appendOutput("""\\""") '"' -> appendOutput("""\"""") '\n' -> appendOutput("""\n""") '\r' -> appendOutput("""\r""") '\t' -> appendOutput("""\t""") in CONTROL_CHARS -> appendOutput("""\u${ch.code.toString(16).padStart(4, '0')}""") else -> output?.append(ch) } i++ } return output?.toString() ?: this } fun String.unescape(): String { var output: StringBuilder? = null val start = 1 val end = length - 1 var i = start while (i < end) { val ch = get(i) if (ch == '\\') { output = output ?: StringBuilder(substring(start, i)) when (val escapedChar = get(++i)) { in SPECIAL_CHARS -> SPECIAL_CHARS[escapedChar].also { i++ } 'u' -> substring(i + 1, i + 5).toInt(16).toChar().also { i += 5 } else -> throw JsonParser.JsonException("Invalid escape character: ${escapedChar}") }.let { output.append(it) } } else { output?.append(ch); i++ } } return output?.toString() ?: substring(start, end) }
package com.android.tools.profilers.perfetto.traceprocessor import com.android.tools.profiler.perfetto.proto.TraceProcessor import com.android.tools.profiler.perfetto.proto.TraceProcessor.AndroidFrameEventsResult.FrameEvent import com.android.tools.profiler.perfetto.proto.TraceProcessor.AndroidFrameEventsResult.Layer import com.android.tools.profiler.perfetto.proto.TraceProcessor.AndroidFrameEventsResult.Phase import com.android.tools.profilers.cpu.ThreadState import com.android.tools.profilers.cpu.systemtrace.AndroidFrameTimelineEvent import com.android.tools.profilers.cpu.systemtrace.CounterModel import com.android.tools.profilers.cpu.systemtrace.CpuCoreModel import com.android.tools.profilers.cpu.systemtrace.SchedulingEventModel import com.android.tools.profilers.cpu.systemtrace.TraceEventModel import com.google.common.truth.Truth.assertThat import org.junit.Test import perfetto.protos.PerfettoTrace class TraceProcessorModelTest { @Test fun addProcessMetadata() { val protoBuilder = TraceProcessor.ProcessMetadataResult.newBuilder() protoBuilder.addProcess(1, "Process1") .addThread(2, "AnotherThreadProcess1") .addThread(1, "MainThreadProcess1") protoBuilder.addProcess(4, "Process2") .addThread(6, "AnotherThreadProcess2") val modelBuilder = TraceProcessorModel.Builder() modelBuilder.addProcessMetadata(protoBuilder.build()) val model = modelBuilder.build() assertThat(model.getProcesses()).hasSize(2) val process1 = model.getProcessById(1)!! assertThat(process1.name).isEqualTo("Process1") assertThat(process1.getThreads()).hasSize(2) assertThat(process1.getThreads().map { it.name }).containsExactly("MainThreadProcess1", "AnotherThreadProcess1").inOrder() assertThat(process1.getMainThread()!!.name).isEqualTo("MainThreadProcess1") val process2 = model.getProcessById(4)!! assertThat(process2.name).isEqualTo("Process2") assertThat(process2.getThreads()).hasSize(1) assertThat(process2.getThreads().map { it.name }).containsExactly("AnotherThreadProcess2") assertThat(process2.getMainThread()).isNull() } @Test fun addTraceEvents() { val processProtoBuilder = TraceProcessor.ProcessMetadataResult.newBuilder() processProtoBuilder.addProcess(1, "Process1") .addThread(2, "AnotherThreadProcess1") .addThread(1, "MainThreadProcess1") val traceProtoBuilder = TraceProcessor.TraceEventsResult.newBuilder() traceProtoBuilder.addThread(1) .addEvent(1000, 1000, 2000, "EventA") .addEvent(1001, 2000, 5000, "EventA-1", 1000, 1) .addEvent(1002, 5000, 1000, "EventA-1-1", 1001, 2) .addEvent(1003, 15000, 3000, "EventA-2", 1000, 1) val modelBuilder = TraceProcessorModel.Builder() modelBuilder.addProcessMetadata(processProtoBuilder.build()) modelBuilder.addTraceEvents(traceProtoBuilder.build()) val model = modelBuilder.build() val process = model.getProcessById(1)!! val thread = process.threadById[1] ?: error("Thread with id = 1 should be present in this process.") assertThat(thread.traceEvents).containsExactly( // EventA end is 18, because A-2 ends at 18. TraceEventModel("EventA", 1, 18, 2, listOf( TraceEventModel("EventA-1", 2, 7, 5, listOf( TraceEventModel("EventA-1-1", 5, 6, 1, listOf()) )), TraceEventModel("EventA-2", 15, 18, 3, listOf())))) assertThat(model.getCaptureStartTimestampUs()).isEqualTo(1) assertThat(model.getCaptureEndTimestampUs()).isEqualTo(18) } @Test fun `addTraceEvents - missing thread`() { val traceProtoBuilder = TraceProcessor.TraceEventsResult.newBuilder() // Just to test that while processing this we don't crash because we can't find the thread referenced. traceProtoBuilder.addThread(1) .addEvent(10000, 10000, 2000, "EventForMissingThread") val modelBuilder = TraceProcessorModel.Builder() modelBuilder.addTraceEvents(traceProtoBuilder.build()) val model = modelBuilder.build() assertThat(model.getProcesses()).isEmpty() } @Test fun addSchedulingEvents() { val processProtoBuilder = TraceProcessor.ProcessMetadataResult.newBuilder() processProtoBuilder.addProcess(1, "Process1") .addThread(2, "AnotherThreadProcess1") .addThread(1, "MainThreadProcess1") val schedProtoBuilder = TraceProcessor.SchedulingEventsResult.newBuilder().setNumCores(4) schedProtoBuilder.addSchedulingEvent(1, 1, 1, 1000, 3000, TraceProcessor.SchedulingEventsResult.SchedulingEvent.SchedulingState.SLEEPING) schedProtoBuilder.addSchedulingEvent(1, 1, 1, 7000, 2000, TraceProcessor.SchedulingEventsResult.SchedulingEvent.SchedulingState.RUNNABLE) schedProtoBuilder.addSchedulingEvent(1, 1, 2, 11000, 2000, TraceProcessor.SchedulingEventsResult.SchedulingEvent.SchedulingState.RUNNABLE) schedProtoBuilder.addSchedulingEvent(1, 2, 2, 2000, 4000, TraceProcessor.SchedulingEventsResult.SchedulingEvent.SchedulingState.RUNNABLE) schedProtoBuilder.addSchedulingEvent(1, 2, 1, 10000, 1000, TraceProcessor.SchedulingEventsResult.SchedulingEvent.SchedulingState.SLEEPING) val modelBuilder = TraceProcessorModel.Builder() modelBuilder.addProcessMetadata(processProtoBuilder.build()) modelBuilder.addSchedulingEvents(schedProtoBuilder.build()) val model = modelBuilder.build() val process = model.getProcessById(1)!! val thread1 = process.threadById[1] ?: error("Thread 1 should be present") assertThat(thread1.schedulingEvents).containsExactly( SchedulingEventModel(ThreadState.RUNNING_CAPTURED, 1, 4, 3, 3, 1, 1, 1), SchedulingEventModel(ThreadState.SLEEPING_CAPTURED, 4, 7, 3, 3, 1, 1, 1), SchedulingEventModel(ThreadState.RUNNING_CAPTURED, 7, 9, 2, 2, 1, 1, 1), SchedulingEventModel(ThreadState.RUNNABLE_CAPTURED, 9, 11, 2, 2, 1, 1, 1), SchedulingEventModel(ThreadState.RUNNING_CAPTURED, 11, 13, 2, 2, 1, 1, 2)) .inOrder() val thread2 = process.threadById[2] ?: error("Thread 2 should be present") assertThat(thread2.schedulingEvents).containsExactly( SchedulingEventModel(ThreadState.RUNNING_CAPTURED, 2, 6, 4, 4, 1, 2, 2), SchedulingEventModel(ThreadState.RUNNABLE_CAPTURED, 6, 10, 4, 4, 1, 2, 2), SchedulingEventModel(ThreadState.RUNNING_CAPTURED, 10, 11, 1, 1, 1, 2, 1)) .inOrder() val cpus = model.getCpuCores() assertThat(cpus).hasSize(4) assertThat(cpus[0].id).isEqualTo(0) assertThat(cpus[0].schedulingEvents).isEmpty() assertThat(cpus[1].id).isEqualTo(1) assertThat(cpus[1].schedulingEvents).containsExactly( SchedulingEventModel(ThreadState.RUNNING_CAPTURED, 1, 4, 3, 3, 1, 1, 1), SchedulingEventModel(ThreadState.RUNNING_CAPTURED, 7, 9, 2, 2, 1, 1, 1), SchedulingEventModel(ThreadState.RUNNING_CAPTURED, 10, 11, 1, 1, 1, 2, 1)) .inOrder() assertThat(cpus[2].id).isEqualTo(2) assertThat(cpus[2].schedulingEvents).containsExactly( SchedulingEventModel(ThreadState.RUNNING_CAPTURED, 2, 6, 4, 4, 1, 2, 2), SchedulingEventModel(ThreadState.RUNNING_CAPTURED, 11, 13, 2, 2, 1, 1, 2)) .inOrder() assertThat(cpus[3].id).isEqualTo(3) assertThat(cpus[3].schedulingEvents).isEmpty() assertThat(model.getCaptureStartTimestampUs()).isEqualTo(1) assertThat(model.getCaptureEndTimestampUs()).isEqualTo(13) } @Test fun addCpuCounters() { val cpuCounters = TraceProcessor.CpuCoreCountersResult.newBuilder() .setNumCores(2) .addCountersPerCore( TraceProcessor.CpuCoreCountersResult.CountersPerCore.newBuilder() .setCpu(0) .addCounter(TraceProcessor.Counter.newBuilder() .setName("cpufreq") .addValue(TraceProcessor.CounterValue.newBuilder().setTimestampNanoseconds(1000).setValue(0.0)) .addValue(TraceProcessor.CounterValue.newBuilder().setTimestampNanoseconds(2000).setValue(1000.0)) .addValue(TraceProcessor.CounterValue.newBuilder().setTimestampNanoseconds(3000).setValue(2000.0))) .addCounter(TraceProcessor.Counter.newBuilder() .setName("cpuidle") .addValue(TraceProcessor.CounterValue.newBuilder().setTimestampNanoseconds(1500).setValue(0.0)) .addValue(TraceProcessor.CounterValue.newBuilder().setTimestampNanoseconds(2500).setValue(4294967295.0)) .addValue(TraceProcessor.CounterValue.newBuilder().setTimestampNanoseconds(3500).setValue(0.0)))) .addCountersPerCore(TraceProcessor.CpuCoreCountersResult.CountersPerCore.newBuilder().setCpu(1)) .build() val model = TraceProcessorModel.Builder().apply { addCpuCounters(cpuCounters) }.build() assertThat(model.getCpuCores()).containsExactly( CpuCoreModel(0, listOf(), mapOf( "cpufreq" to CounterModel("cpufreq", sortedMapOf(1L to 0.0, 2L to 1000.0, 3L to 2000.0)), "cpuidle" to CounterModel("cpuidle", sortedMapOf(1L to 0.0, 2L to 4294967295.0, 3L to 0.0)) )), CpuCoreModel(1, listOf(), mapOf())) } @Test fun addCounters() { val processProtoBuilder = TraceProcessor.ProcessMetadataResult.newBuilder() processProtoBuilder.addProcess(1, "Process1").addThread(1, "MainThreadProcess1") val counterProtoBuilder = TraceProcessor.ProcessCountersResult.newBuilder().setProcessId(1) val p1CounterA = counterProtoBuilder.addCounterBuilder().setName("CounterA") p1CounterA.addValueBuilder().setTimestampNanoseconds(1000).setValue(0.0) p1CounterA.addValueBuilder().setTimestampNanoseconds(2000).setValue(1.0) p1CounterA.addValueBuilder().setTimestampNanoseconds(3000).setValue(0.0) val p1CounterZ = counterProtoBuilder.addCounterBuilder().setName("CounterZ") p1CounterZ.addValueBuilder().setTimestampNanoseconds(1500).setValue(100.0) p1CounterZ.addValueBuilder().setTimestampNanoseconds(2500).setValue(50.0) p1CounterZ.addValueBuilder().setTimestampNanoseconds(3500).setValue(100.0) val modelBuilder = TraceProcessorModel.Builder() modelBuilder.addProcessMetadata(processProtoBuilder.build()) modelBuilder.addProcessCounters(counterProtoBuilder.build()) val model = modelBuilder.build() val process = model.getProcessById(1)!! val counters = process.counterByName assertThat(counters).hasSize(2) val counterA = counters["CounterA"] ?: error("CounterA should be present.") assertThat(counterA.name).isEqualTo("CounterA") assertThat(counterA.valuesByTimestampUs).containsExactly(1L, 0.0, 2L, 1.0, 3L, 0.0).inOrder() val counterZ = counters["CounterZ"] ?: error("CounterZ should be present.") assertThat(counterZ.name).isEqualTo("CounterZ") assertThat(counterZ.valuesByTimestampUs).containsExactly(1L, 100.0, 2L, 50.0, 3L, 100.0).inOrder() } @Test fun addAndroidFrameLayers() { val layer = Layer.newBuilder() .setLayerName("foobar") .addPhase(Phase.newBuilder() .setPhaseName("Display") .addFrameEvent(FrameEvent.newBuilder().setId(1))) .addPhase(Phase.newBuilder() .setPhaseName("GPU") .addFrameEvent(FrameEvent.newBuilder().setId(2))) .build() val frameEventResult = TraceProcessor.AndroidFrameEventsResult.newBuilder() .addLayer(layer) .build() val model = TraceProcessorModel.Builder().apply { addAndroidFrameEvents(frameEventResult) }.build() assertThat(model.getAndroidFrameLayers()).containsExactly(layer) } @Test fun addAndroidFrameTimelineEvents() { val frameTimelineResult = TraceProcessor.AndroidFrameTimelineResult.newBuilder() .addExpectedSlice(TraceProcessor.AndroidFrameTimelineResult.ExpectedSlice.newBuilder() .setDisplayFrameToken(1) .setSurfaceFrameToken(101) .setTimestampNanoseconds(1000) .setDurationNanoseconds(1000)) .addExpectedSlice(TraceProcessor.AndroidFrameTimelineResult.ExpectedSlice.newBuilder() .setDisplayFrameToken(4) .setSurfaceFrameToken(104) .setTimestampNanoseconds(7000) .setDurationNanoseconds(1000)) .addExpectedSlice(TraceProcessor.AndroidFrameTimelineResult.ExpectedSlice.newBuilder() .setDisplayFrameToken(3) .setSurfaceFrameToken(103) .setTimestampNanoseconds(5000) .setDurationNanoseconds(1000)) .addExpectedSlice(TraceProcessor.AndroidFrameTimelineResult.ExpectedSlice.newBuilder() .setDisplayFrameToken(2) .setSurfaceFrameToken(102) .setTimestampNanoseconds(3000) .setDurationNanoseconds(1000)) .addActualSlice(TraceProcessor.AndroidFrameTimelineResult.ActualSlice.newBuilder() .setDisplayFrameToken(2) .setSurfaceFrameToken(102) .setTimestampNanoseconds(3000) .setDurationNanoseconds(2000) .setLayerName("foo") .setPresentType("Late Present") .setJankType("App Deadline Missed, SurfaceFlinger CPU Deadline Missed") .setOnTimeFinish(false) .setGpuComposition(true) .setLayoutDepth(1)) .addActualSlice(TraceProcessor.AndroidFrameTimelineResult.ActualSlice.newBuilder() .setDisplayFrameToken(3) .setSurfaceFrameToken(103) .setTimestampNanoseconds(5000) .setDurationNanoseconds(1000) .setLayerName("foo") .setPresentType("Early Present") .setJankType("Buffer Stuffing, SurfaceFlinger GPU Deadline Missed") .setOnTimeFinish(true) .setGpuComposition(true) .setLayoutDepth(2)) .addActualSlice(TraceProcessor.AndroidFrameTimelineResult.ActualSlice.newBuilder() .setDisplayFrameToken(4) .setSurfaceFrameToken(104) .setTimestampNanoseconds(7000) .setDurationNanoseconds(3000) .setLayerName("foo") .setPresentType("Dropped Frame") .setJankType("Unknown Jank") .setOnTimeFinish(true) .setGpuComposition(false) .setLayoutDepth(0)) .addActualSlice(TraceProcessor.AndroidFrameTimelineResult.ActualSlice.newBuilder() .setDisplayFrameToken(1) .setSurfaceFrameToken(101) .setTimestampNanoseconds(1000) .setDurationNanoseconds(1000) .setLayerName("foo") .setPresentType("On-time Present") .setJankType("None") .setOnTimeFinish(true) .setGpuComposition(true) .setLayoutDepth(0)) .build() val model = TraceProcessorModel.Builder().apply { addAndroidFrameTimelineEvents(frameTimelineResult) }.build() assertThat(model.getAndroidFrameTimelineEvents()).containsExactly( AndroidFrameTimelineEvent(1, 101, 1, 2, 2, "foo", PerfettoTrace.FrameTimelineEvent.PresentType.PRESENT_ON_TIME, PerfettoTrace.FrameTimelineEvent.JankType.JANK_NONE, onTimeFinish = true, gpuComposition = true, layoutDepth = 0), AndroidFrameTimelineEvent(2, 102, 3, 4, 5, "foo", PerfettoTrace.FrameTimelineEvent.PresentType.PRESENT_LATE, PerfettoTrace.FrameTimelineEvent.JankType.JANK_APP_DEADLINE_MISSED, onTimeFinish = false, gpuComposition = true, layoutDepth = 1), AndroidFrameTimelineEvent(3, 103, 5, 6, 6, "foo", PerfettoTrace.FrameTimelineEvent.PresentType.PRESENT_EARLY, PerfettoTrace.FrameTimelineEvent.JankType.JANK_BUFFER_STUFFING, onTimeFinish = true, gpuComposition = true, layoutDepth = 2), AndroidFrameTimelineEvent(4, 104, 7, 8, 10, "foo", PerfettoTrace.FrameTimelineEvent.PresentType.PRESENT_DROPPED, PerfettoTrace.FrameTimelineEvent.JankType.JANK_UNKNOWN, onTimeFinish = true, gpuComposition = false, layoutDepth = 0), ).inOrder() } @Test fun addPowerCounters() { val powerCounters = TraceProcessor.PowerCounterTracksResult.newBuilder() .addCounter( TraceProcessor.Counter.newBuilder() .setName("power.rails.1") .addValue(TraceProcessor.CounterValue.newBuilder().setTimestampNanoseconds(1000).setValue(100.0)) .addValue(TraceProcessor.CounterValue.newBuilder().setTimestampNanoseconds(2000).setValue(200.0)) ) .addCounter( TraceProcessor.Counter.newBuilder() .setName("power.rails.2") .addValue(TraceProcessor.CounterValue.newBuilder().setTimestampNanoseconds(1000).setValue(100.0)) .addValue(TraceProcessor.CounterValue.newBuilder().setTimestampNanoseconds(2000).setValue(200.0)) ) .addCounter( TraceProcessor.Counter.newBuilder() .setName("batt.1") .addValue(TraceProcessor.CounterValue.newBuilder().setTimestampNanoseconds(1000).setValue(100.0)) .addValue(TraceProcessor.CounterValue.newBuilder().setTimestampNanoseconds(2000).setValue(200.0)) ) .addCounter( TraceProcessor.Counter.newBuilder() .setName("batt.2") .addValue(TraceProcessor.CounterValue.newBuilder().setTimestampNanoseconds(1000).setValue(100.0)) .addValue(TraceProcessor.CounterValue.newBuilder().setTimestampNanoseconds(2000).setValue(200.0)) ) .build() val model = TraceProcessorModel.Builder().apply { addPowerCounters(powerCounters) }.build() assertThat(model.getPowerRails()).containsExactly( CounterModel("power.rails.1", sortedMapOf(1L to 100.0, 2L to 200.0)), CounterModel("power.rails.2", sortedMapOf(1L to 100.0, 2L to 200.0))) assertThat(model.getBatteryDrain()).containsExactly( CounterModel("batt.1", sortedMapOf(1L to 100.0, 2L to 200.0)), CounterModel("batt.2", sortedMapOf(1L to 100.0, 2L to 200.0))) } @Test fun `grouping layers by phase adjusts depths`() { fun<O,B> constructorOf(builder: () -> B, build: B.() -> O): (B.() -> Unit) -> O = { builder().apply(it).build() } val layer = constructorOf(Layer::newBuilder, Layer.Builder::build) val phase = constructorOf(Phase::newBuilder, Phase.Builder::build) val frame = constructorOf(FrameEvent::newBuilder, FrameEvent.Builder::build) val displayPhase = phase { phaseName = "Display" addFrameEvent(frame { frameNumber = 1; depth = 0 }) addFrameEvent(frame { frameNumber = 2; depth = 1 }) } val layer1 = layer { addPhase(phase { phaseName = "Application" addFrameEvent(frame { frameNumber = 1; depth = 0 }) addFrameEvent(frame { frameNumber = 2; depth = 1 }) }) addPhase(displayPhase) } val layer2 = layer { addPhase(phase { phaseName = "Application" addFrameEvent(frame { frameNumber = 3; depth = 0 }) addFrameEvent(frame { frameNumber = 4; depth = 1 }) }) addPhase(displayPhase) } val layer3 = layer { addPhase(phase { phaseName = "Application" addFrameEvent(frame { frameNumber = 5; depth = 0 }) addFrameEvent(frame { frameNumber = 6; depth = 1 }) }) addPhase(displayPhase) } assertThat(listOf(layer1, layer2, layer3).groupedByPhase()).isEqualTo(listOf( phase { phaseName = "Application" addFrameEvent(frame { frameNumber = 1; depth = 0 }) addFrameEvent(frame { frameNumber = 2; depth = 1 }) addFrameEvent(frame { frameNumber = 3; depth = 2 }) addFrameEvent(frame { frameNumber = 4; depth = 3 }) addFrameEvent(frame { frameNumber = 5; depth = 4 }) addFrameEvent(frame { frameNumber = 6; depth = 5 }) }, displayPhase )) } private fun TraceProcessor.ProcessMetadataResult.Builder.addProcess(id: Long, name: String) : TraceProcessor.ProcessMetadataResult.ProcessMetadata.Builder { return this.addProcessBuilder().setId(id).setName(name) } private fun TraceProcessor.ProcessMetadataResult.ProcessMetadata.Builder.addThread(id: Long, name: String) : TraceProcessor.ProcessMetadataResult.ProcessMetadata.Builder { return this.addThread(TraceProcessor.ProcessMetadataResult.ThreadMetadata.newBuilder().setId(id).setName(name)) } private fun TraceProcessor.TraceEventsResult.Builder.addThread(id: Long): TraceProcessor.TraceEventsResult.ThreadTraceEvents.Builder { return this.addThreadBuilder().setThreadId(id) } private fun TraceProcessor.TraceEventsResult.ThreadTraceEvents.Builder.addEvent(id: Long, tsNs: Long, durNs: Long, name: String, parentId: Long = 0, depth: Int = 0) : TraceProcessor.TraceEventsResult.ThreadTraceEvents.Builder { this.addTraceEventBuilder() .setId(id) .setTimestampNanoseconds(tsNs) .setDurationNanoseconds(durNs) .setName(name) .setParentId(parentId) .setDepth(depth) return this } private fun TraceProcessor.SchedulingEventsResult.Builder.addSchedulingEvent( processId: Long, threadId: Long, cpu: Int, tsNs: Long, durNs: Long, endState: TraceProcessor.SchedulingEventsResult.SchedulingEvent.SchedulingState) { this.addSchedEventBuilder() .setProcessId(processId) .setThreadId(threadId) .setCpu(cpu) .setTimestampNanoseconds(tsNs) .setDurationNanoseconds(durNs) .setEndState(endState) } }
abstract class Abstract fun <D> create(fn: () -> D): D { return fn() } fun main() { create(::<!CREATING_AN_INSTANCE_OF_ABSTRACT_CLASS!>Abstract<!>) }
package cases.interfaces public interface BaseWithImpl { fun foo() = 42 } public interface DerivedWithImpl : BaseWithImpl { override fun foo(): Int { return super.foo() + 1 } } public interface DerivedWithoutImpl : BaseWithImpl
enum class Test { A, B, OTHER } fun peek() = Test.A fun box(): String { val x = when (val t1 = peek()) { Test.A -> { val y = peek() when (val t2 = y) { Test.A -> when (val t3 = peek()) { Test.A -> "OK" else -> "other 3" } else -> "other 2" } } else -> "other 1" } return x }
package org.jetbrains.dukat.tsmodel interface WithModifiersDeclaration { val modifiers: Set<ModifierDeclaration> fun hasDefaultModifier(): Boolean { return modifiers.contains(ModifierDeclaration.DEFAULT_KEYWORD) } fun hasExportModifier(): Boolean { return modifiers.contains(ModifierDeclaration.EXPORT_KEYWORD) } fun hasDeclareModifier(): Boolean { return modifiers.contains(ModifierDeclaration.DECLARE_KEYWORD) } }
package com.android.tools.idea.material.icons.common import com.android.tools.idea.material.icons.utils.MaterialIconsUtils import com.android.tools.idea.material.icons.utils.MaterialIconsUtils.MATERIAL_ICONS_PATH import com.android.tools.idea.material.icons.utils.MaterialIconsUtils.METADATA_FILE_NAME import com.android.utils.SdkUtils import java.net.URL /** * Provides a [URL] that is used to get the metadata file and then parse it. */ interface MaterialIconsMetadataUrlProvider { fun getMetadataUrl(): URL? } /** * The default implementation of [MaterialIconsMetadataUrlProvider], returns the [URL] for the bundled metadata file in Android Studio. */ class BundledMetadataUrlProvider : MaterialIconsMetadataUrlProvider { override fun getMetadataUrl(): URL? = javaClass.classLoader.getResource(MATERIAL_ICONS_PATH + METADATA_FILE_NAME) } /** * Returns the [URL] for the metadata file located in the .../Android/Sdk directory. * * @see MaterialIconsUtils.getIconsSdkTargetPath */ class SdkMetadataUrlProvider: MaterialIconsMetadataUrlProvider { override fun getMetadataUrl(): URL? { val metadataFilePath = MaterialIconsUtils.getIconsSdkTargetPath()?.resolve(METADATA_FILE_NAME) ?: return null return if (metadataFilePath.exists()) SdkUtils.fileToUrl(metadataFilePath) else null } }
@file:Suppress("DuplicatedCode") package org.jetbrains.kotlin.fir.declarations.impl import org.jetbrains.kotlin.KtSourceElement import org.jetbrains.kotlin.fir.FirImplementationDetail import org.jetbrains.kotlin.fir.FirModuleData import org.jetbrains.kotlin.fir.MutableOrEmptyList import org.jetbrains.kotlin.fir.builder.toMutableOrEmpty import org.jetbrains.kotlin.fir.contracts.FirContractDescription import org.jetbrains.kotlin.fir.declarations.* import org.jetbrains.kotlin.fir.expressions.FirAnnotation import org.jetbrains.kotlin.fir.expressions.FirBlock import org.jetbrains.kotlin.fir.references.FirControlFlowGraphReference import org.jetbrains.kotlin.fir.symbols.impl.FirNamedFunctionSymbol import org.jetbrains.kotlin.fir.types.ConeSimpleKotlinType import org.jetbrains.kotlin.fir.types.FirTypeRef import org.jetbrains.kotlin.fir.visitors.FirTransformer import org.jetbrains.kotlin.fir.visitors.FirVisitor import org.jetbrains.kotlin.fir.visitors.transformInplace import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedContainerSource @OptIn(FirImplementationDetail::class, ResolveStateAccess::class) internal class FirSimpleFunctionImpl( override val source: KtSourceElement?, resolvePhase: FirResolvePhase, override val moduleData: FirModuleData, override val origin: FirDeclarationOrigin, override val attributes: FirDeclarationAttributes, override var status: FirDeclarationStatus, override var returnTypeRef: FirTypeRef, override var receiverParameter: FirReceiverParameter?, override var deprecationsProvider: DeprecationsProvider, override val containerSource: DeserializedContainerSource?, override val dispatchReceiverType: ConeSimpleKotlinType?, override var contextReceivers: MutableOrEmptyList<FirContextReceiver>, override val valueParameters: MutableList<FirValueParameter>, override var body: FirBlock?, override var contractDescription: FirContractDescription?, override val name: Name, override val symbol: FirNamedFunctionSymbol, override var annotations: MutableOrEmptyList<FirAnnotation>, override val typeParameters: MutableList<FirTypeParameter>, ) : FirSimpleFunction() { override var controlFlowGraphReference: FirControlFlowGraphReference? = null init { symbol.bind(this) resolveState = resolvePhase.asResolveState() } override fun <R, D> acceptChildren(visitor: FirVisitor<R, D>, data: D) { status.accept(visitor, data) returnTypeRef.accept(visitor, data) receiverParameter?.accept(visitor, data) 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) } 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) contextReceivers.transformInplace(transformer, data) controlFlowGraphReference = controlFlowGraphReference?.transform(transformer, data) transformValueParameters(transformer, data) transformBody(transformer, data) transformContractDescription(transformer, data) transformAnnotations(transformer, data) transformTypeParameters(transformer, data) return this } override fun <D> transformStatus(transformer: FirTransformer<D>, data: D): FirSimpleFunctionImpl { status = status.transform(transformer, data) return this } override fun <D> transformReturnTypeRef(transformer: FirTransformer<D>, data: D): FirSimpleFunctionImpl { returnTypeRef = returnTypeRef.transform(transformer, data) return this } override fun <D> transformReceiverParameter(transformer: FirTransformer<D>, data: D): FirSimpleFunctionImpl { receiverParameter = receiverParameter?.transform(transformer, data) return this } override fun <D> transformValueParameters(transformer: FirTransformer<D>, data: D): FirSimpleFunctionImpl { valueParameters.transformInplace(transformer, data) return this } override fun <D> transformBody(transformer: FirTransformer<D>, data: D): FirSimpleFunctionImpl { body = body?.transform(transformer, data) return this } override fun <D> transformContractDescription(transformer: FirTransformer<D>, data: D): FirSimpleFunctionImpl { contractDescription = contractDescription?.transform(transformer, data) return this } override fun <D> transformAnnotations(transformer: FirTransformer<D>, data: D): FirSimpleFunctionImpl { annotations.transformInplace(transformer, data) return this } override fun <D> transformTypeParameters(transformer: FirTransformer<D>, data: D): FirSimpleFunctionImpl { typeParameters.transformInplace(transformer, data) return this } override fun replaceStatus(newStatus: FirDeclarationStatus) { status = newStatus } override fun replaceReturnTypeRef(newReturnTypeRef: FirTypeRef) { returnTypeRef = newReturnTypeRef } override fun replaceReceiverParameter(newReceiverParameter: FirReceiverParameter?) { receiverParameter = newReceiverParameter } override fun replaceDeprecationsProvider(newDeprecationsProvider: DeprecationsProvider) { deprecationsProvider = newDeprecationsProvider } override fun replaceContextReceivers(newContextReceivers: List<FirContextReceiver>) { contextReceivers = newContextReceivers.toMutableOrEmpty() } override fun replaceControlFlowGraphReference(newControlFlowGraphReference: FirControlFlowGraphReference?) { controlFlowGraphReference = newControlFlowGraphReference } override fun replaceValueParameters(newValueParameters: List<FirValueParameter>) { valueParameters.clear() valueParameters.addAll(newValueParameters) } override fun replaceBody(newBody: FirBlock?) { body = newBody } override fun replaceContractDescription(newContractDescription: FirContractDescription?) { contractDescription = newContractDescription } override fun replaceAnnotations(newAnnotations: List<FirAnnotation>) { annotations = newAnnotations.toMutableOrEmpty() } }
package org.jetbrains.kotlin.gradle.utils import kotlin.test.Test import kotlin.test.assertEquals class MergeWithTest { private fun Map<String, Set<Int>>.prettyStringForDiff() = entries .sortedBy { it.key } .joinToString("\n") { (key, setOfInts) -> "$key => ${setOfInts.sorted()}" } private fun assertEquals(expected: Map<String, Set<Int>>, actual: Map<String, Set<Int>>) { assertEquals(expected.prettyStringForDiff(), actual.prettyStringForDiff()) } private val sample = mapOf( "a" to setOf(1, 2), "b" to setOf(3, 4), "c" to emptySet(), ) @Test fun basicTest() { val a = mapOf( "a" to setOf(1, 2), "b" to setOf(3, 4) ) val b = mapOf( "b" to setOf(3, 5), "c" to setOf(6), "d" to emptySet(), ) val actual = a mergeWith b val expected = mapOf( "a" to setOf(1, 2), "b" to setOf(3, 4, 5), "c" to setOf(6), "d" to emptySet() ) assertEquals(expected, actual) } @Test fun mergeWithSelf() = assertEquals(sample, sample mergeWith sample) @Test fun mergeWithEmpty() { assertEquals(sample, emptyMap<String, Set<Int>>() mergeWith sample) assertEquals(sample, sample mergeWith emptyMap()) assertEquals(emptyMap(), emptyMap<String, Set<Int>>() mergeWith emptyMap()) } }
package com.android.tools.idea.naveditor.dialogs import com.android.SdkConstants.CLASS_PARCELABLE import com.android.ide.common.rendering.api.ResourceValue import com.android.resources.ResourceUrl import com.android.tools.idea.common.model.NlComponent import com.android.tools.idea.naveditor.model.argumentName import com.android.tools.idea.naveditor.model.defaultValue import com.android.tools.idea.naveditor.model.isArgument import com.android.tools.idea.naveditor.model.nullable import com.android.tools.idea.naveditor.model.setArgumentNameAndLog import com.android.tools.idea.naveditor.model.setDefaultValueAndLog import com.android.tools.idea.naveditor.model.setNullableAndLog import com.android.tools.idea.naveditor.model.setTypeAndLog import com.android.tools.idea.naveditor.model.typeAttr import com.android.tools.idea.res.FloatResources import com.android.tools.idea.res.resolve import com.android.tools.idea.uibuilder.model.createChild import com.google.common.annotations.VisibleForTesting import com.google.wireless.android.sdk.stats.NavEditorEvent import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.Messages import com.intellij.openapi.ui.ValidationInfo import com.intellij.openapi.util.Computable import com.intellij.psi.PsiEnumConstant import com.intellij.psi.PsiManager import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.util.ClassUtil import com.intellij.ui.MutableCollectionComboBoxModel import com.intellij.ui.SimpleListCellRenderer import com.intellij.ui.components.JBLabel import com.intellij.util.Functions import org.jetbrains.android.dom.navigation.NavigationSchema.TAG_ARGUMENT import org.jetbrains.kotlin.utils.doNothing import java.awt.CardLayout import java.awt.Dimension import javax.swing.Action import javax.swing.JComponent // open for testing class AddArgumentDialog( private val existingComponent: NlComponent?, private val parent: NlComponent, private val kotlinTreeClassChooserFactory: KotlinTreeClassChooserFactory = KotlinTreeClassChooserFactory.getInstance()) : DialogWrapper(false) { private var selectedType: Type = Type.values().first() private val defaultValueComboModel = MutableCollectionComboBoxModel<String>() private val psiManager = PsiManager.getInstance(parent.model.project) internal val parcelableClass = ClassUtil.findPsiClass(psiManager, CLASS_PARCELABLE)!! internal val serializableClass = ClassUtil.findPsiClass(psiManager, "java.io.Serializable")!! @VisibleForTesting val dialogUI = AddArgumentDialogUI() // open for testing @VisibleForTesting open var type: String? = null // Open for testing @VisibleForTesting open var defaultValue: String? get() = if (selectedType == Type.BOOLEAN || selectedType.isCustom || isArray) { dialogUI.myDefaultValueComboBox.selectedItem as String? } else { dialogUI.myDefaultValueTextField.text } set(defaultValue) = if (selectedType == Type.BOOLEAN || selectedType.isCustom || isArray) { dialogUI.myDefaultValueComboBox.setSelectedItem(defaultValue) } else { dialogUI.myDefaultValueTextField.text = defaultValue } @VisibleForTesting var isArray: Boolean get() = dialogUI.myArrayCheckBox.isSelected set(array) { dialogUI.myArrayCheckBox.isSelected = array } @VisibleForTesting var isNullable: Boolean get() = dialogUI.myNullableCheckBox.isSelected set(nullable) { dialogUI.myNullableCheckBox.isSelected = nullable } // Open for testing @VisibleForTesting open var name: String? get() = dialogUI.myNameTextField.text set(name) { dialogUI.myNameTextField.text = name } @VisibleForTesting enum class Type(val display: String, val attrValue: String?, val isCustom: Boolean = false, val supportsNullable: Boolean = false, val supportsArray: Boolean = true) { INFERRED("<inferred type>", null), INTEGER("Integer", "integer"), FLOAT("Float", "float"), LONG("Long", "long"), BOOLEAN("Boolean", "boolean"), STRING("String", "string", supportsNullable = true), REFERENCE("Resource Reference", "reference", supportsArray = false), CUSTOM_PARCELABLE("Custom Parcelable...", "custom_parcelable", isCustom = true, supportsNullable = true), CUSTOM_SERIALIZABLE("Custom Serializable...", "custom_serializable", isCustom = true, supportsNullable = true), CUSTOM_ENUM("Custom Enum...", "custom_enum", isCustom = true, supportsArray = false); override fun toString(): String { return display } } init { init() Type.values().forEach { dialogUI.myTypeComboBox.addItem(it) } dialogUI.myTypeComboBox.setRenderer(SimpleListCellRenderer.create( SimpleListCellRenderer.Customizer { label: JBLabel, value: Type, index: Int -> if (index == -1 && value.isCustom && selectedType == value) { label.text = type } else { label.text = value.display } } )) dialogUI.myTypeComboBox.isEditable = false dialogUI.myDefaultValueComboBox.model = defaultValueComboModel if (existingComponent != null) { name = existingComponent.argumentName val nullable = existingComponent.nullable isNullable = nullable != null && nullable val typeStr = existingComponent.typeAttr type = typeStr if (typeStr == null) { dialogUI.myTypeComboBox.setSelectedItem(Type.INFERRED) } else { var found = false if (typeStr.endsWith("[]")) isArray = true val typeStrNoSuffix = typeStr.removeSuffix("[]") for (type in Type.values()) { if (typeStrNoSuffix == type.attrValue) { selectedType = type dialogUI.myTypeComboBox.selectedItem = selectedType found = true break } } if (!found) { selectedType = ClassUtil.findPsiClassByJVMName(psiManager, typeStrNoSuffix)?.let { when { it.isEnum -> Type.CUSTOM_ENUM it.isInheritor(parcelableClass, true) -> Type.CUSTOM_PARCELABLE it.isInheritor(serializableClass, true) -> Type.CUSTOM_SERIALIZABLE else -> null } } ?: Type.CUSTOM_PARCELABLE dialogUI.myTypeComboBox.selectedItem = selectedType } } updateUi() defaultValue = existingComponent.defaultValue myOKAction.putValue(Action.NAME, "Update") title = "Update Argument" } else { (dialogUI.myDefaultValuePanel.layout as CardLayout).show(dialogUI.myDefaultValuePanel, "textDefaultValue") myOKAction.putValue(Action.NAME, "Add") title = "Add Argument" } dialogUI.myTypeComboBox.addActionListener { event -> if ("comboBoxChanged" == event.actionCommand) { newTypeSelected() } } dialogUI.myDefaultValueComboBox.renderer = SimpleListCellRenderer.create("No default value", Functions.id()) dialogUI.myArrayCheckBox.addActionListener { event -> type = updateArgType(type) updateUi() } dialogUI.myNullableCheckBox.addActionListener { event -> updateUi() } } private fun updateArgType(argType: String?) = argType?.let { it.removeSuffix("[]") + if (isArray) "[]" else "" } private fun newTypeSelected() { val selectedItem = dialogUI.myTypeComboBox.selectedItem as? Type if (selectedItem != null) { if (selectedItem.isCustom) { val project = parent.model.project val superType = when (dialogUI.myTypeComboBox.selectedItem) { Type.CUSTOM_PARCELABLE -> parcelableClass Type.CUSTOM_SERIALIZABLE -> serializableClass // we're using a class filter in createInheritanceClassChooser below for the Enum case, // as during manual tests the behavior was inconsistent when using Enum supertype Type.CUSTOM_ENUM -> null else -> throw IllegalStateException("Can never happen.") } val current = type?.removeSuffix("[]")?.let { ClassUtil.findPsiClass(psiManager, it) } val chooser = kotlinTreeClassChooserFactory.createKotlinTreeClassChooser("Select Class", project, GlobalSearchScope.allScope(project), superType, current) { aClass -> if (superType == null) aClass.isEnum else true } chooser.showDialog() val selection = chooser.selected if (selection != null) { type = updateArgType(ClassUtil.getJVMClassName(selection)) selectedType = selectedItem } else { dialogUI.myTypeComboBox.setSelectedItem(selectedType) } } else { type = updateArgType(selectedItem.attrValue) selectedType = selectedItem } } updateUi() } private fun updateUi() { val nullable = selectedType.supportsNullable || isArray dialogUI.myNullableCheckBox.isEnabled = nullable dialogUI.myNullableLabel.isEnabled = nullable if (!nullable) { dialogUI.myNullableCheckBox.isSelected = false } val supportsArray = selectedType.supportsArray dialogUI.myArrayCheckBox.isEnabled = supportsArray dialogUI.myArrayLabel.isEnabled = supportsArray if (!supportsArray) { dialogUI.myArrayCheckBox.isSelected = false } when { selectedType == Type.BOOLEAN && !isArray -> { (dialogUI.myDefaultValuePanel.layout as CardLayout).show(dialogUI.myDefaultValuePanel, "comboDefaultValue") defaultValueComboModel.update(listOf(null, "true", "false")) } selectedType == Type.CUSTOM_ENUM && !isArray -> { (dialogUI.myDefaultValuePanel.layout as CardLayout).show(dialogUI.myDefaultValuePanel, "comboDefaultValue") val list = ClassUtil.findPsiClass(psiManager, type.orEmpty()) ?.fields ?.filter { it is PsiEnumConstant } ?.map { it.name }?.toMutableList<String?>() ?: mutableListOf() list.add(null) if (isNullable) list.add("@null") defaultValueComboModel.update(list) } selectedType.isCustom || isArray -> { (dialogUI.myDefaultValuePanel.layout as CardLayout).show(dialogUI.myDefaultValuePanel, "comboDefaultValue") val list = mutableListOf<String?>(null) if (isNullable) list.add("@null") defaultValueComboModel.update(list) } else -> { dialogUI.myDefaultValueTextField.text = "" (dialogUI.myDefaultValuePanel.layout as CardLayout).show(dialogUI.myDefaultValuePanel, "textDefaultValue") } } dialogUI.myDefaultValueComboBox.isEnabled = defaultValueComboModel.size != 1 } override fun createCenterPanel(): JComponent { dialogUI.myContentPanel.minimumSize = Dimension(320,200) return dialogUI.myContentPanel } override fun createActions(): Array<Action> { return arrayOf(okAction, cancelAction) } public override fun doValidate(): ValidationInfo? { val name = name if (name.isNullOrEmpty()) { return ValidationInfo("Name must be set", dialogUI.myNameTextField) } if (parent.children.any { c -> c !== existingComponent && c.isArgument && c.argumentName == name }) { return ValidationInfo("Name must be unique", dialogUI.myNameTextField) } var newDefaultValue = defaultValue if (!newDefaultValue.isNullOrEmpty() && !isArray) { when (dialogUI.myTypeComboBox.selectedItem as Type) { Type.LONG -> { if (!newDefaultValue.endsWith("L")) { newDefaultValue += "L" } try { (newDefaultValue.substring(0, newDefaultValue.length - 1)).toLong() } catch (e: NumberFormatException) { return ValidationInfo("Long default values must be in the format '1234L'") } } Type.INTEGER -> { try { newDefaultValue.toInt() } catch (e: NumberFormatException) { return ValidationInfo("Default value must be an integer") } } Type.REFERENCE -> { val url = ResourceUrl.parse(newDefaultValue) ?: return ValidationInfo("Reference not correctly formatted") val resourceResolver = parent.model.configuration.resourceResolver if (resourceResolver != null) { ApplicationManager.getApplication().runReadAction(Computable<ResourceValue> { resourceResolver.resolve(url, parent.tagDeprecated) }) ?: return ValidationInfo("Resource does not exist") } } Type.FLOAT -> { if (!FloatResources.parseFloatAttribute(newDefaultValue, FloatResources.TypedValue(), false)) { try { newDefaultValue.toFloat() return null } catch (e: NumberFormatException) { return ValidationInfo("Default value must be an integer") } } } Type.INFERRED, Type.BOOLEAN, Type.STRING, Type.CUSTOM_PARCELABLE, Type.CUSTOM_SERIALIZABLE, Type.CUSTOM_ENUM -> doNothing() } } return null } fun save() { WriteCommandAction.runWriteCommandAction(parent.model.project) { val realComponent = existingComponent ?: parent.createChild(TAG_ARGUMENT) if (realComponent == null) { ApplicationManager.getApplication().invokeLater { Messages.showErrorDialog(parent.model.project, "Failed to create Argument!", "Error") } return@runWriteCommandAction } realComponent.setArgumentNameAndLog(name, NavEditorEvent.Source.PROPERTY_INSPECTOR) realComponent.setTypeAndLog(type, NavEditorEvent.Source.PROPERTY_INSPECTOR) realComponent.setNullableAndLog(isNullable, NavEditorEvent.Source.PROPERTY_INSPECTOR) var newDefaultValue = defaultValue if (!isArray && !newDefaultValue.isNullOrEmpty() && dialogUI.myTypeComboBox.selectedItem === Type.LONG && !newDefaultValue.endsWith("L")) { newDefaultValue += "L" } realComponent.setDefaultValueAndLog(newDefaultValue, NavEditorEvent.Source.PROPERTY_INSPECTOR) } } }
@file:JsModule("child_process") @file:Suppress("INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS") package child_process import kotlin.js.* import org.khronos.webgl.* import org.w3c.dom.* import org.w3c.dom.events.* import org.w3c.dom.parsing.* import org.w3c.dom.svg.* import org.w3c.dom.url.* import org.w3c.fetch.* import org.w3c.files.* import org.w3c.notifications.* import org.w3c.performance.* import org.w3c.workers.* import org.w3c.xhr.* external interface ChildProcess : events.EventEmitter { var stdin: Writable? get() = definedExternally set(value) = definedExternally var stdout: Readable? get() = definedExternally set(value) = definedExternally var stderr: Readable? get() = definedExternally set(value) = definedExternally var channel: Pipe? get() = definedExternally set(value) = definedExternally var stdio: dynamic /* JsTuple<Writable?, Readable?, Readable?, dynamic, dynamic> */ get() = definedExternally set(value) = definedExternally var killed: Boolean var pid: Number var connected: Boolean fun kill(signal: String? = definedExternally /* null */) fun send(message: Any, callback: ((error: Error?) -> Unit)? = definedExternally /* null */): Boolean fun send(message: Any, sendHandle: net.Socket? = definedExternally /* null */, callback: ((error: Error?) -> Unit)? = definedExternally /* null */): Boolean fun send(message: Any, sendHandle: net.Server? = definedExternally /* null */, callback: ((error: Error?) -> Unit)? = definedExternally /* null */): Boolean fun send(message: Any, sendHandle: net.Socket? = definedExternally /* null */, options: MessageOptions? = definedExternally /* null */, callback: ((error: Error?) -> Unit)? = definedExternally /* null */): Boolean fun send(message: Any, sendHandle: net.Server? = definedExternally /* null */, options: MessageOptions? = definedExternally /* null */, callback: ((error: Error?) -> Unit)? = definedExternally /* null */): Boolean fun disconnect() fun unref() fun ref() fun addListener(event: String, listener: (args: Array<Any>) -> Unit): ChildProcess /* this */ fun addListener(event: String /* "close" */, listener: (code: Number, signal: String) -> Unit): ChildProcess /* this */ fun addListener(event: String /* "disconnect" */, listener: () -> Unit): ChildProcess /* this */ fun addListener(event: String /* "error" */, listener: (err: Error) -> Unit): ChildProcess /* this */ fun addListener(event: String /* "exit" */, listener: (code: Number?, signal: String?) -> Unit): ChildProcess /* this */ fun addListener(event: String /* "message" */, listener: (message: Any, sendHandle: dynamic /* net.Socket | net.Server */) -> Unit): ChildProcess /* this */ fun emit(event: String, vararg args: Any): Boolean fun emit(event: Any, vararg args: Any): Boolean fun emit(event: String /* "close" */, code: Number, signal: String): Boolean fun emit(event: String /* "disconnect" */): Boolean fun emit(event: String /* "error" */, err: Error): Boolean fun emit(event: String /* "exit" */, code: Number?, signal: String?): Boolean fun emit(event: String /* "message" */, message: Any, sendHandle: net.Socket): Boolean fun emit(event: String /* "message" */, message: Any, sendHandle: net.Server): Boolean fun on(event: String, listener: (args: Array<Any>) -> Unit): ChildProcess /* this */ fun on(event: String /* "close" */, listener: (code: Number, signal: String) -> Unit): ChildProcess /* this */ fun on(event: String /* "disconnect" */, listener: () -> Unit): ChildProcess /* this */ fun on(event: String /* "error" */, listener: (err: Error) -> Unit): ChildProcess /* this */ fun on(event: String /* "exit" */, listener: (code: Number?, signal: String?) -> Unit): ChildProcess /* this */ fun on(event: String /* "message" */, listener: (message: Any, sendHandle: dynamic /* net.Socket | net.Server */) -> Unit): ChildProcess /* this */ fun once(event: String, listener: (args: Array<Any>) -> Unit): ChildProcess /* this */ fun once(event: String /* "close" */, listener: (code: Number, signal: String) -> Unit): ChildProcess /* this */ fun once(event: String /* "disconnect" */, listener: () -> Unit): ChildProcess /* this */ fun once(event: String /* "error" */, listener: (err: Error) -> Unit): ChildProcess /* this */ fun once(event: String /* "exit" */, listener: (code: Number?, signal: String?) -> Unit): ChildProcess /* this */ fun once(event: String /* "message" */, listener: (message: Any, sendHandle: dynamic /* net.Socket | net.Server */) -> Unit): ChildProcess /* this */ fun prependListener(event: String, listener: (args: Array<Any>) -> Unit): ChildProcess /* this */ fun prependListener(event: String /* "close" */, listener: (code: Number, signal: String) -> Unit): ChildProcess /* this */ fun prependListener(event: String /* "disconnect" */, listener: () -> Unit): ChildProcess /* this */ fun prependListener(event: String /* "error" */, listener: (err: Error) -> Unit): ChildProcess /* this */ fun prependListener(event: String /* "exit" */, listener: (code: Number?, signal: String?) -> Unit): ChildProcess /* this */ fun prependListener(event: String /* "message" */, listener: (message: Any, sendHandle: dynamic /* net.Socket | net.Server */) -> Unit): ChildProcess /* this */ fun prependOnceListener(event: String, listener: (args: Array<Any>) -> Unit): ChildProcess /* this */ fun prependOnceListener(event: String /* "close" */, listener: (code: Number, signal: String) -> Unit): ChildProcess /* this */ fun prependOnceListener(event: String /* "disconnect" */, listener: () -> Unit): ChildProcess /* this */ fun prependOnceListener(event: String /* "error" */, listener: (err: Error) -> Unit): ChildProcess /* this */ fun prependOnceListener(event: String /* "exit" */, listener: (code: Number?, signal: String?) -> Unit): ChildProcess /* this */ fun prependOnceListener(event: String /* "message" */, listener: (message: Any, sendHandle: dynamic /* net.Socket | net.Server */) -> Unit): ChildProcess /* this */ } external interface ChildProcessWithoutNullStreams : ChildProcess { var stdin: Writable var stdout: Readable var stderr: Readable override var stdio: dynamic /* JsTuple<Writable, Readable, Readable, dynamic, dynamic> */ get() = definedExternally set(value) = definedExternally } external interface ChildProcessByStdio<I : Writable?, O : Readable?, E : Readable?> : ChildProcess { var stdin: I var stdout: O var stderr: E override var stdio: dynamic /* JsTuple<I, O, E, dynamic, dynamic> */ get() = definedExternally set(value) = definedExternally } external interface MessageOptions { var keepOpen: Boolean? get() = definedExternally set(value) = definedExternally } external interface ProcessEnvOptions { var uid: Number? get() = definedExternally set(value) = definedExternally var gid: Number? get() = definedExternally set(value) = definedExternally var cwd: String? get() = definedExternally set(value) = definedExternally var env: NodeJS.ProcessEnv? get() = definedExternally set(value) = definedExternally } external interface CommonOptions : ProcessEnvOptions { var windowsHide: Boolean? get() = definedExternally set(value) = definedExternally var timeout: Number? get() = definedExternally set(value) = definedExternally } external interface SpawnOptions : CommonOptions { var argv0: String? get() = definedExternally set(value) = definedExternally var stdio: dynamic /* "pipe" | "ignore" | "inherit" | Array<dynamic /* "pipe" | "ipc" | "ignore" | "inherit" | Stream | Number | Nothing? | Nothing? */> */ get() = definedExternally set(value) = definedExternally var detached: Boolean? get() = definedExternally set(value) = definedExternally var shell: dynamic /* Boolean | String */ get() = definedExternally set(value) = definedExternally var windowsVerbatimArguments: Boolean? get() = definedExternally set(value) = definedExternally } external interface SpawnOptionsWithoutStdio : SpawnOptions { override var stdio: dynamic /* 'pipe' | Array<String?> */ get() = definedExternally set(value) = definedExternally } external interface SpawnOptionsWithStdioTuple<Stdin : dynamic, Stdout : dynamic, Stderr : dynamic> : SpawnOptions { override var stdio: dynamic /* JsTuple<Stdin, Stdout, Stderr> */ get() = definedExternally set(value) = definedExternally } external fun spawn(command: String, options: SpawnOptionsWithoutStdio? = definedExternally /* null */): ChildProcessWithoutNullStreams external fun spawn(command: String, options: SpawnOptionsWithStdioTuple<String?, String?, String?>): ChildProcessByStdio<Writable, Readable, Readable> external fun spawn(command: String, options: SpawnOptionsWithStdioTuple<String?, String?, dynamic /* 'inherit' | 'ignore' | Stream */>): ChildProcessByStdio<Writable, Readable, Nothing?> external fun spawn(command: String, options: SpawnOptionsWithStdioTuple<String?, dynamic /* 'inherit' | 'ignore' | Stream */, String?>): ChildProcessByStdio<Writable, Nothing?, Readable> external fun spawn(command: String, options: SpawnOptionsWithStdioTuple<dynamic /* 'inherit' | 'ignore' | Stream */, String?, String?>): ChildProcessByStdio<Nothing?, Readable, Readable> external fun spawn(command: String, options: SpawnOptionsWithStdioTuple<String?, dynamic /* 'inherit' | 'ignore' | Stream */, dynamic /* 'inherit' | 'ignore' | Stream */>): ChildProcessByStdio<Writable, Nothing?, Nothing?> external fun spawn(command: String, options: SpawnOptionsWithStdioTuple<dynamic /* 'inherit' | 'ignore' | Stream */, String?, dynamic /* 'inherit' | 'ignore' | Stream */>): ChildProcessByStdio<Nothing?, Readable, Nothing?> external fun spawn(command: String, options: SpawnOptionsWithStdioTuple<dynamic /* 'inherit' | 'ignore' | Stream */, dynamic /* 'inherit' | 'ignore' | Stream */, String?>): ChildProcessByStdio<Nothing?, Nothing?, Readable> external fun spawn(command: String, options: SpawnOptionsWithStdioTuple<dynamic /* 'inherit' | 'ignore' | Stream */, dynamic /* 'inherit' | 'ignore' | Stream */, dynamic /* 'inherit' | 'ignore' | Stream */>): ChildProcessByStdio<Nothing?, Nothing?, Nothing?> external fun spawn(command: String, options: SpawnOptions): ChildProcess external fun spawn(command: String, args: ReadonlyArray<String>? = definedExternally /* null */, options: SpawnOptionsWithoutStdio? = definedExternally /* null */): ChildProcessWithoutNullStreams external fun spawn(command: String, args: ReadonlyArray<String>, options: SpawnOptionsWithStdioTuple<String?, String?, String?>): ChildProcessByStdio<Writable, Readable, Readable> external fun spawn(command: String, args: ReadonlyArray<String>, options: SpawnOptionsWithStdioTuple<String?, String?, dynamic /* 'inherit' | 'ignore' | Stream */>): ChildProcessByStdio<Writable, Readable, Nothing?> external fun spawn(command: String, args: ReadonlyArray<String>, options: SpawnOptionsWithStdioTuple<String?, dynamic /* 'inherit' | 'ignore' | Stream */, String?>): ChildProcessByStdio<Writable, Nothing?, Readable> external fun spawn(command: String, args: ReadonlyArray<String>, options: SpawnOptionsWithStdioTuple<dynamic /* 'inherit' | 'ignore' | Stream */, String?, String?>): ChildProcessByStdio<Nothing?, Readable, Readable> external fun spawn(command: String, args: ReadonlyArray<String>, options: SpawnOptionsWithStdioTuple<String?, dynamic /* 'inherit' | 'ignore' | Stream */, dynamic /* 'inherit' | 'ignore' | Stream */>): ChildProcessByStdio<Writable, Nothing?, Nothing?> external fun spawn(command: String, args: ReadonlyArray<String>, options: SpawnOptionsWithStdioTuple<dynamic /* 'inherit' | 'ignore' | Stream */, String?, dynamic /* 'inherit' | 'ignore' | Stream */>): ChildProcessByStdio<Nothing?, Readable, Nothing?> external fun spawn(command: String, args: ReadonlyArray<String>, options: SpawnOptionsWithStdioTuple<dynamic /* 'inherit' | 'ignore' | Stream */, dynamic /* 'inherit' | 'ignore' | Stream */, String?>): ChildProcessByStdio<Nothing?, Nothing?, Readable> external fun spawn(command: String, args: ReadonlyArray<String>, options: SpawnOptionsWithStdioTuple<dynamic /* 'inherit' | 'ignore' | Stream */, dynamic /* 'inherit' | 'ignore' | Stream */, dynamic /* 'inherit' | 'ignore' | Stream */>): ChildProcessByStdio<Nothing?, Nothing?, Nothing?> external fun spawn(command: String, args: ReadonlyArray<String>, options: SpawnOptions): ChildProcess external interface ExecOptions : CommonOptions { var shell: String? get() = definedExternally set(value) = definedExternally var maxBuffer: Number? get() = definedExternally set(value) = definedExternally var killSignal: String? get() = definedExternally set(value) = definedExternally } external interface ExecOptionsWithStringEncoding : ExecOptions { var encoding: dynamic /* "ascii" | "utf8" | "utf-8" | "utf16le" | "ucs2" | "ucs-2" | "base64" | "latin1" | "binary" | "hex" */ get() = definedExternally set(value) = definedExternally } external interface ExecOptionsWithBufferEncoding : ExecOptions { var encoding: String? get() = definedExternally set(value) = definedExternally } external interface ExecException : Error { var cmd: String? get() = definedExternally set(value) = definedExternally var killed: Boolean? get() = definedExternally set(value) = definedExternally var code: Number? get() = definedExternally set(value) = definedExternally var signal: String? get() = definedExternally set(value) = definedExternally } external fun exec(command: String, callback: ((error: ExecException?, stdout: String, stderr: String) -> Unit)? = definedExternally /* null */): ChildProcess external interface `T$0` { var encoding: String? get() = definedExternally set(value) = definedExternally } external fun exec(command: String, options: `T$0` /* `T$0` & ExecOptions */, callback: ((error: ExecException?, stdout: Buffer, stderr: Buffer) -> Unit)? = definedExternally /* null */): ChildProcess external interface `T$1` { var encoding: dynamic /* "ascii" | "utf8" | "utf-8" | "utf16le" | "ucs2" | "ucs-2" | "base64" | "latin1" | "binary" | "hex" */ get() = definedExternally set(value) = definedExternally } external fun exec(command: String, options: `T$1` /* `T$1` & ExecOptions */, callback: ((error: ExecException?, stdout: String, stderr: String) -> Unit)? = definedExternally /* null */): ChildProcess external interface `T$2` { var encoding: String } external fun exec(command: String, options: `T$2` /* `T$2` & ExecOptions */, callback: ((error: ExecException?, stdout: dynamic /* String | Buffer */, stderr: dynamic /* String | Buffer */) -> Unit)? = definedExternally /* null */): ChildProcess external fun exec(command: String, options: ExecOptions, callback: ((error: ExecException?, stdout: String, stderr: String) -> Unit)? = definedExternally /* null */): ChildProcess external interface `T$3` { var encoding: String? get() = definedExternally set(value) = definedExternally } external fun exec(command: String, options: `T$3` /* `T$3` & ExecOptions */, callback: ((error: ExecException?, stdout: dynamic /* String | Buffer */, stderr: dynamic /* String | Buffer */) -> Unit)? = definedExternally /* null */): ChildProcess external interface PromiseWithChild<T> : Promise<T> { var child: ChildProcess } external interface ExecFileOptions : CommonOptions { var maxBuffer: Number? get() = definedExternally set(value) = definedExternally var killSignal: String? get() = definedExternally set(value) = definedExternally var windowsVerbatimArguments: Boolean? get() = definedExternally set(value) = definedExternally var shell: dynamic /* Boolean | String */ get() = definedExternally set(value) = definedExternally } external interface ExecFileOptionsWithStringEncoding : ExecFileOptions { var encoding: dynamic /* "ascii" | "utf8" | "utf-8" | "utf16le" | "ucs2" | "ucs-2" | "base64" | "latin1" | "binary" | "hex" */ get() = definedExternally set(value) = definedExternally } external interface ExecFileOptionsWithBufferEncoding : ExecFileOptions { var encoding: String? get() = definedExternally set(value) = definedExternally } external interface ExecFileOptionsWithOtherEncoding : ExecFileOptions { var encoding: String } external fun execFile(file: String): ChildProcess external fun execFile(file: String, options: `T$3` /* `T$3` & ExecFileOptions */): ChildProcess external fun execFile(file: String, args: ReadonlyArray<String>? = definedExternally /* null */): ChildProcess external fun execFile(file: String, args: ReadonlyArray<String>?, options: `T$3` /* `T$3` & ExecFileOptions */): ChildProcess external fun execFile(file: String, callback: (error: Error?, stdout: String, stderr: String) -> Unit): ChildProcess external fun execFile(file: String, args: ReadonlyArray<String>?, callback: (error: Error?, stdout: String, stderr: String) -> Unit): ChildProcess external fun execFile(file: String, options: ExecFileOptionsWithBufferEncoding, callback: (error: Error?, stdout: Buffer, stderr: Buffer) -> Unit): ChildProcess external fun execFile(file: String, args: ReadonlyArray<String>?, options: ExecFileOptionsWithBufferEncoding, callback: (error: Error?, stdout: Buffer, stderr: Buffer) -> Unit): ChildProcess external fun execFile(file: String, options: ExecFileOptionsWithStringEncoding, callback: (error: Error?, stdout: String, stderr: String) -> Unit): ChildProcess external fun execFile(file: String, args: ReadonlyArray<String>?, options: ExecFileOptionsWithStringEncoding, callback: (error: Error?, stdout: String, stderr: String) -> Unit): ChildProcess external fun execFile(file: String, options: ExecFileOptionsWithOtherEncoding, callback: (error: Error?, stdout: dynamic /* String | Buffer */, stderr: dynamic /* String | Buffer */) -> Unit): ChildProcess external fun execFile(file: String, args: ReadonlyArray<String>?, options: ExecFileOptionsWithOtherEncoding, callback: (error: Error?, stdout: dynamic /* String | Buffer */, stderr: dynamic /* String | Buffer */) -> Unit): ChildProcess external fun execFile(file: String, options: ExecFileOptions, callback: (error: Error?, stdout: String, stderr: String) -> Unit): ChildProcess external fun execFile(file: String, args: ReadonlyArray<String>?, options: ExecFileOptions, callback: (error: Error?, stdout: String, stderr: String) -> Unit): ChildProcess external fun execFile(file: String, options: `T$3` /* `T$3` & ExecFileOptions */, callback: ((error: Error?, stdout: dynamic /* String | Buffer */, stderr: dynamic /* String | Buffer */) -> Unit)?): ChildProcess external fun execFile(file: String, args: ReadonlyArray<String>?, options: `T$3` /* `T$3` & ExecFileOptions */, callback: ((error: Error?, stdout: dynamic /* String | Buffer */, stderr: dynamic /* String | Buffer */) -> Unit)?): ChildProcess external interface ForkOptions : ProcessEnvOptions { var execPath: String? get() = definedExternally set(value) = definedExternally var execArgv: Array<String>? get() = definedExternally set(value) = definedExternally var silent: Boolean? get() = definedExternally set(value) = definedExternally var stdio: dynamic /* "pipe" | "ignore" | "inherit" | Array<dynamic /* "pipe" | "ipc" | "ignore" | "inherit" | Stream | Number | Nothing? | Nothing? */> */ get() = definedExternally set(value) = definedExternally var detached: Boolean? get() = definedExternally set(value) = definedExternally var windowsVerbatimArguments: Boolean? get() = definedExternally set(value) = definedExternally } external fun fork(modulePath: String, args: ReadonlyArray<String>? = definedExternally /* null */, options: ForkOptions? = definedExternally /* null */): ChildProcess external interface SpawnSyncOptions : CommonOptions { var argv0: String? get() = definedExternally set(value) = definedExternally var input: dynamic /* String | Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array | Int8Array | Int16Array | Int32Array | Float32Array | Float64Array | DataView */ get() = definedExternally set(value) = definedExternally var stdio: dynamic /* "pipe" | "ignore" | "inherit" | Array<dynamic /* "pipe" | "ipc" | "ignore" | "inherit" | Stream | Number | Nothing? | Nothing? */> */ get() = definedExternally set(value) = definedExternally var killSignal: dynamic /* String | Number */ get() = definedExternally set(value) = definedExternally var maxBuffer: Number? get() = definedExternally set(value) = definedExternally var encoding: String? get() = definedExternally set(value) = definedExternally var shell: dynamic /* Boolean | String */ get() = definedExternally set(value) = definedExternally var windowsVerbatimArguments: Boolean? get() = definedExternally set(value) = definedExternally } external interface SpawnSyncOptionsWithStringEncoding : SpawnSyncOptions { var encoding: dynamic /* "ascii" | "utf8" | "utf-8" | "utf16le" | "ucs2" | "ucs-2" | "base64" | "latin1" | "binary" | "hex" */ get() = definedExternally set(value) = definedExternally } external interface SpawnSyncOptionsWithBufferEncoding : SpawnSyncOptions { var encoding: String } external interface SpawnSyncReturns<T> { var pid: Number var output: Array<String> var stdout: T var stderr: T var status: Number? get() = definedExternally set(value) = definedExternally var signal: String? get() = definedExternally set(value) = definedExternally var error: Error? get() = definedExternally set(value) = definedExternally } external fun spawnSync(command: String): SpawnSyncReturns<Buffer> external fun spawnSync(command: String, options: SpawnSyncOptionsWithStringEncoding? = definedExternally /* null */): SpawnSyncReturns<String> external fun spawnSync(command: String, options: SpawnSyncOptionsWithBufferEncoding? = definedExternally /* null */): SpawnSyncReturns<Buffer> external fun spawnSync(command: String, options: SpawnSyncOptions? = definedExternally /* null */): SpawnSyncReturns<Buffer> external fun spawnSync(command: String, args: ReadonlyArray<String>? = definedExternally /* null */, options: SpawnSyncOptionsWithStringEncoding? = definedExternally /* null */): SpawnSyncReturns<String> external fun spawnSync(command: String, args: ReadonlyArray<String>? = definedExternally /* null */, options: SpawnSyncOptionsWithBufferEncoding? = definedExternally /* null */): SpawnSyncReturns<Buffer> external fun spawnSync(command: String, args: ReadonlyArray<String>? = definedExternally /* null */, options: SpawnSyncOptions? = definedExternally /* null */): SpawnSyncReturns<Buffer> external interface ExecSyncOptions : CommonOptions { var input: dynamic /* String | Uint8Array */ get() = definedExternally set(value) = definedExternally var stdio: dynamic /* "pipe" | "ignore" | "inherit" | Array<dynamic /* "pipe" | "ipc" | "ignore" | "inherit" | Stream | Number | Nothing? | Nothing? */> */ get() = definedExternally set(value) = definedExternally var shell: String? get() = definedExternally set(value) = definedExternally var killSignal: dynamic /* String | Number */ get() = definedExternally set(value) = definedExternally var maxBuffer: Number? get() = definedExternally set(value) = definedExternally var encoding: String? get() = definedExternally set(value) = definedExternally } external interface ExecSyncOptionsWithStringEncoding : ExecSyncOptions { var encoding: dynamic /* "ascii" | "utf8" | "utf-8" | "utf16le" | "ucs2" | "ucs-2" | "base64" | "latin1" | "binary" | "hex" */ get() = definedExternally set(value) = definedExternally } external interface ExecSyncOptionsWithBufferEncoding : ExecSyncOptions { var encoding: String } external fun execSync(command: String): Buffer external fun execSync(command: String, options: ExecSyncOptionsWithStringEncoding? = definedExternally /* null */): String external fun execSync(command: String, options: ExecSyncOptionsWithBufferEncoding? = definedExternally /* null */): Buffer external fun execSync(command: String, options: ExecSyncOptions? = definedExternally /* null */): Buffer external interface ExecFileSyncOptions : CommonOptions { var input: dynamic /* String | Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array | Int8Array | Int16Array | Int32Array | Float32Array | Float64Array | DataView */ get() = definedExternally set(value) = definedExternally var stdio: dynamic /* "pipe" | "ignore" | "inherit" | Array<dynamic /* "pipe" | "ipc" | "ignore" | "inherit" | Stream | Number | Nothing? | Nothing? */> */ get() = definedExternally set(value) = definedExternally var killSignal: dynamic /* String | Number */ get() = definedExternally set(value) = definedExternally var maxBuffer: Number? get() = definedExternally set(value) = definedExternally var encoding: String? get() = definedExternally set(value) = definedExternally var shell: dynamic /* Boolean | String */ get() = definedExternally set(value) = definedExternally } external interface ExecFileSyncOptionsWithStringEncoding : ExecFileSyncOptions { var encoding: dynamic /* "ascii" | "utf8" | "utf-8" | "utf16le" | "ucs2" | "ucs-2" | "base64" | "latin1" | "binary" | "hex" */ get() = definedExternally set(value) = definedExternally } external interface ExecFileSyncOptionsWithBufferEncoding : ExecFileSyncOptions { var encoding: String } external fun execFileSync(command: String): Buffer external fun execFileSync(command: String, options: ExecFileSyncOptionsWithStringEncoding? = definedExternally /* null */): String external fun execFileSync(command: String, options: ExecFileSyncOptionsWithBufferEncoding? = definedExternally /* null */): Buffer external fun execFileSync(command: String, options: ExecFileSyncOptions? = definedExternally /* null */): Buffer external fun execFileSync(command: String, args: ReadonlyArray<String>? = definedExternally /* null */, options: ExecFileSyncOptionsWithStringEncoding? = definedExternally /* null */): String external fun execFileSync(command: String, args: ReadonlyArray<String>? = definedExternally /* null */, options: ExecFileSyncOptionsWithBufferEncoding? = definedExternally /* null */): Buffer external fun execFileSync(command: String, args: ReadonlyArray<String>? = definedExternally /* null */, options: ExecFileSyncOptions? = definedExternally /* null */): Buffer
package org.jetbrains.letsPlot.commons.intern.observable.property import org.jetbrains.letsPlot.commons.intern.function.Supplier import org.jetbrains.letsPlot.commons.intern.observable.event.EventHandler import org.jetbrains.letsPlot.commons.registration.Registration /** * Derived property based on a Supplier<Value> and a set of dependencies </Value> */ class SimpleDerivedProperty<ValueT>( private val mySupplier: Supplier<ValueT>, vararg deps: ReadableProperty<*> ) : BaseDerivedProperty<ValueT>(mySupplier.get()) { private val myDependencies: Array<ReadableProperty<*>> private var myRegistrations: Array<Registration>? = null override val propExpr: String get() { val result = StringBuilder() result.append("derived(") result.append(mySupplier) for (d in myDependencies) { result.append(", ") result.append(d.propExpr) } result.append(")") return result.toString() } init { // myDependencies = arrayOfNulls<ReadableProperty<*>>(deps.size) // System.arraycopy(deps, 0, myDependencies, 0, deps.size) myDependencies = arrayOf(*deps) } override fun doAddListeners() { myRegistrations = Array(myDependencies.size) { i -> register(myDependencies[i]) } // myRegistrations = arrayOfNulls<Registration>(myDependencies.size) // myRegistrations = arr // var i = 0 // val myDependenciesLength = myDependencies.size // while (i < myDependenciesLength) { // myRegistrations[i] = register<Any>(myDependencies[i]) // i++ // } } private fun <DependencyT> register(prop: ReadableProperty<DependencyT>): Registration { return prop.addHandler(object : EventHandler<PropertyChangeEvent<out DependencyT>> { override fun onEvent(event: PropertyChangeEvent<out DependencyT>) { somethingChanged() } }) } override fun doRemoveListeners() { for (r in myRegistrations!!) { r.remove() } myRegistrations = null } override fun doGet(): ValueT { return mySupplier.get() } }
package com.google.samples.apps.iosched.tv.ui.presenter import android.view.View import android.widget.TextView import androidx.leanback.widget.Presenter import androidx.recyclerview.widget.RecyclerView import com.google.samples.apps.iosched.tv.R /** * [DetailsDescriptionPresenter] creates and binds this session details view holder. */ class SessionDetailViewHolder(view: View?) : Presenter.ViewHolder(view) { val titleView: TextView val timeView: TextView val roomView: TextView val descriptionView: TextView val tagRecyclerView: RecyclerView init { val v = requireNotNull(view) titleView = v.findViewById(R.id.session_detail_title) timeView = v.findViewById(R.id.session_detail_time) roomView = v.findViewById(R.id.session_detail_room) descriptionView = v.findViewById(R.id.session_detail_description) tagRecyclerView = v.findViewById(R.id.tags) } }
package example.exampleSerializer09 import kotlinx.serialization.* import kotlinx.serialization.json.* import kotlinx.serialization.encoding.* import kotlinx.serialization.descriptors.* object ColorAsStringSerializer : KSerializer<Color> { override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("Color", PrimitiveKind.STRING) override fun serialize(encoder: Encoder, value: Color) { val string = value.rgb.toString(16).padStart(6, '0') encoder.encodeString(string) } override fun deserialize(decoder: Decoder): Color { val string = decoder.decodeString() return Color(string.toInt(16)) } } @Serializable(with = ColorAsStringSerializer::class) data class Color(val rgb: Int) @Serializable data class Settings(val background: Color, val foreground: Color) fun main() { val data = Settings(Color(0xffffff), Color(0)) val string = Json.encodeToString(data) println(string) require(Json.decodeFromString<Settings>(string) == data) }
package kotlinx.kover.features.jvm import kotlinx.kover.features.jvm.impl.OfflineInstrumenterImpl import kotlinx.kover.features.jvm.impl.wildcardsToRegex import java.util.* /** * A class for using features via Java calls. */ public object KoverFeatures { /** * Getting version of Kover used in these utilities. */ public val version: String = readVersion() /** * Converts a Kover [template] string to a regular expression string. *ё * Replaces characters `*` to `.*`, `#` to `[^.]*` and `?` to `.` regexp characters. * All special characters of regular expressions are also escaped. */ public fun koverWildcardToRegex(template: String): String { return template.wildcardsToRegex() } /** * Create instance to instrument already compiled class-files. * * @return instrumenter for offline instrumentation. */ public fun createOfflineInstrumenter(): OfflineInstrumenter { return OfflineInstrumenterImpl(false) } private fun readVersion(): String { var version = "unrecognized" // read version from file in resources try { KoverFeatures::class.java.classLoader.getResourceAsStream("kover.version").use { stream -> if (stream != null) { version = Scanner(stream).nextLine() } } } catch (e: Throwable) { // can't read } return version } }
@kotlin.SinceKotlin(version = "1.6") @kotlin.WasExperimental(markerClass = {kotlin.ExperimentalStdlibApi::class}) public inline fun <reified T> typeOf(): kotlin.reflect.KType @kotlin.SinceKotlin(version = "1.4") @kotlin.internal.LowPriorityInOverloadResolution public fun <T : kotlin.Any> kotlin.reflect.KClass<T>.cast(value: kotlin.Any?): T @kotlin.SinceKotlin(version = "1.9") @kotlin.js.ExperimentalJsReflectionCreateInstance public fun <T : kotlin.Any> kotlin.reflect.KClass<T>.createInstance(): T @kotlin.reflect.ExperimentalAssociatedObjects public inline fun <reified T : kotlin.Annotation> kotlin.reflect.KClass<*>.findAssociatedObject(): kotlin.Any? @kotlin.SinceKotlin(version = "1.4") @kotlin.internal.LowPriorityInOverloadResolution public fun <T : kotlin.Any> kotlin.reflect.KClass<T>.safeCast(value: kotlin.Any?): T? @kotlin.reflect.ExperimentalAssociatedObjects @kotlin.annotation.Retention(value = AnnotationRetention.BINARY) @kotlin.annotation.Target(allowedTargets = {AnnotationTarget.ANNOTATION_CLASS}) public final annotation class AssociatedObjectKey : kotlin.Annotation { public constructor AssociatedObjectKey() } @kotlin.RequiresOptIn(level = Level.ERROR) @kotlin.annotation.Retention(value = AnnotationRetention.BINARY) public final annotation class ExperimentalAssociatedObjects : kotlin.Annotation { public constructor ExperimentalAssociatedObjects() } public interface KCallable<out R> { @kotlin.internal.IntrinsicConstEvaluation public abstract val name: kotlin.String { get; } } public interface KClass<T : kotlin.Any> : kotlin.reflect.KClassifier { public abstract val qualifiedName: kotlin.String? { get; } public abstract val simpleName: kotlin.String? { get; } public abstract override operator fun equals(other: kotlin.Any?): kotlin.Boolean public abstract override fun hashCode(): kotlin.Int @kotlin.SinceKotlin(version = "1.1") public abstract fun isInstance(value: kotlin.Any?): kotlin.Boolean } @kotlin.SinceKotlin(version = "1.1") public interface KClassifier { } public interface KFunction<out R> : kotlin.reflect.KCallable<R>, kotlin.Function<R> { } public interface KMutableProperty<V> : kotlin.reflect.KProperty<V> { } public interface KMutableProperty0<V> : kotlin.reflect.KProperty0<V>, kotlin.reflect.KMutableProperty<V> { public abstract fun set(value: V): kotlin.Unit } public interface KMutableProperty1<T, V> : kotlin.reflect.KProperty1<T, V>, kotlin.reflect.KMutableProperty<V> { public abstract fun set(receiver: T, value: V): kotlin.Unit } public interface KMutableProperty2<D, E, V> : kotlin.reflect.KProperty2<D, E, V>, kotlin.reflect.KMutableProperty<V> { public abstract fun set(receiver1: D, receiver2: E, value: V): kotlin.Unit } public interface KProperty<out V> : kotlin.reflect.KCallable<V> { } public interface KProperty0<out V> : kotlin.reflect.KProperty<V>, () -> V { public abstract fun get(): V } public interface KProperty1<T, out V> : kotlin.reflect.KProperty<V>, (T) -> V { public abstract fun get(receiver: T): V } public interface KProperty2<D, E, out V> : kotlin.reflect.KProperty<V>, (D, E) -> V { public abstract fun get(receiver1: D, receiver2: E): V } public interface KType { @kotlin.SinceKotlin(version = "1.1") public abstract val arguments: kotlin.collections.List<kotlin.reflect.KTypeProjection> { get; } @kotlin.SinceKotlin(version = "1.1") public abstract val classifier: kotlin.reflect.KClassifier? { get; } public abstract val isMarkedNullable: kotlin.Boolean { get; } } @kotlin.SinceKotlin(version = "1.1") public interface KTypeParameter : kotlin.reflect.KClassifier { public abstract val isReified: kotlin.Boolean { get; } public abstract val name: kotlin.String { get; } public abstract val upperBounds: kotlin.collections.List<kotlin.reflect.KType> { get; } public abstract val variance: kotlin.reflect.KVariance { get; } } @kotlin.SinceKotlin(version = "1.1") public final data class KTypeProjection { public constructor KTypeProjection(variance: kotlin.reflect.KVariance?, type: kotlin.reflect.KType?) public final val type: kotlin.reflect.KType? { get; } public final val variance: kotlin.reflect.KVariance? { get; } public final operator fun component1(): kotlin.reflect.KVariance? public final operator fun component2(): kotlin.reflect.KType? public final fun copy(variance: kotlin.reflect.KVariance? = ..., type: kotlin.reflect.KType? = ...): kotlin.reflect.KTypeProjection public open override operator fun equals(other: kotlin.Any?): kotlin.Boolean public open override fun hashCode(): kotlin.Int public open override fun toString(): kotlin.String public companion object of KTypeProjection { public final val STAR: kotlin.reflect.KTypeProjection { get; } @kotlin.jvm.JvmStatic public final fun contravariant(type: kotlin.reflect.KType): kotlin.reflect.KTypeProjection @kotlin.jvm.JvmStatic public final fun covariant(type: kotlin.reflect.KType): kotlin.reflect.KTypeProjection @kotlin.jvm.JvmStatic public final fun invariant(type: kotlin.reflect.KType): kotlin.reflect.KTypeProjection } } @kotlin.SinceKotlin(version = "1.1") public final enum class KVariance : kotlin.Enum<kotlin.reflect.KVariance> { enum entry INVARIANT enum entry IN enum entry OUT }
package kotlinx.serialization.features import kotlinx.serialization.* import kotlinx.serialization.EncodeDefault.Mode.* import kotlinx.serialization.json.* import kotlin.test.* class SkipDefaultsTest { private val jsonDropDefaults = Json { encodeDefaults = false } private val jsonEncodeDefaults = Json { encodeDefaults = true } @Serializable data class Data(val bar: String, val foo: Int = 42) { var list: List<Int> = emptyList() val listWithSomething: List<Int> = listOf(1, 2, 3) } @Serializable data class DifferentModes( val a: String = "a", @EncodeDefault val b: String = "b", @EncodeDefault(ALWAYS) val c: String = "c", @EncodeDefault(NEVER) val d: String = "d" ) @Test fun serializeCorrectlyDefaults() { val d = Data("bar") assertEquals( """{"bar":"bar","foo":42,"list":[],"listWithSomething":[1,2,3]}""", jsonEncodeDefaults.encodeToString(Data.serializer(), d) ) } @Test fun serializeCorrectly() { val d = Data("bar", 100).apply { list = listOf(1, 2, 3) } assertEquals( """{"bar":"bar","foo":100,"list":[1,2,3]}""", jsonDropDefaults.encodeToString(Data.serializer(), d) ) } @Test fun serializeCorrectlyAndDropBody() { val d = Data("bar", 43) assertEquals("""{"bar":"bar","foo":43}""", jsonDropDefaults.encodeToString(Data.serializer(), d)) } @Test fun serializeCorrectlyAndDropAll() { val d = Data("bar") assertEquals("""{"bar":"bar"}""", jsonDropDefaults.encodeToString(Data.serializer(), d)) } @Test fun encodeDefaultsAnnotationWithFlag() { val data = DifferentModes() assertEquals("""{"a":"a","b":"b","c":"c"}""", jsonEncodeDefaults.encodeToString(data)) assertEquals("""{"b":"b","c":"c"}""", jsonDropDefaults.encodeToString(data)) } }
package org.jetbrains.kotlin.scripting.extensions import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtImportInfo import org.jetbrains.kotlin.resolve.ImportPath import org.jetbrains.kotlin.resolve.extensions.ExtraImportsProviderExtension import org.jetbrains.kotlin.scripting.definitions.ScriptDependenciesProvider import org.jetbrains.kotlin.scripting.definitions.runReadAction class ScriptExtraImportsProviderExtension : ExtraImportsProviderExtension { // initially copied from org.jetbrains.kotlin.resolve.lazy.FileScopeFactory.DefaultImportImpl, but kept separate to simplify dependencies // and allow easier extension private class ScriptExtraImportImpl(private val importPath: ImportPath) : KtImportInfo { override val isAllUnder: Boolean get() = importPath.isAllUnder override val importContent = KtImportInfo.ImportContent.FqNameBased(importPath.fqName) override val aliasName: String? get() = importPath.alias?.asString() override val importedFqName: FqName? get() = importPath.fqName } override fun getExtraImports(ktFile: KtFile): Collection<KtImportInfo> = ktFile.takeIf { runReadAction { it.isScript() } }?.let { file -> val refinedConfiguration = ScriptDependenciesProvider.getInstance(file.project) ?.getScriptConfiguration(file.originalFile as KtFile) refinedConfiguration?.defaultImports?.map { ScriptExtraImportImpl( ImportPath.fromString(it) ) } }.orEmpty() }
package org.jetbrains.kotlin.commonizer.mergedtree import com.intellij.util.containers.FactoryMap import org.jetbrains.kotlin.commonizer.ModulesProvider import org.jetbrains.kotlin.commonizer.ModulesProvider.CInteropModuleAttributes import org.jetbrains.kotlin.commonizer.cir.CirEntityId import org.jetbrains.kotlin.commonizer.cir.CirName import org.jetbrains.kotlin.commonizer.cir.CirPackageName import org.jetbrains.kotlin.commonizer.cir.CirProvided import org.jetbrains.kotlin.commonizer.mergedtree.CirProvidedClassifiers.Companion.FALLBACK_FORWARD_DECLARATION_CLASS import org.jetbrains.kotlin.commonizer.utils.* import org.jetbrains.kotlin.library.SerializedMetadata import org.jetbrains.kotlin.library.metadata.parsePackageFragment import org.jetbrains.kotlin.metadata.ProtoBuf import org.jetbrains.kotlin.metadata.deserialization.* import org.jetbrains.kotlin.serialization.deserialization.ProtoEnumFlags import org.jetbrains.kotlin.types.Variance internal class CirProvidedClassifiersByModules internal constructor( private val hasForwardDeclarations: Boolean, private val classifiers: Map<CirEntityId, CirProvided.Classifier>, ) : CirProvidedClassifiers { private val typeAliasesByUnderlyingTypes = run { CommonizerMap<CirEntityId, MutableList<CirEntityId>>().also { map -> classifiers.forEach { (id, classifier) -> if (classifier is CirProvided.TypeAlias) { val set = map.computeIfAbsent(classifier.underlyingType.classifierId) { ArrayList() } set.add(id) } } } } override fun hasClassifier(classifierId: CirEntityId) = if (classifierId.packageName.isUnderKotlinNativeSyntheticPackages) { hasForwardDeclarations } else { classifierId in classifiers } override fun findTypeAliasesWithUnderlyingType(underlyingClassifier: CirEntityId): List<CirEntityId> { return typeAliasesByUnderlyingTypes[underlyingClassifier].orEmpty() } override fun classifier(classifierId: CirEntityId) = classifiers[classifierId] ?: if (hasForwardDeclarations && classifierId.packageName.isUnderKotlinNativeSyntheticPackages) FALLBACK_FORWARD_DECLARATION_CLASS else null companion object { fun load(modulesProvider: ModulesProvider): CirProvidedClassifiers { val classifiers = CommonizerMap<CirEntityId, CirProvided.Classifier>() modulesProvider.moduleInfos.forEach { moduleInfo -> val metadata = modulesProvider.loadModuleMetadata(moduleInfo.name) readModule(metadata, classifiers::set) } if (classifiers.isEmpty()) return CirProvidedClassifiers.EMPTY return CirProvidedClassifiersByModules(false, classifiers) } /** * Will load *all* forward declarations provided by all modules into a flat [CirProvidedClassifiers]. * Note: This builds a union *not an intersection* of forward declarations. */ fun loadExportedForwardDeclarations(modulesProviders: List<ModulesProvider>): CirProvidedClassifiers { val classifiers = CommonizerMap<CirEntityId, CirProvided.Classifier>() modulesProviders.flatMap { moduleProvider -> moduleProvider.moduleInfos } .mapNotNull { moduleInfo -> moduleInfo.cInteropAttributes } .forEach { attrs -> readExportedForwardDeclarations(attrs, classifiers::set) } if (classifiers.isEmpty()) return CirProvidedClassifiers.EMPTY return CirProvidedClassifiersByModules(true, classifiers) } } } private fun readExportedForwardDeclarations( cInteropAttributes: CInteropModuleAttributes, consumer: (CirEntityId, CirProvided.Classifier) -> Unit ) { val exportedForwardDeclarations = cInteropAttributes.exportedForwardDeclarations if (exportedForwardDeclarations.isEmpty()) return val mainPackageName = CirPackageName.create(cInteropAttributes.mainPackage) exportedForwardDeclarations.forEach { classFqName -> // Class has synthetic package FQ name (cnames/objcnames). Need to transfer it to the main package. val syntheticPackageName = CirPackageName.create(classFqName.substringBeforeLast('.', missingDelimiterValue = "")) val className = CirName.create(classFqName.substringAfterLast('.')) val syntheticClassId = CirEntityId.create(syntheticPackageName, className) val aliasedClassId = CirEntityId.create(mainPackageName, className) val clazz = CirProvided.ExportedForwardDeclarationClass(syntheticClassId) consumer(syntheticClassId, clazz) consumer(aliasedClassId, clazz) } } private fun readModule(metadata: SerializedMetadata, consumer: (CirEntityId, CirProvided.Classifier) -> Unit) { for (i in metadata.fragmentNames.indices) { val packageFqName = metadata.fragmentNames[i] val packageFragments = metadata.fragments[i] val classProtosToRead = ClassProtosToRead() for (j in packageFragments.indices) { val packageFragmentProto = parsePackageFragment(packageFragments[j]) val classProtos: List<ProtoBuf.Class> = packageFragmentProto.class_List val typeAliasProtos: List<ProtoBuf.TypeAlias> = packageFragmentProto.`package`?.typeAliasList.orEmpty() if (classProtos.isEmpty() && typeAliasProtos.isEmpty()) continue val packageName = CirPackageName.create(packageFqName) val strings = NameResolverImpl(packageFragmentProto.strings, packageFragmentProto.qualifiedNames) classProtosToRead.addClasses(classProtos, strings) if (typeAliasProtos.isNotEmpty()) { val types = TypeTable(packageFragmentProto.`package`.typeTable) for (typeAliasProto in typeAliasProtos) { readTypeAlias(typeAliasProto, packageName, strings, types, consumer) } } } classProtosToRead.forEachClassInScope(parentClassId = null) { classEntry -> readClass(classEntry, classProtosToRead, typeParameterIndexOffset = 0, consumer) } } } private class ClassProtosToRead { data class ClassEntry( val classId: CirEntityId, val proto: ProtoBuf.Class, val strings: NameResolver ) // key = parent class ID (or NON_EXISTING_CLASSIFIER_ID for top-level classes) // value = class protos under this parent class (MutableList to preserve order of classes) private val groupedByParentClassId = FactoryMap.create<CirEntityId, MutableList<ClassEntry>> { ArrayList() } fun addClasses(classProtos: List<ProtoBuf.Class>, strings: NameResolver) { classProtos.forEach { classProto -> if (strings.isLocalClassName(classProto.fqName)) return@forEach val classId = CirEntityId.create(strings.getQualifiedClassName(classProto.fqName)) val parentClassId: CirEntityId = classId.getParentEntityId() ?: NON_EXISTING_CLASSIFIER_ID groupedByParentClassId.getValue(parentClassId) += ClassEntry(classId, classProto, strings) } } fun forEachClassInScope(parentClassId: CirEntityId?, block: (ClassEntry) -> Unit) { groupedByParentClassId[parentClassId ?: NON_EXISTING_CLASSIFIER_ID]?.forEach { classEntry -> block(classEntry) } } } private fun readClass( classEntry: ClassProtosToRead.ClassEntry, classProtosToRead: ClassProtosToRead, typeParameterIndexOffset: Int, consumer: (CirEntityId, CirProvided.Classifier) -> Unit ) { val (classId, classProto) = classEntry val typeParameterNameToIndex = HashMap<Int, Int>() val typeParameters = readTypeParameters( typeParameterProtos = classProto.typeParameterList, typeParameterIndexOffset = typeParameterIndexOffset, nameToIndexMapper = typeParameterNameToIndex::set ) val typeReadContext = TypeReadContext(classEntry.strings, TypeTable(classProto.typeTable), typeParameterNameToIndex) val supertypes = (classProto.supertypeList.map { readType(it, typeReadContext) } + classProto.supertypeIdList.map { readType(classProto.typeTable.getType(it), typeReadContext) }) .filterNot { type -> type is CirProvided.ClassType && type.classifierId == ANY_CLASS_ID } val visibility = ProtoEnumFlags.visibility(Flags.VISIBILITY.get(classProto.flags)) val kind = ProtoEnumFlags.classKind(Flags.CLASS_KIND.get(classProto.flags)) val clazz = CirProvided.RegularClass(typeParameters, supertypes, visibility, kind) consumer(classId, clazz) classProtosToRead.forEachClassInScope(parentClassId = classId) { nestedClassEntry -> readClass(nestedClassEntry, classProtosToRead, typeParameterIndexOffset = typeParameters.size + typeParameterIndexOffset, consumer) } } private inline fun readTypeAlias( typeAliasProto: ProtoBuf.TypeAlias, packageName: CirPackageName, strings: NameResolver, types: TypeTable, consumer: (CirEntityId, CirProvided.Classifier) -> Unit ) { val typeAliasId = CirEntityId.create(packageName, CirName.create(strings.getString(typeAliasProto.name))) val typeParameterNameToIndex = HashMap<Int, Int>() val typeParameters = readTypeParameters( typeParameterProtos = typeAliasProto.typeParameterList, typeParameterIndexOffset = 0, nameToIndexMapper = typeParameterNameToIndex::set ) val underlyingType = readType(typeAliasProto.underlyingType(types), TypeReadContext(strings, types, typeParameterNameToIndex)) val typeAlias = CirProvided.TypeAlias(typeParameters, underlyingType as CirProvided.ClassOrTypeAliasType) consumer(typeAliasId, typeAlias) } private inline fun readTypeParameters( typeParameterProtos: List<ProtoBuf.TypeParameter>, typeParameterIndexOffset: Int, nameToIndexMapper: (name: Int, id: Int) -> Unit = { _, _ -> } ): List<CirProvided.TypeParameter> = typeParameterProtos.compactMapIndexed { localIndex, typeParameterProto -> val index = localIndex + typeParameterIndexOffset val typeParameter = CirProvided.TypeParameter( index = index, variance = readVariance(typeParameterProto.variance) ) nameToIndexMapper(typeParameterProto.name, index) typeParameter } private class TypeReadContext( val strings: NameResolver, val types: TypeTable, private val _typeParameterNameToIndex: Map<Int, Int> ) { val typeParameterNameToIndex: (Int) -> Int = { name -> _typeParameterNameToIndex[name] ?: error("No type parameter index for ${strings.getString(name)}") } private val _typeParameterIdToIndex = HashMap<Int, Int>() val typeParameterIdToIndex: (Int) -> Int = { id -> _typeParameterIdToIndex.getOrPut(id) { _typeParameterIdToIndex.size } } } private fun readType(typeProto: ProtoBuf.Type, context: TypeReadContext): CirProvided.Type = with(typeProto.abbreviatedType(context.types) ?: typeProto) { when { hasClassName() -> { val classId = CirEntityId.create(context.strings.getQualifiedClassName(className)) val outerType = typeProto.outerType(context.types)?.let { outerType -> val outerClassType = readType(outerType, context) check(outerClassType is CirProvided.ClassType) { "Outer type of $classId is not a class: $outerClassType" } outerClassType } CirProvided.ClassType( classifierId = classId, outerType = outerType, arguments = readTypeArguments(argumentList, context), isMarkedNullable = nullable ) } hasTypeAliasName() -> CirProvided.TypeAliasType( classifierId = CirEntityId.create(context.strings.getQualifiedClassName(typeAliasName)), arguments = readTypeArguments(argumentList, context), isMarkedNullable = nullable ) hasTypeParameter() -> CirProvided.TypeParameterType( index = context.typeParameterIdToIndex(typeParameter), isMarkedNullable = nullable ) hasTypeParameterName() -> CirProvided.TypeParameterType( index = context.typeParameterNameToIndex(typeParameterName), isMarkedNullable = nullable ) else -> error("No classifier (class, type alias or type parameter) recorded for Type") } } private fun readTypeArguments(argumentProtos: List<ProtoBuf.Type.Argument>, context: TypeReadContext): List<CirProvided.TypeProjection> = argumentProtos.compactMap { argumentProto -> val variance = readVariance(argumentProto.projection!!) ?: return@compactMap CirProvided.StarTypeProjection val typeProto = argumentProto.type(context.types) ?: error("No type argument for non-STAR projection in Type") CirProvided.RegularTypeProjection( variance = variance, type = readType(typeProto, context) ) } @Suppress("NOTHING_TO_INLINE") private inline fun readVariance(varianceProto: ProtoBuf.TypeParameter.Variance): Variance = when (varianceProto) { ProtoBuf.TypeParameter.Variance.IN -> Variance.IN_VARIANCE ProtoBuf.TypeParameter.Variance.OUT -> Variance.OUT_VARIANCE ProtoBuf.TypeParameter.Variance.INV -> Variance.INVARIANT } @Suppress("NOTHING_TO_INLINE") private inline fun readVariance(varianceProto: ProtoBuf.Type.Argument.Projection): Variance? = when (varianceProto) { ProtoBuf.Type.Argument.Projection.IN -> Variance.IN_VARIANCE ProtoBuf.Type.Argument.Projection.OUT -> Variance.OUT_VARIANCE ProtoBuf.Type.Argument.Projection.INV -> Variance.INVARIANT ProtoBuf.Type.Argument.Projection.STAR -> null }
interface Option<T> class Some<T> : Option<T> class None<T> : Option<T> fun <T> bind(r: Option<T>): Option<T> { return if (r is Some) { // Ideally we should infer Option<T> here (see KT-10896) (if (true) None() else r) checkType { _<Option<T>>() } // Works correctly if (true) None() else r } else r } fun <T> bind2(r: Option<T>): Option<T> { return if (r is Some) { // Works correctly if (true) None<T>() else r } else r } fun <T, R> bind3(r: Option<T>): Option<T> { return <!RETURN_TYPE_MISMATCH!>if (r is Some) { // Diagnoses an error correctly if (true) None<R>() else r } else r<!> } fun <T> bindWhen(r: Option<T>): Option<T> { return when (r) { is Some -> { // Works correctly if (true) None() else r } else -> r } } interface SimpleOption class SimpleSome : SimpleOption class SimpleNone : SimpleOption fun bindNoGeneric(r: SimpleOption): SimpleOption { return if (r is SimpleSome) { (if (true) SimpleNone() else r) checkType { _<SimpleOption>() } if (true) SimpleNone() else r } else r }
package com.maddyhome.idea.vim.action.change.change import com.intellij.vim.annotations.CommandOrMotion import com.intellij.vim.annotations.Mode import com.maddyhome.idea.vim.action.motion.updown.MotionDownLess1FirstNonSpaceAction import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.VimCaret import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.command.Argument import com.maddyhome.idea.vim.command.Command import com.maddyhome.idea.vim.command.CommandFlags import com.maddyhome.idea.vim.command.CommandFlags.FLAG_NO_REPEAT_INSERT import com.maddyhome.idea.vim.command.OperatorArguments import com.maddyhome.idea.vim.handler.ChangeEditorActionHandler import com.maddyhome.idea.vim.helper.enumSetOf import java.util.* @CommandOrMotion(keys = ["S"], modes = [Mode.NORMAL]) public class ChangeLineAction : ChangeEditorActionHandler.ForEachCaret() { override val type: Command.Type = Command.Type.CHANGE override val flags: EnumSet<CommandFlags> = enumSetOf(FLAG_NO_REPEAT_INSERT) override fun execute( editor: VimEditor, caret: VimCaret, context: ExecutionContext, argument: Argument?, operatorArguments: OperatorArguments, ): Boolean { // `S` command is a synonym of `cc` val motion = MotionDownLess1FirstNonSpaceAction() val command = Command(1, motion, motion.type, motion.flags) return injector.changeGroup.changeMotion( editor, caret, context, Argument(command), operatorArguments, ) } }
package typescript import js.array.ReadonlyArray sealed external interface FileTextChanges { var fileName: String var textChanges: ReadonlyArray<TextChange> var isNewFile: Boolean? }
package org.jetbrains.kotlin.gradle.plugin.statistics import org.gradle.api.Project import org.gradle.api.logging.Logging import org.jetbrains.kotlin.gradle.plugin.statistics.old.Pre232IdeaKotlinBuildStatsMXBean import org.jetbrains.kotlin.gradle.plugin.statistics.old.Pre232IdeaKotlinBuildStatsBeanService import java.io.Closeable import java.lang.management.ManagementFactory import javax.management.MBeanServer import javax.management.ObjectName import javax.management.StandardMBean /** * A registry of Kotlin FUS services scoped to a project. * In general, we use only one instance of a service either it is a real service or a JMX wrapper. * However, we also register legacy variants of the services so previous IDEA versions could access them. * We must properly manage the lifecycle of such services. * * The implementation is not thread-safe! */ internal class KotlinBuildStatsServicesRegistry : Closeable { internal val logger = Logging.getLogger(this::class.java) private val services = hashMapOf<String, KotlinBuildStatsBeanService>() /** * Registers the Kotlin build stats services for the given project. * * The registry must be closed at the end of the usage. */ fun registerServices(project: Project) { val mbs: MBeanServer = ManagementFactory.getPlatformMBeanServer() registerStatsService( mbs, DefaultKotlinBuildStatsBeanService(project, getBeanName(DEFAULT_SERVICE_QUALIFIER)), KotlinBuildStatsMXBean::class.java, DEFAULT_SERVICE_QUALIFIER ) // to support backward compatibility with Idea before version 232 registerStatsService( mbs, Pre232IdeaKotlinBuildStatsBeanService(project, getBeanName(LEGACY_SERVICE_QUALIFIER)), Pre232IdeaKotlinBuildStatsMXBean::class.java, LEGACY_SERVICE_QUALIFIER ) } fun recordBuildStart(buildId: String) { services.forEach { it.value.recordBuildStart(buildId) } } private fun <T : KotlinBuildStatsBeanService> registerStatsService( mbs: MBeanServer, service: T, beanInterfaceType: Class<in T>, qualifier: String, ) { val beanName = getBeanName(qualifier) val loggedServiceName = "${KotlinBuildStatsBeanService::class.java}" + if (qualifier.isNotEmpty()) "_$qualifier" else "" if (!mbs.isRegistered(beanName)) { mbs.registerMBean(StandardMBean(service, beanInterfaceType), beanName) services[qualifier] = service logger.debug("Instantiated $loggedServiceName: new instance $service") } else { logger.debug("$loggedServiceName is already instantiated in another classpath.") } } /** * Unregisters all the registered JMX services and may release other resources allocated by a service. */ override fun close() { for (service in services.values) { service.close() } services.clear() } companion object { private const val JXM_BEAN_BASE_NAME = "org.jetbrains.kotlin.gradle.plugin.statistics:type=StatsService" // Do not rename this bean otherwise compatibility with the older Kotlin Gradle Plugins would be lost private const val LEGACY_SERVICE_QUALIFIER = "" // Update name when API changed internal const val DEFAULT_SERVICE_QUALIFIER = "v2" internal fun getBeanName(qualifier: String) = ObjectName(JXM_BEAN_BASE_NAME + if (qualifier.isNotEmpty()) ",name=$qualifier" else "") } }
@file:Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE") package test import kotlin.contracts.* fun twoReturnsValue(b: Boolean) { contract { returns(true) implies b returns(false) implies (!b) } } fun threeReturnsValue(b: Boolean) { contract { returnsNotNull() implies (b != null) returns(true) implies (b) returns(false) implies (!b) } } fun returnsAndFinished(b: Boolean) { contract { returns(true) implies (b) returns() implies (b != null) returns(false) implies (!b) } } fun returnsAndCalls(b: Boolean, block: () -> Unit) { contract { returns(false) implies (!b) callsInPlace(block) returns(true) implies (b) } } fun severalCalls(x: () -> Unit, y: () -> Unit) { contract { callsInPlace(x, InvocationKind.AT_MOST_ONCE) callsInPlace(y, InvocationKind.AT_LEAST_ONCE) } }
fun test() { run {<!RETURN_NOT_ALLOWED!>return<!>} run {} } fun test2() { run {<!RETURN_NOT_ALLOWED!>return@test2<!>} run {} } fun test3() { fun test4() { run {<!RETURN_NOT_ALLOWED!>return@test3<!>} run {} } } fun <T> run(f: () -> T): T { return f() }
package org.jetbrains.kotlin.codegen.optimization import org.jetbrains.kotlin.builtins.PrimitiveType import org.jetbrains.kotlin.codegen.AsmUtil import org.jetbrains.kotlin.codegen.optimization.common.* import org.jetbrains.kotlin.codegen.optimization.fixStack.peek import org.jetbrains.kotlin.codegen.optimization.fixStack.top import org.jetbrains.kotlin.codegen.optimization.transformer.MethodTransformer import org.jetbrains.kotlin.resolve.jvm.AsmTypes import org.jetbrains.org.objectweb.asm.Opcodes import org.jetbrains.org.objectweb.asm.Type import org.jetbrains.org.objectweb.asm.tree.* import org.jetbrains.org.objectweb.asm.tree.analysis.BasicValue import org.jetbrains.org.objectweb.asm.tree.analysis.Frame class CapturedVarsOptimizationMethodTransformer : MethodTransformer() { override fun transform(internalClassName: String, methodNode: MethodNode) { Transformer(internalClassName, methodNode).run() } // Tracks proper usages of objects corresponding to captured variables. // // The 'kotlin.jvm.internal.Ref.*' instance can be replaced with a local variable, if // * it is created inside a current method; // * the only operations on it are ALOAD, ASTORE, DUP, POP, GETFIELD element, PUTFIELD element. // // Note that for code that doesn't create Ref objects explicitly these conditions are true, // unless the Ref object escapes to a local class constructor (including local classes for lambdas). // private class CapturedVarDescriptor(val newInsn: TypeInsnNode, val refType: Type, val valueType: Type) : ReferenceValueDescriptor { var hazard = false var initCallInsn: MethodInsnNode? = null var localVar: LocalVariableNode? = null var localVarIndex = -1 val wrapperInsns: MutableCollection<AbstractInsnNode> = LinkedHashSet() val getFieldInsns: MutableCollection<FieldInsnNode> = LinkedHashSet() val putFieldInsns: MutableCollection<FieldInsnNode> = LinkedHashSet() override fun onUseAsTainted() { hazard = true } fun canRewrite() = !hazard && initCallInsn != null } private class Transformer(private val internalClassName: String, private val methodNode: MethodNode) { private val refValues = ArrayList<CapturedVarDescriptor>() private val refValuesByNewInsn = LinkedHashMap<TypeInsnNode, CapturedVarDescriptor>() fun run() { createRefValues() if (refValues.isEmpty()) return val frames = analyze(internalClassName, methodNode, Interpreter()) trackPops(frames) assignLocalVars(frames) for (refValue in refValues) { if (refValue.canRewrite()) { rewriteRefValue(refValue) } } methodNode.removeEmptyCatchBlocks() methodNode.removeUnusedLocalVariables() } private fun AbstractInsnNode.getIndex() = methodNode.instructions.indexOf(this) private fun createRefValues() { for (insn in methodNode.instructions.asSequence()) { if (insn.opcode == Opcodes.NEW && insn is TypeInsnNode) { val type = Type.getObjectType(insn.desc) if (AsmTypes.isSharedVarType(type)) { val valueType = REF_TYPE_TO_ELEMENT_TYPE[type.internalName] ?: continue val refValue = CapturedVarDescriptor(insn, type, valueType) refValues.add(refValue) refValuesByNewInsn[insn] = refValue } } } } private inner class Interpreter : ReferenceTrackingInterpreter() { override fun newOperation(insn: AbstractInsnNode): BasicValue = refValuesByNewInsn[insn]?.let { ProperTrackedReferenceValue(it.refType, it) } ?: super.newOperation(insn) override fun processRefValueUsage(value: TrackedReferenceValue, insn: AbstractInsnNode, position: Int) { for (descriptor in value.descriptors) { if (descriptor !is CapturedVarDescriptor) throw AssertionError("Unexpected descriptor: $descriptor") when { insn.opcode == Opcodes.DUP -> descriptor.wrapperInsns.add(insn) insn.opcode == Opcodes.ALOAD -> descriptor.wrapperInsns.add(insn) insn.opcode == Opcodes.ASTORE -> descriptor.wrapperInsns.add(insn) insn.opcode == Opcodes.GETFIELD && insn is FieldInsnNode && insn.name == REF_ELEMENT_FIELD && position == 0 -> descriptor.getFieldInsns.add(insn) insn.opcode == Opcodes.PUTFIELD && insn is FieldInsnNode && insn.name == REF_ELEMENT_FIELD && position == 0 -> descriptor.putFieldInsns.add(insn) insn.opcode == Opcodes.INVOKESPECIAL && insn is MethodInsnNode && insn.name == INIT_METHOD_NAME && position == 0 -> if (descriptor.initCallInsn != null && descriptor.initCallInsn != insn) descriptor.hazard = true else descriptor.initCallInsn = insn else -> descriptor.hazard = true } } } } private fun trackPops(frames: Array<out Frame<BasicValue>?>) { for ((i, insn) in methodNode.instructions.asSequence().withIndex()) { val frame = frames[i] ?: continue when (insn.opcode) { Opcodes.POP -> { frame.top()?.getCapturedVarOrNull()?.run { wrapperInsns.add(insn) } } Opcodes.POP2 -> { val top = frame.top() if (top?.size == 1) { top.getCapturedVarOrNull()?.hazard = true frame.peek(1)?.getCapturedVarOrNull()?.hazard = true } } } } } private fun BasicValue.getCapturedVarOrNull(): CapturedVarDescriptor? = (this as? ProperTrackedReferenceValue)?.descriptor as? CapturedVarDescriptor private fun assignLocalVars(frames: Array<out Frame<BasicValue>?>) { for (localVar in methodNode.localVariables) { val type = Type.getType(localVar.desc) if (!AsmTypes.isSharedVarType(type)) continue val startFrame = frames[localVar.start.getIndex()] ?: continue val refValue = startFrame.getLocal(localVar.index) as? ProperTrackedReferenceValue ?: continue val descriptor = refValue.descriptor as? CapturedVarDescriptor ?: continue if (descriptor.hazard) continue if (descriptor.localVar == null) { descriptor.localVar = localVar } else { descriptor.hazard = true } } for (refValue in refValues) { if (refValue.hazard) continue if (refValue.localVar == null || refValue.valueType.size != 1) { refValue.localVarIndex = methodNode.maxLocals methodNode.maxLocals += refValue.valueType.size } else { refValue.localVarIndex = refValue.localVar!!.index } } } private fun LocalVariableNode.findCleanInstructions() = InsnSequence(methodNode.instructions).dropWhile { it != start }.takeWhile { it != end }.filter { it is VarInsnNode && it.opcode == Opcodes.ASTORE && it.`var` == index && it.previous?.opcode == Opcodes.ACONST_NULL } // Be careful to not remove instructions that are the only instruction for a line number. That will // break debugging. If the previous instruction is a line number and the following instruction is // a label followed by a line number, insert a nop instead of deleting the instruction. private fun InsnList.removeOrReplaceByNop(insn: AbstractInsnNode) { if (insn.previous is LineNumberNode && insn.next is LabelNode && insn.next.next is LineNumberNode) { set(insn, InsnNode(Opcodes.NOP)) } else { remove(insn) } } private fun rewriteRefValue(capturedVar: CapturedVarDescriptor) { methodNode.instructions.run { val loadOpcode = capturedVar.valueType.getOpcode(Opcodes.ILOAD) val storeOpcode = capturedVar.valueType.getOpcode(Opcodes.ISTORE) val localVar = capturedVar.localVar if (localVar != null) { if (capturedVar.putFieldInsns.none { it.getIndex() < localVar.start.getIndex() }) { // variable needs to be initialized before its live range can begin insertBefore(capturedVar.newInsn, InsnNode(AsmUtil.defaultValueOpcode(capturedVar.valueType))) insertBefore(capturedVar.newInsn, VarInsnNode(storeOpcode, capturedVar.localVarIndex)) } for (insn in localVar.findCleanInstructions()) { // after visiting block codegen tries to delete all allocated references: // see ExpressionCodegen.addLeaveTaskToRemoveLocalVariableFromFrameMap if (storeOpcode == Opcodes.ASTORE) { set(insn.previous, InsnNode(AsmUtil.defaultValueOpcode(capturedVar.valueType))) } else { remove(insn.previous) remove(insn) } } localVar.index = capturedVar.localVarIndex localVar.desc = capturedVar.valueType.descriptor localVar.signature = null } remove(capturedVar.newInsn) remove(capturedVar.initCallInsn!!) capturedVar.wrapperInsns.forEach { removeOrReplaceByNop(it) } capturedVar.getFieldInsns.forEach { set(it, VarInsnNode(loadOpcode, capturedVar.localVarIndex)) } capturedVar.putFieldInsns.forEach { set(it, VarInsnNode(storeOpcode, capturedVar.localVarIndex)) } } } } } internal const val REF_ELEMENT_FIELD = "element" internal const val INIT_METHOD_NAME = "<init>" internal val REF_TYPE_TO_ELEMENT_TYPE = HashMap<String, Type>().apply { put(AsmTypes.OBJECT_REF_TYPE.internalName, AsmTypes.OBJECT_TYPE) PrimitiveType.entries.forEach { put(AsmTypes.sharedTypeForPrimitive(it).internalName, AsmTypes.valueTypeForPrimitive(it)) } }
package node.v8 sealed external interface HeapCodeStatistics { var code_and_metadata_size: Double var bytecode_and_metadata_size: Double var external_script_source_size: Double }
package org.jetbrains.kotlin.js.test.utils import org.jetbrains.kotlin.config.CompilerConfiguration import org.jetbrains.kotlin.ir.backend.js.WholeWorldStageController import org.jetbrains.kotlin.ir.backend.js.ic.* import org.jetbrains.kotlin.ir.backend.js.moduleName import org.jetbrains.kotlin.ir.backend.js.utils.serialization.serializeTo import org.jetbrains.kotlin.ir.backend.js.utils.serialization.deserializeJsIrProgramFragment import org.jetbrains.kotlin.ir.declarations.impl.IrFactoryImplForJsIC import org.jetbrains.kotlin.js.test.handlers.JsBoxRunner import org.jetbrains.kotlin.konan.properties.propertyList import org.jetbrains.kotlin.library.KLIB_PROPERTY_DEPENDS import org.jetbrains.kotlin.library.KotlinLibrary import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.test.directives.JsEnvironmentConfigurationDirectives import org.jetbrains.kotlin.test.model.TestModule import org.jetbrains.kotlin.test.services.* import org.jetbrains.kotlin.test.services.configuration.JsEnvironmentConfigurator import java.io.ByteArrayOutputStream import java.io.File private class TestArtifactCache(val moduleName: String, val binaryAsts: MutableMap<String, ByteArray> = mutableMapOf()) { fun fetchArtifacts(): ModuleArtifact { return ModuleArtifact( moduleName = moduleName, fileArtifacts = binaryAsts.entries.map { SrcFileArtifact( srcFilePath = it.key, // TODO: It will be better to use saved fragments, but it doesn't work // Merger.merge() + JsNode.resolveTemporaryNames() modify fragments, // therefore the sequential calls produce different results fragments = deserializeJsIrProgramFragment(it.value) ) } ) } } class JsIrIncrementalDataProvider(private val testServices: TestServices) : TestService { private val fullRuntimeKlib = testServices.standardLibrariesPathProvider.fullJsStdlib() private val defaultRuntimeKlib = testServices.standardLibrariesPathProvider.defaultJsStdlib() private val kotlinTestKLib = testServices.standardLibrariesPathProvider.kotlinTestJsKLib() private val predefinedKlibHasIcCache = mutableMapOf<String, TestArtifactCache?>( fullRuntimeKlib.absolutePath to null, kotlinTestKLib.absolutePath to null, defaultRuntimeKlib.absolutePath to null ) private val icCache: MutableMap<String, TestArtifactCache> = mutableMapOf() fun getCaches() = icCache.map { it.value.fetchArtifacts() } fun getCacheForModule(module: TestModule): Map<String, ByteArray> { val path = JsEnvironmentConfigurator.getKlibArtifactFile(testServices, module.name) val canonicalPath = path.canonicalPath val moduleCache = icCache[canonicalPath] ?: error("No cache found for $path") val oldBinaryAsts = mutableMapOf<String, ByteArray>() for (testFile in module.files) { if (JsEnvironmentConfigurationDirectives.RECOMPILE in testFile.directives) { val fileName = "/${testFile.name}" oldBinaryAsts[fileName] = moduleCache.binaryAsts[fileName] ?: error("No AST found for $fileName") moduleCache.binaryAsts.remove(fileName) } } return oldBinaryAsts } private fun recordIncrementalDataForRuntimeKlib(module: TestModule) { val runtimeKlibPath = JsEnvironmentConfigurator.getRuntimePathsForModule(module, testServices) val libs = runtimeKlibPath.map { val descriptor = testServices.libraryProvider.getDescriptorByPath(it) testServices.libraryProvider.getCompiledLibraryByDescriptor(descriptor) } val configuration = testServices.compilerConfigurationProvider.getCompilerConfiguration(module) val mainArguments = JsEnvironmentConfigurator.getMainCallParametersForModule(module) .run { if (shouldBeGenerated()) arguments() else null } runtimeKlibPath.forEach { recordIncrementalData(it, null, libs, configuration, mainArguments) } } fun recordIncrementalData(module: TestModule, library: KotlinLibrary) { recordIncrementalDataForRuntimeKlib(module) val dirtyFiles = module.files.map { "/${it.relativePath}" } val path = JsEnvironmentConfigurator.getKlibArtifactFile(testServices, module.name).path val configuration = testServices.compilerConfigurationProvider.getCompilerConfiguration(module) val mainArguments = JsEnvironmentConfigurator.getMainCallParametersForModule(module) .run { if (shouldBeGenerated()) arguments() else null } val allDependencies = JsEnvironmentConfigurator.getAllRecursiveLibrariesFor(module, testServices).keys.toList() recordIncrementalData( path, dirtyFiles, allDependencies + library, configuration, mainArguments, ) } private fun recordIncrementalData( path: String, dirtyFiles: List<String>?, allDependencies: List<KotlinLibrary>, configuration: CompilerConfiguration, mainArguments: List<String>?, ) { val canonicalPath = File(path).canonicalPath val predefinedModuleCache = predefinedKlibHasIcCache[canonicalPath] if (predefinedModuleCache != null) { icCache[canonicalPath] = predefinedModuleCache return } val libs = allDependencies.associateBy { File(it.libraryFile.path).canonicalPath } val nameToKotlinLibrary: Map<String, KotlinLibrary> = libs.values.associateBy { it.moduleName } val dependencyGraph = libs.values.associateWith { it.manifestProperties.propertyList(KLIB_PROPERTY_DEPENDS, escapeInQuotes = true).map { depName -> nameToKotlinLibrary[depName] ?: error("No Library found for $depName") } } val currentLib = libs[File(canonicalPath).canonicalPath] ?: error("Expected library at $canonicalPath") val testPackage = extractTestPackage(testServices) val (mainModuleIr, rebuiltFiles) = rebuildCacheForDirtyFiles( currentLib, configuration, dependencyGraph, dirtyFiles, IrFactoryImplForJsIC(WholeWorldStageController()), setOf(FqName.fromSegments(listOfNotNull(testPackage, JsBoxRunner.TEST_FUNCTION))), mainArguments, ) val moduleCache = icCache[canonicalPath] ?: TestArtifactCache(mainModuleIr.name.asString()) for (rebuiltFile in rebuiltFiles) { if (rebuiltFile.first.module == mainModuleIr) { val output = ByteArrayOutputStream() rebuiltFile.second.serializeTo(output) moduleCache.binaryAsts[rebuiltFile.first.fileEntry.name] = output.toByteArray() } } if (canonicalPath in predefinedKlibHasIcCache) { predefinedKlibHasIcCache[canonicalPath] = moduleCache } icCache[canonicalPath] = moduleCache } } val TestServices.jsIrIncrementalDataProvider: JsIrIncrementalDataProvider by TestServices.testServiceAccessor()
package com.android.tools.idea.dagger.index import com.android.tools.idea.dagger.concepts.classToPsiType import com.android.tools.idea.kotlin.psiType import com.android.tools.idea.kotlin.toPsiType import com.android.tools.idea.testing.AndroidProjectRule import com.android.tools.idea.testing.findParentElement import com.android.tools.idea.testing.moveCaret import com.android.tools.idea.testing.onEdt import com.google.common.truth.Truth.assertThat import com.intellij.psi.PsiField import com.intellij.testFramework.RunsInEdt import com.intellij.testFramework.fixtures.CodeInsightTestFixture import org.jetbrains.kotlin.idea.base.util.projectScope import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.KtProperty import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) @RunsInEdt class IndexKeyUtilTest { @get:Rule val projectRule = AndroidProjectRule.onDisk().onEdt() private lateinit var myFixture: CodeInsightTestFixture @Before fun setup() { myFixture = projectRule.fixture } @Test fun getIndexKeys_standardTypeKotlin() { myFixture.configureByText( "/src/com/example/Foo.kt", // language=kotlin """ package com.example class F<caret>oo """ .trimIndent() ) val psiType = (myFixture.elementAtCaret as KtClass).toPsiType()!! assertThat(getIndexKeys(psiType, myFixture.project, myFixture.project.projectScope())) .containsExactly("com.example.Foo", "Foo", "") .inOrder() } @Test fun getIndexKeys_standardTypeJava() { myFixture.configureByText( "/src/com/example/Foo.java", // language=kotlin """ package com.example; class F<caret>oo {} """ .trimIndent() ) val psiType = myFixture.elementAtCaret.classToPsiType() assertThat(getIndexKeys(psiType, myFixture.project, myFixture.project.projectScope())) .containsExactly("com.example.Foo", "Foo", "") .inOrder() } @Test fun getIndexKeys_typeWithoutPackage() { myFixture.configureByText( "/src/Foo.kt", // language=kotlin """ class F<caret>oo """ .trimIndent() ) val psiType = (myFixture.elementAtCaret as KtClass).toPsiType()!! assertThat(getIndexKeys(psiType, myFixture.project, myFixture.project.projectScope())) .containsExactly("Foo", "") .inOrder() } @Test fun getIndexKeys_typeWithAliasByAlias() { // Files need to be added to the project (not just configured as in other test cases) to ensure // the references between files work. myFixture.openFileInEditor( myFixture .addFileToProject( "/src/com/example/Foo.kt", // language=kotlin """ package com.example class Foo """ .trimIndent() ) .virtualFile ) myFixture.moveCaret("class F|oo") val basePsiType = (myFixture.elementAtCaret as KtClass).toPsiType()!! assertThat(getIndexKeys(basePsiType, myFixture.project, myFixture.project.projectScope())) .containsExactly("com.example.Foo", "Foo", "") .inOrder() myFixture.openFileInEditor( myFixture .addFileToProject( "/src/com/example/FooAlias1.kt", // language=kotlin """ package com.example typealias FooAlias1 = com.example.Foo val fooAlias1: FooAlias1 = FooAlias() """ .trimIndent() ) .virtualFile ) myFixture.moveCaret("val fooAl|ias1") val alias1PsiType = (myFixture.elementAtCaret as KtProperty).psiType!! assertThat(alias1PsiType).isEqualTo(basePsiType) assertThat(getIndexKeys(alias1PsiType, myFixture.project, myFixture.project.projectScope())) .containsExactly("com.example.Foo", "Foo", "FooAlias1", "") .inOrder() myFixture.openFileInEditor( myFixture .addFileToProject( "/src/com/example/FooAlias2.kt", // language=kotlin """ package com.example typealias FooAlias2 = com.example.Foo val fooAlias2: FooAlias2 = FooAlias() """ .trimIndent() ) .virtualFile ) myFixture.moveCaret("val fooAl|ias2") val alias2PsiType = (myFixture.elementAtCaret as KtProperty).psiType!! assertThat(alias2PsiType).isEqualTo(basePsiType) val indexKeysWithAlias2 = getIndexKeys(alias2PsiType, myFixture.project, myFixture.project.projectScope()) assertThat(indexKeysWithAlias2) .containsExactly("com.example.Foo", "Foo", "FooAlias1", "FooAlias2", "") assertThat(indexKeysWithAlias2[0]).isEqualTo("com.example.Foo") assertThat(indexKeysWithAlias2[1]).isEqualTo("Foo") assertThat(indexKeysWithAlias2.subList(2, 4)).containsExactly("FooAlias1", "FooAlias2") assertThat(indexKeysWithAlias2[4]).isEqualTo("") // Same short name as above, but different package myFixture.openFileInEditor( myFixture .addFileToProject( "/src/com/other/FooAlias2.kt", // language=kotlin """ package com.other typealias FooAlias2 = com.example.Foo val fooAlias2: FooAlias2 = FooAlias() """ .trimIndent() ) .virtualFile ) myFixture.moveCaret("val fooAl|ias2") val alias2OtherPsiType = (myFixture.elementAtCaret as KtProperty).psiType!! assertThat(alias2OtherPsiType).isEqualTo(basePsiType) val indexKeysWithAlias2Other = getIndexKeys(alias2OtherPsiType, myFixture.project, myFixture.project.projectScope()) assertThat(indexKeysWithAlias2Other) .containsExactly("com.example.Foo", "Foo", "FooAlias1", "FooAlias2", "") assertThat(indexKeysWithAlias2Other[0]).isEqualTo("com.example.Foo") assertThat(indexKeysWithAlias2Other[1]).isEqualTo("Foo") assertThat(indexKeysWithAlias2Other.subList(2, 4)).containsExactly("FooAlias1", "FooAlias2") assertThat(indexKeysWithAlias2Other[4]).isEqualTo("") } @Test fun getIndexKeys_primitivesKotlin() { myFixture.openFileInEditor( myFixture .addFileToProject( "/src/com/example/Foo.kt", // language=kotlin """ package com.example val fooZ: Boolean = false val fooB: Byte = 0 val fooC: Char = 'a' val fooD: Double = 0.0 val fooF: Float = 0f val fooI: Int = 0 val fooJ: Long = 0L val fooS: Short = 0 """ .trimIndent() ) .virtualFile ) val booleanType = myFixture.findParentElement<KtProperty>("val foo|Z").psiType!! val byteType = myFixture.findParentElement<KtProperty>("val foo|B").psiType!! val charType = myFixture.findParentElement<KtProperty>("val foo|C").psiType!! val doubleType = myFixture.findParentElement<KtProperty>("val foo|D").psiType!! val floatType = myFixture.findParentElement<KtProperty>("val foo|F").psiType!! val intType = myFixture.findParentElement<KtProperty>("val foo|I").psiType!! val longType = myFixture.findParentElement<KtProperty>("val foo|J").psiType!! val shortType = myFixture.findParentElement<KtProperty>("val foo|S").psiType!! assertThat(getIndexKeys(booleanType, myFixture.project, myFixture.project.projectScope())) .containsExactly("Boolean", "") .inOrder() assertThat(getIndexKeys(byteType, myFixture.project, myFixture.project.projectScope())) .containsExactly("Byte", "") .inOrder() assertThat(getIndexKeys(charType, myFixture.project, myFixture.project.projectScope())) .containsExactly("Char", "Character", "") .inOrder() assertThat(getIndexKeys(doubleType, myFixture.project, myFixture.project.projectScope())) .containsExactly("Double", "") .inOrder() assertThat(getIndexKeys(floatType, myFixture.project, myFixture.project.projectScope())) .containsExactly("Float", "") .inOrder() assertThat(getIndexKeys(intType, myFixture.project, myFixture.project.projectScope())) .containsExactly("Int", "Integer", "") .inOrder() assertThat(getIndexKeys(longType, myFixture.project, myFixture.project.projectScope())) .containsExactly("Long", "") .inOrder() assertThat(getIndexKeys(shortType, myFixture.project, myFixture.project.projectScope())) .containsExactly("Short", "") .inOrder() } @Test fun getIndexKeys_primitivesUnboxedJava() { myFixture.openFileInEditor( myFixture .addFileToProject( "/src/com/example/Foo.java", // language=java """ package com.example; class Foo { private boolean unboxedZ = false; private byte unboxedB = 0; private char unboxedC = 'a'; private double unboxedD = 0.0; private float unboxedF = 0.0f; private int unboxedI = 0; private long unboxedJ = 0l; private short unboxedS = 0; } """ .trimIndent() ) .virtualFile ) val unboxedBooleanType = myFixture.findParentElement<PsiField>("unboxed|Z").type val unboxedByteType = myFixture.findParentElement<PsiField>("unboxed|B").type val unboxedCharType = myFixture.findParentElement<PsiField>("unboxed|C").type val unboxedDoubleType = myFixture.findParentElement<PsiField>("unboxed|D").type val unboxedFloatType = myFixture.findParentElement<PsiField>("unboxed|F").type val unboxedIntType = myFixture.findParentElement<PsiField>("unboxed|I").type val unboxedLongType = myFixture.findParentElement<PsiField>("unboxed|J").type val unboxedShortType = myFixture.findParentElement<PsiField>("unboxed|S").type assertThat( getIndexKeys(unboxedBooleanType, myFixture.project, myFixture.project.projectScope()) ) .containsExactly("Boolean", "") .inOrder() assertThat(getIndexKeys(unboxedByteType, myFixture.project, myFixture.project.projectScope())) .containsExactly("Byte", "") .inOrder() assertThat(getIndexKeys(unboxedCharType, myFixture.project, myFixture.project.projectScope())) .containsExactly("Char", "Character", "") .inOrder() assertThat(getIndexKeys(unboxedDoubleType, myFixture.project, myFixture.project.projectScope())) .containsExactly("Double", "") .inOrder() assertThat(getIndexKeys(unboxedFloatType, myFixture.project, myFixture.project.projectScope())) .containsExactly("Float", "") .inOrder() assertThat(getIndexKeys(unboxedIntType, myFixture.project, myFixture.project.projectScope())) .containsExactly("Int", "Integer", "") .inOrder() assertThat(getIndexKeys(unboxedLongType, myFixture.project, myFixture.project.projectScope())) .containsExactly("Long", "") .inOrder() assertThat(getIndexKeys(unboxedShortType, myFixture.project, myFixture.project.projectScope())) .containsExactly("Short", "") .inOrder() } @Test fun getIndexKeys_primitivesBoxedJava() { myFixture.openFileInEditor( myFixture .addFileToProject( "/src/com/example/Foo.java", // language=java """ package com.example; class Foo { private Boolean boxedZ = false; private Byte boxedB = 0; private Character boxedC = 'a'; private Double boxedD = 0.0; private Float boxedF = 0.0f; private Integer boxedI = 0; private Long boxedJ = 0l; private Short boxedS = 0; } """ .trimIndent() ) .virtualFile ) val boxedBooleanType = myFixture.findParentElement<PsiField>(" boxed|Z").type val boxedByteType = myFixture.findParentElement<PsiField>(" boxed|B").type val boxedCharType = myFixture.findParentElement<PsiField>(" boxed|C").type val boxedDoubleType = myFixture.findParentElement<PsiField>(" boxed|D").type val boxedFloatType = myFixture.findParentElement<PsiField>(" boxed|F").type val boxedIntType = myFixture.findParentElement<PsiField>(" boxed|I").type val boxedLongType = myFixture.findParentElement<PsiField>(" boxed|J").type val boxedShortType = myFixture.findParentElement<PsiField>(" boxed|S").type assertThat(getIndexKeys(boxedBooleanType, myFixture.project, myFixture.project.projectScope())) .containsExactly("Boolean", "") .inOrder() assertThat(getIndexKeys(boxedByteType, myFixture.project, myFixture.project.projectScope())) .containsExactly("Byte", "") .inOrder() assertThat(getIndexKeys(boxedCharType, myFixture.project, myFixture.project.projectScope())) .containsExactly("Char", "Character", "") .inOrder() assertThat(getIndexKeys(boxedDoubleType, myFixture.project, myFixture.project.projectScope())) .containsExactly("Double", "") .inOrder() assertThat(getIndexKeys(boxedFloatType, myFixture.project, myFixture.project.projectScope())) .containsExactly("Float", "") .inOrder() assertThat(getIndexKeys(boxedIntType, myFixture.project, myFixture.project.projectScope())) .containsExactly("Int", "Integer", "") .inOrder() assertThat(getIndexKeys(boxedLongType, myFixture.project, myFixture.project.projectScope())) .containsExactly("Long", "") .inOrder() assertThat(getIndexKeys(boxedShortType, myFixture.project, myFixture.project.projectScope())) .containsExactly("Short", "") .inOrder() } @Test fun getIndexKeys_strings() { myFixture.openFileInEditor( myFixture .addFileToProject( "/src/com/example/Foo.java", // language=java """ package com.example; class Foo { private String javaString = ""; } """ .trimIndent() ) .virtualFile ) val javaStringType = myFixture.findParentElement<PsiField>("java|String").type myFixture.openFileInEditor( myFixture .addFileToProject( "/src/com/example/Foo.kt", // language=kotlin """ package com.example val kotlinString: String = "" """ .trimIndent() ) .virtualFile ) val kotlinStringType = myFixture.findParentElement<KtProperty>("kotlin|String").psiType!! assertThat(getIndexKeys(javaStringType, myFixture.project, myFixture.project.projectScope())) .containsExactly("java.lang.String", "String", "") .inOrder() assertThat(getIndexKeys(kotlinStringType, myFixture.project, myFixture.project.projectScope())) .containsExactly("java.lang.String", "String", "") .inOrder() } @Test fun getIndexKeys_genericsKotlin() { myFixture.openFileInEditor( myFixture .addFileToProject( "/src/com/example/Foo.kt", // language=kotlin """ package com.example class SomeGenericType<T> val type1: SomeGenericType<kotlin.String> = SomeGenericType() """ .trimIndent() ) .virtualFile ) val psiType1 = myFixture.findParentElement<KtProperty>("type|1").psiType!! assertThat(getIndexKeys(psiType1, myFixture.project, myFixture.project.projectScope())) .containsExactly("com.example.SomeGenericType", "SomeGenericType", "") .inOrder() } @Test fun getIndexKeys_genericsJava() { myFixture.openFileInEditor( myFixture .addFileToProject( "/src/com/example/Foo.java", // language=java """ package com.example; class SomeGenericType<T> { public static SomeGenericType<String> value = new SomeGenericType<String>(); } """ .trimIndent() ) .virtualFile ) val psiType1 = myFixture.findParentElement<PsiField>("val|ue = new").type assertThat(getIndexKeys(psiType1, myFixture.project, myFixture.project.projectScope())) .containsExactly("com.example.SomeGenericType", "SomeGenericType", "") .inOrder() } @Test fun getIndexKeys_genericsWithTypeAlias() { myFixture.openFileInEditor( myFixture .addFileToProject( "/src/com/example/Foo.kt", // language=kotlin """ package com.example class SomeGenericType<T> typealias MyTypeAlias1 = SomeGenericType<List<Int>> typealias MyTypeAlias2<T> = SomeGenericType<List<T>> typealias MyTypeAlias3<T> = SomeGenericType<T> typealias MyIntAlias = Int typealias MyListAlias<T> = List<T> val type1: SomeGenericType<List<Int>> = SomeGenericType() """ .trimIndent() ) .virtualFile ) val psiType1 = myFixture.findParentElement<KtProperty>("type|1").psiType!! val indexKeys = getIndexKeys(psiType1, myFixture.project, myFixture.project.projectScope()) assertThat(indexKeys[0]).isEqualTo("com.example.SomeGenericType") assertThat(indexKeys[1]).isEqualTo("SomeGenericType") assertThat(indexKeys.subList(2, 5)) .containsExactly("MyTypeAlias1", "MyTypeAlias2", "MyTypeAlias3") assertThat(indexKeys[5]).isEqualTo("") } @Test fun getIndexKeys_arraysKotlin() { myFixture.openFileInEditor( myFixture .addFileToProject( "/src/com/example/Foo.kt", // language=kotlin """ package com.example class Foo val fooArray: Array<Foo> = arrayOf() val stringArray: Array<String> = arrayOf() val booleanArray: BooleanArray = booleanArrayOf() val byteArray: ByteArray = byteArrayOf() val charArray: CharArray = charArrayOf() val doubleArray: DoubleArray = doubleArrayOf() val floatArray: FloatArray = floatArrayOf() val intArray: IntArray = intArrayOf() val longArray: LongArray = longArrayOf() val shortArray: ShortArray = shortArrayOf() """ .trimIndent() ) .virtualFile ) val fooArrayType = myFixture.findParentElement<KtProperty>("foo|Array").psiType!! assertThat(getIndexKeys(fooArrayType, myFixture.project, myFixture.project.projectScope())) .containsExactly("Array", "Foo[]", "") .inOrder() val stringArrayType = myFixture.findParentElement<KtProperty>("string|Array").psiType!! assertThat(getIndexKeys(stringArrayType, myFixture.project, myFixture.project.projectScope())) .containsExactly("Array", "String[]", "") .inOrder() val booleanArrayType = myFixture.findParentElement<KtProperty>("boolean|Array").psiType!! assertThat(getIndexKeys(booleanArrayType, myFixture.project, myFixture.project.projectScope())) .containsExactly("BooleanArray", "boolean[]", "") .inOrder() val byteArrayType = myFixture.findParentElement<KtProperty>("byte|Array").psiType!! assertThat(getIndexKeys(byteArrayType, myFixture.project, myFixture.project.projectScope())) .containsExactly("ByteArray", "byte[]", "") .inOrder() val charArrayType = myFixture.findParentElement<KtProperty>("char|Array").psiType!! assertThat(getIndexKeys(charArrayType, myFixture.project, myFixture.project.projectScope())) .containsExactly("CharArray", "char[]", "") .inOrder() val doubleArrayType = myFixture.findParentElement<KtProperty>("double|Array").psiType!! assertThat(getIndexKeys(doubleArrayType, myFixture.project, myFixture.project.projectScope())) .containsExactly("DoubleArray", "double[]", "") .inOrder() val floatArrayType = myFixture.findParentElement<KtProperty>("float|Array").psiType!! assertThat(getIndexKeys(floatArrayType, myFixture.project, myFixture.project.projectScope())) .containsExactly("FloatArray", "float[]", "") .inOrder() val intArrayType = myFixture.findParentElement<KtProperty>("int|Array").psiType!! assertThat(getIndexKeys(intArrayType, myFixture.project, myFixture.project.projectScope())) .containsExactly("IntArray", "int[]", "") .inOrder() val longArrayType = myFixture.findParentElement<KtProperty>("long|Array").psiType!! assertThat(getIndexKeys(longArrayType, myFixture.project, myFixture.project.projectScope())) .containsExactly("LongArray", "long[]", "") .inOrder() val shortArrayType = myFixture.findParentElement<KtProperty>("short|Array").psiType!! assertThat(getIndexKeys(shortArrayType, myFixture.project, myFixture.project.projectScope())) .containsExactly("ShortArray", "short[]", "") .inOrder() } @Test fun getIndexKeys_arraysJava() { myFixture.openFileInEditor( myFixture .addFileToProject( "/src/com/example/Foo.java", // language=java """ package com.example; class Foo { public Foo[] fooArray = {}; public String[] stringArray = {}; public boolean[] booleanArray = {}; public byte[] byteArray = {}; public char[] charArray = {}; public double[] doubleArray = {}; public float[] floatArray = {}; public int[] intArray = {}; public long[] longArray = {}; public short[] shortArray = {}; public Integer[] boxedArray = {}; } """ .trimIndent() ) .virtualFile ) val fooArrayType = myFixture.findParentElement<PsiField>("foo|Array").type!! assertThat(getIndexKeys(fooArrayType, myFixture.project, myFixture.project.projectScope())) .containsExactly("Array", "Foo[]", "") .inOrder() val stringArrayType = myFixture.findParentElement<PsiField>("string|Array").type assertThat(getIndexKeys(stringArrayType, myFixture.project, myFixture.project.projectScope())) .containsExactly("Array", "String[]", "") .inOrder() val booleanArrayType = myFixture.findParentElement<PsiField>("boolean|Array").type assertThat(getIndexKeys(booleanArrayType, myFixture.project, myFixture.project.projectScope())) .containsExactly("BooleanArray", "boolean[]", "") .inOrder() val byteArrayType = myFixture.findParentElement<PsiField>("byte|Array").type assertThat(getIndexKeys(byteArrayType, myFixture.project, myFixture.project.projectScope())) .containsExactly("ByteArray", "byte[]", "") .inOrder() val charArrayType = myFixture.findParentElement<PsiField>("char|Array").type assertThat(getIndexKeys(charArrayType, myFixture.project, myFixture.project.projectScope())) .containsExactly("CharArray", "char[]", "") .inOrder() val doubleArrayType = myFixture.findParentElement<PsiField>("double|Array").type assertThat(getIndexKeys(doubleArrayType, myFixture.project, myFixture.project.projectScope())) .containsExactly("DoubleArray", "double[]", "") .inOrder() val floatArrayType = myFixture.findParentElement<PsiField>("float|Array").type assertThat(getIndexKeys(floatArrayType, myFixture.project, myFixture.project.projectScope())) .containsExactly("FloatArray", "float[]", "") .inOrder() val intArrayType = myFixture.findParentElement<PsiField>("int|Array").type assertThat(getIndexKeys(intArrayType, myFixture.project, myFixture.project.projectScope())) .containsExactly("IntArray", "int[]", "") .inOrder() val longArrayType = myFixture.findParentElement<PsiField>("long|Array").type assertThat(getIndexKeys(longArrayType, myFixture.project, myFixture.project.projectScope())) .containsExactly("LongArray", "long[]", "") .inOrder() val shortArrayType = myFixture.findParentElement<PsiField>("short|Array").type assertThat(getIndexKeys(shortArrayType, myFixture.project, myFixture.project.projectScope())) .containsExactly("ShortArray", "short[]", "") .inOrder() val boxedArrayType = myFixture.findParentElement<PsiField>("boxed|Array").type assertThat(getIndexKeys(boxedArrayType, myFixture.project, myFixture.project.projectScope())) .containsExactly("Array", "Integer[]", "") .inOrder() } @Test fun getIndexKeys_arraysWithGenericsKotlin() { myFixture.openFileInEditor( myFixture .addFileToProject( "/src/com/example/Foo.kt", // language=kotlin """ package com.example class SomeGenericType<T> class Foo val fooArray: Array<SomeGenericType<Foo>> = arrayOf() val stringArray: Array<SomeGenericType<String>> = arrayOf() """ .trimIndent() ) .virtualFile ) val fooArrayType = myFixture.findParentElement<KtProperty>("foo|Array").psiType!! assertThat(getIndexKeys(fooArrayType, myFixture.project, myFixture.project.projectScope())) .containsExactly("Array", "SomeGenericType[]", "") .inOrder() val stringArrayType = myFixture.findParentElement<KtProperty>("string|Array").psiType!! assertThat(getIndexKeys(stringArrayType, myFixture.project, myFixture.project.projectScope())) .containsExactly("Array", "SomeGenericType[]", "") .inOrder() } @Test fun getIndexKeys_arraysWithGenericsJava() { myFixture.openFileInEditor( myFixture .addFileToProject( "/src/com/example/Foo.java", // language=java """ package com.example; class SomeGenericType<T> {} class Foo { public SomeGenericType<Foo>[] fooArray = {}; public SomeGenericType<String>[] stringArray = {}; } """ .trimIndent() ) .virtualFile ) val fooArrayType = myFixture.findParentElement<PsiField>("foo|Array").type assertThat(getIndexKeys(fooArrayType, myFixture.project, myFixture.project.projectScope())) .containsExactly("Array", "SomeGenericType[]", "") .inOrder() val stringArrayType = myFixture.findParentElement<PsiField>("string|Array").type assertThat(getIndexKeys(stringArrayType, myFixture.project, myFixture.project.projectScope())) .containsExactly("Array", "SomeGenericType[]", "") .inOrder() } @Test fun getIndexKeys_typeAliasesForPrimitivesKotlin() { myFixture.openFileInEditor( myFixture .addFileToProject( "/src/com/example/Foo.kt", // language=kotlin """ package com.example typealias MyInt = Int typealias MyChar = Char typealias MyInteger = java.lang.Integer val intProperty: Int = 0 val charProperty: Char = 'a' """ .trimIndent() ) .virtualFile ) val intType = myFixture.findParentElement<KtProperty>("int|Property").psiType!! assertThat(getIndexKeys(intType, myFixture.project, myFixture.project.projectScope())) .containsExactly("Int", "Integer", "MyInt", "MyInteger", "") .inOrder() val charType = myFixture.findParentElement<KtProperty>("char|Property").psiType!! assertThat(getIndexKeys(charType, myFixture.project, myFixture.project.projectScope())) .containsExactly("Char", "Character", "MyChar", "") .inOrder() } @Test fun getIndexKeys_typeAliasesForArraysKotlin() { myFixture.openFileInEditor( myFixture .addFileToProject( "/src/com/example/Foo.kt", // language=kotlin """ package com.example class Foo typealias MyIntArray = IntArray typealias MyIntegerArray = Array<Int> typealias MyFooArray = Array<Foo> val intArrayProperty: MyIntArray = arrayOf() val integerArrayProperty: MyIntegerArray = arrayOf() val charArrayProperty: MyFooArray = arrayOf() """ .trimIndent() ) .virtualFile ) val intArrayType = myFixture.findParentElement<KtProperty>("intArray|Property").psiType!! assertThat(getIndexKeys(intArrayType, myFixture.project, myFixture.project.projectScope())) .containsExactly("IntArray", "int[]", "MyIntArray", "") val integerArrayType = myFixture.findParentElement<KtProperty>("integerArray|Property").psiType!! assertThat(getIndexKeys(integerArrayType, myFixture.project, myFixture.project.projectScope())) .containsExactly("Array", "Integer[]", "MyIntegerArray", "MyFooArray", "") val charArrayType = myFixture.findParentElement<KtProperty>("charArray|Property").psiType!! assertThat(getIndexKeys(charArrayType, myFixture.project, myFixture.project.projectScope())) .containsExactly("Array", "Foo[]", "MyFooArray", "MyIntegerArray", "") } @Test fun getIndexKeys_multipleTypeAliasesWithDifferentGenericArgsKotlin() { myFixture.addFileToProject( "/src/com/other/Foo.kt", // language=kotlin """ package com.other class Foo<T> """ .trimIndent() ) myFixture.openFileInEditor( myFixture .addFileToProject( "/src/com/example/Foo.kt", // language=kotlin """ package com.example class Foo<T> class Bar typealias MyFooInt = Foo<Int> typealias MyFooBar = Foo<Bar> typealias OtherFooInt = com.other.Foo<Int> typealias OtherFooBar = com.other.Foo<Bar> typealias MyArrayInt = IntArray typealias MyArrayBar = Array<Bar> typealias MyArrayFooBar = Array<Foo<Bar>> val fooIntProperty: MyFooInt = MyFooInt() val fooBarProperty: MyFooBar = MyFooBar() val otherFooIntProperty: OtherFooInt = OtherFooInt() val otherFooBarProperty: OtherFooBar = OtherFooBar() val arrayIntProperty: MyArrayInt = intArrayOf() val arrayBarProperty: MyArrayBar = arrayOf() val arrayFooBarProperty: MyArrayFooBar = arrayOf() """ .trimIndent() ) .virtualFile ) val fooIntType = myFixture.findParentElement<KtProperty>("fooInt|Property").psiType!! val fooIntIndexKeys = getIndexKeys(fooIntType, myFixture.project, myFixture.project.projectScope()) assertThat(fooIntIndexKeys) .containsExactly( "com.example.Foo", "Foo", "MyFooInt", "MyFooBar", "OtherFooInt", "OtherFooBar", "" ) val fooBarType = myFixture.findParentElement<KtProperty>("fooBar|Property").psiType!! assertThat(getIndexKeys(fooBarType, myFixture.project, myFixture.project.projectScope())) .containsExactlyElementsIn(fooIntIndexKeys) val otherFooIntType = myFixture.findParentElement<KtProperty>("otherFooInt|Property").psiType!! val otherFooIntIndexKeys = getIndexKeys(otherFooIntType, myFixture.project, myFixture.project.projectScope()) assertThat(otherFooIntIndexKeys) .containsExactly( "com.other.Foo", "Foo", "MyFooInt", "MyFooBar", "OtherFooInt", "OtherFooBar", "" ) val otherFooBarType = myFixture.findParentElement<KtProperty>("otherFooBar|Property").psiType!! assertThat(getIndexKeys(otherFooBarType, myFixture.project, myFixture.project.projectScope())) .containsExactlyElementsIn(otherFooIntIndexKeys) val arrayIntType = myFixture.findParentElement<KtProperty>("arrayInt|Property").psiType!! assertThat(getIndexKeys(arrayIntType, myFixture.project, myFixture.project.projectScope())) .containsExactly("IntArray", "int[]", "MyArrayInt", "") val arrayBarType = myFixture.findParentElement<KtProperty>("arrayBar|Property").psiType!! assertThat(getIndexKeys(arrayBarType, myFixture.project, myFixture.project.projectScope())) .containsExactly("Array", "Bar[]", "MyArrayBar", "MyArrayFooBar", "") val arrayFooBarType = myFixture.findParentElement<KtProperty>("arrayFooBar|Property").psiType!! assertThat(getIndexKeys(arrayFooBarType, myFixture.project, myFixture.project.projectScope())) .containsExactly("Array", "Foo[]", "MyArrayBar", "MyArrayFooBar", "") } }
open class A<T : Number>(val t: T) { open fun foo(): T = t } class Z : A<Int>(17) { override fun foo() = 239 } fun box(): String { val z = Z() val a: A<Int> = z return when { z.foo() != 239 -> "Fail #1" a.foo() != 239 -> "Fail #2" else -> "OK" } }
import kotlin.coroutines.* import kotlin.coroutines.intrinsics.* import helpers.* // Function is suspend // parameter is noinline // parameter is NOT suspend // Block is allowed to be called inside the body of owner inline function // Block is allowed to be called from nested classes/lambdas (as common crossinlines) // It is NOT possible to call startCoroutine on the parameter // suspend calls NOT possible inside lambda matching to the parameter suspend inline fun test(noinline c: () -> Unit) { c() val o = object : Runnable { override fun run() { c() } } val l = { c() } c.<!UNRESOLVED_REFERENCE_WRONG_RECEIVER!>startCoroutine<!>(EmptyContinuation) } fun builder(c: suspend () -> Unit) { c.startCoroutine(EmptyContinuation) } suspend fun calculate() = "OK" fun box() { builder { test { <!NON_LOCAL_SUSPENSION_POINT!>calculate<!>() } } }
package com.google.samples.apps.iosched.ui /** * Fragments representing main navigation destinations (shown by [MainActivity]) implement this * interface. */ interface MainNavigationFragment { /** * Called by the hosting activity when the Back button is pressed. * @return True if the fragment handled the back press, false otherwise. */ fun onBackPressed(): Boolean { return false } /** Called by the hosting activity when the user interacts with it. */ fun onUserInteraction() {} }
import kotlin.reflect.KFunction0 fun main() { class A class B { val x = ::A val f: KFunction0<A> = x } }
package com.android.tools.idea.layoutinspector.pipeline.foregroundprocessdetection import com.android.tools.idea.appinspection.api.process.ProcessesModel import com.android.tools.idea.appinspection.inspector.api.process.DeviceDescriptor import com.android.tools.idea.appinspection.inspector.api.process.ProcessDescriptor import com.intellij.openapi.Disposable import com.intellij.openapi.util.Disposer import org.jetbrains.annotations.TestOnly import java.util.concurrent.CopyOnWriteArraySet /** * Keeps track of the currently selected device. * * The selected device is controlled by [ForegroundProcessDetection], and it is used by * [SelectedDeviceAction]. */ class DeviceModel(parentDisposable: Disposable, private val processesModel: ProcessesModel) : Disposable { @TestOnly constructor( parentDisposable: Disposable, processesModel: ProcessesModel, foregroundProcessDetectionSupportedDeviceTest: Set<DeviceDescriptor> ) : this(parentDisposable, processesModel) { foregroundProcessDetectionSupportedDeviceTest.forEach { foregroundProcessDetectionDevicesSupport[it] = ForegroundProcessDetectionSupport.SUPPORTED } } init { Disposer.register(parentDisposable, this) ForegroundProcessDetectionImpl.addDeviceModel(this) } override fun dispose() { ForegroundProcessDetectionImpl.removeDeviceModel(this) } /** * Allow connecting only to this device. This is useful for the embedded Layout Inspector, in this * mode we should connect only to the currently visible device. Once embedded mode is the only * mode, Layout Inspector code that auto-select the device can be removed, this property with it. */ var forcedDeviceSerialNumber: String? = null /** * The device on which the on-device library is polling for foreground process. When null, it * means that we are not polling on any device. * * [selectedDevice] should only be set by [ForegroundProcessDetection], this is to make sure that * there is consistency between the [selectedDevice] and the device we are polling on. */ var selectedDevice: DeviceDescriptor? = null internal set(value) { if ( forcedDeviceSerialNumber != null && value?.serial != null && value.serial != forcedDeviceSerialNumber ) { return } // each time the selected device changes, the selected process should be reset // If selectedDevice is null, no device was selected. So we should not reset the process, // because selectedProcess might be set by the user from the process picker. if (selectedDevice != null) { processesModel.selectedProcess = null } newSelectedDeviceListeners.forEach { it.invoke(value) } field = value } @TestOnly fun setSelectedDevice(device: DeviceDescriptor?) { selectedDevice = device } val newSelectedDeviceListeners = CopyOnWriteArraySet<(DeviceDescriptor?) -> Unit>() /** The set of connected devices and their support of foreground process detection. */ internal val foregroundProcessDetectionDevicesSupport = mutableMapOf<DeviceDescriptor, ForegroundProcessDetectionSupport>() val devices: Set<DeviceDescriptor> get() { return processesModel.devices } val selectedProcess: ProcessDescriptor? get() { return processesModel.selectedProcess } val processes: Set<ProcessDescriptor> get() { return processesModel.processes } fun getForegroundProcessDetectionSupport( device: DeviceDescriptor ): ForegroundProcessDetectionSupport { return foregroundProcessDetectionDevicesSupport[device] ?: ForegroundProcessDetectionSupport.NOT_SUPPORTED } } enum class ForegroundProcessDetectionSupport { SUPPORTED, NOT_SUPPORTED, /** * The handshake is started but not concluded yet. So we don't know if fg process detection is * supported or not. */ HANDSHAKE_IN_PROGRESS }
package com.android.tools.idea.uibuilder.editor.multirepresentation import com.intellij.openapi.project.Project import com.intellij.psi.PsiFile /** * A generic interface for a [PreviewRepresentation] provider. Used by the * [MultiRepresentationPreview] to find all the [PreviewRepresentation]s suitable for particular * file. [PreviewRepresentationProvider] is implied to have 1-to-1 correspondence with some * [PreviewRepresentation] that it provides (creates). */ interface PreviewRepresentationProvider { /** A name associated with the representation */ val displayName: RepresentationName /** * Tells a client if the corresponding [PreviewRepresentation] is applicable for the input file. */ suspend fun accept(project: Project, psiFile: PsiFile): Boolean /** * Creates a corresponding [PreviewRepresentation] for the input file. It is only valid to call * this if [accept] is true, undefined behavior otherwise. */ fun createRepresentation(psiFile: PsiFile): PreviewRepresentation }
package org.jetbrains.plugins.ideavim.extension.matchit import org.jetbrains.plugins.ideavim.VimTestCase import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestInfo class MatchitCMakeTest : VimTestCase() { @Throws(Exception::class) @BeforeEach override fun setUp(testInfo: TestInfo) { super.setUp(testInfo) enableExtensions("matchit") } @Test fun `test jump from if to else`() { doTest( "%", """ ${c}if (CMAKE_SYSTEM_NAME MATCHES "Linux") message("Linux") else() message("Non-linux system") endif() """.trimIndent(), """ if (CMAKE_SYSTEM_NAME MATCHES "Linux") message("Linux") ${c}else() message("Non-linux system") endif() """.trimIndent(), fileName = "CMakeLists.txt", ) } @Test fun `test jump from else to endif`() { doTest( "%", """ if (CMAKE_SYSTEM_NAME MATCHES "Linux") message("Linux") ${c}else() message("Non-linux system") endif() """.trimIndent(), """ if (CMAKE_SYSTEM_NAME MATCHES "Linux") message("Linux") else() message("Non-linux system") ${c}endif() """.trimIndent(), fileName = "CMakeLists.txt", ) } @Test fun `test jump from endif to if`() { doTest( "%", """ if (CMAKE_SYSTEM_NAME MATCHES "Linux") message("Linux") else() message("Non-linux system") ${c}endif() """.trimIndent(), """ ${c}if (CMAKE_SYSTEM_NAME MATCHES "Linux") message("Linux") else() message("Non-linux system") endif() """.trimIndent(), fileName = "CMakeLists.txt", ) } @Test fun `test jump from if to elseif in if-else structure`() { doTest( "%", """ ${c}if (CMAKE_SYSTEM_NAME MATCHES "Linux") message("Linux") elseif (CMAKE_SYSTEM_NAME MATCHES "Darwin") message("MacOS") elseif (CMAKE_SYSTEM_NAME MATCHES "Windows") message("Windows") else() message("Unknown system") endif() """.trimIndent(), """ if (CMAKE_SYSTEM_NAME MATCHES "Linux") message("Linux") ${c}elseif (CMAKE_SYSTEM_NAME MATCHES "Darwin") message("MacOS") elseif (CMAKE_SYSTEM_NAME MATCHES "Windows") message("Windows") else() message("Unknown system") endif() """.trimIndent(), fileName = "CMakeLists.txt", ) } @Test fun `test jump from elseif to elseif`() { doTest( "%", """ if (CMAKE_SYSTEM_NAME MATCHES "Linux") message("Linux") ${c}elseif (CMAKE_SYSTEM_NAME MATCHES "Darwin") message("MacOS") elseif (CMAKE_SYSTEM_NAME MATCHES "Windows") message("Windows") else() message("Unknown system") endif() """.trimIndent(), """ if (CMAKE_SYSTEM_NAME MATCHES "Linux") message("Linux") elseif (CMAKE_SYSTEM_NAME MATCHES "Darwin") message("MacOS") ${c}elseif (CMAKE_SYSTEM_NAME MATCHES "Windows") message("Windows") else() message("Unknown system") endif() """.trimIndent(), fileName = "CMakeLists.txt", ) } @Test fun `test jump from elseif to else`() { doTest( "%", """ if (CMAKE_SYSTEM_NAME MATCHES "Linux") message("Linux") elseif (CMAKE_SYSTEM_NAME MATCHES "Darwin") message("MacOS") ${c}elseif (CMAKE_SYSTEM_NAME MATCHES "Windows") message("Windows") else() message("Unknown system") endif() """.trimIndent(), """ if (CMAKE_SYSTEM_NAME MATCHES "Linux") message("Linux") elseif (CMAKE_SYSTEM_NAME MATCHES "Darwin") message("MacOS") elseif (CMAKE_SYSTEM_NAME MATCHES "Windows") message("Windows") ${c}else() message("Unknown system") endif() """.trimIndent(), fileName = "CMakeLists.txt", ) } @Test fun `test jump from else to endif in if-else structure`() { doTest( "%", """ if (CMAKE_SYSTEM_NAME MATCHES "Linux") message("Linux") elseif (CMAKE_SYSTEM_NAME MATCHES "Darwin") message("MacOS") elseif (CMAKE_SYSTEM_NAME MATCHES "Windows") message("Windows") ${c}else() message("Unknown system") endif() """.trimIndent(), """ if (CMAKE_SYSTEM_NAME MATCHES "Linux") message("Linux") elseif (CMAKE_SYSTEM_NAME MATCHES "Darwin") message("MacOS") elseif (CMAKE_SYSTEM_NAME MATCHES "Windows") message("Windows") else() message("Unknown system") ${c}endif() """.trimIndent(), fileName = "CMakeLists.txt", ) } @Test fun `test jump from endif to if in if-else structure`() { doTest( "%", """ if (CMAKE_SYSTEM_NAME MATCHES "Linux") message("Linux") elseif (CMAKE_SYSTEM_NAME MATCHES "Darwin") message("MacOS") elseif (CMAKE_SYSTEM_NAME MATCHES "Windows") message("Windows") else() message("Unknown system") ${c}endif() """.trimIndent(), """ ${c}if (CMAKE_SYSTEM_NAME MATCHES "Linux") message("Linux") elseif (CMAKE_SYSTEM_NAME MATCHES "Darwin") message("MacOS") elseif (CMAKE_SYSTEM_NAME MATCHES "Windows") message("Windows") else() message("Unknown system") endif() """.trimIndent(), fileName = "CMakeLists.txt", ) } @Test fun `test jump from foreach to endforeach`() { doTest( "%", """ ${c}foreach(X IN LISTS A B C) message(STATUS "X=${"\${X}"}") endforeach() """.trimIndent(), """ foreach(X IN LISTS A B C) message(STATUS "X=${"\${X}"}") ${c}endforeach() """.trimIndent(), fileName = "CMakeLists.txt", ) } @Test fun `test jump from endforeach to foreach`() { doTest( "%", """ foreach(X IN LISTS A B C) message(STATUS "X=${"\${X}"}") ${c}endforeach() """.trimIndent(), """ ${c}foreach(X IN LISTS A B C) message(STATUS "X=${"\${X}"}") endforeach() """.trimIndent(), fileName = "CMakeLists.txt", ) } @Test fun `test jump from foreach to break`() { doTest( "%", """ ${c}foreach(X IN LISTS A B C) if (X MATCHES "FOO") break endif() message(STATUS "X=${"\${X}"}") endforeach() """.trimIndent(), """ foreach(X IN LISTS A B C) if (X MATCHES "FOO") ${c}break endif() message(STATUS "X=${"\${X}"}") endforeach() """.trimIndent(), fileName = "CMakeLists.txt", ) } @Test fun `test jump from break to endforeach`() { doTest( "%", """ foreach(X IN LISTS A B C) if (X MATCHES "FOO") ${c}break endif() message(STATUS "X=${"\${X}"}") endforeach() """.trimIndent(), """ foreach(X IN LISTS A B C) if (X MATCHES "FOO") break endif() message(STATUS "X=${"\${X}"}") ${c}endforeach() """.trimIndent(), fileName = "CMakeLists.txt", ) } @Test fun `test jump from while to endwhile`() { doTest( "%", """ ${c}while(${"\${index}"} LESS 10) MATH(EXPR VAR "${"\${index}"}+1") endwhile() """.trimIndent(), """ while(${"\${index}"} LESS 10) MATH(EXPR VAR "${"\${index}"}+1") ${c}endwhile() """.trimIndent(), fileName = "CMakeLists.txt", ) } @Test fun `test jump from endwhile to while`() { doTest( "%", """ while(${"\${index}"} LESS 10) MATH(EXPR VAR "${"\${index}"}+1") ${c}endwhile() """.trimIndent(), """ ${c}while(${"\${index}"} LESS 10) MATH(EXPR VAR "${"\${index}"}+1") endwhile() """.trimIndent(), fileName = "CMakeLists.txt", ) } @Test fun `test jump from while to break`() { doTest( "%", """ ${c}while (TRUE) MATH(EXPR VAR "${"\${index}+1\""}") if (${"\${index}"} EQUAL 5) break endif() endwhile() """.trimIndent(), """ while (TRUE) MATH(EXPR VAR "${"\${index}+1\""}") if (${"\${index}"} EQUAL 5) ${c}break endif() endwhile() """.trimIndent(), fileName = "CMakeLists.txt", ) } @Test fun `test jump from break to endwhile`() { doTest( "%", """ while (TRUE) MATH(EXPR VAR "${"\${index}+1\""}") if (${"\${index}"} EQUAL 5) ${c}break endif() endwhile() """.trimIndent(), """ while (TRUE) MATH(EXPR VAR "${"\${index}+1\""}") if (${"\${index}"} EQUAL 5) break endif() ${c}endwhile() """.trimIndent(), fileName = "CMakeLists.txt", ) } @Test fun `test jump from function to endfunction`() { doTest( "%", """ ${c}function(foo) bar(x y z) endfunction() """.trimIndent(), """ function(foo) bar(x y z) ${c}endfunction() """.trimIndent(), fileName = "CMakeLists.txt", ) } @Test fun `test jump from endfunction to function`() { doTest( "%", """ function(foo) bar(x y z) ${c}endfunction() """.trimIndent(), """ ${c}function(foo) bar(x y z) endfunction() """.trimIndent(), fileName = "CMakeLists.txt", ) } @Test fun `test jump from macro to endmacro`() { doTest( "%", """ ${c}macro(Foo arg) message("arg = ${"\${arg}\""}") endmacro() """.trimIndent(), """ macro(Foo arg) message("arg = ${"\${arg}\""}") ${c}endmacro() """.trimIndent(), fileName = "CMakeLists.txt", ) } @Test fun `test jump from endmacro to macro`() { doTest( "%", """ macro(Foo arg) message("arg = ${"\${arg}\""}") ${c}endmacro() """.trimIndent(), """ ${c}macro(Foo arg) message("arg = ${"\${arg}\""}") endmacro() """.trimIndent(), fileName = "CMakeLists.txt", ) } // Tests for reverse motion @Test fun `test reverse jump from if to endif`() { doTest( "g%", """ ${c}if (CMAKE_SYSTEM_NAME MATCHES "Linux") message("Linux") else() message("Non-linux system") endif() """.trimIndent(), """ if (CMAKE_SYSTEM_NAME MATCHES "Linux") message("Linux") else() message("Non-linux system") ${c}endif() """.trimIndent(), fileName = "CMakeLists.txt", ) } @Test fun `test reverse jump from else to if`() { doTest( "g%", """ if (CMAKE_SYSTEM_NAME MATCHES "Linux") message("Linux") ${c}else() message("Non-linux system") endif() """.trimIndent(), """ ${c}if (CMAKE_SYSTEM_NAME MATCHES "Linux") message("Linux") else() message("Non-linux system") endif() """.trimIndent(), fileName = "CMakeLists.txt", ) } @Test fun `test reverse jump from endif to else`() { doTest( "g%", """ if (CMAKE_SYSTEM_NAME MATCHES "Linux") message("Linux") else() message("Non-linux system") ${c}endif() """.trimIndent(), """ if (CMAKE_SYSTEM_NAME MATCHES "Linux") message("Linux") ${c}else() message("Non-linux system") endif() """.trimIndent(), fileName = "CMakeLists.txt", ) } @Test fun `test reverse jump from if to endif in if-else block`() { doTest( "g%", """ ${c}if (CMAKE_SYSTEM_NAME MATCHES "Linux") message("Linux") elseif (CMAKE_SYSTEM_NAME MATCHES "Darwin") message("MacOS") elseif (CMAKE_SYSTEM_NAME MATCHES "Windows") message("Windows") else() message("Unknown system") endif() """.trimIndent(), """ if (CMAKE_SYSTEM_NAME MATCHES "Linux") message("Linux") elseif (CMAKE_SYSTEM_NAME MATCHES "Darwin") message("MacOS") elseif (CMAKE_SYSTEM_NAME MATCHES "Windows") message("Windows") else() message("Unknown system") ${c}endif() """.trimIndent(), fileName = "CMakeLists.txt", ) } @Test fun `test reverse jump from elseif to if`() { doTest( "g%", """ if (CMAKE_SYSTEM_NAME MATCHES "Linux") message("Linux") ${c}elseif (CMAKE_SYSTEM_NAME MATCHES "Darwin") message("MacOS") elseif (CMAKE_SYSTEM_NAME MATCHES "Windows") message("Windows") else() message("Unknown system") endif() """.trimIndent(), """ ${c}if (CMAKE_SYSTEM_NAME MATCHES "Linux") message("Linux") elseif (CMAKE_SYSTEM_NAME MATCHES "Darwin") message("MacOS") elseif (CMAKE_SYSTEM_NAME MATCHES "Windows") message("Windows") else() message("Unknown system") endif() """.trimIndent(), fileName = "CMakeLists.txt", ) } @Test fun `test reverse jump from elseif in else block to elseif`() { doTest( "g%", """ if (CMAKE_SYSTEM_NAME MATCHES "Linux") message("Linux") elseif (CMAKE_SYSTEM_NAME MATCHES "Darwin") message("MacOS") ${c}elseif (CMAKE_SYSTEM_NAME MATCHES "Windows") message("Windows") else() message("Unknown system") endif() """.trimIndent(), """ if (CMAKE_SYSTEM_NAME MATCHES "Linux") message("Linux") ${c}elseif (CMAKE_SYSTEM_NAME MATCHES "Darwin") message("MacOS") elseif (CMAKE_SYSTEM_NAME MATCHES "Windows") message("Windows") else() message("Unknown system") endif() """.trimIndent(), fileName = "CMakeLists.txt", ) } @Test fun `test reverse jump from else to elseif`() { doTest( "g%", """ if (CMAKE_SYSTEM_NAME MATCHES "Linux") message("Linux") elseif (CMAKE_SYSTEM_NAME MATCHES "Darwin") message("MacOS") elseif (CMAKE_SYSTEM_NAME MATCHES "Windows") message("Windows") ${c}else() message("Unknown system") endif() """.trimIndent(), """ if (CMAKE_SYSTEM_NAME MATCHES "Linux") message("Linux") elseif (CMAKE_SYSTEM_NAME MATCHES "Darwin") message("MacOS") ${c}elseif (CMAKE_SYSTEM_NAME MATCHES "Windows") message("Windows") else() message("Unknown system") endif() """.trimIndent(), fileName = "CMakeLists.txt", ) } @Test fun `test reverse jump from endif to else in if-else block`() { doTest( "g%", """ if (CMAKE_SYSTEM_NAME MATCHES "Linux") message("Linux") elseif (CMAKE_SYSTEM_NAME MATCHES "Darwin") message("MacOS") elseif (CMAKE_SYSTEM_NAME MATCHES "Windows") message("Windows") else() message("Unknown system") ${c}endif() """.trimIndent(), """ if (CMAKE_SYSTEM_NAME MATCHES "Linux") message("Linux") elseif (CMAKE_SYSTEM_NAME MATCHES "Darwin") message("MacOS") elseif (CMAKE_SYSTEM_NAME MATCHES "Windows") message("Windows") ${c}else() message("Unknown system") endif() """.trimIndent(), fileName = "CMakeLists.txt", ) } @Test fun `test reverse jump from foreach to endforeach`() { doTest( "g%", """ ${c}foreach(X IN LISTS A B C) message(STATUS "X=${"\${X}"}") endforeach() """.trimIndent(), """ foreach(X IN LISTS A B C) message(STATUS "X=${"\${X}"}") ${c}endforeach() """.trimIndent(), fileName = "CMakeLists.txt", ) } @Test fun `test reverse jump from endforeach to foreach`() { doTest( "g%", """ foreach(X IN LISTS A B C) message(STATUS "X=${"\${X}"}") ${c}endforeach() """.trimIndent(), """ ${c}foreach(X IN LISTS A B C) message(STATUS "X=${"\${X}"}") endforeach() """.trimIndent(), fileName = "CMakeLists.txt", ) } @Test fun `test reverse jump from foreach to endforeach over a break`() { doTest( "g%", """ ${c}foreach(X IN LISTS A B C) if (X MATCHES "FOO") break endif() message(STATUS "X=${"\${X}"}") endforeach() """.trimIndent(), """ foreach(X IN LISTS A B C) if (X MATCHES "FOO") break endif() message(STATUS "X=${"\${X}"}") ${c}endforeach() """.trimIndent(), fileName = "CMakeLists.txt", ) } @Test fun `test reverse jump from endforeach to break`() { doTest( "g%", """ foreach(X IN LISTS A B C) if (X MATCHES "FOO") break endif() message(STATUS "X=${"\${X}"}") ${c}endforeach() """.trimIndent(), """ foreach(X IN LISTS A B C) if (X MATCHES "FOO") ${c}break endif() message(STATUS "X=${"\${X}"}") endforeach() """.trimIndent(), fileName = "CMakeLists.txt", ) } @Test fun `test reverse jump from break to foreach`() { doTest( "g%", """ foreach(X IN LISTS A B C) if (X MATCHES "FOO") ${c}break endif() message(STATUS "X=${"\${X}"}") endforeach() """.trimIndent(), """ ${c}foreach(X IN LISTS A B C) if (X MATCHES "FOO") break endif() message(STATUS "X=${"\${X}"}") endforeach() """.trimIndent(), fileName = "CMakeLists.txt", ) } @Test fun `test reverse jump from while to endwhile`() { doTest( "g%", """ ${c}while(${"\${index}"} LESS 10) MATH(EXPR VAR "${"\${index}"}+1") endwhile() """.trimIndent(), """ while(${"\${index}"} LESS 10) MATH(EXPR VAR "${"\${index}"}+1") ${c}endwhile() """.trimIndent(), fileName = "CMakeLists.txt", ) } @Test fun `test reverse jump from endwhile to while`() { doTest( "g%", """ while(${"\${index}"} LESS 10) MATH(EXPR VAR "${"\${index}"}+1") ${c}endwhile() """.trimIndent(), """ ${c}while(${"\${index}"} LESS 10) MATH(EXPR VAR "${"\${index}"}+1") endwhile() """.trimIndent(), fileName = "CMakeLists.txt", ) } @Test fun `test reverse jump from while to endwhile over a break`() { doTest( "g%", """ ${c}while (TRUE) MATH(EXPR VAR "${"\${index}+1\""}") if (${"\${index}"} EQUAL 5) break endif() endwhile() """.trimIndent(), """ while (TRUE) MATH(EXPR VAR "${"\${index}+1\""}") if (${"\${index}"} EQUAL 5) break endif() ${c}endwhile() """.trimIndent(), fileName = "CMakeLists.txt", ) } @Test fun `test reverse jump from endwhile to break`() { doTest( "g%", """ while (TRUE) MATH(EXPR VAR "${"\${index}+1\""}") if (${"\${index}"} EQUAL 5) break endif() ${c}endwhile() """.trimIndent(), """ while (TRUE) MATH(EXPR VAR "${"\${index}+1\""}") if (${"\${index}"} EQUAL 5) ${c}break endif() endwhile() """.trimIndent(), fileName = "CMakeLists.txt", ) } @Test fun `test reverse jump from break to while`() { doTest( "g%", """ while (TRUE) MATH(EXPR VAR "${"\${index}+1\""}") if (${"\${index}"} EQUAL 5) ${c}break endif() endwhile() """.trimIndent(), """ ${c}while (TRUE) MATH(EXPR VAR "${"\${index}+1\""}") if (${"\${index}"} EQUAL 5) break endif() endwhile() """.trimIndent(), fileName = "CMakeLists.txt", ) } @Test fun `test reverse jump from function to endfunction`() { doTest( "g%", """ ${c}function(foo) bar(x y z) endfunction() """.trimIndent(), """ function(foo) bar(x y z) ${c}endfunction() """.trimIndent(), fileName = "CMakeLists.txt", ) } @Test fun `test reverse jump from endfunction to function`() { doTest( "g%", """ function(foo) bar(x y z) ${c}endfunction() """.trimIndent(), """ ${c}function(foo) bar(x y z) endfunction() """.trimIndent(), fileName = "CMakeLists.txt", ) } @Test fun `test reverse jump from macro to endmacro`() { doTest( "g%", """ ${c}macro(Foo arg) message("arg = ${"\${arg}\""}") endmacro() """.trimIndent(), """ macro(Foo arg) message("arg = ${"\${arg}\""}") ${c}endmacro() """.trimIndent(), fileName = "CMakeLists.txt", ) } @Test fun `test reverse jump from endmacro to macro`() { doTest( "g%", """ macro(Foo arg) message("arg = ${"\${arg}\""}") ${c}endmacro() """.trimIndent(), """ ${c}macro(Foo arg) message("arg = ${"\${arg}\""}") endmacro() """.trimIndent(), fileName = "CMakeLists.txt", ) } }
import kotlin.collections.* val sideEffectsHolder = mutableListOf<Int>() fun withSideEffect(param: Int): String? { sideEffectsHolder.add(param) return "Result $param" } fun box(): String { val result1 = "Result1 is: " + withSideEffect(1) if (result1 != "Result1 is: Result 1") return "FAIL 1: $result1" if (sideEffectsHolder != listOf(1)) return "FAIL 1 sideffects: $sideEffectsHolder" sideEffectsHolder.clear() val result2 = "Result2 is: " + withSideEffect(2) + "!" if (result2 != "Result2 is: Result 2!") return "FAIL 2: $result2" if (sideEffectsHolder != listOf(2)) return "FAIL 2 sideffects: $sideEffectsHolder" sideEffectsHolder.clear() val result3 = withSideEffect(31) + withSideEffect(32) if (result3 != "Result 31Result 32") return "FAIL 3: $result3" if (sideEffectsHolder != listOf(31,32)) return "FAIL 3 sideffects: $sideEffectsHolder" sideEffectsHolder.clear() val result4 = withSideEffect(41) + withSideEffect(42) + withSideEffect(43) if (result4 != "Result 41Result 42Result 43") return "FAIL 4: $result4" if (sideEffectsHolder != listOf(41,42,43)) return "FAIL 4 sideffects: $sideEffectsHolder" return "OK" }
@file:JsModule("@mui/material/ButtonBase/TouchRipple") package mui.material external interface StartActionOptions { var pulsate: Boolean? var center: Boolean? } external interface TouchRippleActions { fun start( event: react.dom.events.SyntheticEvent<*, *> = definedExternally, options: StartActionOptions = definedExternally, callback: () -> Unit = definedExternally, ) fun pulsate(event: react.dom.events.SyntheticEvent<*, *> = definedExternally) fun stop(event: react.dom.events.SyntheticEvent<*, *> = definedExternally, callback: () -> Unit = definedExternally) } @JsName("default") external val TouchRipple: react.FC<TouchRippleProps>
package org.jetbrains.kotlinx.dl.impl.util /** * Executes the given [block] function on this resource list and closes the resources correctly * even when exception is thrown from the block. Similar to [kotlin.use] extension. */ public fun <A : AutoCloseable, R> List<A>.use(block: (List<A>) -> R): R { if (isEmpty()) return block(this) var exception: Throwable? = null try { return block(this) } catch (e: Throwable) { exception = e throw e } finally { closeSafely(exception) } } /** * Executes the given [block] function on this resources map and closes the resources correctly * even when exception is thrown from the block. Similar to [kotlin.use] extension. */ public fun <K, A : AutoCloseable, R> Map<K, A>.use(block: (Map<K, A>) -> R): R { if (isEmpty()) return block(this) var exception: Throwable? = null try { return block(this) } catch (e: Throwable) { exception = e throw e } finally { values.closeSafely(exception) } } private fun <A : AutoCloseable> Collection<A>.closeSafely(cause: Throwable?) { forEach { try { it.close() } catch (e: Throwable) { cause?.addSuppressed(e) } } }
external interface I { fun foo(): String } interface J { fun bar(): String } external abstract class B() : I external class A(x: String) : B { override fun foo(): String = definedExternally } fun createObject(): Any = A("OK") fun <T> castToI(o: Any): T where T : I, T : B = o as T fun box() = castToI<A>(createObject()).foo() // FILE: castToTypeParamBoundedByNativeInterface.js function B() { } function A(x) { this.x = x; } A.prototype = Object.create(B.prototype); A.prototype.foo = function() { return this.x; }
package org.jetbrains.kotlinx.dataframe.io import org.apache.commons.csv.CSVFormat import org.apache.commons.csv.CSVRecord import org.jetbrains.kotlinx.dataframe.AnyFrame import org.jetbrains.kotlinx.dataframe.AnyRow import org.jetbrains.kotlinx.dataframe.DataColumn import org.jetbrains.kotlinx.dataframe.DataFrame import org.jetbrains.kotlinx.dataframe.api.* import org.jetbrains.kotlinx.dataframe.codeGen.DefaultReadCsvMethod import org.jetbrains.kotlinx.dataframe.codeGen.DefaultReadDfMethod import org.jetbrains.kotlinx.dataframe.impl.ColumnNameGenerator import org.jetbrains.kotlinx.dataframe.impl.api.Parsers import org.jetbrains.kotlinx.dataframe.impl.api.parse import org.jetbrains.kotlinx.dataframe.values import java.io.BufferedReader import java.io.File import java.io.FileInputStream import java.io.FileWriter import java.io.IOException import java.io.InputStream import java.io.InputStreamReader import java.io.Reader import java.io.StringReader import java.io.StringWriter import java.math.BigDecimal import java.net.URL import java.nio.charset.Charset import java.time.LocalDate import java.time.LocalDateTime import java.time.LocalTime import java.util.zip.GZIPInputStream import kotlin.reflect.KClass import kotlin.reflect.full.withNullability import kotlin.reflect.typeOf public class CSV(private val delimiter: Char = ',') : SupportedDataFrameFormat { override fun readDataFrame(stream: InputStream, header: List<String>): AnyFrame = DataFrame.readCSV(stream = stream, delimiter = delimiter, header = header) override fun readDataFrame(file: File, header: List<String>): AnyFrame = DataFrame.readCSV(file = file, delimiter = delimiter, header = header) override fun acceptsExtension(ext: String): Boolean = ext == "csv" override fun acceptsSample(sample: SupportedFormatSample): Boolean = true // Extension is enough override val testOrder: Int = 20000 override fun createDefaultReadMethod(pathRepresentation: String?): DefaultReadDfMethod { val arguments = MethodArguments().add("delimiter", typeOf<Char>(), "'%L'", delimiter) return DefaultReadCsvMethod(pathRepresentation, arguments) } } public enum class CSVType(public val format: CSVFormat) { DEFAULT(CSVFormat.DEFAULT.withAllowMissingColumnNames().withIgnoreSurroundingSpaces()), TDF(CSVFormat.TDF.withAllowMissingColumnNames()) } private val defaultCharset = Charsets.UTF_8 internal fun isCompressed(fileOrUrl: String) = listOf("gz", "zip").contains(fileOrUrl.split(".").last()) internal fun isCompressed(file: File) = listOf("gz", "zip").contains(file.extension) internal fun isCompressed(url: URL) = isCompressed(url.path) public fun DataFrame.Companion.readDelimStr( text: String, colTypes: Map<String, ColType> = mapOf(), skipLines: Int = 0, readLines: Int? = null, ): DataFrame<*> = StringReader(text).use { readDelim(it, CSVType.DEFAULT.format.withHeader(), colTypes, skipLines, readLines) } public fun DataFrame.Companion.read( fileOrUrl: String, delimiter: Char, header: List<String> = listOf(), colTypes: Map<String, ColType> = mapOf(), skipLines: Int = 0, readLines: Int? = null, duplicate: Boolean = true, charset: Charset = Charsets.UTF_8, ): DataFrame<*> = catchHttpResponse(asURL(fileOrUrl)) { readDelim( it, delimiter, header, isCompressed(fileOrUrl), getCSVType(fileOrUrl), colTypes, skipLines, readLines, duplicate, charset ) } public fun DataFrame.Companion.readCSV( fileOrUrl: String, delimiter: Char = ',', header: List<String> = listOf(), colTypes: Map<String, ColType> = mapOf(), skipLines: Int = 0, readLines: Int? = null, duplicate: Boolean = true, charset: Charset = Charsets.UTF_8, parserOptions: ParserOptions? = null, ): DataFrame<*> = catchHttpResponse(asURL(fileOrUrl)) { readDelim( it, delimiter, header, isCompressed(fileOrUrl), CSVType.DEFAULT, colTypes, skipLines, readLines, duplicate, charset, parserOptions ) } public fun DataFrame.Companion.readCSV( file: File, delimiter: Char = ',', header: List<String> = listOf(), colTypes: Map<String, ColType> = mapOf(), skipLines: Int = 0, readLines: Int? = null, duplicate: Boolean = true, charset: Charset = Charsets.UTF_8, parserOptions: ParserOptions? = null, ): DataFrame<*> = readDelim( FileInputStream(file), delimiter, header, isCompressed(file), CSVType.DEFAULT, colTypes, skipLines, readLines, duplicate, charset, parserOptions ) public fun DataFrame.Companion.readCSV( url: URL, delimiter: Char = ',', header: List<String> = listOf(), colTypes: Map<String, ColType> = mapOf(), skipLines: Int = 0, readLines: Int? = null, duplicate: Boolean = true, charset: Charset = Charsets.UTF_8, parserOptions: ParserOptions? = null, ): DataFrame<*> = readCSV( url.openStream(), delimiter, header, isCompressed(url), colTypes, skipLines, readLines, duplicate, charset, parserOptions ) public fun DataFrame.Companion.readCSV( stream: InputStream, delimiter: Char = ',', header: List<String> = listOf(), isCompressed: Boolean = false, colTypes: Map<String, ColType> = mapOf(), skipLines: Int = 0, readLines: Int? = null, duplicate: Boolean = true, charset: Charset = Charsets.UTF_8, parserOptions: ParserOptions? = null, ): DataFrame<*> = readDelim( stream, delimiter, header, isCompressed, CSVType.DEFAULT, colTypes, skipLines, readLines, duplicate, charset, parserOptions ) private fun getCSVType(path: String): CSVType = when (path.substringAfterLast('.').lowercase()) { "csv" -> CSVType.DEFAULT "tdf" -> CSVType.TDF else -> throw IOException("Unknown file format") } private fun asStream(fileOrUrl: String) = ( if (isURL(fileOrUrl)) { URL(fileOrUrl).toURI() } else { File(fileOrUrl).toURI() } ).toURL().openStream() public fun asURL(fileOrUrl: String): URL = ( if (isURL(fileOrUrl)) { URL(fileOrUrl).toURI() } else { File(fileOrUrl).toURI() } ).toURL() private fun getFormat(type: CSVType, delimiter: Char, header: List<String>, duplicate: Boolean): CSVFormat = type.format.withDelimiter(delimiter).withHeader(*header.toTypedArray()).withAllowDuplicateHeaderNames(duplicate) public fun DataFrame.Companion.readDelim( inStream: InputStream, delimiter: Char = ',', header: List<String> = listOf(), isCompressed: Boolean = false, csvType: CSVType, colTypes: Map<String, ColType> = mapOf(), skipLines: Int = 0, readLines: Int? = null, duplicate: Boolean = true, charset: Charset = defaultCharset, parserOptions: ParserOptions? = null, ): AnyFrame = if (isCompressed) { InputStreamReader(GZIPInputStream(inStream), charset) } else { BufferedReader(InputStreamReader(inStream, charset)) }.run { readDelim( this, getFormat(csvType, delimiter, header, duplicate), colTypes, skipLines, readLines, parserOptions ) } public enum class ColType { Int, Long, Double, Boolean, BigDecimal, LocalDate, LocalTime, LocalDateTime, String, } public fun ColType.toType(): KClass<out Any> = when (this) { ColType.Int -> Int::class ColType.Long -> Long::class ColType.Double -> Double::class ColType.Boolean -> Boolean::class ColType.BigDecimal -> BigDecimal::class ColType.LocalDate -> LocalDate::class ColType.LocalTime -> LocalTime::class ColType.LocalDateTime -> LocalDateTime::class ColType.String -> String::class } public fun DataFrame.Companion.readDelim( reader: Reader, format: CSVFormat = CSVFormat.DEFAULT.withHeader(), colTypes: Map<String, ColType> = mapOf(), skipLines: Int = 0, readLines: Int? = null, parserOptions: ParserOptions? = null, ): AnyFrame { var reader = reader if (skipLines > 0) { reader = BufferedReader(reader) repeat(skipLines) { reader.readLine() } } val csvParser = format.parse(reader) val records = if (readLines == null) { csvParser.records } else { require(readLines >= 0) { "`readLines` must not be negative" } val records = ArrayList<CSVRecord>(readLines) val iter = csvParser.iterator() var count = readLines ?: 0 while (iter.hasNext() && 0 < count--) { records.add(iter.next()) } records } val columnNames = csvParser.headerNames.takeIf { it.isNotEmpty() } ?: (1..records[0].count()).map { index -> "X$index" } val generator = ColumnNameGenerator() val uniqueNames = columnNames.map { generator.addUnique(it) } val cols = uniqueNames.mapIndexed { colIndex, colName -> val defaultColType = colTypes[".default"] val colType = colTypes[colName] ?: defaultColType var hasNulls = false val values = records.map { if (it.isSet(colIndex)) { it[colIndex].ifEmpty { hasNulls = true null } } else { hasNulls = true null } } val column = DataColumn.createValueColumn(colName, values, typeOf<String>().withNullability(hasNulls)) when (colType) { null -> column.tryParse(parserOptions) else -> { val parser = Parsers[colType.toType()]!! column.parse(parser, parserOptions) } } } return cols.toDataFrame() } public fun AnyFrame.writeCSV( file: File, format: CSVFormat = CSVFormat.DEFAULT, ): Unit = writeCSV(FileWriter(file), format) public fun AnyFrame.writeCSV( path: String, format: CSVFormat = CSVFormat.DEFAULT, ): Unit = writeCSV(FileWriter(path), format) public fun AnyFrame.writeCSV( writer: Appendable, format: CSVFormat = CSVFormat.DEFAULT, ) { format.print(writer).use { printer -> if (!format.skipHeaderRecord) { printer.printRecord(columnNames()) } forEach { val values = it.values.map { when (it) { is AnyRow -> it.toJson() is AnyFrame -> it.toJson() else -> it } } printer.printRecord(values) } } } public fun AnyFrame.toCsv(format: CSVFormat = CSVFormat.DEFAULT): String = StringWriter().use { this.writeCSV(it, format) it }.toString()
package node.vm sealed external interface RunningScriptOptions : BaseOptions { /** * When `true`, if an `Error` occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. * Default: `true`. */ var displayErrors: Boolean? /** * Specifies the number of milliseconds to execute code before terminating execution. * If execution is terminated, an `Error` will be thrown. This value must be a strictly positive integer. */ var timeout: Double? /** * If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. * Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. * If execution is terminated, an `Error` will be thrown. * Default: `false`. */ var breakOnSigint: Boolean? }
package org.jetbrains.compose.internal.utils import org.gradle.api.Project import org.gradle.api.Task import org.gradle.api.tasks.TaskContainer import org.gradle.api.tasks.TaskProvider internal fun <T : Task> TaskProvider<T>.dependsOn(vararg dependencies: Any) { configure { it.dependsOn(*dependencies) } } internal inline fun <reified T : Task> Project.registerTask( name: String, crossinline fn: T.() -> Unit ): TaskProvider<T> = tasks.register(name, T::class.java) { task -> task.fn() } @Suppress("UNCHECKED_CAST") inline fun <reified T : Task> TaskContainer.registerOrConfigure( taskName: String, crossinline configureFn: T.() -> Unit ): TaskProvider<T> = when (taskName) { in names -> named(taskName) as TaskProvider<T> else -> register(taskName, T::class.java) as TaskProvider<T> }.apply { configure { it.configureFn() } }
import kotlin.contracts.* inline fun <reified T> referToReifiedGeneric(x: Any?) { contract { returns() implies (x is T) } } class Generic<T> { fun referToCaptured(x: Any?) { contract { returns() implies (x is <!CANNOT_CHECK_FOR_ERASED, ERROR_IN_CONTRACT_DESCRIPTION!>T<!>) } } } fun referToSubstituted(x: Any?) { <!ERROR_IN_CONTRACT_DESCRIPTION("Error in contract description")!>contract<!> { returns() implies (x is <!CANNOT_CHECK_FOR_ERASED!>Generic<String><!>) } } fun referToSubstitutedWithStar(x: Any?) { contract { returns() implies (x is Generic<*>) } } typealias GenericString = Generic<String> typealias FunctionalType = () -> Unit typealias SimpleType = Int fun referToAliasedGeneric(x: Any?) { <!ERROR_IN_CONTRACT_DESCRIPTION("Error in contract description")!>contract<!> { returns() implies (x is <!CANNOT_CHECK_FOR_ERASED!>GenericString<!>) } } fun referToAliasedFunctionType(x: Any?) { <!ERROR_IN_CONTRACT_DESCRIPTION("Error in contract description")!>contract<!> { returns() implies (x is <!CANNOT_CHECK_FOR_ERASED!>FunctionalType<!>) } } fun referToAliasedSimpleType(x: Any?) { contract { returns() implies (x is SimpleType) } }
package org.jetbrains.kotlin.codegen.optimization.fixStack import org.jetbrains.org.objectweb.asm.Opcodes import org.jetbrains.org.objectweb.asm.Type import org.jetbrains.org.objectweb.asm.tree.analysis.Value enum class FixStackValue( private val _size: Int, val loadOpcode: Int, val storeOpcode: Int, val popOpcode: Int ) : Value { INT(1, Opcodes.ILOAD, Opcodes.ISTORE, Opcodes.POP), LONG(2, Opcodes.LLOAD, Opcodes.LSTORE, Opcodes.POP2), FLOAT(1, Opcodes.FLOAD, Opcodes.FSTORE, Opcodes.POP), DOUBLE(2, Opcodes.DLOAD, Opcodes.DSTORE, Opcodes.POP2), OBJECT(1, Opcodes.ALOAD, Opcodes.ASTORE, Opcodes.POP), UNINITIALIZED(1, -1, -1, -1) ; override fun getSize(): Int = _size } fun Type.toFixStackValue(): FixStackValue? = when (this.sort) { Type.VOID -> null Type.BOOLEAN, Type.BYTE, Type.CHAR, Type.SHORT, Type.INT -> FixStackValue.INT Type.LONG -> FixStackValue.LONG Type.FLOAT -> FixStackValue.FLOAT Type.DOUBLE -> FixStackValue.DOUBLE Type.OBJECT, Type.ARRAY, Type.METHOD -> FixStackValue.OBJECT else -> throw AssertionError("Unexpected type: $this") }
class Ctx context(Ctx) fun Ctx.foo(): String = "NOK" context(Ctx) fun bar(foo: Ctx.() -> String ): String { return foo() } fun box(): String = with (Ctx()) { bar { "OK" } }
package com.android.tools.idea.wearpairing import com.android.ddmlib.IDevice import com.android.tools.adtui.HtmlLabel import com.android.tools.idea.avdmanager.AvdManagerConnection import com.android.tools.idea.concurrency.AndroidCoroutineScope import com.android.tools.idea.concurrency.AndroidDispatchers.uiThread import com.android.tools.idea.observable.BindingsManager import com.android.tools.idea.observable.ListenerManager import com.android.tools.idea.observable.core.BoolValueProperty import com.android.tools.idea.observable.core.ObservableBool import com.android.tools.idea.observable.core.OptionalProperty import com.android.tools.idea.run.DeviceHeadsUpListener import com.android.tools.idea.wearpairing.AndroidWearPairingBundle.Companion.message import com.android.tools.idea.wearpairing.WearPairingManager.PairingState import com.android.tools.idea.wearpairing.WearPairingManager.PhoneWearPair import com.android.tools.idea.wizard.model.ModelWizard import com.android.tools.idea.wizard.model.ModelWizardStep import com.google.common.util.concurrent.Futures import com.google.wireless.android.sdk.stats.WearPairingEvent import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import com.intellij.openapi.util.IconLoader import com.intellij.ui.HyperlinkLabel import com.intellij.ui.JBColor import com.intellij.ui.components.JBLabel import com.intellij.ui.components.JBPanel import com.intellij.ui.components.labels.LinkLabel import com.intellij.ui.icons.CachedImageIcon import com.intellij.ui.scale.ScaleContext import com.intellij.util.IconUtil import com.intellij.util.SVGLoader import com.intellij.util.ui.AsyncProcessIcon import com.intellij.util.ui.JBFont import com.intellij.util.ui.JBUI.Borders.empty import com.intellij.util.ui.UIUtil import icons.StudioIcons import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.delay import kotlinx.coroutines.flow.takeWhile import kotlinx.coroutines.launch import kotlinx.coroutines.time.withTimeoutOrNull import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeoutOrNull import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.addBorder import java.awt.EventQueue import java.awt.GridBagConstraints.HORIZONTAL import java.awt.GridBagConstraints.LINE_START import java.awt.GridBagConstraints.RELATIVE import java.awt.GridBagConstraints.REMAINDER import java.awt.GridBagConstraints.VERTICAL import java.awt.GridBagLayout import java.awt.event.ActionEvent import java.io.IOException import java.time.Duration import java.util.concurrent.CompletionStage import java.util.concurrent.Future import javax.swing.Box import javax.swing.Box.createVerticalStrut import javax.swing.Icon import javax.swing.ImageIcon import javax.swing.JButton import javax.swing.JComponent import javax.swing.JLabel import javax.swing.JPanel import javax.swing.JProgressBar import javax.swing.SwingConstants import javax.swing.event.HyperlinkListener private const val TIME_TO_SHOW_MANUAL_RETRY = 60_000L private const val TIME_TO_INSTALL_COMPANION_APP = 120_000L private const val PATH_PLAY_SCREEN = "/screens/playStore.png" private const val PATH_PLAY_SCREEN_LEGACY = "/screens/playStoreLegacy.png" private const val PATH_PAIR_SCREEN = "/screens/wearPair.png" private val LOG get() = logger<WearPairingManager>() class DevicesConnectionStep(model: WearDevicePairingModel, val project: Project?, private val wizardAction: WizardAction, private val isFirstStage: Boolean = true) : ModelWizardStep<WearDevicePairingModel>(model, "") { private val coroutineScope = AndroidCoroutineScope(this) private var runningJob: Job? = null private var backgroundJob: Job? = null // Independent of the UI state, monitors the devices for pairing private var currentUiHeader = "" private var currentUiDescription = "" private val secondStageStep = if (isFirstStage) DevicesConnectionStep(model, project, wizardAction, false) else null private lateinit var wizardFacade: ModelWizard.Facade private lateinit var phoneIDevice: IDevice private lateinit var wearIDevice: IDevice private val canGoForward = BoolValueProperty() private val deviceStateListener = ListenerManager() private val bindings = BindingsManager() private val mainPanel = JBPanel<JBPanel<*>>(GridBagLayout()).apply { border = empty(24, 24, 0, 24) } override fun createDependentSteps(): Collection<ModelWizardStep<*>> { return if (secondStageStep == null) super.createDependentSteps() else listOf(secondStageStep) } override fun onWizardStarting(wizard: ModelWizard.Facade) { wizardFacade = wizard } override fun onEntering() { startStepFlow() } override fun getComponent(): JComponent = mainPanel override fun canGoForward(): ObservableBool = canGoForward override fun canGoBack(): Boolean = false override fun dispose() { synchronized(this) { // Dispose can be called from the UI thread or from coroutines runningJob?.cancel(null) backgroundJob?.cancel(null) deviceStateListener.releaseAll() bindings.releaseAll() } } private suspend fun forceDispose() { runningJob?.cancelAndJoin() backgroundJob?.cancelAndJoin() dispose() } private fun startStepFlow() { model.removePairingOnCancel.set(true) dispose() // Cancel any previous jobs and error listeners runningJob = coroutineScope.launch(Dispatchers.IO) { if (model.selectedPhoneDevice.valueOrNull == null || model.selectedWearDevice.valueOrNull == null) { showUI(header = message("wear.assistant.device.connection.error.title"), description = message("wear.assistant.device.connection.error.subtitle")) return@launch } if (isFirstStage) { phoneIDevice = model.selectedPhoneDevice.launchDeviceIfNeeded() ?: return@launch wearIDevice = model.selectedWearDevice.launchDeviceIfNeeded() ?: return@launch secondStageStep!!.phoneIDevice = phoneIDevice secondStageStep.wearIDevice = wearIDevice waitForDevicePairingStatus(phoneIDevice, wearIDevice) LOG.warn("Devices are online") } prepareErrorListener() if (isFirstStage) { showFirstPhase(model.selectedPhoneDevice.value, phoneIDevice, model.selectedWearDevice.value, wearIDevice) } else { showSecondPhase(model.selectedPhoneDevice.value, phoneIDevice, model.selectedWearDevice.value, wearIDevice) } } } private suspend fun showFirstPhase(phonePairingDevice: PairingDevice, phoneDevice: IDevice, wearPairingDevice: PairingDevice, wearDevice: IDevice) { if (!phoneDevice.hasPairingFeature(PairingFeature.MULTI_WATCH_SINGLE_PHONE_PAIRING)) { showDeviceGmscoreNeedsUpdate(phonePairingDevice) phoneDevice.executeShellCommand("am start -a android.intent.action.VIEW -d 'market://details?id=com.google.android.gms'") showEmbeddedEmulator(phoneDevice) return } if (!wearDevice.hasPairingFeature(PairingFeature.REVERSE_PORT_FORWARD)) { showDeviceGmscoreNeedsUpdate(wearPairingDevice) wearDevice.executeShellCommand("am start -a android.intent.action.VIEW -d 'market://details?id=com.google.android.gms'") showEmbeddedEmulator(wearDevice) return } showUiBridgingDevices() if (checkWearMayNeedFactoryReset(phoneDevice, wearDevice)) { showUiNeedsFactoryReset(model.selectedWearDevice.value.displayName) return } val isNewWearPairingDevice = WearPairingManager.getInstance().getPairsForDevice(phonePairingDevice.deviceID) .firstOrNull { wearPairingDevice.deviceID == it.wear.deviceID } == null WearPairingManager.getInstance().removeAllPairedDevices(wearPairingDevice.deviceID, restartWearGmsCore = isNewWearPairingDevice) companionAppStep(phoneDevice, wearDevice) } private suspend fun companionAppStep(phoneDevice: IDevice, wearDevice: IDevice) { val companionAppId = wearDevice.getCompanionAppIdForWatch() if (phoneDevice.isCompanionAppInstalled(companionAppId)) { // Companion App already installed, go to the next step goToNextStep() } else if (companionAppId == PIXEL_COMPANION_APP_ID || companionAppId == OEM_COMPANION_FALLBACK_APP_ID) { showUiInstallCompanionAppInstructions(phoneDevice, wearDevice) } else { showIncompatibleCompanionAppError(phoneDevice, wearDevice) } } private fun showIncompatibleCompanionAppError(phoneDevice: IDevice, wearDevice: IDevice) { dispose() coroutineScope.launch(Dispatchers.IO) { val body = createWarningPanel(message("wear.assistant.device.connection.wear.os.wear3")) body.add( LinkLabel<Unit>("Retry", null) { _, _ -> check(runningJob?.isActive != true) // This is a manual retry. No job should be running at this point. runningJob = coroutineScope.launch(Dispatchers.IO) { companionAppStep(phoneDevice, wearDevice) } }, gridConstraint(x = 1, y = RELATIVE, anchor = LINE_START) ) showUI(header = currentUiHeader, description = currentUiDescription, body = body) } } private fun showDeviceGmscoreNeedsUpdate(device: PairingDevice) { coroutineScope.launch(Dispatchers.IO) { val warningMessage = if (device.isWearDevice) { "wear.assistant.device.connection.gmscore.error.wear" } else if (device.isEmulator) { "wear.assistant.device.connection.gmscore.error.phone.emulator" } else { "wear.assistant.device.connection.gmscore.error.phone.physical" } val body = createWarningPanel(message(warningMessage, device.displayName), StudioIcons.Common.ERROR) body.add( LinkLabel<Unit>(message("wear.assistant.device.connection.restart.pairing"), null) { _, _ -> wizardAction.restart(project) }.addBorder( empty(10, 0)), gridConstraint(x = 1, y = RELATIVE, anchor = LINE_START) ) showUI(header = currentUiHeader, description = currentUiDescription, body = body) } } private suspend fun showWaitForCompanionAppInstall(phoneDevice: IDevice, wearDevice: IDevice, launchPlayStore: Boolean) { if (launchPlayStore) { showUiInstallCompanionAppScanning(phoneDevice, wearDevice, scanningLabelKey = "wear.assistant.device.connection.scanning.wear.os.btn") phoneDevice.executeShellCommand( "am start -a android.intent.action.VIEW -d 'market://details?id=${wearDevice.getCompanionAppIdForWatch()}'") showEmbeddedEmulator(phoneDevice) } else { showUiInstallCompanionAppScanning(phoneDevice, wearDevice, scanningLabelKey = "wear.assistant.device.connection.scanning.wear.os.lnk") } if (waitForCondition(TIME_TO_INSTALL_COMPANION_APP) { phoneDevice.isCompanionAppInstalled(wearDevice.getCompanionAppIdForWatch()) }) { showUiInstallCompanionAppSuccess(phoneDevice, wearDevice) canGoForward.set(true) } else { showUiInstallCompanionAppRetry(phoneDevice, wearDevice) // After some time we give up and show the manual retry ui } } private suspend fun showSecondPhase(phone: PairingDevice, phoneDevice: IDevice, wear: PairingDevice, wearDevice: IDevice) { // Note: createPairedDeviceBridge() may restart GmsCore, so it may take a bit of time until pairing. Show some UI placeholder. showUiBridgingDevices() try { val phoneWearPair = WearPairingManager.getInstance().createPairedDeviceBridge(phone, phoneDevice, wear, wearDevice) if (phoneWearPair.pairingStatus != PairingState.CONNECTED) { showPairing(phoneWearPair, phoneDevice, wearDevice) } waitForPairingSuccessOnBackground(phoneWearPair, phoneDevice, wearDevice) } catch (ex: IOException) { showGenericError(ex) } } private suspend fun showPairing(phoneWearPair: PhoneWearPair, phoneDevice: IDevice, wearDevice: IDevice) { val companionAppId = wearDevice.getCompanionAppIdForWatch() if (phoneDevice.hasPairingFeature(PairingFeature.COMPANION_EMULATOR_ACTIVITY, companionAppId)) { showUiPairingNonInteractive(phoneWearPair, phoneDevice, wearDevice) NonInteractivePairing.startPairing(this, phoneDevice, wearDevice.avdName!!, companionAppId, wearDevice.loadNodeID()).use { withTimeoutOrNull(Duration.ofMinutes(1)) { it.pairingState.takeWhile { !it.hasFinished() }.collect { state -> if (state == NonInteractivePairing.PairingState.CONSENT) { showUiPairingNonInteractive(phoneWearPair, phoneDevice, wearDevice, message("wear.assistant.device.connection.pairing.auto.consent", phoneWearPair.phone.displayName)) } } } if (WearPairingManager.getInstance().updateDeviceStatus(phoneWearPair, phoneDevice, wearDevice) != PairingState.CONNECTED) { showUiPairingNonInteractive(phoneWearPair, phoneDevice, wearDevice, message("wear.assistant.device.connection.pairing.auto.failed"), "Retry", "Skip to manual instructions", false) } // else waitForPairingSuccessOnBackground() will take care of success case } } else { showUiPairingAppInstructions(phoneWearPair, phoneDevice, wearDevice) } } private suspend fun showWaitForPairingSetup(phoneWearPair: PhoneWearPair, phoneDevice: IDevice, wearDevice: IDevice, launchCompanionApp: Boolean) { if (launchCompanionApp) { showUiPairingScanning(phoneWearPair, phoneDevice, wearDevice, scanningLabel = message("wear.assistant.device.connection.wait.pairing.btn")) // Use monkey here as it avoids having to specify an activity for each companion app phoneDevice.executeShellCommand("monkey -p ${wearDevice.getCompanionAppIdForWatch()} -c android.intent.category.LAUNCHER 1") showEmbeddedEmulator(phoneDevice) } else { showUiPairingScanning(phoneWearPair, phoneDevice, wearDevice, scanningLabel = message("wear.assistant.device.connection.wait.pairing.lnk")) } // After some time we give up and show the manual retry ui. waitForPairingSuccessOnBackground() will take care of success case delay(TIME_TO_SHOW_MANUAL_RETRY) showUiPairingRetry(phoneWearPair, phoneDevice, wearDevice) } private fun waitForPairingSuccessOnBackground(phoneWearPair: PhoneWearPair, phoneDevice: IDevice, wearDevice: IDevice) { check(backgroundJob?.isActive != true) // There can only be a single background job at any time backgroundJob = coroutineScope.launch(Dispatchers.IO) { try { while (phoneWearPair.pairingStatus != PairingState.CONNECTED && WearPairingManager.getInstance().updateDeviceStatus(phoneWearPair, phoneDevice, wearDevice) != PairingState.CONNECTED) { delay(2_000) } // If 2.x companion older than 773393865 is used with manual pairing, we have to let the // user know how they can finish the pairing on the companion. val showTapAndFinishWarning = !phoneDevice.hasPairingFeature(PairingFeature.COMPANION_SKIP_AND_FINISH_FIXED, wearDevice.getCompanionAppIdForWatch()) showPairingSuccess(phoneWearPair.phone.displayName, phoneWearPair.wear.displayName, showTapAndFinishWarning) } catch (ex: IOException) { showGenericError(ex) } } } private suspend fun showPairingSuccess(phoneName: String, watchName: String, tapAndFinishWarning: Boolean) { showUiPairingSuccess(phoneName, watchName, tapAndFinishWarning) canGoForward.set(true) } private suspend fun OptionalProperty<PairingDevice>.launchDeviceIfNeeded(): IDevice? { try { showUiLaunchingDevice(value.displayName) val iDevice = value.launch(project).await() value.launch = { Futures.immediateFuture(iDevice) } // We can only launch AVDs once! // If it was not launched by us, it may still be booting. Wait for "boot complete". while (!iDevice.arePropertiesSet() || iDevice.getProperty("dev.bootcomplete") == null) { LOG.warn("${iDevice.name} not ready yet") delay(2000) } return iDevice } catch (ex: Throwable) { showDeviceError( header = message("wear.assistant.connection.alert.cant.start.device.title", value.displayName), description = " ", errorMessage = message("wear.assistant.connection.alert.cant.start.device.subtitle", value.displayName) ) LOG.warn("Failed to launch device", ex) return null } } private suspend fun IDevice.waitForPairingStatus() { if (hasPairingFeature(PairingFeature.GET_PAIRING_STATUS)) { waitForCondition(50_000) { isPairingStatusAvailable() } } else { // Give some time for Node/Cloud ID to load, but not too long, as it may just mean it never paired before waitForCondition(50_000) { loadNodeID().isNotEmpty() } waitForCondition(10_000) { loadCloudNetworkID(ignoreNullOutput = false).isNotEmpty() } } } private suspend fun waitForDevicePairingStatus(phoneDevice: IDevice, wearDevice: IDevice) { showUiWaitingDeviceStatus() val companionAppId = wearDevice.getCompanionAppIdForWatch() if (phoneDevice.isCompanionAppInstalled(companionAppId)) { // No need to wait, if Companion App is not installed phoneDevice.waitForPairingStatus() } wearDevice.waitForPairingStatus() } private suspend fun showUI( header: String = "", description: String = "", progressTopLabel: String = "", progressBottomLabel: String = "", body: JComponent? = null, imagePath: String = "" ) = withContext(uiThread(ModalityState.any())) { currentUiHeader = header currentUiDescription = description mainPanel.apply { removeAll() if (header.isNotEmpty()) { add(JBLabel(header, UIUtil.ComponentStyle.LARGE).apply { name = "header" font = JBFont.label().biggerOn(5.0f) }, gridConstraint(x = 0, y = RELATIVE, weightx = 1.0, fill = HORIZONTAL, gridwidth = 3)) } if (description.isNotEmpty()) { add(HtmlLabel().apply { name = "description" HtmlLabel.setUpAsHtmlLabel(this) text = description border = empty(20, 0, 20, 16) }, gridConstraint(x = 0, y = RELATIVE, weightx = 1.0, fill = HORIZONTAL, gridwidth = 3)) } if (progressTopLabel.isNotEmpty()) { add(JBLabel(progressTopLabel).apply { border = empty(4, 0) }, gridConstraint(x = 0, y = RELATIVE, weightx = 1.0, fill = HORIZONTAL, gridwidth = 2)) add(JProgressBar().apply { isIndeterminate = true }, gridConstraint(x = 0, y = RELATIVE, weightx = 1.0, fill = HORIZONTAL, gridwidth = 2)) } if (progressBottomLabel.isNotEmpty()) { add(JBLabel(progressBottomLabel).apply { border = empty(4, 0) foreground = JBColor.DARK_GRAY }, gridConstraint(x = 0, y = RELATIVE, weightx = 1.0, fill = HORIZONTAL, gridwidth = 2)) } if (body != null) { add(body, gridConstraint(x = 0, y = RELATIVE, weightx = 1.0, fill = HORIZONTAL, gridwidth = 2)) } if (imagePath.isNotEmpty()) { add(JBLabel(IconLoader.getIcon(imagePath, DevicesConnectionStep::class.java.classLoader)).apply { verticalAlignment = JLabel.BOTTOM }, gridConstraint(x = 2, y = RELATIVE, fill = VERTICAL, weighty = 1.0).apply { gridheight = REMAINDER }) } add(Box.createVerticalGlue(), gridConstraint(x = 0, y = RELATIVE, weighty = 1.0)) revalidate() repaint() } } private fun createScanningPanel( firstStepLabel: String, buttonLabel: String, buttonListener: (ActionEvent) -> Unit = {}, showLoadingIcon: Boolean, showSuccessIcon: Boolean, scanningLabel: String, scanningLink: String, scanningListener: HyperlinkListener?, additionalStepsLabel: String ): JPanel = JPanel(GridBagLayout()).apply { add( JBLabel(firstStepLabel).addBorder(empty(8, 0, 8, 0)), gridConstraint(x = 0, y = 0, weightx = 1.0, fill = HORIZONTAL, gridwidth = 2) ) if (buttonLabel.isNotBlank()) { add( JButton(buttonLabel).apply { addActionListener(buttonListener) }, gridConstraint(x = 0, y = RELATIVE, gridwidth = 2, anchor = LINE_START) ) } add( JBLabel(additionalStepsLabel).addBorder(empty(8, 0, 0, 0)), gridConstraint(x = 0, y = RELATIVE, weightx = 1.0, fill = HORIZONTAL, gridwidth = 2) ) if (showLoadingIcon) { add( AsyncProcessIcon("ScanningLabel").addBorder(empty(0, 0, 0, 8)), gridConstraint(x = 0, y = RELATIVE) ) } if (showSuccessIcon || scanningLabel.isNotEmpty()) { add( JBLabel(scanningLabel).apply { foreground = JBColor.DARK_GRAY icon = StudioIcons.Common.SUCCESS.takeIf { showSuccessIcon } }.addBorder(empty(4, 0, 0, 0)), when (showLoadingIcon) { // Scanning label may be on the right of the "loading" icon true -> gridConstraint(x = 1, y = RELATIVE, weightx = 1.0, fill = HORIZONTAL, gridwidth = 1) else -> gridConstraint(x = 0, y = RELATIVE, weightx = 1.0, fill = HORIZONTAL, gridwidth = 2) } ) } if (scanningLink.isNotEmpty()) { add( HyperlinkLabel().apply { setHyperlinkText(scanningLink) addHyperlinkListener(scanningListener) }.addBorder(empty(4, 0, 0, 0)), gridConstraint(x = 0, y = RELATIVE, weightx = 1.0, fill = HORIZONTAL, gridwidth = 2) ) } isOpaque = false border = empty(8, 2, 12, 4) } private suspend fun showUiLaunchingDevice(progressTopLabel: String, progressBottomLabel: String) = showUI( header = message("wear.assistant.device.connection.start.device.title"), description = message("wear.assistant.device.connection.start.device.subtitle"), progressTopLabel = progressTopLabel, progressBottomLabel = progressBottomLabel ) private suspend fun showUiLaunchingDevice(deviceName: String) = showUiLaunchingDevice( progressTopLabel = message("wear.assistant.device.connection.start.device.top.label"), progressBottomLabel = message("wear.assistant.device.connection.start.device.bottom.label", deviceName) ) private suspend fun showUiWaitingDeviceStatus() = showUiLaunchingDevice( progressTopLabel = message("wear.assistant.device.connection.connecting.device.top.label"), progressBottomLabel = message("wear.assistant.device.connection.status.device.bottom.label") ) private suspend fun showUiBridgingDevices() = showUiLaunchingDevice( progressTopLabel = message("wear.assistant.device.connection.connecting.device.top.label"), progressBottomLabel = message("wear.assistant.device.connection.connecting.device.bottom.label") ) private suspend fun showUiInstallCompanionAppInstructions(phoneDevice: IDevice, wearDevice: IDevice) { showUiInstallCompanionApp( phoneDevice = phoneDevice, wearDevice = wearDevice ) WearPairingUsageTracker.log(WearPairingEvent.EventKind.SHOW_INSTALL_WEAR_OS_COMPANION) } private suspend fun showUiInstallCompanionAppScanning(phoneDevice: IDevice, wearDevice: IDevice, scanningLabelKey: String) = showUiInstallCompanionApp( phoneDevice = phoneDevice, showLoadingIcon = true, scanningLabelKey = scanningLabelKey, wearDevice = wearDevice ) private suspend fun showUiInstallCompanionAppSuccess(phoneDevice: IDevice, wearDevice: IDevice) = showUiInstallCompanionApp( phoneDevice = phoneDevice, wearDevice = wearDevice, showSuccessIcon = true, scanningLabelKey = "wear.assistant.device.connection.wear.os.installed", ) private suspend fun showUiInstallCompanionAppRetry(phoneDevice: IDevice, wearDevice: IDevice) = showUiInstallCompanionApp( phoneDevice = phoneDevice, wearDevice = wearDevice, scanningLabelKey = "wear.assistant.device.connection.wear.os.missing", scanningLink = message("wear.assistant.device.connection.check.again"), scanningListener = { check(runningJob?.isActive != true) // This is a manual retry. No job should be running at this point. runningJob = coroutineScope.launch(Dispatchers.IO) { showWaitForCompanionAppInstall(phoneDevice, wearDevice, launchPlayStore = false) } }, ) private suspend fun showUiInstallCompanionApp( phoneDevice: IDevice, showLoadingIcon: Boolean = false, showSuccessIcon: Boolean = false, scanningLabelKey: String = "", scanningLink: String = "", scanningListener: HyperlinkListener? = null, wearDevice: IDevice ) { // scanningLabelKey resource must contain exactly one parameter for companion app name val companionAppName = if (wearDevice.getCompanionAppIdForWatch() == PIXEL_COMPANION_APP_ID) message( "wear.assistant.companion.app.name") else message("wear.assistant.companion.app.name.legacy") val scanningLabel = if (scanningLabelKey.isNotEmpty()) message(scanningLabelKey, companionAppName) else "" showUI( header = message("wear.assistant.device.connection.install.wear.os.title"), description = message("wear.assistant.device.connection.install.wear.os.subtitle", companionAppName, WEAR_DOCS_LINK), body = createScanningPanel( firstStepLabel = message("wear.assistant.device.connection.install.wear.os.firstStep", companionAppName), buttonLabel = message("wear.assistant.device.connection.install.wear.os.button", companionAppName), buttonListener = { runningJob?.cancel() runningJob = coroutineScope.launch(Dispatchers.IO) { showWaitForCompanionAppInstall(phoneDevice, wearDevice, launchPlayStore = true) } }, showLoadingIcon = showLoadingIcon, showSuccessIcon = showSuccessIcon, scanningLabel = scanningLabel, scanningLink = scanningLink, scanningListener = scanningListener, additionalStepsLabel = message("wear.assistant.device.connection.install.wear.os.additionalSteps", companionAppName), ), imagePath = if (wearDevice.getCompanionAppIdForWatch() == PIXEL_COMPANION_APP_ID) PATH_PLAY_SCREEN else PATH_PLAY_SCREEN_LEGACY, ) } private suspend fun showUiPairing( phoneWearPair: PhoneWearPair, phoneDevice: IDevice, wearDevice: IDevice, showLoadingIcon: Boolean = false, showSuccessIcon: Boolean = false, scanningLabel: String = "", scanningLink: String = "", scanningListener: HyperlinkListener? = null ) = showUI( header = message("wear.assistant.device.connection.complete.pairing.title"), description = message("wear.assistant.device.connection.complete.pairing.subtitle", WEAR_DOCS_LINK), body = createScanningPanel( firstStepLabel = message("wear.assistant.device.connection.complete.pairing.firstStep"), buttonLabel = message("wear.assistant.device.connection.open.companion.button"), buttonListener = { runningJob?.cancel() runningJob = coroutineScope.launch(Dispatchers.IO) { showWaitForPairingSetup(phoneWearPair, phoneDevice, wearDevice, launchCompanionApp = true) } }, showLoadingIcon = showLoadingIcon, showSuccessIcon = showSuccessIcon, scanningLabel = scanningLabel, scanningLink = scanningLink, scanningListener = scanningListener, additionalStepsLabel = message("wear.assistant.device.connection.complete.pairing.additionalSteps"), ), imagePath = PATH_PAIR_SCREEN, ) private suspend fun showUiPairingNonInteractive(phoneWearPair: PhoneWearPair, phoneDevice: IDevice, wearDevice: IDevice, scanningLabel: String = message( "wear.assistant.device.connection.pairing.auto.start"), buttonLabel: String = "", scanningLink: String = "", showLoadingIcon: Boolean = true) = showUI( header = message("wear.assistant.device.connection.pairing.auto.title"), body = createScanningPanel( firstStepLabel = message("wear.assistant.device.connection.pairing.auto.step"), buttonLabel = buttonLabel, buttonListener = { runningJob?.cancel() runningJob = coroutineScope.launch(Dispatchers.IO) { showPairing(phoneWearPair, phoneDevice, wearDevice) } }, showLoadingIcon = showLoadingIcon, showSuccessIcon = false, scanningLabel = scanningLabel, scanningLink = scanningLink, scanningListener = { runningJob?.cancel() runningJob = coroutineScope.launch(Dispatchers.IO) { showUiPairingAppInstructions(phoneWearPair, phoneDevice, wearDevice) } }, additionalStepsLabel = "", ) ) private suspend fun showUiPairingAppInstructions(wearPairing: PhoneWearPair, phoneDevice: IDevice, wearDevice: IDevice) = showUiPairing( wearPairing, phoneDevice = phoneDevice, wearDevice = wearDevice, ) private suspend fun showUiPairingScanning(phoneWearPair: PhoneWearPair, phoneDevice: IDevice, wearDevice: IDevice, scanningLabel: String) = showUiPairing( phoneWearPair = phoneWearPair, phoneDevice = phoneDevice, wearDevice = wearDevice, showLoadingIcon = true, scanningLabel = scanningLabel, ) private suspend fun showUiPairingSuccess(phoneName: String, watchName: String, tapAndFinishWarning: Boolean) { // Load svg image offline check(!EventQueue.isDispatchThread()) val svgUrl = (StudioIcons.Common.SUCCESS as CachedImageIcon).url!! val svgImg = SVGLoader.load(svgUrl, svgUrl.openStream(), ScaleContext.create(mainPanel), 150.0, 150.0) val successLabel = message(if (tapAndFinishWarning) { "wear.assistant.device.connection.pairing.success.skipandfinish" } else { "wear.assistant.device.connection.pairing.success.subtitle" }, phoneName, watchName) val svgLabel = JBLabel(successLabel).apply { horizontalAlignment = SwingConstants.CENTER horizontalTextPosition = JLabel.CENTER verticalTextPosition = JLabel.BOTTOM icon = ImageIcon(svgImg) } // Show ui on UI Thread withContext(uiThread(ModalityState.any())) { mainPanel.apply { removeAll() add(JBLabel(message("wear.assistant.device.connection.pairing.success.title"), UIUtil.ComponentStyle.LARGE).apply { font = JBFont.label().biggerOn(5.0f) }, gridConstraint(x = 0, y = RELATIVE, weightx = 1.0, fill = HORIZONTAL)) add(Box.createVerticalGlue(), gridConstraint(x = 0, y = RELATIVE, weighty = 1.0)) add(svgLabel, gridConstraint(x = 0, y = RELATIVE, weightx = 1.0, fill = HORIZONTAL)) add(Box.createVerticalGlue(), gridConstraint(x = 0, y = RELATIVE, weighty = 1.0)) revalidate() repaint() } } WearPairingUsageTracker.log(WearPairingEvent.EventKind.SHOW_SUCCESSFUL_PAIRING) } private suspend fun showUiNeedsFactoryReset(wearDeviceName: String) { val wipeButton = JButton(message("wear.assistant.factory.reset.button")) val warningPanel = createWarningPanel(message("wear.assistant.factory.reset.subtitle", wearDeviceName)).apply { add(createVerticalStrut(8), gridConstraint(x = 1, y = RELATIVE)) add(wipeButton, gridConstraint(x = 1, y = RELATIVE, anchor = LINE_START)) border = empty(20, 0, 0, 0) } val actionListener: (ActionEvent) -> Unit = { warningPanel.remove(wipeButton) warningPanel.add( JLabel(message("wear.assistant.factory.reset.progress", wearDeviceName)).addBorder(empty(0, 0, 4, 0)), gridConstraint(x = 1, y = RELATIVE, anchor = LINE_START) ) warningPanel.add(JProgressBar().apply { isIndeterminate = true }, gridConstraint(x = 1, y = RELATIVE, fill = HORIZONTAL)) check(runningJob?.isActive != true) // This is a button callback. No job should be running at this point. dispose() // Stop listening for device connection lost runningJob = coroutineScope.launch(Dispatchers.IO) { try { showUI(header = message("wear.assistant.factory.reset.title"), body = warningPanel) val wearDeviceId = model.selectedWearDevice.valueOrNull?.deviceID ?: "" val avdManager = AvdManagerConnection.getDefaultAvdManagerConnection() avdManager.getAvds(false).firstOrNull { it.id == wearDeviceId }?.apply { WearPairingManager.getInstance().removeAllPairedDevices(wearDeviceId, restartWearGmsCore = false) avdManager.stopAvd(this) waitForCondition(10_000) { model.selectedWearDevice.valueOrNull?.isOnline() != true } avdManager.wipeUserData(this) } } finally { startStepFlow() } } } wipeButton.addActionListener(actionListener) showUI(header = message("wear.assistant.factory.reset.title"), body = warningPanel) } private suspend fun showUiPairingRetry(phoneWearPair: PhoneWearPair, phoneDevice: IDevice, wearDevice: IDevice) = showUiPairing( phoneWearPair = phoneWearPair, phoneDevice = phoneDevice, wearDevice = wearDevice, scanningLabel = message("wear.assistant.device.connection.pairing.not.detected"), scanningLink = message("wear.assistant.device.connection.check.again"), scanningListener = { check(runningJob?.isActive != true) // This is a manual retry. No job should be running at this point. runningJob = coroutineScope.launch(Dispatchers.IO) { showWaitForPairingSetup(phoneWearPair, phoneDevice, wearDevice, launchCompanionApp = false) } } ) private fun prepareErrorListener() { deviceStateListener.listenAll(model.selectedPhoneDevice, model.selectedWearDevice).withAndFire { val errorDevice = model.selectedPhoneDevice.valueOrNull.takeIf { it?.isOnline() == false } ?: model.selectedWearDevice.valueOrNull.takeIf { it?.isOnline() == false } if (errorDevice != null) { showDeviceError( header = currentUiHeader, description = currentUiDescription, errorMessage = message("wear.assistant.device.connection.error", errorDevice.displayName) ) } } } private fun showDeviceError(header: String, description: String, errorMessage: String) { coroutineScope.launch(uiThread) { forceDispose() val body = createWarningPanel(errorMessage) body.add( JButton(message("wear.assistant.connection.alert.button.try.again")).apply { addActionListener { wizardAction.restart(project) } }, gridConstraint(x = 1, y = RELATIVE, anchor = LINE_START) ) showUI(header = header, description = description, body = body) } } private fun showGenericError(ex: Throwable) { LOG.warn("Error connecting devices", ex) showDeviceError( header = message("wear.assistant.connection.alert.cant.bridge.title"), description = " ", errorMessage = message("wear.assistant.connection.alert.cant.bridge.subtitle") ) } private fun goToNextStep() { ApplicationManager.getApplication().invokeLater({ // The "Next" button changes asynchronously. Create a temporary property that will change state at the same time. val doGoForward = BoolValueProperty() bindings.bind(doGoForward, canGoForward) deviceStateListener.listenAndFire(doGoForward) { if (canGoForward.get()) { dispose() ApplicationManager.getApplication().invokeLater({ wizardFacade.goForward() }, ModalityState.any()) } } canGoForward.set(true) }, ModalityState.any()) } private fun showEmbeddedEmulator(device: IDevice) { // Show embedded emulator tab if needed project?.messageBus?.syncPublisher(DeviceHeadsUpListener.TOPIC)?.userInvolvementRequired(device.serialNumber, project) } } private fun createWarningPanel(errorMessage: String, icon: Icon = StudioIcons.Common.WARNING): JPanel = JPanel(GridBagLayout()).apply { add(JBLabel(IconUtil.scale(icon, null, 2f)).withBorder(empty(0, 0, 0, 8)), gridConstraint(x = 0, y = 0)) add(HtmlLabel().apply { name = "errorMessage" HtmlLabel.setUpAsHtmlLabel(this) text = errorMessage }, gridConstraint(x = 1, y = 0, weightx = 1.0, fill = HORIZONTAL)) } suspend fun <T> Future<T>.await(): T { // There is no good way to convert a Java Future to a suspendCoroutine if (this is CompletionStage<*>) { @Suppress("UNCHECKED_CAST") return this.await() } while (!isDone) { delay(100) } @Suppress("BlockingMethodInNonBlockingContext") return get() // If isDone() returned true, this call will not block } private suspend fun waitForCondition(timeMillis: Long, condition: suspend () -> Boolean): Boolean { val res = withTimeoutOrNull(timeMillis) { while (!condition()) { delay(1000) } true } return res == true } private suspend fun checkWearMayNeedFactoryReset(phoneDevice: IDevice, wearDevice: IDevice): Boolean { if (wearDevice.hasPairingFeature(PairingFeature.GET_PAIRING_STATUS)) { val (wearNodeId, wearPairingStatus) = wearDevice.getPairingStatus() if (wearNodeId != null) { // Only need factory reset if the watch thinks it's paired with another phone return wearPairingStatus.isNotEmpty() && !wearPairingStatus[0].nodeId.isNullOrEmpty() && !wearPairingStatus[0].nodeId.equals(phoneDevice.loadNodeID(), ignoreCase = true) } } val phoneCloudID = phoneDevice.loadCloudNetworkID() val wearCloudID = wearDevice.loadCloudNetworkID() return wearCloudID.isNotEmpty() && phoneCloudID != wearCloudID }
interface MyCollection<out E1> { fun foo(): E1 val bar: E1 } interface MyList<out E2> : MyCollection<E2> { override fun foo(): E2 override val bar: E2 } interface MyMutableCollection<E3> : MyCollection<E3> interface MyMutableList<E4> : MyList<E4>, MyMutableCollection<E4> abstract class MyAbstractCollection<out E5> protected constructor() : MyCollection<E5> { abstract override fun foo(): E5 abstract override val bar: E5 } class MyArrayList<E6> : MyMutableList<E6>, MyAbstractCollection<E6>() { override fun foo(): E6 = "O" as E6 override val bar: E6 = "K" as E6 } class MC : MyMutableCollection<String> by MyArrayList() fun box(): String { val x = MC() return x.foo() + x.bar }
package org.jetbrains.letsPlot.core.spec.config import demoAndTestShared.TestingGeomLayersBuilder.getSingleGeomLayer import org.jetbrains.letsPlot.commons.values.Color import org.jetbrains.letsPlot.commons.values.Colors import org.jetbrains.letsPlot.core.plot.base.Aes import org.jetbrains.letsPlot.core.plot.base.DataPointAesthetics import org.jetbrains.letsPlot.core.plot.builder.GeomLayer import org.jetbrains.letsPlot.core.plot.builder.PlotUtil import org.jetbrains.letsPlot.core.plot.builder.scale.provider.ColorBrewerMapperProvider import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNull class ScaleOrderingTest { private val myData = """{ 'x' : [ "B", "A", "B", "B", "A", "A", "A", "B", "B", "C", "C", "B", "C" ], 'fill': [ '4', '2', '3', '3', '2', '3', '1', '1', '3', '4', '2', '2', '2' ], 'color': [ '1', '0', '2', '1', '1', '2', '1', '1', '0', '2', '0', '0', '0' ] }""" private val myMappingFill: String = """{ "x": "x", "fill": "fill" }""" private val myMappingFillColor = """{ "x": "x", "fill": "fill", "color": "color" }""" private fun makePlotSpec( annotations: String, sampling: String? = null, data: String = myData, mapping: String = myMappingFill ): String { return """{ "kind": "plot", "layers": [ { "data" : $data, "mapping": $mapping, "geom": "bar", "data_meta": { "mapping_annotations": [ $annotations ] }, "sampling" : $sampling } ] }""".trimIndent() } private fun makeOrderingSettings(aes: String, orderBy: String?, order: Int?): String { val orderByVar = if (orderBy != null) { "\"" + "$orderBy" + "\"" } else null return """{ "aes": "$aes", "annotation": "as_discrete", "parameters": { "order" : $order, "order_by" : $orderByVar } }""".trimIndent() } @Test fun default() { val geomLayer = getSingleGeomLayer(makePlotSpec("")) assertScaleOrdering( geomLayer, expectedScaleBreaks = mapOf( Aes.X to listOf("B", "C", "A"), Aes.FILL to listOf("4", "2", "3", "1") ), expectedOrderInBar = mapOf( Aes.FILL to listOf( listOf("4", "2", "3", "1"), // B listOf("4", "2"), // C listOf("2", "3", "1") // A ) ) ) } @Test fun `order x`() { run { //ascending val orderingSettings = makeOrderingSettings("x", null, 1) val geomLayer = getSingleGeomLayer(makePlotSpec(orderingSettings)) assertScaleOrdering( geomLayer, expectedScaleBreaks = mapOf( Aes.X to listOf("A", "B", "C"), Aes.FILL to listOf("4", "2", "3", "1") ), expectedOrderInBar = mapOf( Aes.FILL to listOf( listOf("2", "3", "1"), // A listOf("4", "2", "3", "1"), // B listOf("4", "2") // C ) ) ) } run { //descending val orderingSettings = makeOrderingSettings("x", null, -1) val geomLayer = getSingleGeomLayer(makePlotSpec(orderingSettings)) assertScaleOrdering( geomLayer, expectedScaleBreaks = mapOf( Aes.X to listOf("C", "B", "A"), Aes.FILL to listOf("4", "2", "3", "1") ), expectedOrderInBar = mapOf( Aes.FILL to listOf( listOf("4", "2"), // C listOf("4", "2", "3", "1"), // B listOf("2", "3", "1"), // A ) ) ) } } @Test fun `order fill`() { run { //ascending val orderingSettings = makeOrderingSettings("fill", null, 1) val geomLayer = getSingleGeomLayer(makePlotSpec(orderingSettings)) assertScaleOrdering( geomLayer, expectedScaleBreaks = mapOf( Aes.FILL to listOf("1", "2", "3", "4"), Aes.X to listOf("A", "B", "C") ), expectedOrderInBar = mapOf( Aes.FILL to listOf( listOf("1", "2", "3"), // A listOf("1", "2", "3", "4"), // B listOf("2", "4"), // C ) ) ) } run { //descending val orderingSettings = makeOrderingSettings("fill", null, -1) val geomLayer = getSingleGeomLayer(makePlotSpec(orderingSettings)) assertScaleOrdering( geomLayer, expectedScaleBreaks = mapOf( Aes.FILL to listOf("4", "3", "2", "1"), Aes.X to listOf("B", "C", "A") ), expectedOrderInBar = mapOf( Aes.FILL to listOf( listOf("4", "3", "2", "1"), // B listOf("4", "2"), // C listOf("3", "2", "1") // A ) ) ) } } @Test fun `order x by count`() { run { //ascending val orderingSettings = makeOrderingSettings("x", "..count..", 1) val geomLayer = getSingleGeomLayer(makePlotSpec(orderingSettings)) assertScaleOrdering( geomLayer, expectedScaleBreaks = mapOf( Aes.X to listOf("C", "A", "B"), Aes.FILL to listOf("4", "2", "3", "1") ), expectedOrderInBar = mapOf( Aes.FILL to listOf( listOf("4", "2"), // C listOf("2", "3", "1"), // A listOf("4", "2", "3", "1") // B ) ) ) } run { //descending val orderingSettings = makeOrderingSettings("x", "..count..", -1) val geomLayer = getSingleGeomLayer(makePlotSpec(orderingSettings)) assertScaleOrdering( geomLayer, expectedScaleBreaks = mapOf( Aes.X to listOf("B", "A", "C"), Aes.FILL to listOf("4", "2", "3", "1") ), expectedOrderInBar = mapOf( Aes.FILL to listOf( listOf("4", "2", "3", "1"), // B listOf("2", "3", "1"), // A listOf("4", "2") // C ) ) ) } } @Test fun `order x and fill`() { run { //x descending - fill ascending val orderingSettings = makeOrderingSettings("x", null, -1) + "," + makeOrderingSettings("fill", null, 1) val geomLayer = getSingleGeomLayer(makePlotSpec(orderingSettings)) assertScaleOrdering( geomLayer, expectedScaleBreaks = mapOf( Aes.X to listOf("C", "B", "A"), Aes.FILL to listOf("1", "2", "3", "4") ), expectedOrderInBar = mapOf( Aes.FILL to listOf( listOf("2", "4"), // C listOf("1", "2", "3", "4"), // B listOf("1", "2", "3") // A ) ) ) } run { //x descending - fill descending val orderingSettings = makeOrderingSettings("x", null, -1) + "," + makeOrderingSettings("fill", null, -1) val geomLayer = getSingleGeomLayer(makePlotSpec(orderingSettings)) assertScaleOrdering( geomLayer, expectedScaleBreaks = mapOf( Aes.X to listOf("C", "B", "A"), Aes.FILL to listOf("4", "3", "2", "1") ), expectedOrderInBar = mapOf( Aes.FILL to listOf( listOf("4", "2"), // C listOf("4", "3", "2", "1"), // B listOf("3", "2", "1") // A ) ) ) } } @Test fun `order x by count and fill by itself`() { run { //ascending val orderingSettings = makeOrderingSettings("x", "..count..", 1) + "," + makeOrderingSettings("fill", null, 1) val geomLayer = getSingleGeomLayer(makePlotSpec(orderingSettings)) assertScaleOrdering( geomLayer, expectedScaleBreaks = mapOf( Aes.X to listOf("C", "A", "B"), Aes.FILL to listOf("1", "2", "3", "4") ), expectedOrderInBar = mapOf( Aes.FILL to listOf( listOf("2", "4"), // C listOf("1", "2", "3"), // A listOf("1", "2", "3", "4") // B ) ) ) } run { //descending val orderingSettings = makeOrderingSettings("x", "..count..", -1) + "," + makeOrderingSettings("fill", null, -1) val geomLayer = getSingleGeomLayer(makePlotSpec(orderingSettings)) assertScaleOrdering( geomLayer, expectedScaleBreaks = mapOf( Aes.X to listOf("B", "A", "C"), Aes.FILL to listOf("4", "3", "2", "1") ), expectedOrderInBar = mapOf( Aes.FILL to listOf( listOf("4", "3", "2", "1"), // B listOf("3", "2", "1"), // A listOf("4", "2") // C ) ) ) } } @Test fun `order by fill and color`() { val orderingSettings = makeOrderingSettings("color", null, 1) + "," + makeOrderingSettings("fill", null, 1) val geomLayer = getSingleGeomLayer(makePlotSpec(orderingSettings, mapping = myMappingFillColor)) assertScaleOrdering( geomLayer, expectedScaleBreaks = mapOf( Aes.COLOR to listOf("0", "1", "2"), Aes.FILL to listOf("1", "2", "3", "4"), Aes.X to listOf("A", "C", "B") ), expectedOrderInBar = mapOf( Aes.FILL to listOf( listOf("2", "1", "2", "3"), // A listOf("2", "4"), // C listOf("2", "3", "1", "3", "4", "3"), // B ), Aes.COLOR to listOf( listOf("0", "1", "1", "2"), // A listOf("0", "2"), // C listOf("0", "0", "1", "1", "1", "2"), // B ), ) ) } @Test fun `pick sampling`() { val samplingPick = """{ "name": "pick", "n": 2 }""" run { // no ordering val geomLayer = getSingleGeomLayer(makePlotSpec("", samplingPick)) assertScaleOrdering( geomLayer, expectedScaleBreaks = mapOf( Aes.X to listOf("B", "C"), Aes.FILL to listOf("4", "2", "3", "1") ), expectedOrderInBar = mapOf( Aes.FILL to listOf( listOf("4", "2", "3", "1"), // B listOf("4", "2") // C ) ) ) } run { // Order x val orderingSettings = makeOrderingSettings("x", null, -1) val geomLayer = getSingleGeomLayer(makePlotSpec(orderingSettings, samplingPick)) assertScaleOrdering( geomLayer, expectedScaleBreaks = mapOf( Aes.X to listOf("C", "B"), Aes.FILL to listOf("4", "2", "3", "1") ), expectedOrderInBar = mapOf( Aes.FILL to listOf( listOf("4", "2"), // C listOf("4", "2", "3", "1") // B ) ) ) } run { // Order x and fill val orderingSettings = makeOrderingSettings("x", null, -1) + "," + makeOrderingSettings("fill", null, 1) val geomLayer = getSingleGeomLayer(makePlotSpec(orderingSettings, samplingPick)) assertScaleOrdering( geomLayer, expectedScaleBreaks = mapOf( Aes.X to listOf("C", "B"), Aes.FILL to listOf("1", "2", "3", "4") ), expectedOrderInBar = mapOf( Aes.FILL to listOf( listOf("2", "4"), // C listOf("1", "2", "3", "4") // B ) ) ) } run { // Order x by count val orderingSettings = makeOrderingSettings("x", "..count..", 1) val geomLayer = getSingleGeomLayer(makePlotSpec(orderingSettings, samplingPick)) assertScaleOrdering( geomLayer, expectedScaleBreaks = mapOf( Aes.X to listOf("C", "A"), Aes.FILL to listOf("4", "2", "3", "1") ), expectedOrderInBar = mapOf( Aes.FILL to listOf( listOf("4", "2"), // C listOf("2", "3", "1") // A ) ) ) } } @Test fun `apply pick sampling after group sampling`() { val samplingGroup = """{ "name": "group_systematic", "n": 2 }""" val samplingPick = """{ "name": "pick", "n": 2 }""" val sampling = """{ "feature-list": [ { "sampling": $samplingGroup }, { "sampling": $samplingPick } ] }""" // After group sampling: B, C, A run { // No ordering. val geomLayer = getSingleGeomLayer(makePlotSpec("", sampling)) assertScaleOrdering( geomLayer, expectedScaleBreaks = mapOf( Aes.X to listOf("B", "C"), Aes.FILL to listOf("4", "1") ), expectedOrderInBar = mapOf( Aes.FILL to listOf( listOf("4", "1"), // B listOf("4") // C ) ) ) } run { // Order x. val orderingSettings = makeOrderingSettings("x", null, 1) val geomLayer = getSingleGeomLayer(makePlotSpec(orderingSettings, sampling)) assertScaleOrdering( geomLayer, expectedScaleBreaks = mapOf( Aes.X to listOf("A", "B"), Aes.FILL to listOf("4", "1") ), expectedOrderInBar = mapOf( Aes.FILL to listOf( listOf("1"), // A listOf("4", "1") // B ) ) ) } } @Test fun `group sampling`() { val samplingGroup = """{ "name": "group_systematic", "n": 3 }""" run { // Default - no ordering val geomLayer = getSingleGeomLayer(makePlotSpec("", samplingGroup)) assertScaleOrdering( geomLayer, expectedScaleBreaks = mapOf( Aes.X to listOf("B", "C", "A"), Aes.FILL to listOf("4", "3") ), expectedOrderInBar = mapOf( Aes.FILL to listOf( listOf("4", "3"), // B listOf("4"), // C listOf("3") // A ) ) ) } run { // Order x val orderingSettings = makeOrderingSettings("x", null, 1) val geomLayer = getSingleGeomLayer(makePlotSpec(orderingSettings, samplingGroup)) assertScaleOrdering( geomLayer, expectedScaleBreaks = mapOf( Aes.X to listOf("A", "B", "C"), Aes.FILL to listOf("4", "3") ), expectedOrderInBar = mapOf( Aes.FILL to listOf( listOf("3"), // A listOf("4", "3"), // B listOf("4") // C ) ) ) } } @Test fun `order in the bar and in the legend should be the same`() { val data = """{ 'x' : [ "A", "A", "A"], 'fill': [ "2", "1", "3"] }""" val orderingSettings = makeOrderingSettings("fill", "..count..", -1) val spec = makePlotSpec(orderingSettings, data = data) val geomLayer = getSingleGeomLayer(spec) val expectedOrder = listOf("3", "2", "1") assertScaleOrdering( geomLayer, expectedScaleBreaks = mapOf(Aes.FILL to expectedOrder), expectedOrderInBar = mapOf( Aes.FILL to listOf(expectedOrder) ) ) } @Test fun `all null values`() { val data = """{ 'x' : [ null, null ], 'fill': [ null, null ] }""" val orderingSettings = makeOrderingSettings("fill", null, 1) val spec = makePlotSpec(orderingSettings, data = data) val geomLayer = getSingleGeomLayer(spec) assertScaleOrdering( geomLayer, expectedScaleBreaks = mapOf(Aes.FILL to null), expectedOrderInBar = mapOf(Aes.FILL to null) ) } @Test fun `'order by' variable has null value`() { val data = """{ 'x' : [ "A", "A", "A", "A"], 'fill': [ "3", null, "1", "2"] }""" run { //ascending val orderingSettings = makeOrderingSettings("fill", null, 1) val spec = makePlotSpec(orderingSettings, data = data) val geomLayer = getSingleGeomLayer(spec) assertScaleOrdering( geomLayer, expectedScaleBreaks = mapOf(Aes.FILL to listOf("1", "2", "3")), expectedOrderInBar = mapOf( Aes.FILL to listOf(listOf("1", "2", "3", null)) ) ) } run { //descending val orderingSettings = makeOrderingSettings("fill", null, -1) val spec = makePlotSpec(orderingSettings, data = data) val geomLayer = getSingleGeomLayer(spec) assertScaleOrdering( geomLayer, expectedScaleBreaks = mapOf(Aes.FILL to listOf("3", "2", "1")), expectedOrderInBar = mapOf( Aes.FILL to listOf(listOf("3", "2", "1", null)) ) ) } } @Test fun `few ordering fields with null values`() { val data = """{ 'x' : [ "A", "A", "A"], 'fill': [ null, "v", null], 'color': [ '2', null, '1'] }""" run { // color ascending val orderingSettings = makeOrderingSettings("color", null, 1) + "," + makeOrderingSettings("fill", null, 1) val spec = makePlotSpec(orderingSettings, data = data, mapping = myMappingFillColor) val geomLayer = getSingleGeomLayer(spec) assertScaleOrdering( geomLayer, expectedScaleBreaks = mapOf( Aes.COLOR to listOf("1", "2"), Aes.FILL to listOf("v") ), expectedOrderInBar = mapOf( Aes.COLOR to listOf(listOf("1", "2", null)), Aes.FILL to listOf(listOf(null, null, "v")) ) ) } run { // color descending val orderingSettings = makeOrderingSettings("color", null, -1) + "," + makeOrderingSettings("fill", null, 1) val spec = makePlotSpec(orderingSettings, data = data, mapping = myMappingFillColor) val geomLayer = getSingleGeomLayer(spec) assertScaleOrdering( geomLayer, expectedScaleBreaks = mapOf( Aes.COLOR to listOf("2", "1"), Aes.FILL to listOf("v") ), expectedOrderInBar = mapOf( Aes.COLOR to listOf(listOf("2", "1", null)), Aes.FILL to listOf(listOf(null, null, "v")) ) ) } run { // color ascending val orderingSettings = makeOrderingSettings("fill", null, 1) + "," + makeOrderingSettings("color", null, 1) val spec = makePlotSpec(orderingSettings, data = data, mapping = myMappingFillColor) val geomLayer = getSingleGeomLayer(spec) assertScaleOrdering( geomLayer, expectedScaleBreaks = mapOf( Aes.COLOR to listOf("1", "2"), Aes.FILL to listOf("v") ), expectedOrderInBar = mapOf( Aes.FILL to listOf(listOf("v", null, null)), Aes.COLOR to listOf(listOf(null, "1", "2")) ) ) } run { // color descending val orderingSettings = makeOrderingSettings("fill", null, 1) + "," + makeOrderingSettings("color", null, -1) val spec = makePlotSpec(orderingSettings, data = data, mapping = myMappingFillColor) val geomLayer = getSingleGeomLayer(spec) assertScaleOrdering( geomLayer, expectedScaleBreaks = mapOf( Aes.COLOR to listOf("2", "1"), Aes.FILL to listOf("v") ), expectedOrderInBar = mapOf( Aes.FILL to listOf(listOf("v", null, null)), Aes.COLOR to listOf(listOf(null, "2", "1")) ) ) } } // The variable is mapped to different aes @Test fun `x='x', fill='x' - default`() { val mapping = """{ "x": "x", "fill": "x" }""" val geomLayer = getSingleGeomLayer(makePlotSpec(annotations = "", mapping = mapping)) assertScaleBreaks(geomLayer, Aes.X, listOf("B", "A", "C")) assertScaleBreaks(geomLayer, Aes.FILL, listOf("B", "A", "C")) } @Test // Now 'x' and 'fill' mapped to different variables ("x.x" and "fill.x") => should not inherit options fun `x=as_discrete('x', order=1), fill='x' - the ordering does no apply to the 'fill'`() { val mapping = """{ "x": "x", "fill": "x" }""" val orderingSettings = makeOrderingSettings("x", null, 1) val geomLayer = getSingleGeomLayer(makePlotSpec(orderingSettings, mapping = mapping)) assertScaleBreaks(geomLayer, Aes.X, listOf("A", "B", "C")) assertScaleBreaks(geomLayer, Aes.FILL, listOf("B", "A", "C")) } @Test // Now 'x' and 'fill' mapped to different variables ("x.x" and "fill.x") => should not combine options fun `x=as_discrete('x', order=1), fill=as_discrete('x') - should not apply the ordering to the 'fill'`() { val mapping = """{ "x": "x", "fill": "x" }""" val orderingSettings = makeOrderingSettings("x", null, 1) + "," + makeOrderingSettings("fill", null, null) val geomLayer = getSingleGeomLayer(makePlotSpec(orderingSettings, mapping = mapping)) assertScaleBreaks(geomLayer, Aes.X, listOf("A", "B", "C")) assertScaleBreaks(geomLayer, Aes.FILL, listOf("B", "A", "C")) } @Test // Now 'x' and 'fill' mapped to different variables ("x.x" and "fill.x") => should not combine options fun `x=as_discrete('x', order_by='count'), fill=as_discrete('x', order=1) - should not combine order options`() { val mapping = """{ "x": "x", "fill": "x" }""" val orderingSettings = makeOrderingSettings("x", "..count..", order = null) + "," + makeOrderingSettings("fill", orderBy = null, order = 1) val geomLayer = getSingleGeomLayer(makePlotSpec(orderingSettings, mapping = mapping)) assertScaleBreaks(geomLayer, Aes.X, listOf("B", "A", "C")) assertScaleBreaks(geomLayer, Aes.FILL, listOf("A", "B", "C")) } // variable in plot and layer @Test // Now 'x' and 'fill' mapped to different variables ("x.x" and "x") => should not inherit options fun `ggplot(aes(as_discrete('x',order=1))) + geom_bar(aes(fill='x')) - should not apply the ordering to the 'fill'`() { val spec = """{ "kind": "plot", "data" : $myData, "mapping": { "x": "x" }, "data_meta": { "mapping_annotations": [ ${makeOrderingSettings("x", null, 1)} ] }, "layers": [ { "mapping": { "fill": "x" }, "geom": "bar" } ] }""".trimIndent() val geomLayer = getSingleGeomLayer(spec) assertScaleBreaks(geomLayer, Aes.X, listOf("A", "B", "C")) assertScaleBreaks(geomLayer, Aes.FILL, listOf("B", "A", "C")) } @Test // Now 'x' and 'fill' mapped to different variables ("x" and "fill.x") => should not inherit options fun `ggplot(aes('x')) + geom_bar(aes(fill=as_discrete('x',order=1))) - should not apply the ordering to the 'x'`() { val spec = """{ "kind": "plot", "data" : $myData, "mapping": { "x": "x" }, "layers": [ { "mapping": { "fill": "x" }, "geom": "bar", "data_meta": { "mapping_annotations": [ ${makeOrderingSettings("fill", null, 1)} ] } } ] }""".trimIndent() val geomLayer = getSingleGeomLayer(spec) assertScaleBreaks(geomLayer, Aes.X, listOf("B", "A", "C")) assertScaleBreaks(geomLayer, Aes.FILL, listOf("A", "B", "C")) } companion object { private fun assertScaleBreaks( layer: GeomLayer, aes: Aes<*>, expectedScaleBreaks: List<Any>? ) { val scale = layer.scaleMap[aes] if (expectedScaleBreaks == null) { assertNull(scale, "Scale for ${aes.name.uppercase()} should not be present") } else { assertEquals( expectedScaleBreaks, scale!!.getScaleBreaks().domainValues, "Wrong ticks order on ${aes.name.uppercase()}." ) } } private fun getBarColumnValues( geomLayer: GeomLayer, valueToColors: Map<Color, Any>, colorFactory: (DataPointAesthetics) -> Color? ): Map<Int, List<Any?>> { val colorInColumns = mutableMapOf<Int, ArrayList<Color>>() // val aesthetics = PlotUtil.createLayerDryRunAesthetics(geomLayer) val aesthetics = PlotUtil.DemoAndTest.layerAestheticsWithoutLayout(geomLayer) for (index in 0 until aesthetics.dataPointCount()) { val p = aesthetics.dataPointAt(index) val x = p.x()!! val color = colorFactory(p)!! colorInColumns.getOrPut(x.toInt(), ::ArrayList).add(color) } return colorInColumns.map { (x, values) -> x to values.map { color -> valueToColors[color] } }.toMap() } private val legendColors = ColorBrewerMapperProvider.DEFAULT_QUAL_COLOR_SCHEME.getColors(4).map(Colors::parseColor) internal fun assertScaleOrdering( geomLayer: GeomLayer, expectedScaleBreaks: Map<Aes<*>, List<String>?>, expectedOrderInBar: Map<Aes<*>, List<List<*>>?> ) { expectedScaleBreaks.forEach { (aes, breaks) -> assertScaleBreaks(geomLayer, aes, breaks) } expectedOrderInBar.forEach { (aes, expected) -> val scale = geomLayer.scaleMap[aes] if (expected == null) { assertNull(scale, "Scale for ${aes.name.uppercase()} should not be present") } else { val breaks = scale!!.getScaleBreaks().domainValues val breakColors = breaks.zip(legendColors).associate { it.second to it.first } val actual: Map<Int, List<Any?>> = getBarColumnValues(geomLayer, breakColors) { p: DataPointAesthetics -> if (aes == Aes.FILL) p.fill() else p.color() } assertEquals(expected.size, actual.size) for (i in expected.indices) { assertEquals(expected[i], actual[i], "Wrong color order in ${aes.name.uppercase()}.") } } } } } }
annotation class Foo(val b: Byte) @Foo('8'.toByte()) const val x = '8'.toByte() fun box(): String { return if (x == 56.toByte()) { "OK" } else { "FAIL" } }
package org.jetbrains.kotlin import com.google.gson.annotations.Expose import java.io.PrintWriter import java.io.StringWriter import org.gradle.api.Project enum class TestStatus { PASSED, FAILED, ERROR, SKIPPED } data class Statistics( @Expose var passed: Int = 0, @Expose var failed: Int = 0, @Expose var error: Int = 0, @Expose var skipped: Int = 0) { fun pass(count: Int = 1) { passed += count } fun skip(count: Int = 1) { skipped += count } fun fail(count: Int = 1) { failed += count } fun error(count: Int = 1) { error += count } fun add(other: Statistics) { passed += other.passed failed += other.failed error += other.error skipped += other.skipped } } val Statistics.total: Int get() = passed + failed + error + skipped class TestFailedException(msg:String) : RuntimeException(msg) data class KonanTestGroupReport(@Expose val name: String, val suites: List<KonanTestSuiteReport>) data class KonanTestSuiteReport(@Expose val name: String, val tests: List<KonanTestCaseReport>) data class KonanTestCaseReport(@Expose val name: String, @Expose val status: TestStatus, @Expose val comment: String? = null) class KonanTestSuiteReportEnvironment(val name: String, val project: Project, val statistics: Statistics) { private val tc = if ((System.getenv("TEAMCITY_BUILD_PROPERTIES_FILE") != null)) TeamCityTestPrinter(project) else null val tests = mutableListOf<KonanTestCaseReport>() fun executeTest(testName: String, action:() -> Unit) { var test: KonanTestCaseReport? try { tc?.startTest(testName) action() tc?.passTest(testName) statistics.pass() test = KonanTestCaseReport(testName, TestStatus.PASSED) } catch (e:TestFailedException) { tc?.failedTest(testName, e) statistics.fail() test = KonanTestCaseReport(testName, TestStatus.FAILED, "Exception: ${e.message}. Cause: ${e.cause?.message}") project.logger.quiet("test: $testName failed") } catch (e:Exception) { tc?.errorTest(testName, e) statistics.error() test = KonanTestCaseReport(testName, TestStatus.ERROR, "Exception: ${e.message}. Cause: ${e.cause?.message}") project.logger.quiet("error on test: $testName", e) } test!!.apply { tests += this if (status == TestStatus.ERROR || status == TestStatus.FAILED) { project.logger.quiet("Command to reproduce: ./gradlew $name -Pfilter=${test.name}\n") } } } fun skipTest(name: String) { tc?.skipTest(name) statistics.skip() tests += KonanTestCaseReport(name, TestStatus.SKIPPED) } fun abort(comment: String, throwable: Throwable, testNames: List<String>) { testNames.forEach { tc?.startTest(it) tc?.errorTest(it, java.lang.Exception(throwable)) tests += KonanTestCaseReport(it, TestStatus.ERROR, "$comment\n${throwable.toString()}") } abort(throwable, testNames.size) } fun abort(throwable: Throwable, count: Int) { statistics.error(count) project.logger.quiet("suite `$name` aborted with exception", throwable) } internal operator fun invoke(action: (KonanTestSuiteReportEnvironment) -> Unit) { tc?.suiteStart(name) action(this) tc?.suiteFinish(name) } } class KonanTestGroupReportEnvironment(val project:Project) { val statistics = Statistics() val suiteReports = mutableListOf<KonanTestSuiteReport>() fun suite(suiteName:String, action:(KonanTestSuiteReportEnvironment)->Unit) { val konanTestSuiteEnvironment = KonanTestSuiteReportEnvironment(suiteName, project, statistics) konanTestSuiteEnvironment { action(it) } suiteReports += KonanTestSuiteReport(suiteName, konanTestSuiteEnvironment.tests) } } private class TeamCityTestPrinter(val project:Project) { fun suiteStart(name: String) { teamcityReport("testSuiteStarted name='$name'") } fun suiteFinish(name: String) { teamcityReport("testSuiteFinished name='$name'") } fun startTest(name: String) { teamcityReport("testStarted name='$name'") } fun passTest(testName: String) = teamcityFinish(testName) fun failedTest(testName: String, testFailedException: TestFailedException) { teamcityReport("testFailed type='comparisonFailure' name='$testName' message='${testFailedException.message.toTeamCityFormat()}'") teamcityFinish(testName) } fun errorTest(testName: String, exception: Exception) { val writer = StringWriter() exception.printStackTrace(PrintWriter(writer)) val rawString = writer.toString() teamcityReport("testFailed name='$testName' message='${exception.message.toTeamCityFormat()}' " + "details='${rawString.toTeamCityFormat()}'") teamcityFinish(testName) } fun skipTest(testName: String) { teamcityReport("testIgnored name='$testName'") teamcityFinish(testName) } private fun teamcityFinish(testName:String) { teamcityReport("testFinished name='$testName'") } /** * Teamcity require escaping some symbols in pipe manner. * https://github.com/GitTools/GitVersion/issues/94 */ private fun String?.toTeamCityFormat(): String = this?.let { it.replace("\\|", "||") .replace("\r", "|r") .replace("\n", "|n") .replace("'", "|'") .replace("\\[", "|[") .replace("]", "|]")} ?: "null" private fun teamcityReport(msg: String) { project.logger.quiet("##teamcity[$msg]") } }
package foo class A<T>(val list: MutableList<T>) { fun addAll(c: Collection<T>) { list.addAll(c) } } operator fun <T> A<T>.plusAssign(other: Collection<T>) { addAll(other) } fun box(): String { var v1 = arrayListOf("foo") val v2 = listOf("bar") val a = A(v1) a += v2 if (v1.size != 2) return "fail1: ${v1.size}" if (v1[0] != "foo") return "fail2: ${v1[0]}" if (v1[1] != "bar") return "fail3: ${v1[1]}" return "OK" }
package org.jetbrains.kotlin.contracts.model.functors /** * Applies [operation] to [first] and [second] if both not-null, otherwise returns null */ internal fun <F, S, R> applyIfBothNotNull(first: F?, second: S?, operation: (F, S) -> R): R? = if (first == null || second == null) null else operation(first, second) /** * If both [first] and [second] are null, then return null * If only one of [first] and [second] is null, then return other one * Otherwise, return result of [operation] */ internal fun <F : R, S : R, R> applyWithDefault(first: F?, second: S?, operation: (F, S) -> R): R? = when { first == null && second == null -> null first == null -> second second == null -> first else -> operation(first, second) }
package one interface Interface { fun foo(param: String) } open class ClassWithParameter(i: Interface) class TopLevelClass : ClassWithParameter(object : Interface { override fun fo<caret>o(param: String) { } })
@file:kotlin.jvm.JvmMultifileClass @file:kotlin.jvm.JvmName("Test") fun foo() { } /* ACC_PUBLIC ACC_FINAL ACC_SUPER */ // 1 access flags 0x31 // 1 public final class Test /* ACC_SYNTHETIC ACC_FINAL ACC_SUPER */ // 1 access flags 0x1030 // 1 final synthetic class Test__SuperFlagInMultiFileFacadeKt
@file:Suppress("FunctionName") package org.jetbrains.kotlin.gradle.dependencyResolutionTests.tcs import org.jetbrains.kotlin.compilerRunner.konanVersion import org.jetbrains.kotlin.gradle.dsl.multiplatformExtension import org.jetbrains.kotlin.gradle.idea.testFixtures.tcs.assertMatches import org.jetbrains.kotlin.gradle.idea.testFixtures.tcs.binaryCoordinates import org.jetbrains.kotlin.gradle.plugin.ide.dependencyResolvers.IdeNativePlatformDependencyResolver import org.jetbrains.kotlin.gradle.util.buildProjectWithMPP import org.jetbrains.kotlin.konan.target.HostManager import org.jetbrains.kotlin.konan.target.KonanTarget.LINUX_X64 import org.jetbrains.kotlin.konan.target.KonanTarget.MACOS_ARM64 import org.junit.Assume import kotlin.test.Test class IdeNativePlatformDependencyResolverTest { @Test fun `test - posix on linux`() { val project = buildProjectWithMPP() val kotlin = project.multiplatformExtension kotlin.applyDefaultHierarchyTemplate() kotlin.linuxX64() project.evaluate() val commonMain = kotlin.sourceSets.getByName("commonMain") val commonTest = kotlin.sourceSets.getByName("commonTest") val linuxX64Main = kotlin.sourceSets.getByName("linuxX64Main") val linuxX64Test = kotlin.sourceSets.getByName("linuxX64Test") val dependencies = listOf( binaryCoordinates("org.jetbrains.kotlin.native:posix:$LINUX_X64:${project.konanVersion}"), binaryCoordinates(Regex("""org\.jetbrains\.kotlin\.native:.*:$LINUX_X64:${project.konanVersion}""")) ) IdeNativePlatformDependencyResolver.resolve(commonMain).assertMatches(dependencies) IdeNativePlatformDependencyResolver.resolve(commonTest).assertMatches(dependencies) IdeNativePlatformDependencyResolver.resolve(linuxX64Main).assertMatches(dependencies) IdeNativePlatformDependencyResolver.resolve(linuxX64Test).assertMatches(dependencies) } @Test fun `test - CoreFoundation on macos`() { Assume.assumeTrue("Macos host required for this test", HostManager.hostIsMac) val project = buildProjectWithMPP() val kotlin = project.multiplatformExtension kotlin.applyDefaultHierarchyTemplate() kotlin.macosArm64() project.evaluate() val commonMain = kotlin.sourceSets.getByName("commonMain") val commonTest = kotlin.sourceSets.getByName("commonTest") val macosArm64Main = kotlin.sourceSets.getByName("macosArm64Main") val macosArm64Test = kotlin.sourceSets.getByName("macosArm64Test") val dependencies = listOf( binaryCoordinates("org.jetbrains.kotlin.native:CoreFoundation:$MACOS_ARM64:${project.konanVersion}"), binaryCoordinates(Regex("""org\.jetbrains\.kotlin\.native:.*:$MACOS_ARM64:${project.konanVersion}""")) ) IdeNativePlatformDependencyResolver.resolve(commonMain).assertMatches(dependencies) IdeNativePlatformDependencyResolver.resolve(commonTest).assertMatches(dependencies) IdeNativePlatformDependencyResolver.resolve(macosArm64Main).assertMatches(dependencies) IdeNativePlatformDependencyResolver.resolve(macosArm64Test).assertMatches(dependencies) } @Test fun `test - non native source sets`() { val project = buildProjectWithMPP() val kotlin = project.multiplatformExtension kotlin.jvm() kotlin.linuxX64() project.evaluate() val commonMain = kotlin.sourceSets.getByName("commonMain") val commonTest = kotlin.sourceSets.getByName("commonTest") val jvmMain = kotlin.sourceSets.getByName("jvmMain") val jvmTest = kotlin.sourceSets.getByName("jvmTest") IdeNativePlatformDependencyResolver.resolve(commonMain).assertMatches(emptyList<Any>()) IdeNativePlatformDependencyResolver.resolve(commonTest).assertMatches(emptyList<Any>()) IdeNativePlatformDependencyResolver.resolve(jvmMain).assertMatches(emptyList<Any>()) IdeNativePlatformDependencyResolver.resolve(jvmTest).assertMatches(emptyList<Any>()) } }
package org.jetbrains.kotlin.backend.jvm.intrinsics import org.jetbrains.kotlin.backend.jvm.codegen.* import org.jetbrains.kotlin.backend.jvm.ir.receiverAndArgs import org.jetbrains.kotlin.ir.expressions.IrExpression import org.jetbrains.kotlin.ir.expressions.IrFunctionAccessExpression import org.jetbrains.org.objectweb.asm.Label object OrOr : IntrinsicMethod() { private class BooleanDisjunction( val left: IrExpression, val right: IrExpression, codegen: ExpressionCodegen, val data: BlockInfo ) : BooleanValue(codegen) { override fun jumpIfFalse(target: Label) { val stayLabel = Label() val leftValue = left.accept(codegen, data).coerceToBoolean() markLineNumber(left) leftValue.jumpIfTrue(stayLabel) val rightValue = right.accept(codegen, data).coerceToBoolean() markLineNumber(right) rightValue.jumpIfFalse(target) mv.visitLabel(stayLabel) } override fun jumpIfTrue(target: Label) { val leftValue = left.accept(codegen, data).coerceToBoolean() markLineNumber(left) leftValue.jumpIfTrue(target) val rightValue = right.accept(codegen, data).coerceToBoolean() markLineNumber(right) rightValue.jumpIfTrue(target) } override fun discard() { val end = Label() val leftValue = left.accept(codegen, data).coerceToBoolean() markLineNumber(left) leftValue.jumpIfTrue(end) val rightValue = right.accept(codegen, data) markLineNumber(right) rightValue.discard() mv.visitLabel(end) } } override fun invoke(expression: IrFunctionAccessExpression, codegen: ExpressionCodegen, data: BlockInfo): PromisedValue { val (left, right) = expression.receiverAndArgs() return BooleanDisjunction(left, right, codegen, data) } }
package test import dependency.JavaInterface import dependency.JavaInterface.Nested class Foo : JavaInterface { <expr>val prop: JavaInterface.Nested = JavaInterface.Nested()</expr> } // FILE: dependency/JavaInterface.java package dependency; public interface JavaInterface { public class Nested {} }
package org.jetbrains.kotlin.gradle.unitTests import org.gradle.api.Project import org.jetbrains.kotlin.gradle.dsl.* import org.jetbrains.kotlin.gradle.dsl.multiplatformExtension import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinMetadataTarget import org.jetbrains.kotlin.gradle.plugin.mpp.external.createCompilation import org.jetbrains.kotlin.gradle.plugin.mpp.external.createExternalKotlinTarget import org.jetbrains.kotlin.gradle.tasks.Kotlin2JsCompile import org.jetbrains.kotlin.gradle.tasks.KotlinCompilationTask import org.jetbrains.kotlin.gradle.tasks.KotlinJvmCompile as KotlinJvmCompileTask import org.jetbrains.kotlin.gradle.tasks.withType import org.jetbrains.kotlin.gradle.util.* import org.jetbrains.kotlin.gradle.utils.named import org.jetbrains.kotlin.test.util.JUnit4Assertions.assertTrue import kotlin.test.Ignore import kotlin.test.Test import kotlin.test.assertEquals class ProjectCompilerOptionsTests { @Test fun nativeTargetCompilerOptionsDSL() { val project = buildProjectWithMPP { with(multiplatformExtension) { linuxX64 { compilerOptions { progressiveMode.set(true) } } iosX64 { compilerOptions { suppressWarnings.set(true) } } applyDefaultHierarchyTemplate() } } project.evaluate() assertEquals(true, project.kotlinNativeTask("compileKotlinLinuxX64").compilerOptions.progressiveMode.get()) assertEquals(false, project.kotlinNativeTask("compileKotlinLinuxX64").compilerOptions.suppressWarnings.get()) assertEquals(true, project.kotlinNativeTask("compileTestKotlinLinuxX64").compilerOptions.progressiveMode.get()) assertEquals(false, project.kotlinNativeTask("compileTestKotlinLinuxX64").compilerOptions.suppressWarnings.get()) assertEquals(true, project.kotlinNativeTask("compileKotlinIosX64").compilerOptions.suppressWarnings.get()) assertEquals(false, project.kotlinNativeTask("compileKotlinIosX64").compilerOptions.progressiveMode.get()) assertEquals(true, project.kotlinNativeTask("compileTestKotlinIosX64").compilerOptions.suppressWarnings.get()) assertEquals(false, project.kotlinNativeTask("compileTestKotlinIosX64").compilerOptions.progressiveMode.get()) } @Test fun nativeTaskOverridesTargetOptions() { val project = buildProjectWithMPP { tasks.withType<KotlinCompilationTask<*>>().configureEach { if (it.name == "compileKotlinLinuxX64") { it.compilerOptions.progressiveMode.set(false) } } with(multiplatformExtension) { linuxX64 { compilerOptions { progressiveMode.set(true) } } applyDefaultHierarchyTemplate() } } project.evaluate() assertEquals(false, project.kotlinNativeTask("compileKotlinLinuxX64").compilerOptions.progressiveMode.get()) } @Test fun nativeLanguageSettingsOverridesTargetOptions() { val project = buildProjectWithMPP { with(multiplatformExtension) { linuxX64 { compilerOptions { progressiveMode.set(true) } } applyDefaultHierarchyTemplate() sourceSets.getByName("linuxX64Main").languageSettings { progressiveMode = false } } } project.evaluate() assertEquals(false, project.kotlinNativeTask("compileKotlinLinuxX64").compilerOptions.progressiveMode.get()) } @Test fun jvmTargetCompilerOptionsDSL() { val project = buildProjectWithMPP { with(multiplatformExtension) { jvm { compilerOptions { noJdk.set(true) } } applyDefaultHierarchyTemplate() } } project.evaluate() assertEquals(true, project.kotlinJvmTask("compileKotlinJvm").compilerOptions.noJdk.get()) assertEquals(true, project.kotlinJvmTask("compileTestKotlinJvm").compilerOptions.noJdk.get()) } @Test fun jvmTaskOverridesTargetOptions() { val project = buildProjectWithMPP { tasks.withType<KotlinCompilationTask<*>>().configureEach { if (it.name == "compileKotlinJvm") { it.compilerOptions.progressiveMode.set(false) } } with(multiplatformExtension) { jvm { compilerOptions { progressiveMode.set(true) } } applyDefaultHierarchyTemplate() } } project.evaluate() assertEquals(false, project.kotlinJvmTask("compileKotlinJvm").compilerOptions.progressiveMode.get()) } @Test fun jvmLanguageSettingsOverridesTargetOptions() { val project = buildProjectWithMPP { with(multiplatformExtension) { jvm { compilerOptions { progressiveMode.set(true) } } applyDefaultHierarchyTemplate() sourceSets.getByName("jvmMain").languageSettings { progressiveMode = false } } } project.evaluate() assertEquals(false, project.kotlinJvmTask("compileKotlinJvm").compilerOptions.progressiveMode.get()) } @Test fun jsTargetCompilerOptionsDsl() { val project = buildProjectWithMPP { with(multiplatformExtension) { js { compilerOptions { suppressWarnings.set(true) } } applyDefaultHierarchyTemplate() } } project.evaluate() assertEquals(true, project.kotlinJsTask("compileKotlinJs").compilerOptions.suppressWarnings.get()) assertEquals(true, project.kotlinJsTask("compileTestKotlinJs").compilerOptions.suppressWarnings.get()) } @Test fun jsTaskOptionsOverridesTargetOptions() { val project = buildProjectWithMPP { tasks.withType<KotlinCompilationTask<*>>().configureEach { if (it.name == "compileKotlinJs") { it.compilerOptions.suppressWarnings.set(false) } } with(multiplatformExtension) { js { compilerOptions { suppressWarnings.set(true) } } applyDefaultHierarchyTemplate() } } project.evaluate() assertEquals(false, project.kotlinJsTask("compileKotlinJs").compilerOptions.suppressWarnings.get()) } @Test fun jsLanguageSettingsOverridesTargetOptions() { val project = buildProjectWithMPP { with(multiplatformExtension) { js { compilerOptions { progressiveMode.set(true) } } applyDefaultHierarchyTemplate() sourceSets.getByName("jsMain").languageSettings { progressiveMode = false } } } project.evaluate() assertEquals(false, project.kotlinJsTask("compileKotlinJs").compilerOptions.progressiveMode.get()) } @Test fun metadataTargetDsl() { val project = buildProjectWithMPP { with(multiplatformExtension) { linuxX64() iosX64() iosArm64() targets.named("metadata", KotlinMetadataTarget::class.java) { it.compilerOptions { progressiveMode.set(true) } } applyDefaultHierarchyTemplate() } } project.evaluate() assertEquals(true, project.kotlinCommonTask("compileKotlinMetadata").compilerOptions.progressiveMode.get()) } @Test fun metadataTaskOptionsOverrideTargetOptions() { val project = buildProjectWithMPP { tasks.withType<KotlinCompilationTask<*>>().configureEach { if (it.name == "compileKotlinMetadata") { it.compilerOptions.progressiveMode.set(false) } } with(multiplatformExtension) { linuxX64() iosX64() iosArm64() targets.named("metadata", KotlinMetadataTarget::class.java) { it.compilerOptions { progressiveMode.set(true) } } applyDefaultHierarchyTemplate() } } project.evaluate() assertEquals(false, project.kotlinCommonTask("compileKotlinMetadata").compilerOptions.progressiveMode.get()) } @Test fun externalTargetDsl() { val project = buildProjectWithMPP() project.runLifecycleAwareTest { with(multiplatformExtension) { val target = createExternalKotlinTarget<FakeTarget> { defaults() } target.createCompilation<FakeCompilation> { defaults(this@with) } target.createCompilation<FakeCompilation> { defaults(this@with, "test") } target.compilerOptions { javaParameters.set(true) } } } assertEquals(true, project.kotlinJvmTask("compileKotlinFake").compilerOptions.javaParameters.get()) assertEquals(true, project.kotlinJvmTask("compileTestKotlinFake").compilerOptions.javaParameters.get()) } @Test fun externalTaskOptionsOverridesTargetOptions() { val project = buildProjectWithMPP() project.runLifecycleAwareTest { tasks.withType<KotlinJvmCompileTask>().configureEach { if (it.name == "compileKotlinFake") { it.compilerOptions.javaParameters.set(false) } } with(multiplatformExtension) { val target = createExternalKotlinTarget<FakeTarget> { defaults() } target.createCompilation<FakeCompilation> { defaults(this@with) } target.createCompilation<FakeCompilation> { defaults(this@with, "test") } target.compilerOptions { javaParameters.set(true) } } } assertEquals(false, project.kotlinJvmTask("compileKotlinFake").compilerOptions.javaParameters.get()) assertEquals(true, project.kotlinJvmTask("compileTestKotlinFake").compilerOptions.javaParameters.get()) } @Test fun topLevelOptions() { val project = buildProjectWithMPP() project.runLifecycleAwareTest { with(multiplatformExtension) { compilerOptions { progressiveMode.set(true) } jvm() js() iosArm64() linuxX64() } } assertEquals(true, project.kotlinCommonTask("compileKotlinMetadata").compilerOptions.progressiveMode.get()) assertEquals(true, project.kotlinCommonTask("compileNativeMainKotlinMetadata").compilerOptions.progressiveMode.get()) assertEquals(true, project.kotlinCommonTask("compileCommonMainKotlinMetadata").compilerOptions.progressiveMode.get()) assertEquals(true, project.kotlinJvmTask("compileKotlinJvm").compilerOptions.progressiveMode.get()) assertEquals(true, project.kotlinJvmTask("compileTestKotlinJvm").compilerOptions.progressiveMode.get()) assertEquals(true, project.kotlinJsTask("compileKotlinJs").compilerOptions.progressiveMode.get()) assertEquals(true, project.kotlinJsTask("compileTestKotlinJs").compilerOptions.progressiveMode.get()) assertEquals(true, project.kotlinNativeTask("compileKotlinLinuxX64").compilerOptions.progressiveMode.get()) assertEquals(true, project.kotlinNativeTask("compileTestKotlinLinuxX64").compilerOptions.progressiveMode.get()) assertEquals(true, project.kotlinNativeTask("compileKotlinIosArm64").compilerOptions.progressiveMode.get()) assertEquals(true, project.kotlinNativeTask("compileTestKotlinIosArm64").compilerOptions.progressiveMode.get()) } @Test fun testTargetDslOverridesTopLevelDsl() { val project = buildProjectWithMPP() project.runLifecycleAwareTest { with(multiplatformExtension) { jvm { compilerOptions { languageVersion.set(KotlinVersion.KOTLIN_1_8) } } compilerOptions { languageVersion.set(KotlinVersion.KOTLIN_2_0) } } } assertEquals(KotlinVersion.KOTLIN_1_8, project.kotlinJvmTask("compileKotlinJvm").compilerOptions.languageVersion.orNull) assertEquals(KotlinVersion.KOTLIN_1_8, project.kotlinJvmTask("compileTestKotlinJvm").compilerOptions.languageVersion.orNull) } @Test fun testTaskDslOverrideTopLevelDsl() { val project = buildProjectWithMPP() project.runLifecycleAwareTest { tasks.withType<KotlinJvmCompileTask>().configureEach { if (it.name == "compileKotlinJvm") { it.compilerOptions.languageVersion.set(KotlinVersion.KOTLIN_1_8) } } with(multiplatformExtension) { jvm() compilerOptions { languageVersion.set(KotlinVersion.KOTLIN_2_0) } } } assertEquals(KotlinVersion.KOTLIN_1_8, project.kotlinJvmTask("compileKotlinJvm").compilerOptions.languageVersion.orNull) } @Test fun testTopLevelDslAlsoConfiguresSharedSourceSets() { val project = buildProjectWithMPP() project.runLifecycleAwareTest { with(multiplatformExtension) { jvm() js() compilerOptions { languageVersion.set(KotlinVersion.KOTLIN_2_0) } } } assertEquals("2.0", project.multiplatformExtension.sourceSets.getByName("commonTest").languageSettings.languageVersion) } @Test fun testJvmModuleNameInMppIsConfigured() { val project = buildProjectWithMPP() project.runLifecycleAwareTest { with(multiplatformExtension) { jvm { compilerOptions.moduleName.set("my-custom-module-name") } } } assertEquals("my-custom-module-name", project.kotlinJvmTask("compileKotlinJvm").compilerOptions.moduleName.orNull) } @Test fun testJsOptionsIsConfigured() { val project = buildProjectWithMPP() project.runLifecycleAwareTest { with(multiplatformExtension) { js { compilerOptions { moduleName.set("js-module-name") freeCompilerArgs.add("-Xstrict-implicit-export-types") } } } } val kotlinJsCompileTask = project.kotlinJsTask("compileKotlinJs") assertEquals("js-module-name", kotlinJsCompileTask.compilerOptions.moduleName.orNull) assertTrue( kotlinJsCompileTask .compilerOptions .freeCompilerArgs.get() .contains("-Xstrict-implicit-export-types") ) } @Test fun testJsBrowserConfigDoesNotOverrideFreeCompilerArgsFromTarget() { val project = buildProjectWithMPP() project.runLifecycleAwareTest { with(multiplatformExtension) { js { binaries.executable() browser() compilerOptions { freeCompilerArgs.addAll("-Xstrict-implicit-export-types", "-Xexplicit-api=warning") } } } } val kotlinJsCompileTask = project.kotlinJsTask("compileKotlinJs") assertTrue( (kotlinJsCompileTask as Kotlin2JsCompile) .enhancedFreeCompilerArgs.get() .containsAll(listOf("-Xstrict-implicit-export-types", "-Xexplicit-api=warning")) ) } @Test fun testJsLinkTaskAreAlsoConfiguredWithOptionsFromDSL() { val project = buildProjectWithMPP() project.runLifecycleAwareTest { with(multiplatformExtension) { js { nodejs() binaries.library() compilerOptions { moduleName.set("my-custom-module") languageVersion.set(KotlinVersion.KOTLIN_1_8) apiVersion.set(KotlinVersion.KOTLIN_1_8) moduleKind.set(JsModuleKind.MODULE_PLAIN) freeCompilerArgs.addAll("-Xstrict-implicit-export-types", "-Xexplicit-api=warning") } } } } val jsTasks = listOf( project.kotlinJsTask("compileKotlinJs"), project.kotlinJsTask("compileDevelopmentLibraryKotlinJs"), project.kotlinJsTask("compileProductionLibraryKotlinJs") ) jsTasks.forEach { jsTask -> if (jsTask.name == "compileKotlinJs") { // JS IR has different module name from 'compileKotlinJs' assertEquals("my-custom-module", jsTask.compilerOptions.moduleName.orNull) } assertEquals(KotlinVersion.KOTLIN_1_8, jsTask.compilerOptions.languageVersion.orNull) assertEquals(KotlinVersion.KOTLIN_1_8, jsTask.compilerOptions.apiVersion.orNull) assertEquals(JsModuleKind.MODULE_PLAIN, jsTask.compilerOptions.moduleKind.orNull) assertTrue( jsTask.compilerOptions.freeCompilerArgs.get().containsAll( listOf("-Xstrict-implicit-export-types", "-Xexplicit-api=warning") ) ) } } private fun Project.kotlinNativeTask(name: String): KotlinCompilationTask<KotlinNativeCompilerOptions> = tasks .named<KotlinCompilationTask<KotlinNativeCompilerOptions>>(name) .get() private fun Project.kotlinJsTask(name: String): KotlinCompilationTask<KotlinJsCompilerOptions> = tasks .named<KotlinCompilationTask<KotlinJsCompilerOptions>>(name) .get() private fun Project.kotlinJvmTask(name: String): KotlinCompilationTask<KotlinJvmCompilerOptions> = tasks .named<KotlinCompilationTask<KotlinJvmCompilerOptions>>(name) .get() private fun Project.kotlinCommonTask(name: String): KotlinCompilationTask<KotlinCommonCompilerOptions> = tasks .named<KotlinCompilationTask<KotlinCommonCompilerOptions>>(name) .get() }
package node.http2 import node.events.EventEmitter @Suppress("INTERFACE_WITH_SUPERCLASS") sealed external interface Http2Session : EventEmitter { /** * Value will be `undefined` if the `Http2Session` is not yet connected to a * socket, `h2c` if the `Http2Session` is not connected to a `TLSSocket`, or * will return the value of the connected `TLSSocket`'s own `alpnProtocol`property. * @since v9.4.0 */ val alpnProtocol: String? /** * Will be `true` if this `Http2Session` instance has been closed, otherwise`false`. * @since v9.4.0 */ val closed: Boolean /** * Will be `true` if this `Http2Session` instance is still connecting, will be set * to `false` before emitting `connect` event and/or calling the `http2.connect`callback. * @since v10.0.0 */ val connecting: Boolean /** * Will be `true` if this `Http2Session` instance has been destroyed and must no * longer be used, otherwise `false`. * @since v8.4.0 */ val destroyed: Boolean /** * Value is `undefined` if the `Http2Session` session socket has not yet been * connected, `true` if the `Http2Session` is connected with a `TLSSocket`, * and `false` if the `Http2Session` is connected to any other kind of socket * or stream. * @since v9.4.0 */ val encrypted: Boolean? /** * A prototype-less object describing the current local settings of this`Http2Session`. The local settings are local to _this_`Http2Session` instance. * @since v8.4.0 */ val localSettings: Settings /** * If the `Http2Session` is connected to a `TLSSocket`, the `originSet` property * will return an `Array` of origins for which the `Http2Session` may be * considered authoritative. * * The `originSet` property is only available when using a secure TLS connection. * @since v9.4.0 */ val originSet: js.array.ReadonlyArray<String>? /** * Indicates whether the `Http2Session` is currently waiting for acknowledgment of * a sent `SETTINGS` frame. Will be `true` after calling the`http2session.settings()` method. Will be `false` once all sent `SETTINGS`frames have been acknowledged. * @since v8.4.0 */ val pendingSettingsAck: Boolean /** * A prototype-less object describing the current remote settings of this`Http2Session`. The remote settings are set by the _connected_ HTTP/2 peer. * @since v8.4.0 */ val remoteSettings: Settings /** * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but * limits available methods to ones safe to use with HTTP/2. * * `destroy`, `emit`, `end`, `pause`, `read`, `resume`, and `write` will throw * an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for more information. * * `setTimeout` method will be called on this `Http2Session`. * * All other interactions will be routed directly to the socket. * @since v8.4.0 */ val socket: Any /* net.Socket | tls.TLSSocket */ /** * Provides miscellaneous information about the current state of the`Http2Session`. * * An object describing the current status of this `Http2Session`. * @since v8.4.0 */ val state: SessionState /** * The `http2session.type` will be equal to`http2.constants.NGHTTP2_SESSION_SERVER` if this `Http2Session` instance is a * server, and `http2.constants.NGHTTP2_SESSION_CLIENT` if the instance is a * client. * @since v8.4.0 */ val type: Double /** * Gracefully closes the `Http2Session`, allowing any existing streams to * complete on their own and preventing new `Http2Stream` instances from being * created. Once closed, `http2session.destroy()`_might_ be called if there * are no open `Http2Stream` instances. * * If specified, the `callback` function is registered as a handler for the`'close'` event. * @since v9.4.0 */ fun close(callback: () -> Unit = definedExternally): Unit /** * Immediately terminates the `Http2Session` and the associated `net.Socket` or`tls.TLSSocket`. * * Once destroyed, the `Http2Session` will emit the `'close'` event. If `error`is not undefined, an `'error'` event will be emitted immediately before the`'close'` event. * * If there are any remaining open `Http2Streams` associated with the`Http2Session`, those will also be destroyed. * @since v8.4.0 * @param error An `Error` object if the `Http2Session` is being destroyed due to an error. * @param code The HTTP/2 error code to send in the final `GOAWAY` frame. If unspecified, and `error` is not undefined, the default is `INTERNAL_ERROR`, otherwise defaults to `NO_ERROR`. */ fun destroy(error: Throwable /* JsError */ = definedExternally, code: Number = definedExternally): Unit /** * Transmits a `GOAWAY` frame to the connected peer _without_ shutting down the`Http2Session`. * @since v9.4.0 * @param code An HTTP/2 error code * @param lastStreamID The numeric ID of the last processed `Http2Stream` * @param opaqueData A `TypedArray` or `DataView` instance containing additional data to be carried within the `GOAWAY` frame. */ fun goaway( code: Number = definedExternally, lastStreamID: Number = definedExternally, opaqueData: js.buffer.ArrayBufferView = definedExternally, ): Unit /** * Sends a `PING` frame to the connected HTTP/2 peer. A `callback` function must * be provided. The method will return `true` if the `PING` was sent, `false`otherwise. * * The maximum number of outstanding (unacknowledged) pings is determined by the`maxOutstandingPings` configuration option. The default maximum is 10. * * If provided, the `payload` must be a `Buffer`, `TypedArray`, or `DataView`containing 8 bytes of data that will be transmitted with the `PING` and * returned with the ping acknowledgment. * * The callback will be invoked with three arguments: an error argument that will * be `null` if the `PING` was successfully acknowledged, a `duration` argument * that reports the number of milliseconds elapsed since the ping was sent and the * acknowledgment was received, and a `Buffer` containing the 8-byte `PING`payload. * * ```js * session.ping(Buffer.from('abcdefgh'), (err, duration, payload) => { * if (!err) { * console.log(`Ping acknowledged in ${duration} milliseconds`); * console.log(`With payload '${payload.toString()}'`); * } * }); * ``` * * If the `payload` argument is not specified, the default payload will be the * 64-bit timestamp (little endian) marking the start of the `PING` duration. * @since v8.9.3 * @param payload Optional ping payload. */ fun ping(callback: (err: Throwable /* JsError */?, duration: Double, payload: node.buffer.Buffer) -> Unit): Boolean fun ping( payload: js.buffer.ArrayBufferView, callback: (err: Throwable /* JsError */?, duration: Double, payload: node.buffer.Buffer) -> Unit, ): Boolean /** * Calls `ref()` on this `Http2Session`instance's underlying `net.Socket`. * @since v9.4.0 */ fun ref(): Unit /** * Sets the local endpoint's window size. * The `windowSize` is the total window size to set, not * the delta. * * ```js * const http2 = require('node:http2'); * * const server = http2.createServer(); * const expectedWindowSize = 2 ** 20; * server.on('connect', (session) => { * * // Set local window size to be 2 ** 20 * session.setLocalWindowSize(expectedWindowSize); * }); * ``` * @since v15.3.0, v14.18.0 */ fun setLocalWindowSize(windowSize: Number): Unit /** * Used to set a callback function that is called when there is no activity on * the `Http2Session` after `msecs` milliseconds. The given `callback` is * registered as a listener on the `'timeout'` event. * @since v8.4.0 */ fun setTimeout(msecs: Number, callback: () -> Unit = definedExternally): Unit /** * Updates the current local settings for this `Http2Session` and sends a new`SETTINGS` frame to the connected HTTP/2 peer. * * Once called, the `http2session.pendingSettingsAck` property will be `true`while the session is waiting for the remote peer to acknowledge the new * settings. * * The new settings will not become effective until the `SETTINGS` acknowledgment * is received and the `'localSettings'` event is emitted. It is possible to send * multiple `SETTINGS` frames while acknowledgment is still pending. * @since v8.4.0 * @param callback Callback that is called once the session is connected or right away if the session is already connected. */ fun settings( settings: Settings, callback: (err: Throwable /* JsError */?, settings: Settings, duration: Double) -> Unit = definedExternally, ): Unit /** * Calls `unref()` on this `Http2Session`instance's underlying `net.Socket`. * @since v9.4.0 */ fun unref(): Unit fun addListener(event: Http2SessionEvent.CLOSE, listener: () -> Unit): Unit /* this */ fun addListener(event: Http2SessionEvent.ERROR, listener: (err: Throwable /* JsError */) -> Unit): Unit /* this */ fun addListener( event: Http2SessionEvent.FRAMEERROR, listener: (frameType: Double, errorCode: Double, streamID: Double) -> Unit, ): Unit /* this */ fun addListener( event: Http2SessionEvent.GOAWAY, listener: (errorCode: Double, lastStreamID: Double, opaqueData: node.buffer.Buffer? /* use undefined for default */) -> Unit, ): Unit /* this */ fun addListener(event: Http2SessionEvent.LOCALSETTINGS, listener: (settings: Settings) -> Unit): Unit /* this */ fun addListener(event: Http2SessionEvent.PING, listener: () -> Unit): Unit /* this */ fun addListener(event: Http2SessionEvent.REMOTESETTINGS, listener: (settings: Settings) -> Unit): Unit /* this */ fun addListener(event: Http2SessionEvent.TIMEOUT, listener: () -> Unit): Unit /* this */ fun addListener(event: String, listener: Function<Unit> /* (...args: any[]) => void */): Unit /* this */ fun addListener(event: js.symbol.Symbol, listener: Function<Unit> /* (...args: any[]) => void */): Unit /* this */ fun emit(event: Http2SessionEvent.CLOSE): Boolean fun emit(event: Http2SessionEvent.ERROR, err: Throwable /* JsError */): Boolean fun emit(event: Http2SessionEvent.FRAMEERROR, frameType: Number, errorCode: Number, streamID: Number): Boolean fun emit( event: Http2SessionEvent.GOAWAY, errorCode: Number, lastStreamID: Number, opaqueData: node.buffer.Buffer = definedExternally, ): Boolean fun emit(event: Http2SessionEvent.LOCALSETTINGS, settings: Settings): Boolean fun emit(event: Http2SessionEvent.PING): Boolean fun emit(event: Http2SessionEvent.REMOTESETTINGS, settings: Settings): Boolean fun emit(event: Http2SessionEvent.TIMEOUT): Boolean fun emit(event: String, vararg args: Any?): Boolean fun emit(event: js.symbol.Symbol, vararg args: Any?): Boolean fun on(event: Http2SessionEvent.CLOSE, listener: () -> Unit): Unit /* this */ fun on(event: Http2SessionEvent.ERROR, listener: (err: Throwable /* JsError */) -> Unit): Unit /* this */ fun on( event: Http2SessionEvent.FRAMEERROR, listener: (frameType: Double, errorCode: Double, streamID: Double) -> Unit, ): Unit /* this */ fun on( event: Http2SessionEvent.GOAWAY, listener: (errorCode: Double, lastStreamID: Double, opaqueData: node.buffer.Buffer? /* use undefined for default */) -> Unit, ): Unit /* this */ fun on(event: Http2SessionEvent.LOCALSETTINGS, listener: (settings: Settings) -> Unit): Unit /* this */ fun on(event: Http2SessionEvent.PING, listener: () -> Unit): Unit /* this */ fun on(event: Http2SessionEvent.REMOTESETTINGS, listener: (settings: Settings) -> Unit): Unit /* this */ fun on(event: Http2SessionEvent.TIMEOUT, listener: () -> Unit): Unit /* this */ fun on(event: String, listener: Function<Unit> /* (...args: any[]) => void */): Unit /* this */ fun on(event: js.symbol.Symbol, listener: Function<Unit> /* (...args: any[]) => void */): Unit /* this */ fun once(event: Http2SessionEvent.CLOSE, listener: () -> Unit): Unit /* this */ fun once(event: Http2SessionEvent.ERROR, listener: (err: Throwable /* JsError */) -> Unit): Unit /* this */ fun once( event: Http2SessionEvent.FRAMEERROR, listener: (frameType: Double, errorCode: Double, streamID: Double) -> Unit, ): Unit /* this */ fun once( event: Http2SessionEvent.GOAWAY, listener: (errorCode: Double, lastStreamID: Double, opaqueData: node.buffer.Buffer? /* use undefined for default */) -> Unit, ): Unit /* this */ fun once(event: Http2SessionEvent.LOCALSETTINGS, listener: (settings: Settings) -> Unit): Unit /* this */ fun once(event: Http2SessionEvent.PING, listener: () -> Unit): Unit /* this */ fun once(event: Http2SessionEvent.REMOTESETTINGS, listener: (settings: Settings) -> Unit): Unit /* this */ fun once(event: Http2SessionEvent.TIMEOUT, listener: () -> Unit): Unit /* this */ fun once(event: String, listener: Function<Unit> /* (...args: any[]) => void */): Unit /* this */ fun once(event: js.symbol.Symbol, listener: Function<Unit> /* (...args: any[]) => void */): Unit /* this */ fun prependListener(event: Http2SessionEvent.CLOSE, listener: () -> Unit): Unit /* this */ fun prependListener( event: Http2SessionEvent.ERROR, listener: (err: Throwable /* JsError */) -> Unit, ): Unit /* this */ fun prependListener( event: Http2SessionEvent.FRAMEERROR, listener: (frameType: Double, errorCode: Double, streamID: Double) -> Unit, ): Unit /* this */ fun prependListener( event: Http2SessionEvent.GOAWAY, listener: (errorCode: Double, lastStreamID: Double, opaqueData: node.buffer.Buffer? /* use undefined for default */) -> Unit, ): Unit /* this */ fun prependListener(event: Http2SessionEvent.LOCALSETTINGS, listener: (settings: Settings) -> Unit): Unit /* this */ fun prependListener(event: Http2SessionEvent.PING, listener: () -> Unit): Unit /* this */ fun prependListener( event: Http2SessionEvent.REMOTESETTINGS, listener: (settings: Settings) -> Unit, ): Unit /* this */ fun prependListener(event: Http2SessionEvent.TIMEOUT, listener: () -> Unit): Unit /* this */ fun prependListener(event: String, listener: Function<Unit> /* (...args: any[]) => void */): Unit /* this */ fun prependListener( event: js.symbol.Symbol, listener: Function<Unit>, /* (...args: any[]) => void */ ): Unit /* this */ fun prependOnceListener(event: Http2SessionEvent.CLOSE, listener: () -> Unit): Unit /* this */ fun prependOnceListener( event: Http2SessionEvent.ERROR, listener: (err: Throwable /* JsError */) -> Unit, ): Unit /* this */ fun prependOnceListener( event: Http2SessionEvent.FRAMEERROR, listener: (frameType: Double, errorCode: Double, streamID: Double) -> Unit, ): Unit /* this */ fun prependOnceListener( event: Http2SessionEvent.GOAWAY, listener: (errorCode: Double, lastStreamID: Double, opaqueData: node.buffer.Buffer? /* use undefined for default */) -> Unit, ): Unit /* this */ fun prependOnceListener( event: Http2SessionEvent.LOCALSETTINGS, listener: (settings: Settings) -> Unit, ): Unit /* this */ fun prependOnceListener(event: Http2SessionEvent.PING, listener: () -> Unit): Unit /* this */ fun prependOnceListener( event: Http2SessionEvent.REMOTESETTINGS, listener: (settings: Settings) -> Unit, ): Unit /* this */ fun prependOnceListener(event: Http2SessionEvent.TIMEOUT, listener: () -> Unit): Unit /* this */ fun prependOnceListener(event: String, listener: Function<Unit> /* (...args: any[]) => void */): Unit /* this */ fun prependOnceListener( event: js.symbol.Symbol, listener: Function<Unit>, /* (...args: any[]) => void */ ): Unit /* this */ }
package second @Target(AnnotationTarget.TYPE) annotation class Anno(val int: Int) interface Base fun bar(): Base = object : Base {} const val constant = 0 class MyClass: @Anno(constant) Base by bar() { @Target(AnnotationTarget.TYPE) annotation class Anno(val string: String) }
package node.dns import js.promise.await suspend fun resolve4(hostname: String): js.array.ReadonlyArray<String> = resolve4Async( hostname ).await() suspend fun resolve4(hostname: String, options: ResolveWithTtlOptions): js.array.ReadonlyArray<RecordWithTtl> = resolve4Async( hostname, options ).await() suspend fun resolve4(hostname: String, options: ResolveOptions): Any /* string[] | RecordWithTtl[] */ = resolve4Async( hostname, options ).await()
package org.jetbrains.dokka.dokkatoo.utils import kotlin.properties.ReadOnlyProperty // Utilities for fetching System Properties and Environment Variables via delegated properties internal fun optionalSystemProperty() = optionalSystemProperty { it } internal fun <T : Any> optionalSystemProperty( convert: (String) -> T? ): ReadOnlyProperty<Any, T?> = ReadOnlyProperty { _, property -> val value = System.getProperty(property.name) if (value != null) convert(value) else null } internal fun systemProperty() = systemProperty { it } internal fun <T> systemProperty( convert: (String) -> T ): ReadOnlyProperty<Any, T> = ReadOnlyProperty { _, property -> val value = requireNotNull(System.getProperty(property.name)) { "system property ${property.name} is unavailable" } convert(value) } internal fun optionalEnvironmentVariable() = optionalEnvironmentVariable { it } internal fun <T : Any> optionalEnvironmentVariable( convert: (String) -> T? ): ReadOnlyProperty<Any, T?> = ReadOnlyProperty { _, property -> val value = System.getenv(property.name) if (value != null) convert(value) else null }
fun <T> T.id() = this const val minusOneVal = (-1).<!EVALUATED("-1")!>toByte()<!> const val oneVal = 1.<!EVALUATED("1")!>toByte()<!> const val twoVal = 2.<!EVALUATED("2")!>toByte()<!> const val threeVal = 3.<!EVALUATED("3")!>toByte()<!> const val fourVal = 4.<!EVALUATED("4")!>toByte()<!> const val byteVal = 2.<!EVALUATED("2")!>toByte()<!> const val shortVal = 2.<!EVALUATED("2")!>toShort()<!> const val intVal = <!EVALUATED("2")!>2<!> const val longVal = <!EVALUATED("2")!>2L<!> const val floatVal = <!EVALUATED("2.0")!>2.0f<!> const val doubleVal = <!EVALUATED("2.0")!>2.0<!> const val compareTo1 = oneVal.<!EVALUATED("-1")!>compareTo(twoVal)<!> const val compareTo2 = twoVal.<!EVALUATED("0")!>compareTo(twoVal)<!> const val compareTo3 = threeVal.<!EVALUATED("1")!>compareTo(twoVal)<!> const val compareTo4 = twoVal.<!EVALUATED("0")!>compareTo(shortVal)<!> const val compareTo5 = twoVal.<!EVALUATED("0")!>compareTo(intVal)<!> const val compareTo6 = twoVal.<!EVALUATED("0")!>compareTo(longVal)<!> const val compareTo7 = twoVal.<!EVALUATED("0")!>compareTo(floatVal)<!> const val compareTo8 = twoVal.<!EVALUATED("0")!>compareTo(doubleVal)<!> const val plus1 = oneVal.<!EVALUATED("3")!>plus(twoVal)<!> const val plus2 = twoVal.<!EVALUATED("4")!>plus(twoVal)<!> const val plus3 = threeVal.<!EVALUATED("5")!>plus(twoVal)<!> const val plus4 = twoVal.<!EVALUATED("4")!>plus(shortVal)<!> const val plus5 = twoVal.<!EVALUATED("4")!>plus(intVal)<!> const val plus6 = twoVal.<!EVALUATED("4")!>plus(longVal)<!> const val plus7 = twoVal.<!EVALUATED("4.0")!>plus(floatVal)<!> const val plus8 = twoVal.<!EVALUATED("4.0")!>plus(doubleVal)<!> const val minus1 = oneVal.<!EVALUATED("-1")!>minus(twoVal)<!> const val minus2 = twoVal.<!EVALUATED("0")!>minus(twoVal)<!> const val minus3 = threeVal.<!EVALUATED("1")!>minus(twoVal)<!> const val minus4 = twoVal.<!EVALUATED("0")!>minus(shortVal)<!> const val minus5 = twoVal.<!EVALUATED("0")!>minus(intVal)<!> const val minus6 = twoVal.<!EVALUATED("0")!>minus(longVal)<!> const val minus7 = twoVal.<!EVALUATED("0.0")!>minus(floatVal)<!> const val minus8 = twoVal.<!EVALUATED("0.0")!>minus(doubleVal)<!> const val times1 = oneVal.<!EVALUATED("2")!>times(twoVal)<!> const val times2 = twoVal.<!EVALUATED("4")!>times(twoVal)<!> const val times3 = threeVal.<!EVALUATED("6")!>times(twoVal)<!> const val times4 = twoVal.<!EVALUATED("4")!>times(shortVal)<!> const val times5 = twoVal.<!EVALUATED("4")!>times(intVal)<!> const val times6 = twoVal.<!EVALUATED("4")!>times(longVal)<!> const val times7 = twoVal.<!EVALUATED("4.0")!>times(floatVal)<!> const val times8 = twoVal.<!EVALUATED("4.0")!>times(doubleVal)<!> const val div1 = oneVal.<!EVALUATED("0")!>div(twoVal)<!> const val div2 = twoVal.<!EVALUATED("1")!>div(twoVal)<!> const val div3 = threeVal.<!EVALUATED("1")!>div(twoVal)<!> const val div4 = twoVal.<!EVALUATED("1")!>div(shortVal)<!> const val div5 = twoVal.<!EVALUATED("1")!>div(intVal)<!> const val div6 = twoVal.<!EVALUATED("1")!>div(longVal)<!> const val div7 = twoVal.<!EVALUATED("1.0")!>div(floatVal)<!> const val div8 = twoVal.<!EVALUATED("1.0")!>div(doubleVal)<!> const val rem1 = oneVal.<!EVALUATED("1")!>rem(twoVal)<!> const val rem2 = twoVal.<!EVALUATED("0")!>rem(twoVal)<!> const val rem3 = threeVal.<!EVALUATED("1")!>rem(twoVal)<!> const val rem4 = twoVal.<!EVALUATED("0")!>rem(shortVal)<!> const val rem5 = twoVal.<!EVALUATED("0")!>rem(intVal)<!> const val rem6 = twoVal.<!EVALUATED("0")!>rem(longVal)<!> const val rem7 = twoVal.<!EVALUATED("0.0")!>rem(floatVal)<!> const val rem8 = twoVal.<!EVALUATED("0.0")!>rem(doubleVal)<!> const val unaryPlus1 = oneVal.<!EVALUATED("1")!>unaryPlus()<!> const val unaryPlus2 = minusOneVal.<!EVALUATED("-1")!>unaryPlus()<!> const val unaryMinus1 = oneVal.<!EVALUATED("-1")!>unaryMinus()<!> const val unaryMinus2 = minusOneVal.<!EVALUATED("1")!>unaryMinus()<!> const val convert1 = oneVal.<!EVALUATED("1")!>toByte()<!> const val convert2 = oneVal.<!EVALUATED("")!>toChar()<!> const val convert3 = oneVal.<!EVALUATED("1")!>toShort()<!> const val convert4 = oneVal.<!EVALUATED("1")!>toInt()<!> const val convert5 = oneVal.<!EVALUATED("1")!>toLong()<!> const val convert6 = oneVal.<!EVALUATED("1.0")!>toFloat()<!> const val convert7 = oneVal.<!EVALUATED("1.0")!>toDouble()<!> const val equals1 = <!EVALUATED("false")!>oneVal == twoVal<!> const val equals2 = <!EVALUATED("true")!>twoVal == twoVal<!> const val equals3 = <!EVALUATED("false")!>threeVal == twoVal<!> const val equals4 = <!EVALUATED("false")!>fourVal == twoVal<!> const val toString1 = oneVal.<!EVALUATED("1")!>toString()<!> const val toString2 = twoVal.<!EVALUATED("2")!>toString()<!> // STOP_EVALUATION_CHECKS fun box(): String { if (compareTo1.id() != -1) return "Fail 1.1" if (compareTo2.id() != 0) return "Fail 1.2" if (compareTo3.id() != 1) return "Fail 1.3" if (compareTo4.id() != 0) return "Fail 1.4" if (compareTo5.id() != 0) return "Fail 1.5" if (compareTo6.id() != 0) return "Fail 1.6" if (compareTo7.id() != 0) return "Fail 1.7" if (compareTo8.id() != 0) return "Fail 1.8" if (plus1.id() != 3) return "Fail 2.1" if (plus2.id() != 4) return "Fail 2.2" if (plus3.id() != 5) return "Fail 2.3" if (plus4.id() != 4) return "Fail 2.4" if (plus5.id() != 4) return "Fail 2.5" if (plus6.id() != 4L) return "Fail 2.6" if (plus7.id() != 4.0f) return "Fail 2.7" if (plus8.id() != 4.0) return "Fail 2.8" if (minus1.id() != -1) return "Fail 3.1" if (minus2.id() != 0) return "Fail 3.2" if (minus3.id() != 1) return "Fail 3.3" if (minus4.id() != 0) return "Fail 3.4" if (minus5.id() != 0) return "Fail 3.5" if (minus6.id() != 0L) return "Fail 3.6" if (minus7.id() != 0.0f) return "Fail 3.7" if (minus8.id() != 0.0) return "Fail 3.8" if (times1.id() != 2) return "Fail 4.1" if (times2.id() != 4) return "Fail 4.2" if (times3.id() != 6) return "Fail 4.3" if (times4.id() != 4) return "Fail 4.4" if (times5.id() != 4) return "Fail 4.5" if (times6.id() != 4L) return "Fail 4.6" if (times7.id() != 4.0f) return "Fail 4.7" if (times8.id() != 4.0) return "Fail 4.8" if (div1.id() != 0) return "Fail 5.1" if (div2.id() != 1) return "Fail 5.2" if (div3.id() != 1) return "Fail 5.3" if (div4.id() != 1) return "Fail 5.4" if (div5.id() != 1) return "Fail 5.5" if (div6.id() != 1L) return "Fail 5.6" if (div7.id() != 1.0f) return "Fail 5.7" if (div8.id() != 1.0) return "Fail 5.8" if (rem1.id() != 1) return "Fail 6.1" if (rem2.id() != 0) return "Fail 6.2" if (rem3.id() != 1) return "Fail 6.3" if (rem4.id() != 0) return "Fail 6.4" if (rem5.id() != 0) return "Fail 6.5" if (rem6.id() != 0L) return "Fail 6.6" if (rem7.id() != 0.0f) return "Fail 6.7" if (rem8.id() != 0.0) return "Fail 6.8" if (unaryPlus1.id() != 1) return "Fail 7.1" if (unaryPlus2.id() != -1) return "Fail 7.2" if (unaryMinus1.id() != -1) return "Fail 7.3" if (unaryMinus2.id() != 1) return "Fail 7.4" if (convert1.id() != 1.toByte()) return "Fail 8.1" if (convert2.id() != '') return "Fail 8.2" if (convert3.id() != 1.toShort()) return "Fail 8.3" if (convert4.id() != 1) return "Fail 8.4" if (convert5.id() != 1L) return "Fail 8.5" if (convert6.id() != 1.0f) return "Fail 8.6" if (convert7.id() != 1.0) return "Fail 8.7" if (equals1.id() != false) return "Fail 9.1" if (equals2.id() != true) return "Fail 9.2" if (equals3.id() != false) return "Fail 9.3" if (equals4.id() != false) return "Fail 9.4" if (toString1.id() != "1") return "Fail 10.1" if (toString2.id() != "2") return "Fail 10.2" return "OK" }
package com.android.build.attribution.ui.model import com.android.build.attribution.BuildAttributionWarningsFilter import com.android.build.attribution.analyzers.DownloadsAnalyzer import com.android.build.attribution.ui.data.BuildAttributionReportUiData class BuildAnalyzerViewModel( val reportUiData: BuildAttributionReportUiData, val warningSuppressions: BuildAttributionWarningsFilter ) { enum class DataSet(val uiName: String) { OVERVIEW("Overview"), TASKS("Tasks"), WARNINGS("Warnings"), DOWNLOADS("Downloads") } val availableDataSets: List<DataSet> get() = listOfNotNull( DataSet.OVERVIEW, DataSet.TASKS, DataSet.WARNINGS, if (reportUiData.downloadsData != DownloadsAnalyzer.AnalyzerIsDisabled) DataSet.DOWNLOADS else null ) /** * Listener to be called on selection change. * Called only if the selectedData value was changed. */ var dataSetSelectionListener: (() -> Unit)? = null /** * Keeps track of currently selected dataSet page. * Notifies the listener on set if the value is different from the current one. */ var selectedData: DataSet = when { reportUiData.jetifierData.checkJetifierBuild -> DataSet.WARNINGS else -> DataSet.OVERVIEW } set(value) { if (value != field) { field = value dataSetSelectionListener?.invoke() } } val overviewPageModel: BuildOverviewPageModel = BuildOverviewPageModel(reportUiData, warningSuppressions) val tasksPageModel: TasksDataPageModel = TasksDataPageModelImpl(reportUiData) val warningsPageModel: WarningsDataPageModel = WarningsDataPageModelImpl(reportUiData) val downloadsInfoPageModel: DownloadsInfoPageModel = DownloadsInfoPageModel(reportUiData.downloadsData) }
package org.jetbrains.kotlinx.kandy.echarts.translator.option.series.settings import kotlinx.serialization.Serializable @Serializable internal data class LabelLayout( val hideOverlap: Boolean? = null, val moveOverlap: String? = null, // Todo val x: String? = null, val y: String? = null, val dx: Int? = null, val dy: Int? = null, val rotate: Int? = null, val width: Int? = null, val height: Int? = null, val align: String? = null, val verticalAlign: String? = null, val fontSize: Int? = null, val draggable: Boolean? = null, val labelLinePoints: Triple<Pair<String, String>, Pair<String, String>, Pair<String, String>>? = null )
package org.jetbrains.kotlinx.dl.api.core.activation import org.junit.jupiter.api.Test internal class GeluActivationTest : ActivationTest() { @Test fun default() { val input = floatArrayOf(-3.0f, -1.0f, 0.0f, 1.0f, 3.0f) val expected = floatArrayOf(-0.00404951f, -0.15865529f, 0f, 0.8413447f, 2.9959507f) assertActivationFunction(GeluActivation(), input, expected) } @Test fun approxTest() { val input = floatArrayOf(-3.0f, -1.0f, 0.0f, 1.0f, 3.0f) val expected = floatArrayOf(-0.00363752f, -0.15880796f, 0f, 0.841192f, 2.9963627f) assertActivationFunction(GeluActivation(approximate = true), input, expected) } }
package com.android.tools.idea.nav.safeargs.project import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import com.intellij.openapi.startup.StartupManager import com.intellij.openapi.util.ModificationTracker import com.intellij.openapi.util.SimpleModificationTracker /** * A project-wide modification tracker whose modification count is a value incremented by any modifications of * corresponding navigation resource files. */ class ProjectNavigationResourceModificationTracker(project: Project) : ModificationTracker { private val navigationModificationTracker = SimpleModificationTracker() init { if (!project.isDefault) { val startupManager = StartupManager.getInstance(project) if (!startupManager.postStartupActivityPassed()) { // If query happens before indexing when project just starts up, invalid queried results are cached. // So we need to explicitly update tracker to ensure another index query, instead of providing stale cached results. startupManager.runAfterOpened { DumbService.getInstance(project).runWhenSmart(::navigationChanged) } } } } companion object { @JvmStatic fun getInstance(project: Project) = project.getService(ProjectNavigationResourceModificationTracker::class.java)!! } override fun getModificationCount() = navigationModificationTracker.modificationCount /** * This is invoked when NavigationModificationListener detects a navigation file has been changed or added or deleted for this project */ internal fun navigationChanged() { navigationModificationTracker.incModificationCount() } }
package org.jetbrains.kotlin.gradle.model.builder import org.jetbrains.kotlin.gradle.model.Kapt import org.junit.Test import kotlin.test.assertFalse import kotlin.test.assertTrue class KaptModelBuilderTest { @Test fun testCanBuild() { val modelBuilder = KaptModelBuilder() assertTrue(modelBuilder.canBuild(Kapt::class.java.name)) assertFalse(modelBuilder.canBuild("wrongModel")) } }
package org.jetbrains.kotlin.android.synthetic.idea import com.intellij.ide.highlighter.XmlFileType import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.util.SimpleModificationTracker import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.impl.PsiTreeChangeEventImpl import com.intellij.psi.impl.PsiTreeChangePreprocessor import com.intellij.psi.xml.XmlAttribute import com.intellij.psi.xml.XmlAttributeValue import com.intellij.psi.xml.XmlFile import com.intellij.psi.xml.XmlToken import org.jetbrains.kotlin.android.synthetic.res.AndroidLayoutXmlFileManager class AndroidPsiTreeChangePreprocessor : PsiTreeChangePreprocessor, SimpleModificationTracker() { override fun treeChanged(event: PsiTreeChangeEventImpl) { if (event.code in HANDLED_EVENTS) { val child = event.child // We should get more precise event notification (not just "that file was changed somehow") if (child == null && event.code == PsiTreeChangeEventImpl.PsiEventType.CHILDREN_CHANGED) { return } // Layout file was renamed val element = event.element if (element != null && event.code == PsiTreeChangeEventImpl.PsiEventType.PROPERTY_CHANGED && event.propertyName == "fileName") { if (checkIfLayoutFile(element)) { incModificationCount() return } } if (child != null && checkIfLayoutFile(child)) { incModificationCount() return } val file = event.file if (file == null) { // We can't be sure what changed, so we conservatively increment the counter. // This can happen if a file is added or deleted, since we might get a PROP_UNLOADED_PSI event with no associated PSI. incModificationCount() return } if (!checkIfLayoutFile(file)) return if (child == null || !child.isValid) { // We can't be sure what changed, so we conservatively increment the counter. incModificationCount() return } val xmlAttribute = findXmlAttribute(child) ?: return val name = xmlAttribute.name if (name != "android:id" && name != "class") return incModificationCount() } } private companion object { private val HANDLED_EVENTS = setOf( PsiTreeChangeEventImpl.PsiEventType.CHILD_ADDED, PsiTreeChangeEventImpl.PsiEventType.CHILD_MOVED, PsiTreeChangeEventImpl.PsiEventType.CHILD_REMOVED, PsiTreeChangeEventImpl.PsiEventType.CHILD_REPLACED, PsiTreeChangeEventImpl.PsiEventType.CHILDREN_CHANGED, PsiTreeChangeEventImpl.PsiEventType.PROPERTY_CHANGED) private fun checkIfLayoutFile(element: PsiElement): Boolean { val xmlFile = (element as? XmlFile)?.takeIf { it.isLayoutXmlFile() } ?: return false val projectFileIndex = ProjectRootManager.getInstance(xmlFile.project).fileIndex val module = projectFileIndex.getModuleForFile(xmlFile.virtualFile) ?: element.getContainingDirectorySafe()?.let { projectFileIndex.getModuleForFile(it.virtualFile) } if (module != null && !module.isDisposed) { val resourceManager = AndroidLayoutXmlFileManager.getInstance(module) ?: return false val resDirectories = resourceManager.getAllModuleResDirectories() val baseDirectory = xmlFile.parent?.parent?.virtualFile if (baseDirectory != null && baseDirectory in resDirectories) { return true } } return false } private fun PsiFile.getContainingDirectorySafe(): PsiDirectory? { val virtualFile = this.viewProvider.virtualFile.takeIf { it.isValid } ?: return null val parentDirectory = virtualFile.parent?.takeIf { it.isValid } ?: return null return this.manager.findDirectory(parentDirectory) } private fun findXmlAttribute(element: PsiElement?): XmlAttribute? { return when (element) { is XmlToken, is XmlAttributeValue -> findXmlAttribute(element.parent) is XmlAttribute -> element else -> null } } private fun AndroidLayoutXmlFileManager.getAllModuleResDirectories(): List<VirtualFile> { val module = androidModule ?: return listOf() val fileManager = VirtualFileManager.getInstance() return module.variants.fold(arrayListOf<VirtualFile>()) { list, variant -> for (dir in variant.resDirectories) { fileManager.findFileByUrl("file://$dir")?.let { list += it } } list } } private fun PsiFile.isLayoutXmlFile(): Boolean { if (fileType != XmlFileType.INSTANCE) return false return parent?.name?.startsWith("layout") ?: false } } }
package org.jetbrains.exposed.sql import org.jetbrains.exposed.sql.vendors.DatabaseDialect /** * A configuration class for a [Database]. * * Parameters set in this class apply to all transactions that use the [Database] instance, * unless an applicable override is specified in an individual transaction block. */ @Suppress("LongParameterList") class DatabaseConfig private constructor( val sqlLogger: SqlLogger, val useNestedTransactions: Boolean, val defaultFetchSize: Int?, val defaultIsolationLevel: Int, val defaultMaxAttempts: Int, val defaultMinRetryDelay: Long, val defaultMaxRetryDelay: Long, @Deprecated( message = "This property will be removed in future releases", replaceWith = ReplaceWith("defaultMaxAttempts"), level = DeprecationLevel.WARNING ) val defaultRepetitionAttempts: Int, @Deprecated( message = "This property will be removed in future releases", replaceWith = ReplaceWith("defaultMinRetryDelay"), level = DeprecationLevel.WARNING ) val defaultMinRepetitionDelay: Long, @Deprecated( message = "This property will be removed in future releases", replaceWith = ReplaceWith("defaultMaxRetryDelay"), level = DeprecationLevel.WARNING ) val defaultMaxRepetitionDelay: Long, val defaultReadOnly: Boolean, val warnLongQueriesDuration: Long?, val maxEntitiesToStoreInCachePerEntity: Int, val keepLoadedReferencesOutOfTransaction: Boolean, val explicitDialect: DatabaseDialect?, val defaultSchema: Schema?, val logTooMuchResultSetsThreshold: Int, val preserveKeywordCasing: Boolean, ) { class Builder( /** * SQLLogger to be used to log all SQL statements. [Slf4jSqlDebugLogger] by default. */ var sqlLogger: SqlLogger? = null, /** * Turn on/off nested transactions support. Is disabled by default */ var useNestedTransactions: Boolean = false, /** * How many records will be fetched at once by select queries */ var defaultFetchSize: Int? = null, /** * Default transaction isolation level. If not specified, the database-specific level will be used. * This can be overridden on a per-transaction level by specifying the `transactionIsolation` parameter of * the `transaction` function. * Check [Database.getDefaultIsolationLevel] for the database defaults. */ var defaultIsolationLevel: Int = -1, /** * The maximum amount of attempts that will be made to perform any transaction block. * If this value is set to 1 and an SQLException happens, the exception will be thrown without performing a retry. * This can be overridden on a per-transaction level by specifying the `maxAttempts` property in a * `transaction` block. * Default amount of attempts is 3. * * @throws IllegalArgumentException If the amount of attempts is set to a value less than 1. */ var defaultMaxAttempts: Int = 3, /** * The minimum number of milliseconds to wait before retrying a transaction if an SQLException happens. * This can be overridden on a per-transaction level by specifying the `minRetryDelay` property in a * `transaction` block. * Default minimum delay is 0. */ var defaultMinRetryDelay: Long = 0, /** * The maximum number of milliseconds to wait before retrying a transaction if an SQLException happens. * This can be overridden on a per-transaction level by specifying the `maxRetryDelay` property in a * `transaction` block. * Default maximum delay is 0. */ var defaultMaxRetryDelay: Long = 0, /** * Should all connections/transactions be executed in read-only mode by default or not. * Default state is false. */ var defaultReadOnly: Boolean = false, /** * Threshold in milliseconds to log queries which exceed the threshold with WARN level. * No tracing enabled by default. * This can be set on a per-transaction level by setting [Transaction.warnLongQueriesDuration] field. */ var warnLongQueriesDuration: Long? = null, /** * Amount of entities to keep in an EntityCache per an Entity class. * Applicable only when `exposed-dao` module is used. * This can be overridden on a per-transaction basis via [EntityCache.maxEntitiesToStore]. * All entities will be kept by default. */ var maxEntitiesToStoreInCachePerEntity: Int = Int.MAX_VALUE, /** * Turns on "mode" for Exposed DAO to store relations (after they were loaded) within the entity that will * allow access to them outside the transaction. * Useful when [eager loading](https://github.com/JetBrains/Exposed/wiki/DAO#eager-loading) is used. */ var keepLoadedReferencesOutOfTransaction: Boolean = false, /** * Set the explicit dialect for a database. * This can be useful when working with unsupported dialects which have the same behavior as the one that * Exposed supports. */ var explicitDialect: DatabaseDialect? = null, /** * Set the default schema for a database. */ var defaultSchema: Schema? = null, /** * Log too much result sets opened in parallel. * The error log will contain the stacktrace of the place in the code where a new result set occurs, and it * exceeds the threshold. * 0 value means no log needed. */ var logTooMuchResultSetsThreshold: Int = 0, /** * Toggle whether table and column identifiers that are also keywords should retain their case sensitivity. * Keeping user-defined case sensitivity (value set to `true`) is the default setting. */ @ExperimentalKeywordApi var preserveKeywordCasing: Boolean = true, ) { @Deprecated( message = "This property will be removed in future releases", replaceWith = ReplaceWith("defaultMaxAttempts"), level = DeprecationLevel.WARNING ) var defaultRepetitionAttempts: Int get() = defaultMaxAttempts set(value) { defaultMaxAttempts = value } @Deprecated( message = "This property will be removed in future releases", replaceWith = ReplaceWith("defaultMinRetryDelay"), level = DeprecationLevel.WARNING ) var defaultMinRepetitionDelay: Long get() = defaultMinRetryDelay set(value) { defaultMinRetryDelay = value } @Deprecated( message = "This property will be removed in future releases", replaceWith = ReplaceWith("defaultMaxRetryDelay"), level = DeprecationLevel.WARNING ) var defaultMaxRepetitionDelay: Long get() = defaultMaxRetryDelay set(value) { defaultMaxRetryDelay = value } } companion object { operator fun invoke(body: Builder.() -> Unit = {}): DatabaseConfig { val builder = Builder().apply(body) require(builder.defaultMaxAttempts > 0) { "defaultMaxAttempts must be set to perform at least 1 attempt." } @OptIn(ExperimentalKeywordApi::class) return DatabaseConfig( sqlLogger = builder.sqlLogger ?: Slf4jSqlDebugLogger, useNestedTransactions = builder.useNestedTransactions, defaultFetchSize = builder.defaultFetchSize, defaultIsolationLevel = builder.defaultIsolationLevel, defaultMaxAttempts = builder.defaultMaxAttempts, defaultMinRetryDelay = builder.defaultMinRetryDelay, defaultMaxRetryDelay = builder.defaultMaxRetryDelay, defaultRepetitionAttempts = builder.defaultMaxAttempts, defaultMinRepetitionDelay = builder.defaultMinRetryDelay, defaultMaxRepetitionDelay = builder.defaultMaxRetryDelay, defaultReadOnly = builder.defaultReadOnly, warnLongQueriesDuration = builder.warnLongQueriesDuration, maxEntitiesToStoreInCachePerEntity = builder.maxEntitiesToStoreInCachePerEntity, keepLoadedReferencesOutOfTransaction = builder.keepLoadedReferencesOutOfTransaction, explicitDialect = builder.explicitDialect, defaultSchema = builder.defaultSchema, logTooMuchResultSetsThreshold = builder.logTooMuchResultSetsThreshold, preserveKeywordCasing = builder.preserveKeywordCasing, ) } } }
package org.jetbrains.kotlin.fir.resolve import org.jetbrains.kotlin.builtins.functions.FunctionTypeKind import org.jetbrains.kotlin.descriptors.ClassKind import org.jetbrains.kotlin.descriptors.EffectiveVisibility import org.jetbrains.kotlin.descriptors.Modality import org.jetbrains.kotlin.fir.FirSession import org.jetbrains.kotlin.fir.FirSessionComponent import org.jetbrains.kotlin.fir.caches.FirCache import org.jetbrains.kotlin.fir.caches.NullableMap import org.jetbrains.kotlin.fir.caches.firCachesFactory import org.jetbrains.kotlin.fir.caches.getOrPut import org.jetbrains.kotlin.fir.containingClassForStaticMemberAttr import org.jetbrains.kotlin.fir.declarations.* import org.jetbrains.kotlin.fir.declarations.builder.FirTypeParameterBuilder import org.jetbrains.kotlin.fir.declarations.builder.buildSimpleFunction import org.jetbrains.kotlin.fir.declarations.builder.buildValueParameter import org.jetbrains.kotlin.fir.declarations.impl.FirResolvedDeclarationStatusImpl import org.jetbrains.kotlin.fir.declarations.utils.isAbstract import org.jetbrains.kotlin.fir.declarations.utils.isActual import org.jetbrains.kotlin.fir.declarations.utils.isExpect import org.jetbrains.kotlin.fir.declarations.utils.visibility import org.jetbrains.kotlin.fir.diagnostics.ConeIntermediateDiagnostic import org.jetbrains.kotlin.fir.diagnostics.ConeSimpleDiagnostic import org.jetbrains.kotlin.fir.diagnostics.DiagnosticKind import org.jetbrains.kotlin.fir.extensions.extensionService import org.jetbrains.kotlin.fir.moduleData import org.jetbrains.kotlin.fir.resolve.calls.FirSyntheticFunctionSymbol import org.jetbrains.kotlin.fir.resolve.providers.symbolProvider import org.jetbrains.kotlin.fir.resolve.substitution.ConeSubstitutor import org.jetbrains.kotlin.fir.resolve.substitution.substitutorByMap import org.jetbrains.kotlin.fir.scopes.impl.FirFakeOverrideGenerator import org.jetbrains.kotlin.fir.scopes.impl.hasTypeOf import org.jetbrains.kotlin.fir.scopes.unsubstitutedScope import org.jetbrains.kotlin.fir.symbols.impl.* import org.jetbrains.kotlin.fir.types.* import org.jetbrains.kotlin.fir.types.builder.buildResolvedTypeRef import org.jetbrains.kotlin.fir.types.impl.ConeClassLikeTypeImpl import org.jetbrains.kotlin.fir.types.impl.ConeTypeParameterTypeImpl import org.jetbrains.kotlin.name.CallableId import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.name.StandardClassIds import org.jetbrains.kotlin.types.Variance import org.jetbrains.kotlin.utils.exceptions.errorWithAttachment import org.jetbrains.kotlin.utils.addToStdlib.unreachableBranch private val SAM_PARAMETER_NAME = Name.identifier("function") data class SAMInfo<out C : ConeKotlinType>(internal val symbol: FirNamedFunctionSymbol, val type: C) class FirSamResolver( private val session: FirSession, private val scopeSession: ScopeSession, private val outerClassManager: FirOuterClassManager? = null, ) { private val resolvedFunctionType: NullableMap<FirRegularClass, SAMInfo<ConeLookupTagBasedType>?> = NullableMap() private val samConstructorsCache = session.samConstructorStorage.samConstructors private val samConversionTransformers = session.extensionService.samConversionTransformers fun isSamType(type: ConeKotlinType): Boolean = when (type) { is ConeClassLikeType -> { val symbol = type.fullyExpandedType(session).lookupTag.toSymbol(session) symbol is FirRegularClassSymbol && resolveFunctionTypeIfSamInterface(symbol.fir) != null } is ConeFlexibleType -> isSamType(type.lowerBound) && isSamType(type.upperBound) else -> false } /** * fun interface Foo { * fun bar(x: Int): String * } * * [functionalType] is `(Int) -> String` * [samType] is `Foo` */ data class SamConversionInfo(val functionalType: ConeKotlinType, val samType: ConeKotlinType) fun getSamInfoForPossibleSamType(type: ConeKotlinType): SamConversionInfo? { return when (type) { is ConeClassLikeType -> SamConversionInfo( functionalType = getFunctionTypeForPossibleSamType(type.fullyExpandedType(session)) ?: return null, samType = type ) is ConeFlexibleType -> { val lowerType = getSamInfoForPossibleSamType(type.lowerBound)?.functionalType ?: return null val upperType = getSamInfoForPossibleSamType(type.upperBound)?.functionalType ?: return null SamConversionInfo( functionalType = ConeFlexibleType(lowerType.lowerBoundIfFlexible(), upperType.upperBoundIfFlexible()), samType = type ) } is ConeStubType, is ConeTypeParameterType, is ConeTypeVariableType, is ConeDefinitelyNotNullType, is ConeIntersectionType, is ConeIntegerLiteralType, -> null is ConeCapturedType -> type.lowerType?.let { getSamInfoForPossibleSamType(it) } is ConeLookupTagBasedType -> unreachableBranch(type) } } private fun getFunctionTypeForPossibleSamType(type: ConeClassLikeType): ConeLookupTagBasedType? { val firRegularClass = type.lookupTag.toFirRegularClass(session) ?: return null val (_, unsubstitutedFunctionType) = resolveFunctionTypeIfSamInterface(firRegularClass) ?: return null val functionType = firRegularClass.buildSubstitutorWithUpperBounds(session, type)?.substituteOrNull(unsubstitutedFunctionType) ?: unsubstitutedFunctionType require(functionType is ConeLookupTagBasedType) { "Function type should always be ConeLookupTagBasedType, but ${functionType::class} was found" } return functionType.withNullability(ConeNullability.create(type.isMarkedNullable), session.typeContext) } fun getSamConstructor(firClassOrTypeAlias: FirClassLikeDeclaration): FirSimpleFunction? { if (firClassOrTypeAlias is FirTypeAlias) { // Precompute the constructor for the base type to avoid deadlocks in the IDE. firClassOrTypeAlias.expandedTypeRef.coneTypeSafe<ConeClassLikeType>() ?.fullyExpandedType(session)?.lookupTag?.toSymbol(session) ?.let { samConstructorsCache.getValue(it, this) } } return samConstructorsCache.getValue(firClassOrTypeAlias.symbol, this)?.fir } fun buildSamConstructorForRegularClass(classSymbol: FirRegularClassSymbol): FirNamedFunctionSymbol? { val firRegularClass = classSymbol.fir val (functionSymbol, functionType) = resolveFunctionTypeIfSamInterface(firRegularClass) ?: return null val syntheticFunctionSymbol = classSymbol.createSyntheticConstructorSymbol() val newTypeParameters = firRegularClass.typeParameters.map { typeParameter -> val declaredTypeParameter = typeParameter.symbol.fir FirTypeParameterBuilder().apply { source = declaredTypeParameter.source moduleData = session.moduleData origin = FirDeclarationOrigin.SamConstructor resolvePhase = FirResolvePhase.DECLARATIONS name = declaredTypeParameter.name this.symbol = FirTypeParameterSymbol() variance = Variance.INVARIANT isReified = false annotations += declaredTypeParameter.annotations containingDeclarationSymbol = syntheticFunctionSymbol } } val newTypeParameterTypes = newTypeParameters .map { ConeTypeParameterTypeImpl(it.symbol.toLookupTag(), isNullable = false) } val substitutor = substitutorByMap( firRegularClass.typeParameters .map { it.symbol } .zip(newTypeParameterTypes).toMap(), session ) for ((newTypeParameter, oldTypeParameter) in newTypeParameters.zip(firRegularClass.typeParameters)) { val declared = oldTypeParameter.symbol.fir newTypeParameter.bounds += declared.symbol.resolvedBounds.map { typeRef -> buildResolvedTypeRef { source = typeRef.source type = substitutor.substituteOrSelf(typeRef.coneType) } } } return buildSimpleFunction { moduleData = session.moduleData source = firRegularClass.source name = syntheticFunctionSymbol.name origin = FirDeclarationOrigin.SamConstructor val visibility = firRegularClass.visibility status = FirResolvedDeclarationStatusImpl( visibility, Modality.FINAL, EffectiveVisibility.Local ).apply { isExpect = firRegularClass.isExpect isActual = firRegularClass.isActual } this.symbol = syntheticFunctionSymbol typeParameters += newTypeParameters.map { it.build() } val substitutedFunctionType = substitutor.substituteOrSelf(functionType) val substitutedReturnType = ConeClassLikeTypeImpl( firRegularClass.symbol.toLookupTag(), newTypeParameterTypes.toTypedArray(), isNullable = false, ) returnTypeRef = buildResolvedTypeRef { source = null type = substitutedReturnType } valueParameters += buildValueParameter { moduleData = session.moduleData containingFunctionSymbol = syntheticFunctionSymbol origin = FirDeclarationOrigin.SamConstructor returnTypeRef = buildResolvedTypeRef { source = firRegularClass.source type = substitutedFunctionType } name = SAM_PARAMETER_NAME this.symbol = FirValueParameterSymbol(SAM_PARAMETER_NAME) isCrossinline = false isNoinline = false isVararg = false resolvePhase = FirResolvePhase.BODY_RESOLVE } annotations += functionSymbol.annotations resolvePhase = FirResolvePhase.BODY_RESOLVE }.apply { containingClassForStaticMemberAttr = outerClassManager?.outerClass(firRegularClass.symbol)?.toLookupTag() }.symbol } fun buildSamConstructorForTypeAlias(typeAliasSymbol: FirTypeAliasSymbol): FirNamedFunctionSymbol? { val type = typeAliasSymbol.fir.expandedTypeRef.coneTypeUnsafe<ConeClassLikeType>().fullyExpandedType(session) val expansionRegularClass = type.lookupTag.toSymbol(session)?.fir as? FirRegularClass ?: return null val samConstructorForClass = getSamConstructor(expansionRegularClass) ?: return null // The constructor is something like `fun <T, ...> C(...): C<T, ...>`, meaning the type parameters // we need to replace are owned by it, not by the class (see the substitutor in `buildSamConstructor` // for `FirRegularClass` above). val substitutor = samConstructorForClass.buildSubstitutorWithUpperBounds(session, type) ?: return samConstructorForClass.symbol val newReturnType = substitutor.substituteOrNull(samConstructorForClass.returnTypeRef.coneType) val newParameterTypes = samConstructorForClass.valueParameters.map { substitutor.substituteOrNull(it.returnTypeRef.coneType) } val newContextReceiverTypes = samConstructorForClass.contextReceivers.map { substitutor.substituteOrNull(it.typeRef.coneType) } if (newReturnType == null && newParameterTypes.all { it == null } && newContextReceiverTypes.all { it == null }) { return samConstructorForClass.symbol } return FirFakeOverrideGenerator.createCopyForFirFunction( typeAliasSymbol.createSyntheticConstructorSymbol(), samConstructorForClass, derivedClassLookupTag = null, session, FirDeclarationOrigin.SamConstructor, newDispatchReceiverType = null, newReceiverType = null, newContextReceiverTypes = newContextReceiverTypes, newReturnType = newReturnType, newParameterTypes = newParameterTypes, newTypeParameters = typeAliasSymbol.fir.typeParameters, ).symbol } private fun FirClassLikeSymbol<*>.createSyntheticConstructorSymbol() = FirSyntheticFunctionSymbol( CallableId( classId.packageFqName, classId.relativeClassName.parent().takeIf { !it.isRoot }, classId.shortClassName, ), ) private fun resolveFunctionTypeIfSamInterface(firRegularClass: FirRegularClass): SAMInfo<ConeLookupTagBasedType>? { return resolvedFunctionType.getOrPut(firRegularClass) { if (!firRegularClass.status.isFun) return@getOrPut null val abstractMethod = firRegularClass.getSingleAbstractMethodOrNull(session, scopeSession) ?: return@getOrPut null // TODO: KT-59674 // val shouldConvertFirstParameterToDescriptor = samWithReceiverResolvers.any { it.shouldConvertFirstSamParameterToReceiver(abstractMethod) } val typeFromExtension = samConversionTransformers.firstNotNullOfOrNull { it.getCustomFunctionTypeForSamConversion(abstractMethod) } SAMInfo(abstractMethod.symbol, typeFromExtension ?: abstractMethod.getFunctionTypeForAbstractMethod(session)) } } } /** * This function creates a substitutor for SAM class/SAM constructor based on the expected SAM type. * If there is a typeless projection in some argument of the expected type then the upper bound of the corresponding type parameters is used */ private fun FirTypeParameterRefsOwner.buildSubstitutorWithUpperBounds(session: FirSession, type: ConeClassLikeType): ConeSubstitutor? { if (typeParameters.isEmpty()) return null fun createMapping(substitutor: ConeSubstitutor): Map<FirTypeParameterSymbol, ConeKotlinType> { return typeParameters.zip(type.typeArguments).associate { (parameter, projection) -> val typeArgument = (projection as? ConeKotlinTypeProjection)?.type // TODO: Consider using `parameterSymbol.fir.bounds.first().coneType` once sure that it won't fail with exception ?: parameter.symbol.fir.bounds.firstOrNull()?.coneTypeSafe() ?: session.builtinTypes.nullableAnyType.type Pair(parameter.symbol, substitutor.substituteOrSelf(typeArgument)) } } /* * * There might be a case when there is a recursion in upper bounds of SAM type parameters: * * ``` * public interface Function<E extends CharSequence, F extends Map<String, E>> { * E handle(F f); * } * ``` * * In this case, it's not enough to just take the upper bound of the parameter, as it may contain the reference to another parameter. * To handle it correctly, we need to substitute upper bounds with existing substitutor too. * This recursive substitution process may last at most as the number of presented type parameters */ var substitutor: ConeSubstitutor = ConeSubstitutor.Empty var containsNonSubstitutedArguments = false for (i in typeParameters.indices) { val mapping = createMapping(substitutor) substitutor = substitutorByMap(mapping, session) containsNonSubstitutedArguments = mapping.values.any { bound -> bound.contains { type -> type is ConeTypeParameterType && typeParameters.any { it.symbol == type.lookupTag.typeParameterSymbol } } } if (!containsNonSubstitutedArguments) { break } } /* * If there are still unsubstituted * parameters, then it means that there is a cycle in parameters themselves and it's impossible to infer proper substitution. For that * case we just create error types for such parameters * * ``` * public interface Function1<A extends B, B extends A> { * B handle(A a); * } * ``` */ if (containsNonSubstitutedArguments) { val errorSubstitution = typeParameters.associate { val diagnostic = ConeSimpleDiagnostic( reason = "Parameter ${it.symbol.name} has a cycle in its upper bounds", DiagnosticKind.CannotInferParameterType ) it.symbol to ConeErrorType(diagnostic) } val errorSubstitutor = substitutorByMap(errorSubstitution, session) substitutor = substitutorByMap(createMapping(errorSubstitutor), session) } return substitutor } private fun FirRegularClass.getSingleAbstractMethodOrNull( session: FirSession, scopeSession: ScopeSession, ): FirSimpleFunction? { if (classKind != ClassKind.INTERFACE || hasMoreThenOneAbstractFunctionOrHasAbstractProperty()) return null val samCandidateNames = computeSamCandidateNames(session) return findSingleAbstractMethodByNames(session, scopeSession, samCandidateNames) } private fun FirRegularClass.computeSamCandidateNames(session: FirSession): Set<Name> { val classes = // Note: we search only for names in this function, so substitution is not needed V lookupSuperTypes(this, lookupInterfaces = true, deep = true, useSiteSession = session, substituteTypes = false) .mapNotNullTo(mutableListOf(this)) { (session.symbolProvider.getSymbolByLookupTag(it.lookupTag) as? FirRegularClassSymbol)?.fir } val samCandidateNames = mutableSetOf<Name>() for (clazz in classes) { for (declaration in clazz.declarations) { when (declaration) { is FirProperty -> if (declaration.resolvedIsAbstract) { samCandidateNames.add(declaration.name) } is FirSimpleFunction -> if (declaration.resolvedIsAbstract) { samCandidateNames.add(declaration.name) } else -> {} } } } return samCandidateNames } private fun FirRegularClass.findSingleAbstractMethodByNames( session: FirSession, scopeSession: ScopeSession, samCandidateNames: Set<Name>, ): FirSimpleFunction? { var resultMethod: FirSimpleFunction? = null var metIncorrectMember = false val classUseSiteMemberScope = this.unsubstitutedScope( session, scopeSession, withForcedTypeCalculator = false, memberRequiredPhase = null, ) for (candidateName in samCandidateNames) { if (metIncorrectMember) break classUseSiteMemberScope.processPropertiesByName(candidateName) { if (it is FirPropertySymbol && it.fir.resolvedIsAbstract) { metIncorrectMember = true } } if (metIncorrectMember) break classUseSiteMemberScope.processFunctionsByName(candidateName) { functionSymbol -> val firFunction = functionSymbol.fir if (!firFunction.resolvedIsAbstract || firFunction.isPublicInObject(checkOnlyName = false) ) return@processFunctionsByName if (resultMethod != null) { metIncorrectMember = true } else { resultMethod = firFunction } } } if (metIncorrectMember || resultMethod == null || resultMethod!!.typeParameters.isNotEmpty()) return null return resultMethod } private fun FirRegularClass.hasMoreThenOneAbstractFunctionOrHasAbstractProperty(): Boolean { var wasAbstractFunction = false for (declaration in declarations) { if (declaration is FirProperty && declaration.resolvedIsAbstract) return true if (declaration is FirSimpleFunction && declaration.resolvedIsAbstract && !declaration.isPublicInObject(checkOnlyName = true) ) { if (wasAbstractFunction) return true wasAbstractFunction = true } } return false } /** * Checks if declaration is indeed abstract, ensuring that its status has been completely resolved * beforehand. */ private val FirCallableDeclaration.resolvedIsAbstract: Boolean get() = symbol.isAbstract /** * From the definition of function interfaces in the Java specification (pt. 9.8): * "methods that are members of I that do not have the same signature as any public instance method of the class Object" * It means that if an interface declares `int hashCode()` then the method won't be taken into account when * checking if the interface is SAM. * * For K1 compatibility, this only applies to members declared in Java, see KT-67283. */ private fun FirSimpleFunction.isPublicInObject(checkOnlyName: Boolean): Boolean { if (!isJavaOrEnhancement) return false if (name.asString() !in PUBLIC_METHOD_NAMES_IN_OBJECT) return false if (checkOnlyName) return true return when (name.asString()) { "hashCode", "getClass", "notify", "notifyAll", "toString" -> valueParameters.isEmpty() "equals" -> valueParameters.singleOrNull()?.hasTypeOf(StandardClassIds.Any, allowNullable = true) == true "wait" -> when (valueParameters.size) { 0 -> true 1 -> valueParameters[0].hasTypeOf(StandardClassIds.Long, allowNullable = false) 2 -> valueParameters[0].hasTypeOf(StandardClassIds.Long, allowNullable = false) && valueParameters[1].hasTypeOf(StandardClassIds.Int, allowNullable = false) else -> false } else -> errorWithAttachment("Unexpected method name") { withEntry("methodName", name.asString()) } } } private val PUBLIC_METHOD_NAMES_IN_OBJECT = setOf("equals", "hashCode", "getClass", "wait", "notify", "notifyAll", "toString") private fun FirSimpleFunction.getFunctionTypeForAbstractMethod(session: FirSession): ConeLookupTagBasedType { val parameterTypes = valueParameters.map { it.returnTypeRef.coneTypeSafe<ConeKotlinType>() ?: ConeErrorType(ConeIntermediateDiagnostic("No type for parameter $it")) } val contextReceiversTypes = contextReceivers.map { it.typeRef.coneTypeSafe<ConeKotlinType>() ?: ConeErrorType(ConeIntermediateDiagnostic("No type for context receiver $it")) } val kind = session.functionTypeService.extractSingleSpecialKindForFunction(symbol) ?: FunctionTypeKind.Function return createFunctionType( kind, parameterTypes, receiverType = receiverParameter?.typeRef?.coneType, rawReturnType = returnTypeRef.coneType, contextReceivers = contextReceiversTypes ) } class FirSamConstructorStorage(session: FirSession) : FirSessionComponent { val samConstructors: FirCache<FirClassLikeSymbol<*>, FirNamedFunctionSymbol?, FirSamResolver> = session.firCachesFactory.createCache { classSymbol, samResolver -> when (classSymbol) { is FirRegularClassSymbol -> samResolver.buildSamConstructorForRegularClass(classSymbol) is FirTypeAliasSymbol -> samResolver.buildSamConstructorForTypeAlias(classSymbol) is FirAnonymousObjectSymbol -> null } } } private val FirSession.samConstructorStorage: FirSamConstructorStorage by FirSession.sessionComponentAccessor()
package com.android.tools.idea.run.deployment.liveedit.analysis import com.android.tools.idea.run.deployment.liveedit.analysis.leir.IrMethod import org.jetbrains.kotlin.load.java.JvmAbi /** * Checks if a method is an inline method. * * The kotlin compiler adds a synthetic variable to every inline method, consisting of a prefix followed by the method's name. The variable * will be scoped to the entire body of the method, from the second label to the last label in the method. The scope must be checked * because a similarly named variable may be present if the method calls another inline method with the same name. */ fun IrMethod.isInline(): Boolean { val inlineName = "${JvmAbi.LOCAL_VARIABLE_NAME_PREFIX_INLINE_FUNCTION}$name" return localVariables.filter { it.name == inlineName }.any { it.start.index <= 1 && it.end.index == instructions.labels.size - 1 } }
interface I<F, G, H> class A(impl: Interface) : <!UNRESOLVED_REFERENCE!>Nested<!>(), <!DELEGATION_NOT_TO_INTERFACE, UNRESOLVED_REFERENCE!>Interface<!> by impl, <!UNRESOLVED_REFERENCE!>Inner<!>, I<<!UNRESOLVED_REFERENCE!>Nested<!>, <!UNRESOLVED_REFERENCE!>Interface<!>, <!UNRESOLVED_REFERENCE!>Inner<!>> { class Nested inner class Inner interface Interface }
package com.android.tools.idea.navigator.nodes.ndk.includes.model import nl.jqno.equalsverifier.EqualsVerifier import org.junit.Test class SimpleIncludeValueTest { @Test fun testEqualsHash() { EqualsVerifier.forClass(SimpleIncludeValue::class.java).verify() } }
package demo.plot.batik.geom import demo.common.batik.demoUtils.SvgViewerDemoWindowBatik import demo.plot.shared.model.geom.PointDemo fun main() { with(PointDemo()) { SvgViewerDemoWindowBatik( "Points SVG", createSvgRoots(createModels()) ).open() } }
import kotlin.reflect.KClass class OK class T inline fun <reified F : Any> bar(k: KClass<out F>): String = k.simpleName!! inline fun <reified T : Any> foo(): String = bar(T::class) fun box(): String { return foo<OK>() }