text
stringlengths 0
3.9M
|
---|
package org.jetbrains.plugins.ideavim.action.motion.text
import com.maddyhome.idea.vim.state.mode.Mode
import org.jetbrains.plugins.ideavim.VimTestCase
import org.junit.jupiter.api.Test
class MotionSentenceNextStartActionTest : VimTestCase() {
@Test
fun `test with two empty lines`() {
doTest(
"C<CR><S-Left><C-Right><C-O>)",
"""
Lorem ipsum dolor sit amet,
consectetur adipiscing elit
Sed in orci mauris.
Cras id tellus in ${c}ex imperdiet egestas.
""".trimIndent(),
"""
Lorem ipsum dolor sit amet,
consectetur adipiscing elit
Sed in orci mauris.
Cras id tellus in
""".trimIndent(),
Mode.INSERT,
)
}
}
|
package org.jetbrains.letsPlot.core.plot.base.geom
import org.jetbrains.letsPlot.commons.geometry.DoubleSegment
import org.jetbrains.letsPlot.commons.geometry.DoubleVector
import org.jetbrains.letsPlot.core.commons.data.SeriesUtil
import org.jetbrains.letsPlot.core.plot.base.Aesthetics
import org.jetbrains.letsPlot.core.plot.base.CoordinateSystem
import org.jetbrains.letsPlot.core.plot.base.GeomContext
import org.jetbrains.letsPlot.core.plot.base.PositionAdjustment
import org.jetbrains.letsPlot.core.plot.base.geom.util.GeomHelper
import org.jetbrains.letsPlot.core.plot.base.render.LegendKeyElementFactory
import org.jetbrains.letsPlot.core.plot.base.render.SvgRoot
import org.jetbrains.letsPlot.datamodel.svg.dom.SvgNode
class ABLineGeom : GeomBase() {
override val legendKeyElementFactory: LegendKeyElementFactory
get() = HLineGeom.LEGEND_KEY_ELEMENT_FACTORY
override fun buildIntern(
root: SvgRoot,
aesthetics: Aesthetics,
pos: PositionAdjustment,
coord: CoordinateSystem,
ctx: GeomContext
) {
val helper = GeomHelper(pos, coord, ctx)
.createSvgElementHelper()
helper.setStrokeAlphaEnabled(true)
val viewPort = overallAesBounds(ctx)
val boundaries = viewPort.parts.toList()
val lines = ArrayList<SvgNode>()
for (p in aesthetics.dataPoints()) {
val intercept = p.intercept()
val slope = p.slope()
if (SeriesUtil.allFinite(intercept, slope)) {
val p1 = DoubleVector(viewPort.left, intercept!! + viewPort.left * slope!!)
val p2 = DoubleVector(viewPort.right, p1.y + viewPort.dimension.x * slope)
val s = DoubleSegment(p1, p2)
val lineEnds = HashSet<DoubleVector>(2)
for (boundary in boundaries) {
val intersection = boundary.intersection(s)
if (intersection != null) {
lineEnds.add(intersection)
if (lineEnds.size == 2) {
break
}
}
}
if (lineEnds.size == 2) {
val it = lineEnds.iterator()
val (svg) = helper.createLine(it.next(), it.next(), p) ?: continue
lines.add(svg)
}
}
}
lines.forEach { root.add(it) }
}
companion object {
const val HANDLES_GROUPS = false
}
}
|
@file:JsModule("react-router-dom")
package react.router.dom
import web.url.URLSearchParams
/**
* A convenient wrapper for reading and writing search parameters via the
* URLSearchParams interface.
*/
external fun useSearchParams(defaultInit: URLSearchParamsInit = definedExternally): js.array.JsTuple2<URLSearchParams, SetURLSearchParams>
|
package org.jetbrains.plugins.ideavim.ex.implementation.commands
import com.maddyhome.idea.vim.state.mode.Mode
import org.jetbrains.plugins.ideavim.SkipNeovimReason
import org.jetbrains.plugins.ideavim.TestWithoutNeovim
import org.jetbrains.plugins.ideavim.VimJavaTestCase
import org.junit.jupiter.api.Test
class ActionCommandJavaTest : VimJavaTestCase() {
// VIM-862 |:action| in visual character mode
@TestWithoutNeovim(SkipNeovimReason.ACTION_COMMAND)
@Test
fun testExCommandInVisualCharacterMode() {
configureByJavaText(
"-----\n" +
"1<caret>2345\n" +
"abcde\n" +
"-----",
)
typeText("vjl")
enterCommand("'<,'>action CommentByBlockComment")
assertMode(Mode.NORMAL())
assertState(
"-----\n" +
"1/*2345\n" +
"abc*/de\n" +
"-----",
)
}
// https://github.com/JetBrains/ideavim/commit/fe714a90032d0cb5ef0a0e0d8783980b6f1c7d20#r35647600
@TestWithoutNeovim(SkipNeovimReason.ACTION_COMMAND)
@Test
fun testExCommandInVisualCharacterModeWithIncSearch() {
configureByJavaText(
"-----\n" +
"1<caret>2345\n" +
"abcde\n" +
"-----",
)
enterCommand("set incsearch")
typeText("vjl")
enterCommand("'<,'>action CommentByBlockComment")
assertMode(Mode.NORMAL())
assertState(
"-----\n" +
"1/*2345\n" +
"abc*/de\n" +
"-----",
)
}
// VIM-862 |:action|
@TestWithoutNeovim(SkipNeovimReason.ACTION_COMMAND)
@Test
fun testExCommandInVisualCharacterModeSameLine() {
configureByJavaText("1<caret>2345\n" + "abcde\n")
typeText("vl")
enterCommand("'<,'>action CommentByBlockComment")
assertMode(Mode.NORMAL())
assertState("1/*23*/45\n" + "abcde\n")
}
@TestWithoutNeovim(SkipNeovimReason.ACTION_COMMAND)
@Test
fun testExCommandInVisualCharacterModeSameLineWithIncsearch() {
configureByJavaText("1<caret>2345\n" + "abcde\n")
enterCommand("set incsearch")
typeText("vl")
enterCommand("'<,'>action CommentByBlockComment")
assertMode(Mode.NORMAL())
assertState("1/*23*/45\n" + "abcde\n")
}
// VIM-862 |:action| in visual line mode
@TestWithoutNeovim(SkipNeovimReason.ACTION_COMMAND)
@Test
fun testExCommandInVisualLineMode() {
configureByJavaText(
"-----\n" +
"1<caret>2345\n" +
"abcde\n" +
"-----",
)
typeText("Vj")
enterCommand("'<,'>action CommentByBlockComment")
assertMode(Mode.NORMAL())
assertState(
"-----\n" +
"/*\n" +
"12345\n" +
"abcde\n" +
"*/\n" +
"-----",
)
}
@TestWithoutNeovim(SkipNeovimReason.ACTION_COMMAND)
@Test
fun testExCommandInVisualLineModeWithIncsearch() {
configureByJavaText(
"-----\n" +
"1<caret>2345\n" +
"abcde\n" +
"-----",
)
enterCommand("incsearch")
typeText("Vj")
enterCommand("'<,'>action CommentByBlockComment")
assertMode(Mode.NORMAL())
assertState(
"-----\n" +
"/*\n" +
"12345\n" +
"abcde\n" +
"*/\n" +
"-----",
)
}
// VIM-862 |:action| in visual block mode
@TestWithoutNeovim(SkipNeovimReason.ACTION_COMMAND)
@Test
fun testExCommandInVisualBlockMode() {
configureByJavaText(
"-----\n" +
"1<caret>2345\n" +
"abcde\n" +
"-----",
)
typeText("<C-V>lj")
enterCommand("'<,'>action CommentByBlockComment")
assertMode(Mode.NORMAL())
assertState(
"-----\n" +
"1/*23*/45\n" +
"a/*bc*/de\n" +
"-----",
)
}
@TestWithoutNeovim(SkipNeovimReason.ACTION_COMMAND)
@Test
fun testExCommandInVisualBlockModeWithIncsearch() {
configureByJavaText(
"-----\n" +
"1<caret>2345\n" +
"abcde\n" +
"-----",
)
enterCommand("set incsearch")
typeText("<C-V>lj")
enterCommand("'<,'>action CommentByBlockComment")
assertMode(Mode.NORMAL())
assertState(
"-----\n" +
"1/*23*/45\n" +
"a/*bc*/de\n" +
"-----",
)
}
} |
import kotlin.reflect.KProperty
import java.lang.reflect.Type
interface IDelegate<T> {
operator fun getValue(t: T, p: KProperty<*>): T
}
val <T> T.property by object : IDelegate<T> {
override fun getValue(t: T, p: KProperty<*>): T {
return t
}
}
val <T> T.property2 by run<IDelegate<T>> {
fun test(t: T): T {
return t
}
object : IDelegate<T> {
override fun getValue(t: T, p: KProperty<*>): T {
return test(t)
}
}
}
fun box(): String {
val superInterfaces: Array<Type> = Class.forName("TypeParameterInDelegatedPropertyKt\$property\$2").getGenericInterfaces()
if (!superInterfaces[0].toString().contains("IDelegate<java.lang.Object>")) return "FAIL"
val superInterfaces2: Array<Type> = Class.forName("TypeParameterInDelegatedPropertyKt\$property2\$2\$1").getGenericInterfaces()
if (!superInterfaces2[0].toString().contains("IDelegate<java.lang.Object>")) return "FAIL"
if ("OK".property2 != "OK") return "FAIL"
return "OK"
} |
package one.two;
public class Bar {
public static final int BAR = MainKt.FOO + 1;
}
// FILE: Main.kt
package one.two
const val FOO = <!EVALUATED("1")!>1<!>
const val BAZ = <!EVALUATED("3")!>Bar.BAR + 1<!>
fun box(): String {
return "OK"
}
|
OPTIONAL_JVM_INLINE_ANNOTATION
value class Z<T: Int>(val int: T)
OPTIONAL_JVM_INLINE_ANNOTATION
value class L<T: Long>(val long: T)
OPTIONAL_JVM_INLINE_ANNOTATION
value class Str<T: String>(val string: T)
OPTIONAL_JVM_INLINE_ANNOTATION
value class Obj<T: Any>(val obj: T)
fun box(): String {
var xz = Z(0)
var xl = L(0L)
var xs = Str("")
var xo = Obj("")
val fn = {
xz = Z(42)
xl = L(1234L)
xs = Str("abc")
xo = Obj("def")
}
fn()
if (xz.int != 42) throw AssertionError()
if (xl.long != 1234L) throw AssertionError()
if (xs.string != "abc") throw AssertionError()
if (xo.obj != "def") throw AssertionError()
return "OK"
} |
package foo
var log = ""
class T(val id: Int) {
operator fun component1(): Int {
log += "($id).component1();"
return 1
}
operator fun component2(): String {
log += "($id).component2();"
return "1"
}
}
class C {
operator fun iterator(): Iterator<T> = object: Iterator<T> {
var i = 0
var data = arrayOf(T(3), T(1), T(2))
override fun hasNext(): Boolean {
log += "C.hasNext();"
return i < data.size
}
override fun next(): T {
log += "C.next();"
return data[i++]
}
}
}
fun box(): String {
for ((a, b) in arrayOf(T(3), T(1), T(2)));
assertEquals("(3).component1();(3).component2();(1).component1();(1).component2();(2).component1();(2).component2();", log)
log = ""
for ((a, b) in C());
assertEquals("C.hasNext();C.next();(3).component1();(3).component2();C.hasNext();C.next();" +
"(1).component1();(1).component2();C.hasNext();C.next();" +
"(2).component1();(2).component2();C.hasNext();", log)
return "OK"
}
|
package androidx.fragment.app
import android.app.Activity
import android.os.Bundle
import java.io.File
import kotlinx.android.synthetic.main.layout.*
open class FragmentManager {
open fun findFragmentById(id: Int): Fragment = throw Exception("Function getFragmentById() is not overriden")
}
open class Fragment {
open fun getFragmentManager(): FragmentManager = throw Exception("Function getFragmentManager() is not overriden")
}
open class FragmentActivity : Activity() {
open fun getSupportFragmentManager(): FragmentManager = throw Exception("Function getSupportFragmentManager() is not overriden")
}
public class MyActivity : FragmentActivity() {
init { fragm }
}
public class MyFragment : Fragment() {
init { fragm }
}
// 1 INVOKEVIRTUAL androidx/fragment/app/FragmentActivity\.getSupportFragmentManager
// 1 INVOKEVIRTUAL androidx/fragment/app/Fragment\.getFragmentManager
// 2 GETSTATIC test/R\$id\.fragm
// 2 INVOKEVIRTUAL androidx/fragment/app/FragmentManager\.findFragmentById |
operator fun <K, V> MutableMap<K, V>.set(k: K, v: V) {}
fun foo(a: MutableMap<String, String>, x: String?) {
a[x!!] = <!DEBUG_INFO_SMARTCAST!>x<!>
a[<!DEBUG_INFO_SMARTCAST!>x<!>] = x<!UNNECESSARY_NOT_NULL_ASSERTION!>!!<!>
}
fun foo1(a: MutableMap<String, String>, x: String?) {
a[<!TYPE_MISMATCH!>x<!>] = x!!
a[x<!UNNECESSARY_NOT_NULL_ASSERTION!>!!<!>] = <!DEBUG_INFO_SMARTCAST!>x<!>
}
|
@Target(AnnotationTarget.PROPERTY, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER)
annotation class Ann
expect val onGetter: String
@Ann get
expect val onGetterImplicit: String
@Ann get
@get:Ann
expect val onGetterWithExplicitTarget: String
@get:Ann
expect val explicitTargetMatchesWithoutTarget: String
@get:Ann
expect val setOnPropertyWithoutTargetNotMatch: String
expect var onSetter: String
@Ann set
// MODULE: m1-jvm()()(m1-common)
// FILE: jvm.kt
actual val <!ACTUAL_ANNOTATIONS_NOT_MATCH_EXPECT!>onGetter<!>: String
get() = ""
actual val <!ACTUAL_ANNOTATIONS_NOT_MATCH_EXPECT!>onGetterImplicit<!>: String = ""
actual val <!ACTUAL_ANNOTATIONS_NOT_MATCH_EXPECT!>onGetterWithExplicitTarget<!>: String
get() = ""
actual val explicitTargetMatchesWithoutTarget: String
@Ann get() = ""
@Ann
actual val <!ACTUAL_ANNOTATIONS_NOT_MATCH_EXPECT!>setOnPropertyWithoutTargetNotMatch<!>: String = ""
actual var <!ACTUAL_ANNOTATIONS_NOT_MATCH_EXPECT!>onSetter<!>: String
get() = ""
set(_) {}
|
package org.jetbrains.kotlin.descriptors.deserialization
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
interface ClassDescriptorFactory {
fun shouldCreateClass(packageFqName: FqName, name: Name): Boolean
fun createClass(classId: ClassId): ClassDescriptor?
// Note: do not rely on this function to return _all_ classes. Some factories can not enumerate all classes that they're able to create
fun getAllContributedClassesIfPossible(packageFqName: FqName): Collection<ClassDescriptor>
}
|
class A(val w: Char) {
val x: Int
var y: Int
val z: Int
val v = -1
<!MUST_BE_INITIALIZED_OR_BE_ABSTRACT!>val uninitialized: Int<!>
val overinitialized: Int
constructor(): this('a') {
y = 1
<!VAL_REASSIGNMENT!>overinitialized<!> = 2
<!VAL_REASSIGNMENT!>uninitialized<!> = 3
}
// anonymous
init {
x = 4
z = 5
overinitialized = 6
}
constructor(a: Int): this('b') {
y = 7
}
// anonymous
init {
y = 8
}
}
|
package com.android.tools.idea.layoutinspector.model
import com.android.ide.common.rendering.api.ResourceNamespace
import com.android.ide.common.rendering.api.ResourceReference
import com.android.resources.ResourceType
import com.android.tools.idea.layoutinspector.model
import com.android.tools.idea.layoutinspector.util.FakeTreeSettings
import com.google.common.truth.Truth.assertThat
import com.intellij.testFramework.UsefulTestCase
import org.junit.Test
private val LAYOUT_SCREEN_SIMPLE =
ResourceReference(ResourceNamespace.ANDROID, ResourceType.LAYOUT, "screen_simple")
private val LAYOUT_APPCOMPAT_SCREEN_SIMPLE =
ResourceReference(ResourceNamespace.APPCOMPAT, ResourceType.LAYOUT, "abc_screen_simple")
private val LAYOUT_MAIN =
ResourceReference(ResourceNamespace.RES_AUTO, ResourceType.LAYOUT, "activity_main")
class ViewNodeTest {
@Test
fun testFlatten() {
val model = model {
view(ROOT) {
view(VIEW1) { view(VIEW3) }
view(VIEW2)
}
}
UsefulTestCase.assertSameElements(
model[ROOT]!!.flattenedList().map { it.drawId }.toList(),
ROOT,
VIEW1,
VIEW3,
VIEW2
)
UsefulTestCase.assertSameElements(
model[VIEW1]!!.flattenedList().map { it.drawId }.toList(),
VIEW1,
VIEW3
)
}
@Test
fun testIsSystemNode() {
val model = model {
view(ROOT, layout = null, qualifiedName = "com.android.internal.policy.DecorView") {
view(VIEW1, layout = LAYOUT_SCREEN_SIMPLE) {
view(VIEW2, layout = LAYOUT_APPCOMPAT_SCREEN_SIMPLE) {
view(VIEW3, layout = LAYOUT_MAIN) {
view(VIEW4, layout = null, qualifiedName = "com.acme.MyImageView")
}
}
}
}
}
val treeSettings = FakeTreeSettings()
val system1 = model[ROOT]!!
val system2 = model[VIEW1]!!
val system3 = model[VIEW2]!!
val user1 = model[VIEW3]!!
val user2 = model[VIEW4]!!
assertThat(system1.isSystemNode).isTrue()
assertThat(system2.isSystemNode).isTrue()
assertThat(system3.isSystemNode).isTrue()
assertThat(user1.isSystemNode).isFalse()
assertThat(user2.isSystemNode).isFalse()
treeSettings.hideSystemNodes = true
assertThat(system1.isInComponentTree(treeSettings)).isFalse()
assertThat(system2.isInComponentTree(treeSettings)).isFalse()
assertThat(system3.isInComponentTree(treeSettings)).isFalse()
assertThat(user1.isInComponentTree(treeSettings)).isTrue()
assertThat(user2.isInComponentTree(treeSettings)).isTrue()
treeSettings.hideSystemNodes = false
assertThat(system1.isInComponentTree(treeSettings)).isTrue()
assertThat(system2.isInComponentTree(treeSettings)).isTrue()
assertThat(system3.isInComponentTree(treeSettings)).isTrue()
assertThat(user1.isInComponentTree(treeSettings)).isTrue()
assertThat(user2.isInComponentTree(treeSettings)).isTrue()
}
@Test
fun testClosestUnfilteredNode() {
val model = model {
view(ROOT, layout = null, qualifiedName = "com.android.internal.policy.DecorView") {
view(VIEW1, layout = LAYOUT_MAIN) {
view(VIEW2, layout = LAYOUT_SCREEN_SIMPLE) {
view(VIEW3, layout = LAYOUT_APPCOMPAT_SCREEN_SIMPLE) {}
}
}
}
}
val treeSettings = FakeTreeSettings()
val root = model[ROOT]!!
val view1 = model[VIEW1]!!
val view2 = model[VIEW2]!!
val view3 = model[VIEW3]!!
assertThat(view3.findClosestUnfilteredNode(treeSettings)).isSameAs(view1)
assertThat(view2.findClosestUnfilteredNode(treeSettings)).isSameAs(view1)
assertThat(view1.findClosestUnfilteredNode(treeSettings)).isSameAs(view1)
assertThat(root.findClosestUnfilteredNode(treeSettings)).isNull()
}
}
|
object Host {
@JvmStatic fun concat(s1: String, s2: String, s3: String = "K", s4: String = "x") =
s1 + s2 + s3 + s4
}
fun box(): String {
val concat = Host::concat
val concatParams = concat.parameters
return concat.callBy(mapOf(
concatParams[0] to "",
concatParams[1] to "O",
concatParams[3] to ""
))
}
|
<!EXPECT_ACTUAL_INCOMPATIBILITY{JVM}!>expect class Foo() {
<!EXPECT_ACTUAL_INCOMPATIBILITY{JVM}!>fun foo(p: Int = 1)<!>
}<!>
// MODULE: m2-jvm()()(m1-common)
// FILE: jvm.kt
open class Base<T> {
fun foo(p: T) {}
}
actual class Foo : <!DEFAULT_ARGUMENTS_IN_EXPECT_ACTUALIZED_BY_FAKE_OVERRIDE!>Base<Int>()<!>
|
class Host {
val ok = "OK"
fun foo() = run { bar(ok) }
companion object {
val ok = 0
fun bar(s: String) = s.substring(ok)
}
}
fun box() = Host().foo() |
package demo.plot.batik.plotConfig
import demo.plot.common.model.plotConfig.TransformLog10
import demo.common.batik.demoUtils.PlotSpecsDemoWindowBatik
fun main() {
with(TransformLog10()) {
PlotSpecsDemoWindowBatik(
"'log10' transform.",
plotSpecList()
).open()
}
}
|
package foo
external class B {
companion object {
val value: String
}
}
inline fun test() = B.value
fun box(): String {
return test()
}
// FILE: native.js
function B() {};
B.value = "OK";
|
package org.jetbrains.kotlin.ir.expressions
import org.jetbrains.kotlin.ir.symbols.IrSymbol
import org.jetbrains.kotlin.ir.types.IrType
import org.jetbrains.kotlin.ir.util.transformInPlace
import org.jetbrains.kotlin.ir.visitors.IrElementTransformer
import org.jetbrains.kotlin.ir.visitors.IrElementVisitor
/**
* Generated from: [org.jetbrains.kotlin.ir.generator.IrTree.memberAccessExpression]
*/
abstract class IrMemberAccessExpression<S : IrSymbol> : IrDeclarationReference() {
abstract var dispatchReceiver: IrExpression?
abstract var extensionReceiver: IrExpression?
abstract override val symbol: S
abstract var origin: IrStatementOrigin?
protected abstract val valueArguments: Array<IrExpression?>
protected abstract val typeArguments: Array<IrType?>
val valueArgumentsCount: Int
get() = valueArguments.size
val typeArgumentsCount: Int
get() = typeArguments.size
fun getValueArgument(index: Int): IrExpression? {
checkArgumentSlotAccess("value", index, valueArguments.size)
return valueArguments[index]
}
fun getTypeArgument(index: Int): IrType? {
checkArgumentSlotAccess("type", index, typeArguments.size)
return typeArguments[index]
}
fun putValueArgument(index: Int, valueArgument: IrExpression?) {
checkArgumentSlotAccess("value", index, valueArguments.size)
valueArguments[index] = valueArgument
}
fun putTypeArgument(index: Int, type: IrType?) {
checkArgumentSlotAccess("type", index, typeArguments.size)
typeArguments[index] = type
}
override fun <D> acceptChildren(visitor: IrElementVisitor<Unit, D>, data: D) {
dispatchReceiver?.accept(visitor, data)
extensionReceiver?.accept(visitor, data)
valueArguments.forEach { it?.accept(visitor, data) }
}
override fun <D> transformChildren(transformer: IrElementTransformer<D>, data: D) {
dispatchReceiver = dispatchReceiver?.transform(transformer, data)
extensionReceiver = extensionReceiver?.transform(transformer, data)
valueArguments.transformInPlace(transformer, data)
}
}
|
package org.jetbrains.kotlin.backend.konan
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.konan.exec.Command
import org.jetbrains.kotlin.konan.file.*
import org.jetbrains.kotlin.konan.target.ClangArgs
import org.jetbrains.kotlin.konan.target.KonanTarget
private const val dumpBridges = false
internal class CStubsManager(private val target: KonanTarget, private val generationState: NativeGenerationState) {
fun getUniqueName(prefix: String) = generationState.fileLowerState.getCStubUniqueName(prefix)
fun addStub(kotlinLocation: CompilerMessageLocation?, lines: List<String>, language: String) {
val stubs = languageToStubs.getOrPut(language) { mutableListOf() }
stubs += Stub(kotlinLocation, lines)
}
fun compile(clang: ClangArgs, messageCollector: MessageCollector, verbose: Boolean): List<File> {
if (languageToStubs.isEmpty()) return emptyList()
val bitcodes = languageToStubs.entries.map { (language, stubs) ->
val compilerOptions = mutableListOf<String>()
val sourceFileExtension = when {
language == "C++" -> ".cpp"
target.family.isAppleFamily -> {
compilerOptions += "-fobjc-arc"
".m" // TODO: consider managing C and Objective-C stubs separately.
}
else -> ".c"
}
val cSource = createTempFile("cstubs", sourceFileExtension).deleteOnExit()
cSource.writeLines(stubs.flatMap { it.lines })
val bitcode = createTempFile("cstubs", ".bc").deleteOnExit()
val cSourcePath = cSource.absolutePath
val clangCommand = clang.clangC(
*compilerOptions.toTypedArray(), "-O2",
"-fexceptions", // Allow throwing exceptions through generated stubs.
cSourcePath, "-emit-llvm", "-c", "-o", bitcode.absolutePath
)
if (dumpBridges) {
println("CSTUBS for ${language}")
stubs.flatMap { it.lines }.forEach {
println(it)
}
println("CSTUBS in ${cSource.absolutePath}")
println("CSTUBS CLANG COMMAND:")
println(clangCommand.joinToString(" "))
}
val result = Command(clangCommand).getResult(withErrors = true)
if (result.exitCode != 0) {
reportCompilationErrors(cSourcePath, stubs, result, messageCollector, verbose)
}
bitcode
}
return bitcodes
}
private fun reportCompilationErrors(
cSourcePath: String,
stubs: List<Stub>,
result: Command.Result,
messageCollector: MessageCollector,
verbose: Boolean
): Nothing {
val regex = Regex("${Regex.escape(cSourcePath)}:([0-9]+):[0-9]+: error: .*")
val errorLines = result.outputLines.mapNotNull { line ->
regex.matchEntire(line)?.let { matchResult ->
matchResult.groupValues[1].toInt()
}
}
val lineToStub = ArrayList<Stub>()
stubs.forEach { stub ->
repeat(stub.lines.size) { lineToStub.add(stub) }
}
val cSourceCopyPath = "cstubs.c"
if (verbose) {
File(cSourcePath).copyTo(File(cSourceCopyPath))
}
if (errorLines.isNotEmpty()) {
errorLines.forEach {
messageCollector.report(
CompilerMessageSeverity.ERROR,
"Unable to compile C bridge" + if (verbose) " at $cSourceCopyPath:$it" else "",
lineToStub[it - 1].kotlinLocation
)
}
} else {
messageCollector.report(
CompilerMessageSeverity.ERROR,
"Unable to compile C bridges",
null
)
}
throw KonanCompilationException()
}
private val languageToStubs = mutableMapOf<String, MutableList<Stub>>()
private class Stub(val kotlinLocation: CompilerMessageLocation?, val lines: List<String>)
} |
import java.util.HashSet
fun test123() {
val g: (Int) -> Unit = if (true) {
val set = HashSet<Int>()
fun (i: Int) {
set.add(i)
}
}
else {
{ it -> it }
}
} |
package node.diagnosticsChannel
sealed external interface TracingChannelSubscribersAsyncEndMessage<ContextType : Any> {
var error: Any?
var result: Any?
@Suppress(
"WRONG_BODY_OF_EXTERNAL_DECLARATION",
"INLINE_EXTERNAL_DECLARATION",
"NON_ABSTRACT_MEMBER_OF_EXTERNAL_INTERFACE",
"DECLARATION_CANT_BE_INLINED",
)
inline val contextType: ContextType
get() = unsafeCast<ContextType>()
}
|
package org.jetbrains.kotlin.backend.konan.llvm.objcexport
import kotlinx.cinterop.toKString
import llvm.*
import org.jetbrains.kotlin.backend.common.lower.coroutines.getOrCreateFunctionWithContinuationStub
import org.jetbrains.kotlin.backend.konan.*
import org.jetbrains.kotlin.backend.konan.ir.*
import org.jetbrains.kotlin.backend.konan.ir.ClassLayoutBuilder
import org.jetbrains.kotlin.backend.konan.ir.KonanSymbols
import org.jetbrains.kotlin.backend.konan.llvm.*
import org.jetbrains.kotlin.backend.konan.llvm.objc.ObjCCodeGenerator
import org.jetbrains.kotlin.backend.konan.llvm.objc.ObjCDataGenerator
import org.jetbrains.kotlin.backend.konan.lower.getObjectClassInstanceFunction
import org.jetbrains.kotlin.backend.konan.objcexport.*
import org.jetbrains.kotlin.descriptors.ClassKind
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.ir.ObsoleteDescriptorBasedAPI
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.expressions.IrClassReference
import org.jetbrains.kotlin.ir.expressions.IrVararg
import org.jetbrains.kotlin.ir.symbols.IrClassSymbol
import org.jetbrains.kotlin.ir.symbols.IrConstructorSymbol
import org.jetbrains.kotlin.ir.symbols.IrFunctionSymbol
import org.jetbrains.kotlin.ir.symbols.IrSimpleFunctionSymbol
import org.jetbrains.kotlin.ir.types.IrType
import org.jetbrains.kotlin.ir.types.isNothing
import org.jetbrains.kotlin.ir.types.isUnit
import org.jetbrains.kotlin.ir.util.*
import org.jetbrains.kotlin.konan.target.AppleConfigurables
import org.jetbrains.kotlin.konan.target.LinkerOutputKind
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi2ir.descriptors.IrBuiltInsOverDescriptors
import org.jetbrains.kotlin.utils.DFS
internal fun TypeBridge.makeNothing(llvm: CodegenLlvmHelpers) = when (this) {
is ReferenceBridge, is BlockPointerBridge -> llvm.kNullInt8Ptr
is ValueTypeBridge -> LLVMConstNull(this.objCValueType.toLlvmType(llvm))!!
}
internal class ObjCExportFunctionGenerationContext(
builder: ObjCExportFunctionGenerationContextBuilder,
override val needCleanupLandingpadAndLeaveFrame: Boolean
) : FunctionGenerationContext(builder) {
val objCExportCodegen = builder.objCExportCodegen
// Note: we could generate single "epilogue" and make all [ret]s just branch to it (like [DefaultFunctionGenerationContext]),
// but this would be useless for most of the usages, which have only one [ret].
// Remaining usages can be optimized ad hoc.
override fun ret(value: LLVMValueRef?): LLVMValueRef = if (value == null) {
retVoid()
} else {
retValue(value)
}
/**
* autoreleases and returns [value].
* It is equivalent to `ret(autorelease(value))`, but optimizes the autorelease out if the caller is prepared for it.
*
* See the Clang documentation and the Obj-C runtime source code for more details:
* https://clang.llvm.org/docs/AutomaticReferenceCounting.html#arc-runtime-objc-autoreleasereturnvalue
* https://github.com/opensource-apple/objc4/blob/cd5e62a5597ea7a31dccef089317abb3a661c154/runtime/objc-object.h#L930
*/
fun autoreleaseAndRet(value: LLVMValueRef) {
onReturn()
// Note: it is important to make this call tail (otherwise the elimination magic won't work),
// so it should go after other "epilogue" instructions, and that's why we couldn't just use
// ret(autorelease(value))
val result = call(objCExportCodegen.objcAutoreleaseReturnValue, listOf(value))
LLVMSetTailCall(result, 1)
rawRet(result)
}
fun objcReleaseFromRunnableThreadState(objCReference: LLVMValueRef) {
switchThreadStateIfExperimentalMM(ThreadState.Native)
objcReleaseFromNativeThreadState(objCReference)
switchThreadStateIfExperimentalMM(ThreadState.Runnable)
}
fun objcReleaseFromNativeThreadState(objCReference: LLVMValueRef) {
// It is nounwind, so no exception handler is required.
call(objCExportCodegen.objcRelease, listOf(objCReference), exceptionHandler = ExceptionHandler.None)
}
override fun processReturns() {
// Do nothing.
}
val terminatingExceptionHandler = object : ExceptionHandler.Local() {
override val unwind: LLVMBasicBlockRef by lazy {
val result = basicBlockInFunction("fatal_landingpad", endLocation)
appendingTo(result) {
val landingpad = gxxLandingpad(0)
LLVMSetCleanup(landingpad, 1)
terminateWithCurrentException(landingpad)
}
result
}
}
}
internal class ObjCExportFunctionGenerationContextBuilder(
functionProto: LlvmFunctionProto,
val objCExportCodegen: ObjCExportCodeGeneratorBase
) : FunctionGenerationContextBuilder<ObjCExportFunctionGenerationContext>(
functionProto,
objCExportCodegen.codegen
) {
// Unless specified otherwise, all generated bridges by ObjCExport should have `LeaveFrame`
// because there is no guarantee of catching Kotlin exception in Kotlin code.
var needCleanupLandingpadAndLeaveFrame = true
override fun build() = ObjCExportFunctionGenerationContext(this, needCleanupLandingpadAndLeaveFrame)
}
internal inline fun ObjCExportCodeGeneratorBase.functionGenerator(
functionProto: LlvmFunctionProto,
configure: ObjCExportFunctionGenerationContextBuilder.() -> Unit = {}
): ObjCExportFunctionGenerationContextBuilder = ObjCExportFunctionGenerationContextBuilder(
functionProto,
this
).apply(configure)
internal fun ObjCExportFunctionGenerationContext.callAndMaybeRetainAutoreleased(
function: LlvmCallable,
signature: LlvmFunctionSignature,
args: List<LLVMValueRef>,
resultLifetime: Lifetime = Lifetime.IRRELEVANT,
exceptionHandler: ExceptionHandler,
doRetain: Boolean
): LLVMValueRef {
if (!doRetain) return call(function, args, resultLifetime, exceptionHandler)
// Objective-C runtime provides "optimizable" return for autoreleased references:
// the caller (this code) handles the return value with objc_retainAutoreleasedReturnValue,
// and the callee tries to detect this by looking at the code location at the return address.
// The latter is implemented as tail calls to objc_retainAutoreleaseReturnValue or objc_autoreleaseReturnValue.
//
// These functions look for a specific pattern immediately following the call site.
// Depending on the platform, this pattern is either
// * move from the return value register to the argument register and call to objcRetainAutoreleasedReturnValue, or
// * special instruction (like `mov fp, fp`) that is not supposed to be generated in any other case.
//
// Unfortunately, we can't just generate this straightforwardly in LLVM,
// because we have to catch exceptions thrown by `function`.
// So we have to use `invoke` LLVM instructions. In this case LLVM sometimes inserts
// a redundant jump after the call when generating the machine code, ruining the expected code pattern.
//
// To workaround this, we generate the call and the pattern after it as a separate noinline function ("outlined"),
// and catch the exceptions in the caller of this function.
// So, no exception handler in "outlined" => no redundant jump => the optimized return works properly.
val functionIsPassedAsLastParameter = !function.isConstant
val valuesToPass = args + if (functionIsPassedAsLastParameter) listOf(function.asCallback()) else emptyList()
val outlinedType = LlvmFunctionSignature(
signature.returnType,
signature.parameterTypes + if (functionIsPassedAsLastParameter) listOf(LlvmParamType(pointerType(function.functionType))) else emptyList(),
functionAttributes = listOf(LlvmFunctionAttribute.NoInline)
)
val outlined = objCExportCodegen.functionGenerator(outlinedType.toProto( this.function.name.orEmpty() + "_outlined", null, LLVMLinkage.LLVMPrivateLinkage)) {
setupBridgeDebugInfo()
// Don't generate redundant cleanup landingpad (the generation would fail due to forbidRuntime below):
needCleanupLandingpadAndLeaveFrame = false
}.generate {
forbidRuntime = true // Don't emit safe points, frame management etc.
val actualArgs = signature.parameterTypes.indices.map { param(it) }
val actualCallable = if (functionIsPassedAsLastParameter) LlvmCallable(signature.llvmFunctionType, param(signature.parameterTypes.size), signature) else function
// Use LLVMBuildCall instead of call, because the latter enforces using exception handler, which is exactly what we have to avoid.
val result = actualCallable.buildCall(builder, actualArgs).let { callResult ->
// Simplified version of emitAutoreleasedReturnValueMarker in Clang:
objCExportCodegen.objcRetainAutoreleasedReturnValueMarker?.let {
LLVMBuildCall2(arg0 = builder, functionType(llvm.voidType), Fn = it, Args = null, NumArgs = 0, Name = "")
}
call(objCExportCodegen.objcRetainAutoreleasedReturnValue, listOf(callResult)).also {
if (context.config.target.markARCOptimizedReturnCallsAsNoTail())
LLVMSetNoTailCall(it)
}
}
ret(result)
}
return call(outlined, valuesToPass, resultLifetime, exceptionHandler)
}
internal open class ObjCExportCodeGeneratorBase(codegen: CodeGenerator) : ObjCCodeGenerator(codegen) {
val symbols get() = context.ir.symbols
val runtime get() = codegen.runtime
val staticData get() = codegen.staticData
// TODO: pass referenced functions explicitly
val rttiGenerator = RTTIGenerator(generationState, referencedFunctions = null)
fun dispose() {
rttiGenerator.dispose()
}
fun ObjCExportFunctionGenerationContext.callFromBridge(
llvmFunction: LLVMValueRef,
args: List<LLVMValueRef>,
resultLifetime: Lifetime = Lifetime.IRRELEVANT
): LLVMValueRef {
val llvmDeclarations = LlvmCallable(
getGlobalFunctionType(llvmFunction),
// llvmFunction could be a function pointer here, and we can't infer attributes from it.
llvmFunction,
LlvmFunctionAttributeProvider.makeEmpty()
)
return callFromBridge(llvmDeclarations, args, resultLifetime)
}
fun ObjCExportFunctionGenerationContext.callFromBridge(
function: LlvmCallable,
args: List<LLVMValueRef>,
resultLifetime: Lifetime = Lifetime.IRRELEVANT,
): LLVMValueRef {
// All calls that actually do need to forward exceptions to callers should express this explicitly.
val exceptionHandler = terminatingExceptionHandler
return call(function, args, resultLifetime, exceptionHandler)
}
fun ObjCExportFunctionGenerationContext.kotlinReferenceToLocalObjC(value: LLVMValueRef) =
callFromBridge(llvm.Kotlin_ObjCExport_refToLocalObjC, listOf(value))
fun ObjCExportFunctionGenerationContext.kotlinReferenceToRetainedObjC(value: LLVMValueRef) =
callFromBridge(llvm.Kotlin_ObjCExport_refToRetainedObjC, listOf(value))
fun ObjCExportFunctionGenerationContext.objCReferenceToKotlin(value: LLVMValueRef, resultLifetime: Lifetime) =
callFromBridge(llvm.Kotlin_ObjCExport_refFromObjC, listOf(value), resultLifetime)
private val blockToKotlinFunctionConverterCache = mutableMapOf<BlockPointerBridge, LlvmCallable>()
internal fun blockToKotlinFunctionConverter(bridge: BlockPointerBridge): LlvmCallable =
blockToKotlinFunctionConverterCache.getOrPut(bridge) {
generateBlockToKotlinFunctionConverter(bridge)
}
protected val blockGenerator = BlockGenerator(this.codegen)
private val functionToRetainedBlockConverterCache = mutableMapOf<BlockPointerBridge, LlvmCallable>()
internal fun kotlinFunctionToRetainedBlockConverter(bridge: BlockPointerBridge): LlvmCallable =
functionToRetainedBlockConverterCache.getOrPut(bridge) {
blockGenerator.run {
generateConvertFunctionToRetainedBlock(bridge)
}
}
}
internal class ObjCExportBlockCodeGenerator(codegen: CodeGenerator) : ObjCExportCodeGeneratorBase(codegen) {
init {
// Must be generated along with stdlib:
// 1. Enumerates [BuiltInFictitiousFunctionIrClassFactory] built classes, which may be incomplete otherwise.
// 2. Modifies stdlib global initializers.
// 3. Defines runtime-declared globals.
require(generationState.shouldDefineFunctionClasses)
}
fun generate() {
emitFunctionConverters()
emitBlockToKotlinFunctionConverters()
dispose()
}
}
internal class ObjCExportCodeGenerator(
codegen: CodeGenerator,
val namer: ObjCExportNamer,
val mapper: ObjCExportMapper
) : ObjCExportCodeGeneratorBase(codegen) {
inline fun <reified T: IrFunction> T.getLowered(): T = when (this) {
is IrSimpleFunction -> when {
isSuspend -> this.getOrCreateFunctionWithContinuationStub(context) as T
else -> this
}
else -> this
}
val ObjCMethodSpec.BaseMethod<IrFunctionSymbol>.owner get() = symbol.owner.getLowered()
val ObjCMethodSpec.BaseMethod<IrConstructorSymbol>.owner get() = symbol.owner.getLowered()
val ObjCMethodSpec.BaseMethod<IrSimpleFunctionSymbol>.owner get() = symbol.owner.getLowered()
val selectorsToDefine = mutableMapOf<String, MethodBridge>()
internal val continuationToRetainedCompletionConverter: LlvmCallable by lazy {
generateContinuationToRetainedCompletionConverter(blockGenerator)
}
internal val unitContinuationToRetainedCompletionConverter: LlvmCallable by lazy {
generateUnitContinuationToRetainedCompletionConverter(blockGenerator)
}
// Caution! Arbitrary methods shouldn't be called from Runnable thread state.
fun ObjCExportFunctionGenerationContext.genSendMessage(
returnType: LlvmParamType,
parameterTypes: List<LlvmParamType>,
receiver: LLVMValueRef,
selector: String,
vararg args: LLVMValueRef,
): LLVMValueRef {
val objcMsgSendType = LlvmFunctionSignature(
returnType,
listOf(LlvmParamType(llvm.int8PtrType), LlvmParamType(llvm.int8PtrType)) + parameterTypes
)
return callFromBridge(msgSender(objcMsgSendType), listOf(receiver, genSelector(selector)) + args)
}
fun FunctionGenerationContext.kotlinToObjC(
value: LLVMValueRef,
valueType: ObjCValueType
): LLVMValueRef = when (valueType) {
ObjCValueType.BOOL -> zext(value, llvm.int8Type) // TODO: zext behaviour may be strange on bit types.
ObjCValueType.UNICHAR,
ObjCValueType.CHAR, ObjCValueType.SHORT, ObjCValueType.INT, ObjCValueType.LONG_LONG,
ObjCValueType.UNSIGNED_CHAR, ObjCValueType.UNSIGNED_SHORT, ObjCValueType.UNSIGNED_INT,
ObjCValueType.UNSIGNED_LONG_LONG,
ObjCValueType.FLOAT, ObjCValueType.DOUBLE, ObjCValueType.POINTER -> value
}
private fun FunctionGenerationContext.objCToKotlin(
value: LLVMValueRef,
valueType: ObjCValueType
): LLVMValueRef = when (valueType) {
ObjCValueType.BOOL -> icmpNe(value, llvm.int8(0))
ObjCValueType.UNICHAR,
ObjCValueType.CHAR, ObjCValueType.SHORT, ObjCValueType.INT, ObjCValueType.LONG_LONG,
ObjCValueType.UNSIGNED_CHAR, ObjCValueType.UNSIGNED_SHORT, ObjCValueType.UNSIGNED_INT,
ObjCValueType.UNSIGNED_LONG_LONG,
ObjCValueType.FLOAT, ObjCValueType.DOUBLE, ObjCValueType.POINTER -> value
}
private fun ObjCExportFunctionGenerationContext.objCBlockPointerToKotlin(
value: LLVMValueRef,
typeBridge: BlockPointerBridge,
resultLifetime: Lifetime
) = callFromBridge(
blockToKotlinFunctionConverter(typeBridge),
listOf(value),
resultLifetime
)
internal fun ObjCExportFunctionGenerationContext.kotlinFunctionToRetainedObjCBlockPointer(
typeBridge: BlockPointerBridge,
value: LLVMValueRef
) = callFromBridge(kotlinFunctionToRetainedBlockConverter(typeBridge), listOf(value))
fun ObjCExportFunctionGenerationContext.objCToKotlin(
value: LLVMValueRef,
typeBridge: TypeBridge,
resultLifetime: Lifetime
): LLVMValueRef = when (typeBridge) {
is ReferenceBridge -> objCReferenceToKotlin(value, resultLifetime)
is BlockPointerBridge -> objCBlockPointerToKotlin(value, typeBridge, resultLifetime)
is ValueTypeBridge -> objCToKotlin(value, typeBridge.objCValueType)
}
fun FunctionGenerationContext.initRuntimeIfNeeded() {
this.needsRuntimeInit = true
}
/**
* Convert [genValue] of Kotlin type from [actualType] to [expectedType] in a bridge method.
*/
inline fun ObjCExportFunctionGenerationContext.convertKotlin(
genValue: (Lifetime) -> LLVMValueRef,
actualType: IrType,
expectedType: IrType,
resultLifetime: Lifetime
): LLVMValueRef {
val conversion = context.getTypeConversion(actualType, expectedType)
?: return genValue(resultLifetime)
val value = genValue(Lifetime.ARGUMENT)
return callFromBridge(conversion.owner.llvmFunction, listOf(value), resultLifetime)
}
private fun generateTypeAdaptersForKotlinTypes(spec: ObjCExportCodeSpec?): List<ObjCTypeAdapter> {
val types = spec?.types.orEmpty() + objCClassForAny
val allReverseAdapters = createReverseAdapters(types)
return types.map {
val reverseAdapters = allReverseAdapters.getValue(it).adapters
when (it) {
objCClassForAny -> {
createTypeAdapter(it, superClass = null, reverseAdapters)
}
is ObjCClassForKotlinClass -> {
val superClass = it.superClassNotAny ?: objCClassForAny
dataGenerator.emitEmptyClass(it.binaryName, superClass.binaryName)
// Note: it is generated only to be visible for linker.
// Methods will be added at runtime.
createTypeAdapter(it, superClass, reverseAdapters)
}
is ObjCProtocolForKotlinInterface -> createTypeAdapter(it, superClass = null, reverseAdapters)
}
}
}
private fun generateTypeAdapters(spec: ObjCExportCodeSpec?) {
val objCTypeAdapters = mutableListOf<ObjCTypeAdapter>()
objCTypeAdapters += generateTypeAdaptersForKotlinTypes(spec)
spec?.files?.forEach {
objCTypeAdapters += createTypeAdapterForFileClass(it)
dataGenerator.emitEmptyClass(it.binaryName, namer.kotlinAnyName.binaryName)
}
emitTypeAdapters(objCTypeAdapters)
}
internal fun generate(spec: ObjCExportCodeSpec?) {
generateTypeAdapters(spec)
NSNumberKind.values().mapNotNull { it.mappedKotlinClassId }.forEach {
dataGenerator.exportClass(namer.numberBoxName(it).binaryName)
}
dataGenerator.exportClass(namer.mutableSetName.binaryName)
dataGenerator.exportClass(namer.mutableMapName.binaryName)
dataGenerator.exportClass(namer.kotlinAnyName.binaryName)
emitSpecialClassesConvertions()
// Replace runtime global with weak linkage:
codegen.replaceExternalWeakOrCommonGlobalFromNativeRuntime(
"Kotlin_ObjCInterop_uniquePrefix",
codegen.staticData.cStringLiteral(namer.topLevelNamePrefix)
)
emitSelectorsHolder()
emitKt42254Hint()
}
private fun emitTypeAdapters(objCTypeAdapters: List<ObjCTypeAdapter>) {
val placedClassAdapters = mutableMapOf<String, ConstPointer>()
val placedInterfaceAdapters = mutableMapOf<String, ConstPointer>()
objCTypeAdapters.forEach { adapter ->
val typeAdapter = staticData.placeGlobal("", adapter).pointer
val irClass = adapter.irClass
val descriptorToAdapter = if (irClass?.isInterface == true) {
placedInterfaceAdapters
} else {
// Objective-C class for Kotlin class or top-level declarations.
placedClassAdapters
}
descriptorToAdapter[adapter.objCName] = typeAdapter
if (irClass != null) {
if (!generationState.llvmModuleSpecification.importsKotlinDeclarationsFromOtherSharedLibraries()) {
setObjCExportTypeInfo(irClass, typeAdapter = typeAdapter)
} else {
// Optimization: avoid generating huge initializers;
// handled with "Kotlin_ObjCExport_initTypeAdapters" below.
}
}
}
fun emitSortedAdapters(nameToAdapter: Map<String, ConstPointer>, prefix: String) {
val sortedAdapters = nameToAdapter.toList().sortedBy { it.first }.map {
it.second
}
if (sortedAdapters.isNotEmpty()) {
val type = sortedAdapters.first().llvmType
val sortedAdaptersPointer = staticData.placeGlobalConstArray("", type, sortedAdapters)
// Note: this globals replace runtime globals with weak linkage:
codegen.replaceExternalWeakOrCommonGlobalFromNativeRuntime(prefix, sortedAdaptersPointer)
codegen.replaceExternalWeakOrCommonGlobalFromNativeRuntime("${prefix}Num", llvm.constInt32(sortedAdapters.size))
}
}
emitSortedAdapters(placedClassAdapters, "Kotlin_ObjCExport_sortedClassAdapters")
emitSortedAdapters(placedInterfaceAdapters, "Kotlin_ObjCExport_sortedProtocolAdapters")
if (generationState.llvmModuleSpecification.importsKotlinDeclarationsFromOtherSharedLibraries()) {
codegen.replaceExternalWeakOrCommonGlobalFromNativeRuntime(
"Kotlin_ObjCExport_initTypeAdapters",
llvm.constInt1(true)
)
}
}
private fun emitKt42254Hint() {
if (determineLinkerOutput(context) == LinkerOutputKind.STATIC_LIBRARY) {
// Might be affected by https://youtrack.jetbrains.com/issue/KT-42254.
// The code below generally follows [replaceExternalWeakOrCommonGlobal] implementation.
if (generationState.llvmModuleSpecification.importsKotlinDeclarationsFromOtherObjectFiles()) {
// So the compiler uses caches. If a user is linking two such static frameworks into a single binary,
// the linker might fail with a lot of "duplicate symbol" errors due to KT-42254.
// Adding a similar symbol that would explicitly hint to take a look at the YouTrack issue if reported.
// Note: for some reason this symbol is reported as the last one, which is good for its purpose.
val name = "See https://youtrack.jetbrains.com/issue/KT-42254"
val global = staticData.placeGlobal(name, llvm.constInt8(0), isExported = true)
llvm.usedGlobals += global.llvmGlobal
LLVMSetVisibility(global.llvmGlobal, LLVMVisibility.LLVMHiddenVisibility)
}
}
}
// TODO: consider including this into ObjCExportCodeSpec.
private val objCClassForAny = ObjCClassForKotlinClass(
namer.kotlinAnyName.binaryName,
symbols.any,
methods = listOf("equals", "hashCode", "toString").map { nameString ->
val name = Name.identifier(nameString)
val irFunction = symbols.any.owner.simpleFunctions().single { it.name == name }
val descriptor = context.builtIns.any.unsubstitutedMemberScope
.getContributedFunctions(name, NoLookupLocation.FROM_BACKEND).single()
val baseMethod = createObjCMethodSpecBaseMethod(mapper, namer, irFunction.symbol, descriptor)
ObjCMethodForKotlinMethod(baseMethod)
},
categoryMethods = emptyList(),
superClassNotAny = null
)
private fun emitSelectorsHolder() {
val impProto = LlvmFunctionSignature(LlvmRetType(llvm.voidType)).toProto(
name = "",
origin = null,
linkage = LLVMLinkage.LLVMInternalLinkage
)
val imp = generateFunctionNoRuntime(codegen, impProto) {
unreachable()
}
val methods = selectorsToDefine.map { (selector, bridge) ->
ObjCDataGenerator.Method(selector, getEncoding(bridge), imp.toConstPointer())
}
dataGenerator.emitClass(
"${namer.topLevelNamePrefix}KotlinSelectorsHolder",
superName = "NSObject",
instanceMethods = methods
)
}
private val impType = pointerType(functionType(llvm.voidType, false))
internal val directMethodAdapters = mutableMapOf<DirectAdapterRequest, ObjCToKotlinMethodAdapter>()
internal val exceptionTypeInfoArrays = mutableMapOf<IrFunction, ConstPointer>()
internal val typeInfoArrays = mutableMapOf<Set<IrClass>, ConstPointer>()
inner class ObjCToKotlinMethodAdapter(
selector: String,
encoding: String,
imp: ConstPointer
) : Struct(
runtime.objCToKotlinMethodAdapter,
staticData.cStringLiteral(selector),
staticData.cStringLiteral(encoding),
imp.bitcast(impType)
)
inner class KotlinToObjCMethodAdapter(
selector: String,
itablePlace: ClassLayoutBuilder.InterfaceTablePlace,
vtableIndex: Int,
kotlinImpl: ConstPointer
) : Struct(
runtime.kotlinToObjCMethodAdapter,
staticData.cStringLiteral(selector),
llvm.constInt32(itablePlace.interfaceId),
llvm.constInt32(itablePlace.itableSize),
llvm.constInt32(itablePlace.methodIndex),
llvm.constInt32(vtableIndex),
kotlinImpl
)
inner class ObjCTypeAdapter(
val irClass: IrClass?,
typeInfo: ConstPointer?,
vtable: ConstPointer?,
vtableSize: Int,
itable: List<RTTIGenerator.InterfaceTableRecord>,
itableSize: Int,
val objCName: String,
directAdapters: List<ObjCToKotlinMethodAdapter>,
classAdapters: List<ObjCToKotlinMethodAdapter>,
virtualAdapters: List<ObjCToKotlinMethodAdapter>,
reverseAdapters: List<KotlinToObjCMethodAdapter>
) : Struct(
runtime.objCTypeAdapter,
typeInfo,
vtable,
llvm.constInt32(vtableSize),
staticData.placeGlobalConstArray("", runtime.interfaceTableRecordType, itable),
llvm.constInt32(itableSize),
staticData.cStringLiteral(objCName),
staticData.placeGlobalConstArray(
"",
runtime.objCToKotlinMethodAdapter,
directAdapters
),
llvm.constInt32(directAdapters.size),
staticData.placeGlobalConstArray(
"",
runtime.objCToKotlinMethodAdapter,
classAdapters
),
llvm.constInt32(classAdapters.size),
staticData.placeGlobalConstArray(
"",
runtime.objCToKotlinMethodAdapter,
virtualAdapters
),
llvm.constInt32(virtualAdapters.size),
staticData.placeGlobalConstArray(
"",
runtime.kotlinToObjCMethodAdapter,
reverseAdapters
),
llvm.constInt32(reverseAdapters.size)
)
}
private fun ObjCExportCodeGenerator.setObjCExportTypeInfo(
irClass: IrClass,
convertToRetained: ConstPointer? = null,
objCClass: ConstPointer? = null,
typeAdapter: ConstPointer? = null
) {
val writableTypeInfoValue = buildWritableTypeInfoValue(
convertToRetained = convertToRetained,
objCClass = objCClass,
typeAdapter = typeAdapter
)
if (codegen.isExternal(irClass)) {
// Note: this global replaces the external one with common linkage.
codegen.replaceExternalWeakOrCommonGlobal(
irClass.writableTypeInfoSymbolName,
writableTypeInfoValue,
irClass
)
} else {
setOwnWritableTypeInfo(irClass, writableTypeInfoValue)
}
}
private fun ObjCExportCodeGeneratorBase.setOwnWritableTypeInfo(irClass: IrClass, writableTypeInfoValue: Struct) {
require(!codegen.isExternal(irClass))
val writeableTypeInfoGlobal = generationState.llvmDeclarations.forClass(irClass).writableTypeInfoGlobal!!
writeableTypeInfoGlobal.setLinkage(LLVMLinkage.LLVMExternalLinkage)
writeableTypeInfoGlobal.setInitializer(writableTypeInfoValue)
}
private fun ObjCExportCodeGeneratorBase.buildWritableTypeInfoValue(
convertToRetained: ConstPointer? = null,
objCClass: ConstPointer? = null,
typeAdapter: ConstPointer? = null
): Struct {
if (convertToRetained != null) {
val expectedType = pointerType(functionType(llvm.int8PtrType, false, codegen.kObjHeaderPtr))
assert(convertToRetained.llvmType == expectedType) {
"Expected: ${LLVMPrintTypeToString(expectedType)!!.toKString()} " +
"found: ${LLVMPrintTypeToString(convertToRetained.llvmType)!!.toKString()}"
}
}
val objCExportAddition = Struct(runtime.typeInfoObjCExportAddition,
convertToRetained?.bitcast(llvm.int8PtrType),
objCClass,
typeAdapter
)
val writableTypeInfoType = runtime.writableTypeInfoType!!
return Struct(writableTypeInfoType, objCExportAddition)
}
private val ObjCExportCodeGenerator.kotlinToObjCFunctionType: LlvmFunctionSignature
get() = LlvmFunctionSignature(LlvmRetType(llvm.int8PtrType), listOf(LlvmParamType(codegen.kObjHeaderPtr)), isVararg = false)
private val ObjCExportCodeGeneratorBase.objCToKotlinFunctionType: LLVMTypeRef
get() = functionType(codegen.kObjHeaderPtr, false, llvm.int8PtrType, codegen.kObjHeaderPtrPtr)
private fun ObjCExportCodeGenerator.emitBoxConverters() {
val irBuiltIns = context.irBuiltIns
emitBoxConverter(irBuiltIns.booleanClass, ObjCValueType.BOOL, "initWithBool:")
emitBoxConverter(irBuiltIns.byteClass, ObjCValueType.CHAR, "initWithChar:")
emitBoxConverter(irBuiltIns.shortClass, ObjCValueType.SHORT, "initWithShort:")
emitBoxConverter(irBuiltIns.intClass, ObjCValueType.INT, "initWithInt:")
emitBoxConverter(irBuiltIns.longClass, ObjCValueType.LONG_LONG, "initWithLongLong:")
emitBoxConverter(symbols.uByte!!, ObjCValueType.UNSIGNED_CHAR, "initWithUnsignedChar:")
emitBoxConverter(symbols.uShort!!, ObjCValueType.UNSIGNED_SHORT, "initWithUnsignedShort:")
emitBoxConverter(symbols.uInt!!, ObjCValueType.UNSIGNED_INT, "initWithUnsignedInt:")
emitBoxConverter(symbols.uLong!!, ObjCValueType.UNSIGNED_LONG_LONG, "initWithUnsignedLongLong:")
emitBoxConverter(irBuiltIns.floatClass, ObjCValueType.FLOAT, "initWithFloat:")
emitBoxConverter(irBuiltIns.doubleClass, ObjCValueType.DOUBLE, "initWithDouble:")
}
private fun ObjCExportCodeGenerator.emitBoxConverter(
boxClassSymbol: IrClassSymbol,
objCValueType: ObjCValueType,
nsNumberInitSelector: String
) {
val boxClass = boxClassSymbol.owner
val name = "${boxClass.name}ToNSNumber"
val converter = functionGenerator(kotlinToObjCFunctionType.toProto(name, null, LLVMLinkage.LLVMPrivateLinkage)).generate {
val unboxFunction = context.getUnboxFunction(boxClass).llvmFunction
val kotlinValue = callFromBridge(
unboxFunction,
listOf(param(0)),
Lifetime.IRRELEVANT
)
val value = kotlinToObjC(kotlinValue, objCValueType)
val valueParameterTypes: List<LlvmParamType> = listOf(
LlvmParamType(value.type, objCValueType.defaultParameterAttributes)
)
val nsNumberSubclass = genGetLinkedClass(namer.numberBoxName(boxClass.classId!!).binaryName)
// We consider this function fast enough, so don't switch thread state to Native.
val instance = callFromBridge(objcAlloc, listOf(nsNumberSubclass))
val returnType = LlvmRetType(llvm.int8PtrType)
// We consider these methods fast enough, so don't switch thread state to Native.
ret(genSendMessage(returnType, valueParameterTypes, instance, nsNumberInitSelector, value))
}
setObjCExportTypeInfo(boxClass, converter.toConstPointer())
}
private fun ObjCExportCodeGenerator.generateContinuationToRetainedCompletionConverter(
blockGenerator: BlockGenerator
): LlvmCallable = with(blockGenerator) {
generateWrapKotlinObjectToRetainedBlock(
BlockType(numberOfParameters = 2, returnsVoid = true),
convertName = "convertContinuation",
invokeName = "invokeCompletion"
) { continuation, arguments ->
check(arguments.size == 2)
val resultArgument = objCReferenceToKotlin(arguments[0], Lifetime.ARGUMENT)
val errorArgument = arguments[1]
callFromBridge(llvm.Kotlin_ObjCExport_resumeContinuation, listOf(continuation, resultArgument, errorArgument))
ret(null)
}
}
private fun ObjCExportCodeGenerator.generateUnitContinuationToRetainedCompletionConverter(
blockGenerator: BlockGenerator
): LlvmCallable = with(blockGenerator) {
generateWrapKotlinObjectToRetainedBlock(
BlockType(numberOfParameters = 1, returnsVoid = true),
convertName = "convertUnitContinuation",
invokeName = "invokeUnitCompletion"
) { continuation, arguments ->
check(arguments.size == 1)
val errorArgument = arguments[0]
val resultArgument = ifThenElse(icmpNe(errorArgument, llvm.kNullInt8Ptr), kNullObjHeaderPtr) {
codegen.theUnitInstanceRef.llvm
}
callFromBridge(llvm.Kotlin_ObjCExport_resumeContinuation, listOf(continuation, resultArgument, errorArgument))
ret(null)
}
}
// TODO: find out what to use instead here and in the dependent code
@OptIn(ObsoleteDescriptorBasedAPI::class)
private val ObjCExportBlockCodeGenerator.mappedFunctionNClasses get() =
// failed attempt to migrate to descriptor-less IrBuiltIns
((context.irBuiltIns as IrBuiltInsOverDescriptors).functionFactory as BuiltInFictitiousFunctionIrClassFactory).builtFunctionNClasses
.filter { it.descriptor.isMappedFunctionClass() }
private fun ObjCExportBlockCodeGenerator.emitFunctionConverters() {
require(generationState.shouldDefineFunctionClasses)
mappedFunctionNClasses.forEach { functionClass ->
val convertToRetained = kotlinFunctionToRetainedBlockConverter(BlockPointerBridge(functionClass.arity, returnsVoid = false))
val writableTypeInfoValue = buildWritableTypeInfoValue(convertToRetained = convertToRetained.toConstPointer())
setOwnWritableTypeInfo(functionClass.irClass, writableTypeInfoValue)
}
}
private fun ObjCExportBlockCodeGenerator.emitBlockToKotlinFunctionConverters() {
require(generationState.shouldDefineFunctionClasses)
val functionClassesByArity = mappedFunctionNClasses.associateBy { it.arity }
val arityLimit = (functionClassesByArity.keys.maxOrNull() ?: -1) + 1
val converters = (0 until arityLimit).map { arity ->
functionClassesByArity[arity]?.let {
val bridge = BlockPointerBridge(numberOfParameters = arity, returnsVoid = false)
blockToKotlinFunctionConverter(bridge).toConstPointer()
} ?: NullPointer(objCToKotlinFunctionType)
}
val type = pointerType(objCToKotlinFunctionType)
val ptr = staticData.placeGlobalArray(
"",
type,
converters
).pointer.getElementPtr(llvm, LLVMArrayType(type, converters.size)!!, 0)
// Note: defining globals declared in runtime.
staticData.placeGlobal("Kotlin_ObjCExport_blockToFunctionConverters", ptr, isExported = true)
staticData.placeGlobal("Kotlin_ObjCExport_blockToFunctionConverters_size", llvm.constInt32(arityLimit), isExported = true)
}
private fun ObjCExportCodeGenerator.emitSpecialClassesConvertions() {
setObjCExportTypeInfo(
symbols.string.owner,
llvm.Kotlin_ObjCExport_CreateRetainedNSStringFromKString.toConstPointer()
)
emitCollectionConverters()
emitBoxConverters()
}
private fun ObjCExportCodeGenerator.emitCollectionConverters() {
fun importConverter(name: String): ConstPointer =
llvm.externalNativeRuntimeFunction(name, kotlinToObjCFunctionType).toConstPointer()
setObjCExportTypeInfo(
symbols.list.owner,
importConverter("Kotlin_Interop_CreateRetainedNSArrayFromKList")
)
setObjCExportTypeInfo(
symbols.mutableList.owner,
importConverter("Kotlin_Interop_CreateRetainedNSMutableArrayFromKList")
)
setObjCExportTypeInfo(
symbols.set.owner,
importConverter("Kotlin_Interop_CreateRetainedNSSetFromKSet")
)
setObjCExportTypeInfo(
symbols.mutableSet.owner,
importConverter("Kotlin_Interop_CreateRetainedKotlinMutableSetFromKSet")
)
setObjCExportTypeInfo(
symbols.map.owner,
importConverter("Kotlin_Interop_CreateRetainedNSDictionaryFromKMap")
)
setObjCExportTypeInfo(
symbols.mutableMap.owner,
importConverter("Kotlin_Interop_CreateRetainedKotlinMutableDictionaryFromKMap")
)
}
private fun ObjCExportFunctionGenerationContextBuilder.setupBridgeDebugInfo() {
val location = setupBridgeDebugInfo(this.objCExportCodegen.generationState, function)
startLocation = location
endLocation = location
}
private inline fun ObjCExportCodeGenerator.generateObjCImpBy(
methodBridge: MethodBridge,
debugInfo: Boolean = false,
suffix: String,
genBody: ObjCExportFunctionGenerationContext.() -> Unit
): LlvmCallable {
val functionType = objCFunctionType(generationState, methodBridge)
val functionName = "objc2kotlin_$suffix"
val result = functionGenerator(functionType.toProto(functionName, null, LLVMLinkage.LLVMInternalLinkage)) {
if (debugInfo) {
this.setupBridgeDebugInfo()
}
switchToRunnable = true
}.generate {
genBody()
}
return result
}
private fun ObjCExportCodeGenerator.generateAbstractObjCImp(methodBridge: MethodBridge, baseMethod: IrFunction): LlvmCallable =
generateObjCImpBy(methodBridge, suffix = baseMethod.computeSymbolName()) {
callFromBridge(
llvm.Kotlin_ObjCExport_AbstractMethodCalled,
listOf(param(0), param(1))
)
unreachable()
}
private fun ObjCExportCodeGenerator.generateObjCImp(
target: IrFunction?,
baseMethod: IrFunction,
methodBridge: MethodBridge,
isVirtual: Boolean = false,
customBridgeSuffix: String? = null,
) = if (target == null) {
generateAbstractObjCImp(methodBridge, baseMethod)
} else {
generateObjCImp(
methodBridge,
isDirect = !isVirtual,
baseMethod = baseMethod,
bridgeSuffix = customBridgeSuffix ?: ((if (isVirtual) "virtual_" else "") + target.computeSymbolName())
) { args, resultLifetime, exceptionHandler ->
if (target is IrConstructor && target.constructedClass.isAbstract()) {
callFromBridge(
llvm.Kotlin_ObjCExport_AbstractClassConstructorCalled,
listOf(param(0), codegen.typeInfoValue(target.parent as IrClass))
)
}
val llvmCallable = if (isVirtual) {
codegen.getVirtualFunctionTrampoline(target as IrSimpleFunction)
} else {
codegen.llvmFunction(target)
}
call(llvmCallable, args, resultLifetime, exceptionHandler)
}
}
private fun ObjCExportCodeGenerator.generateObjCImp(
methodBridge: MethodBridge,
isDirect: Boolean,
baseMethod: IrFunction? = null,
bridgeSuffix: String,
callKotlin: ObjCExportFunctionGenerationContext.(
args: List<LLVMValueRef>,
resultLifetime: Lifetime,
exceptionHandler: ExceptionHandler
) -> LLVMValueRef?
): LlvmCallable = generateObjCImpBy(
methodBridge,
debugInfo = isDirect /* see below */,
suffix = bridgeSuffix,
) {
// Considering direct calls inlinable above. If such a call is inlined into a bridge with no debug information,
// lldb will not decode the inlined frame even if the callee has debug information.
// So generate dummy debug information for bridge in this case.
// TODO: consider adding debug info to other bridges.
val returnType = methodBridge.returnBridge
// TODO: call [NSObject init] if it is a constructor?
// TODO: check for abstract class if it is a constructor.
if (!methodBridge.isInstance) {
initRuntimeIfNeeded() // For instance methods it gets called when allocating.
}
var errorOutPtr: LLVMValueRef? = null
var continuation: LLVMValueRef? = null
val kotlinArgs = methodBridge.paramBridges.mapIndexedNotNull { index, paramBridge ->
val parameter = param(index)
when (paramBridge) {
is MethodBridgeValueParameter.Mapped ->
objCToKotlin(parameter, paramBridge.bridge, Lifetime.ARGUMENT)
MethodBridgeReceiver.Static, MethodBridgeSelector -> null
MethodBridgeReceiver.Instance -> objCReferenceToKotlin(parameter, Lifetime.ARGUMENT)
MethodBridgeReceiver.Factory -> null // actual value added by [callKotlin].
MethodBridgeValueParameter.ErrorOutParameter -> {
assert(errorOutPtr == null)
errorOutPtr = parameter
null
}
is MethodBridgeValueParameter.SuspendCompletion -> {
val createContinuationArgument = if (paramBridge.useUnitCompletion) {
llvm.Kotlin_ObjCExport_createUnitContinuationArgument
} else {
llvm.Kotlin_ObjCExport_createContinuationArgument
}
callFromBridge(
createContinuationArgument,
listOf(parameter, generateExceptionTypeInfoArray(baseMethod!!)),
Lifetime.ARGUMENT
).also {
continuation = it
}
}
}
}
// TODO: consider merging this handler with function cleanup.
val exceptionHandler = when {
errorOutPtr != null -> kotlinExceptionHandler { exception ->
callFromBridge(
llvm.Kotlin_ObjCExport_RethrowExceptionAsNSError,
listOf(exception, errorOutPtr!!, generateExceptionTypeInfoArray(baseMethod!!))
)
val returnValue = when (returnType) {
!is MethodBridge.ReturnValue.WithError ->
error("bridge with error parameter has unexpected return type: $returnType")
MethodBridge.ReturnValue.WithError.Success -> llvm.int8(0) // false
is MethodBridge.ReturnValue.WithError.ZeroForError -> {
if (returnType.successBridge == MethodBridge.ReturnValue.Instance.InitResult) {
// Release init receiver, as required by convention.
objcReleaseFromRunnableThreadState(param(0))
}
Zero(returnType.toLlvmRetType(generationState).llvmType).llvm
}
}
ret(returnValue)
}
continuation != null -> kotlinExceptionHandler { exception ->
// Callee haven't suspended, so it isn't going to call the completion. Call it here:
callFromBridge(
context.ir.symbols.objCExportResumeContinuationWithException.owner.llvmFunction,
listOf(continuation!!, exception)
)
// Note: completion block could be called directly instead, but this implementation is
// simpler and avoids duplication.
ret(null)
}
else -> kotlinExceptionHandler { exception ->
callFromBridge(symbols.objCExportTrapOnUndeclaredException.owner.llvmFunction, listOf(exception))
unreachable()
}
}
val targetResult = callKotlin(kotlinArgs, Lifetime.ARGUMENT, exceptionHandler)
tailrec fun genReturnOnSuccess(returnBridge: MethodBridge.ReturnValue) {
val returnValue: LLVMValueRef? = when (returnBridge) {
MethodBridge.ReturnValue.Void -> null
MethodBridge.ReturnValue.HashCode -> {
val kotlinHashCode = targetResult!!
if (generationState.is64BitNSInteger()) zext(kotlinHashCode, llvm.int64Type) else kotlinHashCode
}
is MethodBridge.ReturnValue.Mapped -> if (LLVMTypeOf(targetResult!!) == llvm.voidType) {
returnBridge.bridge.makeNothing(llvm)
} else {
when (val bridge = returnBridge.bridge) {
is ReferenceBridge -> return autoreleaseAndRet(kotlinReferenceToRetainedObjC(targetResult))
is BlockPointerBridge -> return autoreleaseAndRet(kotlinFunctionToRetainedObjCBlockPointer(bridge, targetResult))
is ValueTypeBridge -> kotlinToObjC(targetResult, bridge.objCValueType)
}
}
MethodBridge.ReturnValue.WithError.Success -> llvm.int8(1) // true
is MethodBridge.ReturnValue.WithError.ZeroForError -> return genReturnOnSuccess(returnBridge.successBridge)
MethodBridge.ReturnValue.Instance.InitResult -> param(0)
MethodBridge.ReturnValue.Instance.FactoryResult -> return autoreleaseAndRet(kotlinReferenceToRetainedObjC(targetResult!!)) // provided by [callKotlin]
MethodBridge.ReturnValue.Suspend -> {
val coroutineSuspended = callFromBridge(
codegen.llvmFunction(context.ir.symbols.objCExportGetCoroutineSuspended.owner),
emptyList(),
Lifetime.STACK
)
ifThen(icmpNe(targetResult!!, coroutineSuspended)) {
// Callee haven't suspended, so it isn't going to call the completion. Call it here:
callFromBridge(
context.ir.symbols.objCExportResumeContinuation.owner.llvmFunction,
listOf(continuation!!, targetResult)
)
// Note: completion block could be called directly instead, but this implementation is
// simpler and avoids duplication.
}
null
}
}
// Note: some branches above don't reach here, because emit their own optimized return code.
ret(returnValue)
}
genReturnOnSuccess(returnType)
}
private fun ObjCExportCodeGenerator.generateExceptionTypeInfoArray(baseMethod: IrFunction): LLVMValueRef =
exceptionTypeInfoArrays.getOrPut(baseMethod) {
val types = effectiveThrowsClasses(baseMethod, symbols)
generateTypeInfoArray(types.toSet())
}.llvm
private fun ObjCExportCodeGenerator.generateTypeInfoArray(types: Set<IrClass>): ConstPointer =
typeInfoArrays.getOrPut(types) {
val typeInfos = types.map { with(codegen) { it.typeInfoPtr } } + NullPointer(codegen.kTypeInfo)
codegen.staticData.placeGlobalConstArray("", codegen.kTypeInfoPtr, typeInfos)
}
private fun ObjCExportCodeGenerator.effectiveThrowsClasses(method: IrFunction, symbols: KonanSymbols): List<IrClass> {
if (method is IrSimpleFunction && method.overriddenSymbols.isNotEmpty()) {
return effectiveThrowsClasses(method.overriddenSymbols.first().owner, symbols)
}
val throwsAnnotation = method.annotations.findAnnotation(KonanFqNames.throws)
?: return if (method is IrSimpleFunction && method.origin == IrDeclarationOrigin.LOWERED_SUSPEND_FUNCTION) {
listOf(symbols.cancellationException.owner)
} else {
// Note: frontend ensures that all topmost overridden methods have (equal) @Throws annotations.
// However due to linking different versions of libraries IR could end up not meeting this condition.
// Handling missing annotation gracefully:
emptyList()
}
val throwsVararg = throwsAnnotation.getValueArgument(0)
?: return emptyList()
if (throwsVararg !is IrVararg) error(method.fileOrNull, throwsVararg, "unexpected vararg")
return throwsVararg.elements.map {
(it as? IrClassReference)?.symbol?.owner as? IrClass
?: error(method.fileOrNull, it, "unexpected @Throws argument")
}
}
private fun ObjCExportCodeGenerator.generateObjCImpForArrayConstructor(
target: IrConstructor,
methodBridge: MethodBridge
): LlvmCallable = generateObjCImp(methodBridge, bridgeSuffix = target.computeSymbolName(), isDirect = true) { args, resultLifetime, exceptionHandler ->
val arrayInstance = callFromBridge(
llvm.allocArrayFunction,
listOf(target.constructedClass.llvmTypeInfoPtr, args.first()),
resultLifetime = Lifetime.ARGUMENT
)
call(target.llvmFunction, listOf(arrayInstance) + args, resultLifetime, exceptionHandler)
arrayInstance
}
// TODO: cache bridges.
private fun ObjCExportCodeGenerator.generateKotlinToObjCBridge(
irFunction: IrFunction,
baseMethod: ObjCMethodSpec.BaseMethod<IrSimpleFunctionSymbol>
): ConstPointer {
val baseIrFunction = baseMethod.owner
val methodBridge = baseMethod.bridge
val parameterToBase = irFunction.allParameters.zip(baseIrFunction.allParameters).toMap()
val functionType = LlvmFunctionSignature(irFunction, codegen)
val functionName = "kotlin2objc_${baseIrFunction.computeSymbolName()}"
val result = functionGenerator(functionType.toProto(functionName, null, LLVMLinkage.LLVMInternalLinkage)).generate {
var errorOutPtr: LLVMValueRef? = null
val parameters = irFunction.allParameters.mapIndexed { index, parameterDescriptor ->
parameterDescriptor to param(index)
}.toMap()
val objCReferenceArgsToRelease = mutableListOf<LLVMValueRef>()
val objCArgs = methodBridge.parametersAssociated(irFunction).map { (bridge, parameter) ->
when (bridge) {
is MethodBridgeValueParameter.Mapped -> {
parameter!!
val kotlinValue = convertKotlin(
{ parameters[parameter]!! },
actualType = parameter.type,
expectedType = parameterToBase[parameter]!!.type,
resultLifetime = Lifetime.ARGUMENT
)
if (LLVMTypeOf(kotlinValue) == llvm.voidType) {
bridge.bridge.makeNothing(llvm)
} else {
when (val typeBridge = bridge.bridge) {
is ReferenceBridge -> kotlinReferenceToRetainedObjC(kotlinValue).also { objCReferenceArgsToRelease += it }
is BlockPointerBridge -> kotlinFunctionToRetainedObjCBlockPointer(typeBridge, kotlinValue) // TODO: use stack-allocated block here.
.also { objCReferenceArgsToRelease += it }
is ValueTypeBridge -> kotlinToObjC(kotlinValue, typeBridge.objCValueType)
}
}
}
MethodBridgeReceiver.Instance -> {
// `kotlinReferenceToLocalObjC` can add the result to autoreleasepool in some cases. But not here.
// Because this `parameter` is the receiver of a bridge in an Obj-C/Swift class extending
// Kotlin class or interface.
// So `kotlinReferenceToLocalObjC` here just unwraps the Obj-C reference
// without using autoreleasepool or any other reference counting operations.
kotlinReferenceToLocalObjC(parameters[parameter]!!)
}
MethodBridgeSelector -> {
val selector = baseMethod.selector
// Selector is referenced thus should be defined to avoid false positive non-public API rejection:
selectorsToDefine[selector] = methodBridge
genSelector(selector)
}
MethodBridgeReceiver.Static,
MethodBridgeReceiver.Factory ->
error("Method is not instance and thus can't have bridge for overriding: $baseMethod")
MethodBridgeValueParameter.ErrorOutParameter ->
alloca(llvm.int8PtrType).also {
store(llvm.kNullInt8Ptr, it)
errorOutPtr = it
}
is MethodBridgeValueParameter.SuspendCompletion -> {
require(!irFunction.isSuspend) { "Suspend function should be lowered out at this point" }
parameter!!
val continuation = convertKotlin(
{ parameters[parameter]!! },
actualType = parameter.type,
expectedType = parameterToBase[parameter]!!.type,
resultLifetime = Lifetime.ARGUMENT
)
// TODO: consider placing interception into the converter to reduce code size.
val intercepted = callFromBridge(
context.ir.symbols.objCExportInterceptedContinuation.owner.llvmFunction,
listOf(continuation),
Lifetime.ARGUMENT
)
// TODO: use stack-allocated block here instead.
val converter = if (bridge.useUnitCompletion) {
unitContinuationToRetainedCompletionConverter
} else {
continuationToRetainedCompletionConverter
}
callFromBridge(converter, listOf(intercepted))
.also { objCReferenceArgsToRelease += it }
}
}
}
switchThreadStateIfExperimentalMM(ThreadState.Native)
val retainAutoreleasedTargetResult = methodBridge.returnBridge.isAutoreleasedObjCReference()
val objCFunctionType = objCFunctionType(generationState, methodBridge)
val objcMsgSend = msgSender(objCFunctionType)
// Using terminatingExceptionHandler, so any exception thrown by the method will lead to the termination,
// and switching the thread state back to `Runnable` on exceptional path is not required.
val targetResult = callAndMaybeRetainAutoreleased(
objcMsgSend,
objCFunctionType,
objCArgs,
exceptionHandler = terminatingExceptionHandler,
doRetain = retainAutoreleasedTargetResult
)
objCReferenceArgsToRelease.forEach {
objcReleaseFromNativeThreadState(it)
}
switchThreadStateIfExperimentalMM(ThreadState.Runnable)
assert(baseMethod.symbol !is IrConstructorSymbol)
fun rethrow() {
val error = load(llvm.int8PtrType, errorOutPtr!!)
val exception = callFromBridge(
llvm.Kotlin_ObjCExport_NSErrorAsException,
listOf(error),
resultLifetime = Lifetime.THROW
)
ExceptionHandler.Caller.genThrow(this, exception)
}
fun genKotlinBaseMethodResult(
lifetime: Lifetime,
returnBridge: MethodBridge.ReturnValue
): LLVMValueRef? = when (returnBridge) {
MethodBridge.ReturnValue.Void -> null
MethodBridge.ReturnValue.HashCode -> {
if (generationState.is64BitNSInteger()) {
val low = trunc(targetResult, llvm.int32Type)
val high = trunc(shr(targetResult, 32, signed = false), llvm.int32Type)
xor(low, high)
} else {
targetResult
}
}
is MethodBridge.ReturnValue.Mapped -> {
objCToKotlin(targetResult, returnBridge.bridge, lifetime)
}
MethodBridge.ReturnValue.WithError.Success -> {
ifThen(icmpEq(targetResult, llvm.int8(0))) {
check(!retainAutoreleasedTargetResult)
rethrow()
}
null
}
is MethodBridge.ReturnValue.WithError.ZeroForError -> {
if (returnBridge.successMayBeZero) {
val error = load(llvm.int8PtrType, errorOutPtr!!)
ifThen(icmpNe(error, llvm.kNullInt8Ptr)) {
// error is not null, so targetResult should be null => no need for objc_release on it.
rethrow()
}
} else {
ifThen(icmpEq(targetResult, llvm.kNullInt8Ptr)) {
// targetResult is null => no need for objc_release on it.
rethrow()
}
}
genKotlinBaseMethodResult(lifetime, returnBridge.successBridge)
}
MethodBridge.ReturnValue.Instance.InitResult,
MethodBridge.ReturnValue.Instance.FactoryResult ->
error("init or factory method can't have bridge for overriding: $baseMethod")
MethodBridge.ReturnValue.Suspend -> {
// Objective-C implementation of Kotlin suspend function is always responsible
// for calling the completion, so in Kotlin coroutines machinery terms it suspends,
// which is indicated by the return value:
callFromBridge(
context.ir.symbols.objCExportGetCoroutineSuspended.owner.llvmFunction,
emptyList(),
Lifetime.RETURN_VALUE
)
}
}
val baseReturnType = baseIrFunction.returnType
val actualReturnType = irFunction.returnType
val retVal = when {
actualReturnType.isUnit() || actualReturnType.isNothing() -> {
genKotlinBaseMethodResult(Lifetime.ARGUMENT, methodBridge.returnBridge)
null
}
baseReturnType.isUnit() || baseReturnType.isNothing() -> {
genKotlinBaseMethodResult(Lifetime.ARGUMENT, methodBridge.returnBridge)
codegen.theUnitInstanceRef.llvm
}
else ->
convertKotlin(
{ lifetime -> genKotlinBaseMethodResult(lifetime, methodBridge.returnBridge)!! },
actualType = baseReturnType,
expectedType = actualReturnType,
resultLifetime = Lifetime.RETURN_VALUE
)
}
if (retainAutoreleasedTargetResult) {
// TODO: in some cases the return sequence will have redundant retain-release pair:
// retain in the return value conversion and release here.
// We could implement an optimized objCRetainedReferenceToKotlin, which takes ownership
// of its argument (i.e. consumes retained reference).
objcReleaseFromRunnableThreadState(targetResult)
}
ret(retVal)
}
return result.toConstPointer()
}
private fun MethodBridge.ReturnValue.isAutoreleasedObjCReference(): Boolean = when (this) {
MethodBridge.ReturnValue.HashCode, // integer
MethodBridge.ReturnValue.Instance.FactoryResult, // retained
MethodBridge.ReturnValue.Instance.InitResult, // retained
MethodBridge.ReturnValue.Suspend, // void
MethodBridge.ReturnValue.WithError.Success, // boolean
MethodBridge.ReturnValue.Void -> false
is MethodBridge.ReturnValue.Mapped -> when (this.bridge) {
is BlockPointerBridge, ReferenceBridge -> true
is ValueTypeBridge -> false
}
is MethodBridge.ReturnValue.WithError.ZeroForError -> this.successBridge.isAutoreleasedObjCReference()
}
/**
* Reverse adapters are required when Kotlin code invokes virtual method which might be overriden on Objective-C side.
* Example:
*
* ```kotlin
* interface I {
* fun foo()
* }
*
* fun usage(i: I) {
* i.foo() // Here we invoke
* }
* ```
*
* ```swift
* class C : I {
* override func foo() { ... }
* }
*
* FileKt.usage(C()) // C.foo is invoked via reverse method adapter.
* ```
*/
private fun ObjCExportCodeGenerator.createReverseAdapter(
irFunction: IrFunction,
baseMethod: ObjCMethodSpec.BaseMethod<IrSimpleFunctionSymbol>,
vtableIndex: Int?,
itablePlace: ClassLayoutBuilder.InterfaceTablePlace?
): ObjCExportCodeGenerator.KotlinToObjCMethodAdapter {
val selector = baseMethod.selector
val kotlinToObjC = generateKotlinToObjCBridge(
irFunction,
baseMethod
).bitcast(llvm.int8PtrType)
return KotlinToObjCMethodAdapter(selector,
itablePlace ?: ClassLayoutBuilder.InterfaceTablePlace.INVALID,
vtableIndex ?: -1,
kotlinToObjC)
}
/**
* We need to generate indirect version of a method for a cases
* when it is called on an object of non-exported type.
*
* Consider the following example:
* file.kt:
* ```
* open class Foo {
* open fun foo() {}
* }
* private class Bar : Foo() {
* override fun foo() {}
* }
*
* fun createBar(): Foo = Bar()
* ```
* file.swift:
* ```
* FileKt.createBar().foo()
* ```
* There is no Objective-C typeinfo for `Bar`, thus `foo` will be called via method lookup.
*/
private fun ObjCExportCodeGenerator.createMethodVirtualAdapter(
baseMethod: ObjCMethodSpec.BaseMethod<IrSimpleFunctionSymbol>
): ObjCExportCodeGenerator.ObjCToKotlinMethodAdapter {
val selector = baseMethod.selector
val methodBridge = baseMethod.bridge
val irFunction = baseMethod.owner
val imp = generateObjCImp(irFunction, irFunction, methodBridge, isVirtual = true)
return objCToKotlinMethodAdapter(selector, methodBridge, imp)
}
private fun ObjCExportCodeGenerator.createMethodAdapter(
implementation: IrFunction?,
baseMethod: ObjCMethodSpec.BaseMethod<*>
) = createMethodAdapter(DirectAdapterRequest(implementation, baseMethod))
private fun ObjCExportCodeGenerator.createFinalMethodAdapter(
baseMethod: ObjCMethodSpec.BaseMethod<IrSimpleFunctionSymbol>
): ObjCExportCodeGenerator.ObjCToKotlinMethodAdapter {
val irFunction = baseMethod.owner
require(irFunction.modality == Modality.FINAL)
return createMethodAdapter(irFunction, baseMethod)
}
private fun ObjCExportCodeGenerator.createMethodAdapter(
request: DirectAdapterRequest
): ObjCExportCodeGenerator.ObjCToKotlinMethodAdapter = this.directMethodAdapters.getOrPut(request) {
val selectorName = request.base.selector
val methodBridge = request.base.bridge
val imp = generateObjCImp(request.implementation, request.base.owner, methodBridge)
objCToKotlinMethodAdapter(selectorName, methodBridge, imp)
}
private fun ObjCExportCodeGenerator.createConstructorAdapter(
baseMethod: ObjCMethodSpec.BaseMethod<IrConstructorSymbol>
): ObjCExportCodeGenerator.ObjCToKotlinMethodAdapter = createMethodAdapter(baseMethod.owner, baseMethod)
private fun ObjCExportCodeGenerator.createArrayConstructorAdapter(
baseMethod: ObjCMethodSpec.BaseMethod<IrConstructorSymbol>
): ObjCExportCodeGenerator.ObjCToKotlinMethodAdapter {
val selectorName = baseMethod.selector
val methodBridge = baseMethod.bridge
val irConstructor = baseMethod.owner
val imp = generateObjCImpForArrayConstructor(irConstructor, methodBridge)
return objCToKotlinMethodAdapter(selectorName, methodBridge, imp)
}
private fun ObjCExportCodeGenerator.vtableIndex(irFunction: IrSimpleFunction): Int? {
assert(irFunction.isOverridable)
val irClass = irFunction.parentAsClass
return if (irClass.isInterface) {
null
} else {
context.getLayoutBuilder(irClass).vtableIndex(irFunction)
}
}
private fun ObjCExportCodeGenerator.itablePlace(irFunction: IrSimpleFunction): ClassLayoutBuilder.InterfaceTablePlace? {
assert(irFunction.isOverridable)
val irClass = irFunction.parentAsClass
return if (irClass.isInterface
&& (irFunction.isReal || irFunction.resolveFakeOverrideMaybeAbstract()?.parent != context.irBuiltIns.anyClass.owner)
) {
context.getLayoutBuilder(irClass).itablePlace(irFunction)
} else {
null
}
}
private fun ObjCExportCodeGenerator.createTypeAdapterForFileClass(
fileClass: ObjCClassForKotlinFile
): ObjCExportCodeGenerator.ObjCTypeAdapter {
val name = fileClass.binaryName
val adapters = fileClass.methods.map { createFinalMethodAdapter(it.baseMethod) }
return ObjCTypeAdapter(
irClass = null,
typeInfo = null,
vtable = null,
vtableSize = -1,
itable = emptyList(),
itableSize = -1,
objCName = name,
directAdapters = emptyList(),
classAdapters = adapters,
virtualAdapters = emptyList(),
reverseAdapters = emptyList()
)
}
private fun ObjCExportCodeGenerator.createTypeAdapter(
type: ObjCTypeForKotlinType,
superClass: ObjCClassForKotlinClass?,
reverseAdapters: List<ObjCExportCodeGenerator.KotlinToObjCMethodAdapter>
): ObjCExportCodeGenerator.ObjCTypeAdapter {
val irClass = type.irClassSymbol.owner
val adapters = mutableListOf<ObjCExportCodeGenerator.ObjCToKotlinMethodAdapter>()
val classAdapters = mutableListOf<ObjCExportCodeGenerator.ObjCToKotlinMethodAdapter>()
type.methods.forEach {
when (it) {
is ObjCInitMethodForKotlinConstructor -> {
adapters += createConstructorAdapter(it.baseMethod)
}
is ObjCFactoryMethodForKotlinArrayConstructor -> {
classAdapters += createArrayConstructorAdapter(it.baseMethod)
}
is ObjCGetterForKotlinEnumEntry -> {
classAdapters += createEnumEntryAdapter(it.irEnumEntrySymbol.owner, it.selector)
}
is ObjCClassMethodForKotlinEnumValuesOrEntries -> {
classAdapters += createEnumValuesOrEntriesAdapter(it.valuesFunctionSymbol.owner, it.selector)
}
is ObjCGetterForObjectInstance -> {
classAdapters += if (it.classSymbol.owner.isUnit()) {
createUnitInstanceAdapter(it.selector)
} else {
createObjectInstanceAdapter(it.classSymbol.owner, it.selector, irClass)
}
}
ObjCKotlinThrowableAsErrorMethod -> {
adapters += createThrowableAsErrorAdapter()
}
is ObjCMethodForKotlinMethod -> {} // Handled below.
}.let {} // Force exhaustive.
}
val additionalReverseAdapters = mutableListOf<ObjCExportCodeGenerator.KotlinToObjCMethodAdapter>()
if (type is ObjCClassForKotlinClass) {
type.categoryMethods.forEach {
adapters += createFinalMethodAdapter(it.baseMethod)
additionalReverseAdapters += nonOverridableAdapter(it.baseMethod.selector, hasSelectorAmbiguity = false)
}
adapters += createDirectAdapters(type, superClass)
}
val virtualAdapters = type.kotlinMethods
.filter {
val irFunction = it.baseMethod.owner
irFunction.parentAsClass == irClass && irFunction.isOverridable
}.map { createMethodVirtualAdapter(it.baseMethod) }
val typeInfo = constPointer(codegen.typeInfoValue(irClass))
val objCName = type.binaryName
val vtableSize = if (irClass.kind == ClassKind.INTERFACE) {
-1
} else {
context.getLayoutBuilder(irClass).vtableEntries.size
}
val vtable = if (!irClass.isInterface && !irClass.typeInfoHasVtableAttached) {
val table = rttiGenerator.vtable(irClass)
staticData.placeGlobal("", table).also {
it.setConstant(true)
}.pointer.getElementPtr(llvm, LLVMArrayType(llvm.int8PtrType, table.elements.size)!!, 0)
} else {
null
}
val (itable, itableSize) = when {
irClass.isInterface -> Pair(emptyList(), context.getLayoutBuilder(irClass).interfaceVTableEntries.size)
irClass.isAbstract() -> rttiGenerator.interfaceTableRecords(irClass)
else -> Pair(emptyList(), -1)
}
return ObjCTypeAdapter(
irClass,
typeInfo,
vtable,
vtableSize,
itable,
itableSize,
objCName,
adapters,
classAdapters,
virtualAdapters,
reverseAdapters + additionalReverseAdapters
)
}
private fun ObjCExportCodeGenerator.createReverseAdapters(
types: List<ObjCTypeForKotlinType>
): Map<ObjCTypeForKotlinType, ReverseAdapters> {
val irClassSymbolToType = types.associateBy { it.irClassSymbol }
val result = mutableMapOf<ObjCTypeForKotlinType, ReverseAdapters>()
fun getOrCreateFor(type: ObjCTypeForKotlinType): ReverseAdapters = result.getOrPut(type) {
// Each type also inherits reverse adapters from super types.
// This is handled in runtime when building TypeInfo for Swift or Obj-C type
// subclassing Kotlin classes or interfaces. See [createTypeInfo] in ObjCExport.mm.
val allSuperClasses = DFS.dfs(
type.irClassSymbol.owner.superClasses,
{ it.owner.superClasses },
object : DFS.NodeHandlerWithListResult<IrClassSymbol, IrClassSymbol>() {
override fun afterChildren(current: IrClassSymbol) {
this.result += current
}
}
)
val inheritsAdaptersFrom = allSuperClasses.mapNotNull { irClassSymbolToType[it] }
val inheritedAdapters = inheritsAdaptersFrom.map { getOrCreateFor(it) }
createReverseAdapters(type, inheritedAdapters)
}
types.forEach { getOrCreateFor(it) }
return result
}
private class ReverseAdapters(
val adapters: List<ObjCExportCodeGenerator.KotlinToObjCMethodAdapter>,
val coveredMethods: Set<IrSimpleFunction>
)
private fun ObjCExportCodeGenerator.createReverseAdapters(
type: ObjCTypeForKotlinType,
inheritedAdapters: List<ReverseAdapters>
): ReverseAdapters {
val result = mutableListOf<ObjCExportCodeGenerator.KotlinToObjCMethodAdapter>()
val coveredMethods = mutableSetOf<IrSimpleFunction>()
val methodsCoveredByInheritedAdapters = inheritedAdapters.flatMapTo(mutableSetOf()) { it.coveredMethods }
val allBaseMethodsByIr = type.kotlinMethods.map { it.baseMethod }.associateBy { it.owner }
for (method in type.irClassSymbol.owner.simpleFunctions().map { it.getLowered() }) {
val baseMethods = method.allOverriddenFunctions.mapNotNull { allBaseMethodsByIr[it] }
if (baseMethods.isEmpty()) continue
val hasSelectorAmbiguity = baseMethods.map { it.selector }.distinct().size > 1
if (method.isOverridable && !hasSelectorAmbiguity) {
val baseMethod = baseMethods.first()
val presentVtableBridges = mutableSetOf<Int?>(null)
val presentMethodTableBridges = mutableSetOf<String>()
val presentItableBridges = mutableSetOf<ClassLayoutBuilder.InterfaceTablePlace?>(null)
val allOverriddenMethods = method.allOverriddenFunctions
val (inherited, uninherited) = allOverriddenMethods.partition {
it in methodsCoveredByInheritedAdapters
}
inherited.forEach {
presentVtableBridges += vtableIndex(it)
presentMethodTableBridges += it.computeFunctionName()
presentItableBridges += itablePlace(it)
}
uninherited.forEach {
val vtableIndex = vtableIndex(it)
val functionName = it.computeFunctionName()
val itablePlace = itablePlace(it)
if (vtableIndex !in presentVtableBridges || functionName !in presentMethodTableBridges
|| itablePlace !in presentItableBridges) {
presentVtableBridges += vtableIndex
presentMethodTableBridges += functionName
presentItableBridges += itablePlace
result += createReverseAdapter(it, baseMethod, vtableIndex, itablePlace)
coveredMethods += it
}
}
} else {
// Mark it as non-overridable:
baseMethods.map { it.selector }.distinct().forEach {
result += nonOverridableAdapter(it, hasSelectorAmbiguity)
}
}
}
return ReverseAdapters(result, coveredMethods)
}
private fun ObjCExportCodeGenerator.nonOverridableAdapter(
selector: String,
hasSelectorAmbiguity: Boolean
): ObjCExportCodeGenerator.KotlinToObjCMethodAdapter = KotlinToObjCMethodAdapter(
selector,
vtableIndex = if (hasSelectorAmbiguity) -2 else -1, // Describes the reason.
kotlinImpl = NullPointer(llvm.int8Type),
itablePlace = ClassLayoutBuilder.InterfaceTablePlace.INVALID
)
private val ObjCTypeForKotlinType.kotlinMethods: List<ObjCMethodForKotlinMethod>
get() = this.methods.filterIsInstance<ObjCMethodForKotlinMethod>()
internal data class DirectAdapterRequest(val implementation: IrFunction?, val base: ObjCMethodSpec.BaseMethod<*>)
private fun ObjCExportCodeGenerator.createDirectAdapters(
typeDeclaration: ObjCClassForKotlinClass,
superClass: ObjCClassForKotlinClass?
): List<ObjCExportCodeGenerator.ObjCToKotlinMethodAdapter> {
fun ObjCClassForKotlinClass.getAllRequiredDirectAdapters() = this.kotlinMethods.map { method ->
DirectAdapterRequest(
findImplementation(irClassSymbol.owner, method.baseMethod.owner, context),
method.baseMethod
)
}
val inheritedAdapters = superClass?.getAllRequiredDirectAdapters().orEmpty().toSet()
val requiredAdapters = typeDeclaration.getAllRequiredDirectAdapters() - inheritedAdapters
return requiredAdapters.distinctBy { it.base.selector }.map { createMethodAdapter(it) }
}
private fun ObjCExportCodeGenerator.findImplementation(irClass: IrClass, method: IrSimpleFunction, context: Context): IrSimpleFunction? {
val override = irClass.simpleFunctions().singleOrNull {
method in it.getLowered().allOverriddenFunctions
} ?: error("no implementation for ${method.render()}\nin ${irClass.fqNameWhenAvailable}")
return OverriddenFunctionInfo(override.getLowered(), method).getImplementation(context)
}
private inline fun ObjCExportCodeGenerator.generateObjCToKotlinSyntheticGetter(
selector: String,
suffix: String,
block: ObjCExportFunctionGenerationContext.() -> Unit
): ObjCExportCodeGenerator.ObjCToKotlinMethodAdapter {
val methodBridge = MethodBridge(
MethodBridge.ReturnValue.Mapped(ReferenceBridge),
MethodBridgeReceiver.Static, valueParameters = emptyList()
)
val functionType = objCFunctionType(generationState, methodBridge)
val functionName = "objc2kotlin_$suffix"
val imp = functionGenerator(functionType.toProto(functionName, null, LLVMLinkage.LLVMInternalLinkage)) {
switchToRunnable = true
}.generate {
block()
}
return objCToKotlinMethodAdapter(selector, methodBridge, imp)
}
private fun ObjCExportCodeGenerator.objCToKotlinMethodAdapter(
selector: String,
methodBridge: MethodBridge,
imp: LlvmCallable
): ObjCExportCodeGenerator.ObjCToKotlinMethodAdapter {
selectorsToDefine[selector] = methodBridge
return ObjCToKotlinMethodAdapter(selector, getEncoding(methodBridge), imp.toConstPointer())
}
private fun ObjCExportCodeGenerator.createUnitInstanceAdapter(selector: String) =
generateObjCToKotlinSyntheticGetter(selector, "UnitInstance") {
// Note: generateObjCToKotlinSyntheticGetter switches to Runnable, which is probably not required here and thus suboptimal.
initRuntimeIfNeeded() // For instance methods it gets called when allocating.
autoreleaseAndRet(callFromBridge(llvm.Kotlin_ObjCExport_convertUnitToRetained, listOf(codegen.theUnitInstanceRef.llvm)))
}
private fun ObjCExportCodeGenerator.createObjectInstanceAdapter(
objectClass: IrClass,
selector: String,
owner: IrClass,
): ObjCExportCodeGenerator.ObjCToKotlinMethodAdapter {
assert(objectClass.kind == ClassKind.OBJECT)
assert(!objectClass.isUnit())
val methodBridge = MethodBridge(
returnBridge = MethodBridge.ReturnValue.Mapped(ReferenceBridge),
receiver = MethodBridgeReceiver.Static,
valueParameters = emptyList()
)
val function = context.getObjectClassInstanceFunction(objectClass)
val imp = generateObjCImp(
function, function, methodBridge,
isVirtual = false,
customBridgeSuffix = "${owner.computeTypeInfoSymbolName()}#$selector")
return objCToKotlinMethodAdapter(selector, methodBridge, imp)
}
private fun ObjCExportCodeGenerator.createEnumEntryAdapter(
irEnumEntry: IrEnumEntry,
selector: String
): ObjCExportCodeGenerator.ObjCToKotlinMethodAdapter {
val bridgeName = "${irEnumEntry.parentAsClass.computeTypeInfoSymbolName()}.${irEnumEntry.name.asString()}"
return generateObjCToKotlinSyntheticGetter(selector, bridgeName) {
initRuntimeIfNeeded() // For instance methods it gets called when allocating.
val value = getEnumEntry(irEnumEntry, ExceptionHandler.Caller)
autoreleaseAndRet(kotlinReferenceToRetainedObjC(value))
}
}
private fun ObjCExportCodeGenerator.createEnumValuesOrEntriesAdapter(
function: IrFunction,
selector: String
): ObjCExportCodeGenerator.ObjCToKotlinMethodAdapter {
val methodBridge = MethodBridge(
returnBridge = MethodBridge.ReturnValue.Mapped(ReferenceBridge),
receiver = MethodBridgeReceiver.Static,
valueParameters = emptyList()
)
val imp = generateObjCImp(function, function, methodBridge, isVirtual = false)
return objCToKotlinMethodAdapter(selector, methodBridge, imp)
}
private fun ObjCExportCodeGenerator.createThrowableAsErrorAdapter(): ObjCExportCodeGenerator.ObjCToKotlinMethodAdapter {
val methodBridge = MethodBridge(
returnBridge = MethodBridge.ReturnValue.Mapped(ReferenceBridge),
receiver = MethodBridgeReceiver.Instance,
valueParameters = emptyList()
)
val imp = generateObjCImpBy(methodBridge, suffix = "ThrowableAsError") {
val exception = objCReferenceToKotlin(param(0), Lifetime.ARGUMENT)
ret(callFromBridge(llvm.Kotlin_ObjCExport_WrapExceptionToNSError, listOf(exception)))
}
val selector = ObjCExportNamer.kotlinThrowableAsErrorMethodName
return objCToKotlinMethodAdapter(selector, methodBridge, imp)
}
private fun objCFunctionType(generationState: NativeGenerationState, methodBridge: MethodBridge): LlvmFunctionSignature {
val paramTypes = methodBridge.paramBridges.map { it.toLlvmParamType(generationState.llvm) }
val returnType = methodBridge.returnBridge.toLlvmRetType(generationState)
return LlvmFunctionSignature(returnType, paramTypes, isVararg = false)
}
private fun ObjCValueType.toLlvmType(llvm: CodegenLlvmHelpers): LLVMTypeRef = when (this) {
ObjCValueType.BOOL -> llvm.int8Type
ObjCValueType.UNICHAR -> llvm.int16Type
ObjCValueType.CHAR -> llvm.int8Type
ObjCValueType.SHORT -> llvm.int16Type
ObjCValueType.INT -> llvm.int32Type
ObjCValueType.LONG_LONG -> llvm.int64Type
ObjCValueType.UNSIGNED_CHAR -> llvm.int8Type
ObjCValueType.UNSIGNED_SHORT -> llvm.int16Type
ObjCValueType.UNSIGNED_INT -> llvm.int32Type
ObjCValueType.UNSIGNED_LONG_LONG -> llvm.int64Type
ObjCValueType.FLOAT -> llvm.floatType
ObjCValueType.DOUBLE -> llvm.doubleType
ObjCValueType.POINTER -> llvm.int8PtrType
}
private fun MethodBridgeParameter.toLlvmParamType(llvm: CodegenLlvmHelpers): LlvmParamType = when (this) {
is MethodBridgeValueParameter.Mapped -> this.bridge.toLlvmParamType(llvm)
is MethodBridgeReceiver -> ReferenceBridge.toLlvmParamType(llvm)
MethodBridgeSelector -> LlvmParamType(llvm.int8PtrType)
MethodBridgeValueParameter.ErrorOutParameter -> LlvmParamType(pointerType(ReferenceBridge.toLlvmParamType(llvm).llvmType))
is MethodBridgeValueParameter.SuspendCompletion -> LlvmParamType(llvm.int8PtrType)
}
private fun MethodBridge.ReturnValue.toLlvmRetType(
generationState: NativeGenerationState
): LlvmRetType {
val llvm = generationState.llvm
return when (this) {
MethodBridge.ReturnValue.Suspend,
MethodBridge.ReturnValue.Void -> LlvmRetType(llvm.voidType)
MethodBridge.ReturnValue.HashCode -> LlvmRetType(if (generationState.is64BitNSInteger()) llvm.int64Type else llvm.int32Type)
is MethodBridge.ReturnValue.Mapped -> this.bridge.toLlvmParamType(llvm)
MethodBridge.ReturnValue.WithError.Success -> ValueTypeBridge(ObjCValueType.BOOL).toLlvmParamType(llvm)
MethodBridge.ReturnValue.Instance.InitResult,
MethodBridge.ReturnValue.Instance.FactoryResult -> ReferenceBridge.toLlvmParamType(llvm)
is MethodBridge.ReturnValue.WithError.ZeroForError -> this.successBridge.toLlvmRetType(generationState)
}
}
private fun TypeBridge.toLlvmParamType(llvm: CodegenLlvmHelpers): LlvmParamType = when (this) {
is ReferenceBridge, is BlockPointerBridge -> LlvmParamType(llvm.int8PtrType)
is ValueTypeBridge -> LlvmParamType(this.objCValueType.toLlvmType(llvm), this.objCValueType.defaultParameterAttributes)
}
internal fun ObjCExportCodeGenerator.getEncoding(methodBridge: MethodBridge): String {
var paramOffset = 0
val params = buildString {
methodBridge.paramBridges.forEach {
append(it.objCEncoding)
append(paramOffset)
paramOffset += LLVMStoreSizeOfType(runtime.targetData, it.toLlvmParamType(llvm).llvmType).toInt()
}
}
val returnTypeEncoding = methodBridge.returnBridge.getObjCEncoding(generationState)
val paramSize = paramOffset
return "$returnTypeEncoding$paramSize$params"
}
private fun MethodBridge.ReturnValue.getObjCEncoding(generationState: NativeGenerationState): String = when (this) {
MethodBridge.ReturnValue.Suspend,
MethodBridge.ReturnValue.Void -> "v"
MethodBridge.ReturnValue.HashCode -> if (generationState.is64BitNSInteger()) "Q" else "I"
is MethodBridge.ReturnValue.Mapped -> this.bridge.objCEncoding
MethodBridge.ReturnValue.WithError.Success -> ObjCValueType.BOOL.encoding
MethodBridge.ReturnValue.Instance.InitResult,
MethodBridge.ReturnValue.Instance.FactoryResult -> ReferenceBridge.objCEncoding
is MethodBridge.ReturnValue.WithError.ZeroForError -> this.successBridge.getObjCEncoding(generationState)
}
private val MethodBridgeParameter.objCEncoding: String get() = when (this) {
is MethodBridgeValueParameter.Mapped -> this.bridge.objCEncoding
is MethodBridgeReceiver -> ReferenceBridge.objCEncoding
MethodBridgeSelector -> ":"
MethodBridgeValueParameter.ErrorOutParameter -> "^${ReferenceBridge.objCEncoding}"
is MethodBridgeValueParameter.SuspendCompletion -> "@"
}
private val TypeBridge.objCEncoding: String get() = when (this) {
ReferenceBridge, is BlockPointerBridge -> "@"
is ValueTypeBridge -> this.objCValueType.encoding
}
private fun NativeGenerationState.is64BitNSInteger(): Boolean {
val configurables = config.platform.configurables
require(configurables is AppleConfigurables) {
"Target ${configurables.target} has no support for NSInteger type."
}
return llvm.nsIntegerTypeWidth == 64L
}
private fun MethodBridge.parametersAssociated(
irFunction: IrFunction
): List<Pair<MethodBridgeParameter, IrValueParameter?>> {
val kotlinParameters = irFunction.allParameters.iterator()
return this.paramBridges.map {
when (it) {
is MethodBridgeValueParameter.Mapped,
MethodBridgeReceiver.Instance,
is MethodBridgeValueParameter.SuspendCompletion ->
it to kotlinParameters.next()
MethodBridgeReceiver.Static, MethodBridgeSelector, MethodBridgeValueParameter.ErrorOutParameter ->
it to null
MethodBridgeReceiver.Factory -> {
kotlinParameters.next()
it to null
}
}
}.also { assert(!kotlinParameters.hasNext()) }
}
|
package kotlin.js
import JsError
@JsName("Boolean")
internal external fun nativeBoolean(obj: Any?): Boolean
internal fun booleanInExternalLog(name: String, obj: dynamic) {
if (jsTypeOf(obj) != "boolean") {
console.asDynamic().error("Boolean expected for '$name', but actual:", obj)
}
}
internal fun booleanInExternalException(name: String, obj: dynamic) {
if (jsTypeOf(obj) != "boolean") {
throw JsError("Boolean expected for '$name', but actual: $obj")
}
} |
package org.jetbrains.kotlin.extensions.internal
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.VariableDescriptor
import org.jetbrains.kotlin.descriptors.impl.AnonymousFunctionDescriptor
import org.jetbrains.kotlin.incremental.components.LookupLocation
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtLambdaExpression
import org.jetbrains.kotlin.resolve.BindingTrace
import org.jetbrains.kotlin.resolve.calls.CallResolver
import org.jetbrains.kotlin.resolve.calls.CandidateResolver
import org.jetbrains.kotlin.resolve.calls.context.BasicCallResolutionContext
import org.jetbrains.kotlin.resolve.calls.inference.components.NewTypeSubstitutor
import org.jetbrains.kotlin.resolve.calls.model.KotlinCallDiagnostic
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCallAtom
import org.jetbrains.kotlin.resolve.calls.tasks.TracingStrategy
import org.jetbrains.kotlin.resolve.calls.tower.ImplicitScopeTower
import org.jetbrains.kotlin.resolve.calls.tower.NewResolutionOldInference
import org.jetbrains.kotlin.resolve.calls.tower.PSICallResolver
import org.jetbrains.kotlin.resolve.scopes.ResolutionScope
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValueWithSmartCastInfo
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.expressions.ExpressionTypingContext
/**
* This is marker for non-stable experimental extension points.
* Extension points marked with this meta-annotation will be broken in the future version.
* Please do not use them in general code.
*/
@RequiresOptIn(level = RequiresOptIn.Level.ERROR)
@Retention(AnnotationRetention.BINARY)
annotation class InternalNonStableExtensionPoints
@InternalNonStableExtensionPoints
interface TypeResolutionInterceptorExtension {
fun interceptFunctionLiteralDescriptor(
expression: KtLambdaExpression,
context: ExpressionTypingContext,
descriptor: AnonymousFunctionDescriptor
): AnonymousFunctionDescriptor = descriptor
fun interceptType(
element: KtElement,
context: ExpressionTypingContext,
resultType: KotlinType
): KotlinType = resultType
}
@InternalNonStableExtensionPoints
interface CallResolutionInterceptorExtension {
fun interceptResolvedCallAtomCandidate(
candidateDescriptor: CallableDescriptor,
completedCallAtom: ResolvedCallAtom,
trace: BindingTrace?,
resultSubstitutor: NewTypeSubstitutor?,
diagnostics: Collection<KotlinCallDiagnostic>
): CallableDescriptor = candidateDescriptor
fun interceptCandidates(
candidates: Collection<NewResolutionOldInference.MyCandidate>,
context: BasicCallResolutionContext,
candidateResolver: CandidateResolver,
callResolver: CallResolver,
name: Name,
kind: NewResolutionOldInference.ResolutionKind,
tracing: TracingStrategy
): Collection<NewResolutionOldInference.MyCandidate> = candidates
fun interceptFunctionCandidates(
candidates: Collection<FunctionDescriptor>,
scopeTower: ImplicitScopeTower,
resolutionContext: BasicCallResolutionContext,
resolutionScope: ResolutionScope,
callResolver: CallResolver,
name: Name,
location: LookupLocation
): Collection<FunctionDescriptor> = candidates
fun interceptFunctionCandidates(
candidates: Collection<FunctionDescriptor>,
scopeTower: ImplicitScopeTower,
resolutionContext: BasicCallResolutionContext,
resolutionScope: ResolutionScope,
callResolver: PSICallResolver,
name: Name,
location: LookupLocation,
dispatchReceiver: ReceiverValueWithSmartCastInfo?,
extensionReceiver: ReceiverValueWithSmartCastInfo?
): Collection<FunctionDescriptor> = candidates
fun interceptVariableCandidates(
candidates: Collection<VariableDescriptor>,
scopeTower: ImplicitScopeTower,
resolutionContext: BasicCallResolutionContext,
resolutionScope: ResolutionScope,
callResolver: CallResolver,
name: Name,
location: LookupLocation
): Collection<VariableDescriptor> = candidates
fun interceptVariableCandidates(
candidates: Collection<VariableDescriptor>,
scopeTower: ImplicitScopeTower,
resolutionContext: BasicCallResolutionContext,
resolutionScope: ResolutionScope,
callResolver: PSICallResolver,
name: Name,
location: LookupLocation,
dispatchReceiver: ReceiverValueWithSmartCastInfo?,
extensionReceiver: ReceiverValueWithSmartCastInfo?
): Collection<VariableDescriptor> = candidates
}
|
class A {
@Suppress("") @MustBeDocumented
}
class B {
@Suppress("") @MustBeDocumented
}
class Outer {
class Inner {
@Suppress("") @MustBeDocumented
}
fun withLocal() {
class Local {
@Suppress("") @MustBeDocumented
}
val r : I = object : I {
@Suppress("") @MustBeDocumented
}
}
}
interface I {} |
package com.android.tools.idea.lang.androidSql.resolution
import com.android.tools.idea.lang.androidSql.psi.AndroidSqlColumnDefinitionName
import com.android.tools.idea.lang.androidSql.psi.AndroidSqlWithClauseTable
import com.intellij.psi.PsiElement
import com.intellij.util.Processor
class WithClauseTable(withClauseTable: AndroidSqlWithClauseTable) : AndroidSqlTable {
private val tableDefinition = withClauseTable.withClauseTableDef
override val name get() = tableDefinition.tableDefinitionName.nameAsString
override val definingElement get() = tableDefinition.tableDefinitionName
override val isView: Boolean get() = true
override fun processColumns(processor: Processor<AndroidSqlColumn>, sqlTablesInProcess: MutableSet<PsiElement>): Boolean {
for (columnDefinition in tableDefinition.columnDefinitionNameList) {
if (!processor.process(DefinedColumn(columnDefinition))) return false
}
return true
}
private class DefinedColumn(override val definingElement: AndroidSqlColumnDefinitionName) : AndroidSqlColumn {
override val name get() = definingElement.nameAsString
override val type: SqlType? get() = null
}
}
|
package com.google.devtools.ksp.symbol
/**
* A Kotlin source file
*/
interface KSFile : KSDeclarationContainer, KSAnnotated {
/**
* The [KSName] representation of this file's package.
*/
val packageName: KSName
/**
* File name of this source file.
*/
val fileName: String
/**
* Absolute path of this source file.
*/
val filePath: String
}
|
@file:Suppress("OPT_IN_USAGE", "JS_NAME_CLASH")
package foo
<!EXPORTING_JS_NAME_CLASH, EXPORTING_JS_NAME_CLASH_ES!>@JsExport fun test() = 1<!>
// FILE: B.kt
@file:Suppress("OPT_IN_USAGE", "JS_NAME_CLASH")
package foo
<!EXPORTING_JS_NAME_CLASH, EXPORTING_JS_NAME_CLASH_ES!>@JsExport @JsName("test") fun bar() = 2<!>
|
package org.jetbrains.kotlin.benchmarks
import org.openjdk.jmh.annotations.*
import org.openjdk.jmh.infra.Blackhole
import java.util.concurrent.TimeUnit
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Benchmark)
open class ComplexDataFlowBenchmark : AbstractSimpleFileBenchmark(){
@Param("1", "100", "1000", "3000", "5000", "7000", "10000")
private var size: Int = 0
@Benchmark
fun benchmark(bh: Blackhole) {
analyzeGreenFile(bh)
}
override fun buildText() =
"""
|
|fun bar(x: Any?) {
| var y = x
|${(1..size).joinToString("\n") {
"""
|if (x is String) {
| y = x
|}
|y = 1
""".trimMargin()
}}
|}
""".trimMargin()
}
|
package plugin;
import entities.*;
public class Plugin {
public CommonFields getCommonFields() {
return new CommonFields("OK");
}
}
// FILE: entities/CommonFields.kt
package entities
data class CommonFields(val screenShots: String)
// FILE: test/foo.kt
package test
import plugin.Plugin
fun foo(plugin: Plugin): String? {
return plugin.commonFields?.screenShots
}
// FILE: example/test.kt
import test.foo
import plugin.Plugin
fun box(): String =
foo(Plugin())!!
|
class Outer {
class Nested {
companion object {
fun foo() = 42
}
}
companion object {
fun bar() = 239
}
}
fun foo() = Outer.Nested.foo()
fun bar() = Outer.bar()
|
@file:Suppress(
"NESTED_CLASS_IN_EXTERNAL_INTERFACE",
)
package web.http
import seskar.js.JsValue
import seskar.js.JsVirtual
@JsVirtual
sealed external interface RequestCredentials {
companion object {
@JsValue("include")
val include: RequestCredentials
@JsValue("omit")
val omit: RequestCredentials
@JsValue("same-origin")
val sameOrigin: RequestCredentials
}
}
|
package org.jetbrains.kotlinx.kandy.letsplot.layers.context.aes
import org.jetbrains.kotlinx.dataframe.DataColumn
import org.jetbrains.kotlinx.dataframe.columns.ColumnReference
import org.jetbrains.kotlinx.kandy.dsl.internal.BindingContext
import org.jetbrains.kotlinx.kandy.ir.bindings.NonPositionalMapping
import org.jetbrains.kotlinx.kandy.letsplot.internal.LINE_TYPE
import org.jetbrains.kotlinx.kandy.letsplot.internal.LetsPlotNonPositionalMappingParametersCategorical
import org.jetbrains.kotlinx.kandy.letsplot.settings.LineType
import kotlin.reflect.KProperty
/**
* Interface for configuring the `lineType` aesthetic, which specifies the type of lines in the plot.
*
* This interface allows you to specify the lineType as a constant, map it to a column, or provide iterable of values.
*/
public interface WithLineType : BindingContext {
/**
* Sets a constant `lineType` for the layer.
*
* @property lineType the value to be set.
*/
public var lineType: LineType?
get() = null
set(value) {
addNonPositionalSetting(LINE_TYPE, value)
}
/**
* Maps the `lineType` aesthetic to a data column by [ColumnReference].
*
* @param column the data column to map to the color.
* @param parameters optional lambda to configure additional scale parameters.
* @return a [NonPositionalMapping] object representing the mapping.
*/
public fun <T> lineType(
column: ColumnReference<T>,
parameters: LetsPlotNonPositionalMappingParametersCategorical<T, LineType>.() -> Unit = {}
): NonPositionalMapping<T, LineType> {
return addNonPositionalMapping<T, LineType>(
LINE_TYPE,
column.name(),
LetsPlotNonPositionalMappingParametersCategorical<T, LineType>().apply(parameters)
)
}
/**
* Maps the `lineType` aesthetic to a data column by [KProperty].
*
* @param column the data column to map to the color.
* @param parameters optional lambda to configure additional scale parameters.
* @return a [NonPositionalMapping] object representing the mapping.
*/
public fun <T> lineType(
column: KProperty<T>,
parameters: LetsPlotNonPositionalMappingParametersCategorical<T, LineType>.() -> Unit = {}
): NonPositionalMapping<T, LineType> {
return addNonPositionalMapping<T, LineType>(
LINE_TYPE,
column.name,
LetsPlotNonPositionalMappingParametersCategorical<T, LineType>().apply(parameters)
)
}
/**
* Maps the `lineType` aesthetic to a data column by [String].
*
* @param column the data column to map to the color.
* @param parameters optional lambda to configure additional scale parameters.
* @return a [NonPositionalMapping] object representing the mapping.
*/
public fun lineType(
column: String,
parameters: LetsPlotNonPositionalMappingParametersCategorical<Any?, LineType>.() -> Unit = {}
): NonPositionalMapping<Any?, LineType> {
return addNonPositionalMapping(
LINE_TYPE,
column,
LetsPlotNonPositionalMappingParametersCategorical<Any?, LineType>().apply(parameters)
)
}
/**
* Maps the `lineType` aesthetic to iterable of values.
*
* @param values the iterable containing the values.
* @param name optional name for this aesthetic mapping.
* @param parameters optional lambda to configure additional scale parameters.
* @return a [NonPositionalMapping] object representing the mapping.
*/
public fun <T> lineType(
values: Iterable<T>,
name: String? = null,
parameters: LetsPlotNonPositionalMappingParametersCategorical<T, LineType>.() -> Unit = {}
): NonPositionalMapping<T, LineType> {
return addNonPositionalMapping(
LINE_TYPE,
values.toList(),
name,
LetsPlotNonPositionalMappingParametersCategorical<T, LineType>().apply(parameters)
)
}
/**
* Maps the `lineType` aesthetic to a data column.
*
* @param values the data column to map to the color.
* @param parameters optional lambda to configure additional scale parameters.
* @return a [NonPositionalMapping] object representing the mapping.
*/
public fun <T> lineType(
values: DataColumn<T>,
//name: String? = null,
parameters: LetsPlotNonPositionalMappingParametersCategorical<T, LineType>.() -> Unit = {}
): NonPositionalMapping<T, LineType> {
return addNonPositionalMapping(
LINE_TYPE,
values,
LetsPlotNonPositionalMappingParametersCategorical<T, LineType>().apply(parameters)
)
}
}
|
package com.android.tools.idea.editors.strings.action
import com.android.testutils.MockitoKt.mock
import com.android.testutils.MockitoKt.whenever
import com.android.tools.idea.editors.strings.StringResourceEditor
import com.android.tools.idea.editors.strings.StringResourceViewPanel
import com.android.tools.idea.testing.AndroidProjectRule
import com.google.common.truth.Truth.assertThat
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.actionSystem.Presentation
import com.intellij.openapi.project.Project
import com.intellij.testFramework.MapDataContext
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import org.mockito.Mockito.verify
/** Test [AddLocaleAction] methods. */
@RunWith(JUnit4::class)
class ReloadStringResourcesActionTest {
@get:Rule val projectRule = AndroidProjectRule.inMemory()
private val project: Project
get() = projectRule.project
private val stringResourceEditor: StringResourceEditor = mock()
private val panel: StringResourceViewPanel = mock()
private val reloadStringResourcesAction = ReloadStringResourcesAction()
private val mapDataContext = MapDataContext()
private lateinit var event: AnActionEvent
@Before
fun setUp() {
event = AnActionEvent(null, mapDataContext, "place", Presentation(), ActionManager.getInstance(), 0)
mapDataContext.apply {
put(CommonDataKeys.PROJECT, project)
put(PlatformDataKeys.FILE_EDITOR, stringResourceEditor)
}
whenever(stringResourceEditor.panel).thenReturn(panel)
}
@Test
fun doUpdate() {
reloadStringResourcesAction.update(event)
assertThat(event.presentation.isEnabled).isTrue()
}
@Test
fun actionPerformed() {
reloadStringResourcesAction.actionPerformed(event)
verify(panel).reloadData()
}
}
|
package org.jetbrains.kotlinx.dl.api.core.layer.core
import org.jetbrains.kotlinx.dl.api.core.layer.Layer
import org.jetbrains.kotlinx.dl.api.core.util.DATA_PLACEHOLDER
import org.jetbrains.kotlinx.dl.api.core.util.getDType
import org.tensorflow.Operand
import org.tensorflow.Shape
import org.tensorflow.op.Ops
import org.tensorflow.op.core.Placeholder
/**
* This layer is responsible for the input shape of the built model.
*
* First and required layer in [org.jetbrains.kotlinx.dl.api.core.Sequential.of] method.
*
* @property [name] Custom layer name.
* @constructor Creates [Input] layer from [packedDims] representing [input] data shape.
*/
public class Input(vararg dims: Long, name: String = "") : Layer(name) {
/** Placeholder for input data. */
public lateinit var input: Placeholder<Float>
/** Input data dimensions. Rank = 3 or 4 for most popular supported cases. */
public var packedDims: LongArray = dims
override fun build(
tf: Ops,
input: Operand<Float>,
isTraining: Operand<Boolean>,
numberOfLosses: Operand<Float>?
): Operand<Float> = build(tf)
/**
* Extend this function to define placeholder in layer.
*
* NOTE: Called instead of [Layer.build].
*
* @param [tf] TensorFlow graph API for building operations.
*/
public fun build(tf: Ops): Placeholder<Float> {
input = tf.withName(DATA_PLACEHOLDER).placeholder(
getDType(),
Placeholder.shape(Shape.make(-1L, *packedDims))
)
return input
}
override val hasActivation: Boolean get() = false
override fun toString(): String {
return "Input(name = $name, shape=${packedDims.contentToString()})"
}
}
|
package node.util
import kotlin.contracts.contract
@Suppress("NOTHING_TO_INLINE", "CANNOT_CHECK_FOR_EXTERNAL_INTERFACE")
inline fun isBuffer(value: Any?): Boolean /* object is Buffer */ {
contract {
returns(true) implies (value is node.buffer.Buffer)
}
return isBufferRaw(value)
}
|
package org.jetbrains.kotlin.psi
import org.jetbrains.kotlin.cli.jvm.compiler.EnvironmentConfigFiles
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.test.KotlinTestUtils
import org.jetbrains.kotlin.test.KotlinTestWithEnvironment
import org.junit.Assert
class KtPsiFactoryTest : KotlinTestWithEnvironment() {
fun testCreateModifierList() {
val psiFactory = KtPsiFactory(project)
KtTokens.MODIFIER_KEYWORDS_ARRAY.forEach {
val modifier = psiFactory.createModifierList(it)
Assert.assertTrue(modifier.hasModifier(it))
}
}
override fun createEnvironment(): KotlinCoreEnvironment {
return KotlinCoreEnvironment.createForTests(
testRootDisposable, KotlinTestUtils.newConfiguration(), EnvironmentConfigFiles.JVM_CONFIG_FILES
)
}
}
|
val bar = 17
var muc = "first"
var toc = "second"
get() = field
class X() {
val bar = "third"
var muc = 19
var toc = "fourth"
get() = field
}
// FILE: B.kt
// VERSION: 2
val bar = 23
var muc = "fifth"
var toc = "sixth"
get() = field
class X() {
val bar = "seventh"
var muc = 29
var toc = "eighth"
get() = field
}
// MODULE: mainLib(lib)
// FILE: mainLib.kt
fun lib(): String {
val x = X()
return when {
bar != 23 -> "fail 1"
muc != "fifth" -> "fail 2"
toc != "sixth" -> "fail 3"
x.bar != "seventh" -> "fail 4"
x.muc != 29 -> "fail 5"
x.toc != "eighth" -> "fail 6"
else -> "OK"
}
}
// MODULE: main(mainLib)
// FILE: main.kt
fun box(): String = lib()
|
inline fun<reified T> createArray(n: Int, crossinline block: () -> T): Array<T> {
return Array<T>(n) { block() }
}
inline fun<T1, T2, T3, T4, T5, T6, reified R> recursive(
crossinline block: () -> R
): Array<R> {
return createArray(5) { block() }
}
fun box(): String {
val x = recursive<Int, Int, Int, Int, Int, Int, String>(){ "abc" }
require(x.all { it == "abc" })
return "OK"
}
|
package org.jetbrains.report.json
import org.jetbrains.report.json.EscapeCharMappings.ESC2C
// special strings
internal const val NULL = "null"
// special chars
internal const val COMMA = ','
internal const val COLON = ':'
internal const val BEGIN_OBJ = '{'
internal const val END_OBJ = '}'
internal const val BEGIN_LIST = '['
internal const val END_LIST = ']'
internal const val STRING = '"'
internal const val STRING_ESC = '\\'
internal const val INVALID = 0.toChar()
internal const val UNICODE_ESC = 'u'
// token classes
internal const val TC_OTHER: Byte = 0
internal const val TC_STRING: Byte = 1
internal const val TC_STRING_ESC: Byte = 2
internal const val TC_WS: Byte = 3
internal const val TC_COMMA: Byte = 4
internal const val TC_COLON: Byte = 5
internal const val TC_BEGIN_OBJ: Byte = 6
internal const val TC_END_OBJ: Byte = 7
internal const val TC_BEGIN_LIST: Byte = 8
internal const val TC_END_LIST: Byte = 9
internal const val TC_NULL: Byte = 10
internal const val TC_INVALID: Byte = 11
internal const val TC_EOF: Byte = 12
// mapping from chars to token classes
private const val CTC_MAX = 0x7e
// mapping from escape chars real chars
private const val C2ESC_MAX = 0x5d
private const val ESC2C_MAX = 0x75
internal val C2TC = ByteArray(CTC_MAX).apply {
for (i in 0..0x20)
initC2TC(i, TC_INVALID)
initC2TC(0x09, TC_WS)
initC2TC(0x0a, TC_WS)
initC2TC(0x0d, TC_WS)
initC2TC(0x20, TC_WS)
initC2TC(COMMA, TC_COMMA)
initC2TC(COLON, TC_COLON)
initC2TC(BEGIN_OBJ, TC_BEGIN_OBJ)
initC2TC(END_OBJ, TC_END_OBJ)
initC2TC(BEGIN_LIST, TC_BEGIN_LIST)
initC2TC(END_LIST, TC_END_LIST)
initC2TC(STRING, TC_STRING)
initC2TC(STRING_ESC, TC_STRING_ESC)
}
// object instead of @SharedImmutable because there is mutual initialization in [initC2ESC]
internal object EscapeCharMappings {
internal val ESC2C = CharArray(ESC2C_MAX)
internal val C2ESC = CharArray(C2ESC_MAX).apply {
for (i in 0x00..0x1f)
initC2ESC(i, UNICODE_ESC)
initC2ESC(0x08, 'b')
initC2ESC(0x09, 't')
initC2ESC(0x0a, 'n')
initC2ESC(0x0c, 'f')
initC2ESC(0x0d, 'r')
initC2ESC('/', '/')
initC2ESC(STRING, STRING)
initC2ESC(STRING_ESC, STRING_ESC)
}
private fun CharArray.initC2ESC(c: Int, esc: Char) {
this[c] = esc
if (esc != UNICODE_ESC) ESC2C[esc.code] = c.toChar()
}
private fun CharArray.initC2ESC(c: Char, esc: Char) = initC2ESC(c.code, esc)
}
private fun ByteArray.initC2TC(c: Int, cl: Byte) {
this[c] = cl
}
private fun ByteArray.initC2TC(c: Char, cl: Byte) {
initC2TC(c.code, cl)
}
internal fun charToTokenClass(c: Char) = if (c.code < CTC_MAX) C2TC[c.code] else TC_OTHER
internal fun escapeToChar(c: Int): Char = if (c < ESC2C_MAX) ESC2C[c] else INVALID
// JSON low level parser
internal class Parser(val source: String) {
var curPos: Int = 0 // position in source
private set
// updated by nextToken
var tokenPos: Int = 0
private set
var tc: Byte = TC_EOF
private set
// update by nextString/nextLiteral
private var offset = -1 // when offset >= 0 string is in source, otherwise in buf
private var length = 0 // length of string
private var buf = CharArray(16) // only used for strings with escapes
init {
nextToken()
}
internal inline fun requireTc(expected: Byte, lazyErrorMsg: () -> String) {
if (tc != expected)
fail(tokenPos, lazyErrorMsg())
}
val canBeginValue: Boolean
get() = when (tc) {
TC_BEGIN_LIST, TC_BEGIN_OBJ, TC_OTHER, TC_STRING, TC_NULL -> true
else -> false
}
@OptIn(ExperimentalStdlibApi::class)
fun takeStr(): String {
if (tc != TC_OTHER && tc != TC_STRING) fail(tokenPos, "Expected string or non-null literal")
val prevStr = if (offset < 0)
buf.concatToString(0, length) else
source.substring(offset, offset + length)
nextToken()
return prevStr
}
private fun append(ch: Char) {
if (length >= buf.size) buf = buf.copyOf(2 * buf.size)
buf[length++] = ch
}
// initializes buf usage upon the first encountered escaped char
private fun appendRange(source: String, fromIndex: Int, toIndex: Int) {
val addLen = toIndex - fromIndex
val oldLen = length
val newLen = oldLen + addLen
if (newLen > buf.size) buf = buf.copyOf(newLen.coerceAtLeast(2 * buf.size))
for (i in 0 until addLen) buf[oldLen + i] = source[fromIndex + i]
length += addLen
}
fun nextToken() {
val source = source
var curPos = curPos
val maxLen = source.length
while (true) {
if (curPos >= maxLen) {
tokenPos = curPos
tc = TC_EOF
return
}
val ch = source[curPos]
val tc = charToTokenClass(ch)
when (tc) {
TC_WS -> curPos++ // skip whitespace
TC_OTHER -> {
nextLiteral(source, curPos)
return
}
TC_STRING -> {
nextString(source, curPos)
return
}
else -> {
this.tokenPos = curPos
this.tc = tc
this.curPos = curPos + 1
return
}
}
}
}
private fun nextLiteral(source: String, startPos: Int) {
tokenPos = startPos
offset = startPos
var curPos = startPos
val maxLen = source.length
while (true) {
curPos++
if (curPos >= maxLen || charToTokenClass(source[curPos]) != TC_OTHER) break
}
this.curPos = curPos
length = curPos - offset
tc = if (rangeEquals(source, offset, length, NULL)) TC_NULL else TC_OTHER
}
private fun nextString(source: String, startPos: Int) {
tokenPos = startPos
length = 0 // in buffer
var curPos = startPos + 1
var lastPos = curPos
val maxLen = source.length
parse@ while (true) {
if (curPos >= maxLen) fail(curPos, "Unexpected end in string")
if (source[curPos] == STRING) {
break@parse
} else if (source[curPos] == STRING_ESC) {
appendRange(source, lastPos, curPos)
val newPos = appendEsc(source, curPos + 1)
curPos = newPos
lastPos = newPos
} else {
curPos++
}
}
if (lastPos == startPos + 1) {
// there was no escaped chars
this.offset = lastPos
this.length = curPos - lastPos
} else {
// some escaped chars were there
appendRange(source, lastPos, curPos)
this.offset = -1
}
this.curPos = curPos + 1
tc = TC_STRING
}
private fun appendEsc(source: String, startPos: Int): Int {
var curPos = startPos
require(curPos < source.length, curPos) { "Unexpected end after escape char" }
val curChar = source[curPos++]
if (curChar == UNICODE_ESC) {
curPos = appendHex(source, curPos)
} else {
val c = escapeToChar(curChar.code)
require(c != INVALID, curPos) { "Invalid escaped char '$curChar'" }
append(c)
}
return curPos
}
private fun appendHex(source: String, startPos: Int): Int {
var curPos = startPos
append(
((fromHexChar(source, curPos++) shl 12) +
(fromHexChar(source, curPos++) shl 8) +
(fromHexChar(source, curPos++) shl 4) +
fromHexChar(source, curPos++)).toChar()
)
return curPos
}
fun skipElement() {
if (tc != TC_BEGIN_OBJ && tc != TC_BEGIN_LIST) {
nextToken()
return
}
val tokenStack = mutableListOf<Byte>()
do {
when (tc) {
TC_BEGIN_LIST, TC_BEGIN_OBJ -> tokenStack.add(tc)
TC_END_LIST -> {
if (tokenStack.last() != TC_BEGIN_LIST) throw JsonParsingException(curPos, "found ] instead of }")
tokenStack.removeAt(tokenStack.size - 1)
}
TC_END_OBJ -> {
if (tokenStack.last() != TC_BEGIN_OBJ) throw JsonParsingException(curPos, "found } instead of ]")
tokenStack.removeAt(tokenStack.size - 1)
}
}
nextToken()
} while (tokenStack.isNotEmpty())
}
}
// Utility functions
private fun fromHexChar(source: String, curPos: Int): Int {
require(curPos < source.length, curPos) { "Unexpected end in unicode escape" }
val curChar = source[curPos]
return when (curChar) {
in '0'..'9' -> curChar.code - '0'.code
in 'a'..'f' -> curChar.code - 'a'.code + 10
in 'A'..'F' -> curChar.code - 'A'.code + 10
else -> fail(curPos, "Invalid toHexChar char '$curChar' in unicode escape")
}
}
private fun rangeEquals(source: String, start: Int, length: Int, str: String): Boolean {
val n = str.length
if (length != n) return false
for (i in 0 until n) if (source[start + i] != str[i]) return false
return true
}
internal inline fun require(condition: Boolean, pos: Int, msg: () -> String) {
if (!condition)
fail(pos, msg())
}
@Suppress("NOTHING_TO_INLINE")
internal inline fun fail(pos: Int, msg: String): Nothing {
throw JsonParsingException(pos, msg)
} |
class C<<!REIFIED_TYPE_PARAMETER_NO_INLINE!>reified<!> T>
fun <T> id(p: T): T = p
fun <A> main() {
<!NEW_INFERENCE_NO_INFORMATION_FOR_PARAMETER!>C<!>()
val a: C<A> = <!TYPE_PARAMETER_AS_REIFIED!>C<!>()
C<<!TYPE_PARAMETER_AS_REIFIED!>A<!>>()
val b: C<Int> = C()
C<Int>()
// TODO svtk, uncomment when extensions are called for nested calls!
//val < !UNUSED_VARIABLE!>с< !>: C<A> = id(< !TYPE_PARAMETER_AS_REIFIED!>C< !>())
}
|
@file:Suppress(
"NESTED_CLASS_IN_EXTERNAL_INTERFACE",
)
package web.cssom
import seskar.js.JsValue
import seskar.js.JsVirtual
@JsVirtual
sealed external interface TextDecorationStyle {
companion object {
@JsValue("dashed")
val dashed: TextDecorationStyle
@JsValue("dotted")
val dotted: TextDecorationStyle
@JsValue("double")
val double: TextDecorationStyle
@JsValue("solid")
val solid: TextDecorationStyle
@JsValue("wavy")
val wavy: TextDecorationStyle
}
}
|
package org.jetbrains.letsPlot.livemap.canvascontrols
import org.jetbrains.letsPlot.core.canvas.CanvasControl
internal class CanvasContentPresenter {
lateinit var canvasControl: CanvasControl
private var canvasContent: CanvasContent = EMPTY_CANVAS_CONTENT
fun show(content: CanvasContent) {
canvasContent.hide()
canvasContent = content
canvasContent.show(canvasControl)
}
fun clear() {
show(EMPTY_CANVAS_CONTENT)
}
private class EmptyContent : CanvasContent {
override fun show(parentControl: CanvasControl) {}
override fun hide() {}
}
companion object {
private val EMPTY_CANVAS_CONTENT = EmptyContent()
}
} |
fun box(): String {
try {
for (i in 0 until 1) {
try {
val x = "x"
throw RuntimeException(x)
} catch (e: Exception) {
val y = "y"
val z = "z"
continue
} finally {
throw RuntimeException("$i")
}
}
} finally {
return "OK"
}
return "FAIL"
}
// EXPECTATIONS JVM_IR
// test.kt:7 box:
// test.kt:8 box:
// test.kt:9 box: i:int=0:int
// test.kt:10 box: i:int=0:int
// test.kt:11 box: i:int=0:int, x:java.lang.String="x":java.lang.String
// test.kt:12 box: i:int=0:int
// test.kt:13 box: i:int=0:int, e:java.lang.Exception=java.lang.RuntimeException
// test.kt:14 box: i:int=0:int, e:java.lang.Exception=java.lang.RuntimeException, y:java.lang.String="y":java.lang.String
// test.kt:15 box: i:int=0:int, e:java.lang.Exception=java.lang.RuntimeException, y:java.lang.String="y":java.lang.String, z:java.lang.String="z":java.lang.String
// test.kt:17 box: i:int=0:int
// test.kt:21 box:
// EXPECTATIONS JS_IR
// test.kt:8 box:
// test.kt:8 box:
// test.kt:8 box:
// test.kt:8 box: i=0:number
// test.kt:10 box: i=0:number
// test.kt:11 box: i=0:number, x="x":kotlin.String
// test.kt:12 box: i=0:number, x="x":kotlin.String
// test.kt:12 box: i=0:number, x="x":kotlin.String
// test.kt:13 box: i=0:number, x="x":kotlin.String, e=kotlin.RuntimeException
// test.kt:14 box: i=0:number, x="x":kotlin.String, e=kotlin.RuntimeException, y="y":kotlin.String
// test.kt:15 box: i=0:number, x="x":kotlin.String, e=kotlin.RuntimeException, y="y":kotlin.String, z="z":kotlin.String
// test.kt:17 box: i=0:number, x="x":kotlin.String, e=kotlin.RuntimeException, y="y":kotlin.String, z="z":kotlin.String
// test.kt:21 box: i=0:number, x="x":kotlin.String, e=kotlin.RuntimeException, y="y":kotlin.String, z="z":kotlin.String
|
expect open class Foo
// MODULE: m2-jvm()()(m1-common)
// FILE: jvm.kt
actual open class Foo {
final override fun <!ACTUAL_WITHOUT_EXPECT!>toString<!>() = "Foo"
}
|
package demo.plot.jfx.plotConfig
import demo.plot.common.model.plotConfig.Density2df
import demo.common.jfx.demoUtils.PlotSpecsDemoWindowJfx
fun main() {
with(Density2df()) {
PlotSpecsDemoWindowJfx(
"Density2df plot",
plotSpecList()
).open()
}
}
|
package org.jetbrains.kotlin.analysis.api.impl.base.test.cases.components.scopeProvider
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.impl.base.test.cases.components.prettyPrintSignature
import org.jetbrains.kotlin.analysis.api.impl.base.test.cases.components.stringRepresentation
import org.jetbrains.kotlin.analysis.api.renderer.declarations.impl.KtDeclarationRendererForSource
import org.jetbrains.kotlin.analysis.api.renderer.declarations.modifiers.renderers.KtRendererKeywordFilter
import org.jetbrains.kotlin.analysis.api.scopes.KtScope
import org.jetbrains.kotlin.analysis.api.scopes.KtTypeScope
import org.jetbrains.kotlin.analysis.api.symbols.DebugSymbolRenderer
import org.jetbrains.kotlin.analysis.test.framework.base.AbstractAnalysisApiBasedTest
import org.jetbrains.kotlin.analysis.test.framework.project.structure.KtTestModule
import org.jetbrains.kotlin.analysis.test.framework.services.expressionMarkerProvider
import org.jetbrains.kotlin.analysis.utils.printer.prettyPrint
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.test.services.TestServices
import org.jetbrains.kotlin.test.services.assertions
import org.jetbrains.kotlin.types.Variance
abstract class AbstractTypeScopeTest : AbstractAnalysisApiBasedTest() {
override fun doTestByMainFile(mainFile: KtFile, mainModule: KtTestModule, testServices: TestServices) {
val expression = testServices.expressionMarkerProvider.getSelectedElementOfType<KtExpression>(mainFile)
analyseForTest(expression) {
val type = expression.getKtType()
?: error("expression $expression is not typable")
val typeScope = type.getTypeScope()
val declaredScopeByTypeScope = typeScope?.getDeclarationScope()
val scopeStringRepresentation = prettyPrint {
appendLine("expression: ${expression.text}")
appendLine("KtType: ${type.render(position = Variance.INVARIANT)}")
appendLine()
appendLine("KtTypeScope:")
appendLine(typeScope?.let { renderForTests(it) } ?: "NO_SCOPE")
appendLine()
appendLine("Declaration Scope:")
appendLine(declaredScopeByTypeScope?.let { renderForTests(it) } ?: "NO_SCOPE")
}
val signaturePretty = prettyPrint {
appendLine("KtTypeScope:")
appendLine(typeScope?.let { prettyPrintForTests(it) } ?: "NO_SCOPE")
appendLine()
appendLine("Declaration Scope:")
appendLine(declaredScopeByTypeScope?.let { prettyPrintForTests(it) } ?: "NO_SCOPE")
}
testServices.assertions.assertEqualsToTestDataFileSibling(scopeStringRepresentation)
testServices.assertions.assertEqualsToTestDataFileSibling(signaturePretty, extension = ".pretty.txt")
}
}
private fun KtAnalysisSession.renderForTests(typeScope: KtTypeScope): String {
val callables = typeScope.getCallableSignatures().toList()
return prettyPrint {
callables.forEach {
appendLine(stringRepresentation(it))
}
}
}
private fun KtAnalysisSession.prettyPrintForTests(typeScope: KtTypeScope): String {
val callables = typeScope.getCallableSignatures().toList()
return prettyPrint {
callables.forEach {
appendLine(prettyPrintSignature(it))
}
}
}
@Suppress("unused")
private fun KtAnalysisSession.renderForTests(scope: KtScope): String {
val callables = scope.getCallableSymbols().toList()
return prettyPrint {
callables.forEach {
appendLine(DebugSymbolRenderer().render(it))
}
}
}
private fun KtAnalysisSession.prettyPrintForTests(scope: KtScope): String {
val callables = scope.getCallableSymbols().toList()
return prettyPrint {
callables.forEach {
appendLine(it.render(renderer))
}
}
}
companion object {
private val renderer = KtDeclarationRendererForSource.WITH_QUALIFIED_NAMES.with {
modifiersRenderer = modifiersRenderer.with {
keywordsRenderer = keywordsRenderer.with { keywordFilter = KtRendererKeywordFilter.NONE }
}
}
}
}
|
var - {}
var f {}
var f :
val foo :
val :
val : Int
val @[a foo = foo
val foo.bar.
val foo.
val @a foo : = bar
val foo.bar
public () {}
() = foo
val f.d.- = f
val foo
get() - |
interface Base<out T> {
fun foo(): T
}
class Derived<T> : Base<T> {
override fun foo(): T = "error" as T
}
fun <T> Derived<T>.bar(): Base<T> = object : Base<T> {
override fun foo(): T = "OK" as T
}
fun <T> test(x: Base<T>): T {
if (x is Derived<*>) {
val y: Base<Any?> = x.bar()
return y.foo() as T
}
return x.foo()
}
fun box(): String {
val x = Derived<String>()
return test(x)
}
|
package org.jetbrains.letsPlot.datamodel.mapping.framework
import org.jetbrains.letsPlot.datamodel.mapping.framework.transform.Transformers
internal open class ItemMapper(item: Item) : Mapper<Item, Item>(item, Item()) {
private lateinit var mySimpleRole: SimpleRoleSynchronizer<Item, Item>
override fun registerSynchronizers(conf: SynchronizersConfiguration) {
conf.add(
Synchronizers.forObservableRole(
this, source.observableChildren, target.observableChildren, createMapperFactory()))
conf.add(
Synchronizers.forObservableRole(
this, source.transformedChildren, Transformers.identityList(),
target.transformedChildren, createMapperFactory()))
conf.add(
Synchronizers.forSingleRole(
this, source.singleChild, target.singleChild, createMapperFactory()))
mySimpleRole = Synchronizers.forSimpleRole(
this, source.children, target.children, createMapperFactory())
conf.add(mySimpleRole)
conf.add(Synchronizers.forPropsTwoWay(source.name, target.name))
}
fun refreshSimpleRole() {
mySimpleRole.refresh()
}
protected open fun createMapperFactory(): MapperFactory<Item, Item> {
return object : MapperFactory<Item, Item> {
override fun createMapper(source: Item): Mapper<out Item, out Item> {
return ItemMapper(source)
}
}
}
} |
package com.maddyhome.idea.vim.key
import com.maddyhome.idea.vim.api.injector
internal fun <T> Node<T>.addLeafs(keys: String, actionHolder: T) {
addLeafs(injector.parser.parseKeys(keys), actionHolder)
}
|
package com.maddyhome.idea.vim.vimscript.model.commands
import com.intellij.vim.annotations.ExCommand
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.OperatorArguments
import com.maddyhome.idea.vim.ex.ExException
import com.maddyhome.idea.vim.ex.ranges.Ranges
import com.maddyhome.idea.vim.vimscript.model.ExecutionResult
/*
* see "h :tabmove"
*/
@ExCommand(command = "tabm[ove]")
public data class TabMoveCommand(val ranges: Ranges, var argument: String) : Command.SingleExecution(ranges, argument) {
override val argFlags: CommandHandlerFlags = flags(RangeFlag.RANGE_OPTIONAL, ArgumentFlag.ARGUMENT_OPTIONAL, Access.READ_ONLY)
override fun processCommand(editor: VimEditor, context: ExecutionContext, operatorArguments: OperatorArguments): ExecutionResult {
if (ranges.size() != 0) {
throw ExException("Range form of tabmove command is not supported. Please use the argument form")
}
val tabService = injector.tabService
val tabCount = tabService.getTabCount(context)
val currentIndex = tabService.getCurrentTabIndex(context)
val index: Int
try {
argument = argument.trim()
if (argument == "+" || argument == "-") {
argument += "1"
}
index = if (argument.startsWith("+")) {
val number = Integer.parseInt(argument.substring(1))
if (number == 0) {
throw ExException("E474: Invalid argument")
}
currentIndex + number
} else if (argument.startsWith("-")) {
val number = Integer.parseInt(argument.substring(1))
if (number == 0) {
throw ExException("E474: Invalid argument")
}
currentIndex - number
} else if (argument == "$" || argument.isBlank()) {
tabCount - 1
} else {
var number = Integer.parseInt(argument)
// it's strange, but it is the way Vim works
if (number > currentIndex) number -= 1
number
}
} catch (e: NumberFormatException) {
throw ExException("E474: Invalid argument")
}
if (index < 0 || index >= tabCount) {
throw ExException("E474: Invalid argument")
}
tabService.moveCurrentTabToIndex(index, context)
return ExecutionResult.Success
}
}
|
@file:Suppress(
"NESTED_CLASS_IN_EXTERNAL_INTERFACE",
)
package web.cssom
import seskar.js.JsValue
import seskar.js.JsVirtual
@JsVirtual
sealed external interface TableLayout {
companion object {
@JsValue("fixed")
val fixed: TableLayout
}
}
|
package node.stream.consumers
import js.iterable.AsyncIterable
import js.promise.await
import node.stream.Readable
import web.blob.Blob as NodeBlob
suspend fun blob(stream: node.ReadableStream): NodeBlob =
blobAsync(
stream
).await()
suspend fun blob(stream: Readable): NodeBlob =
blobAsync(
stream
).await()
suspend fun blob(stream: AsyncIterable<Any?>): NodeBlob =
blobAsync(
stream
).await()
|
OPTIONAL_JVM_INLINE_ANNOTATION
value class S1(val s1: String)
OPTIONAL_JVM_INLINE_ANNOTATION
value class S2(val s2: String)
object X1
object X2
fun <T> test(s1: S1, x: T) {
if (s1.s1 != "OK" && x != X1) throw AssertionError()
}
fun <T> test(s2: S2, x: T) {
if (s2.s2 != "OK" && x != X2) throw AssertionError()
}
fun box(): String {
test(S1("OK"), X1)
test(S2("OK"), X2)
return "OK"
} |
package org.jetbrains.kotlin.js.translate.expression
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.js.translate.utils.BindingUtils
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
class LocalFunctionCollector(val bindingContext: BindingContext) : KtVisitorVoid() {
val functions = mutableSetOf<FunctionDescriptor>()
override fun visitExpression(expression: KtExpression) {
if (expression is KtDeclarationWithBody) {
functions += BindingUtils.getFunctionDescriptor(bindingContext, expression)
}
else {
expression.acceptChildren(this, null)
}
}
override fun visitClassOrObject(classOrObject: KtClassOrObject) {
// skip
}
} |
package org.jetbrains.letsPlot.core.plot.export
import org.jetbrains.letsPlot.commons.geometry.DoubleVector
import org.jetbrains.letsPlot.awt.plot.PlotSvgExport.buildSvgImageFromRawSpecs
import org.jetbrains.letsPlot.core.util.PlotSvgHelper.fetchPlotSizeFromSvg
import org.apache.batik.transcoder.ErrorHandler
import org.apache.batik.transcoder.TranscoderException
import org.apache.batik.transcoder.TranscoderInput
import org.apache.batik.transcoder.TranscoderOutput
import org.apache.batik.transcoder.image.ImageTranscoder
import org.apache.batik.transcoder.image.JPEGTranscoder
import org.apache.batik.transcoder.image.PNGTranscoder
import org.apache.batik.transcoder.image.TIFFTranscoder
import java.awt.Color
import java.io.ByteArrayOutputStream
import java.io.StringReader
object PlotImageExport {
sealed class Format {
val defFileExt: String
get() {
return when (this) {
is PNG -> "png"
is TIFF -> "tiff"
is JPEG -> "jpg"
}
}
override fun toString(): String {
return when (this) {
is PNG -> "PNG"
is TIFF -> "TIFF"
is JPEG -> "JPG(quality=${quality})"
}
}
object PNG : Format()
object TIFF : Format()
class JPEG(val quality: Double = 0.8) : Format()
}
class ImageData(
val bytes: ByteArray,
val plotSize: DoubleVector
)
/**
* @param plotSpec Raw specification of a plot or GGBunch.
* @param format Output image format. PNG, TIFF or JPEG (supports quality parameter).
* @param scalingFactor Factor for output image resolution.
* @param targetDPI A resolution value to put in the output image metadata. NaN - leave the metadata empty.
*/
fun buildImageFromRawSpecs(
plotSpec: MutableMap<String, Any>,
format: Format,
scalingFactor: Double,
targetDPI: Double
): ImageData {
require(scalingFactor >= .1) { "scaling factor is too small: $scalingFactor, must be in range [0.1, 10.0]" }
require(scalingFactor <= 10.0) { "scaling factor is too large: $scalingFactor, must be in range [0.1, 10.0]" }
val transcoder = when (format) {
is Format.TIFF -> TIFFTranscoder()
is Format.PNG -> PNGTranscoder()
is Format.JPEG -> {
JPEGTranscoder().apply {
addTranscodingHint(JPEGTranscoder.KEY_QUALITY, format.quality.toFloat())
}
}
}
transcoder.errorHandler = object : ErrorHandler {
override fun warning(ex: TranscoderException?) {
}
override fun error(ex: TranscoderException?) {
ex?.let { throw it } ?: error("PlotImageExport: empty transcoder exception")
}
override fun fatalError(ex: TranscoderException?) {
ex?.let { throw it } ?: error("PlotImageExport: empty transcoder exception")
}
}
val svg = buildSvgImageFromRawSpecs(plotSpec, useCssPixelatedImageRendering = false) // Batik transcoder supports SVG style, not CSS
val plotSize = fetchPlotSizeFromSvg(svg)
val imageSize = plotSize.mul(scalingFactor)
transcoder.addTranscodingHint(ImageTranscoder.KEY_WIDTH, imageSize.x.toFloat())
transcoder.addTranscodingHint(ImageTranscoder.KEY_HEIGHT, imageSize.y.toFloat())
/*
val dpi = ceil(scalingFactor * 72).toInt()
val millimeterPerDot = 25.4 / dpi
transcoder.addTranscodingHint(
ImageTranscoder.KEY_PIXEL_UNIT_TO_MILLIMETER,
millimeterPerDot.toFloat()
)
*/
if (targetDPI.isFinite()) {
val millimeterPerDot = 25.4 / targetDPI
transcoder.addTranscodingHint(
ImageTranscoder.KEY_PIXEL_UNIT_TO_MILLIMETER,
millimeterPerDot.toFloat()
)
}
transcoder.addTranscodingHint(ImageTranscoder.KEY_BACKGROUND_COLOR, Color.white)
val image = ByteArrayOutputStream()
transcoder.transcode(TranscoderInput(StringReader(svg)), TranscoderOutput(image))
return ImageData(image.toByteArray(), plotSize)
}
}
|
<!DIRECTIVES("HELPERS: REFLECT")!>
open class <!ELEMENT(1)!> {
val x1 = true
}
internal open class A: <!ELEMENT(1)!>() {
val x2 = false
}
annotation class <!ELEMENT(2)!>(val x2: Boolean)
@<!ELEMENT(2)!>(false) internal class B: @<!ELEMENT(2)!>(false) A() {}
@<!ELEMENT(2)!>(true) interface C
fun box(): String? {
val o1 = <!ELEMENT(1)!>()
val o2 = A()
val o3 = B()
if (o1.x1 != true) return null
if (o2.x1 != true || o2.x2 != false || o3.x2 != false || o3.x1 != true) return null
if (!checkAnnotation("B", "<!ELEMENT_VALIDATION(2)!>")) return null
if (!checkAnnotation("C", "<!ELEMENT_VALIDATION(2)!>")) return null
if (!checkSuperClass(B::class, "A")) return null
if (!checkSuperTypeAnnotation(B::class, "A", "<!ELEMENT_VALIDATION(2)!>")) return null
if (!checkClassName(<!ELEMENT(2)!>::class, "<!ELEMENT_VALIDATION(2)!>")) return null
if (!checkClassName(<!ELEMENT(1)!>::class, "<!ELEMENT_VALIDATION(1)!>")) return null
return "OK"
} |
@file:Suppress("DuplicatedCode")
package org.jetbrains.kotlin.fir.expressions.impl
import org.jetbrains.kotlin.KtSourceElement
import org.jetbrains.kotlin.fir.MutableOrEmptyList
import org.jetbrains.kotlin.fir.builder.toMutableOrEmpty
import org.jetbrains.kotlin.fir.expressions.FirAnnotation
import org.jetbrains.kotlin.fir.expressions.FirExpression
import org.jetbrains.kotlin.fir.expressions.FirNamedArgumentExpression
import org.jetbrains.kotlin.fir.expressions.UnresolvedExpressionTypeAccess
import org.jetbrains.kotlin.fir.types.ConeKotlinType
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
internal class FirNamedArgumentExpressionImpl(
override val source: KtSourceElement?,
override var annotations: MutableOrEmptyList<FirAnnotation>,
override var expression: FirExpression,
override val isSpread: Boolean,
override val name: Name,
) : FirNamedArgumentExpression() {
@OptIn(UnresolvedExpressionTypeAccess::class)
override val coneTypeOrNull: ConeKotlinType?
get() = expression.coneTypeOrNull
override fun <R, D> acceptChildren(visitor: FirVisitor<R, D>, data: D) {
annotations.forEach { it.accept(visitor, data) }
expression.accept(visitor, data)
}
override fun <D> transformChildren(transformer: FirTransformer<D>, data: D): FirNamedArgumentExpressionImpl {
transformAnnotations(transformer, data)
expression = expression.transform(transformer, data)
return this
}
override fun <D> transformAnnotations(transformer: FirTransformer<D>, data: D): FirNamedArgumentExpressionImpl {
annotations.transformInplace(transformer, data)
return this
}
override fun replaceConeTypeOrNull(newConeTypeOrNull: ConeKotlinType?) {}
override fun replaceAnnotations(newAnnotations: List<FirAnnotation>) {
annotations = newAnnotations.toMutableOrEmpty()
}
}
|
package com.android.tools.adtui.toolwindow.splittingtabs
import com.intellij.ui.content.Content
/**
* Returns true if this context is in a Splitting Tabs ToolWindow.
*/
internal fun Content.isSplittingTab() = findFirstSplitter() != null
/**
* Returns the "first" [SplittingPanel] child of this content or null if this content is not a Splitting Tabs ToolWindow.
*/
internal fun Content.findFirstSplitter(): SplittingPanel? = SplittingPanel.findFirstSplitter(component)
/**
* Convenience method that handles unlikely `manager == null` condition.
*/
internal fun Content.getPosition(): Int = manager?.getIndexOfContent(this) ?: -1 |
package kotlin.coroutines
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater
import kotlin.coroutines.intrinsics.CoroutineSingletons.*
import kotlin.coroutines.intrinsics.COROUTINE_SUSPENDED
import kotlin.coroutines.jvm.internal.CoroutineStackFrame
@PublishedApi
@SinceKotlin("1.3")
internal actual class SafeContinuation<in T>
internal actual constructor(
private val delegate: Continuation<T>,
initialResult: Any?
) : Continuation<T>, CoroutineStackFrame {
@PublishedApi
internal actual constructor(delegate: Continuation<T>) : this(delegate, UNDECIDED)
public actual override val context: CoroutineContext
get() = delegate.context
@Volatile
private var result: Any? = initialResult
private companion object {
@Suppress("UNCHECKED_CAST")
private val RESULT = AtomicReferenceFieldUpdater.newUpdater<SafeContinuation<*>, Any?>(
SafeContinuation::class.java, Any::class.java as Class<Any?>, "result"
)
}
public actual override fun resumeWith(result: Result<T>) {
while (true) { // lock-free loop
val cur = this.result // atomic read
when {
cur === UNDECIDED -> if (RESULT.compareAndSet(this, UNDECIDED, result.value)) return
cur === COROUTINE_SUSPENDED -> if (RESULT.compareAndSet(this, COROUTINE_SUSPENDED, RESUMED)) {
delegate.resumeWith(result)
return
}
else -> throw IllegalStateException("Already resumed")
}
}
}
@PublishedApi
internal actual fun getOrThrow(): Any? {
var result = this.result // atomic read
if (result === UNDECIDED) {
if (RESULT.compareAndSet(this, UNDECIDED, COROUTINE_SUSPENDED)) return COROUTINE_SUSPENDED
result = this.result // reread volatile var
}
return when {
result === RESUMED -> COROUTINE_SUSPENDED // already called continuation, indicate COROUTINE_SUSPENDED upstream
result is Result.Failure -> throw result.exception
else -> result // either COROUTINE_SUSPENDED or data
}
}
// --- CoroutineStackFrame implementation
public override val callerFrame: CoroutineStackFrame?
get() = delegate as? CoroutineStackFrame
override fun getStackTraceElement(): StackTraceElement? =
null
override fun toString(): String =
"SafeContinuation for $delegate"
}
|
package org.jetbrains.exposed.sql.vendors
import org.jetbrains.exposed.exceptions.UnsupportedByDialectException
import org.jetbrains.exposed.exceptions.throwUnsupportedException
import org.jetbrains.exposed.sql.*
/**
* Provides definitions for all the supported SQL functions.
* By default, definitions from the SQL standard are provided but if a vendor doesn't support a specific function, or it
* is implemented differently, the corresponding function should be overridden.
*/
@Suppress("UnnecessaryAbstractClass")
abstract class FunctionProvider {
// Mathematical functions
/**
* SQL function that returns the next value of the specified sequence.
*
* @param seq Sequence that produces the value.
* @param builder Query builder to append the SQL function to.
*/
open fun nextVal(seq: Sequence, builder: QueryBuilder): Unit = builder {
append(seq.identifier, ".NEXTVAL")
}
/**
* SQL function that generates a random value uniformly distributed between 0 (inclusive) and 1 (exclusive).
*
* **Note:** Some vendors generate values outside this range, or ignore the given seed, check the documentation.
*
* @param seed Optional seed.
*/
open fun random(seed: Int?): String = "RANDOM(${seed?.toString().orEmpty()})"
// String functions
/**
* SQL function that returns the length of [expr], measured in characters, or `null` if [expr] is null.
*
* @param expr String expression to count characters in.
* @param queryBuilder Query builder to append the SQL function to.
*/
open fun <T : String?> charLength(expr: Expression<T>, queryBuilder: QueryBuilder): Unit = queryBuilder {
append("CHAR_LENGTH(", expr, ")")
}
/**
* SQL function that extracts a substring from the specified string expression.
*
* @param expr The expression to extract the substring from.
* @param start The start of the substring.
* @param length The length of the substring.
* @param builder Query builder to append the SQL function to.
*/
open fun <T : String?> substring(
expr: Expression<T>,
start: Expression<Int>,
length: Expression<Int>,
builder: QueryBuilder,
prefix: String = "SUBSTRING"
): Unit = builder {
append(prefix, "(", expr, ", ", start, ", ", length, ")")
}
/**
* SQL function that concatenates multiple string expressions together with a given separator.
*
* @param separator Separator to use.
* @param queryBuilder Query builder to append the SQL function to.
* @param expr String expressions to concatenate.
*/
open fun concat(separator: String, queryBuilder: QueryBuilder, vararg expr: Expression<*>): Unit = queryBuilder {
if (separator == "") {
append("CONCAT(")
} else {
append("CONCAT_WS('", separator, "',")
}
expr.appendTo { +it }
append(")")
}
/**
* SQL function that concatenates strings from a group into a single string.
*
* @param expr Group concat options.
* @param queryBuilder Query builder to append the SQL function to.
*/
open fun <T : String?> groupConcat(expr: GroupConcat<T>, queryBuilder: QueryBuilder): Unit = queryBuilder {
append("GROUP_CONCAT(")
if (expr.distinct) {
append("DISTINCT ")
}
append(expr.expr)
if (expr.orderBy.isNotEmpty()) {
append(" ORDER BY ")
expr.orderBy.appendTo { (expression, sortOrder) ->
currentDialect.dataTypeProvider.precessOrderByClause(this, expression, sortOrder)
}
}
expr.separator?.let {
append(" SEPARATOR '$it'")
}
append(")")
}
/**
* SQL function that returns the index of the first occurrence of the given substring [substring]
* in the string expression [expr]
*
* @param queryBuilder Query builder to append the SQL function to.
* @param expr String expression to find the substring in.
* @param substring: Substring to find
* @return index of the first occurrence of [substring] in [expr] starting from 1
* or 0 if [expr] doesn't contain [substring]
*/
open fun <T : String?> locate(queryBuilder: QueryBuilder, expr: Expression<T>, substring: String) {
throw UnsupportedByDialectException(
"There's no generic SQL for LOCATE. There must be vendor specific implementation.", currentDialect
)
}
// Pattern matching
/**
* Marker interface for the possible pattern matching modes.
*/
interface MatchMode {
/** SQL representation of the mode. */
fun mode(): String
}
/**
* SQL function that checks whether the given string expression matches the given pattern.
*
* **Note:** The `mode` parameter is not supported by all vendors, please check the documentation.
*
* @receiver Expression to check.
* @param pattern Pattern the expression is checked against.
* @param mode Match mode used to check the expression.
*/
open fun <T : String?> Expression<T>.match(pattern: String, mode: MatchMode? = null): Op<Boolean> = with(
SqlExpressionBuilder
) {
this@match.like(pattern)
}
/**
* SQL function that performs a pattern match of a given string expression against a given pattern.
*
* @param expr1 String expression to test.
* @param pattern Pattern to match against.
* @param caseSensitive Whether the matching is case-sensitive or not.
* @param queryBuilder Query builder to append the SQL function to.
*/
open fun <T : String?> regexp(
expr1: Expression<T>,
pattern: Expression<String>,
caseSensitive: Boolean,
queryBuilder: QueryBuilder
): Unit = queryBuilder {
append("REGEXP_LIKE(", expr1, ", ", pattern, ", ")
if (caseSensitive) {
append("'c'")
} else {
append("'i'")
}
append(")")
}
// Date/Time functions
/**
* SQL function that extracts the year field from a given date.
*
* @param expr Expression to extract the year from.
* @param queryBuilder Query builder to append the SQL function to.
*/
open fun <T> year(expr: Expression<T>, queryBuilder: QueryBuilder): Unit = queryBuilder {
append("YEAR(")
append(expr)
append(")")
}
/**
* SQL function that extracts the month field from a given date.
* The returned value is a number between 1 and 12 both inclusive.
*
* @param expr Expression to extract the month from.
* @param queryBuilder Query builder to append the SQL function to.
*/
open fun <T> month(expr: Expression<T>, queryBuilder: QueryBuilder): Unit = queryBuilder {
append("MONTH(")
append(expr)
append(")")
}
/**
* SQL function that extracts the day field from a given date.
* The returned value is a number between 1 and 31 both inclusive.
*
* @param expr Expression to extract the day from.
* @param queryBuilder Query builder to append the SQL function to.
*/
open fun <T> day(expr: Expression<T>, queryBuilder: QueryBuilder): Unit = queryBuilder {
append("DAY(")
append(expr)
append(")")
}
/**
* SQL function that extracts the hour field from a given date.
* The returned value is a number between 0 and 23 both inclusive.
*
* @param expr Expression to extract the hour from.
* @param queryBuilder Query builder to append the SQL function to.
*/
open fun <T> hour(expr: Expression<T>, queryBuilder: QueryBuilder): Unit = queryBuilder {
append("HOUR(")
append(expr)
append(")")
}
/**
* SQL function that extracts the minute field from a given date.
* The returned value is a number between 0 and 59 both inclusive.
*
* @param expr Expression to extract the minute from.
* @param queryBuilder Query builder to append the SQL function to.
*/
open fun <T> minute(expr: Expression<T>, queryBuilder: QueryBuilder): Unit = queryBuilder {
append("MINUTE(")
append(expr)
append(")")
}
/**
* SQL function that extracts the second field from a given date.
* The returned value is a number between 0 and 59 both inclusive.
*
* @param expr Expression to extract the second from.
* @param queryBuilder Query builder to append the SQL function to.
*/
open fun <T> second(expr: Expression<T>, queryBuilder: QueryBuilder): Unit = queryBuilder {
append("SECOND(")
append(expr)
append(")")
}
// Cast functions
/**
* SQL function that casts an expression to a specific type.
*
* @param expr Expression to cast.
* @param type Type to cast the expression to.
* @param builder Query builder to append the SQL function to.
*/
open fun cast(
expr: Expression<*>,
type: IColumnType<*>,
builder: QueryBuilder
): Unit = builder {
append("CAST(", expr, " AS ", type.sqlType(), ")")
}
// Aggregate Functions for Statistics
/**
* SQL function that returns the population standard deviation of the non-null input values,
* or `null` if there are no non-null values.
*
* @param expression Expression from which the population standard deviation is calculated.
* @param queryBuilder Query builder to append the SQL function to.
*/
open fun <T> stdDevPop(expression: Expression<T>, queryBuilder: QueryBuilder): Unit = queryBuilder {
append("STDDEV_POP(", expression, ")")
}
/**
* SQL function that returns the sample standard deviation of the non-null input values,
* or `null` if there are no non-null values.
*
* @param expression Expression from which the sample standard deviation is calculated.
* @param queryBuilder Query builder to append the SQL function to.
*/
open fun <T> stdDevSamp(expression: Expression<T>, queryBuilder: QueryBuilder): Unit = queryBuilder {
append("STDDEV_SAMP(", expression, ")")
}
/**
* SQL function that returns the population variance of the non-null input values (square of the population standard deviation),
* or `null` if there are no non-null values.
*
* @param expression Expression from which the population variance is calculated.
* @param queryBuilder Query builder to append the SQL function to.
*/
open fun <T> varPop(expression: Expression<T>, queryBuilder: QueryBuilder): Unit = queryBuilder {
append("VAR_POP(", expression, ")")
}
/**
* SQL function that returns the sample variance of the non-null input values (square of the sample standard deviation),
* or `null` if there are no non-null values.
*
* @param expression Expression from which the sample variance is calculated.
* @param queryBuilder Query builder to append the SQL function to.
*/
open fun <T> varSamp(expression: Expression<T>, queryBuilder: QueryBuilder): Unit = queryBuilder {
append("VAR_SAMP(", expression, ")")
}
// Array Functions
/**
* SQL function that returns a subarray of elements stored from between [lower] and [upper] bounds (inclusive),
* or `null` if the stored array itself is null.
*
* @param expression Array expression from which the subarray is returned.
* @param lower Lower bounds (inclusive) of a subarray.
* @param upper Upper bounds (inclusive) of a subarray.
* **Note** If either bounds is left `null`, the database will use the stored array's respective lower or upper limit.
* @param queryBuilder Query builder to append the SQL function to.
*/
open fun <T> arraySlice(expression: Expression<T>, lower: Int?, upper: Int?, queryBuilder: QueryBuilder) {
throw UnsupportedByDialectException(
"There's no generic SQL for ARRAY_SLICE. There must be a vendor specific implementation", currentDialect
)
}
// JSON Functions
/**
* SQL function that extracts data from a JSON object at the specified [path], either as a JSON representation or as a scalar value.
*
* @param expression Expression from which to extract JSON subcomponents matched by [path].
* @param path String(s) representing JSON path/keys that match fields to be extracted.
* **Note:** Multiple [path] arguments are not supported by all vendors; please check the documentation.
* @param toScalar If `true`, the extracted result is a scalar or text value; otherwise, it is a JSON object.
* @param jsonType Column type of [expression] to check, if casting to JSONB is required.
* @param queryBuilder Query builder to append the SQL function to.
*/
open fun <T> jsonExtract(
expression: Expression<T>,
vararg path: String,
toScalar: Boolean,
jsonType: IColumnType<*>,
queryBuilder: QueryBuilder
) {
throw UnsupportedByDialectException(
"There's no generic SQL for JSON_EXTRACT. There must be a vendor specific implementation", currentDialect
)
}
/**
* SQL function that checks whether a [candidate] expression is contained within a JSON [target].
*
* @param target JSON expression being searched.
* @param candidate Expression to search for in [target].
* @param path String representing JSON path/keys that match specific fields to search for [candidate].
* **Note:** A [path] argument is not supported by all vendors; please check the documentation.
* @param jsonType Column type of [target] to check, if casting to JSONB is required.
* @param queryBuilder Query builder to append the SQL function to.
*/
open fun jsonContains(
target: Expression<*>,
candidate: Expression<*>,
path: String?,
jsonType: IColumnType<*>,
queryBuilder: QueryBuilder
) {
throw UnsupportedByDialectException(
"There's no generic SQL for JSON_CONTAINS. There must be a vendor specific implementation", currentDialect
)
}
/**
* SQL function that checks whether data exists within a JSON [expression] at the specified [path].
*
* @param expression JSON expression being checked.
* @param path String(s) representing JSON path/keys that match fields to check for existing data.
* **Note:** Multiple [path] arguments are not supported by all vendors; please check the documentation.
* @param optional String representing any optional vendor-specific clause or argument.
* @param jsonType Column type of [expression] to check, if casting to JSONB is required.
* @param queryBuilder Query builder to append the SQL function to.
*/
open fun jsonExists(
expression: Expression<*>,
vararg path: String,
optional: String?,
jsonType: IColumnType<*>,
queryBuilder: QueryBuilder
) {
throw UnsupportedByDialectException(
"There's no generic SQL for JSON_EXISTS. There must be a vendor specific implementation", currentDialect
)
}
// Commands
@Suppress("VariableNaming")
open val DEFAULT_VALUE_EXPRESSION: String = "DEFAULT VALUES"
/**
* Returns the SQL command that inserts a new row into a table.
*
* **Note:** The `ignore` parameter is not supported by all vendors, please check the documentation.
*
* @param ignore Whether to ignore errors or not.
* @param table Table to insert the new row into.
* @param columns Columns to insert the values into.
* @param expr Expression with the values to insert.
* @param transaction Transaction where the operation is executed.
*/
open fun insert(
ignore: Boolean,
table: Table,
columns: List<Column<*>>,
expr: String,
transaction: Transaction
): String {
if (ignore) {
transaction.throwUnsupportedException("There's no generic SQL for INSERT IGNORE. There must be vendor specific implementation.")
}
val autoIncColumn = table.autoIncColumn
val nextValExpression = autoIncColumn?.autoIncColumnType?.nextValExpression?.takeIf { autoIncColumn !in columns }
val isInsertFromSelect = columns.isNotEmpty() && expr.isNotEmpty() && !expr.startsWith("VALUES")
val (columnsToInsert, valuesExpr) = when {
isInsertFromSelect -> columns to expr
nextValExpression != null && columns.isNotEmpty() -> (columns + autoIncColumn) to expr.dropLast(1) + ", $nextValExpression)"
nextValExpression != null -> listOf(autoIncColumn) to "VALUES ($nextValExpression)"
columns.isNotEmpty() -> columns to expr
else -> emptyList<Column<*>>() to DEFAULT_VALUE_EXPRESSION
}
val columnsExpr = columnsToInsert.takeIf { it.isNotEmpty() }?.joinToString(prefix = "(", postfix = ")") { transaction.identity(it) } ?: ""
return "INSERT INTO ${transaction.identity(table)} $columnsExpr $valuesExpr"
}
/**
* Returns the SQL command that updates one or more rows of a table.
*
* @param target Table to update values from.
* @param columnsAndValues Pairs of column to update and values to update with.
* @param limit Maximum number of rows to update.
* @param where Condition that decides the rows to update.
* @param transaction Transaction where the operation is executed.
*/
open fun update(
target: Table,
columnsAndValues: List<Pair<Column<*>, Any?>>,
limit: Int?,
where: Op<Boolean>?,
transaction: Transaction
): String = with(QueryBuilder(true)) {
+"UPDATE "
target.describe(transaction, this)
columnsAndValues.appendTo(this, prefix = " SET ") { (col, value) ->
append("${transaction.identity(col)}=")
registerArgument(col, value)
}
where?.let {
+" WHERE "
+it
}
limit?.let { +" LIMIT $it" }
toString()
}
/**
* Returns the SQL command that updates one or more rows of a join.
*
* @param targets Join to update values from.
* @param columnsAndValues Pairs of column to update and values to update with.
* @param limit Maximum number of rows to update.
* @param where Condition that decides the rows to update.
* @param transaction Transaction where the operation is executed.
*/
open fun update(
targets: Join,
columnsAndValues: List<Pair<Column<*>, Any?>>,
limit: Int?,
where: Op<Boolean>?,
transaction: Transaction
): String = transaction.throwUnsupportedException("UPDATE with a join clause is unsupported")
protected fun QueryBuilder.appendJoinPartForUpdateClause(tableToUpdate: Table, targets: Join, transaction: Transaction) {
+" FROM "
val joinPartsToAppend = targets.joinParts.filter { it.joinPart != tableToUpdate }
if (targets.table != tableToUpdate) {
targets.table.describe(transaction, this)
if (joinPartsToAppend.isNotEmpty()) {
+", "
}
}
joinPartsToAppend.appendTo(this, ", ") {
it.joinPart.describe(transaction, this)
}
+" WHERE "
targets.joinParts.appendTo(this, " AND ") {
it.appendConditions(this)
}
}
/**
* Returns the SQL command that either inserts a new row into a table, or, if insertion would violate a unique constraint,
* first deletes the existing row before inserting a new row.
*
* **Note:** This operation is not supported by all vendors, please check the documentation.
*
* @param table Table to either insert values into or delete values from then insert into.
* @param columns Columns to replace the values in.
* @param expression Expression with the values to use in replace.
* @param transaction Transaction where the operation is executed.
*/
open fun replace(
table: Table,
columns: List<Column<*>>,
expression: String,
transaction: Transaction,
prepared: Boolean = true
): String = transaction.throwUnsupportedException("There's no generic SQL for REPLACE. There must be a vendor specific implementation.")
/**
* Returns the SQL command that either inserts a new row into a table, or updates the existing row if insertion would violate a unique constraint.
*
* **Note:** Vendors that do not support this operation directly implement the standard MERGE USING command.
*
* @param table Table to either insert values into or update values from.
* @param data Pairs of columns to use for insert or update and values to insert or update.
* @param onUpdate List of pairs of specific columns to update and the expressions to update them with.
* @param onUpdateExclude List of specific columns to exclude from updating.
* @param where Condition that determines which rows to update, if a unique violation is found.
* @param transaction Transaction where the operation is executed.
*/
open fun upsert(
table: Table,
data: List<Pair<Column<*>, Any?>>,
onUpdate: List<Pair<Column<*>, Expression<*>>>?,
onUpdateExclude: List<Column<*>>?,
where: Op<Boolean>?,
transaction: Transaction,
vararg keys: Column<*>
): String {
if (where != null) {
transaction.throwUnsupportedException("MERGE implementation of UPSERT doesn't support single WHERE clause")
}
val keyColumns = getKeyColumnsForUpsert(table, *keys)
if (keyColumns.isNullOrEmpty()) {
transaction.throwUnsupportedException("UPSERT requires a unique key or constraint as a conflict target")
}
val dataColumns = data.unzip().first
val autoIncColumn = table.autoIncColumn
val nextValExpression = autoIncColumn?.autoIncColumnType?.nextValExpression
val dataColumnsWithoutAutoInc = autoIncColumn?.let { dataColumns - autoIncColumn } ?: dataColumns
val updateColumns = getUpdateColumnsForUpsert(dataColumns, onUpdateExclude, keyColumns)
return with(QueryBuilder(true)) {
+"MERGE INTO "
table.describe(transaction, this)
+" T USING "
data.appendTo(prefix = "(VALUES (", postfix = ")") { (column, value) ->
registerArgument(column, value)
}
dataColumns.appendTo(prefix = ") S(", postfix = ")") { column ->
append(transaction.identity(column))
}
+" ON "
keyColumns.appendTo(separator = " AND ", prefix = "(", postfix = ")") { column ->
val columnName = transaction.identity(column)
append("T.$columnName=S.$columnName")
}
+" WHEN MATCHED THEN"
appendUpdateToUpsertClause(table, updateColumns, onUpdate, transaction, isAliasNeeded = true)
+" WHEN NOT MATCHED THEN INSERT "
dataColumnsWithoutAutoInc.appendTo(prefix = "(") { column ->
append(transaction.identity(column))
}
nextValExpression?.let {
append(", ${transaction.identity(autoIncColumn)}")
}
dataColumnsWithoutAutoInc.appendTo(prefix = ") VALUES(") { column ->
append("S.${transaction.identity(column)}")
}
nextValExpression?.let {
append(", $it")
}
+")"
toString()
}
}
/**
* Returns the columns to be used in the conflict condition of an upsert statement.
*/
protected fun getKeyColumnsForUpsert(table: Table, vararg keys: Column<*>): List<Column<*>>? {
return keys.toList().ifEmpty {
table.primaryKey?.columns?.toList() ?: table.indices.firstOrNull { it.unique }?.columns
}
}
/** Returns the columns to be used in the update clause of an upsert statement. */
protected fun getUpdateColumnsForUpsert(
dataColumns: List<Column<*>>,
toExclude: List<Column<*>>?,
keyColumns: List<Column<*>>?
): List<Column<*>> {
val updateColumns = toExclude?.let { dataColumns - it.toSet() } ?: dataColumns
return keyColumns?.let { keys ->
updateColumns.filter { it !in keys }.ifEmpty { updateColumns }
} ?: updateColumns
}
/**
* Appends the complete default SQL insert (no ignore) command to [this] QueryBuilder.
*/
protected fun QueryBuilder.appendInsertToUpsertClause(table: Table, data: List<Pair<Column<*>, Any?>>, transaction: Transaction) {
val valuesSql = if (data.isEmpty()) {
""
} else {
data.appendTo(QueryBuilder(true), prefix = "VALUES (", postfix = ")") { (column, value) ->
registerArgument(column, value)
}.toString()
}
val insertStatement = insert(false, table, data.unzip().first, valuesSql, transaction)
+insertStatement
}
/**
* Appends an SQL update command for a derived table (with or without alias identifiers) to [this] QueryBuilder.
*/
protected fun QueryBuilder.appendUpdateToUpsertClause(
table: Table,
updateColumns: List<Column<*>>,
onUpdate: List<Pair<Column<*>, Expression<*>>>?,
transaction: Transaction,
isAliasNeeded: Boolean
) {
+" UPDATE SET "
onUpdate?.appendTo { (columnToUpdate, updateExpression) ->
if (isAliasNeeded) {
val aliasExpression = updateExpression.toString().replace(transaction.identity(table), "T")
append("T.${transaction.identity(columnToUpdate)}=$aliasExpression")
} else {
append("${transaction.identity(columnToUpdate)}=$updateExpression")
}
} ?: run {
updateColumns.appendTo { column ->
val columnName = transaction.identity(column)
if (isAliasNeeded) {
append("T.$columnName=S.$columnName")
} else {
append("$columnName=EXCLUDED.$columnName")
}
}
}
}
/**
* Returns the SQL command that deletes one or more rows of a table.
*
* **Note:** The `ignore` parameter is not supported by all vendors, please check the documentation.
*
* @param ignore Whether to ignore errors or not.
* @param table Table to delete rows from.
* @param where Condition that decides the rows to delete.
* @param limit Maximum number of rows to delete.
* @param transaction Transaction where the operation is executed.
*/
open fun delete(
ignore: Boolean,
table: Table,
where: String?,
limit: Int?,
transaction: Transaction
): String {
if (ignore) {
transaction.throwUnsupportedException("There's no generic SQL for DELETE IGNORE. There must be vendor specific implementation.")
}
return buildString {
append("DELETE FROM ")
append(transaction.identity(table))
if (where != null) {
append(" WHERE ")
append(where)
}
if (limit != null) {
append(" LIMIT ")
append(limit)
}
}
}
/**
* Returns the SQL command that limits and offsets the result of a query.
*
* @param size The limit of rows to return.
* @param offset The number of rows to skip.
* @param alreadyOrdered Whether the query is already ordered or not.
*/
open fun queryLimit(size: Int, offset: Long, alreadyOrdered: Boolean): String = buildString {
append("LIMIT $size")
if (offset > 0) {
append(" OFFSET $offset")
}
}
/**
* Returns the SQL command that obtains information about a statement execution plan.
*
* @param analyze Whether [internalStatement] should also be executed.
* @param options Optional string of comma-separated parameters specific to the database.
* @param internalStatement SQL string representing the statement to get information about.
* @param transaction Transaction where the operation is executed.
*/
open fun explain(
analyze: Boolean,
options: String?,
internalStatement: String,
transaction: Transaction
): String {
return buildString {
append("EXPLAIN ")
if (analyze) {
append("ANALYZE ")
}
options?.let {
appendOptionsToExplain(it)
}
append(internalStatement)
}
}
/** Appends optional parameters to an EXPLAIN query. */
protected open fun StringBuilder.appendOptionsToExplain(options: String) { append("$options ") }
}
|
class U<T>
open class WeatherReport
{
public open var forecast: U<String> = U<String>()
}
open class DerivedWeatherReport() : WeatherReport()
{
public override var forecast: U<String>
get() = super.forecast
set(newv: U<String>) { super.forecast = newv }
} |
package com.android.tools.idea.layoutinspector.tree
import com.android.flags.junit.FlagRule
import com.android.testutils.MockitoCleanerRule
import com.android.testutils.MockitoKt.mock
import com.android.testutils.MockitoKt.whenever
import com.android.tools.adtui.workbench.PropertiesComponentMock
import com.android.tools.idea.flags.StudioFlags
import com.android.tools.idea.layoutinspector.LayoutInspector
import com.android.tools.idea.layoutinspector.model.InspectorModel
import com.android.tools.idea.layoutinspector.pipeline.DisconnectedClient
import com.android.tools.idea.layoutinspector.pipeline.InspectorClient
import com.android.tools.idea.layoutinspector.pipeline.InspectorClient.Capability
import com.android.tools.idea.layoutinspector.pipeline.InspectorClientLauncher
import com.android.tools.idea.testing.registerServiceInstance
import com.google.common.truth.Truth.assertThat
import com.google.common.util.concurrent.MoreExecutors
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.application.ApplicationManager
import com.intellij.testFramework.DisposableRule
import com.intellij.testFramework.ProjectRule
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.mockito.Mockito.doAnswer
class InspectorTreeSettingsTest {
@get:Rule val cleaner = MockitoCleanerRule()
@get:Rule
val recompositionFlagRule =
FlagRule(StudioFlags.DYNAMIC_LAYOUT_INSPECTOR_ENABLE_RECOMPOSITION_COUNTS, true)
@get:Rule val disposableRule = DisposableRule()
@get:Rule val projectRule = ProjectRule()
private val client: InspectorClient = mock()
private val capabilities = mutableSetOf<Capability>()
private var isConnected = false
private lateinit var inspector: LayoutInspector
private lateinit var settings: TreeSettings
@Before
fun before() {
val application = ApplicationManager.getApplication()
application.registerServiceInstance(
PropertiesComponent::class.java,
PropertiesComponentMock(),
disposableRule.disposable
)
settings = InspectorTreeSettings { client }
val model = InspectorModel(projectRule.project)
val mockLauncher = mock<InspectorClientLauncher>()
whenever(mockLauncher.activeClient).thenAnswer { DisconnectedClient }
inspector =
LayoutInspector(
mock(),
mock(),
mock(),
mock(),
mock(),
mockLauncher,
model,
mock(),
settings,
MoreExecutors.directExecutor()
)
doAnswer { capabilities }.whenever(client).capabilities
doAnswer { isConnected }.whenever(client).isConnected
}
@Test
fun testHideSystemNodes() {
testFlag(DEFAULT_HIDE_SYSTEM_NODES, KEY_HIDE_SYSTEM_NODES, Capability.SUPPORTS_SYSTEM_NODES) {
settings.hideSystemNodes
}
}
@Test
fun testComposeAsCallStack() {
testFlag(DEFAULT_COMPOSE_AS_CALLSTACK, KEY_COMPOSE_AS_CALLSTACK, null) {
settings.composeAsCallstack
}
}
@Test
fun testHighlightSemantics() {
assertThat(settings.highlightSemantics).isFalse()
settings.highlightSemantics = true
assertThat(settings.highlightSemantics).isTrue()
settings.highlightSemantics = false
assertThat(settings.highlightSemantics).isFalse()
}
@Test
fun testSupportLines() {
testFlag(DEFAULT_SUPPORT_LINES, KEY_SUPPORT_LINES, null) { settings.supportLines }
}
@Test
fun testShowRecompositions() {
testFlag(
DEFAULT_RECOMPOSITIONS,
KEY_RECOMPOSITIONS,
Capability.SUPPORTS_COMPOSE_RECOMPOSITION_COUNTS
) {
settings.showRecompositions
}
capabilities.add(Capability.SUPPORTS_COMPOSE_RECOMPOSITION_COUNTS)
settings.showRecompositions = true
assertThat(settings.showRecompositions).isTrue()
StudioFlags.DYNAMIC_LAYOUT_INSPECTOR_ENABLE_RECOMPOSITION_COUNTS.override(false)
assertThat(settings.showRecompositions).isFalse()
}
private fun testFlag(
defaultValue: Boolean,
key: String,
controllingCapability: Capability?,
flag: () -> Boolean
) {
capabilities.clear()
// All flags should return their actual value in disconnected state:
isConnected = false
assertThat(flag()).named("Disconnected Default value of: $key").isEqualTo(defaultValue)
val properties = PropertiesComponent.getInstance()
properties.setValue(key, !defaultValue, defaultValue)
assertThat(flag()).named("Disconnected opposite value of: $key").isEqualTo(!defaultValue)
properties.unsetValue(key)
if (controllingCapability == null) {
// Flags without a controlling capability should return their actual value when connected:
isConnected = true
assertThat(flag()).named("Connected (default): $key").isEqualTo(defaultValue)
properties.setValue(key, !defaultValue, defaultValue)
assertThat(flag()).named("Connected (opposite): $key").isEqualTo(!defaultValue)
properties.unsetValue(key)
} else {
// All flags (except supportLines) should return false if connected and their controlling
// capability is off:
isConnected = true
assertThat(flag()).named("Connected without $controllingCapability (default): $key").isFalse()
properties.setValue(key, !defaultValue, defaultValue)
assertThat(flag())
.named("Connected without $controllingCapability (opposite): $key")
.isFalse()
properties.unsetValue(key)
// All flags should return their actual value if connected and their controlling capability is
// on:
capabilities.add(controllingCapability)
assertThat(flag())
.named("Connected with $controllingCapability (default): $key")
.isEqualTo(defaultValue)
properties.setValue(key, !defaultValue, defaultValue)
assertThat(flag())
.named("Connected with $controllingCapability (opposite): $key")
.isEqualTo(!defaultValue)
properties.unsetValue(key)
}
}
}
class EditorTreeSettingsTest {
@Test
fun testSettings() {
val client: InspectorClient = mock()
whenever(client.capabilities).thenReturn(setOf(Capability.SUPPORTS_SYSTEM_NODES))
val settings1 = EditorTreeSettings(client.capabilities)
assertThat(settings1.composeAsCallstack).isEqualTo(DEFAULT_COMPOSE_AS_CALLSTACK)
assertThat(settings1.hideSystemNodes).isEqualTo(DEFAULT_HIDE_SYSTEM_NODES)
assertThat(settings1.highlightSemantics).isEqualTo(DEFAULT_HIGHLIGHT_SEMANTICS)
assertThat(settings1.supportLines).isEqualTo(DEFAULT_SUPPORT_LINES)
settings1.hideSystemNodes = !DEFAULT_HIDE_SYSTEM_NODES
settings1.supportLines = !DEFAULT_SUPPORT_LINES
assertThat(settings1.supportLines).isEqualTo(!DEFAULT_SUPPORT_LINES)
assertThat(settings1.hideSystemNodes).isEqualTo(!DEFAULT_HIDE_SYSTEM_NODES)
whenever(client.capabilities).thenReturn(setOf())
val settings2 = EditorTreeSettings(client.capabilities)
assertThat(settings2.hideSystemNodes).isEqualTo(false)
assertThat(settings2.supportLines).isEqualTo(DEFAULT_SUPPORT_LINES)
}
}
|
@file:Suppress(
"CANNOT_CHECK_FOR_EXTERNAL_INTERFACE",
)
package typescript
import kotlin.contracts.contract
fun isPropertyAssignment(node: Node): Boolean {
contract {
returns(true) implies (node is PropertyAssignment)
}
return typescript.raw.isPropertyAssignment(node)
}
|
package com.android.tools.idea.editors.liveedit.ui
import com.android.ddmlib.AndroidDebugBridge
import com.android.ddmlib.IDevice
import com.android.tools.adtui.compose.ComposeStatus
import com.android.tools.adtui.compose.InformationPopup
import com.android.tools.adtui.compose.InformationPopupImpl
import com.android.tools.adtui.compose.IssueNotificationAction
import com.android.tools.idea.actions.BrowserHelpAction
import com.android.tools.idea.editors.literals.LiveEditService
import com.android.tools.idea.editors.literals.LiveEditService.Companion.LiveEditTriggerMode.ON_SAVE
import com.android.tools.idea.editors.liveedit.LiveEditApplicationConfiguration
import com.android.tools.idea.editors.sourcecode.isKotlinFileType
import com.android.tools.idea.run.deployment.liveedit.LiveEditProjectMonitor
import com.android.tools.idea.run.deployment.liveedit.LiveEditStatus
import com.android.tools.idea.run.deployment.liveedit.LiveEditUpdateException
import com.android.tools.idea.streaming.RUNNING_DEVICES_TOOL_WINDOW_ID
import com.android.tools.idea.streaming.SERIAL_NUMBER_KEY
import com.intellij.ide.DataManager
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.actionSystem.DataProvider
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.openapi.actionSystem.PlatformCoreDataKeys
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.actionSystem.RightAlignedToolbarAction
import com.intellij.openapi.actionSystem.Separator
import com.intellij.openapi.actionSystem.ex.ActionUtil
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.keymap.KeymapManager
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiDocumentManager
import com.intellij.ui.components.AnActionLink
import com.intellij.util.ui.JBUI
import java.awt.Insets
import java.util.Collections
internal fun getStatusInfo(project: Project, dataContext: DataContext): LiveEditStatus {
val liveEditService = LiveEditService.getInstance(project)
val editor: Editor? = dataContext.getData(CommonDataKeys.EDITOR)
if (editor != null) {
val psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.document)
if (!project.isInitialized ||
psiFile == null ||
!psiFile.virtualFile.isKotlinFileType() ||
!editor.document.isWritable) {
return LiveEditStatus.Disabled
}
val insetDevices = LiveEditIssueNotificationAction.deviceMap[project]?.devices()?.let { HashSet<IDevice>(it) } ?: Collections.emptySet()
return liveEditService.devices()
.filter { it !in insetDevices }
.map { liveEditService.editStatus(it) }
.fold(LiveEditStatus.Disabled, LiveEditStatus::merge)
}
else {
val device = LiveEditIssueNotificationAction.deviceMap[project]?.device(dataContext) ?: return LiveEditStatus.Disabled
return liveEditService.editStatus(device)
}
}
/**
* Creates an [InformationPopup]. The given [dataContext] will be used by the popup to query for
* things like the current editor.
*/
internal fun defaultCreateInformationPopup(
project: Project,
dataContext: DataContext,
): InformationPopup? {
return getStatusInfo(project, dataContext).let { status ->
if (shouldHideImpl(status, dataContext)) {
return@let null
}
val link = status.actionId?.let {
val id = when (it) {
REFRESH_ACTION_ID -> if (LiveEditApplicationConfiguration.getInstance().leTriggerMode == ON_SAVE) LiveEditService.PIGGYBACK_ACTION_ID else MANUAL_LIVE_EDIT_ACTION_ID
else -> it
}
val action = ActionManager.getInstance().getAction(it)
val shortcut = KeymapManager.getInstance()?.activeKeymap?.getShortcuts(id)?.toList()?.firstOrNull()
AnActionLink("${action.templateText}${if (shortcut != null) " (${KeymapUtil.getShortcutText(shortcut)})" else ""}", action)
}
val upgradeAssistant =
if (status.title == LiveEditStatus.OutOfDate.title &&
status.description.contains(LiveEditUpdateException.Error.UNSUPPORTED_BUILD_LIBRARY_DESUGAR.message))
AnActionLink("View Upgrade Assistant", object : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
ActionUtil.invokeAction(
ActionManager.getInstance().getAction("AgpUpgrade"),
dataContext,
RUNNING_DEVICES_TOOL_WINDOW_ID,
null,
null)
}
})
else
null
val configureLiveEditAction = ConfigureLiveEditAction()
return@let InformationPopupImpl(
null,
if (LiveEditService.isLeTriggerManual()) status.descriptionManualMode ?: status.description else status.description,
emptyList(),
listOfNotNull(
link,
upgradeAssistant,
AnActionLink("View Docs", BrowserHelpAction("Live Edit Docs", "https://developer.android.com/jetpack/compose/tooling/iterative-development#live-edit")),
object: AnActionLink("Configure Live Edit", configureLiveEditAction) {
}.apply {
setDropDownLinkIcon()
configureLiveEditAction.parentComponent = this
}
)
).also { newPopup ->
// Register the data provider of the popup to be the same as the one used in the toolbar.
// This allows for actions within the popup to query for things like the Editor even when
// the Editor is not directly related to the popup.
DataManager.registerDataProvider(newPopup.popupComponent) { dataId ->
if (PlatformCoreDataKeys.BGT_DATA_PROVIDER.`is`(dataId)) {
DataProvider { dataContext.getData(it) }
}
else {
dataContext.getData(dataId)
}
}
configureLiveEditAction.parentDisposable = newPopup
}
}
}
/**
* An interface to exposed to external modules to implement in order to receive device serials and IDevices associated with those serials.
*/
interface DeviceGetter {
fun serial(dataContext: DataContext): String?
fun device(dataContext: DataContext): IDevice?
fun devices(): List<IDevice>
}
/**
* Action that reports the current state of Live Edit.
*
* This action reports:
* - State of Live Edit or preview out of date if Live Edit is disabled
* - Syntax errors
*/
class LiveEditIssueNotificationAction(
createInformationPopup: (Project, DataContext) -> InformationPopup? =
::defaultCreateInformationPopup
) : IssueNotificationAction(::getStatusInfo, createInformationPopup) {
companion object {
val deviceMap = HashMap<Project, DeviceGetter>()
fun registerProject(project: Project, deviceGetter: DeviceGetter) {
deviceMap[project] = deviceGetter
}
fun unregisterProject(project: Project) {
deviceMap.remove(project)
}
}
override fun margins(): Insets {
return JBUI.insets(2)
}
override fun shouldHide(status: ComposeStatus, dataContext: DataContext): Boolean {
return shouldHideImpl(status, dataContext)
}
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.EDT
}
}
private fun shouldHideImpl(status: ComposeStatus, dataContext: DataContext): Boolean {
if (status != LiveEditStatus.Disabled) {
// Always show when it's an active status, even if error.
return false
}
val toolWindowId = dataContext.getData(PlatformDataKeys.TOOL_WINDOW)
if (toolWindowId == null || toolWindowId.id != RUNNING_DEVICES_TOOL_WINDOW_ID) {
return true
}
// Only show for running devices tool window.
val project = dataContext.getData(CommonDataKeys.PROJECT) ?: return true
val serial = dataContext.getData(SERIAL_NUMBER_KEY) ?: return true
val device = AndroidDebugBridge.getBridge()?.devices?.find { it.serialNumber == serial } ?: return true
// Hide status when the device doesn't support Live Edit.
if (!LiveEditProjectMonitor.supportLiveEdits(device)) {
return true
}
// Hide status when the project isn't Compose.
if (!LiveEditService.usesCompose(project)) {
return true
}
// Hide status when Live Edit is already enabled (note: status is Disabled if we get to this part of the code).
return LiveEditApplicationConfiguration.getInstance().isLiveEdit
}
/**
* [DefaultActionGroup] that shows the notification chip and the [RedeployAction] button when applicable.
*/
class LiveEditNotificationGroup :
DefaultActionGroup(
"Live Edit Notification Actions",
listOf(LiveEditIssueNotificationAction(), RedeployAction(), Separator.getInstance()),
), RightAlignedToolbarAction
|
package com.android.tools.idea.gradle.model.impl
import com.android.ide.common.gradle.Component
import com.android.tools.idea.gradle.model.IdeUnresolvedJavaLibrary
import java.io.File
import java.io.Serializable
/**
* The implementation of IdeLibrary for Java libraries.
**/
data class IdeJavaLibraryImpl(
override val artifactAddress: String,
override val component: Component?,
override val name: String,
override val artifact: File,
override val srcJar: File?, // AGP 8.1.0-alpha08 or later only
override val docJar: File?, // AGP 8.1.0-alpha08 or later only
override val samplesJar: File? // AGP 8.1.0-alpha08 or later only
) : IdeUnresolvedJavaLibrary, Serializable {
// Used for serialization by the IDE.
internal constructor() : this(
artifactAddress = "",
component = null,
name = "",
artifact = File(""),
srcJar = null,
docJar = null,
samplesJar = null
)
override val lintJar: File?
get() = null
}
|
package com.android.tools.idea.actions
import com.android.tools.idea.uibuilder.surface.NlDesignSurface
import com.android.tools.idea.uibuilder.surface.ScreenViewProvider
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.ToggleAction
import org.jetbrains.android.util.AndroidBundle.message
/** [ToggleAction] to that sets an specific [ScreenViewProvider] to the [NlDesignSurface]. */
class SetScreenViewProviderAction(
private val sceneModeProvider: ScreenViewProvider,
private val designSurface: NlDesignSurface
) :
ToggleAction(
sceneModeProvider.displayName,
message("android.layout.screenview.action.description", sceneModeProvider.displayName),
null
) {
override fun isSelected(e: AnActionEvent) = designSurface.screenViewProvider == sceneModeProvider
override fun setSelected(e: AnActionEvent, state: Boolean) =
designSurface.setScreenViewProvider(sceneModeProvider, true)
}
|
var result = ""
fun sideEffecting(): Int {
result += "OK"
return 123
}
class C(val x: Int)
val a: C? = C(123)
val b: C? = null
fun box(): String {
if (a?.x != sideEffecting()) return "fail cmp 1"
// RHS not evaluated because `b` is null, might be a bug:
if (b?.x == sideEffecting()) return "fail cmp 2"
return result
}
|
package org.jetbrains.kotlin.commonizer.cir
import org.jetbrains.kotlin.commonizer.mergedtree.CirClassifierIndex
import org.jetbrains.kotlin.commonizer.mergedtree.CirProvidedClassifiers
import org.jetbrains.kotlin.commonizer.mergedtree.findClass
internal interface CirSupertypesResolver {
/**
* Resolves all *declared* supertypes (not their transitive closure)
*/
fun supertypes(type: CirClassType): Set<CirClassType>
}
/**
* Very simple and pragmatic implementation of [CirSupertypesResolver]
* Limitations:
* - Will not resolve parameterized types
* - Supertypes from dependencies are resolved in a "best effort" manner.
*/
internal class SimpleCirSupertypesResolver(
private val classifiers: CirClassifierIndex,
private val dependencies: CirProvidedClassifiers,
) : CirSupertypesResolver {
override fun supertypes(type: CirClassType): Set<CirClassType> {
classifiers.findClass(type.classifierId)?.let { classifier ->
return supertypesFromCirClass(type, classifier)
}
dependencies.classifier(type.classifierId)?.let { classifier ->
if (classifier is CirProvided.Class) {
return dependencies.supertypesFromProvidedClass(type, classifier)
}
}
return emptySet()
}
private fun supertypesFromCirClass(type: CirClassType, classifier: CirClass): Set<CirClassType> {
return classifier.supertypes.filterIsInstance<CirClassType>()
.mapNotNull { superType -> buildSupertypeFromClassifierSupertype(type, superType) }
.toSet()
}
private fun CirProvidedClassifiers.supertypesFromProvidedClass(type: CirClassType, classifier: CirProvided.Class): Set<CirClassType> {
return classifier.supertypes.filterIsInstance<CirProvided.ClassType>()
.mapNotNull { superType -> superType.toCirClassTypeOrNull(this) }
.mapNotNull { superType -> buildSupertypeFromClassifierSupertype(type, superType) }
.toSet()
}
private fun buildSupertypeFromClassifierSupertype(type: CirClassType, supertype: CirClassType): CirClassType? {
if (type.arguments.isEmpty() && supertype.arguments.isEmpty()) {
return supertype.makeNullableIfNecessary(type.isMarkedNullable)
}
return null
}
}
|
package com.maddyhome.idea.vim.action.motion.search
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.CommandFlags
import com.maddyhome.idea.vim.command.OperatorArguments
import com.maddyhome.idea.vim.handler.VimActionHandler
import com.maddyhome.idea.vim.helper.enumSetOf
import java.util.*
@CommandOrMotion(keys = ["gD", "gd", "<C-]>"], modes = [Mode.NORMAL, Mode.VISUAL])
public class GotoDeclarationAction : VimActionHandler.SingleExecution() {
override val type: Command.Type = Command.Type.OTHER_READONLY
override val flags: EnumSet<CommandFlags> = enumSetOf(CommandFlags.FLAG_SAVE_JUMP)
override fun execute(
editor: VimEditor,
context: ExecutionContext,
cmd: Command,
operatorArguments: OperatorArguments,
): Boolean {
injector.jumpService.saveJumpLocation(editor)
injector.actionExecutor.executeAction("GotoDeclaration", context)
return true
}
}
|
package org.jetbrains.letsPlot.core.spec.transform
class SpecSelector private constructor(builder: Builder) {
private val myKey: String
init {
myKey = builder.mySelectorParts!!.joinToString("|")
}
fun with(): Builder {
return Builder(myKey.split("\\|".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray())
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false
val that = other as SpecSelector?
return myKey == that!!.myKey
}
override fun hashCode(): Int {
return listOf(myKey).hashCode()
}
override fun toString(): String {
return "SpecSelector{" +
"myKey='" + myKey + '\''.toString() +
'}'.toString()
}
class Builder {
internal var mySelectorParts: MutableList<String>? = null
internal constructor() {
mySelectorParts = ArrayList()
mySelectorParts!!.add("/") // root
}
internal constructor(selectorParts: Array<String>) {
mySelectorParts = ArrayList()
for (s in selectorParts) {
mySelectorParts!!.add(s)
}
}
fun part(s: String): Builder {
mySelectorParts!!.add(s)
return this
}
fun build(): SpecSelector {
return SpecSelector(this)
}
}
companion object {
fun root(): SpecSelector {
return Builder().build()
}
fun of(vararg parts: String): SpecSelector {
//Builder builder = new Builder();
//for (String part : parts) {
// builder.part(part);
//}
//return builder.build();
return from(listOf(*parts))
}
fun from(parts: Iterable<String>): SpecSelector {
val builder = Builder()
val iterator = parts.iterator()
while (iterator.hasNext()) {
val part = iterator.next()
builder.part(part)
}
return builder.build()
}
}
}
|
package org.jetbrains.kotlin.analysis.api.descriptors.symbols.descriptorBased
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.base.KtContextReceiver
import org.jetbrains.kotlin.analysis.api.descriptors.Fe10AnalysisContext
import org.jetbrains.kotlin.analysis.api.descriptors.symbols.calculateHashCode
import org.jetbrains.kotlin.analysis.api.descriptors.symbols.descriptorBased.base.*
import org.jetbrains.kotlin.analysis.api.descriptors.symbols.isEqualTo
import org.jetbrains.kotlin.analysis.api.descriptors.symbols.pointers.KtFe10DescSamConstructorSymbolPointer
import org.jetbrains.kotlin.analysis.api.descriptors.symbols.pointers.KtFe10NeverRestoringSymbolPointer
import org.jetbrains.kotlin.analysis.api.lifetime.withValidityAssertion
import org.jetbrains.kotlin.analysis.api.symbols.*
import org.jetbrains.kotlin.analysis.api.symbols.pointers.KtPsiBasedSymbolPointer
import org.jetbrains.kotlin.analysis.api.symbols.pointers.KtSymbolPointer
import org.jetbrains.kotlin.analysis.api.types.KtType
import org.jetbrains.kotlin.name.CallableId
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.resolve.calls.inference.returnTypeOrNothing
import org.jetbrains.kotlin.resolve.descriptorUtil.isExtension
import org.jetbrains.kotlin.resolve.sam.SamConstructorDescriptor
import org.jetbrains.kotlin.resolve.sam.SamTypeAliasConstructorDescriptor
internal class KtFe10DescSamConstructorSymbol(
override val descriptor: SamConstructorDescriptor,
override val analysisContext: Fe10AnalysisContext
) : KtSamConstructorSymbol(), KtFe10DescSymbol<SamConstructorDescriptor> {
private val expandedDescriptor: SamConstructorDescriptor
get() = (descriptor as? SamTypeAliasConstructorDescriptor)?.expandedConstructorDescriptor ?: descriptor
override val name: Name
get() = withValidityAssertion { expandedDescriptor.name }
override val valueParameters: List<KtValueParameterSymbol>
get() = withValidityAssertion { descriptor.valueParameters.map { KtFe10DescValueParameterSymbol(it, analysisContext) } }
override val hasStableParameterNames: Boolean
get() = withValidityAssertion { descriptor.ktHasStableParameterNames }
override val callableIdIfNonLocal: CallableId?
get() = withValidityAssertion { expandedDescriptor.callableIdIfNotLocal }
override val returnType: KtType
get() = withValidityAssertion { descriptor.returnTypeOrNothing.toKtType(analysisContext) }
override val receiverParameter: KtReceiverParameterSymbol?
get() = withValidityAssertion { descriptor.extensionReceiverParameter?.toKtReceiverParameterSymbol(analysisContext) }
override val contextReceivers: List<KtContextReceiver>
get() = withValidityAssertion { descriptor.createContextReceivers(analysisContext) }
override val isExtension: Boolean
get() = withValidityAssertion { descriptor.isExtension }
override val origin: KtSymbolOrigin
get() = withValidityAssertion { expandedDescriptor.getSymbolOrigin(analysisContext) }
override val typeParameters: List<KtTypeParameterSymbol>
get() = withValidityAssertion { descriptor.typeParameters.map { KtFe10DescTypeParameterSymbol(it, analysisContext) } }
context(KtAnalysisSession)
override fun createPointer(): KtSymbolPointer<KtSamConstructorSymbol> = withValidityAssertion {
KtPsiBasedSymbolPointer.createForSymbolFromSource<KtSamConstructorSymbol>(this)?.let {
return it
}
val classId = descriptor.baseDescriptorForSynthetic.classId
if (classId != null) {
return KtFe10DescSamConstructorSymbolPointer(classId)
}
return KtFe10NeverRestoringSymbolPointer()
}
override fun equals(other: Any?): Boolean = isEqualTo(other)
override fun hashCode(): Int = calculateHashCode()
} |
package org.jetbrains.kotlin.generators.arguments
import org.jetbrains.kotlin.cli.common.arguments.*
import org.jetbrains.kotlin.config.CompilerSettings
import org.jetbrains.kotlin.config.JpsPluginSettings
import org.jetbrains.kotlin.utils.Printer
import java.io.File
import kotlin.reflect.*
import kotlin.reflect.full.declaredMemberProperties
import kotlin.reflect.full.hasAnnotation
import kotlin.reflect.full.superclasses
private val CLASSES_TO_PROCESS: List<KClass<*>> = listOf(
JpsPluginSettings::class,
CompilerSettings::class,
K2MetadataCompilerArguments::class,
K2NativeCompilerArguments::class,
K2JSDceArguments::class,
K2JSCompilerArguments::class,
K2JVMCompilerArguments::class,
)
private val PACKAGE_TO_DIR_MAPPING: Map<Package, File> = mapOf(
K2JVMCompilerArguments::class.java.`package` to File("compiler/cli/cli-common/gen"),
JpsPluginSettings::class.java.`package` to File("jps/jps-common/gen"),
)
fun generateCompilerArgumentsCopy(withPrinterToFile: (targetFile: File, Printer.() -> Unit) -> Unit) {
val processed = mutableSetOf<KClass<*>>()
for (klass in CLASSES_TO_PROCESS) {
generateRec(klass, withPrinterToFile, processed)
}
}
private fun generateRec(
klass: KClass<*>,
withPrinterToFile: (targetFile: File, Printer.() -> Unit) -> Unit,
processed: MutableSet<KClass<*>>,
) {
if (!processed.add(klass)) return
val klassName = klass.simpleName!!
val fqn = klass.qualifiedName!!
val `package` = klass.java.`package`
val destDir = PACKAGE_TO_DIR_MAPPING[`package`]!!.resolve(`package`.name.replace('.', '/'))
withPrinterToFile(destDir.resolve(klassName + "CopyGenerated.kt")) {
println(
"""
@file:Suppress("unused", "DuplicatedCode")
// DO NOT EDIT MANUALLY!
// Generated by generators/tests/org/jetbrains/kotlin/generators/arguments/GenerateCompilerArgumentsCopy.kt
// To regenerate run 'generateCompilerArgumentsCopy' task
package ${`package`.name}
""".trimIndent()
)
fun isSupportedImmutable(type: KType): Boolean {
val classifier: KClassifier = type.classifier!!
return when {
classifier is KClass<*> && classifier == List::class -> isSupportedImmutable(type.arguments.single().type!!)
classifier == InternalArgument::class -> true
classifier == Boolean::class -> true
classifier == Int::class -> true
classifier == String::class -> true
else -> false
}
}
println("@OptIn(org.jetbrains.kotlin.utils.IDEAPluginsCompatibilityAPI::class)")
println("fun copy$klassName(from: $klassName, to: $klassName): $klassName {")
withIndent {
val superClasses: List<KClass<*>> = klass.superclasses.filterNot { it.java.isInterface }
check(superClasses.size < 2) {
"too many super classes in $klass: ${superClasses.joinToString()}"
}
val superKlass = superClasses.singleOrNull()
if (superKlass != null && superKlass != Freezable::class) {
generateRec(superKlass, withPrinterToFile, processed)
if (superKlass.java.`package` != `package`) {
print("${superKlass.java.`package`.name}.")
}
println("copy${superKlass.simpleName}(from, to)")
println()
}
val properties = collectProperties(klass, false)
for (property in properties.filter { klass.declaredMemberProperties.contains(it) }) {
val type = property.returnType
val classifier: KClassifier = type.classifier!!
when {
// Please add cases on the go
// Please add a test to GenerateCompilerArgumentsCopyTest if the change is not trivial
classifier is KClass<*> && classifier.java.isArray -> {
val arrayElementType = type.arguments.single().type!!
val nullableMarker = if (type.isMarkedNullable) "?" else ""
when (arrayElementType.classifier) {
String::class -> {
deprecatePropertyIfNecessary(property)
println("to.${property.name} = from.${property.name}${nullableMarker}.copyOf()")
}
else -> error("Unsupported array element type $arrayElementType (member '${property.name}' of $fqn)")
}
}
isSupportedImmutable(type) -> {
deprecatePropertyIfNecessary(property)
println("to.${property.name} = from.${property.name}")
}
else -> error("Unsupported type to copy: $type (member '${property.name}' of $fqn)")
}
}
println()
println("return to")
}
println("}")
}
}
private fun Printer.deprecatePropertyIfNecessary(property: KProperty1<*, *>) {
if (property.hasAnnotation<Deprecated>()) {
println("@Suppress(\"DEPRECATION\")")
}
}
fun main() {
generateCompilerArgumentsCopy(::getPrinterToFile)
} |
import kotlin.test.*
interface A<T> {
fun foo(t: T): String
}
interface B {
fun foo(t: Int) = "B"
}
class Z : B
class Z1 : A<Int>, B by Z()
fun box(): String {
val z1 = Z1()
val z1a: A<Int> = z1
val z1b: B = z1
return when {
z1.foo( 0) != "B" -> "Fail #1"
z1a.foo( 0) != "B" -> "Fail #2"
z1b.foo( 0) != "B" -> "Fail #3"
else -> "OK"
}
}
|
package org.jetbrains.letsPlot.core.plot.base.geom
import org.jetbrains.letsPlot.commons.geometry.DoubleVector
import org.jetbrains.letsPlot.core.plot.base.*
import org.jetbrains.letsPlot.core.plot.base.aes.AesScaling
import org.jetbrains.letsPlot.core.plot.base.geom.util.GeomHelper
import org.jetbrains.letsPlot.core.plot.base.geom.util.HintColorUtil
import org.jetbrains.letsPlot.core.plot.base.geom.util.TextUtil
import org.jetbrains.letsPlot.core.plot.base.tooltip.GeomTargetCollector
import org.jetbrains.letsPlot.core.plot.base.tooltip.TipLayoutHint
import org.jetbrains.letsPlot.core.plot.base.render.LegendKeyElementFactory
import org.jetbrains.letsPlot.core.plot.base.render.SvgRoot
import org.jetbrains.letsPlot.core.plot.base.render.svg.MultilineLabel
import org.jetbrains.letsPlot.core.plot.base.render.svg.Text
import org.jetbrains.letsPlot.core.commons.data.SeriesUtil
import org.jetbrains.letsPlot.datamodel.svg.dom.SvgGElement
import org.jetbrains.letsPlot.datamodel.svg.dom.SvgUtils
open class TextGeom : GeomBase() {
var formatter: ((Any) -> String)? = null
var naValue = DEF_NA_VALUE
var sizeUnit: String? = null
override val legendKeyElementFactory: LegendKeyElementFactory
get() = TextLegendKeyElementFactory()
override fun buildIntern(
root: SvgRoot,
aesthetics: Aesthetics,
pos: PositionAdjustment,
coord: CoordinateSystem,
ctx: GeomContext
) {
val helper = GeomHelper(pos, coord, ctx)
val targetCollector = getGeomTargetCollector(ctx)
val colorsByDataPoint = HintColorUtil.createColorMarkerMapper(GeomKind.TEXT, ctx)
val aesBoundsCenter = coord.toClient(ctx.getAesBounds())?.center
for (p in aesthetics.dataPoints()) {
val x = p.x()
val y = p.y()
val text = toString(p.label())
if (SeriesUtil.allFinite(x, y) && text.isNotEmpty()) {
val point = DoubleVector(x!!, y!!)
val loc = helper.toClient(point, p)
if (loc == null) continue
// Adapt point size to plot 'grid step' if necessary (i.e. in correlation matrix).
val sizeUnitRatio = when (sizeUnit) {
null -> 1.0
else -> getSizeUnitRatio(point, coord, sizeUnit!!)
}
val g = buildTextComponent(p, loc, text, sizeUnitRatio, ctx, aesBoundsCenter)
root.add(g)
// The geom_text tooltip is similar to the geom_tile:
// it looks better when the text is on a tile in corr_plot (but the color will be different from the geom_tile tooltip)
targetCollector.addPoint(
p.index(),
loc,
sizeUnitRatio * AesScaling.textSize(p) / 2,
GeomTargetCollector.TooltipParams(
markerColors = colorsByDataPoint(p)
),
TipLayoutHint.Kind.CURSOR_TOOLTIP
)
}
}
}
open fun buildTextComponent(
p: DataPointAesthetics,
location: DoubleVector,
text: String,
sizeUnitRatio: Double,
ctx: GeomContext,
boundsCenter: DoubleVector?
): SvgGElement {
val label = MultilineLabel(text)
TextUtil.decorate(label, p, sizeUnitRatio, applyAlpha = true)
val hAnchor = TextUtil.hAnchor(p, location, boundsCenter)
label.setHorizontalAnchor(hAnchor)
val fontSize = TextUtil.fontSize(p, sizeUnitRatio)
val textHeight = TextUtil.measure(text, p, ctx, sizeUnitRatio).y
//val textHeight = TextHelper.lineheight(p, sizeUnitRatio) * (label.linesCount() - 1) + fontSize
val yPosition = when (TextUtil.vAnchor(p, location, boundsCenter)) {
Text.VerticalAnchor.TOP -> location.y + fontSize * 0.7
Text.VerticalAnchor.BOTTOM -> location.y - textHeight + fontSize
Text.VerticalAnchor.CENTER -> location.y - textHeight / 2 + fontSize * 0.8
}
val textLocation = DoubleVector(location.x, yPosition)
label.moveTo(textLocation)
val g = SvgGElement()
g.children().add(label.rootGroup)
SvgUtils.transformRotate(g, TextUtil.angle(p), location.x, location.y)
return g
}
private fun toString(label: Any?): String {
return when {
label == null -> naValue
formatter != null -> formatter!!.invoke(label)
else -> label.toString()
}
}
companion object {
const val DEF_NA_VALUE = "n/a"
const val HANDLES_GROUPS = false
// Current implementation works for label_format ='.2f'
// and values between -1.0 and 1.0.
private const val BASELINE_TEXT_WIDTH = 6.0
private fun getSizeUnitRatio(
p: DoubleVector,
coord: CoordinateSystem,
axis: String
): Double {
val unitSquareSize = coord.unitSize(p)
val unitSize = when (axis.lowercase()) {
"x" -> unitSquareSize.x
"y" -> unitSquareSize.y
else -> error("Size unit value must be either 'x' or 'y', but was $axis.")
}
return unitSize / BASELINE_TEXT_WIDTH
}
}
}
// How 'just' and 'angle' works together
// https://stackoverflow.com/questions/7263849/what-do-hjust-and-vjust-do-when-making-a-plot-using-ggplot |
import kotlin.reflect.KClass
annotation class Ann(val kClass: KClass<*>)
class A {
@Ann(EmptyList::class)
fun foo() {}
object EmptyList
}
|
class AtomicRef<T>(val value: T)
inline fun <F : Segment<F>> AtomicRef<F>.findSegmentAndMoveForward(createNewSegment: (prev: F?) -> F) = null
interface Queue<Q> {
val tail: AtomicRef<OneElementSegment<Q>>
fun enqueue(element: Q) {
// F <: Segment<F> from upper bound
// F <: OneElementSegment<Segment<F>>? from ::createSegment argument. ? is questionable here
// (F?) -> F <: (OneElementSegment<C>?) -> OneElementSegment<C>
tail.findSegmentAndMoveForward(::createSegment)
}
}
private fun <C> createSegment(prev: OneElementSegment<C>?) = OneElementSegment<C>()
class OneElementSegment<O>() : Segment<OneElementSegment<O>>()
abstract class Segment<S : Segment<S>>
|
public class B {
}
// test.kt
class A
fun main(args: Array<String>) {
<!EQUALITY_NOT_APPLICABLE!>(1 to A()) == A()<!>
<!EQUALITY_NOT_APPLICABLE!>(1 to B()) == B()<!>
<!EQUALITY_NOT_APPLICABLE!>(1 to A()) === A()<!>
<!EQUALITY_NOT_APPLICABLE!>(1 to B()) === B()<!>
}
|
package org.jetbrains.kotlin.resolve.calls
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.test.ConfigurationKind
import org.jetbrains.kotlin.test.TestJdkKind
abstract class AbstractEnhancedSignaturesResolvedCallsTest : AbstractResolvedCallsTest() {
// requires full JDK with various Java API: java.util.Optional, java.util.Map
override fun createEnvironment(): KotlinCoreEnvironment = createEnvironmentWithJdk(ConfigurationKind.ALL, TestJdkKind.FULL_JDK)
override fun renderOutput(originalText: String, text: String, resolvedCallsAt: List<Pair<Int, ResolvedCall<*>?>>): String {
val lines = text.lines()
val lineOffsets = run {
var offset = 0
lines.map { offset.apply { offset += it.length + 1 /* new-line delimiter */ } }
}
fun lineIndexAt(caret: Int): Int =
lineOffsets.binarySearch(caret).let { result ->
if (result < 0) result.inv() - 1 else result }
val callsByLine = resolvedCallsAt.groupBy ({ (caret) -> lineIndexAt(caret) }, { (_, resolvedCall) -> resolvedCall })
return buildString {
lines.forEachIndexed { lineIndex, line ->
appendLine(line)
callsByLine[lineIndex]?.let { calls ->
val indent = line.takeWhile(Char::isWhitespace) + " "
calls.forEach { resolvedCall ->
appendLine("$indent// ${resolvedCall?.status}")
appendLine("$indent// ORIGINAL: ${resolvedCall?.run { resultingDescriptor!!.original.getText() }}")
appendLine("$indent// SUBSTITUTED: ${resolvedCall?.run { resultingDescriptor!!.getText() }}")
}
}
}
}
}
} |
package kotlinx.html
import kotlinx.html.*
import kotlinx.html.impl.*
import kotlinx.html.attributes.*
/*******************************************************************************
DO NOT EDIT
This file was generated by module generate
*******************************************************************************/
@Suppress("unused")
open class FIELDSET(initialAttributes : Map<String, String>, override val consumer : TagConsumer<*>) : HTMLTag("fieldset", consumer, initialAttributes, null, false, false), HtmlBlockTag {
var disabled : Boolean
get() = attributeBooleanTicker.get(this, "disabled")
set(newValue) {attributeBooleanTicker.set(this, "disabled", newValue)}
var form : String
get() = attributeStringString.get(this, "form")
set(newValue) {attributeStringString.set(this, "form", newValue)}
var name : String
get() = attributeStringString.get(this, "name")
set(newValue) {attributeStringString.set(this, "name", newValue)}
}
/**
* Fieldset legend
*/
@HtmlTagMarker
inline fun FIELDSET.legend(classes : String? = null, crossinline block : LEGEND.() -> Unit = {}) : Unit = LEGEND(attributesMapOf("class", classes), consumer).visit(block)
@Suppress("unused")
open class FIGCAPTION(initialAttributes : Map<String, String>, override val consumer : TagConsumer<*>) : HTMLTag("figcaption", consumer, initialAttributes, null, false, false), HtmlBlockTag {
}
@Suppress("unused")
open class FIGURE(initialAttributes : Map<String, String>, override val consumer : TagConsumer<*>) : HTMLTag("figure", consumer, initialAttributes, null, false, false), HtmlBlockTag {
}
/**
* Fieldset legend
*/
@HtmlTagMarker
inline fun FIGURE.legend(classes : String? = null, crossinline block : LEGEND.() -> Unit = {}) : Unit = LEGEND(attributesMapOf("class", classes), consumer).visit(block)
/**
* Caption for
*/
@HtmlTagMarker
inline fun FIGURE.figcaption(classes : String? = null, crossinline block : FIGCAPTION.() -> Unit = {}) : Unit = FIGCAPTION(attributesMapOf("class", classes), consumer).visit(block)
@Suppress("unused")
open class FOOTER(initialAttributes : Map<String, String>, override val consumer : TagConsumer<*>) : HTMLTag("footer", consumer, initialAttributes, null, false, false), HtmlBlockTag {
}
@Suppress("unused")
open class FORM(initialAttributes : Map<String, String>, override val consumer : TagConsumer<*>) : HTMLTag("form", consumer, initialAttributes, null, false, false), HtmlBlockTag {
var acceptCharset : String
get() = attributeStringString.get(this, "accept-charset")
set(newValue) {attributeStringString.set(this, "accept-charset", newValue)}
var action : String
get() = attributeStringString.get(this, "action")
set(newValue) {attributeStringString.set(this, "action", newValue)}
var autoComplete : Boolean
get() = attributeBooleanBooleanOnOff.get(this, "autocomplete")
set(newValue) {attributeBooleanBooleanOnOff.set(this, "autocomplete", newValue)}
var encType : FormEncType
get() = attributeFormEncTypeEnumFormEncTypeValues.get(this, "enctype")
set(newValue) {attributeFormEncTypeEnumFormEncTypeValues.set(this, "enctype", newValue)}
var method : FormMethod
get() = attributeFormMethodEnumFormMethodValues.get(this, "method")
set(newValue) {attributeFormMethodEnumFormMethodValues.set(this, "method", newValue)}
var name : String
get() = attributeStringString.get(this, "name")
set(newValue) {attributeStringString.set(this, "name", newValue)}
var novalidate : Boolean
get() = attributeBooleanTicker.get(this, "novalidate")
set(newValue) {attributeBooleanTicker.set(this, "novalidate", newValue)}
var target : String
get() = attributeStringString.get(this, "target")
set(newValue) {attributeStringString.set(this, "target", newValue)}
}
|
class Generic<T>
// MODULE: intermediate(base)
// FILE: intermediate.kt
class Owner<T>
interface Some<S> {
val g: Owner<Generic<S>>
}
fun register(owner: Owner<*>) {}
// MODULE: user(intermediate)
// FILE: user.kt
fun test(some: Some<String>) {
register(some.g)
}
|
package org.jetbrains.letsPlot.datamodel.mapping.framework
/**
* A simple kind of synchronizer which doesn't listen to a model and refreshes its part of output only when
* the refresh() method is explicitly called.
*/
interface RefreshableSynchronizer : Synchronizer {
fun refresh()
} |
fun foo(list: MutableList<Any?>, condition: Boolean): Unit = when {
condition -> list[0] = ""
else -> Unit
}
fun bar(list: MutableList<Any?>, condition: Boolean): Unit = <!RETURN_TYPE_MISMATCH!>when {
condition -> list.set(0, "")
else -> Unit
}<!>
fun plusFoo(list: MutableList<String>, condition: Boolean): Unit = when {
condition -> list[0] += ""
else -> Unit
}
var x: String = ""
fun assign(condition: Boolean): Unit = when {
condition -> x = ""
else -> Unit
}
fun plugAssign(condition: Boolean): Unit = when {
condition -> x += ""
else -> Unit
}
|
package com.android.tools.profilers.sessions
import com.android.testutils.TestUtils.resolveWorkspacePath
import com.android.tools.adtui.model.FakeTimer
import com.android.tools.adtui.model.stdui.CommonAction
import com.android.tools.adtui.swing.FakeUi
import com.android.tools.idea.protobuf.ByteString
import com.android.tools.idea.transport.faketransport.FakeGrpcChannel
import com.android.tools.idea.transport.faketransport.FakeTransportService
import com.android.tools.profiler.proto.Common
import com.android.tools.profiler.proto.Common.Process.ExposureLevel.PROFILEABLE
import com.android.tools.profiler.proto.Memory.AllocationsInfo
import com.android.tools.profiler.proto.Memory.HeapDumpInfo
import com.android.tools.profiler.proto.Trace
import com.android.tools.profilers.FakeIdeProfilerComponents
import com.android.tools.profilers.FakeIdeProfilerServices
import com.android.tools.profilers.ProfilerClient
import com.android.tools.profilers.ProfilersTestData
import com.android.tools.profilers.StudioMonitorStage
import com.android.tools.profilers.StudioProfilers
import com.android.tools.profilers.Utils.debuggableProcess
import com.android.tools.profilers.Utils.newDevice
import com.android.tools.profilers.Utils.onlineDevice
import com.android.tools.profilers.cpu.CpuCaptureArtifactView
import com.android.tools.profilers.cpu.CpuCaptureStage
import com.android.tools.profilers.cpu.CpuProfilerStage
import com.android.tools.profilers.cpu.ProfilingTechnology
import com.android.tools.profilers.event.FakeEventService
import com.android.tools.profilers.memory.HprofArtifactView
import com.android.tools.profilers.memory.HprofSessionArtifact
import com.android.tools.profilers.memory.LegacyAllocationsArtifactView
import com.android.tools.profilers.memory.MainMemoryProfilerStage
import com.android.tools.profilers.memory.adapters.HeapDumpCaptureObject
import com.android.tools.profilers.memory.adapters.LegacyAllocationCaptureObject
import com.google.common.truth.Truth.assertThat
import com.intellij.testFramework.EdtRule
import com.intellij.testFramework.RunsInEdt
import org.junit.Before
import org.junit.Ignore
import org.junit.Rule
import org.junit.Test
import java.awt.event.ActionEvent
import java.awt.event.KeyEvent.VK_BACK_SPACE
import java.awt.event.KeyEvent.VK_ENTER
import java.nio.file.Files
import java.util.concurrent.TimeUnit
@RunsInEdt
class SessionsViewTest {
private val myTimer = FakeTimer()
private val myTransportService = FakeTransportService(myTimer, false)
private val myIdeProfilerServices = FakeIdeProfilerServices()
@get:Rule
var myGrpcChannel = FakeGrpcChannel("SessionsViewTestChannel", myTransportService, FakeEventService())
@get:Rule val myEdtRule = EdtRule()
private lateinit var myProfilers: StudioProfilers
private lateinit var mySessionsManager: SessionsManager
private lateinit var mySessionsView: SessionsView
@Before
fun setup() {
myProfilers = StudioProfilers(ProfilerClient(myGrpcChannel.channel), myIdeProfilerServices, myTimer)
mySessionsManager = myProfilers.sessionsManager
mySessionsView = SessionsView(myProfilers, FakeIdeProfilerComponents())
}
@Ignore("b/123901060")
@Test
fun testSessionsListUpToDate() {
val sessionsPanel = mySessionsView.sessionsPanel
assertThat(sessionsPanel.componentCount).isEqualTo(0)
val device = Common.Device.newBuilder().setDeviceId(1).setState(Common.Device.State.ONLINE).build()
val process1 = debuggableProcess { pid = 10 }
val process2 = debuggableProcess { pid = 20 }
myTimer.currentTimeNs = 1
mySessionsManager.beginSession(device.deviceId, device, process1)
myTimer.tick(FakeTimer.ONE_SECOND_IN_NS)
var session1 = mySessionsManager.selectedSession
assertThat(sessionsPanel.componentCount).isEqualTo(1)
var sessionItem0 = sessionsPanel.getComponent(0) as SessionItemView
assertThat(sessionItem0.artifact.session).isEqualTo(session1)
mySessionsManager.endCurrentSession()
myTimer.tick(FakeTimer.ONE_SECOND_IN_NS)
session1 = mySessionsManager.selectedSession
assertThat(sessionsPanel.componentCount).isEqualTo(1)
sessionItem0 = sessionsPanel.getComponent(0) as SessionItemView
assertThat(sessionItem0.artifact.session).isEqualTo(session1)
myTimer.currentTimeNs = 2
mySessionsManager.beginSession(device.deviceId, device, process2)
myTimer.tick(FakeTimer.ONE_SECOND_IN_NS)
val session2 = mySessionsManager.selectedSession
assertThat(sessionsPanel.componentCount).isEqualTo(2)
// Sessions are sorted in descending order.
sessionItem0 = sessionsPanel.getComponent(0) as SessionItemView
var sessionItem1 = sessionsPanel.getComponent(1) as SessionItemView
assertThat(sessionItem0.artifact.session).isEqualTo(session2)
assertThat(sessionItem1.artifact.session).isEqualTo(session1)
// Add the heap dump and CPU capture, expand the first session and make sure the artifacts are shown in the list
val heapDumpTimestamp = 10L
val cpuTraceTimestamp = 20L
val heapDumpInfo = HeapDumpInfo.newBuilder().setStartTime(heapDumpTimestamp).setEndTime(heapDumpTimestamp + 1).build()
val cpuTraceInfo = Trace.TraceInfo.newBuilder()
.setConfiguration(Trace.TraceConfiguration.newBuilder())
.setFromTimestamp(cpuTraceTimestamp)
.setToTimestamp(cpuTraceTimestamp + 1)
.build()
val heapDumpEvent = ProfilersTestData.generateMemoryHeapDumpData(heapDumpInfo.startTime, heapDumpInfo.startTime, heapDumpInfo)
myTransportService.addEventToStream(device.deviceId, heapDumpEvent.setPid(session1.pid).build())
myTransportService.addEventToStream(device.deviceId, heapDumpEvent.setPid(session2.pid).build())
val cpuTraceEvent = Common.Event.newBuilder()
.setGroupId(cpuTraceTimestamp)
.setKind(Common.Event.Kind.CPU_TRACE)
.setTimestamp(cpuTraceTimestamp)
.setIsEnded(true)
.setTraceData(Trace.TraceData.newBuilder()
.setTraceEnded(Trace.TraceData.TraceEnded.newBuilder().setTraceInfo(cpuTraceInfo).build()))
myTransportService.addEventToStream(device.deviceId, cpuTraceEvent.setPid(session1.pid).build())
myTransportService.addEventToStream(device.deviceId, cpuTraceEvent.setPid(session2.pid).build())
mySessionsManager.update()
assertThat(sessionsPanel.componentCount).isEqualTo(6)
sessionItem0 = sessionsPanel.getComponent(0) as SessionItemView
val cpuCaptureItem0 = sessionsPanel.getComponent(1) as CpuCaptureArtifactView
val hprofItem0 = sessionsPanel.getComponent(2) as HprofArtifactView
sessionItem1 = sessionsPanel.getComponent(3) as SessionItemView
val cpuCaptureItem1 = sessionsPanel.getComponent(4) as CpuCaptureArtifactView
val hprofItem1 = sessionsPanel.getComponent(5) as HprofArtifactView
assertThat(sessionItem0.artifact.session).isEqualTo(session2)
assertThat(hprofItem0.artifact.session).isEqualTo(session2)
assertThat(cpuCaptureItem0.artifact.session).isEqualTo(session2)
assertThat(sessionItem1.artifact.session).isEqualTo(session1)
assertThat(hprofItem1.artifact.session).isEqualTo(session1)
assertThat(cpuCaptureItem1.artifact.session).isEqualTo(session1)
}
@Test
fun testProcessDropdownUpToDateForProfileables() {
val device1 = onlineDevice { deviceId = NEW_DEVICE_ID_1; manufacturer = "Manufacturer1"; model = "Model1" }
val device2 = onlineDevice { deviceId = NEW_DEVICE_ID_2; manufacturer = "Manufacturer2"; model = "Model2" }
val process1 = debuggableProcess { pid = 10; deviceId = NEW_DEVICE_ID_1; name = "Process1"; exposureLevel = PROFILEABLE }
val otherProcess1 = debuggableProcess { pid = 20; deviceId = NEW_DEVICE_ID_1; name = "Other1" }
val otherProcess2 = debuggableProcess { pid = 30; deviceId = NEW_DEVICE_ID_2; name = "Other2"; exposureLevel = PROFILEABLE }
// Process* is preferred, Other* should be in the other processes flyout.
myProfilers.setPreferredProcess("Manufacturer1 Model1", "Process", null)
var selectionAction = mySessionsView.processSelectionAction
assertThat(selectionAction.childrenActionCount).isEqualTo(3)
var loadAction = selectionAction.childrenActions.first { c -> c.text == "Load from file..." }
assertThat(loadAction.isEnabled).isTrue()
assertThat(loadAction.childrenActionCount).isEqualTo(0)
assertThat(selectionAction.childrenActions[1]).isInstanceOf(CommonAction.SeparatorAction::class.java)
assertThat(selectionAction.childrenActions[2].text).isEqualTo(SessionsView.NO_SUPPORTED_DEVICES)
assertThat(selectionAction.childrenActions[2].isEnabled).isFalse()
myTransportService.addDevice(device1)
myTimer.tick(FakeTimer.ONE_SECOND_IN_NS)
assertThat(selectionAction.childrenActionCount).isEqualTo(3)
assertThat(selectionAction.childrenActions[1]).isInstanceOf(CommonAction.SeparatorAction::class.java)
loadAction = selectionAction.childrenActions.first { c -> c.text == "Load from file..." }
assertThat(loadAction.isEnabled).isTrue()
assertThat(loadAction.childrenActionCount).isEqualTo(0)
var deviceAction1 = selectionAction.childrenActions.first { c -> c.text == "Manufacturer1 Model1" }
assertThat(deviceAction1.isEnabled).isTrue()
assertThat(deviceAction1.childrenActionCount).isEqualTo(1)
assertThat(deviceAction1.childrenActions[0].text).isEqualTo(SessionsView.NO_DEBUGGABLE_OR_PROFILEABLE_PROCESSES)
assertThat(deviceAction1.childrenActions[0].isEnabled).isFalse()
myTransportService.addProcess(device1, process1)
myTimer.tick(FakeTimer.ONE_SECOND_IN_NS)
myProfilers.setProcess(device1, process1)
assertThat(selectionAction.childrenActionCount).isEqualTo(3)
deviceAction1 = selectionAction.childrenActions.first { c -> c.text == "Manufacturer1 Model1" }
assertThat(deviceAction1.isEnabled).isTrue()
assertThat(deviceAction1.childrenActionCount).isEqualTo(3)
var processAction1 = deviceAction1.childrenActions.first { c -> c.text == "Process1 (10) (profileable)" }
assertThat(processAction1.childrenActionCount).isEqualTo(0)
myTransportService.addProcess(device1, otherProcess1)
try {
myTimer.tick(FakeTimer.ONE_SECOND_IN_NS)
} catch (e: NullPointerException) { /* Ignore error from HelpToolTip in test but not in production */ }
assertThat(selectionAction.childrenActionCount).isEqualTo(3)
deviceAction1 = selectionAction.childrenActions.first { c -> c.text == "Manufacturer1 Model1" }
assertThat(deviceAction1.isEnabled).isTrue()
assertThat(deviceAction1.childrenActionCount).isEqualTo(4) // process1 + separator + "other debuggables" + "other profileables"
processAction1 = deviceAction1.childrenActions.first { c -> c.text == "Process1 (10) (profileable)" }
assertThat(deviceAction1.childrenActions[1]).isInstanceOf(CommonAction.SeparatorAction::class.java)
var processAction2 = deviceAction1.childrenActions
.first { c -> c.text == "Other debuggable processes" }.childrenActions
.first { c -> c.text == "Other1 (20)" }
// Test the reverse case of having only "other" processes
myTransportService.addDevice(device2)
myTransportService.addProcess(device2, otherProcess2)
myTimer.tick(FakeTimer.ONE_SECOND_IN_NS)
assertThat(selectionAction.childrenActionCount).isEqualTo(4)
deviceAction1 = selectionAction.childrenActions.first { c -> c.text == "Manufacturer1 Model1" }
assertThat(deviceAction1.isEnabled).isTrue()
assertThat(deviceAction1.childrenActionCount).isEqualTo(4) // process1 + separator + "other debuggables" + "other profileables"
processAction1 = deviceAction1.childrenActions.first { c -> c.text == "Process1 (10) (profileable)" }
assertThat(deviceAction1.childrenActions[1]).isInstanceOf(CommonAction.SeparatorAction::class.java)
processAction2 = deviceAction1.childrenActions
.first { c -> c.text == "Other debuggable processes" }.childrenActions
.first { c -> c.text == "Other1 (20)" }
var deviceAction2 = selectionAction.childrenActions.first { c -> c.text == "Manufacturer2 Model2" }
assertThat(deviceAction2.isEnabled).isTrue()
assertThat(deviceAction2.childrenActionCount).isEqualTo(2) // No separator + "no other debuggables" + "other profileables"
var processAction3 = deviceAction2.childrenActions
.first { c -> c.text == "Other profileable processes" }.childrenActions
.first { c -> c.text == "Other2 (30)" }
}
@Test
fun testUnsupportedDeviceDropdown() {
val unsupportedReasonText = "Unsupported"
val device = onlineDevice { deviceId = NEW_DEVICE_ID_1; manufacturer = "Manufacturer1"; model = "Model1"; unsupportedReason = unsupportedReasonText }
myTransportService.addDevice(device)
myTimer.tick(FakeTimer.ONE_SECOND_IN_NS)
var selectionAction = mySessionsView.processSelectionAction
assertThat(selectionAction.childrenActionCount).isEqualTo(3)
var loadAction = selectionAction.childrenActions.first { c -> c.text == "Load from file..." }
assertThat(loadAction.isEnabled).isTrue()
assertThat(loadAction.childrenActionCount).isEqualTo(0)
assertThat(selectionAction.childrenActions[1]).isInstanceOf(CommonAction.SeparatorAction::class.java)
var deviceAction1 = selectionAction.childrenActions.first { c -> c.text == "Manufacturer1 Model1" }
assertThat(deviceAction1.isEnabled).isTrue()
assertThat(deviceAction1.childrenActionCount).isEqualTo(1)
assertThat(deviceAction1.childrenActions[0].text).isEqualTo(unsupportedReasonText)
assertThat(deviceAction1.childrenActions[0].isEnabled).isFalse()
}
@Test
fun testProcessDropdownHideDeadDevicesAndProcesses() {
val deadDevice = newDevice(Common.Device.State.DISCONNECTED) { deviceId = NEW_DEVICE_ID_1; manufacturer = "Manufacturer1"; model = "Model1" }
val onlineDevice = onlineDevice { deviceId = NEW_DEVICE_ID_2; manufacturer = "Manufacturer2"; model = "Model2" }
val deadProcess1 = debuggableProcess { pid = 10; deviceId = NEW_DEVICE_ID_1; name = "Process1"; state = Common.Process.State.DEAD }
val aliveProcess1 = debuggableProcess { pid = 20; deviceId = NEW_DEVICE_ID_1; name = "Process2" }
val deadProcess2 = debuggableProcess { pid = 30; deviceId = NEW_DEVICE_ID_2; name = "Process3"; state = Common.Process.State.DEAD }
val aliveProcess2 = debuggableProcess { pid = 40; deviceId = NEW_DEVICE_ID_2; name = "Process4" }
val deadProcess3 = debuggableProcess { pid = 50; deviceId = NEW_DEVICE_ID_2; name = "Dead"; state = Common.Process.State.DEAD }
// Also test processes that can be grouped in the fly-out menu.
myProfilers.setPreferredProcess("Manufacturer2 Model2", "Process4", null)
myTransportService.addDevice(deadDevice)
myTransportService.addDevice(onlineDevice)
myTransportService.addProcess(deadDevice, deadProcess1)
myTransportService.addProcess(deadDevice, aliveProcess1)
myTransportService.addProcess(onlineDevice, deadProcess2)
myTransportService.addProcess(onlineDevice, aliveProcess2)
myTransportService.addProcess(onlineDevice, deadProcess3)
myTimer.tick(FakeTimer.ONE_SECOND_IN_NS)
var selectionAction = mySessionsView.processSelectionAction
assertThat(selectionAction.childrenActions.any { c -> c.text == "Manufacturer1 Model1" }).isFalse()
val aliveDeviceAction = selectionAction.childrenActions.first { c -> c.text == "Manufacturer2 Model2" }
assertThat(aliveDeviceAction.childrenActionCount).isEqualTo(3) // the process + no other debuggables + no other profileables
val processAction1 = aliveDeviceAction.childrenActions.first { c -> c.text == "Process4 (40) (debuggable)" }
assertThat(processAction1.childrenActionCount).isEqualTo(0)
}
@Test
fun testDropdownActionsTriggerProcessChange() {
val device1 = onlineDevice { deviceId = NEW_DEVICE_ID_1; manufacturer = "Manufacturer1"; model = "Model1" }
val device2 = onlineDevice { deviceId = NEW_DEVICE_ID_2; manufacturer = "Manufacturer2"; model = "Model2" }
val process1 = debuggableProcess { pid = 10; deviceId = NEW_DEVICE_ID_1; name = "Process1" }
val process2 = debuggableProcess { pid = 20; deviceId = NEW_DEVICE_ID_1; name = "Process2" }
val process3 = debuggableProcess { pid = 10; deviceId = NEW_DEVICE_ID_2; name = "Process3" }
// Mark all process as preferred processes as we are not testing the other processes flyout here.
myProfilers.setPreferredProcess(null, "Process", null)
myTransportService.addDevice(device1)
myTransportService.addProcess(device1, process1)
myTimer.tick(FakeTimer.ONE_SECOND_IN_NS)
myTransportService.addProcess(device1, process2)
myTimer.tick(FakeTimer.ONE_SECOND_IN_NS)
var selectionAction = mySessionsView.processSelectionAction
var processAction2 = selectionAction.childrenActions
.first { c -> c.text == "Manufacturer1 Model1" }.childrenActions
.first { c -> c.text == "Process2 (20) (debuggable)" }
processAction2.actionPerformed(ActionEvent(processAction2, 0, ""))
assertThat(myProfilers.device).isEqualTo(device1)
assertThat(myProfilers.process).isEqualTo(process2)
myTransportService.addDevice(device2)
myTransportService.addProcess(device2, process3)
myTimer.tick(FakeTimer.ONE_SECOND_IN_NS)
var processAction3 = selectionAction.childrenActions
.first { c -> c.text == "Manufacturer2 Model2" }.childrenActions
.first { c -> c.text == "Process3 (10) (debuggable)" }
processAction3.actionPerformed(ActionEvent(processAction3, 0, ""))
assertThat(myProfilers.device).isEqualTo(device2)
assertThat(myProfilers.process).isEqualTo(process3)
}
@Test
fun testStopProfiling() {
val device1 = onlineDevice { deviceId = NEW_DEVICE_ID_1; manufacturer = "Manufacturer1"; model = "Model1" }
val process1 = debuggableProcess { pid = 10; deviceId = NEW_DEVICE_ID_1; name = "Process1" }
val stopProfilingButton = mySessionsView.stopProfilingButton
assertThat(stopProfilingButton.isEnabled).isFalse()
startSession(device1, process1)
val session = myProfilers.session
assertThat(stopProfilingButton.isEnabled).isTrue()
assertThat(mySessionsManager.profilingSession).isNotEqualTo(Common.Session.getDefaultInstance())
assertThat(mySessionsManager.profilingSession).isEqualTo(session)
stopProfilingButton.doClick()
assertThat(stopProfilingButton.isEnabled).isFalse()
assertThat(myProfilers.device).isNull()
assertThat(myProfilers.process).isNull()
assertThat(mySessionsManager.profilingSession).isEqualTo(Common.Session.getDefaultInstance())
assertThat(myProfilers.session.sessionId).isEqualTo(session.sessionId)
}
@Test
fun testImportSessionsFromHprofFile() {
val sessionsPanel = mySessionsView.sessionsPanel
assertThat(sessionsPanel.componentCount).isEqualTo(0)
val device = onlineDevice { deviceId = NEW_DEVICE_ID_1 }
val process1 = debuggableProcess { deviceId = NEW_DEVICE_ID_1; pid = 10 }
startSession(device, process1)
val session1 = mySessionsManager.selectedSession
assertThat(sessionsPanel.componentCount).isEqualTo(1)
assertThat((sessionsPanel.getComponent(0) as SessionItemView).artifact.session).isEqualTo(session1)
myTransportService.addEventToStream(1, ProfilersTestData.generateSessionStartEvent(1, 2, 1,
Common.SessionData.SessionStarted.SessionType.MEMORY_CAPTURE,
1).build())
myTransportService.addEventToStream(1, ProfilersTestData.generateSessionEndEvent(1, 2, 2).build())
mySessionsManager.update()
assertThat(sessionsPanel.componentCount).isEqualTo(2)
assertThat(myProfilers.sessionsManager.selectedSessionMetaData.type).isEqualTo(Common.SessionMetaData.SessionType.MEMORY_CAPTURE)
}
@Ignore("b/123901060")
@Test
fun testSessionItemSelection() {
val sessionsPanel = mySessionsView.sessionsPanel
sessionsPanel.setSize(200, 200)
val ui = FakeUi(sessionsPanel)
val device = Common.Device.newBuilder().setDeviceId(1).setState(Common.Device.State.ONLINE).build()
val process1 = debuggableProcess { pid = 10 }
val process2 = debuggableProcess { pid = 20 }
val heapDumpInfo = HeapDumpInfo.newBuilder().setStartTime(10).setEndTime(11).build()
val cpuTraceInfo = Trace.TraceInfo.newBuilder()
.setConfiguration(Trace.TraceConfiguration.newBuilder())
.setFromTimestamp(20)
.setToTimestamp(21)
.build()
val heapDumpEvent = ProfilersTestData.generateMemoryHeapDumpData(heapDumpInfo.startTime, heapDumpInfo.startTime, heapDumpInfo)
myTransportService.addEventToStream(device.deviceId, heapDumpEvent.setPid(process1.pid).build())
myTransportService.addEventToStream(device.deviceId, heapDumpEvent.setPid(process2.pid).build())
val cpuTraceEvent = Common.Event.newBuilder()
.setGroupId(cpuTraceInfo.fromTimestamp)
.setKind(Common.Event.Kind.CPU_TRACE)
.setTimestamp(cpuTraceInfo.fromTimestamp)
.setIsEnded(true)
.setTraceData(Trace.TraceData.newBuilder()
.setTraceEnded(Trace.TraceData.TraceEnded.newBuilder().setTraceInfo(cpuTraceInfo).build()))
myTransportService.addEventToStream(device.deviceId, cpuTraceEvent.setPid(process1.pid).build())
myTransportService.addEventToStream(device.deviceId, cpuTraceEvent.setPid(process2.pid).build())
myTimer.currentTimeNs = 2
mySessionsManager.beginSession(device.deviceId, device, process1)
myTimer.tick(FakeTimer.ONE_SECOND_IN_NS)
mySessionsManager.endCurrentSession()
myTimer.tick(FakeTimer.ONE_SECOND_IN_NS)
val session1 = mySessionsManager.selectedSession
myTimer.currentTimeNs = 2
mySessionsManager.beginSession(device.deviceId, device, process2)
myTimer.tick(FakeTimer.ONE_SECOND_IN_NS)
mySessionsManager.endCurrentSession()
myTimer.tick(FakeTimer.ONE_SECOND_IN_NS)
val session2 = mySessionsManager.selectedSession
assertThat(sessionsPanel.componentCount).isEqualTo(6)
// Sessions are sorted in descending order.
var sessionItem0 = sessionsPanel.getComponent(0) as SessionItemView
val cpuCaptureItem0 = sessionsPanel.getComponent(1) as CpuCaptureArtifactView
val hprofItem0 = sessionsPanel.getComponent(2) as HprofArtifactView
var sessionItem1 = sessionsPanel.getComponent(3) as SessionItemView
var cpuCaptureItem1 = sessionsPanel.getComponent(4) as CpuCaptureArtifactView
var hprofItem1 = sessionsPanel.getComponent(5) as HprofArtifactView
assertThat(sessionItem0.artifact.session).isEqualTo(session2)
assertThat(hprofItem0.artifact.session).isEqualTo(session2)
assertThat(cpuCaptureItem0.artifact.session).isEqualTo(session2)
assertThat(sessionItem1.artifact.session).isEqualTo(session1)
assertThat(hprofItem1.artifact.session).isEqualTo(session1)
assertThat(cpuCaptureItem1.artifact.session).isEqualTo(session1)
// Selecting on the second item should select the session.
assertThat(mySessionsManager.selectedSession).isEqualTo(session2)
ui.layout()
ui.mouse.click(sessionItem1.bounds.x + 1, sessionItem1.bounds.y + 1)
assertThat(mySessionsManager.selectedSession).isEqualTo(session1)
}
@Ignore("b/123901060")
@Test
fun testSessionArtifactKeyboardSelect() {
val sessionsPanel = mySessionsView.sessionsPanel
sessionsPanel.setSize(200, 200)
val device = Common.Device.newBuilder().setDeviceId(1).setState(Common.Device.State.ONLINE).build()
val process1 = debuggableProcess { pid = 10 }
val process2 = debuggableProcess { pid = 20 }
myTimer.currentTimeNs = 1
mySessionsManager.beginSession(0, device, process1)
mySessionsManager.endCurrentSession()
val session1 = mySessionsManager.selectedSession
myTimer.currentTimeNs = 2
mySessionsManager.beginSession(0, device, process2)
mySessionsManager.endCurrentSession()
val session2 = mySessionsManager.selectedSession
assertThat(sessionsPanel.componentCount).isEqualTo(2)
var sessionItem0 = sessionsPanel.getComponent(0) as SessionItemView
var sessionItem1 = sessionsPanel.getComponent(1) as SessionItemView
// Make sure the second session item is selected
assertThat(mySessionsManager.selectedSession).isEqualTo(session2)
val ui = FakeUi(sessionsPanel)
ui.keyboard.setFocus(sessionItem1)
ui.keyboard.press(VK_ENTER)
ui.keyboard.release(VK_ENTER)
assertThat(mySessionsManager.selectedSession).isEqualTo(session1)
ui.keyboard.setFocus(sessionItem0)
ui.keyboard.press(VK_ENTER)
ui.keyboard.release(VK_ENTER)
assertThat(mySessionsManager.selectedSession).isEqualTo(session2)
}
@Ignore("b/123901060")
@Test
fun testSessionArtifactKeyboardDelete() {
val sessionsPanel = mySessionsView.sessionsPanel
sessionsPanel.setSize(200, 200)
val device = Common.Device.newBuilder().setDeviceId(1).setState(Common.Device.State.ONLINE).build()
val process1 = debuggableProcess { pid = 10 }
val process2 = debuggableProcess { pid = 20 }
myTimer.currentTimeNs = 1
mySessionsManager.beginSession(0, device, process1)
mySessionsManager.endCurrentSession()
myTimer.currentTimeNs = 2
mySessionsManager.beginSession(0, device, process2)
mySessionsManager.endCurrentSession()
assertThat(sessionsPanel.componentCount).isEqualTo(2)
var sessionItem = sessionsPanel.getComponent(0) as SessionItemView
// Delete the ongoing session
FakeUi(sessionsPanel).let { ui ->
ui.keyboard.setFocus(sessionItem)
ui.keyboard.press(VK_BACK_SPACE)
ui.keyboard.release(VK_BACK_SPACE)
assertThat(mySessionsManager.sessionArtifacts).hasSize(1)
assertThat(mySessionsManager.selectedSession).isEqualTo(Common.Session.getDefaultInstance())
assertThat(mySessionsManager.profilingSession).isEqualTo(Common.Session.getDefaultInstance())
}
// Delete the remaining session
assertThat(sessionsPanel.componentCount).isEqualTo(1)
FakeUi(sessionsPanel).let { ui ->
sessionItem = sessionsPanel.getComponent(0) as SessionItemView
ui.layout()
ui.keyboard.setFocus(sessionItem)
ui.keyboard.press(VK_BACK_SPACE)
ui.keyboard.release(VK_BACK_SPACE)
assertThat(mySessionsManager.sessionArtifacts).hasSize(0)
}
}
@Test
fun testCpuCaptureItemSelection() {
val sessionsPanel = mySessionsView.sessionsPanel
sessionsPanel.setSize(200, 200)
val ui = FakeUi(sessionsPanel)
val device = onlineDevice { deviceId = NEW_DEVICE_ID_1 }
val process = debuggableProcess { pid = 10 }
val traceInfoId = 13L
val cpuTraceInfo = Trace.TraceInfo.newBuilder()
.setTraceId(traceInfoId)
.setFromTimestamp(TimeUnit.MINUTES.toNanos(1))
.setToTimestamp(TimeUnit.MINUTES.toNanos(2))
.setConfiguration(Trace.TraceConfiguration.newBuilder()
.setArtOptions(Trace.ArtOptions.newBuilder().setTraceMode(Trace.TraceMode.SAMPLED)))
.build()
myTransportService.addEventToStream(device.deviceId, Common.Event.newBuilder()
.setGroupId(cpuTraceInfo.fromTimestamp)
.setPid(process.pid)
.setKind(Common.Event.Kind.CPU_TRACE)
.setTimestamp(cpuTraceInfo.fromTimestamp)
.setIsEnded(true)
.setTraceData(Trace.TraceData.newBuilder()
.setTraceEnded(Trace.TraceData.TraceEnded.newBuilder().setTraceInfo(cpuTraceInfo).build()))
.build())
myTransportService.addFile(traceInfoId.toString(), ByteString.copyFrom(Files.readAllBytes(resolveWorkspacePath(VALID_TRACE_PATH))))
myTimer.currentTimeNs = 0
mySessionsManager.beginSession(device.deviceId, device, process)
myTimer.tick(FakeTimer.ONE_SECOND_IN_NS)
mySessionsManager.endCurrentSession()
myTimer.tick(FakeTimer.ONE_SECOND_IN_NS)
val session = mySessionsManager.selectedSession
assertThat(sessionsPanel.componentCount).isEqualTo(2)
val sessionItem = sessionsPanel.getComponent(0) as SessionItemView
val cpuCaptureItem = sessionsPanel.getComponent(1) as CpuCaptureArtifactView
assertThat(sessionItem.artifact.session).isEqualTo(session)
assertThat(cpuCaptureItem.artifact.session).isEqualTo(session)
assertThat(cpuCaptureItem.artifact.isOngoing).isFalse()
assertThat(cpuCaptureItem.artifact.name).isEqualTo(ProfilingTechnology.ART_SAMPLED.getName())
assertThat(CpuCaptureArtifactView.getArtifactSubtitle(cpuCaptureItem.artifact)).isEqualTo("00:01:00.000")
assertThat(myProfilers.stage).isInstanceOf(StudioMonitorStage::class.java) // Makes sure we're in monitor stage
// Makes sure current selection (before selecting an artifact) is the session we just began
assertThat(mySessionsManager.selectedArtifactProto).isInstanceOf(Common.Session::class.java)
// Selecting the CpuCaptureSessionArtifact should open CPU profiler and select the capture
ui.layout()
ui.mouse.click(cpuCaptureItem.bounds.x + 1, cpuCaptureItem.bounds.y + 1)
// Move away again so we're not hovering
ui.mouse.moveTo(-10, -10)
assertThat(myProfilers.stage).isInstanceOf(CpuCaptureStage::class.java) // Makes sure CPU capture stage is now open
assertThat(myProfilers.timeline.isStreaming).isFalse()
// Makes sure artifact's proto selection is saved
assertThat(mySessionsManager.selectedArtifactProto).isEqualTo(cpuCaptureItem.artifact.artifactProto);
// Make sure clicking the export label does not select the session.
mySessionsManager.setSession(Common.Session.getDefaultInstance())
assertThat(mySessionsManager.selectedSession).isEqualTo(Common.Session.getDefaultInstance())
val exportLabel = cpuCaptureItem.exportLabel!!
assertThat(exportLabel.isVisible).isFalse()
ui.mouse.moveTo(cpuCaptureItem.bounds.x + 1, cpuCaptureItem.bounds.y + 1)
ui.layout()
assertThat(exportLabel.isVisible).isTrue()
ui.mouse.click(cpuCaptureItem.bounds.x + exportLabel.bounds.x + 1, cpuCaptureItem.bounds.y + exportLabel.bounds.y + 1)
assertThat(mySessionsManager.selectedSession).isEqualTo(Common.Session.getDefaultInstance())
// Makes sure selected artifact's proto stayed the same
assertThat(mySessionsManager.selectedArtifactProto).isEqualTo(cpuCaptureItem.artifact.artifactProto);
}
@Test
fun testCpuOngoingCaptureItemSelection() {
val sessionsPanel = mySessionsView.sessionsPanel
sessionsPanel.setSize(200, 200)
val ui = FakeUi(sessionsPanel)
val device = onlineDevice { deviceId = NEW_DEVICE_ID_1 }
val process = debuggableProcess { pid = 10 }
val sessionStartNs = 1L
// Sets an ongoing trace info in the service
val cpuTraceInfo = Trace.TraceInfo.newBuilder()
.setTraceId(1)
.setConfiguration(Trace.TraceConfiguration.newBuilder()
.setAtraceOptions(Trace.AtraceOptions.getDefaultInstance()))
.setFromTimestamp(sessionStartNs + 1)
.setToTimestamp(-1)
.build()
myTransportService.addEventToStream(device.deviceId, Common.Event.newBuilder()
.setGroupId(cpuTraceInfo.fromTimestamp)
.setPid(process.getPid())
.setKind(Common.Event.Kind.CPU_TRACE)
.setTimestamp(cpuTraceInfo.fromTimestamp)
.setIsEnded(true)
.setTraceData(Trace.TraceData.newBuilder()
.setTraceEnded(Trace.TraceData.TraceEnded.newBuilder().setTraceInfo(cpuTraceInfo).build()))
.build())
myTimer.currentTimeNs = sessionStartNs
mySessionsManager.beginSession(device.deviceId, device, process)
myTimer.tick(FakeTimer.ONE_SECOND_IN_NS)
val session = mySessionsManager.selectedSession
assertThat(sessionsPanel.componentCount).isEqualTo(2)
val sessionItem = sessionsPanel.getComponent(0) as SessionItemView
val cpuCaptureItem = sessionsPanel.getComponent(1) as CpuCaptureArtifactView
assertThat(sessionItem.artifact.session).isEqualTo(session)
assertThat(cpuCaptureItem.artifact.session).isEqualTo(session)
assertThat(cpuCaptureItem.artifact.isOngoing).isTrue()
assertThat(cpuCaptureItem.artifact.name).isEqualTo(ProfilingTechnology.SYSTEM_TRACE.getName())
assertThat(CpuCaptureArtifactView.getArtifactSubtitle(cpuCaptureItem.artifact)).isEqualTo(SessionArtifact.CAPTURING_SUBTITLE)
assertThat(cpuCaptureItem.exportLabel).isNull()
assertThat(myProfilers.stage).isInstanceOf(StudioMonitorStage::class.java) // Makes sure we're in monitor stage
// Selecting on the CpuCaptureSessionArtifact should open CPU profiler and select the capture
ui.layout()
ui.mouse.click(cpuCaptureItem.bounds.x + 1, cpuCaptureItem.bounds.y + 1)
assertThat(myProfilers.stage).isInstanceOf(CpuProfilerStage::class.java) // Makes sure CPU profiler stage is now open
assertThat(myProfilers.timeline.isStreaming).isTrue()
// Makes sure artifact's proto selection is saved
assertThat(mySessionsManager.selectedArtifactProto).isEqualTo(cpuCaptureItem.artifact.artifactProto);
// Selects the CPUCaptureSessionArtifact again
ui.layout()
ui.mouse.click(cpuCaptureItem.bounds.x + 1, cpuCaptureItem.bounds.y + 1)
// Makes sure selected artifact's proto stayed the same
assertThat(mySessionsManager.selectedArtifactProto).isEqualTo(cpuCaptureItem.artifact.artifactProto);
}
@Ignore("b/138573206")
@Test
fun testMemoryHeapDumpSelection() {
val sessionsPanel = mySessionsView.sessionsPanel
sessionsPanel.setSize(200, 200)
val ui = FakeUi(sessionsPanel)
val device = Common.Device.newBuilder().setDeviceId(1).setState(Common.Device.State.ONLINE).build()
val process = debuggableProcess { pid = 10 }
val heapDumpInfo = HeapDumpInfo.newBuilder().setStartTime(10).setEndTime(11).build()
val heapDumpEvent = ProfilersTestData.generateMemoryHeapDumpData(heapDumpInfo.startTime, heapDumpInfo.startTime, heapDumpInfo)
myTransportService.addEventToStream(device.deviceId, heapDumpEvent.setPid(process.pid).build())
myTimer.currentTimeNs = 1
mySessionsManager.beginSession(device.deviceId, device, process)
myTimer.tick(FakeTimer.ONE_SECOND_IN_NS)
mySessionsManager.endCurrentSession()
myTimer.tick(FakeTimer.ONE_SECOND_IN_NS)
val session = mySessionsManager.selectedSession
assertThat(sessionsPanel.componentCount).isEqualTo(2)
var sessionItem = sessionsPanel.getComponent(0) as SessionItemView
var hprofItem = sessionsPanel.getComponent(1) as HprofArtifactView
assertThat(sessionItem.artifact.session).isEqualTo(session)
assertThat(hprofItem.artifact.session).isEqualTo(session)
// Makes sure we're in monitor stage.
assertThat(myProfilers.stage).isInstanceOf(StudioMonitorStage::class.java)
// Selecting on the HprofSessionArtifact should open Memory profiler and select the capture.
ui.layout()
ui.mouse.click(hprofItem.bounds.x + 1, hprofItem.bounds.y + 1)
// Makes sure memory profiler stage is now open.
assertThat(myProfilers.stage).isInstanceOf(MainMemoryProfilerStage::class.java)
// Makes sure a HeapDumpCaptureObject is loaded.
assertThat((myProfilers.stage as MainMemoryProfilerStage).captureSelection.selectedCapture).isInstanceOf(HeapDumpCaptureObject::class.java)
// Make sure clicking the export label does not select the session.
mySessionsManager.setSession(Common.Session.getDefaultInstance())
assertThat(mySessionsManager.selectedSession).isEqualTo(Common.Session.getDefaultInstance())
val exportLabel = hprofItem.exportLabel!!
assertThat(exportLabel.isVisible).isFalse()
ui.mouse.moveTo(hprofItem.bounds.x + 1, hprofItem.bounds.y + 1)
ui.layout()
assertThat(exportLabel.isVisible).isTrue()
ui.mouse.click(hprofItem.bounds.x + exportLabel.bounds.x + 1, hprofItem.bounds.y + exportLabel.bounds.y + 1)
assertThat(mySessionsManager.selectedSession).isEqualTo(Common.Session.getDefaultInstance())
}
@Test
fun testMemoryOngoingHeapDumpItemSelection() {
val sessionsPanel = mySessionsView.sessionsPanel
sessionsPanel.setSize(200, 200)
val ui = FakeUi(sessionsPanel)
val device = onlineDevice { deviceId = NEW_DEVICE_ID_1 }
val process = debuggableProcess { pid = 10 }
val heapDumpInfo = HeapDumpInfo.newBuilder().setStartTime(10).setEndTime(Long.MAX_VALUE).build()
val heapDumpEvent = ProfilersTestData.generateMemoryHeapDumpData(heapDumpInfo.startTime, heapDumpInfo.startTime, heapDumpInfo)
myTransportService.addEventToStream(device.deviceId, heapDumpEvent.setPid(process.pid).build())
mySessionsManager.beginSession(device.deviceId, device, process)
myTimer.tick(FakeTimer.ONE_SECOND_IN_NS)
val session = mySessionsManager.selectedSession
assertThat(sessionsPanel.componentCount).isEqualTo(2)
var sessionItem = sessionsPanel.getComponent(0) as SessionItemView
var hprofItem = sessionsPanel.getComponent(1) as HprofArtifactView
assertThat(sessionItem.artifact.session).isEqualTo(session)
assertThat(hprofItem.artifact.session).isEqualTo(session)
assertThat(hprofItem.exportLabel).isNull()
assertThat(myProfilers.stage).isInstanceOf(StudioMonitorStage::class.java) // Makes sure we're in monitor stage
// Selecting on the HprofSessionArtifact should open Memory profiler.
ui.layout()
ui.mouse.click(hprofItem.bounds.x + 1, hprofItem.bounds.y + 1)
// Makes sure memory profiler stage is now open.
assertThat(myProfilers.stage).isInstanceOf(MainMemoryProfilerStage::class.java)
// Makes sure that there is no capture selected.
assertThat((myProfilers.stage as MainMemoryProfilerStage).captureSelection.selectedCapture).isNull()
assertThat(myProfilers.timeline.isStreaming).isTrue()
// Makes sure artifact's proto selection is saved
assertThat(mySessionsManager.selectedArtifactProto).isEqualTo(hprofItem.artifact.artifactProto);
// Selects the HprofSessionArtifact again
ui.layout()
ui.mouse.click(hprofItem.bounds.x + 1, hprofItem.bounds.y + 1)
// Makes sure selected artifact's proto stayed the same
assertThat(mySessionsManager.selectedArtifactProto).isEqualTo(hprofItem.artifact.artifactProto);
}
@Test
fun testMemoryLegacyAllocationsSelection() {
val sessionsPanel = mySessionsView.sessionsPanel
sessionsPanel.setSize(200, 200)
val ui = FakeUi(sessionsPanel)
val device = onlineDevice { deviceId = NEW_DEVICE_ID_1 }
val process = debuggableProcess { pid = 10 }
val allocationInfo = AllocationsInfo.newBuilder().setStartTime(10).setEndTime(11).setLegacy(true).setSuccess(true).build()
myTransportService.addEventToStream(
device.deviceId, ProfilersTestData.generateMemoryAllocationInfoData(allocationInfo.startTime, process.pid, allocationInfo).build())
mySessionsManager.beginSession(device.deviceId, device, process)
myTimer.tick(FakeTimer.ONE_SECOND_IN_NS)
val session = mySessionsManager.selectedSession
assertThat(sessionsPanel.componentCount).isEqualTo(2)
val sessionItem = sessionsPanel.getComponent(0) as SessionItemView
val allocationItem = sessionsPanel.getComponent(1) as LegacyAllocationsArtifactView
assertThat(sessionItem.artifact.session).isEqualTo(session)
assertThat(allocationItem.artifact.session).isEqualTo(session)
// Makes sure we're in monitor stage.
assertThat(myProfilers.stage).isInstanceOf(StudioMonitorStage::class.java)
// Selecting on the LegacyAllocationsSessionArtifact should open Memory profiler and select the capture.
ui.layout()
ui.mouse.click(allocationItem.bounds.x + 1, allocationItem.bounds.y + 1)
// Move away again so we're not hovering
ui.mouse.moveTo(-10, -10)
// Makes sure memory profiler stage is now open.
assertThat(myProfilers.stage).isInstanceOf(MainMemoryProfilerStage::class.java)
// Makes sure a LegacyAllocationCaptureObject is loaded.
assertThat((myProfilers.stage as MainMemoryProfilerStage).captureSelection.selectedCapture).isInstanceOf(LegacyAllocationCaptureObject::class.java)
// Makes sure artifact's proto selection is saved
assertThat(mySessionsManager.selectedArtifactProto).isEqualTo(allocationItem.artifact.artifactProto);
// Make sure clicking the export label does not select the session.
mySessionsManager.setSession(Common.Session.getDefaultInstance())
assertThat(mySessionsManager.selectedSession).isEqualTo(Common.Session.getDefaultInstance())
val exportLabel = allocationItem.exportLabel!!
assertThat(exportLabel.isVisible).isFalse()
ui.mouse.moveTo(allocationItem.bounds.x + 1, allocationItem.bounds.y + 1)
ui.layout()
assertThat(exportLabel.isVisible).isTrue()
ui.mouse.click(allocationItem.bounds.x + exportLabel.bounds.x + 1, allocationItem.bounds.y + exportLabel.bounds.y + 1)
assertThat(mySessionsManager.selectedSession).isEqualTo(Common.Session.getDefaultInstance())
// Selects the LegacyAllocationsSessionArtifact again
ui.layout()
ui.mouse.click(allocationItem.bounds.x + 1, allocationItem.bounds.y + 1)
// Makes sure selected artifact's proto stayed the same
assertThat(mySessionsManager.selectedArtifactProto).isEqualTo(allocationItem.artifact.artifactProto);
}
@Test
fun testMemoryOngoingLegacyAllocationsSelection() {
val sessionsPanel = mySessionsView.sessionsPanel
sessionsPanel.setSize(200, 200)
val ui = FakeUi(sessionsPanel)
val device = onlineDevice { deviceId = NEW_DEVICE_ID_1 }
val process = debuggableProcess { pid = 10 }
val allocationInfo = AllocationsInfo.newBuilder().setStartTime(10).setEndTime(Long.MAX_VALUE).setLegacy(true).build()
myTransportService.addEventToStream(
device.deviceId, ProfilersTestData.generateMemoryAllocationInfoData(allocationInfo.startTime, process.pid, allocationInfo).build())
mySessionsManager.beginSession(device.deviceId, device, process)
myTimer.tick(FakeTimer.ONE_SECOND_IN_NS)
val session = mySessionsManager.selectedSession
assertThat(sessionsPanel.componentCount).isEqualTo(2)
var sessionItem = sessionsPanel.getComponent(0) as SessionItemView
var allocationItem = sessionsPanel.getComponent(1) as LegacyAllocationsArtifactView
assertThat(sessionItem.artifact.session).isEqualTo(session)
assertThat(allocationItem.artifact.session).isEqualTo(session)
assertThat(allocationItem.exportLabel).isNull()
assertThat(myProfilers.stage).isInstanceOf(StudioMonitorStage::class.java) // Makes sure we're in monitor stage
// Selecting on the HprofSessionArtifact should open Memory profiler.
ui.layout()
ui.mouse.click(allocationItem.bounds.x + 1, allocationItem.bounds.y + 1)
// Makes sure memory profiler stage is now open.
assertThat(myProfilers.stage).isInstanceOf(MainMemoryProfilerStage::class.java)
// Makes sure that there is no capture selected.
assertThat((myProfilers.stage as MainMemoryProfilerStage).captureSelection.selectedCapture).isNull()
assertThat(myProfilers.timeline.isStreaming).isTrue()
// Makes sure artifact's proto selection is saved
assertThat(mySessionsManager.selectedArtifactProto).isEqualTo(allocationItem.artifact.artifactProto);
// Selects the LegacyAllocationsSessionArtifact again
ui.layout()
ui.mouse.click(allocationItem.bounds.x + 1, allocationItem.bounds.y + 1)
// Makes sure selected artifact's proto stayed the same
assertThat(mySessionsManager.selectedArtifactProto).isEqualTo(allocationItem.artifact.artifactProto);
}
@Test
fun testHprofSessionSubtitle() {
val ongoingInfo = HeapDumpInfo.newBuilder().setStartTime(1).setEndTime(Long.MAX_VALUE).build()
val finishedInfo = HeapDumpInfo.newBuilder()
.setStartTime(TimeUnit.SECONDS.toNanos(5)).setEndTime(TimeUnit.SECONDS.toNanos(10)).build()
val ongoingCaptureArtifact = HprofSessionArtifact(myProfilers,
Common.Session.getDefaultInstance(),
Common.SessionMetaData.getDefaultInstance(),
ongoingInfo)
assertThat(HprofArtifactView.getSubtitle(ongoingCaptureArtifact)).isEqualTo(SessionArtifact.CAPTURING_SUBTITLE)
val finishedCaptureArtifact = HprofSessionArtifact(myProfilers,
Common.Session.getDefaultInstance(),
Common.SessionMetaData.getDefaultInstance(),
finishedInfo)
assertThat(HprofArtifactView.getSubtitle(finishedCaptureArtifact)).isEqualTo("00:00:05.000")
}
private fun startSession(device: Common.Device, process: Common.Process) {
myTransportService.addDevice(device)
myTransportService.addProcess(device, process)
myTimer.tick(FakeTimer.ONE_SECOND_IN_NS)
myProfilers.setProcess(device, process)
myTimer.tick(FakeTimer.ONE_SECOND_IN_NS)
}
companion object {
const val VALID_TRACE_PATH = "tools/adt/idea/profilers-ui/testData/valid_trace.trace"
const val NEW_DEVICE_ID_1 = 1L
const val NEW_DEVICE_ID_2 = 2L
}
} |
package org.jetbrains.kotlin.test.util
import com.intellij.psi.*
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.util.SmartFMap
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtPackageDirective
import org.jetbrains.kotlin.psi.KtTreeVisitorVoid
fun PsiFile.findElementByCommentPrefix(commentText: String): PsiElement? =
findElementsByCommentPrefix(commentText).keys.singleOrNull()
fun PsiFile.findElementsByCommentPrefix(prefix: String): Map<PsiElement, String> {
var result = SmartFMap.emptyMap<PsiElement, String>()
accept(
object : KtTreeVisitorVoid() {
override fun visitComment(comment: PsiComment) {
val commentText = comment.text
if (commentText.startsWith(prefix)) {
val parent = comment.parent
val elementToAdd = when (parent) {
is KtDeclaration -> parent
is PsiMember -> parent
else -> PsiTreeUtil.skipSiblingsForward(
comment,
PsiWhiteSpace::class.java, PsiComment::class.java, KtPackageDirective::class.java
)
} ?: return
result = result.plus(elementToAdd, commentText.substring(prefix.length).trim())
}
}
}
)
return result
}
|
fun blockFun(blockArg: String.() -> Unit) =
"OK".blockArg()
fun box() {
blockFun {
this
}
}
// EXPECTATIONS ClassicFrontend JVM_IR
// test.kt:8 box:
// test.kt:5 blockFun: blockArg:kotlin.jvm.functions.Function1=TestKt$box$1
// test.kt:9 invoke: $this$blockFun:java.lang.String="OK":java.lang.String
// test.kt:10 invoke: $this$blockFun:java.lang.String="OK":java.lang.String
// test.kt:5 blockFun: blockArg:kotlin.jvm.functions.Function1=TestKt$box$1
// test.kt:11 box:
// EXPECTATIONS FIR JVM_IR
// test.kt:8 box:
// test.kt:5 blockFun: blockArg:kotlin.jvm.functions.Function1=TestKt$<lambda>
// test.kt:9 box$lambda$0: $this$blockFun:java.lang.String="OK":java.lang.String
// test.kt:10 box$lambda$0: $this$blockFun:java.lang.String="OK":java.lang.String
// test.kt:5 blockFun: blockArg:kotlin.jvm.functions.Function1=TestKt$<lambda>
// test.kt:11 box:
// EXPECTATIONS JS_IR
// test.kt:8 box:
// test.kt:5 blockFun: blockArg=Function1
// test.kt:10 box$lambda: $this$blockFun="OK":kotlin.String
// test.kt:11 box:
|
package org.jetbrains.kotlin.codegen.state
import org.jetbrains.kotlin.codegen.ClassBuilderFactory
import org.jetbrains.kotlin.codegen.ClassNameCollectionClassBuilderFactory
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.resolve.jvm.diagnostics.JvmDeclarationOrigin
import java.util.concurrent.ConcurrentHashMap
class BuilderFactoryForDuplicateClassNameDiagnostics(
builderFactory: ClassBuilderFactory,
private val state: GenerationState,
) : ClassNameCollectionClassBuilderFactory(builderFactory) {
private val className = ConcurrentHashMap<String, JvmDeclarationOrigin>()
override fun handleClashingNames(internalName: String, origin: JvmDeclarationOrigin) {
val another = className.getOrPut(internalName) { origin }
// Allow clashing classes if they are originated from the same source element. For example, this happens during inlining anonymous
// objects. In JVM IR, this also happens for anonymous classes in default arguments of tailrec functions, because default arguments
// are deep-copied (see JvmTailrecLowering).
if (origin.originalSourceElement != another.originalSourceElement) {
reportError(internalName, origin, another)
}
}
private fun reportError(internalName: String, vararg another: JvmDeclarationOrigin) {
val duplicateClasses =
another.mapNotNull { it.descriptor }.joinToString { DescriptorRenderer.ONLY_NAMES_WITH_SHORT_TYPES.render(it) }
for (origin in another) {
state.reportDuplicateClassNameError(origin, internalName, duplicateClasses)
}
}
}
|
package com.android.tools.property.panel.impl.model.util
import com.android.tools.property.panel.api.NewPropertyItem
class FakeNewPropertyItem(val properties: Map<String, FakePropertyItem> = emptyMap()) :
FakePropertyItem("", "", null, null, null), NewPropertyItem {
override var name: String = ""
set(value) {
field = value
delegate = properties[value]
}
override var delegate: FakePropertyItem? = null
// All "New" properties are considered equal, since only 1 should appear in a model
override fun equals(other: Any?) = other is FakeNewPropertyItem
override fun hashCode() = 12345
override fun isSameProperty(qualifiedName: String): Boolean {
return qualifiedName == name
}
}
|
@file:JsModule("node:dns")
package node.dns
/**
* Set the default value of `verbatim` in {@link lookup} and [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromiseslookuphostname-options).
* The value could be:
*
* * `ipv4first`: sets default `verbatim` `false`.
* * `verbatim`: sets default `verbatim` `true`.
*
* The default is `verbatim` and {@link setDefaultResultOrder} have higher
* priority than [`--dns-result-order`](https://nodejs.org/docs/latest-v20.x/api/cli.html#--dns-result-orderorder). When using
* [worker threads](https://nodejs.org/docs/latest-v20.x/api/worker_threads.html), {@link setDefaultResultOrder} from the main
* thread won't affect the default dns orders in workers.
* @since v16.4.0, v14.18.0
* @param order must be `'ipv4first'` or `'verbatim'`.
*/
external fun setDefaultResultOrder(order: SetDefaultResultOrderOrder): Unit
|
package org.jetbrains.kotlin.gradle.plugin
import org.gradle.api.Project
import org.gradle.api.logging.Logging
import org.gradle.api.provider.Property
import org.gradle.api.provider.Provider
import org.gradle.api.services.BuildService
import org.gradle.api.services.BuildServiceParameters
import org.jetbrains.kotlin.gradle.logging.kotlinDebug
import org.jetbrains.kotlin.gradle.utils.kotlinSessionsDir
import org.jetbrains.kotlin.gradle.utils.registerClassLoaderScopedBuildService
import java.io.File
internal abstract class KotlinGradleBuildServices : BuildService<KotlinGradleBuildServices.Parameters>, AutoCloseable {
interface Parameters : BuildServiceParameters {
val sessionsDir: Property<File>
}
private val log = Logging.getLogger(this.javaClass)
private val buildHandler: KotlinGradleFinishBuildHandler = KotlinGradleFinishBuildHandler()
private val multipleProjectsHolder = KotlinPluginInMultipleProjectsHolder(
trackPluginVersionsSeparately = true
)
init {
log.kotlinDebug(INIT_MESSAGE)
buildHandler.buildStart()
}
@Synchronized
internal fun detectKotlinPluginLoadedInMultipleProjects(project: Project, kotlinPluginVersion: String) {
val onRegister = {
project.gradle.taskGraph.whenReady {
if (multipleProjectsHolder.isInMultipleProjects(project, kotlinPluginVersion)) {
val loadedInProjects = multipleProjectsHolder.getAffectedProjects(project, kotlinPluginVersion)!!
if (PropertiesProvider(project).ignorePluginLoadedInMultipleProjects != true) {
project.logger.warn("\n$MULTIPLE_KOTLIN_PLUGINS_LOADED_WARNING")
project.logger.warn(
MULTIPLE_KOTLIN_PLUGINS_SPECIFIC_PROJECTS_WARNING + loadedInProjects.joinToString(limit = 4) { "'$it'" }
)
}
project.logger.info(
"$MULTIPLE_KOTLIN_PLUGINS_SPECIFIC_PROJECTS_INFO: " +
loadedInProjects.joinToString { "'$it'" }
)
}
}
}
multipleProjectsHolder.addProject(
project,
kotlinPluginVersion,
onRegister
)
}
override fun close() {
buildHandler.buildFinished(parameters.sessionsDir.get())
log.kotlinDebug(DISPOSE_MESSAGE)
}
companion object {
private val CLASS_NAME = KotlinGradleBuildServices::class.java.simpleName
private val INIT_MESSAGE = "Initialized $CLASS_NAME"
private val DISPOSE_MESSAGE = "Disposed $CLASS_NAME"
fun registerIfAbsent(project: Project): Provider<KotlinGradleBuildServices> =
project.gradle.registerClassLoaderScopedBuildService(KotlinGradleBuildServices::class) {
it.parameters.sessionsDir.set(project.kotlinSessionsDir)
}
}
}
|
import kotlin.reflect.KProperty
import kotlin.properties.ReadOnlyProperty
private operator fun String.getValue(nothing: Any?, property: KProperty<*>) = "OK"
private operator fun String.setValue(nothing: Any?, property: KProperty<*>, s: String) {}
private operator fun Int.provideDelegate(thisRef: Any?, prop: KProperty<*>): ReadOnlyProperty<Any?, Int> = ReadOnlyProperty { _, _ -> this }
private operator fun O.compareTo(other: O) = 1
private operator fun O.contains(other: O) = true
private operator fun O.invoke() {}
private operator fun O.iterator() = O
private operator fun O.next() = O
private operator fun O.hasNext() = false
private operator fun O.get(i: Int) = O
private operator fun O.set(i: Int, o: O) {}
private operator fun O.component1() = O
private operator fun O.inc() = O
private operator fun O.not() = O
private operator fun O.plus(other: O) = O
private operator fun O.unaryPlus() = O
private operator fun O.rangeTo(other: O) = O
private operator fun O.rangeUntil(other: O) = O
private operator fun O.plusAssign(other: O) {}
object O
object P
operator fun P.iterator() = P
private operator fun P.next() = P
private operator fun P.hasNext() = false
inline fun foo() {
var x by <!NON_PUBLIC_CALL_FROM_PUBLIC_INLINE, NON_PUBLIC_CALL_FROM_PUBLIC_INLINE!>""<!>
x
x = ""
val y by <!NON_PUBLIC_CALL_FROM_PUBLIC_INLINE!>1<!>
y
var o = O
o <!NON_PUBLIC_CALL_FROM_PUBLIC_INLINE!><<!> o
o <!NON_PUBLIC_CALL_FROM_PUBLIC_INLINE!>in<!> o
<!NON_PUBLIC_CALL_FROM_PUBLIC_INLINE!>o<!>()
for (o1 in <!NON_PUBLIC_CALL_FROM_PUBLIC_INLINE, NON_PUBLIC_CALL_FROM_PUBLIC_INLINE, NON_PUBLIC_CALL_FROM_PUBLIC_INLINE!>o<!>) {
}
<!NON_PUBLIC_CALL_FROM_PUBLIC_INLINE!>o[1]<!>
<!NON_PUBLIC_CALL_FROM_PUBLIC_INLINE!>o[1]<!> = o
val (<!NON_PUBLIC_CALL_FROM_PUBLIC_INLINE!>o2<!>) = o
o<!NON_PUBLIC_CALL_FROM_PUBLIC_INLINE!>++<!>
<!NON_PUBLIC_CALL_FROM_PUBLIC_INLINE!>!<!>o
o <!NON_PUBLIC_CALL_FROM_PUBLIC_INLINE!>+<!> o
<!NON_PUBLIC_CALL_FROM_PUBLIC_INLINE!>+<!>o
o<!NON_PUBLIC_CALL_FROM_PUBLIC_INLINE!>..<!>o
o<!NON_PUBLIC_CALL_FROM_PUBLIC_INLINE!>..<<!>o
O <!NON_PUBLIC_CALL_FROM_PUBLIC_INLINE!>+=<!> o
for (p in <!NON_PUBLIC_CALL_FROM_PUBLIC_INLINE, NON_PUBLIC_CALL_FROM_PUBLIC_INLINE!>P<!>) {
}
}
|
package org.jetbrains.kotlin.codegen.inline
import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap
import org.jetbrains.kotlin.codegen.SourceInfo
import org.jetbrains.kotlin.codegen.optimization.common.asSequence
import org.jetbrains.org.objectweb.asm.Label
import org.jetbrains.org.objectweb.asm.MethodVisitor
import org.jetbrains.org.objectweb.asm.Opcodes
import org.jetbrains.org.objectweb.asm.tree.LineNumberNode
import org.jetbrains.org.objectweb.asm.tree.MethodNode
import java.util.*
import kotlin.math.max
import kotlin.math.min
const val KOTLIN_STRATA_NAME = "Kotlin"
const val KOTLIN_DEBUG_STRATA_NAME = "KotlinDebug"
object SMAPBuilder {
fun build(fileMappings: List<FileMapping>, backwardsCompatibleSyntax: Boolean): String? {
if (fileMappings.isEmpty()) {
return null
}
val debugMappings = linkedMapOf<Pair<String, String>, FileMapping>()
for (fileMapping in fileMappings) {
for ((_, dest, range, callSite) in fileMapping.lineMappings) {
callSite?.let { (line, file, path) ->
debugMappings.getOrPut(file to path) { FileMapping(file, path) }.mapNewInterval(line, dest, range)
}
}
}
// Old versions of kotlinc and the IDEA plugin have incorrect implementations of SMAPParser:
// 1. they require *E between strata, which is not correct syntax according to JSR-045;
// 2. in KotlinDebug, they use `1#2,3:4` to mean "map lines 4..6 to line 1 of #2", when in reality (and in
// the non-debug stratum) this maps lines 4..6 to lines 1..3. The correct syntax is `1#2:4,3`.
val defaultStrata = fileMappings.toSMAP(KOTLIN_STRATA_NAME, mapToFirstLine = false)
val debugStrata = debugMappings.values.toSMAP(KOTLIN_DEBUG_STRATA_NAME, mapToFirstLine = !backwardsCompatibleSyntax)
if (backwardsCompatibleSyntax && defaultStrata.isNotEmpty() && debugStrata.isNotEmpty()) {
return "SMAP\n${fileMappings[0].name}\n$KOTLIN_STRATA_NAME\n$defaultStrata${SMAP.END}\n$debugStrata${SMAP.END}\n"
}
return "SMAP\n${fileMappings[0].name}\n$KOTLIN_STRATA_NAME\n$defaultStrata$debugStrata${SMAP.END}\n"
}
private fun Collection<FileMapping>.toSMAP(stratumName: String, mapToFirstLine: Boolean): String = if (isEmpty()) "" else
"${SMAP.STRATA_SECTION} $stratumName\n" +
"${SMAP.FILE_SECTION}\n${mapIndexed { id, file -> file.toSMAPFile(id + 1) }.joinToString("")}" +
"${SMAP.LINE_SECTION}\n${mapIndexed { id, file -> file.toSMAPMapping(id + 1, mapToFirstLine) }.joinToString("")}"
private fun RangeMapping.toSMAP(fileId: Int, oneLine: Boolean): String =
if (range == 1) "$source#$fileId:$dest\n" else if (oneLine) "$source#$fileId:$dest,$range\n" else "$source#$fileId,$range:$dest\n"
private fun FileMapping.toSMAPFile(id: Int): String =
"+ $id $name\n$path\n"
private fun FileMapping.toSMAPMapping(id: Int, mapToFirstLine: Boolean): String =
lineMappings.joinToString("") { it.toSMAP(id, mapToFirstLine) }
}
class SourceMapCopier(val parent: SourceMapper, private val smap: SMAP, val callSite: SourcePosition? = null) {
private val visitedLines = Int2IntOpenHashMap()
private var lastVisitedRange: RangeMapping? = null
fun mapLineNumber(lineNumber: Int): Int {
val mappedLineNumber = visitedLines.get(lineNumber)
if (mappedLineNumber > 0) {
return mappedLineNumber
}
val range = lastVisitedRange?.takeIf { lineNumber in it } ?: smap.findRange(lineNumber) ?: return -1
lastVisitedRange = range
val newLineNumber = parent.mapLineNumber(range.mapDestToSource(lineNumber), callSite ?: range.callSite)
visitedLines.put(lineNumber, newLineNumber)
return newLineNumber
}
}
class SourceMapCopyingMethodVisitor(private val smapCopier: SourceMapCopier, mv: MethodVisitor) : MethodVisitor(Opcodes.API_VERSION, mv) {
constructor(target: SourceMapper, source: SMAP, mv: MethodVisitor) : this(SourceMapCopier(target, source), mv)
override fun visitLineNumber(line: Int, start: Label) =
super.visitLineNumber(smapCopier.mapLineNumber(line), start)
override fun visitLocalVariable(name: String, descriptor: String, signature: String?, start: Label, end: Label, index: Int) =
if (isFakeLocalVariableForInline(name))
super.visitLocalVariable(updateCallSiteLineNumber(name, smapCopier::mapLineNumber), descriptor, signature, start, end, index)
else
super.visitLocalVariable(name, descriptor, signature, start, end, index)
}
data class SourcePosition(val line: Int, val file: String, val path: String)
class SourceMapper(val sourceInfo: SourceInfo?) {
constructor(name: String?, original: SMAP) : this(original.fileMappings.firstOrNull { it.name == name }?.toSourceInfo())
private var maxUsedValue: Int = sourceInfo?.linesInFile ?: 0
private var fileMappings: LinkedHashMap<Pair<String, String>, FileMapping> = linkedMapOf()
val resultMappings: List<FileMapping>
get() = fileMappings.values.toList()
companion object {
const val FAKE_FILE_NAME = "fake.kt"
const val FAKE_PATH = "kotlin/jvm/internal/FakeKt"
const val LOCAL_VARIABLE_INLINE_ARGUMENT_SYNTHETIC_LINE_NUMBER = 1
}
init {
sourceInfo?.let { sourceInfo ->
// If 'sourceFileName' is null we are dealing with a synthesized class
// (e.g., multi-file class facade with multiple parts). Such classes
// only have synthetic debug information and we use a fake file name.
val sourceFileName = sourceInfo.sourceFileName ?: FAKE_FILE_NAME
// Explicitly map the file to itself -- we'll probably need a lot of lines from it, so this will produce fewer ranges.
getOrRegisterNewSource(sourceFileName, sourceInfo.pathOrCleanFQN)
.mapNewInterval(1, 1, sourceInfo.linesInFile)
}
}
val isTrivial: Boolean
get() = maxUsedValue == 0 || maxUsedValue == sourceInfo?.linesInFile
private fun getOrRegisterNewSource(name: String, path: String): FileMapping =
fileMappings.getOrPut(name to path) { FileMapping(name, path) }
fun mapLineNumber(inlineSource: SourcePosition, inlineCallSite: SourcePosition?): Int {
val fileMapping = getOrRegisterNewSource(inlineSource.file, inlineSource.path)
val mappedLineIndex = fileMapping.mapNewLineNumber(inlineSource.line, maxUsedValue, inlineCallSite)
maxUsedValue = max(maxUsedValue, mappedLineIndex)
return mappedLineIndex
}
fun mapSyntheticLineNumber(id: Int): Int {
return mapLineNumber(SourcePosition(id, FAKE_FILE_NAME, FAKE_PATH), null)
}
}
class SMAP(val fileMappings: List<FileMapping>) {
// assuming disjoint line mappings (otherwise binary search can't be used anyway)
private val intervals = fileMappings.flatMap { it.lineMappings }.sortedBy { it.dest }
fun findRange(lineNumber: Int): RangeMapping? {
val index = intervals.binarySearch { if (lineNumber in it) 0 else it.dest - lineNumber }
return if (index < 0) null else intervals[index]
}
companion object {
const val FILE_SECTION = "*F"
const val LINE_SECTION = "*L"
const val STRATA_SECTION = "*S"
const val END = "*E"
// Create a mapping that simply maps a range of a file to itself, which is equivalent to having no mapping at all.
// The contract is: if `smap` is the return value of this method, then `SourceMapCopier(SourceMapper(name, smap), smap)`
// will not change any line numbers in any of the methods passed as an argument.
fun identityMapping(name: String?, path: String, methods: Collection<MethodNode>): SMAP {
if (name.isNullOrEmpty()) return SMAP(emptyList())
var start = 0
var end = 0
for (node in methods) {
for (insn in node.instructions.asSequence()) {
if (insn !is LineNumberNode) continue
start = min(start, insn.line)
end = max(end, insn.line + 1)
}
}
if (start >= end) return SMAP(emptyList())
return SMAP(listOf(FileMapping(name, path).apply { mapNewInterval(start, start, end - start) }))
}
}
}
data class SMAPAndMethodNode(val node: MethodNode, val classSMAP: SMAP)
class FileMapping(val name: String, val path: String) {
val lineMappings = arrayListOf<RangeMapping>()
fun toSourceInfo(): SourceInfo =
SourceInfo(name, path, lineMappings.fold(0) { result, mapping -> max(result, mapping.source + mapping.range - 1) })
fun mapNewLineNumber(source: Int, currentIndex: Int, callSite: SourcePosition?): Int {
// Save some space in the SMAP by reusing (or extending if it's the last one) the existing range.
// TODO some *other* range may already cover `source`; probably too slow to check them all though.
// Maybe keep the list ordered by `source` and use binary search to locate the closest range on the left?
val mapping = lineMappings.lastOrNull()?.takeIf { it.canReuseFor(source, currentIndex, callSite) }
?: lineMappings.firstOrNull()?.takeIf { it.canReuseFor(source, currentIndex, callSite) }
?: mapNewInterval(source, currentIndex + 1, 1, callSite)
mapping.range = max(mapping.range, source - mapping.source + 1)
return mapping.mapSourceToDest(source)
}
private fun RangeMapping.canReuseFor(newSource: Int, globalMaxDest: Int, newCallSite: SourcePosition?): Boolean =
callSite == newCallSite && (newSource - source) in 0 until range + (if (globalMaxDest in this) 10 else 0)
fun mapNewInterval(source: Int, dest: Int, range: Int, callSite: SourcePosition? = null): RangeMapping =
RangeMapping(source, dest, range, callSite, parent = this).also { lineMappings.add(it) }
}
data class RangeMapping(val source: Int, val dest: Int, var range: Int, val callSite: SourcePosition?, val parent: FileMapping) {
operator fun contains(destLine: Int): Boolean =
dest <= destLine && destLine < dest + range
fun hasMappingForSource(sourceLine: Int): Boolean =
source <= sourceLine && sourceLine < source + range
fun mapDestToSource(destLine: Int): SourcePosition =
SourcePosition(source + (destLine - dest), parent.name, parent.path)
fun mapSourceToDest(sourceLine: Int): Int =
dest + (sourceLine - source)
}
val RangeMapping.toRange: IntRange
get() = dest until dest + range
|
package org.jetbrains.kotlinx.dataframe.impl
import kotlin.concurrent.getOrSet
internal class ColumnAccessTracker {
var isEnabled = false
val accessedColumns = mutableSetOf<String>()
fun <T> track(body: () -> T): List<String> {
accessedColumns.clear()
isEnabled = true
body()
isEnabled = false
return accessedColumns.toList()
}
fun registerAccess(columnName: String) {
if (isEnabled) accessedColumns.add(columnName)
}
companion object {
fun registerColumnAccess(name: String) = get().registerAccess(name)
fun get() = columnAccessTracker.getOrSet { ColumnAccessTracker() }
}
}
internal val columnAccessTracker = ThreadLocal<ColumnAccessTracker>()
public fun trackColumnAccess(body: () -> Unit): List<String> = ColumnAccessTracker.get().track(body)
|
package org.jetbrains.kotlin.scripting.compiler.plugin
import org.jetbrains.kotlin.cli.common.environment.setIdeaIoUseFallback
import org.jetbrains.kotlin.scripting.compiler.plugin.definitions.CliScriptDefinitionProvider
import org.jetbrains.kotlin.scripting.definitions.KotlinScriptDefinition
import org.jetbrains.kotlin.scripting.definitions.ScriptDefinition
import org.jetbrains.kotlin.scripting.definitions.ScriptDefinitionsSource
import org.junit.Assert
import org.junit.Test
import java.io.File
import java.util.concurrent.atomic.AtomicInteger
import kotlin.script.experimental.api.SourceCode
import kotlin.script.experimental.host.toScriptSource
import kotlin.script.experimental.jvm.defaultJvmScriptingHostConfiguration
import kotlin.script.templates.standard.ScriptTemplateWithArgs
class ScriptProviderTest {
init {
setIdeaIoUseFallback()
}
@Test
fun testLazyScriptDefinitionsProvider() {
val genDefCounter = AtomicInteger()
val standardDef = FakeScriptDefinition()
val shadedDef = FakeScriptDefinition(".x.kts")
val provider = TestCliScriptDefinitionProvider(standardDef).apply {
setScriptDefinitions(listOf(shadedDef, standardDef))
setScriptDefinitionsSources(
listOf(
TestScriptDefinitionSource(
genDefCounter,
".y.kts",
".x.kts"
)
)
)
}
Assert.assertEquals(0, genDefCounter.get())
provider.isScript(File("a.kt").toScriptSource()).let {
Assert.assertFalse(it)
Assert.assertEquals(0, genDefCounter.get())
}
provider.isScript(File("a.y.kts").toScriptSource()).let {
Assert.assertTrue(it)
Assert.assertEquals(1, genDefCounter.get())
}
provider.isScript(File("a.x.kts").toScriptSource()).let {
Assert.assertTrue(it)
Assert.assertEquals(1, genDefCounter.get())
Assert.assertEquals(1, shadedDef.matchCounter.get())
}
provider.isScript(File("a.z.kts").toScriptSource()).let {
Assert.assertTrue(it)
Assert.assertEquals(2, genDefCounter.get())
Assert.assertEquals(1, standardDef.matchCounter.get())
}
provider.isScript(File("a.ktx").toScriptSource()).let {
Assert.assertFalse(it)
Assert.assertEquals(2, genDefCounter.get())
}
}
}
private open class FakeScriptDefinition(val suffix: String = ".kts") :
ScriptDefinition.FromLegacy(defaultJvmScriptingHostConfiguration, KotlinScriptDefinition(ScriptTemplateWithArgs::class)) {
val matchCounter = AtomicInteger()
override fun isScript(script: SourceCode): Boolean {
val path = script.locationId ?: return false
return path.endsWith(suffix).also {
if (it) matchCounter.incrementAndGet()
}
}
override val isDefault: Boolean
get() = suffix == ".kts"
}
private class TestScriptDefinitionSource(val counter: AtomicInteger, val defGens: Iterable<() -> FakeScriptDefinition>) :
ScriptDefinitionsSource {
constructor(counter: AtomicInteger, vararg suffixes: String) : this(counter, suffixes.map {
{
FakeScriptDefinition(
it
)
}
})
override val definitions: Sequence<ScriptDefinition> = sequence {
for (gen in defGens) {
counter.incrementAndGet()
yield(gen())
}
}
}
private class TestCliScriptDefinitionProvider(private val standardDef: ScriptDefinition) : CliScriptDefinitionProvider() {
@Suppress("DEPRECATION", "OverridingDeprecatedMember", "OVERRIDE_DEPRECATION")
override fun getDefaultScriptDefinition(): KotlinScriptDefinition = standardDef.legacyDefinition
}
|
open class C(val a: Any)
fun box(): String {
class L : C({}) {
}
val l = L()
val javaClass = l.a.javaClass
val enclosingMethod = javaClass.getEnclosingConstructor()!!.getName()
if (enclosingMethod != "LambdaInLocalClassSuperCallKt\$box\$L") return "ctor: $enclosingMethod"
val enclosingClass = javaClass.getEnclosingClass()!!.getName()
if (enclosingClass != "LambdaInLocalClassSuperCallKt\$box\$L") return "enclosing class: $enclosingClass"
if (enclosingMethod != enclosingClass) return "$enclosingClass != $enclosingMethod"
val declaringClass = javaClass.getDeclaringClass()
if (declaringClass != null) return "anonymous function has a declaring class: $declaringClass"
return "OK"
}
|
@file:Suppress(
"NESTED_CLASS_IN_EXTERNAL_INTERFACE",
)
package web.cssom
import seskar.js.JsValue
import seskar.js.JsVirtual
@JsVirtual
sealed external interface FontStyle {
companion object {
@JsValue("italic")
val italic: FontStyle
@JsValue("normal")
val normal: FontStyle
@JsValue("oblique")
val oblique: FontStyle
}
}
|
operator fun Int.compareTo(c: Char) = 0
fun testOverloadedCompareToCall(x: Int, y: Char) =
x < y
fun testOverloadedCompareToCallWithSmartCast(x: Any, y: Any) =
x is Int && y is Char && x < y
fun testEqualsWithSmartCast(x: Any, y: Any) =
x is Int && y is Char && x == y
class C {
operator fun Int.compareTo(c: Char) = 0
fun testMemberExtensionCompareToCall(x: Int, y: Char) =
x < y
fun testMemberExtensionCompareToCallWithSmartCast(x: Any, y: Any) =
x is Int && y is Char && x < y
} |