Datasets:
Tags:
License:
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()
|
End of preview. Expand
in Dataset Viewer.
README.md exists but content is empty.
Use the Edit dataset card button to edit it.
- Downloads last month
- 27