content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jclouds.vsphere.api import com.vmware.vim25.InvalidName import com.vmware.vim25.OptionDef import com.vmware.vim25.OptionValue import com.vmware.vim25.RuntimeFault import java.rmi.RemoteException interface OptionManagerApi { val setting: List<OptionValue> val supportedOption: List<OptionDef> @Throws(InvalidName::class, RuntimeFault::class, RemoteException::class) fun queryOptions(name: String): List<OptionValue> @Throws(InvalidName::class, RuntimeFault::class, RemoteException::class) fun updateOptions(changedValue: List<OptionValue>) }
src/main/kotlin/org/jclouds/vsphere/api/OptionManagerApi.kt
1328891870
package net.nemerosa.ontrack.service.labels import net.nemerosa.ontrack.model.labels.LabelForm import net.nemerosa.ontrack.model.labels.LabelProvider import net.nemerosa.ontrack.model.structure.Project import org.springframework.stereotype.Service @Service class NOPLabelProvider : LabelProvider { override val name: String = "NOP" override val isEnabled: Boolean = true override fun getLabelsForProject(project: Project): List<LabelForm> = emptyList() }
ontrack-service/src/main/java/net/nemerosa/ontrack/service/labels/NOPLabelProvider.kt
3886037849
package top.zbeboy.isy.service.cache /** * 缓存相关key 与 有效期配置 * * @author zbeboy * @version 1.1 * @since 1.0 */ open class CacheBook { companion object { /* 配置通用到期时间 */ @JvmField val EXPIRES_SECONDS: Long = 1800 @JvmField val EXPIRES_MINUTES: Long = 30 @JvmField val EXPIRES_HOURS: Long = 4 @JvmField val EXPIRES_DAYS: Long = 1 @JvmField val EXPIRES_YEAR: Long = 365 /* 特殊到期时间 */ @JvmField val EXPIRES_APPLICATION_ID_DAYS: Long = 2 @JvmField val EXPIRES_GRADUATION_DESIGN_TEACHER_STUDENT_DAYS: Long = 30 @JvmField val EXPIRES_SCHOOL_INFO_DAYS: Long = 300 /* 配置 KEY */ const val QUERY_USER_TYPE_BY_NAME = "QUERY_USER_TYPE_BY_NAME" const val QUERY_USER_TYPE_BY_ID = "QUERY_USER_TYPE_BY_ID" const val QUERY_SYSTEM_ALERT_TYPE_BY_NAME = "QUERY_SYSTEM_ALERT_TYPE_BY_NAME" const val MENU_HTML = "MENU_HTML_" const val SCHOOL_INFO_PATH = "SCHOOL_INFO_PATH_" const val USER_APPLICATION_ID = "USER_APPLICATION_ID_" const val URL_MAPPING = "URL_MAPPING_" const val USER_ROLE_ID = "USER_ROLE_ID_" const val USER_ROLE = "USER_ROLE_" const val USER_KEY = "USER_KEY_" const val USER_COLLEGE_ID = "USER_COLLEGE_ID_" const val USER_DEPARTMENT_ID = "USER_DEPARTMENT_ID_" const val USER_ORGANIZE_INFO = "USER_ORGANIZE_INFO_" const val INTERNSHIP_BASE_CONDITION = "INTERNSHIP_BASE_CONDITION_" const val GRADUATION_DESIGN_BASE_CONDITION = "GRADUATION_DESIGN_BASE_CONDITION_" const val GRADUATION_DESIGN_TEACHER_STUDENT_COUNT = "GRADUATION_DESIGN_TEACHER_STUDENT_COUNT_" const val GRADUATION_DESIGN_TEACHER_STUDENT = "GRADUATION_DESIGN_TEACHER_STUDENT_" const val GRADUATION_DESIGN_PHARMTECH_STUDENT = "GRADUATION_DESIGN_PHARMTECH_STUDENT_" const val GRADUATION_DESIGN_PHARMTECH_STUDENT_LIST = "GRADUATION_DESIGN_PHARMTECH_STUDENT_LIST_" const val GRADUATION_DESIGN_ADJUSTECH_SYNC_TIME = "GRADUATION_DESIGN_ADJUSTECH_SYNC_TIME_" } }
src/main/java/top/zbeboy/isy/service/cache/CacheBook.kt
152768388
package co.smartreceipts.android.identity.widget.login.model import org.junit.Assert.* import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner @RunWith(RobolectricTestRunner::class) class UiInputValidationIndicatorTest { @Test @Throws(Exception::class) fun getters() { val indicator1 = UiInputValidationIndicator("test1", true, true) assertEquals("test1", indicator1.message) assertTrue(indicator1.isEmailValid) assertTrue(indicator1.isPasswordValid) val indicator2 = UiInputValidationIndicator("test2", false, false) assertEquals("test2", indicator2.message) assertFalse(indicator2.isEmailValid) assertFalse(indicator2.isPasswordValid) } }
app/src/test/java/co/smartreceipts/android/identity/widget/login/model/UiInputValidationIndicatorTest.kt
1181418133
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.keychain import com.intellij.openapi.diagnostic.Logger val LOG: Logger = Logger.getInstance(CredentialsStore::class.java) public class Credentials(id: String?, token: String?) { public val id: String? = if (id.isNullOrEmpty()) null else id public val token: String? = if (token.isNullOrEmpty()) null else token override fun equals(other: Any?): Boolean { if (other !is Credentials) return false return id == other.id && token == other.token } override fun hashCode(): Int { return (id?.hashCode() ?: 0) * 37 + (token?.hashCode() ?: 0) } } public fun Credentials?.isFulfilled(): Boolean = this != null && id != null && token != null public interface CredentialsStore { public fun get(host: String?, sshKeyFile: String? = null): Credentials? public fun save(host: String?, credentials: Credentials, sshKeyFile: String? = null) public fun reset(host: String) }
plugins/settings-repository/src/keychain/CredentialsStore.kt
2162943618
package de.ph1b.audiobook.uitools import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import de.ph1b.audiobook.misc.layoutInflater import kotlinx.android.extensions.LayoutContainer open class ExtensionsHolder(itemView: View) : RecyclerView.ViewHolder(itemView), LayoutContainer { constructor(parent: ViewGroup, layoutRes: Int) : this( parent.layoutInflater().inflate( layoutRes, parent, false ) ) final override val containerView: View? get() = itemView }
app/src/main/java/de/ph1b/audiobook/uitools/ExtensionsHolder.kt
3801066279
package com.crimson.addect.feature.playscreen import com.crimson.addect.R import com.crimson.addect.dagger.component.ActivityComponent import com.crimson.addect.databinding.PlayActivityBinding import com.crimson.addect.feature.base.BaseActivity class PlayActivity : BaseActivity<PlayActivityBinding, PlayViewModel>() { override fun layoutId(): Int = R.layout.activity_play override fun onComponentCreated(activityComponent: ActivityComponent) { activityComponent.inject(this) } }
app/src/main/java/com/crimson/addect/feature/playscreen/PlayActivity.kt
3943967907
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.debugger.connection import com.intellij.ide.browsers.WebBrowser import com.intellij.openapi.Disposable import com.intellij.openapi.util.Disposer import com.intellij.util.EventDispatcher import com.intellij.util.containers.ContainerUtil import com.intellij.util.io.socketConnection.ConnectionState import com.intellij.util.io.socketConnection.ConnectionStatus import com.intellij.util.io.socketConnection.SocketConnectionListener import org.jetbrains.annotations.TestOnly import org.jetbrains.concurrency.AsyncPromise import org.jetbrains.concurrency.Promise import org.jetbrains.concurrency.isPending import org.jetbrains.concurrency.resolvedPromise import org.jetbrains.debugger.DebugEventListener import org.jetbrains.debugger.Vm import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicReference import javax.swing.event.HyperlinkListener abstract class VmConnection<T : Vm> : Disposable { open val browser: WebBrowser? = null private val stateRef = AtomicReference(ConnectionState(ConnectionStatus.NOT_CONNECTED)) private val dispatcher = EventDispatcher.create(DebugEventListener::class.java) private val connectionDispatcher = ContainerUtil.createLockFreeCopyOnWriteList<(ConnectionState) -> Unit>() @Volatile var vm: T? = null protected set private val opened = AsyncPromise<Any?>() private val closed = AtomicBoolean() val state: ConnectionState get() = stateRef.get() fun addDebugListener(listener: DebugEventListener) { dispatcher.addListener(listener) } @TestOnly fun opened(): Promise<*> = opened fun executeOnStart(runnable: Runnable) { opened.done { runnable.run() } } protected fun setState(status: ConnectionStatus, message: String? = null, messageLinkListener: HyperlinkListener? = null) { val newState = ConnectionState(status, message, messageLinkListener) val oldState = stateRef.getAndSet(newState) if (oldState == null || oldState.status != status) { if (status == ConnectionStatus.CONNECTION_FAILED) { opened.setError(newState.message) } for (listener in connectionDispatcher) { listener(newState) } } } fun stateChanged(listener: (ConnectionState) -> Unit) { connectionDispatcher.add(listener) } // backward compatibility, go debugger fun addListener(listener: SocketConnectionListener) { stateChanged { listener.statusChanged(it.status) } } protected val debugEventListener: DebugEventListener get() = dispatcher.multicaster protected open fun startProcessing() { opened.setResult(null) } fun close(message: String?, status: ConnectionStatus) { if (!closed.compareAndSet(false, true)) { return } if (opened.isPending) { opened.setError("closed") } setState(status, message) Disposer.dispose(this, false) } override fun dispose() { vm = null } open fun detachAndClose(): Promise<*> { if (opened.isPending) { opened.setError("detached and closed") } val currentVm = vm val callback: Promise<*> if (currentVm == null) { callback = resolvedPromise() } else { vm = null callback = currentVm.attachStateManager.detach() } close(null, ConnectionStatus.DISCONNECTED) return callback } }
platform/script-debugger/debugger-ui/src/org/jetbrains/debugger/connection/VmConnection.kt
1334710588
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.configurationStore import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.ComponentManager /** * Trivial implementation used in tests and in the headless mode. */ internal class HeadlessSaveAndSyncHandler : BaseSaveAndSyncHandler() { override fun scheduleSave(task: SaveTask, forceExecuteImmediately: Boolean) {} override fun scheduleRefresh() {} override fun refreshOpenFiles() {} override fun blockSaveOnFrameDeactivation() {} override fun unblockSaveOnFrameDeactivation() {} override fun blockSyncOnFrameActivation() {} override fun unblockSyncOnFrameActivation() {} override fun saveSettingsUnderModalProgress(componentManager: ComponentManager, isSaveAppAlso: Boolean): Boolean { StoreUtil.saveSettings(componentManager, forceSavingAllSettings = true) if (isSaveAppAlso && componentManager !== ApplicationManager.getApplication()) { StoreUtil.saveSettings(ApplicationManager.getApplication(), forceSavingAllSettings = true) } return true } }
platform/configuration-store-impl/src/HeadlessSaveAndSyncHandler.kt
2357886011
package com.afzaln.awakedebug.ui import androidx.lifecycle.MediatorLiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.afzaln.awakedebug.DebuggingType import com.afzaln.awakedebug.Injector import com.afzaln.awakedebug.ToggleController import com.afzaln.awakedebug.data.Prefs import com.afzaln.awakedebug.data.SystemSettings /** * Responsible for handling logic related to * enabling and disabling the Awake for Debug * setting. Also, for publishing the UI state * to liveData observers. */ class ToggleViewModel( private val systemSettings: SystemSettings = Injector.systemSettings, private val prefs: Prefs = Injector.prefs, private val shortcuts: Shortcuts = Injector.shortcuts, private val toggleController: ToggleController = Injector.toggleController ) : ViewModel() { private val settingsLiveData = MutableLiveData(SettingsUiState()) val uiStateLiveData = MediatorLiveData<SettingsUiState>().apply { addSource(settingsLiveData) { emit () } addSource(toggleController.visibleDebugNotifications) { emit() } addSource(systemSettings.screenTimeoutLiveData) { emit() } } private fun MediatorLiveData<*>.emit() { val settings = settingsLiveData.value ?: return val activeNotification = toggleController.visibleDebugNotifications.value ?: return val screenTimeout = systemSettings.screenTimeoutLiveData.value ?: return value = settings.copy( screenTimeout = screenTimeout, debuggingStatus = activeNotification ) } init { val settingsUiState = SettingsUiState(prefs.awakeDebug, prefs.usbDebugging, prefs.wifiDebugging) settingsLiveData.value = settingsUiState } fun setDebugAwake(shouldEnable: Boolean) { toggleController.toggle(shouldEnable) shortcuts.updateShortcuts() settingsLiveData.value = SettingsUiState( debugAwake = prefs.awakeDebug, usbDebugging = prefs.usbDebugging, wifiDebugging = prefs.wifiDebugging, screenTimeout = systemSettings.screenTimeoutLiveData.value ?: 0 ) } fun toggleUsbDebugging(shouldEnable: Boolean) { prefs.usbDebugging = shouldEnable setDebugAwake(prefs.awakeDebug) } fun toggleWifiDebugging(shouldEnable: Boolean) { prefs.wifiDebugging = shouldEnable setDebugAwake(prefs.awakeDebug) } data class SettingsUiState( val debugAwake: Boolean = false, val usbDebugging: Boolean = true, val wifiDebugging: Boolean = true, val screenTimeout: Int = 0, val debuggingStatus: List<DebuggingType> = listOf(DebuggingType.NONE) ) }
app/src/main/java/com/afzaln/awakedebug/ui/ToggleViewModel.kt
785208959
package com.werb.moretype.me /** * Created by wanbo on 2017/7/15. */ data class MeInfo(val name: String, val desc: String, val icon: String, val email: String, val gitHub: String, val weiBo: String)
app/src/main/java/com/werb/moretype/me/MeInfo.kt
3414716075
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.causeway.client.kroviz.ui.core import io.kvision.core.CssSize import io.kvision.core.UNIT import io.kvision.core.Widget import io.kvision.form.FormPanel import io.kvision.html.Button import io.kvision.html.ButtonStyle import io.kvision.panel.HPanel import io.kvision.panel.vPanel import org.apache.causeway.client.kroviz.to.ValueType import org.apache.causeway.client.kroviz.ui.dialog.Controller import org.apache.causeway.client.kroviz.ui.dialog.DiagramDialog import org.apache.causeway.client.kroviz.ui.kv.override.RoWindow import org.apache.causeway.client.kroviz.utils.Direction import org.apache.causeway.client.kroviz.utils.IconManager import org.apache.causeway.client.kroviz.utils.Point import io.kvision.html.Link as KvisionHtmlLink class RoDialog( caption: String, val items: List<FormItem> = mutableListOf(), val controller: Controller, defaultAction: String = "OK", widthPerc: Int = 30, heightPerc: Int = 50, menu: List<KvisionHtmlLink>? = null, customButtons: List<FormItem> = emptyList() ) : Displayable, RoWindow(caption = caption, closeButton = true, menu = menu) { private val okButton = Button( text = defaultAction, icon = IconManager.find(defaultAction), style = ButtonStyle.SUCCESS ) .onClick { execute() } private val cancelButton = Button( "Cancel", "fas fa-times", ButtonStyle.OUTLINEINFO ) .onClick { close() } @Deprecated("remove once leaflet/svg is fully operational") private val scaleUpButton = Button( "", "fas fa-plus", ButtonStyle.OUTLINEINFO ) .onClick { (controller as DiagramDialog).scale(Direction.UP) } @Deprecated("remove once leaflet/svg is fully operational") private val scaleDownButton = Button( "", "fas fa-minus", ButtonStyle.OUTLINEINFO ) .onClick { (controller as DiagramDialog).scale(Direction.DOWN) } var formPanel: FormPanel<String>? = null init { icon = IconManager.find(caption) isDraggable = true isResizable = true closeButton = true contentWidth = CssSize(widthPerc, UNIT.perc) contentHeight = CssSize(heightPerc, UNIT.perc) vPanel() { height = CssSize(heightPerc, UNIT.vh) this.addCssClass("dialog") formPanel = FormPanelFactory(items).panel formPanel!!.addCssClass("dialog-content") add(formPanel!!) val buttonBar = buildButtonBar(customButtons) buttonBar.addCssClass("button-bar") add(buttonBar) } } private fun buildButtonBar(customButtons: List<FormItem>): HPanel { val buttonBar = HPanel(spacing = 10) buttonBar.add(okButton) customButtons.forEach { val b = createButton(it) buttonBar.add(b) } buttonBar.add(cancelButton) if (items.isNotEmpty() && hasScalableContent()) { buttonBar.add(scaleUpButton) buttonBar.add(scaleDownButton) } return buttonBar } private fun execute() { controller.execute() close() } fun open(at: Point = Point(x = 100, y = 100)): Widget { ViewManager.openDialog(this, at) super.show() okButton.focus() return this } override fun close() { hide() super.remove(this) clearParent() dispose() } @Deprecated("remove once leaflet/svg is fully operational") private fun hasScalableContent(): Boolean { val scalable = items.firstOrNull { it.type == ValueType.IMAGE } return scalable != null } override fun toggleMaximize() { execute() } /** * Minimize or restore the window size. */ override fun toggleMinimize() { //TODO put Dialog to lower right message box } private fun createButton(fi: FormItem): Button { val item = Button(text = fi.label, icon = IconManager.find(fi.label)) val obj = fi.callBack!! as Controller val action = fi.callBackAction item.onClick { obj.execute(action) } return item } }
incubator/clients/kroviz/src/main/kotlin/org/apache/causeway/client/kroviz/ui/core/RoDialog.kt
2294598231
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.navbar import com.intellij.ui.SimpleTextAttributes import org.jetbrains.annotations.Nls import javax.swing.Icon /** * Data needed to present a navigation bar item within the bar itself or a popup menu. */ class NavBarItemPresentation( /** * Icon to be shown */ val icon: Icon?, /** * A mandatory text to be shown in the navigation bar */ @get:Nls val text: String, /** * An optional text to be shown in a popup menu. Falling back to <link>text</link> if <code>null</code>. */ @get:Nls val popupText: String?, /** * Text attributes to highlight the text. */ val textAttributes: SimpleTextAttributes, /** * Not used, tobe deleted */ @Deprecated("not used, to be deleted") val selectedTextAttributes: SimpleTextAttributes )
platform/lang-impl/src/com/intellij/ide/navbar/NavBarItemPresentation.kt
1763809704
package io.boxtape.cli.core.resolution.dispensary import com.google.common.collect.Multimap import org.apache.commons.io.FilenameUtils import java.io.File public data class DispensaryLookupRequest( val requirements:List<String> ) public data class DispensaryLookupResultSet(val matches: Multimap<String,LookupResult>) public data class LookupResult(val name: String, val url: String) { fun toPath(): String { return name.replace("@","/") } fun toPath(root: String): String { return FilenameUtils.concat(root,toPath()) } fun toBoxtapeFilePath(root:String):String { return FilenameUtils.concat(toPath(root), "boxtape.yml") } fun toBoxtapeFile(root:String): File { return File(toBoxtapeFilePath(root)) } }
boxtape-cli/src/main/java/io/boxtape/cli/core/resolution/dispensary/DispensaryLookupRequest.kt
1176162797
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.codeInsight.gradle import com.intellij.build.SyncViewManager import com.intellij.build.events.BuildEvent import com.intellij.build.events.MessageEvent import com.intellij.build.events.impl.MessageEventImpl import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.testFramework.replaceService import com.intellij.workspaceModel.ide.WorkspaceModel import junit.framework.AssertionFailedError import junit.framework.TestCase.* import org.jetbrains.kotlin.idea.core.script.ScriptConfigurationManager import org.jetbrains.kotlin.idea.core.script.applySuggestedScriptConfiguration import org.jetbrains.kotlin.idea.core.script.configuration.CompositeScriptConfigurationManager import org.jetbrains.kotlin.idea.core.script.configuration.loader.DefaultScriptConfigurationLoader import org.jetbrains.kotlin.idea.core.script.configuration.loader.ScriptConfigurationLoadingContext import org.jetbrains.kotlin.idea.core.script.configuration.utils.areSimilar import org.jetbrains.kotlin.idea.core.script.configuration.utils.getKtFile import org.jetbrains.kotlin.idea.core.script.ucache.KotlinScriptEntity import org.jetbrains.kotlin.idea.core.script.ucache.KotlinScriptLibraryRootTypeId import org.jetbrains.kotlin.idea.core.script.ucache.listDependencies import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.scripting.definitions.ScriptDefinition import org.jetbrains.kotlin.scripting.resolve.ScriptCompilationConfigurationWrapper import org.jetbrains.plugins.gradle.settings.GradleSettings import org.jetbrains.plugins.gradle.tooling.annotation.TargetVersions import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized import org.junit.runners.Parameterized.Parameters import java.io.File import kotlin.test.assertFailsWith @RunWith(value = Parameterized::class) @Suppress("ACCIDENTAL_OVERRIDE") abstract class GradleKtsImportTest : KotlinGradleImportingTestCase() { companion object { @JvmStatic @Suppress("ACCIDENTAL_OVERRIDE") @Parameters(name = "{index}: with Gradle-{0}") fun data(): Collection<Array<Any?>> = listOf(arrayOf("6.0.1")) } val projectDir: File get() = File(GradleSettings.getInstance(myProject).linkedProjectsSettings.first().externalProjectPath) internal val scriptConfigurationManager: CompositeScriptConfigurationManager get() = ScriptConfigurationManager.getInstance(myProject) as CompositeScriptConfigurationManager override fun testDataDirName(): String = "gradleKtsImportTest" class WorkspaceModelSyncTest : GradleKtsImportTest() { @Test @TargetVersions("6.0.1+") fun testWorkspaceModelInSyncAfterImport() { Registry.get("kotlin.scripts.as.entities").setValue(true) configureByFiles() importProject() checkEquivalence("build.gradle.kts") checkEquivalence("settings.gradle.kts") } private fun checkEquivalence(fileName: String) { val ktsFile = KtsFixture(fileName).virtualFile val (managerClassFiles, managerSourceFiles) = getDependenciesFromManager(ktsFile) val (sdkClasses, sdkSources) = getSdkDependencies(ktsFile) val entityStorage = WorkspaceModel.getInstance(myProject).entityStorage.current val scriptEntity = entityStorage.entities(KotlinScriptEntity::class.java).find { it.path.contains(fileName) } ?: error("Workspace model is unaware of script $fileName") val entityClassFiles = scriptEntity.listDependencies(KotlinScriptLibraryRootTypeId.COMPILED) val entitySourceFiles = scriptEntity.listDependencies(KotlinScriptLibraryRootTypeId.SOURCES) assertEquals("Class dependencies for $fileName are not equivalent", entityClassFiles, managerClassFiles + sdkClasses) assertEquals("Source dependencies for $fileName are not equivalent", entitySourceFiles, managerSourceFiles + sdkSources) } // classes, sources private fun getDependenciesFromManager(file: VirtualFile): Pair<Collection<VirtualFile>, Collection<VirtualFile>> { val managerClassFiles = scriptConfigurationManager.getScriptDependenciesClassFiles(file) val managerSourceFiles = scriptConfigurationManager.getScriptDependenciesSourceFiles(file) return Pair(managerClassFiles, managerSourceFiles) } // classes, sources private fun getSdkDependencies(file: VirtualFile): Pair<Collection<VirtualFile>, Collection<VirtualFile>> { val managerClassFiles = scriptConfigurationManager.getScriptSdkDependenciesClassFiles(file) val managerSourceFiles = scriptConfigurationManager.getScriptSdkDependenciesSourceFiles(file) return Pair(managerClassFiles, managerSourceFiles) } } class Empty : GradleKtsImportTest() { @Test @TargetVersions("6.0.1+") fun testEmpty() { configureByFiles() importProject() checkConfiguration("build.gradle.kts") } } class Error : GradleKtsImportTest() { @Test @TargetVersions("6.0.1+") fun testError() { val events = mutableListOf<BuildEvent>() val syncViewManager = object : SyncViewManager(myProject) { override fun onEvent(buildId: Any, event: BuildEvent) { events.add(event) } } myProject.replaceService(SyncViewManager::class.java, syncViewManager, testRootDisposable) configureByFiles() assertFailsWith<AssertionFailedError> { importProject() } val expectedErrorMessage = "Unresolved reference: unresolved" val errors = events.filterIsInstance<MessageEventImpl>().filter { it.kind == MessageEvent.Kind.ERROR } val buildScriptErrors = errors.filter { it.message == expectedErrorMessage } assertTrue( "$expectedErrorMessage error has not been reported among other errors: $errors", buildScriptErrors.isNotEmpty() ) } } class CompositeBuild2 : GradleKtsImportTest() { @Test @TargetVersions("6.0.1+") fun testCompositeBuild() { configureByFiles() importProject() checkConfiguration( "settings.gradle.kts", "build.gradle.kts", "subProject/build.gradle.kts", "subBuild/settings.gradle.kts", "subBuild/build.gradle.kts", "subBuild/subProject/build.gradle.kts", "buildSrc/settings.gradle.kts", "buildSrc/build.gradle.kts", "buildSrc/subProject/build.gradle.kts" ) } } protected fun checkConfiguration(vararg files: String) { val scripts = files.map { KtsFixture(it).also { kts -> assertTrue("Configuration for ${kts.file.path} is missing", scriptConfigurationManager.hasConfiguration(kts.psiFile)) kts.imported = scriptConfigurationManager.getConfiguration(kts.psiFile)!! } } // reload configuration and check this it is not changed scripts.forEach { val reloadedConfiguration = scriptConfigurationManager.default.runLoader( it.psiFile, object : DefaultScriptConfigurationLoader(it.psiFile.project) { override fun shouldRunInBackground(scriptDefinition: ScriptDefinition) = false override fun loadDependencies( isFirstLoad: Boolean, ktFile: KtFile, scriptDefinition: ScriptDefinition, context: ScriptConfigurationLoadingContext ): Boolean { val vFile = ktFile.originalFile.virtualFile val result = getConfigurationThroughScriptingApi(ktFile, vFile, scriptDefinition) context.saveNewConfiguration(vFile, result) return true } } ) requireNotNull(reloadedConfiguration) // todo: script configuration can have different accessors, need investigation // assertTrue(areSimilar(it.imported, reloadedConfiguration)) it.assertNoSuggestedConfiguration() } // clear memory cache and check everything loaded from FS ScriptConfigurationManager.clearCaches(myProject) scripts.forEach { val fromFs = scriptConfigurationManager.getConfiguration(it.psiFile)!! assertTrue(areSimilar(it.imported, fromFs)) } } inner class KtsFixture(fileName: String) { val file = projectDir.resolve(fileName) val virtualFile get() = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file)!! val psiFile get() = myProject.getKtFile(virtualFile)!! lateinit var imported: ScriptCompilationConfigurationWrapper fun assertNoSuggestedConfiguration() { assertFalse(virtualFile.applySuggestedScriptConfiguration(myProject)) } } }
plugins/kotlin/gradle/gradle-java/tests/test/org/jetbrains/kotlin/idea/codeInsight/gradle/GradleKtsImportTest.kt
4090973471
package test import IdCacheKeyGenerator import codegen.models.HeroParentTypeDependentFieldQuery import codegen.models.MergedFieldWithSameShapeQuery import codegen.models.type.Episode import com.apollographql.apollo3.ApolloClient import com.apollographql.apollo3.annotations.ApolloExperimental import com.apollographql.apollo3.api.ApolloResponse import com.apollographql.apollo3.api.Optional import com.apollographql.apollo3.api.Query import com.apollographql.apollo3.cache.normalized.ApolloStore import com.apollographql.apollo3.cache.normalized.FetchPolicy import com.apollographql.apollo3.cache.normalized.api.MemoryCacheFactory import com.apollographql.apollo3.cache.normalized.fetchPolicy import com.apollographql.apollo3.cache.normalized.store import com.apollographql.apollo3.mockserver.MockServer import com.apollographql.apollo3.mockserver.enqueue import com.apollographql.apollo3.testing.runTest import testFixtureToUtf8 import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue @OptIn(ApolloExperimental::class) class BasicTest { private lateinit var mockServer: MockServer private lateinit var apolloClient: ApolloClient private lateinit var store: ApolloStore private suspend fun setUp() { store = ApolloStore( normalizedCacheFactory = MemoryCacheFactory(), cacheKeyGenerator = IdCacheKeyGenerator ) mockServer = MockServer() apolloClient = ApolloClient.Builder().serverUrl(mockServer.url()).store(store).build() } private suspend fun tearDown() { mockServer.stop() } private fun <D : Query.Data> basicTest(resourceName: String, query: Query<D>, block: ApolloResponse<D>.() -> Unit) = runTest(before = { setUp() }, after = { tearDown() }) { mockServer.enqueue(testFixtureToUtf8(resourceName)) var response = apolloClient.query(query).fetchPolicy(FetchPolicy.NetworkOnly).execute() response.block() response = apolloClient.query(query).fetchPolicy(FetchPolicy.CacheOnly).execute() response.block() } @Test @Throws(Exception::class) fun heroParentTypeDependentField() = basicTest( "HeroParentTypeDependentField.json", HeroParentTypeDependentFieldQuery(Optional.Present(Episode.NEWHOPE)) ) { assertFalse(hasErrors()) assertEquals(data?.hero?.name, "R2-D2") assertEquals(data?.hero?.name, "R2-D2") val hero = data?.hero?.asDroid!! assertEquals(hero.friends?.size, 3) assertEquals(hero.name, "R2-D2") assertEquals(hero.friends?.get(0)?.name, "Luke Skywalker") assertEquals(hero.friends?.get(0)?.name, "Luke Skywalker") assertEquals((hero.friends?.get(0)?.asHuman2)?.height, 1.72) } @Test fun polymorphicDroidFieldsGetParsedToDroid() = basicTest( "MergedFieldWithSameShape_Droid.json", MergedFieldWithSameShapeQuery(Optional.Present(Episode.NEWHOPE)) ) { assertFalse(hasErrors()) assertTrue(data?.hero?.asDroid != null) assertEquals(data?.hero?.asDroid?.__typename, "Droid") assertEquals(data?.hero?.asDroid?.property, "Astromech") } @Test fun polymorphicHumanFieldsGetParsedToHuman() = basicTest( "MergedFieldWithSameShape_Human.json", MergedFieldWithSameShapeQuery(Optional.Present(Episode.NEWHOPE)) ) { assertFalse(hasErrors()) assertTrue(data?.hero?.asHuman != null) assertEquals(data?.hero?.asHuman?.__typename, "Human") assertEquals(data?.hero?.asHuman?.property, "Tatooine") } }
tests/models-compat/src/commonTest/kotlin/test/BasicTest.kt
3793400679
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea import com.intellij.psi.PsiDocumentManager import junit.framework.TestCase import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithAllCompilerChecks import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor import org.jetbrains.kotlin.idea.core.script.ScriptConfigurationManager import org.jetbrains.kotlin.idea.imports.importableFqName import org.jetbrains.kotlin.idea.project.ResolveElementCache import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.name.SpecialNames import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.findDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.getParentOfType import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.idea.test.util.elementByOffset import org.jetbrains.kotlin.types.typeUtil.containsError import org.junit.internal.runners.JUnit38ClassRunner import org.junit.runner.RunWith @RunWith(JUnit38ClassRunner::class) class ResolveElementCacheTest : AbstractResolveElementCacheTest() { fun testFullResolveCaching() { doTest { this.testResolveCaching() } } private fun Data.testResolveCaching() { // resolve statements in "a()" val statement1 = statements[0] val statement2 = statements[1] val aFunBodyContext1 = statement1.analyze(BodyResolveMode.FULL) val aFunBodyContext2 = statement2.analyze(BodyResolveMode.FULL) assert(aFunBodyContext1 === aFunBodyContext2) val aFunBodyContext3 = statement1.analyze(BodyResolveMode.FULL) assert(aFunBodyContext3 === aFunBodyContext1) val bFun = members[1] as KtNamedFunction val bBody = bFun.bodyBlockExpression!! val bStatement = bBody.statements[0] val bFunBodyContext = bStatement.analyze(BodyResolveMode.FULL) // modify body of "b()" bBody.addAfter(factory.createExpression("x()"), bBody.lBrace) val bFunBodyContextAfterChange1 = bStatement.analyze(BodyResolveMode.FULL) assert(bFunBodyContext !== bFunBodyContextAfterChange1) if (file.isPhysical) { // for non-physical files we reset caches for whole file val aFunBodyContextAfterChange1 = statement1.analyze(BodyResolveMode.FULL) assert(aFunBodyContextAfterChange1 === aFunBodyContext1) // change in other function's body should not affect resolve of other one } // add parameter to "b()" this should invalidate all resolve bFun.valueParameterList!!.addParameter(factory.createParameter("p: Int")) val aFunBodyContextAfterChange2 = statement1.analyze(BodyResolveMode.FULL) assert(aFunBodyContextAfterChange2 !== aFunBodyContext1) val bFunBodyContextAfterChange2 = bStatement.analyze(BodyResolveMode.FULL) assert(bFunBodyContextAfterChange2 !== bFunBodyContextAfterChange1) } fun testNonPhysicalFileFullResolveCaching() { doTest { val nonPhysicalFile = KtPsiFactory.contextual(file).createFile("NonPhysical.kt", FILE_TEXT) val nonPhysicalData = extractData(nonPhysicalFile) nonPhysicalData.testResolveCaching() // now check how changes in the physical file affect non-physical one val statement = nonPhysicalData.statements[0] val nonPhysicalContext1 = statement.analyze(BodyResolveMode.FULL) statements[0].delete() val nonPhysicalContext2 = statement.analyze(BodyResolveMode.FULL) assert(nonPhysicalContext2 === nonPhysicalContext1) // change inside function's body should not affect other files members[2].delete() val nonPhysicalContext3 = statement.analyze(BodyResolveMode.FULL) assert(nonPhysicalContext3 !== nonPhysicalContext1) // and now check that non-physical changes do not affect physical world val physicalContext1 = statements[1].analyze(BodyResolveMode.FULL) nonPhysicalData.members[0].delete() val physicalContext2 = statements[1].analyze(BodyResolveMode.FULL) assert(physicalContext1 === physicalContext2) } } fun testResolveSurvivesTypingInCodeBlock() { doTest { val statement = statements[0] val bindingContext1 = statement.analyze(BodyResolveMode.FULL) val classConstructorParamTypeRef = klass.primaryConstructor!!.valueParameters.first().typeReference!! val bindingContext2 = classConstructorParamTypeRef.analyze(BodyResolveMode.FULL) val documentManager = PsiDocumentManager.getInstance(project) val document = documentManager.getDocument(file)!! documentManager.doPostponedOperationsAndUnblockDocument(document) // modify body of "b()" via document val bFun = members[1] as KtNamedFunction val bBody = bFun.bodyBlockExpression!! document.insertString(bBody.lBrace!!.startOffset + 1, "x()") documentManager.commitAllDocuments() val bindingContext3 = statement.analyze(BodyResolveMode.FULL) assert(bindingContext3 === bindingContext1) val bindingContext4 = classConstructorParamTypeRef.analyze(BodyResolveMode.FULL) assert(bindingContext4 === bindingContext2) // insert statement in "a()" document.insertString(statement.startOffset, "x()\n") documentManager.commitAllDocuments() val bindingContext5 = (members[0] as KtNamedFunction).bodyExpression!!.analyze(BodyResolveMode.FULL) assert(bindingContext5 !== bindingContext1) val bindingContext6 = classConstructorParamTypeRef.analyze(BodyResolveMode.FULL) assert(bindingContext6 === bindingContext2) } } fun testPartialResolveUsesFullResolveCached() { doTest { val statement1 = statements[0] val statement2 = statements[1] val bindingContext1 = statement1.analyze(BodyResolveMode.FULL) val bindingContext2 = statement2.analyze(BodyResolveMode.PARTIAL) assert(bindingContext2 === bindingContext1) val bindingContext3 = statement2.analyze(BodyResolveMode.PARTIAL_FOR_COMPLETION) assert(bindingContext3 === bindingContext1) val bindingContext4 = statement2.analyze(BodyResolveMode.PARTIAL_WITH_DIAGNOSTICS) assert(bindingContext4 === bindingContext1) } } fun testPartialResolveCaching() { doTest { this.testPartialResolveCaching(BodyResolveMode.PARTIAL) } } fun testPartialForCompletionResolveCaching() { doTest { this.testPartialResolveCaching(BodyResolveMode.PARTIAL_FOR_COMPLETION) } } private fun Data.testPartialResolveCaching(mode: BodyResolveMode) { val statement1 = statements[0] val statement2 = statements[1] val bindingContext1 = statement1.analyze(mode) val bindingContext2 = statement2.analyze(mode) assert(bindingContext1 !== bindingContext2) val bindingContext3 = statement1.analyze(mode) val bindingContext4 = statement2.analyze(mode) assert(bindingContext3 === bindingContext1) assert(bindingContext4 === bindingContext2) file.add(factory.createFunction("fun foo(){}")) val bindingContext5 = statement1.analyze(mode) assert(bindingContext5 !== bindingContext1) statement1.parent.addAfter(factory.createExpression("x()"), statement1) val bindingContext6 = statement1.analyze(mode) assert(bindingContext6 !== bindingContext5) } fun testNonPhysicalFilePartialResolveCaching() { doTest { val nonPhysicalFile = KtPsiFactory.contextual(file).createFile("NonPhysical.kt", FILE_TEXT) val nonPhysicalData = extractData(nonPhysicalFile) nonPhysicalData.testPartialResolveCaching(BodyResolveMode.PARTIAL) } } fun testPartialResolveCachedForWholeStatement() { doTest { val statement = statements[0] as KtCallExpression val argument1 = statement.valueArguments[0] val argument2 = statement.valueArguments[1] val bindingContext1 = argument1.analyze(BodyResolveMode.PARTIAL) val bindingContext2 = argument2.analyze(BodyResolveMode.PARTIAL) assert(bindingContext1 === bindingContext2) } } fun testPartialResolveCachedForAllStatementsResolved() { doTest { // resolve 'd(x)' val bindingContext1 = statements[2].analyze(BodyResolveMode.PARTIAL) // resolve initializer in 'val x = c()' - it required for resolved 'd(x)' and should be already resolved val bindingContext2 = (statements[1] as KtVariableDeclaration).initializer!!.analyze(BodyResolveMode.PARTIAL) assert(bindingContext1 === bindingContext2) val bindingContext3 = statements[0].analyze(BodyResolveMode.PARTIAL) assert(bindingContext3 !== bindingContext1) } } fun testPartialResolveCachedForDefaultParameterValue() { doTest { val defaultValue = (members[0] as KtNamedFunction).valueParameters[0].defaultValue val bindingContext1 = defaultValue!!.analyze(BodyResolveMode.PARTIAL) val bindingContext2 = defaultValue.analyze(BodyResolveMode.PARTIAL) assert(bindingContext1 === bindingContext2) val bindingContext3 = statements[0].analyze(BodyResolveMode.PARTIAL) assert(bindingContext3 !== bindingContext2) } } fun testPartialForCompletionAndPartialAfter() { doTest { val statement = statements[0] val bindingContext1 = statement.analyze(BodyResolveMode.PARTIAL_FOR_COMPLETION) val bindingContext2 = statement.analyze(BodyResolveMode.PARTIAL) assert(bindingContext2 === bindingContext1) val bindingContext3 = statement.analyze(BodyResolveMode.PARTIAL_WITH_DIAGNOSTICS) assert(bindingContext3 !== bindingContext1) } } fun testPartialWithDiagnosticsAndPartialAfter() { doTest { val statement = statements[0] val bindingContext1 = statement.analyze(BodyResolveMode.PARTIAL_WITH_DIAGNOSTICS) val bindingContext2 = statement.analyze(BodyResolveMode.PARTIAL) assert(bindingContext2 === bindingContext1) val bindingContext3 = statement.analyze(BodyResolveMode.PARTIAL_FOR_COMPLETION) assert(bindingContext3 !== bindingContext1) } } fun testFullResolvedCachedWhenPartialForConstructorInvoked() { doTest { val defaultValue1 = klass.primaryConstructorParameters[0].defaultValue!! val defaultValue2 = klass.primaryConstructorParameters[1].defaultValue!! val bindingContext1 = defaultValue1.analyze(BodyResolveMode.PARTIAL_WITH_DIAGNOSTICS) val bindingContext2 = defaultValue2.analyze(BodyResolveMode.FULL) assert(bindingContext1 === bindingContext2) } } fun testAnnotationEntry() { val file = configureWithKotlin( """ annotation class A @A class B {} """ ) val klass = file.declarations[1] as KtClass val annotationEntry = klass.annotationEntries.single() val context = annotationEntry.analyze(BodyResolveMode.PARTIAL) assert(context[BindingContext.ANNOTATION, annotationEntry] != null) } fun testFileAnnotationList() { val file = configureWithKotlin( """ @file:Suppress("Some") @file:JvmName("Hi") """ ) val fileAnnotationList = file.fileAnnotationList!! val context = fileAnnotationList.analyze(BodyResolveMode.PARTIAL) assert(context[BindingContext.ANNOTATION, fileAnnotationList.annotationEntries[0]] != null) assert(context[BindingContext.ANNOTATION, fileAnnotationList.annotationEntries[1]] != null) } fun testIncompleteFileAnnotationList() { val file = configureWithKotlin( """ @file import some.hello """ ) val fileAnnotationList = file.fileAnnotationList!! fileAnnotationList.analyze(BodyResolveMode.PARTIAL) } fun testNamedParametersInFunctionType() { val file = configureWithKotlin( """ fun <K, V> intercept(block: (key: K, next: (K) -> V, K) -> V) {} """ ) val function = file.declarations[0] as KtNamedFunction val functionType = function.valueParameters.first().typeReference!!.typeElement as KtFunctionType val descriptorsForParameters = functionType.parameters.map { it.unsafeResolveToDescriptor() } assert( listOf("key", "next", SpecialNames.NO_NAME_PROVIDED.asString()) == descriptorsForParameters.map { it.name.asString() } ) } fun testNoBodyResolveOnFunctionParameterAnalyze() { val file = configureWithKotlin( """ fun test(a: String) { unresolved // Check diagnostics is empty even in FULL mode when starting analyzing for parameter } """ ) val function = file.declarations[0] as KtNamedFunction val functionParameter = function.valueParameters.first() val context = functionParameter.analyze(BodyResolveMode.FULL) assertEmpty(context.diagnostics.all()) } fun testPrimaryConstructorParameterFullAnalysis() { configureWithKotlin( """ class My(param: Int = <caret>0) """ ) val defaultValue = myFixture.elementByOffset.getParentOfType<KtExpression>(true)!! // Kept to preserve correct behaviour of analyzeFully() on class internal elements @Suppress("DEPRECATION") defaultValue.analyzeWithAllCompilerChecks() } fun testPrimaryConstructorAnnotationFullAnalysis() { configureWithKotlin( """ class My @Deprecated("<caret>xyz") protected constructor(param: Int) """ ) val annotationArguments = myFixture.elementByOffset.getParentOfType<KtValueArgumentList>(true)!! @Suppress("DEPRECATION") annotationArguments.analyzeWithAllCompilerChecks() } fun testFunctionParameterAnnotation() { val file = configureWithKotlin( """ annotation class Ann fun foo(@<caret>Ann p: Int) { bar() } """ ) val function = (file.declarations[1]) as KtFunction val typeRef = myFixture.elementByOffset.getParentOfType<KtTypeReference>(true)!! val bindingContext = typeRef.analyze(BodyResolveMode.PARTIAL) val referenceExpr = (typeRef.typeElement as KtUserType).referenceExpression val target = bindingContext[BindingContext.REFERENCE_TARGET, referenceExpr] TestCase.assertEquals("Ann", target?.importableFqName?.asString()) val statement = function.bodyBlockExpression!!.statements[0] TestCase.assertEquals(null, bindingContext[BindingContext.PROCESSED, statement]) } fun testPrimaryConstructorParameterAnnotation() { configureWithKotlin( """ annotation class Ann class X(@set:<caret>Ann var p: Int) """ ) val typeRef = myFixture.elementByOffset.getParentOfType<KtTypeReference>(true)!! val bindingContext = typeRef.analyze(BodyResolveMode.PARTIAL) val referenceExpr = (typeRef.typeElement as KtUserType).referenceExpression val target = bindingContext[BindingContext.REFERENCE_TARGET, referenceExpr] TestCase.assertEquals("Ann", target?.importableFqName?.asString()) } fun testSecondaryConstructorParameterAnnotation() { val file = configureWithKotlin( """ annotation class Ann class X { constructor(@<caret>Ann p: Int) { foo() } } """ ) val constructor = ((file.declarations[1]) as KtClass).secondaryConstructors[0] val typeRef = myFixture.elementByOffset.getParentOfType<KtTypeReference>(true)!! val bindingContext = typeRef.analyze(BodyResolveMode.PARTIAL) val referenceExpr = (typeRef.typeElement as KtUserType).referenceExpression val target = bindingContext[BindingContext.REFERENCE_TARGET, referenceExpr] TestCase.assertEquals("Ann", target?.importableFqName?.asString()) val statement = constructor.bodyBlockExpression!!.statements[0] TestCase.assertEquals(null, bindingContext[BindingContext.PROCESSED, statement]) } fun testFullResolveMultiple() { doTest { val aBody = (members[0] as KtFunction).bodyBlockExpression!! val statement1InFunA = aBody.statements[0] val statement2InFunA = aBody.statements[1] val statementInFunB = ((members[1] as KtFunction).bodyBlockExpression)!!.statements[0] val statementInFunC = ((members[2] as KtFunction).bodyBlockExpression)!!.statements[0] val bindingContext = checkResolveMultiple(BodyResolveMode.FULL, statement1InFunA, statementInFunB) TestCase.assertEquals(true, bindingContext[BindingContext.PROCESSED, statement2InFunA]) TestCase.assertEquals(null, bindingContext[BindingContext.PROCESSED, statementInFunC]) } } fun testPartialResolveMultiple() { doTest { val aBody = (members[0] as KtFunction).bodyBlockExpression!! val statement1InFunA = aBody.statements[0] val statement2InFunA = aBody.statements[1] val statementInFunB = ((members[1] as KtFunction).bodyBlockExpression)!!.statements[0] val constructorParameterDefault = klass.primaryConstructor!!.valueParameters[1].defaultValue!! val funC = members[2] checkResolveMultiple( BodyResolveMode.PARTIAL, statement1InFunA, statement2InFunA, statementInFunB, constructorParameterDefault, funC ) } } fun testPartialResolveMultipleInOneFunction() { doTest { val aBody = (members[0] as KtFunction).bodyBlockExpression!! val statement1InFunA = aBody.statements[0] val statement2InFunA = aBody.statements[1] val bindingContext = checkResolveMultiple(BodyResolveMode.PARTIAL, statement1InFunA, statement2InFunA) val bindingContext1 = statement1InFunA.analyze(BodyResolveMode.PARTIAL) assert(bindingContext1 === bindingContext) } } fun testPartialResolveIsAFullResolveForOpenedFile() { ResolveElementCache.forceFullAnalysisModeInTests = true doTest { val function = members[0] as KtFunction val bindingContextPartial = function.analyze(BodyResolveMode.PARTIAL) val bindingContextFull = function.analyze(BodyResolveMode.FULL) assert(bindingContextPartial === bindingContextFull) { "Partial resolve is forced to FULL resolve for a file currently opened in editor" } } } fun testKT14376() { val file = configureWithKotlin("object Obj(val x: Int)") val nameRef = file.findDescendantOfType<KtNameReferenceExpression>()!! val bindingContext = nameRef.analyze(BodyResolveMode.PARTIAL) assert(bindingContext[BindingContext.REFERENCE_TARGET, nameRef]?.fqNameSafe?.asString() == "kotlin.Int") } fun testResolveDefaultValueInPrimaryConstructor() { configureWithKotlin( """ class ClassA<N> ( messenger: ClassB<N> = object : ClassB<N> { override fun methodOne<caret>(param: List<N>) { } } ) interface ClassB<N> { fun methodOne(param: List<N>) } """ ) val methodOne = myFixture.elementByOffset.getParentOfType<KtFunction>(true)!! val bindingContext = methodOne.analyze(BodyResolveMode.FULL) val parameter = methodOne.valueParameters[0] val parameterDescriptor = bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, parameter] as ValueParameterDescriptor assert(!parameterDescriptor.type.containsError()) } fun testTypingInScriptInitializer() { val file = myFixture.configureByText( "Test.kts", """ run { 1 +<caret> 1 } run { 2 + 2 } """ ) as KtFile val script = file.script ?: error("File should be a script") ScriptConfigurationManager.updateScriptDependenciesSynchronously(file) val statement1 = (script.blockExpression.statements.first() as? KtScriptInitializer)?.body ?: error("Cannot find first expression in script") val statement2 = (script.blockExpression.statements.last() as? KtScriptInitializer)?.body ?: error("Cannot find last expression in script") val bindingContext1Before = statement1.analyze() val bindingContext2Before = statement2.analyze() val caret = myFixture.elementByOffset.getParentOfType<KtExpression>(true) ?: error("Cannot find element at caret") myFixture.project.executeWriteCommand("") { caret.parent.addAfter(KtPsiFactory(project).createWhiteSpace(), caret) } val bindingContext1After = statement1.analyze() val bindingContext2After = statement2.analyze() assert(bindingContext1Before !== bindingContext1After) { "Analysis for first statement must change because statement was changed" } assert(bindingContext2Before === bindingContext2After) { "Analysis for second statement must not change, only first statement was changed" } } private fun checkResolveMultiple(mode: BodyResolveMode, vararg expressions: KtExpression): BindingContext { val resolutionFacade = expressions.first().getResolutionFacade() val bindingContext = resolutionFacade.analyze(expressions.asList(), mode) expressions.forEach { if (it !is KtDeclaration) { TestCase.assertEquals(true, bindingContext[BindingContext.PROCESSED, it]) } else { TestCase.assertNotNull(bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, it]) } } return bindingContext } }
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/ResolveElementCacheTest.kt
1355511442
package xyz.swagbot.commands import com.sedmelluq.discord.lavaplayer.track.* import io.facet.commands.* import io.facet.common.* import io.facet.common.dsl.* import io.facet.core.* import xyz.swagbot.extensions.* import xyz.swagbot.features.music.* import xyz.swagbot.util.* import java.util.* object Play : GlobalGuildApplicationCommand { override val request = applicationCommandRequest("play", "Queue up music and/or videos to be played by the bot.") { string( "query", "The name of the song/video, or url to the YouTube/Soundcloud/Audio file.", true ) } override suspend fun GuildSlashCommandContext.execute() { val guild = getGuild() if (!guild.isPremium()) return event.reply("Music is a premium feature of SwagBot").withEphemeral(true).await() if (member.voiceState.awaitNullable()?.channelId?.unwrap() == null) return event.reply("You must be in a voice channel to add music to the queue!").withEphemeral(true).await() acknowledge() val musicFeature = client.feature(Music) val query: String by options val item: AudioItem? = try { if ("http://" in query || "https://" in query) musicFeature.searchItem(query) else musicFeature.searchItem("ytsearch:$query") } catch (e: Throwable) { event.interactionResponse.createFollowupMessage("I couldn't find anything for *\"$query\"*.").await() return } val scheduler = guild.trackScheduler when (item) { is AudioTrack -> { item.setTrackContext(member, getChannel()) scheduler.queue(item) interactionResponse.sendFollowupMessage( trackRequestedTemplate( member.displayName, item, scheduler.queueTimeLeft ) ) if (getGuild().getConnectedVoiceChannel() == null) member.getConnectedVoiceChannel()?.join() } is AudioPlaylist -> { if (item.isSearchResult) { val track = item.tracks.maxByOrNull { track -> track.info.title.lowercase(Locale.getDefault()).let { "audio" in it || "lyrics" in it } } if (track != null) { track.setTrackContext(member, getChannel()) scheduler.queue(track) event.interactionResponse.sendFollowupMessage( trackRequestedTemplate( member.displayName, track, scheduler.queueTimeLeft ) ) if (getGuild().getConnectedVoiceChannel() == null) member.getConnectedVoiceChannel()?.join() } else event.interactionResponse.createFollowupMessage("I couldn't find anything for *\"$query\"*.") } else { item.tracks.forEach { track -> track.setTrackContext(member, getChannel()) scheduler.queue(track) } event.interactionResponse.sendFollowupMessage( baseTemplate.and { title = ":musical_note: | Playlist requested by ${member.displayName}" description = """ **${item.name}** ${item.tracks.size} Tracks """.trimIndent().trim() } ) if (getGuild().getConnectedVoiceChannel() == null) member.getConnectedVoiceChannel()?.join() } } else -> event.interactionResponse.createFollowupMessage("I couldn't find anything for *\"$query\"*.") } } }
src/main/kotlin/commands/Play.kt
1887265508
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.configurationStore import com.intellij.ide.highlighter.ProjectFileType import com.intellij.ide.highlighter.WorkspaceFileType import com.intellij.notification.Notifications import com.intellij.notification.NotificationsManager import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.invokeAndWaitIfNeed import com.intellij.openapi.application.runReadAction import com.intellij.openapi.components.* import com.intellij.openapi.components.StateStorage.SaveSession import com.intellij.openapi.components.impl.stores.IComponentStore import com.intellij.openapi.components.impl.stores.IProjectStore import com.intellij.openapi.components.impl.stores.StoreUtil import com.intellij.openapi.diagnostic.catchAndLog import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectCoreUtil import com.intellij.openapi.project.impl.ProjectImpl import com.intellij.openapi.project.impl.ProjectManagerImpl.UnableToSaveProjectNotification import com.intellij.openapi.project.impl.ProjectStoreClassProvider import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.Pair import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.io.FileUtilRt import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.ReadonlyStatusHandler import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.PathUtilRt import com.intellij.util.SmartList import com.intellij.util.attribute import com.intellij.util.containers.forEachGuaranteed import com.intellij.util.containers.isNullOrEmpty import com.intellij.util.io.* import com.intellij.util.lang.CompoundRuntimeException import com.intellij.util.text.nullize import org.jdom.Element import java.io.File import java.io.IOException import java.nio.file.Path import java.nio.file.Paths const val PROJECT_FILE = "\$PROJECT_FILE$" const val PROJECT_CONFIG_DIR = "\$PROJECT_CONFIG_DIR$" val IProjectStore.nameFile: Path get() = Paths.get(directoryStorePath, ProjectImpl.NAME_FILE) internal val PROJECT_FILE_STORAGE_ANNOTATION = FileStorageAnnotation(PROJECT_FILE, false) internal val DEPRECATED_PROJECT_FILE_STORAGE_ANNOTATION = FileStorageAnnotation(PROJECT_FILE, true) abstract class ProjectStoreBase(override final val project: ProjectImpl) : ComponentStoreImpl(), IProjectStore { // protected setter used in upsource // Zelix KlassMaster - ERROR: Could not find method 'getScheme()' var scheme = StorageScheme.DEFAULT override final var loadPolicy = StateLoadPolicy.LOAD override final fun isOptimiseTestLoadSpeed() = loadPolicy != StateLoadPolicy.LOAD override final fun getStorageScheme() = scheme override abstract val storageManager: StateStorageManagerImpl protected val isDirectoryBased: Boolean get() = scheme == StorageScheme.DIRECTORY_BASED override final fun setOptimiseTestLoadSpeed(value: Boolean) { // we don't load default state in tests as app store does because // 1) we should not do it // 2) it was so before, so, we preserve old behavior (otherwise RunManager will load template run configurations) loadPolicy = if (value) StateLoadPolicy.NOT_LOAD else StateLoadPolicy.LOAD } override fun getProjectFilePath() = storageManager.expandMacro(PROJECT_FILE) override final fun getWorkspaceFilePath() = storageManager.expandMacro(StoragePathMacros.WORKSPACE_FILE) override final fun clearStorages() { storageManager.clearStorages() } override final fun loadProjectFromTemplate(defaultProject: Project) { defaultProject.save() val element = (defaultProject.stateStore as DefaultProjectStoreImpl).getStateCopy() ?: return LOG.catchAndLog { removeWorkspaceComponentConfiguration(defaultProject, element) } if (isDirectoryBased) { LOG.catchAndLog { for (component in element.getChildren("component")) { when (component.getAttributeValue("name")) { "InspectionProjectProfileManager" -> convertProfiles(component.getChildren("profile").iterator(), true) "CopyrightManager" -> convertProfiles(component.getChildren("copyright").iterator(), false) } } } } (storageManager.getOrCreateStorage(PROJECT_FILE) as XmlElementStorage).setDefaultState(element) } fun convertProfiles(profileIterator: MutableIterator<Element>, isInspection: Boolean) { for (profile in profileIterator) { val schemeName = profile.getChildren("option").find { it.getAttributeValue("name") == "myName" }?.getAttributeValue( "value") ?: continue profileIterator.remove() val wrapper = Element("component").attribute("name", if (isInspection) "InspectionProjectProfileManager" else "CopyrightManager") wrapper.addContent(profile) val path = Paths.get(storageManager.expandMacro(PROJECT_CONFIG_DIR), if (isInspection) "inspectionProfiles" else "copyright", "${FileUtil.sanitizeFileName(schemeName, true)}.xml") JDOMUtil.writeParent(wrapper, path.outputStream(), "\n") } } override final fun getProjectBasePath(): String { if (isDirectoryBased) { val path = PathUtilRt.getParentPath(storageManager.expandMacro(PROJECT_CONFIG_DIR)) if (Registry.`is`("store.basedir.parent.detection", true) && PathUtilRt.getFileName(path).startsWith("${Project.DIRECTORY_STORE_FOLDER}.")) { return PathUtilRt.getParentPath(PathUtilRt.getParentPath(path)) } return path } else { return PathUtilRt.getParentPath(projectFilePath) } } // used in upsource protected fun setPath(filePath: String, refreshVfs: Boolean, useOldWorkspaceContentIfExists: Boolean) { val storageManager = storageManager val fs = LocalFileSystem.getInstance() if (FileUtilRt.extensionEquals(filePath, ProjectFileType.DEFAULT_EXTENSION)) { scheme = StorageScheme.DEFAULT storageManager.addMacro(PROJECT_FILE, filePath) val workspacePath = composeWsPath(filePath) storageManager.addMacro(StoragePathMacros.WORKSPACE_FILE, workspacePath) if (refreshVfs) { invokeAndWaitIfNeed { VfsUtil.markDirtyAndRefresh(false, true, false, fs.refreshAndFindFileByPath(filePath), fs.refreshAndFindFileByPath(workspacePath)) } } if (ApplicationManager.getApplication().isUnitTestMode) { // load state only if there are existing files isOptimiseTestLoadSpeed = !File(filePath).exists() } } else { scheme = StorageScheme.DIRECTORY_BASED // if useOldWorkspaceContentIfExists false, so, file path is expected to be correct (we must avoid file io operations) val isDir = !useOldWorkspaceContentIfExists || Paths.get(filePath).isDirectory() val configDir = "${(if (isDir) filePath else PathUtilRt.getParentPath(filePath))}/${Project.DIRECTORY_STORE_FOLDER}" storageManager.addMacro(PROJECT_CONFIG_DIR, configDir) storageManager.addMacro(PROJECT_FILE, "$configDir/misc.xml") storageManager.addMacro(StoragePathMacros.WORKSPACE_FILE, "$configDir/workspace.xml") if (!isDir) { val workspace = File(workspaceFilePath) if (!workspace.exists()) { useOldWorkspaceContent(filePath, workspace) } } if (ApplicationManager.getApplication().isUnitTestMode) { // load state only if there are existing files isOptimiseTestLoadSpeed = !Paths.get(filePath).exists() } if (refreshVfs) { invokeAndWaitIfNeed { VfsUtil.markDirtyAndRefresh(false, true, true, fs.refreshAndFindFileByPath(configDir)) } } } } override fun <T> getStorageSpecs(component: PersistentStateComponent<T>, stateSpec: State, operation: StateStorageOperation): Array<out Storage> { val storages = stateSpec.storages if (storages.isEmpty()) { return arrayOf(PROJECT_FILE_STORAGE_ANNOTATION) } if (isDirectoryBased) { var result: MutableList<Storage>? = null for (storage in storages) { @Suppress("DEPRECATION") if (storage.path != PROJECT_FILE) { if (result == null) { result = SmartList() } result.add(storage) } } if (result.isNullOrEmpty()) { return arrayOf(PROJECT_FILE_STORAGE_ANNOTATION) } else { result!!.sortWith(deprecatedComparator) // if we create project from default, component state written not to own storage file, but to project file, // we don't have time to fix it properly, so, ancient hack restored result.add(DEPRECATED_PROJECT_FILE_STORAGE_ANNOTATION) return result.toTypedArray() } } else { var result: MutableList<Storage>? = null // FlexIdeProjectLevelCompilerOptionsHolder, FlexProjectLevelCompilerOptionsHolderImpl and CustomBeanRegistry var hasOnlyDeprecatedStorages = true for (storage in storages) { @Suppress("DEPRECATION") if (storage.path == PROJECT_FILE || storage.path == StoragePathMacros.WORKSPACE_FILE) { if (result == null) { result = SmartList() } result.add(storage) if (!storage.deprecated) { hasOnlyDeprecatedStorages = false } } } if (result.isNullOrEmpty()) { return arrayOf(PROJECT_FILE_STORAGE_ANNOTATION) } else { if (hasOnlyDeprecatedStorages) { result!!.add(PROJECT_FILE_STORAGE_ANNOTATION) } result!!.sortWith(deprecatedComparator) return result.toTypedArray() } } } override fun isProjectFile(file: VirtualFile): Boolean { if (!file.isInLocalFileSystem || !ProjectCoreUtil.isProjectOrWorkspaceFile(file, file.fileType)) { return false } val filePath = file.path if (!isDirectoryBased) { return filePath == projectFilePath || filePath == workspaceFilePath } return FileUtil.isAncestor(PathUtilRt.getParentPath(projectFilePath), filePath, false) } override fun getDirectoryStorePath(ignoreProjectStorageScheme: Boolean) = if (!ignoreProjectStorageScheme && !isDirectoryBased) null else PathUtilRt.getParentPath(projectFilePath).nullize() override fun getDirectoryStoreFile() = directoryStorePath?.let { LocalFileSystem.getInstance().findFileByPath(it) } override fun getDirectoryStorePathOrBase() = PathUtilRt.getParentPath(projectFilePath) } private open class ProjectStoreImpl(project: ProjectImpl, private val pathMacroManager: PathMacroManager) : ProjectStoreBase(project) { private var lastSavedProjectName: String? = null init { assert(!project.isDefault) } override final fun getPathMacroManagerForDefaults() = pathMacroManager override val storageManager = ProjectStateStorageManager(pathMacroManager.createTrackingSubstitutor(), project) override fun setPath(filePath: String) { setPath(filePath, true, true) } override fun getProjectName(): String { if (isDirectoryBased) { val baseDir = projectBasePath val nameFile = nameFile if (nameFile.exists()) { try { nameFile.inputStream().reader().useLines { it.firstOrNull { !it.isEmpty() }?.trim() }?.let { lastSavedProjectName = it return it } } catch (ignored: IOException) { } } return PathUtilRt.getFileName(baseDir).replace(":", "") } else { return PathUtilRt.getFileName(projectFilePath).removeSuffix(ProjectFileType.DOT_DEFAULT_EXTENSION) } } private fun saveProjectName() { if (!isDirectoryBased) { return } val currentProjectName = project.name if (lastSavedProjectName == currentProjectName) { return } lastSavedProjectName = currentProjectName val basePath = projectBasePath if (currentProjectName == PathUtilRt.getFileName(basePath)) { // name equals to base path name - just remove name nameFile.delete() } else { if (Paths.get(basePath).isDirectory()) { nameFile.write(currentProjectName.toByteArray()) } } } override fun doSave(saveSessions: List<SaveSession>, readonlyFiles: MutableList<Pair<SaveSession, VirtualFile>>, prevErrors: MutableList<Throwable>?): MutableList<Throwable>? { try { saveProjectName() } catch (e: Throwable) { LOG.error("Unable to store project name", e) } var errors = prevErrors beforeSave(readonlyFiles) errors = super.doSave(saveSessions, readonlyFiles, errors) val notifications = NotificationsManager.getNotificationsManager().getNotificationsOfType(UnableToSaveProjectNotification::class.java, project) if (readonlyFiles.isEmpty()) { for (notification in notifications) { notification.expire() } return errors } if (!notifications.isEmpty()) { throw IComponentStore.SaveCancelledException() } val status = runReadAction { ReadonlyStatusHandler.getInstance(project).ensureFilesWritable(*getFilesList(readonlyFiles)) } if (status.hasReadonlyFiles()) { dropUnableToSaveProjectNotification(project, status.readonlyFiles) throw IComponentStore.SaveCancelledException() } val oldList = readonlyFiles.toTypedArray() readonlyFiles.clear() for (entry in oldList) { errors = executeSave(entry.first, readonlyFiles, errors) } CompoundRuntimeException.throwIfNotEmpty(errors) if (!readonlyFiles.isEmpty()) { dropUnableToSaveProjectNotification(project, getFilesList(readonlyFiles)) throw IComponentStore.SaveCancelledException() } return errors } protected open fun beforeSave(readonlyFiles: List<Pair<SaveSession, VirtualFile>>) { } } private fun dropUnableToSaveProjectNotification(project: Project, readOnlyFiles: Array<VirtualFile>) { val notifications = NotificationsManager.getNotificationsManager().getNotificationsOfType(UnableToSaveProjectNotification::class.java, project) if (notifications.isEmpty()) { Notifications.Bus.notify(UnableToSaveProjectNotification(project, readOnlyFiles), project) } else { notifications[0].myFiles = readOnlyFiles } } private fun getFilesList(readonlyFiles: List<Pair<SaveSession, VirtualFile>>) = Array(readonlyFiles.size) { readonlyFiles[it].second } private class ProjectWithModulesStoreImpl(project: ProjectImpl, pathMacroManager: PathMacroManager) : ProjectStoreImpl(project, pathMacroManager) { override fun beforeSave(readonlyFiles: List<Pair<SaveSession, VirtualFile>>) { super.beforeSave(readonlyFiles) for (module in (ModuleManager.getInstance(project)?.modules ?: Module.EMPTY_ARRAY)) { module.stateStore.save(readonlyFiles) } } } // used in upsource class PlatformLangProjectStoreClassProvider : ProjectStoreClassProvider { override fun getProjectStoreClass(isDefaultProject: Boolean): Class<out IComponentStore> { return if (isDefaultProject) DefaultProjectStoreImpl::class.java else ProjectWithModulesStoreImpl::class.java } } private class PlatformProjectStoreClassProvider : ProjectStoreClassProvider { override fun getProjectStoreClass(isDefaultProject: Boolean): Class<out IComponentStore> { return if (isDefaultProject) DefaultProjectStoreImpl::class.java else ProjectStoreImpl::class.java } } private fun composeWsPath(filePath: String) = "${FileUtilRt.getNameWithoutExtension(filePath)}${WorkspaceFileType.DOT_DEFAULT_EXTENSION}" private fun useOldWorkspaceContent(filePath: String, ws: File) { val oldWs = File(composeWsPath(filePath)) if (!oldWs.exists()) { return } try { FileUtil.copyContent(oldWs, ws) } catch (e: IOException) { LOG.error(e) } } // public only to test fun removeWorkspaceComponentConfiguration(defaultProject: Project, element: Element) { val componentElements = element.getChildren("component") if (componentElements.isEmpty()) { return } @Suppress("DEPRECATION") val projectComponents = defaultProject.getComponents(PersistentStateComponent::class.java) projectComponents.forEachGuaranteed { val stateAnnotation = StoreUtil.getStateSpec(it.javaClass) if (stateAnnotation == null || stateAnnotation.name.isNullOrEmpty()) { return@forEachGuaranteed } val storage = stateAnnotation.storages.sortByDeprecated().firstOrNull() ?: return@forEachGuaranteed if (storage.path != StoragePathMacros.WORKSPACE_FILE) { return@forEachGuaranteed } val iterator = componentElements.iterator() for (componentElement in iterator) { if (componentElement.getAttributeValue("name") == stateAnnotation.name) { iterator.remove() break } } } return }
platform/configuration-store-impl/src/ProjectStoreImpl.kt
648835950
import org.junit.Ignore import org.junit.Test import kotlin.test.assertEquals class TwoFerTest { @Test fun noNameGiven() { assertEquals("One for you, one for me.", twofer()) } @Test @Ignore fun aNameGiven() { assertEquals("One for Alice, one for me.", twofer("Alice")) } @Test @Ignore fun anotherNameGiven() { assertEquals("One for Bob, one for me.", twofer("Bob")) } @Test @Ignore fun emptyStringGiven() { assertEquals("One for , one for me.", twofer("")) } }
exercises/practice/two-fer/src/test/kotlin/TwoFerTest.kt
2483690481
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.rebase.interactive.dialog import com.intellij.ide.DataManager import com.intellij.ide.ui.laf.darcula.ui.DarculaButtonPainter import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.Presentation import com.intellij.openapi.actionSystem.ex.ActionUtil.performActionDumbAwareWithCallbacks import com.intellij.openapi.actionSystem.ex.CustomComponentAction import com.intellij.openapi.project.DumbAware import com.intellij.ui.AnActionButton import com.intellij.ui.components.JBOptionButton import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import com.intellij.util.ui.components.BorderLayoutPanel import java.awt.Component import java.awt.Dimension import java.awt.Insets import java.awt.event.ActionEvent import javax.swing.AbstractAction import javax.swing.JButton import javax.swing.JComponent internal fun JButton.adjustForToolbar() { val buttonHeight = JBUI.scale(28) preferredSize = Dimension(preferredSize.width, buttonHeight) border = object : DarculaButtonPainter() { override fun getBorderInsets(c: Component?): Insets { return JBUI.emptyInsets() } } isFocusable = false } internal fun JButton.withLeftToolbarBorder() = BorderLayoutPanel().addToCenter(this).apply { border = JBUI.Borders.emptyLeft(6) } internal class AnActionOptionButton( val action: AnAction, val options: List<AnAction> ) : AnActionButton(), CustomComponentAction, DumbAware { private val optionButton = JBOptionButton(null, null).apply { action = AnActionWrapper([email protected], this) setOptions([email protected]) adjustForToolbar() mnemonic = [email protected]().toInt() } private val optionButtonPanel = optionButton.withLeftToolbarBorder() override fun actionPerformed(e: AnActionEvent) { throw UnsupportedOperationException() } override fun createCustomComponent(presentation: Presentation, place: String) = optionButtonPanel override fun updateButton(e: AnActionEvent) { action.update(e) UIUtil.setEnabled(optionButton, e.presentation.isEnabled, true) } private class AnActionWrapper( private val action: AnAction, private val component: JComponent ) : AbstractAction(action.templatePresentation.text) { override fun actionPerformed(e: ActionEvent?) { val context = DataManager.getInstance().getDataContext(component) val event = AnActionEvent.createFromAnAction(action, null, GitInteractiveRebaseDialog.PLACE, context) performActionDumbAwareWithCallbacks(action, event) } } }
plugins/git4idea/src/git4idea/rebase/interactive/dialog/AnActionOptionButton.kt
2898628380
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.plugins.test import com.netflix.spinnaker.kork.plugins.tck.PluginsTck import com.netflix.spinnaker.kork.plugins.tck.serviceFixture import com.netflix.spinnaker.orca.api.preconfigured.jobs.TitusPreconfiguredJobProperties import com.netflix.spinnaker.orca.plugins.SimpleStageExtension import com.netflix.spinnaker.orca.plugins.StageDefinitionBuilderExtension import com.netflix.spinnaker.orca.plugins.TaskExtension1 import com.netflix.spinnaker.orca.plugins.TaskExtension2 import dev.minutest.rootContext import strikt.api.expect import strikt.assertions.hasSize import strikt.assertions.isEqualTo class OrcaPluginsTest : PluginsTck<OrcaPluginsFixture>() { fun tests() = rootContext<OrcaPluginsFixture> { context("an orca integration test environment and an orca plugin") { serviceFixture { OrcaPluginsFixture() } defaultPluginTests() test("preconfigured job configuration is correctly loaded from extension") { val titusPreconfiguredJobProperties = objectMapper .readValue( this::class.java.getResource("/preconfigured.yml").readText(), TitusPreconfiguredJobProperties::class.java ) expect { that(jobService.preconfiguredStages).hasSize(1) jobService.preconfiguredStages.first().let { preconfiguredStage -> that(preconfiguredStage).isEqualTo(titusPreconfiguredJobProperties) } } } test("Stage defintion builder for extension is resolved to the correct type") { val stageDefinitionBuilder = stageResolver.getStageDefinitionBuilder( StageDefinitionBuilderExtension::class.java.simpleName, "extensionStage") expect { that(stageDefinitionBuilder.type).isEqualTo(StageDefinitionBuilderExtension().type) } } test("Simple stage extension is resolved to the correct type") { val stageDefinitionBuilder = stageResolver.getStageDefinitionBuilder( SimpleStageExtension::class.java.simpleName, "simpleStage") expect { that(stageDefinitionBuilder.type).isEqualTo("simple") } } test("Task extensions are resolved to the correct type") { val taskExtension1 = taskResolver.getTaskClass(TaskExtension1::class.java.name) val taskExtension2 = taskResolver.getTaskClass(TaskExtension2::class.java.name) expect { that(taskExtension1.typeName).isEqualTo(TaskExtension1().javaClass.typeName) that(taskExtension2.typeName).isEqualTo(TaskExtension2().javaClass.typeName) } } } } }
orca-plugins-test/src/test/kotlin/com/netflix/spinnaker/orca/plugins/test/OrcaPluginsTest.kt
3499425921
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.uast import com.intellij.psi.PsiClassInitializer import org.jetbrains.uast.internal.acceptList import org.jetbrains.uast.internal.log import org.jetbrains.uast.visitor.UastTypedVisitor import org.jetbrains.uast.visitor.UastVisitor /** * A class initializer wrapper to be used in [UastVisitor]. */ interface UClassInitializer : UDeclaration, PsiClassInitializer { @Suppress("OverridingDeprecatedMember") @Deprecated("see the base property description", ReplaceWith("javaPsi")) override val psi: PsiClassInitializer /** * Returns the body of this class initializer. */ val uastBody: UExpression @Suppress("DEPRECATION") private val javaPsiInternal get() = (this as? UClassInitializerEx)?.javaPsi ?: psi override fun accept(visitor: UastVisitor) { if (visitor.visitInitializer(this)) return uAnnotations.acceptList(visitor) uastBody.accept(visitor) visitor.afterVisitInitializer(this) } override fun asRenderString(): String = buildString { append(modifierList) appendln(uastBody.asRenderString().withMargin) } override fun <D, R> accept(visitor: UastTypedVisitor<D, R>, data: D): R = visitor.visitClassInitializer(this, data) override fun asLogString(): String = log("isStatic = $isStatic") } interface UClassInitializerEx : UClassInitializer, UDeclarationEx { override val javaPsi: PsiClassInitializer }
uast/uast-common/src/org/jetbrains/uast/declarations/UClassInitializer.kt
3276022217
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.resolve.processors.inference import com.intellij.psi.PsiElement import com.intellij.psi.PsiSubstitutor import com.intellij.psi.PsiType import com.intellij.psi.PsiTypeParameter import com.intellij.psi.impl.source.resolve.graphInference.InferenceSession import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.TypeConversionUtil import org.jetbrains.plugins.groovy.codeInspection.utils.ControlFlowUtils import org.jetbrains.plugins.groovy.lang.psi.GroovyFile import org.jetbrains.plugins.groovy.lang.psi.api.GrFunctionalExpression import org.jetbrains.plugins.groovy.lang.psi.api.GroovyMethodResult import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.GrListOrMap import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrClassInitializer import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList import org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrReturnStatement import org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrThrowStatement import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.* import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrCallExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrIndexProperty import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinitionBody import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod import org.jetbrains.plugins.groovy.lang.psi.api.types.GrClassTypeElement import org.jetbrains.plugins.groovy.lang.psi.typeEnhancers.GrTypeConverter.Position.* import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil.skipParentheses import org.jetbrains.plugins.groovy.lang.resolve.MethodResolveResult import org.jetbrains.plugins.groovy.lang.resolve.api.Argument import org.jetbrains.plugins.groovy.lang.resolve.api.ExpressionArgument import org.jetbrains.plugins.groovy.lang.resolve.api.GroovyMethodCandidate import org.jetbrains.plugins.groovy.lang.resolve.delegatesTo.getContainingCall open class GroovyInferenceSessionBuilder constructor( private val context: PsiElement, private val candidate: GroovyMethodCandidate, private val contextSubstitutor: PsiSubstitutor ) { protected var expressionFilters = mutableSetOf<ExpressionPredicate>() protected var skipClosureBlock = true fun resolveMode(skipClosureBlock: Boolean): GroovyInferenceSessionBuilder { //TODO:add explicit typed closure constraints this.skipClosureBlock = skipClosureBlock return this } fun ignoreArguments(arguments: Collection<Argument>): GroovyInferenceSessionBuilder { expressionFilters.add { ExpressionArgument(it) !in arguments } return this } fun skipClosureIn(call: GrCall): GroovyInferenceSessionBuilder { expressionFilters.add { it !is GrFunctionalExpression || call != getContainingCall(it) } return this } protected fun collectExpressionFilters() { if (skipClosureBlock) expressionFilters.add(ignoreFunctionalExpressions) } open fun build(): GroovyInferenceSession { collectExpressionFilters() val session = GroovyInferenceSession(candidate.method.typeParameters, contextSubstitutor, context, skipClosureBlock, expressionFilters) return doBuild(session) } protected fun doBuild(basicSession: GroovyInferenceSession): GroovyInferenceSession { basicSession.initArgumentConstraints(candidate.argumentMapping) return basicSession } } fun buildTopLevelSession(place: PsiElement): GroovyInferenceSession = GroovyInferenceSession(PsiTypeParameter.EMPTY_ARRAY, PsiSubstitutor.EMPTY, place, false).apply { addExpression(place) } fun InferenceSession.addExpression(place : PsiElement) { val expression = findExpression(place) ?: return val startConstraint = if (expression is GrBinaryExpression || expression is GrAssignmentExpression && expression.isOperatorAssignment) { OperatorExpressionConstraint(expression as GrOperatorExpression) } else if (expression is GrSafeCastExpression && expression.operand !is GrFunctionalExpression) { val result = expression.reference.advancedResolve() as? GroovyMethodResult ?: return MethodCallConstraint(null, result, expression) } else { val mostTopLevelExpression = getMostTopLevelExpression(expression) val typeAndPosition = getExpectedTypeAndPosition(mostTopLevelExpression) ExpressionConstraint(typeAndPosition, mostTopLevelExpression) } addConstraint(startConstraint) } fun findExpression(place: PsiElement): GrExpression? { val parent = place.parent return when { parent is GrAssignmentExpression && parent.lValue === place -> parent place is GrIndexProperty -> place parent is GrMethodCall -> parent parent is GrNewExpression -> parent parent is GrClassTypeElement -> parent.parent as? GrSafeCastExpression place is GrExpression -> place else -> null } } fun getMostTopLevelExpression(start: GrExpression): GrExpression { var current: GrExpression = start while (true) { val parent = current.parent current = if (parent is GrArgumentList) { val grandParent = parent.parent if (grandParent is GrCallExpression && grandParent.advancedResolve() is MethodResolveResult) { grandParent } else { return current } } else { return current } } } fun getExpectedType(expression: GrExpression): PsiType? { return getExpectedTypeAndPosition(expression)?.type } private fun getExpectedTypeAndPosition(expression: GrExpression): ExpectedType? { return getAssignmentOrReturnExpectedTypeAndPosition(expression) ?: getArgumentExpectedType(expression) } private fun getAssignmentOrReturnExpectedTypeAndPosition(expression: GrExpression): ExpectedType? { return getAssignmentExpectedType(expression)?.let { ExpectedType(it, ASSIGNMENT) } ?: getReturnExpectedType(expression)?.let { ExpectedType(it, RETURN_VALUE) } } fun getAssignmentOrReturnExpectedType(expression: GrExpression): PsiType? { return getAssignmentExpectedType(expression) ?: getReturnExpectedType(expression) } fun getAssignmentExpectedType(expression: GrExpression): PsiType? { val parent: PsiElement = expression.parent if (parent is GrAssignmentExpression && expression == parent.rValue) { val lValue: PsiElement? = skipParentheses(parent.lValue, false) return if (lValue is GrExpression && lValue !is GrIndexProperty) lValue.nominalType else null } else if (parent is GrVariable) { return parent.declaredType } else if (parent is GrListOrMap) { val pParent: PsiElement? = parent.parent if (pParent is GrVariableDeclaration && pParent.isTuple) { val index: Int = parent.initializers.indexOf(expression) return pParent.variables.getOrNull(index)?.declaredType } else if (pParent is GrTupleAssignmentExpression) { val index: Int = parent.initializers.indexOf(expression) val expressions: Array<out GrReferenceExpression> = pParent.lValue.expressions val lValue: GrReferenceExpression = expressions.getOrNull(index) ?: return null val variable: GrVariable? = lValue.staticReference.resolve() as? GrVariable return variable?.declaredType } } return null } private fun getReturnExpectedType(expression: GrExpression): PsiType? { val parent: PsiElement = expression.parent val parentMethod: GrMethod? = PsiTreeUtil.getParentOfType(parent, GrMethod::class.java, false, GrFunctionalExpression::class.java) if (parentMethod == null) { return null } if (parent is GrReturnStatement) { return parentMethod.returnType } else if (isExitPoint(expression)) { val returnType: PsiType = parentMethod.returnType ?: return null if (TypeConversionUtil.isVoidType(returnType)) return null return returnType } return null } private fun getArgumentExpectedType(expression: GrExpression): ExpectedType? { val parent = expression.parent as? GrArgumentList ?: return null val call = parent.parent as? GrCallExpression ?: return null val result = call.advancedResolve() as? GroovyMethodResult ?: return null val mapping = result.candidate?.argumentMapping ?: return null val type = result.substitutor.substitute(mapping.expectedType(ExpressionArgument(expression))) ?: return null return ExpectedType(type, METHOD_PARAMETER) } internal typealias ExpressionPredicate = (GrExpression) -> Boolean private val ignoreFunctionalExpressions: ExpressionPredicate = { it !is GrFunctionalExpression } private fun isExitPoint(place: GrExpression): Boolean { return collectExitPoints(place).contains(place) } private fun collectExitPoints(place: GrExpression): List<GrStatement> { return if (canBeExitPoint(place)) { val flowOwner = ControlFlowUtils.findControlFlowOwner(place) ControlFlowUtils.collectReturns(flowOwner) } else { emptyList() } } private fun canBeExitPoint(element: PsiElement?): Boolean { var place = element while (place != null) { if (place is GrMethod || place is GrFunctionalExpression || place is GrClassInitializer) return true if (place is GrThrowStatement || place is GrTypeDefinitionBody || place is GroovyFile) return false place = place.parent } return false }
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/processors/inference/GroovyInferenceSessionBuilder.kt
3423114195
package com.aemtools.codeinsight.htl.annotator import com.aemtools.common.intention.BaseHtlIntentionAction import com.aemtools.common.util.findChildrenByType import com.aemtools.common.util.findParentByType import com.aemtools.common.util.isDoubleQuoted import com.aemtools.common.util.psiDocumentManager import com.aemtools.lang.htl.psi.HtlHtlEl import com.aemtools.lang.htl.psi.mixin.HtlStringLiteralMixin import com.aemtools.lang.util.getHtlFile import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiFile import com.intellij.psi.SmartPsiElementPointer import com.intellij.psi.templateLanguages.OuterLanguageElement import com.intellij.psi.xml.XmlAttribute /** * Inverts [XmlAttribute] quotes. * * @author Dmytro Troynikov */ class HtlWrongQuotesXmlAttributeInvertQuotesIntentionAction( private val pointer: SmartPsiElementPointer<XmlAttribute> ) : BaseHtlIntentionAction( text = { "Invert XML Attribute quotes" } ) { override fun invoke(project: Project, editor: Editor, file: PsiFile) { val element = pointer.element ?: return val valueElement = element.valueElement ?: return val psiDocumentManager = project.psiDocumentManager() val document = psiDocumentManager.getDocument(file) ?: return val rootDoublequoted = element.isDoubleQuoted() val htl = element.containingFile.getHtlFile() ?: return if (rootDoublequoted) { document.replaceString( valueElement.textRange.startOffset, valueElement.textRange.startOffset + 1, "'" ) document.replaceString( valueElement.textRange.endOffset - 1, valueElement.textRange.endOffset, "'" ) } else { document.replaceString( valueElement.textRange.startOffset, valueElement.textRange.startOffset + 1, "\"" ) document.replaceString( valueElement.textRange.endOffset - 1, valueElement.textRange.endOffset, "\"" ) } val htlLiterals = element.findChildrenByType(OuterLanguageElement::class.java) .flatMap { outerLanguageElement -> val htlEl = htl.findElementAt(outerLanguageElement.textOffset) ?.findParentByType(HtlHtlEl::class.java) ?: return@flatMap emptyList<HtlStringLiteralMixin>() htlEl.findChildrenByType(HtlStringLiteralMixin::class.java) } htlLiterals.forEach { literal -> val newVal = if (rootDoublequoted) { literal.toDoubleQuoted() } else { literal.toSingleQuoted() } document.replaceString( literal.textRange.startOffset, literal.textRange.endOffset, newVal ) } psiDocumentManager.commitDocument(document) } }
aem-intellij-core/src/main/kotlin/com/aemtools/codeinsight/htl/annotator/HtlWrongQuotesXmlAttributeInvertQuotesIntentionAction.kt
2783010502
/* * Copyright 2019 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.matrix.androidsdk.rest.model.terms import com.google.gson.annotations.SerializedName /** * This class represent a list of urls of terms the user wants to accept */ data class AcceptTermsBody( @JvmField @SerializedName("user_accepts") val acceptedTermUrls: List<String> )
matrix-sdk/src/main/java/org/matrix/androidsdk/rest/model/terms/AcceptTermsBody.kt
14212227
/* * Copyright 2019 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.matrix.androidsdk.crypto.verification enum class CancelCode(val value: String, val humanReadable: String) { User("m.user", "the user cancelled the verification"), Timeout("m.timeout", "the verification process timed out"), UnknownTransaction("m.unknown_transaction", "the device does not know about that transaction"), UnknownMethod("m.unknown_method", "the device can’t agree on a key agreement, hash, MAC, or SAS method"), MismatchedCommitment("m.mismatched_commitment", "the hash commitment did not match"), MismatchedSas("m.mismatched_sas", "the SAS did not match"), UnexpectedMessage("m.unexpected_message", "the device received an unexpected message"), InvalidMessage("m.invalid_message", "an invalid message was received"), MismatchedKeys("m.key_mismatch", "Key mismatch"), UserMismatchError("m.user_error", "User mismatch") } fun safeValueOf(code: String?): CancelCode { return CancelCode.values().firstOrNull { code == it.value } ?: CancelCode.User }
matrix-sdk-crypto/src/main/java/org/matrix/androidsdk/crypto/verification/CancelCode.kt
89646872
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package io.github.tgeng.firviewer import com.intellij.icons.AllIcons import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.util.elementType import org.jetbrains.kotlin.fir.FirLabel import org.jetbrains.kotlin.fir.FirPureAbstractElement import org.jetbrains.kotlin.fir.contracts.FirContractDescription import org.jetbrains.kotlin.fir.contracts.FirEffectDeclaration import org.jetbrains.kotlin.fir.declarations.FirAnonymousInitializer import org.jetbrains.kotlin.fir.declarations.FirConstructor import org.jetbrains.kotlin.fir.declarations.FirErrorFunction import org.jetbrains.kotlin.fir.declarations.FirFile import org.jetbrains.kotlin.fir.declarations.FirImport import org.jetbrains.kotlin.fir.declarations.FirProperty import org.jetbrains.kotlin.fir.declarations.FirPropertyAccessor import org.jetbrains.kotlin.fir.declarations.FirRegularClass import org.jetbrains.kotlin.fir.declarations.FirSimpleFunction import org.jetbrains.kotlin.fir.declarations.FirTypeAlias import org.jetbrains.kotlin.fir.declarations.FirTypeParameter import org.jetbrains.kotlin.fir.declarations.FirTypeParameterRef import org.jetbrains.kotlin.fir.declarations.FirVariable import org.jetbrains.kotlin.fir.declarations.impl.FirDeclarationStatusImpl import org.jetbrains.kotlin.fir.expressions.FirArgumentList import org.jetbrains.kotlin.fir.expressions.FirAssignmentOperatorStatement import org.jetbrains.kotlin.fir.expressions.FirAugmentedArraySetCall import org.jetbrains.kotlin.fir.expressions.FirCatch import org.jetbrains.kotlin.fir.expressions.FirDelegatedConstructorCall import org.jetbrains.kotlin.fir.expressions.FirExpression import org.jetbrains.kotlin.fir.expressions.FirLoop import org.jetbrains.kotlin.fir.expressions.FirVariableAssignment import org.jetbrains.kotlin.fir.expressions.FirWhenBranch import org.jetbrains.kotlin.fir.expressions.impl.FirStubStatement import org.jetbrains.kotlin.fir.references.FirReference import org.jetbrains.kotlin.fir.types.FirTypeProjection import org.jetbrains.kotlin.fir.types.FirTypeRef import org.jetbrains.kotlin.psi.* import java.awt.Component import javax.swing.JTree import javax.swing.tree.TreeCellRenderer class TreeObjectRenderer : TreeCellRenderer { override fun getTreeCellRendererComponent( tree: JTree, value: Any, selected: Boolean, expanded: Boolean, leaf: Boolean, row: Int, hasFocus: Boolean ): Component { val node = value as? TreeNode<*> ?: return label("nothing to show") return when (val e = node.t) { is FirAnonymousInitializer -> type(node) + render(e) is FirArgumentList -> type(node) + render(e) is FirAssignmentOperatorStatement -> type(node) + render(e) is FirAugmentedArraySetCall -> type(node) + render(e) is FirCatch -> type(node) + render(e) is FirConstructor -> type(node) + label("<init>", icon = AllIcons.Nodes.Function) is FirContractDescription -> type(node) + render(e) is FirDeclarationStatusImpl -> type(node) + render(e) is FirDelegatedConstructorCall -> type(node) + render(e) is FirEffectDeclaration -> type(node) + render(e) is FirErrorFunction -> type(node) + render(e) is FirExpression -> type(node) + render(e) is FirFile -> type(node) + label(e.name) is FirImport -> type(node) + render(e) is FirLabel -> type(node) + render(e) is FirLoop -> type(node) + render(e) is FirPropertyAccessor -> type(node) + render(e) is FirReference -> type(node) + render(e) is FirRegularClass -> type(node) + label(e.name.asString(), icon = AllIcons.Nodes.Class) is FirSimpleFunction -> type(node) + label(e.name.asString(), icon = AllIcons.Nodes.Function) is FirStubStatement -> type(node) + render(e) is FirTypeAlias -> type(node) + render(e) is FirTypeParameter -> type(node) + render(e) is FirTypeProjection -> type(node) + render(e) is FirTypeRef -> type(node) + render(e) is FirProperty -> type(node) + label(e.name.asString(), icon = AllIcons.Nodes.Property) is FirVariable -> type(node) + label(e.name.asString(), icon = AllIcons.Nodes.Variable) is FirVariableAssignment -> type(node) + render(e) is FirWhenBranch -> type(node) + render(e) // is FirConstructedClassTypeParameterRef, // is FirOuterClassTypeParameterRef, is FirTypeParameterRef -> type(node) + render(e as FirPureAbstractElement) is PsiFile -> type(node) + label(e.name) is PsiElement -> type(node) + e.elementType?.let { label("[$it]", italic = true) } + when (e) { is KtDeclaration -> label( e.name ?: "<anonymous>", icon = when (e) { is KtClassOrObject -> AllIcons.Nodes.Class is KtFunction -> AllIcons.Nodes.Function is KtProperty -> AllIcons.Nodes.Property is KtVariableDeclaration -> AllIcons.Nodes.Variable else -> null } ) else -> label(e.text) } else -> label(e.toString()) } } }
src/main/kotlin/io/github/tgeng/firviewer/TreeObjectRenderer.kt
626027480
package slatekit import slatekit.apis.SetupType import slatekit.apis.routes.Api import slatekit.apis.tools.code.CodeGenApi import slatekit.common.conf.Conf import slatekit.context.Context import slatekit.docs.DocApi import slatekit.generator.* interface SlateKitServices { val ctx: Context fun apis(settings:Conf): List<Api> { // APIs val toolSettings = ToolSettings(settings.getString("slatekit.version"), settings.getString("slatekit.version.beta"), "logs/logback.log") val buildSettings = BuildSettings(settings.getString("kotlin.version")) val logger = ctx.logs.getLogger("gen") return listOf( Api(GeneratorApi(ctx, GeneratorService(ctx, settings, SlateKit::class.java, GeneratorSettings(toolSettings, buildSettings), logger = logger)), declaredOnly = true, setup = SetupType.Annotated), Api(DocApi(ctx), declaredOnly = true, setup = SetupType.Annotated), Api(CodeGenApi(), declaredOnly = true, setup = SetupType.Annotated) ) } }
src/lib/kotlin/slatekit/src/main/kotlin/slatekit/SlateKitServices.kt
751524924
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.testing import com.intellij.execution.ExecutionException import com.intellij.execution.Location import com.intellij.execution.PsiLocation import com.intellij.execution.RunnerAndConfigurationSettings import com.intellij.execution.actions.ConfigurationContext import com.intellij.execution.actions.ConfigurationFromContext import com.intellij.execution.configurations.* import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.execution.testframework.AbstractTestProxy import com.intellij.execution.testframework.sm.runner.SMTestLocator import com.intellij.openapi.extensions.ExtensionNotApplicableException import com.intellij.openapi.module.Module import com.intellij.openapi.module.impl.scopes.ModuleWithDependenciesScope import com.intellij.openapi.options.SettingsEditor import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.util.JDOMExternalizerUtil.readField import com.intellij.openapi.util.JDOMExternalizerUtil.writeField import com.intellij.openapi.util.Pair import com.intellij.openapi.util.Ref import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiElement import com.intellij.psi.PsiFileSystemItem import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.util.QualifiedName import com.intellij.refactoring.listeners.RefactoringElementListener import com.intellij.remote.PathMappingProvider import com.intellij.remote.RemoteSdkAdditionalData import com.intellij.util.ThreeState import com.jetbrains.extensions.* import com.jetbrains.extensions.ModuleBasedContextAnchor import com.jetbrains.extensions.QNameResolveContext import com.jetbrains.extensions.getElementAndResolvableName import com.jetbrains.extensions.resolveToElement import com.jetbrains.python.PyBundle import com.jetbrains.python.PyNames import com.jetbrains.python.psi.PyFile import com.jetbrains.python.psi.PyFunction import com.jetbrains.python.psi.PyQualifiedNameOwner import com.jetbrains.python.psi.types.TypeEvalContext import com.jetbrains.python.run.* import com.jetbrains.python.run.targetBasedConfiguration.PyRunTargetVariant import com.jetbrains.python.run.targetBasedConfiguration.TargetWithVariant import com.jetbrains.python.run.targetBasedConfiguration.createRefactoringListenerIfPossible import com.jetbrains.python.run.targetBasedConfiguration.targetAsPsiElement import com.jetbrains.python.sdk.PythonSdkUtil import com.jetbrains.reflection.DelegationProperty import com.jetbrains.reflection.Properties import com.jetbrains.reflection.Property import com.jetbrains.reflection.getProperties import jetbrains.buildServer.messages.serviceMessages.ServiceMessage import jetbrains.buildServer.messages.serviceMessages.TestStdErr import jetbrains.buildServer.messages.serviceMessages.TestStdOut import java.util.regex.Matcher /** * New configuration factories */ internal val pythonFactories get() = arrayOf<PythonConfigurationFactoryBase>( PyUnitTestFactory(), PyTestFactory(), PyNoseTestFactory(), PyTrialTestFactory()) /** * Accepts text that may be wrapped in TC message. Unwraps it and removes TC escape code. * Regular text is unchanged */ fun processTCMessage(text: String): String { val parsedMessage = ServiceMessage.parse(text.trim()) ?: return text // Not a TC message return when (parsedMessage) { is TestStdOut -> parsedMessage.stdOut // TC with stdout is TestStdErr -> parsedMessage.stdErr // TC with stderr else -> "" // TC with out of any output } } internal fun getAdditionalArgumentsPropertyName() = com.jetbrains.python.testing.PyAbstractTestConfiguration::additionalArguments.name /** * If runner name is here that means test runner only can run inheritors for TestCase */ val RunnersThatRequireTestCaseClass: Set<String> = setOf<String>(PythonTestConfigurationsModel.getPythonsUnittestName(), PyTestFrameworkService.getSdkReadableNameByFramework(PyNames.TRIAL_TEST)) /** * Checks if element could be test target * @param testCaseClassRequired see [PythonUnitTestUtil] docs */ fun isTestElement(element: PsiElement, testCaseClassRequired: ThreeState, typeEvalContext: TypeEvalContext): Boolean = when (element) { is PyFile -> PythonUnitTestUtil.isTestFile(element, testCaseClassRequired, typeEvalContext) is com.intellij.psi.PsiDirectory -> element.name.contains("test", true) || element.children.any { it is PyFile && PythonUnitTestUtil.isTestFile(it, testCaseClassRequired, typeEvalContext) } is PyFunction -> PythonUnitTestUtil.isTestFunction(element, testCaseClassRequired, typeEvalContext) is com.jetbrains.python.psi.PyClass -> { PythonUnitTestUtil.isTestClass(element, testCaseClassRequired, typeEvalContext) } else -> false } /** * Since runners report names of tests as qualified name, no need to convert it to PSI and back to string. * We just save its name and provide it again to rerun * @param metainfo additional info provided by test runner, in case of pytest it is test name with parameters (if test is parametrized) */ private class PyTargetBasedPsiLocation(val target: ConfigurationTarget, element: PsiElement, val metainfo: String?) : PsiLocation<PsiElement>(element) { override fun equals(other: Any?): Boolean { if (other is PyTargetBasedPsiLocation) { return target == other.target && metainfo == other.metainfo } return false } override fun hashCode(): Int { return target.hashCode() } } /** * @return factory chosen by user in "test runner" settings */ private fun findConfigurationFactoryFromSettings(module: Module): ConfigurationFactory { val name = TestRunnerService.getInstance(module).projectConfiguration val factories = PythonTestConfigurationType.getInstance().configurationFactories val configurationFactory = factories.find { it.name == name } return configurationFactory ?: factories.first() } // folder provided by python side. Resolve test names versus it private val PATH_URL = java.util.regex.Pattern.compile("^python<([^<>]+)>$") private fun Sdk.getMapping(project: Project) = (sdkAdditionalData as? RemoteSdkAdditionalData<*>)?.let { data -> PathMappingProvider.getSuitableMappingProviders(data).flatMap { it.getPathMappingSettings(project, data).pathMappings } } ?: emptyList() private fun getFolderFromMatcher(matcher: Matcher, module: Module): String? { if (!matcher.matches()) { return null } val folder = matcher.group(1) val sdk = module.getSdk() if (sdk != null && PythonSdkUtil.isRemote(sdk)) { return sdk.getMapping(module.project).find { it.canReplaceRemote(folder) }?.mapToLocal(folder) } else { return folder } } private fun getElementByUrl(protocol: String, path: String, module: Module, evalContext: TypeEvalContext, matcher: Matcher = PATH_URL.matcher(protocol), metainfo: String? = null): Location<out PsiElement>? { val folder = getFolderFromMatcher(matcher, module)?.let { LocalFileSystem.getInstance().findFileByPath(it) } val qualifiedName = QualifiedName.fromDottedString(path) // Assume qname id good and resolve it directly val element = qualifiedName.resolveToElement(QNameResolveContext(ModuleBasedContextAnchor(module), evalContext = evalContext, folderToStart = folder, allowInaccurateResult = true)) return if (element != null) { // Path is qualified name of python test according to runners protocol // Parentheses are part of generators / parametrized tests // Until https://github.com/JetBrains/teamcity-messages/issues/121 they are disabled, // so we cut them out of path not to provide unsupported targets to runners val pathNoParentheses = QualifiedName.fromComponents( qualifiedName.components.filter { !it.contains('(') }).toString() PyTargetBasedPsiLocation(ConfigurationTarget(pathNoParentheses, PyRunTargetVariant.PYTHON), element, metainfo) } else { null } } object PyTestsLocator : SMTestLocator { override fun getLocation(protocol: String, path: String, metainfo: String?, project: Project, scope: GlobalSearchScope): List<Location<out PsiElement>> = getLocationInternal(protocol, path, project, metainfo, scope) override fun getLocation(protocol: String, path: String, project: Project, scope: GlobalSearchScope): List<Location<out PsiElement>> { return getLocationInternal(protocol, path, project, null, scope) } private fun getLocationInternal(protocol: String, path: String, project: Project, metainfo: String?, scope: GlobalSearchScope): List<Location<out PsiElement>> { if (scope !is ModuleWithDependenciesScope) { return listOf() } val matcher = PATH_URL.matcher(protocol) if (!matcher.matches()) { // special case: setup.py runner uses unittest configuration but different (old) protocol // delegate to old protocol locator until setup.py moved to separate configuration val oldLocation = PythonUnitTestTestIdUrlProvider.INSTANCE.getLocation(protocol, path, project, scope) if (oldLocation.isNotEmpty()) { return oldLocation } } return getElementByUrl(protocol, path, scope.module, TypeEvalContext.codeAnalysis(project, null), matcher, metainfo)?.let { listOf(it) } ?: listOf() } } abstract class PyTestExecutionEnvironment<T : PyAbstractTestConfiguration>(configuration: T, environment: ExecutionEnvironment) : PythonTestCommandLineStateBase<T>(configuration, environment) { override fun getTestLocator(): SMTestLocator = PyTestsLocator override fun getTestSpecs(): MutableList<String> = java.util.ArrayList(configuration.getTestSpec()) override fun generateCommandLine(): GeneralCommandLine { val line = super.generateCommandLine() line.workDirectory = java.io.File(configuration.workingDirectorySafe) return line } } abstract class PyAbstractTestSettingsEditor(private val sharedForm: PyTestSharedForm) : SettingsEditor<PyAbstractTestConfiguration>() { override fun resetEditorFrom(s: PyAbstractTestConfiguration) { // usePojoProperties is true because we know that Form is java-based AbstractPythonRunConfiguration.copyParams(s, sharedForm.optionsForm) s.copyTo(getProperties(sharedForm, usePojoProperties = true)) } override fun applyEditorTo(s: PyAbstractTestConfiguration) { AbstractPythonRunConfiguration.copyParams(sharedForm.optionsForm, s) s.copyFrom(getProperties(sharedForm, usePojoProperties = true)) } override fun createEditor(): javax.swing.JComponent = sharedForm.panel } /** * Default target path (run all tests ion project folder) */ private const val DEFAULT_PATH = "" /** * Target depends on target type. It could be path to file/folder or python target */ data class ConfigurationTarget(@ConfigField override var target: String, @ConfigField override var targetType: PyRunTargetVariant) : TargetWithVariant { fun copyTo(dst: ConfigurationTarget) { // TODO: do we have such method it in Kotlin? dst.target = target dst.targetType = targetType } /** * Validates configuration and throws exception if target is invalid */ fun checkValid() { if (targetType != PyRunTargetVariant.CUSTOM && target.isEmpty()) { throw RuntimeConfigurationWarning("Target not provided") } if (targetType == PyRunTargetVariant.PYTHON && !isWellFormed()) { throw RuntimeConfigurationError("Provide a qualified name of function, class or a module") } } fun asPsiElement(configuration: PyAbstractTestConfiguration): PsiElement? = asPsiElement(configuration, configuration.getWorkingDirectoryAsVirtual()) fun generateArgumentsLine(configuration: PyAbstractTestConfiguration): List<String> = when (targetType) { PyRunTargetVariant.CUSTOM -> emptyList() PyRunTargetVariant.PYTHON -> getArgumentsForPythonTarget(configuration) PyRunTargetVariant.PATH -> listOf("--path", target.trim()) } private fun getArgumentsForPythonTarget(configuration: PyAbstractTestConfiguration): List<String> { val element = asPsiElement(configuration) ?: throw ExecutionException( "Can't resolve $target. Try to remove configuration and generate it again") if (element is PsiDirectory) { // Directory is special case: we can't run it as package for now, so we run it as path return listOf("--path", element.virtualFile.path) } val context = TypeEvalContext.userInitiated(configuration.project, null) val qNameResolveContext = QNameResolveContext( contextAnchor = ModuleBasedContextAnchor(configuration.module!!), evalContext = context, folderToStart = LocalFileSystem.getInstance().findFileByPath(configuration.workingDirectorySafe), allowInaccurateResult = true ) val qualifiedNameParts = QualifiedName.fromDottedString(target.trim()).tryResolveAndSplit(qNameResolveContext) ?: throw ExecutionException("Can't find file where $target declared. " + "Make sure it is in project root") // We can't provide element qname here: it may point to parent class in case of inherited functions, // so we make fix file part, but obey element(symbol) part of qname if (!configuration.shouldSeparateTargetPath()) { // Here generate qname instead of file/path::element_name // Try to set path relative to work dir (better than path from closest root) // If we can resolve element by this path relative to working directory then use it val qNameInsideOfDirectory = qualifiedNameParts.getElementNamePrependingFile() val elementAndName = qNameInsideOfDirectory.getElementAndResolvableName(qNameResolveContext.copy(allowInaccurateResult = false)) if (elementAndName != null) { // qNameInsideOfDirectory may contain redundant elements like subtests so we use name that was really resolved // element.qname can't be used because inherited test resolves to parent return listOf("--target", elementAndName.name.toString()) } // Use "full" (path from closest root) otherwise val name = (element.containingFile as? PyFile)?.getQName()?.append(qualifiedNameParts.elementName) ?: throw ExecutionException( "Can't get importable name for ${element.containingFile}. Is it a python file in project?") return listOf("--target", name.toString()) } else { // Here generate file/path::element_name val pyTarget = qualifiedNameParts.elementName val elementFile = element.containingFile.virtualFile val workingDir = elementFile.fileSystem.findFileByPath(configuration.workingDirectorySafe) val fileSystemPartOfTarget = (if (workingDir != null) VfsUtil.getRelativePath(elementFile, workingDir) else null) ?: elementFile.path if (pyTarget.componentCount == 0) { // If python part is empty we are launching file. To prevent junk like "foo.py::" we run it as file instead return listOf("--path", fileSystemPartOfTarget) } return listOf("--target", "$fileSystemPartOfTarget::$pyTarget") } } /** * @return directory which target is situated */ fun getElementDirectory(configuration: PyAbstractTestConfiguration): VirtualFile? { if (target == DEFAULT_PATH) { //This means "current directory", so we do not know where is it // getting vitualfile for it may return PyCharm working directory which is not what we want return null } val fileOrDir = asVirtualFile() ?: asPsiElement(configuration)?.containingFile?.virtualFile ?: return null return if (fileOrDir.isDirectory) fileOrDir else fileOrDir.parent } } /** * To prevent legacy configuration options from clashing with new names, we add prefix * to use for writing/reading xml */ private val Property.prefixedName: String get() = "_new_" + this.getName() /** * "Custom symbol" is mode when test runner uses [PyRunTargetVariant.CUSTOM] and has * [PyAbstractTestConfiguration.additionalArguments] that points to some symbol inside of file i.e.: * ``/foo/bar.py::SomeTest.some_method`` * * This mode is framework-specific. * It is used for cases like ``PY-25586`` */ internal interface PyTestConfigurationWithCustomSymbol { /** * Separates file part and symbol */ val fileSymbolSeparator: String /** * Separates parts of symbol name */ val symbolSymbolSeparator: String fun createAdditionalArguments(parts: QualifiedNameParts) = with(parts) { file.virtualFile.path + fileSymbolSeparator + elementName.components.joinToString(symbolSymbolSeparator) } } /** * Parent of all new test configurations. * All config-specific fields are implemented as properties. They are saved/restored automatically and passed to GUI form. * */ abstract class PyAbstractTestConfiguration(project: Project, configurationFactory: ConfigurationFactory, private val runnerName: String) : AbstractPythonTestRunConfiguration<PyAbstractTestConfiguration>(project, configurationFactory), PyRerunAwareConfiguration, RefactoringListenerProvider { /** * Args after it passed to test runner itself */ protected val rawArgumentsSeparator = "--" @DelegationProperty val target: ConfigurationTarget = ConfigurationTarget(DEFAULT_PATH, PyRunTargetVariant.PATH) @ConfigField var additionalArguments: String = "" val testFrameworkName: String = configurationFactory.name /** * @see [RunnersThatRequireTestCaseClass] */ fun isTestClassRequired(): ThreeState = if (RunnersThatRequireTestCaseClass.contains(runnerName)) { ThreeState.YES } else { ThreeState.NO } @Suppress("LeakingThis") // Legacy adapter is used to support legacy configs. Leak is ok here since everything takes place in one thread @DelegationProperty val legacyConfigurationAdapter: PyTestLegacyConfigurationAdapter<PyAbstractTestConfiguration> = PyTestLegacyConfigurationAdapter(this) /** * For real launch use [getWorkingDirectorySafe] instead */ internal fun getWorkingDirectoryAsVirtual(): VirtualFile? { if (!workingDirectory.isNullOrEmpty()) { return LocalFileSystem.getInstance().findFileByPath(workingDirectory) } return null } override fun getWorkingDirectorySafe(): String { val dirProvidedByUser = super.getWorkingDirectory() if (!dirProvidedByUser.isNullOrEmpty()) { return dirProvidedByUser } return target.getElementDirectory(this)?.path ?: super.getWorkingDirectorySafe() } override fun getRefactoringElementListener(element: PsiElement?): RefactoringElementListener? { if (element == null) return null var renamer = CompositeRefactoringElementListener(PyWorkingDirectoryRenamer(getWorkingDirectoryAsVirtual(), this)) createRefactoringListenerIfPossible(element, target.asPsiElement(this), target.asVirtualFile(), { target.target = it })?.let { renamer = renamer.plus(it) } return renamer } override fun checkConfiguration() { super.checkConfiguration() if (!isFrameworkInstalled()) { throw RuntimeConfigurationWarning( PyBundle.message("runcfg.testing.no.test.framework", testFrameworkName)) } target.checkValid() } /** * Check if framework is available on SDK */ abstract fun isFrameworkInstalled(): Boolean override fun isIdTestBased(): Boolean = true private fun getPythonTestSpecByLocation(location: Location<*>): List<String> { if (location is PyTargetBasedPsiLocation) { return location.target.generateArgumentsLine(this) } if (location !is PsiLocation) { return emptyList() } if (location.psiElement !is PyQualifiedNameOwner) { return emptyList() } val qualifiedName = (location.psiElement as PyQualifiedNameOwner).qualifiedName ?: return emptyList() // Resolve name as python qname as last resort return ConfigurationTarget(qualifiedName, PyRunTargetVariant.PYTHON).generateArgumentsLine(this) } final override fun getTestSpec(location: Location<*>, failedTest: AbstractTestProxy): String? { val list = getPythonTestSpecByLocation(location) if (list.isEmpty()) { return null } else { return list.joinToString(" ") } } override fun getTestSpecsForRerun(scope: com.intellij.psi.search.GlobalSearchScope, locations: MutableList<Pair<Location<*>, AbstractTestProxy>>): List<String> { val result = java.util.ArrayList<String>() // Set used to remove duplicate targets locations.map { it.first }.distinctBy { it.psiElement }.map { getPythonTestSpecByLocation(it) }.forEach { result.addAll(it) } return result + generateRawArguments(true) } open fun getTestSpec(): List<String> { return target.generateArgumentsLine(this) + generateRawArguments() } /** * raw arguments to be added after "--" and passed to runner directly */ private fun generateRawArguments(forRerun: Boolean = false): List<String> { val rawArguments = additionalArguments + " " + getCustomRawArgumentsString(forRerun) if (rawArguments.isNotBlank()) { return listOf(rawArgumentsSeparator) + com.intellij.util.execution.ParametersListUtil.parse(rawArguments, false, true) } return emptyList() } override fun suggestedName(): String = when (target.targetType) { PyRunTargetVariant.PATH -> { val name = target.asVirtualFile()?.name "$testFrameworkName in " + (name ?: target.target) } PyRunTargetVariant.PYTHON -> { "$testFrameworkName for " + target.target } else -> { testFrameworkName } } /** * @return configuration-specific arguments */ protected open fun getCustomRawArgumentsString(forRerun: Boolean = false): String = "" fun reset() { target.target = DEFAULT_PATH target.targetType = PyRunTargetVariant.PATH additionalArguments = "" } fun copyFrom(src: Properties) { src.copyTo(getConfigFields()) } fun copyTo(dst: Properties) { getConfigFields().copyTo(dst) } override fun writeExternal(element: org.jdom.Element) { // Write legacy config to preserve it legacyConfigurationAdapter.writeExternal(element) // Super is called after to overwrite legacy settings with new one super.writeExternal(element) val gson = com.google.gson.Gson() getConfigFields().properties.forEach { val value = it.get() if (value != null) { // No need to write null since null is default value writeField(element, it.prefixedName, gson.toJson(value)) } } } override fun readExternal(element: org.jdom.Element) { super.readExternal(element) val gson = com.google.gson.Gson() getConfigFields().properties.forEach { val fromJson: Any? = gson.fromJson(readField(element, it.prefixedName), it.getType()) if (fromJson != null) { it.set(fromJson) } } legacyConfigurationAdapter.readExternal(element) } private fun getConfigFields() = getProperties(this, ConfigField::class.java) /** * Checks if element could be test target for this config. * Function is used to create tests by context. * * If yes, and element is [PsiElement] then it is [PyRunTargetVariant.PYTHON]. * If file then [PyRunTargetVariant.PATH] */ fun couldBeTestTarget(element: PsiElement): Boolean { // TODO: PythonUnitTestUtil logic is weak. We should give user ability to launch test on symbol since user knows better if folder // contains tests etc val context = TypeEvalContext.userInitiated(element.project, element.containingFile) return isTestElement(element, isTestClassRequired(), context) } /** * There are 2 ways to provide target to runner: * * As full qname (package1.module1.Class1.test_foo) * * As filesystem path (package1/module1.py::Class1.test_foo) full or relative to working directory * * Second approach is prefered if this flag is set. It is generally better because filesystem path does not need __init__.py */ internal open fun shouldSeparateTargetPath(): Boolean = true /** * @param metaInfo String "metainfo" field provided by test runner. * Pytest reports test name with parameters here */ open fun setMetaInfo(metaInfo: String) { } /** * @return Boolean if metainfo and target produces same configuration */ open fun isSameAsLocation(target: ConfigurationTarget, metainfo: String?): Boolean = target == this.target } abstract class PyAbstractTestFactory<out CONF_T : PyAbstractTestConfiguration> : PythonConfigurationFactoryBase( PythonTestConfigurationType.getInstance()) { abstract override fun createTemplateConfiguration(project: Project): CONF_T } internal sealed class PyTestTargetForConfig(val configurationTarget: ConfigurationTarget, val workingDirectory: VirtualFile) { class PyTestPathTarget(target: String, workingDirectory: VirtualFile) : PyTestTargetForConfig(ConfigurationTarget(target, PyRunTargetVariant.PATH), workingDirectory) class PyTestPythonTarget(target: String, workingDirectory: VirtualFile, val namePaths: QualifiedNameParts) : PyTestTargetForConfig(ConfigurationTarget(target, PyRunTargetVariant.PYTHON), workingDirectory) } /** * Only one producer is registered with EP, but it uses factory configured by user to produce different configs */ internal class PyTestsConfigurationProducer : AbstractPythonTestConfigurationProducer<PyAbstractTestConfiguration>() { companion object { /** * Creates [ConfigurationTarget] to make configuration work with provided element. * Also reports working dir what should be set to configuration to work correctly * @return [target, workingDirectory] */ internal fun getTargetForConfig(configuration: PyAbstractTestConfiguration, baseElement: PsiElement): PyTestTargetForConfig? { var element = baseElement // Go up until we reach top of the file // asking configuration about each element if it is supported or not // If element is supported -- set it as configuration target do { if (configuration.couldBeTestTarget(element)) { when (element) { is PyQualifiedNameOwner -> { // Function, class, method val module = configuration.module ?: return null val elementFile = element.containingFile as? PyFile ?: return null val workingDirectory = getDirectoryForFileToBeImportedFrom(elementFile) ?: return null val context = QNameResolveContext(ModuleBasedContextAnchor(module), evalContext = TypeEvalContext.userInitiated(configuration.project, null), folderToStart = workingDirectory.virtualFile) val parts = element.tryResolveAndSplit(context) ?: return null val qualifiedName = parts.getElementNamePrependingFile(workingDirectory) return PyTestTargetForConfig.PyTestPythonTarget(qualifiedName.toString(), workingDirectory.virtualFile, parts) } is PsiFileSystemItem -> { val virtualFile = element.virtualFile val workingDirectory: VirtualFile = when (element) { is PyFile -> getDirectoryForFileToBeImportedFrom(element)?.virtualFile is PsiDirectory -> virtualFile else -> return null } ?: return null return PyTestTargetForConfig.PyTestPathTarget(virtualFile.path, workingDirectory) } } } element = element.parent ?: break } while (element !is PsiDirectory) // if parent is folder, then we are at file level return null } /** * Inspects file relative imports, finds farthest and returns folder with imported file */ private fun getDirectoryForFileToBeImportedFrom(file: PyFile): PsiDirectory? { val maxRelativeLevel = file.fromImports.map { it.relativeLevel }.max() ?: 0 var elementFolder = file.parent ?: return null for (i in 1..maxRelativeLevel) { elementFolder = elementFolder.parent ?: return null } return elementFolder } } init { if (!isNewTestsModeEnabled()) { throw ExtensionNotApplicableException.INSTANCE } } override fun getConfigurationFactory() = PythonTestConfigurationType.getInstance().configurationFactories[0] override val configurationClass: Class<PyAbstractTestConfiguration> = PyAbstractTestConfiguration::class.java override fun createLightConfiguration(context: ConfigurationContext): RunConfiguration? { val module = context.module ?: return null val project = context.project ?: return null val configuration = findConfigurationFactoryFromSettings(module).createTemplateConfiguration(project) as? PyAbstractTestConfiguration ?: return null if (!setupConfigurationFromContext(configuration, context, Ref(context.psiLocation))) return null return configuration } override fun cloneTemplateConfiguration(context: ConfigurationContext): RunnerAndConfigurationSettings { return cloneTemplateConfigurationStatic(context, findConfigurationFactoryFromSettings(context.module)) } override fun createConfigurationFromContext(context: ConfigurationContext): ConfigurationFromContext? { // Since we need module, no need to even try to create config with out of it context.module ?: return null return super.createConfigurationFromContext(context) } override fun findOrCreateConfigurationFromContext(context: ConfigurationContext): ConfigurationFromContext? { if (!isNewTestsModeEnabled()) { return null } return super.findOrCreateConfigurationFromContext(context) } // test configuration is always prefered over regular one override fun shouldReplace(self: ConfigurationFromContext, other: ConfigurationFromContext): Boolean = other.configuration is PythonRunConfiguration override fun isPreferredConfiguration(self: ConfigurationFromContext?, other: ConfigurationFromContext): Boolean = other.configuration is PythonRunConfiguration override fun setupConfigurationFromContext(configuration: PyAbstractTestConfiguration, context: ConfigurationContext, sourceElement: Ref<PsiElement>): Boolean { val element = sourceElement.get() ?: return false if (element.containingFile !is PyFile && element !is PsiDirectory) { return false } val location = context.location configuration.module = context.module configuration.isUseModuleSdk = true if (location is PyTargetBasedPsiLocation) { location.target.copyTo(configuration.target) location.metainfo?.let { configuration.setMetaInfo(it) } } else { val targetForConfig = PyTestsConfigurationProducer.getTargetForConfig(configuration, element) ?: return false targetForConfig.configurationTarget.copyTo(configuration.target) // Directory may be set in Default configuration. In that case no need to rewrite it. if (configuration.workingDirectory.isNullOrEmpty()) { configuration.workingDirectory = targetForConfig.workingDirectory.path } else { // Template has working directory set if (targetForConfig is PyTestTargetForConfig.PyTestPythonTarget) { configuration.target.asPsiElement(configuration)?.containingFile?.let { file -> val namePaths = targetForConfig.namePaths //This working directory affects resolving process making it point to different file if (file != namePaths.file && configuration is PyTestConfigurationWithCustomSymbol) { /*** * Use "Custom symbol" ([PyTestConfigurationWithCustomSymbol]) mode */ configuration.target.target = "" configuration.target.targetType = PyRunTargetVariant.CUSTOM configuration.additionalArguments = configuration.createAdditionalArguments(namePaths) } } } } } configuration.setGeneratedName() return true } override fun isConfigurationFromContext(configuration: PyAbstractTestConfiguration, context: ConfigurationContext): Boolean { if (PyTestConfigurationSelector.EP.extensionList.find { it.isFromContext(configuration, context) } != null) { return true } val location = context.location if (location is PyTargetBasedPsiLocation) { // With derived classes several configurations for same element may exist return configuration.isSameAsLocation(location.target, location.metainfo) } val psiElement = context.psiLocation ?: return false val configurationFromContext = createConfigurationFromContext(context)?.configuration as? PyAbstractTestConfiguration ?: return false if (configuration.target != configurationFromContext.target) { return false } if (configuration.target.targetType == PyRunTargetVariant.CUSTOM) { /** * Two "custom symbol" ([PyTestConfigurationWithCustomSymbol]) configurations are same when additional args are same */ return (configuration is PyTestConfigurationWithCustomSymbol && configuration.additionalArguments == configurationFromContext.additionalArguments && configuration.fileSymbolSeparator in configuration.additionalArguments) } //Even of both configurations have same targets, it could be that both have same qname which is resolved // to different elements due to different working folders. // Resolve them and check files if (configuration.target.targetType != PyRunTargetVariant.PYTHON) return true val targetPsi = targetAsPsiElement(configuration.target.targetType, configuration.target.target, configuration, configuration.getWorkingDirectoryAsVirtual()) ?: return true return targetPsi.containingFile == psiElement.containingFile } } @Retention(AnnotationRetention.RUNTIME) @Target(AnnotationTarget.PROPERTY) /** * Mark run configuration field with it to enable saving, resotring and form iteraction */ annotation class ConfigField
python/src/com/jetbrains/python/testing/PyTestsShared.kt
269129524
package acr.browser.lightning.adblock.allowlist /** * The model that determines if a URL is whitelisted or not. */ interface AllowListModel { /** * Returns `true` if the [url] is allowed to display ads, `false` otherwise. */ fun isUrlAllowedAds(url: String): Boolean /** * Adds the provided [url] to the list of sites that are allowed to display ads. */ fun addUrlToAllowList(url: String) /** * Removes the provided [url] from the whitelist. */ fun removeUrlFromAllowList(url: String) }
app/src/main/java/acr/browser/lightning/adblock/allowlist/AllowListModel.kt
3687587669
package slatekit.query object Const { @JvmStatic val Null = "null" @JvmStatic val Asc = "asc" @JvmStatic val Desc = "desc" @JvmStatic val All = "*" @JvmStatic val EmptyString = "''" }
src/lib/kotlin/slatekit-query/src/main/kotlin/slatekit/query/Const.kt
1891785403
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.java.refactoring.suggested import com.intellij.ide.highlighter.JavaFileType import com.intellij.openapi.actionSystem.IdeActions import com.intellij.openapi.fileTypes.LanguageFileType import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiElementFactory import com.intellij.psi.PsiJavaFile import com.intellij.psi.search.GlobalSearchScope import com.intellij.refactoring.BaseRefactoringProcessor import com.intellij.refactoring.suggested.BaseSuggestedRefactoringTest import com.intellij.refactoring.suggested.SuggestedRefactoringExecution import com.intellij.refactoring.suggested._suggestedChangeSignatureNewParameterValuesForTests class JavaSuggestedRefactoringTest : BaseSuggestedRefactoringTest() { override val fileType: LanguageFileType get() = JavaFileType.INSTANCE override fun setUp() { super.setUp() _suggestedChangeSignatureNewParameterValuesForTests = { SuggestedRefactoringExecution.NewParameterValue.Expression( PsiElementFactory.getInstance(project).createExpressionFromText("default$it", null) ) } } fun testRenameClass() { doTestRename( """ class C { private class Inner<caret> { } private void foo(Inner inner) { } } """.trimIndent(), """ class C { private class InnerNew<caret> { } private void foo(InnerNew innerNew) { } } """.trimIndent(), "Inner", "InnerNew", { myFixture.type("New") } ) } fun testRenameMethod() { doTestRename( """ class C { void foo<caret>(float f) { foo(1); } void bar() { foo(2); } } """.trimIndent(), """ class C { void fooNew<caret>(float f) { fooNew(1); } void bar() { fooNew(2); } } """.trimIndent(), "foo", "fooNew", { myFixture.type("New") } ) } fun testRenameField() { doTestRename( """ class C { private int <caret>field; public C(int field) { this.field = field; } void foo() { field++; } } """.trimIndent(), """ class C { private int newField<caret>; public C(int newField) { this.newField = newField; } void foo() { newField++; } } """.trimIndent(), "field", "newField", { myFixture.performEditorAction(IdeActions.ACTION_EDITOR_SELECT_WORD_AT_CARET) myFixture.type("newField") } ) } fun testRenameLocal() { doTestRename( """ class C { void foo(float f) { float local<caret> = f; local += 1; } } """.trimIndent(), """ class C { void foo(float f) { float localNew<caret> = f; localNew += 1; } } """.trimIndent(), "local", "localNew", { myFixture.type("New") } ) } fun testRenameClass2() { doTestRename( """ class C { private class <caret>Inner { } private void foo(Inner inner) { } } """.trimIndent(), """ class C { private class New<caret>Inner { } private void foo(NewInner newInner) { } } """.trimIndent(), "Inner", "NewInner", { myFixture.type("New") } ) } fun testChangeReturnType() { ignoreErrorsAfter = true doTestChangeSignature( """ interface I { <caret>void foo(float f); } class C implements I { public void foo(float f) { } } """.trimIndent(), """ interface I { <caret>int foo(float f); } class C implements I { public int foo(float f) { } } """.trimIndent(), "implementations", { replaceTextAtCaret("void", "int") } ) } fun testAddParameter() { ignoreErrorsAfter = true doTestChangeSignature( """ package ppp; import java.io.IOException; interface I { void foo(String s<caret>) throws IOException; } class C implements I { public void foo(String s) throws IOException { } void bar(I i) { try { i.foo(""); } catch(Exception e) {} } } class C1 implements I { public void foo(String s) /* don't add IOException here! */ { } } """.trimIndent(), """ package ppp; import java.io.IOException; interface I { void foo(String s, I p<caret>) throws IOException; } class C implements I { public void foo(String s, I p) throws IOException { } void bar(I i) { try { i.foo("", default0); } catch(Exception e) {} } } class C1 implements I { public void foo(String s, I p) /* don't add IOException here! */ { } } """.trimIndent(), "usages", { myFixture.type(", I p") }, expectedPresentation = """ Old: 'void' ' ' 'foo' '(' LineBreak('', true) Group: 'String' ' ' 's' LineBreak('', false) ')' LineBreak(' ', false) 'throws' LineBreak(' ', true) 'IOException' New: 'void' ' ' 'foo' '(' LineBreak('', true) Group: 'String' ' ' 's' ',' LineBreak(' ', true) Group (added): 'I' ' ' 'p' LineBreak('', false) ')' LineBreak(' ', false) 'throws' LineBreak(' ', true) 'IOException' """.trimIndent() ) } fun testRemoveParameter() { doTestChangeSignature( """ interface I { void foo(float f, int i<caret>); } class C implements I { public void foo(float f, int i) { } void bar(I i) { i.foo(1, 2); } } """.trimIndent(), """ interface I { void foo(float f<caret>); } class C implements I { public void foo(float f) { } void bar(I i) { i.foo(1); } } """.trimIndent(), "usages", { deleteTextBeforeCaret(", int i") } ) } fun testReorderParameters() { doTestChangeSignature( """ interface I { void foo(float p1, int p2, boolean p3<caret>); } class C implements I { public void foo(float p1, int p2, boolean p3) { } void bar(I i) { i.foo(1, 2, false); } } """.trimIndent(), """ interface I { void foo(boolean p3, float p1, int p2); } class C implements I { public void foo(boolean p3, float p1, int p2) { } void bar(I i) { i.foo(false, 1, 2); } } """.trimIndent(), "usages", { myFixture.performEditorAction(IdeActions.MOVE_ELEMENT_LEFT) }, { myFixture.performEditorAction(IdeActions.MOVE_ELEMENT_LEFT) }, wrapIntoCommandAndWriteAction = false ) } fun testChangeParameterType() { doTestChangeSignature( """ interface I { void foo(float<caret> f); } class C implements I { public void foo(float f) { } void bar(I i) { i.foo(1); } } """.trimIndent(), """ interface I { void foo(int<caret> f); } class C implements I { public void foo(int f) { } void bar(I i) { i.foo(1); } } """.trimIndent(), "implementations", { repeat("float".length) { myFixture.performEditorAction(IdeActions.ACTION_EDITOR_BACKSPACE) } }, { myFixture.type("int") } ) } fun testChangeParameterTypeWithImportInsertion() { myFixture.addFileToProject( "X.java", """ package xxx; public class X {} """.trimIndent() ) val otherFile = myFixture.addFileToProject( "Other.java", """ class D implements I { public void foo(float p) { } } """.trimIndent() ) doTestChangeSignature( """ interface I { void foo(<caret>float p); } class C implements I { public void foo(float p) { } } """.trimIndent(), """ import xxx.X; interface I { void foo(<caret>X p); } class C implements I { public void foo(X p) { } } """.trimIndent(), "implementations", { replaceTextAtCaret("float", "X") }, { addImport("xxx.X") } ) assertEquals( """ import xxx.X; class D implements I { public void foo(X p) { } } """.trimIndent(), otherFile.text ) } fun testChangeParameterTypeWithImportReplaced() { myFixture.addFileToProject( "X.java", """ package xxx; public class X {} """.trimIndent() ) myFixture.addFileToProject( "Y.java", """ package xxx; public class Y {} """.trimIndent() ) val otherFile = myFixture.addFileToProject( "Other.java", """ import xxx.X; class D implements I { public void foo(X p) { } } """.trimIndent() ) doTestChangeSignature( """ import xxx.X; interface I { void foo(<caret>X p); } """.trimIndent(), """ import xxx.Y; interface I { void foo(<caret>Y p); } """.trimIndent(), "implementations", { val offset = editor.caretModel.offset editor.document.replaceString(offset, offset + "X".length, "Y") }, { addImport("xxx.Y") removeImport("xxx.X") } ) assertEquals( """ import xxx.Y; class D implements I { public void foo(Y p) { } } """.trimIndent(), otherFile.text ) } fun testAddConstructorParameter() { ignoreErrorsAfter = true doTestChangeSignature( """ class C { C(float f<caret>) { } void bar() { C c = new C(1); } } """.trimIndent(), """ class C { C(float f, int p<caret>) { } void bar() { C c = new C(1, default0); } } """.trimIndent(), "usages", { myFixture.type(", int p") } ) } fun testAddParameterWithAnnotations() { addFileWithAnnotations() val otherFile = myFixture.addFileToProject( "Other.java", """ class C implements I { @Override public void foo() { } } """.trimIndent() ) doTestChangeSignature( """ interface I { void foo(<caret>); } """.trimIndent(), """ import annotations.Language; import annotations.NonStandard; import annotations.NotNull; import org.jetbrains.annotations.Nls; interface I { void foo(@NotNull @Language("JAVA") @Nls @NonStandard("X") String s<caret>); } """.trimIndent(), "usages", { myFixture.type("@NotNull") }, { addImport("annotations.NotNull") }, { myFixture.type(" @Language(\"JAVA\") @Nls @NonStandard(\"X\")") }, { addImport("annotations.Language") addImport("org.jetbrains.annotations.Nls") addImport("annotations.NonStandard") }, { myFixture.type(" String s") }, expectedPresentation = """ Old: 'void' ' ' 'foo' '(' LineBreak('', false) ')' New: 'void' ' ' 'foo' '(' LineBreak('', true) Group (added): '@Nls @NotNull @NonStandard("X")' ' ' 'String' ' ' 's' LineBreak('', false) ')' """.trimIndent() ) assertEquals( """ import annotations.NonStandard; import annotations.NotNull; import org.jetbrains.annotations.Nls; class C implements I { @Override public void foo(@Nls @NotNull @NonStandard("X") String s) { } } """.trimIndent(), otherFile.text ) } fun testChangeNullableToNotNull() { addFileWithAnnotations() val otherFile = myFixture.addFileToProject( "Other.java", """ import annotations.Nullable; class C implements I { @Override public void foo(@Nullable Object o) { } } """.trimIndent() ) doTestChangeSignature( """ import annotations.Nullable; interface I { void foo(@Nullable<caret> Object o); } """.trimIndent(), """ import annotations.NotNull; interface I { void foo(@NotNull<caret> Object o); } """.trimIndent(), "implementations", { val offset = editor.caretModel.offset editor.document.replaceString(offset - "Nullable".length, offset, "NotNull") }, { addImport("annotations.NotNull") removeImport("annotations.Nullable") }, expectedPresentation = """ Old: 'void' ' ' 'foo' '(' LineBreak('', true) Group: '@Nullable' (modified) ' ' 'Object' ' ' 'o' LineBreak('', false) ')' New: 'void' ' ' 'foo' '(' LineBreak('', true) Group: '@NotNull' (modified) ' ' 'Object' ' ' 'o' LineBreak('', false) ')' """.trimIndent() ) assertEquals( """ import annotations.NotNull; class C implements I { @Override public void foo(@NotNull Object o) { } } """.trimIndent(), otherFile.text ) } // TODO: see IDEA-230807 fun testNotNullAnnotation() { addFileWithAnnotations() doTestChangeSignature( """ interface I {<caret> Object foo(); } class C implements I { @Override public Object foo() { return ""; } } """.trimIndent(), """ import annotations.NotNull; interface I { @NotNull<caret> Object foo(); } class C implements I { @Override public @annotations.NotNull Object foo() { return ""; } } """.trimIndent(), "implementations", { myFixture.performEditorAction(IdeActions.ACTION_EDITOR_ENTER) myFixture.type("@NotNull") }, { addImport("annotations.NotNull") } ) } fun testAddThrowsList() { val otherFile = myFixture.addFileToProject( "Other.java", """ class C implements I { @Override public void foo() { } } """.trimIndent() ) doTestChangeSignature( """ interface I { void foo()<caret>; } """.trimIndent(), """ import java.io.IOException; interface I { void foo() throws IOException<caret>; } """.trimIndent(), "implementations", { myFixture.type(" throws IOException") }, { addImport("java.io.IOException") }, expectedPresentation = """ Old: 'void' ' ' 'foo' '(' LineBreak('', false) ')' New: 'void' ' ' 'foo' '(' LineBreak('', false) ')' LineBreak(' ', false) Group (added): 'throws' LineBreak(' ', true) 'IOException' """.trimIndent() ) assertEquals( """ import java.io.IOException; class C implements I { @Override public void foo() throws IOException { } } """.trimIndent(), otherFile.text ) } fun testRemoveThrowsList() { doTestChangeSignature( """ import java.io.IOException; interface I { void foo() throws IOException<caret>; } class C implements I { @Override public void foo() throws IOException { } } """.trimIndent(), """ interface I { void foo()<caret>; } class C implements I { @Override public void foo() { } } """.trimIndent(), "implementations", { deleteTextBeforeCaret(" throws IOException") }, expectedPresentation = """ Old: 'void' ' ' 'foo' '(' LineBreak('', false) ')' LineBreak(' ', false) Group (removed): 'throws' LineBreak(' ', true) 'IOException' New: 'void' ' ' 'foo' '(' LineBreak('', false) ')' """.trimIndent() ) } fun testAddSecondException() { doTestChangeSignature( """ import java.io.IOException; interface I { void foo() throws IOException<caret>; } class C implements I { @Override public void foo() throws IOException { } } """.trimIndent(), """ import java.io.IOException; interface I { void foo() throws IOException, NumberFormatException<caret>; } class C implements I { @Override public void foo() throws IOException, NumberFormatException { } } """.trimIndent(), "implementations", { myFixture.type(", NumberFormatException") }, expectedPresentation = """ Old: 'void' ' ' 'foo' '(' LineBreak('', false) ')' LineBreak(' ', false) 'throws' LineBreak(' ', true) 'IOException' New: 'void' ' ' 'foo' '(' LineBreak('', false) ')' LineBreak(' ', false) 'throws' LineBreak(' ', true) 'IOException' ',' LineBreak(' ', true) 'NumberFormatException' (added) """.trimIndent() ) } fun testChangeVisibility1() { //TODO: see IDEA-230741 BaseRefactoringProcessor.ConflictsInTestsException.withIgnoredConflicts<Throwable> { doTestChangeSignature( """ abstract class Base { <caret>protected abstract void foo(); } class C extends Base { @Override protected void foo() { } } """.trimIndent(), """ abstract class Base { <caret>public abstract void foo(); } class C extends Base { @Override public void foo() { } } """.trimIndent(), "implementations", { val offset = editor.caretModel.offset editor.document.replaceString(offset, offset + "protected".length, "public") }, expectedPresentation = """ Old: 'protected' (modified) ' ' 'void' ' ' 'foo' '(' LineBreak('', false) ')' New: 'public' (modified) ' ' 'void' ' ' 'foo' '(' LineBreak('', false) ')' """.trimIndent() ) } } fun testChangeVisibility2() { //TODO: see IDEA-230741 BaseRefactoringProcessor.ConflictsInTestsException.withIgnoredConflicts<Throwable> { doTestChangeSignature( """ abstract class Base { <caret>abstract void foo(); } class C extends Base { @Override void foo() { } } """.trimIndent(), """ abstract class Base { public <caret>abstract void foo(); } class C extends Base { @Override public void foo() { } } """.trimIndent(), "implementations", { myFixture.type("public ") }, expectedPresentation = """ Old: 'void' ' ' 'foo' '(' LineBreak('', false) ')' New: 'public' (added) ' ' 'void' ' ' 'foo' '(' LineBreak('', false) ')' """.trimIndent() ) } } private fun addFileWithAnnotations() { myFixture.addFileToProject( "Annotations.java", """ package annotations; import java.lang.annotation.*; @Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.LOCAL_VARIABLE, ElementType.TYPE_USE}) public @interface NotNull {} @Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.LOCAL_VARIABLE, ElementType.TYPE_USE}) public @interface Nullable {} @Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.LOCAL_VARIABLE, ElementType.ANNOTATION_TYPE}) public @interface Language { String value(); } @Target({ElementType.TYPE_USE}) public @interface NonStandard { String value(); } """.trimIndent() ) } private fun addImport(fqName: String) { val psiClass = JavaPsiFacade.getInstance(project).findClass(fqName, GlobalSearchScope.allScope(project))!! val importStatement = PsiElementFactory.getInstance(project).createImportStatement(psiClass) (file as PsiJavaFile).importList!!.add(importStatement) } private fun removeImport(fqName: String) { (file as PsiJavaFile).importList!!.findSingleClassImportStatement(fqName)!!.delete() } }
java/java-tests/testSrc/com/intellij/java/refactoring/suggested/JavaSuggestedRefactoringTest.kt
1758019204
object A { class B class C<T> } fun box(): String { val b = A.B() val c = A.C<String>() return "OK" }
backend.native/tests/external/codegen/box/innerNested/nestedClassInObject.kt
933231369
package a interface A<T> { fun foo(): T } open class C: A<Int> { override fun foo(): Int = 42 }
backend.native/tests/codegen/bridges/linkTest_lib.kt
2720997439
/* * File-Finder - KToolZ * * Copyright (c) 2016 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.github.ktoolz.filefinder.model import com.github.ktoolz.filefinder.utils.ExecutionContext import javaslang.collection.List import java.io.File /** * Provides the list of all registered Bangs to be used during a search * * @return a List of all [Bang] to be used during the search process */ fun registeredBangs() = List.of(TargetBang(), SourceBang(), IgnoredBang())!! // --------------------------------------------------------------------------------------------------------------------- /** * Definition of a [Bang] element. * * A [Bang] is actually kind of a filter on the search process. */ interface Bang { /** * Name of the [Bang]. * The name will actually be used in the search field for calling the Bang. * User will have to write it using the syntax: `!name` */ val name: String /** * The actual behavior of the [Bang] which allows to say if a particular File matches the * [Bang] filter criteria * * @param result the result of the search which we want to filter - basically a File which we found * @return a Boolean stating if that File must be considered in the results depending of the Bang. */ fun filter(result: File): Boolean } // --------------------------------------------------------------------------------------------------------------------- /** * [Bang] allowing to filter only source files by their extensions. * It'll allow to keep in the results only source files. If negated, it'll only keep only non-source files. (Cap'tain obvious). */ class SourceBang : Bang { /** * Just a List of all the extensions we consider as "source" files. Surely not complete though, and might be extended in the future. */ val sourceExtensions = listOf("kt", "java", "c", "sh", "cpp", "scala", "xml", "js", "html", "css", "yml", "md") /** * @see [Bang.name] */ override val name = "src" /** * @see [Bang.filter] */ override fun filter(result: File) = sourceExtensions.foldRight(false) { extension, keep -> keep || result.name.endsWith(".$extension") } } // --------------------------------------------------------------------------------------------------------------------- /** * [Bang] allowing to filter only files from a target repository (usual folder used for results of builds). * It'll allow to keep only files coming from those target repositories, or the opposite while negated. */ class TargetBang : Bang { /** * @see [Bang.name] */ override val name = "target" /** * @see [Bang.filter] */ override fun filter(result: File) = result.canonicalPath.contains("/target/") } // --------------------------------------------------------------------------------------------------------------------- /** * [Bang] allowing to filter only files which are considered as ignored. Ignored files are determined through their * extension, using the ones provided in the [ExecutionContext] configuration (ie. the configuration file of * the application). * It'll allow to keep only the ones which are considered ignored, or the opposite if it's negated. */ class IgnoredBang : Bang { /** * @see [Bang.name] */ override val name = "ignored" /** * @see [Bang.filter] */ override fun filter(result: File) = ExecutionContext.ignored.fold(false) { keep, extension -> keep || result.name.endsWith(".$extension") } }
core/src/main/kotlin/com/github/ktoolz/filefinder/model/bangs.kt
1504747972
/* * Copyright (c) 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.chromeos.videocompositionsample.presentation.ui.base import dev.chromeos.videocompositionsample.presentation.tools.exception.ErrorModel import dev.chromeos.videocompositionsample.presentation.tools.info.MessageModel import io.reactivex.disposables.Disposable interface IBaseView { fun showProgress(disposable: Disposable? = null, withPercent: Boolean = false) fun showProgress(withPercent: Boolean = false) { showProgress(null, withPercent) } fun showProgress() { showProgress(null, false) } fun setProgressPercent(percent: Int) fun hideProgress() fun showError(message: String) fun showError(errorModel: ErrorModel) fun onShowMessage(messageModel: MessageModel) fun onShowMessage(message: String) }
VideoCompositionSample/src/main/java/dev/chromeos/videocompositionsample/presentation/ui/base/IBaseView.kt
4153345762
package com.antonio.samir.meteoritelandingsspots.data.repository.model import android.os.Parcelable import androidx.room.Entity import androidx.room.Index import androidx.room.PrimaryKey import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize @Entity(tableName = "meteorites", indices = [Index("id")]) @Parcelize data class Meteorite( @PrimaryKey @SerializedName("id") var id: Int = 0, var mass: String? = null, var nametype: String? = null, var recclass: String? = null, var name: String? = null, var fall: String? = null, var year: String? = null, var reclong: String? = null, var reclat: String? = null, var address: String? = null ) : Parcelable
app/src/main/java/com/antonio/samir/meteoritelandingsspots/data/repository/model/Meteorite.kt
440686066
package com.peterlaurence.trekme.model.providers.stream import com.peterlaurence.trekme.core.map.TileStreamProvider import com.peterlaurence.trekme.core.mapsource.IGNCredentials import com.peterlaurence.trekme.core.providers.bitmap.TileStreamProviderHttpAuth import com.peterlaurence.trekme.core.providers.layers.IgnLayers import com.peterlaurence.trekme.core.providers.urltilebuilder.UrlTileBuilder import com.peterlaurence.trekme.core.providers.urltilebuilder.UrlTileBuilderIgn import java.io.InputStream /** * A [TileStreamProvider] specific for France IGN. * Luckily, IGN's [WMTS service](https://geoservices.ign.fr/documentation/geoservices/wmts.html) has * a grid coordinates that is exactly the same as the one [MapView] uses. <br> * Consequently, to make a valid HTTP request, we just have to format the URL with raw zoom-level, * row and col numbers. <br> * Additional information have to be provided though, like IGN credentials. * * @author peterLaurence on 20/06/19 */ class TileStreamProviderIgn(credentials: IGNCredentials, layer: String = IgnLayers.ScanExpressStandard.realName, urlTileBuilder: UrlTileBuilder): TileStreamProvider { private val base: TileStreamProvider init { base = TileStreamProviderHttpAuth(urlTileBuilder, credentials.user ?: "", credentials.pwd ?: "") } override fun getTileStream(row: Int, col: Int, zoomLvl: Int): InputStream? { /* Filter-out inaccessible tiles at lower levels */ when(zoomLvl) { 3 -> if (row > 7 || col > 7) return null } /* Safeguard */ if (zoomLvl > 17) return null return base.getTileStream(row, col, zoomLvl) } }
app/src/main/java/com/peterlaurence/trekme/model/providers/stream/TileStreamProviderIgn.kt
187515332
/* * This file is part of MythicDrops, licensed under the MIT License. * * Copyright (C) 2019 Richard Harrah * * Permission is hereby granted, free of charge, * to any person obtaining a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.tealcube.minecraft.bukkit.mythicdrops.api.settings.language.command import com.tealcube.minecraft.bukkit.mythicdrops.api.settings.language.traits.Feasible /** * Represents the `command.spawn-random` section in the language.yml. Names map practically one-to-one. */ interface SpawnRandomMessages : Feasible
src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/api/settings/language/command/SpawnRandomMessages.kt
965428411
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.integration.macrobenchmark import androidx.benchmark.macro.CompilationMode import androidx.benchmark.macro.StartupMode import androidx.benchmark.macro.junit4.MacrobenchmarkRule import androidx.test.filters.LargeTest import androidx.testutils.createStartupCompilationParams import androidx.testutils.measureStartup import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized @LargeTest @RunWith(Parameterized::class) class FullyDrawnStartupBenchmark( private val startupMode: StartupMode, private val compilationMode: CompilationMode ) { @get:Rule val benchmarkRule = MacrobenchmarkRule() @Test fun startup() = benchmarkRule.measureStartup( compilationMode = compilationMode, startupMode = startupMode, packageName = "androidx.compose.integration.macrobenchmark.target" ) { action = "androidx.compose.integration.macrobenchmark.target.FULLY_DRAWN_STARTUP_ACTIVITY" } companion object { @Parameterized.Parameters(name = "startup={0},compilation={1}") @JvmStatic fun parameters() = createStartupCompilationParams() } }
compose/integration-tests/macrobenchmark/src/androidTest/java/androidx/compose/integration/macrobenchmark/FullyDrawnStartupBenchmark.kt
2131854692
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.stash import com.github.benmanes.caffeine.cache.CacheLoader import com.github.benmanes.caffeine.cache.Caffeine import com.google.common.util.concurrent.MoreExecutors import com.intellij.openapi.Disposable import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.LowMemoryWatcher import com.intellij.openapi.vcs.VcsException import com.intellij.openapi.vcs.changes.Change import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.vcs.log.Hash import git4idea.GitCommit import git4idea.ui.StashInfo import java.util.concurrent.CompletableFuture import java.util.concurrent.CompletionException class GitStashCache(val project: Project) : Disposable { private val executor = MoreExecutors.listeningDecorator(AppExecutorUtil.createBoundedApplicationPoolExecutor("Git Stash Loader", 1)) private val cache = Caffeine.newBuilder() .maximumSize(100) .executor(executor) .buildAsync<StashId, StashData>(CacheLoader { stashId -> doLoadStashData(stashId) }) init { LowMemoryWatcher.register(Runnable { cache.synchronous().invalidateAll() }, this) } private fun doLoadStashData(stashId: StashId): StashData { try { LOG.debug("Loading stash at '${stashId.hash}' in '${stashId.root}'") val (changes, indexChanges) = GitStashOperations.loadStashChanges(project, stashId.root, stashId.hash, stashId.parentHashes) return StashData.Changes(changes, indexChanges) } catch (e: VcsException) { LOG.warn("Could not load stash at '${stashId.hash}' in '${stashId.root}'", e) return StashData.Error(e) } catch (e: Exception) { if (e !is ProcessCanceledException) LOG.error("Could not load stash at '${stashId.hash}' in '${stashId.root}'", e) throw CompletionException(e); } } fun loadStashData(stashInfo: StashInfo): CompletableFuture<StashData>? { if (Disposer.isDisposed(this)) return null val commitId = StashId(stashInfo.hash, stashInfo.parentHashes, stashInfo.root) val future = cache.get(commitId) if (future.isCancelled) return cache.synchronous().refresh(commitId) return future } override fun dispose() { executor.shutdown() cache.synchronous().invalidateAll() } companion object { private val LOG = Logger.getInstance(GitStashCache::class.java) } sealed class StashData { class Changes(val changes: Collection<Change>, val parentCommits: Collection<GitCommit>) : StashData() class Error(val error: VcsException) : StashData() } private data class StashId(val hash: Hash, val parentHashes: List<Hash>, val root: VirtualFile) }
plugins/git4idea/src/git4idea/stash/GitStashCache.kt
1662359845
package org.ccci.gto.android.common.text import android.text.Editable import android.text.TextWatcher abstract class SimpleTextWatcher : TextWatcher { override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) = Unit override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) = Unit override fun afterTextChanged(s: Editable) = Unit }
gto-support-core/src/main/kotlin/org/ccci/gto/android/common/text/SimpleTextWatcher.kt
809462318
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.editor.tables.inspections import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixture4TestCase import org.intellij.plugins.markdown.MarkdownBundle import org.intellij.plugins.markdown.editor.tables.TableTestUtils import org.junit.Test class MarkdownNoTableBordersInspectionQuickFixTest: LightPlatformCodeInsightFixture4TestCase() { @Test fun `works on table without borders`() { // language=Markdown val before = """ none | none -----|--- some | some """.trimIndent() // language=Markdown val after = """ | none | none | |------|------| | some | some | """.trimIndent() doTest(before, after) } @Test fun `works on table with partial borders`() { // language=Markdown val before = """ |none | none -----|---| |some | some """.trimIndent() // language=Markdown val after = """ | none | none | |------|------| | some | some | """.trimIndent() doTest(before, after) } @Test fun `works on table without borders and empty last cell`() { // language=Markdown val before = """ none | none -----|--- some | """.trimIndent() // language=Markdown val after = """ | none | none | |------|------| | some | | """.trimIndent() doTest(before, after) } private fun doTest(content: String, after: String) { TableTestUtils.runWithChangedSettings(myFixture.project) { myFixture.configureByText("some.md", content) myFixture.enableInspections(MarkdownNoTableBordersInspection()) val targetText = MarkdownBundle.message("markdown.fix.table.borders.intention.text") val fix = myFixture.getAllQuickFixes().find { it.text == targetText } assertNotNull(fix) myFixture.launchAction(fix!!) myFixture.checkResult(after) } } }
plugins/markdown/test/src/org/intellij/plugins/markdown/editor/tables/inspections/MarkdownNoTableBordersInspectionQuickFixTest.kt
2853473673
package test.class_object class ClassObject { fun f() { } val c = 1 public companion object { val j = 0 fun z() = 0 class A { class B { val i: Int = 0 fun f() = 0 } } } class B { companion object { class C { companion object { class D { companion object { val i = 3 fun f() { } enum class En annotation class Anno } } } } } } }
plugins/kotlin/idea/tests/testData/decompiler/stubBuilder/ClassObject/ClassObject.kt
1720349977
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.jsonpath.ui import com.intellij.ide.scratch.ScratchFileService import com.intellij.ide.scratch.ScratchRootType import com.intellij.json.JsonBundle import com.intellij.jsonpath.ui.JsonPathEvaluateManager.Companion.JSON_PATH_EVALUATE_RESULT_KEY import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.OpenFileDescriptor import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.vfs.VfsUtil internal class JsonPathExportEvaluateResultAction : DumbAwareAction() { override fun actionPerformed(e: AnActionEvent) { val project = e.project ?: return val editor = e.getData(CommonDataKeys.EDITOR) ?: return if (editor.getUserData(JSON_PATH_EVALUATE_RESULT_KEY) != true) return ProgressManager.getInstance().runProcessWithProgressSynchronously( Runnable { WriteCommandAction.runWriteCommandAction(project, JsonBundle.message("jsonpath.evaluate.export.result"), null, Runnable { val file = ScratchRootType.getInstance() .findFile(project, "jsonpath-result.json", ScratchFileService.Option.create_new_always) VfsUtil.saveText(file, editor.document.text) val fileEditorManager = FileEditorManager.getInstance(project) if (!fileEditorManager.isFileOpen(file)) { fileEditorManager.openEditor(OpenFileDescriptor(project, file), true) } }) }, JsonBundle.message("jsonpath.evaluate.progress.export.result"), false, project) } override fun update(e: AnActionEvent) { val editor = e.getData(CommonDataKeys.EDITOR) e.presentation.isEnabledAndVisible = editor != null && editor.getUserData(JSON_PATH_EVALUATE_RESULT_KEY) == true } }
json/src/com/intellij/jsonpath/ui/JsonPathExportEvaluateResultAction.kt
1972204527
// "Convert supertype to '(String, T) -> Unit'" "true" class Foo<T> : <caret>String.(T) -> Unit { override fun invoke(p1: String, p2: T) { } }
plugins/kotlin/idea/tests/testData/quickfix/superTypeIsExtensionType/typeWithTypeArgument.kt
4036835887
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.testing import com.intellij.execution.testframework.sm.runner.BaseSMTRunnerTestCase import com.intellij.execution.testframework.sm.runner.SMTestProxy import com.intellij.execution.testframework.sm.runner.states.TestStateInfo import org.junit.Assert import org.junit.Before import org.junit.Test class PyTestMagnitudeTest { private lateinit var root: SMTestProxy.SMRootTestProxy private val tree: String get() = BaseSMTRunnerTestCase.getFormattedTestTree(root) private val test11 = "test11" @Before fun setUp() { root = SMTestProxy.SMRootTestProxy() val file1 = SMTestProxy("file1", false, null) val test11 = SMTestProxy(test11, false, null) val test12 = SMTestProxy("test12", false, null) val file2 = SMTestProxy("file2", false, null) val test21 = SMTestProxy("test21", false, null) val test22 = SMTestProxy("test22", false, null) file1.addChild(test11) file1.addChild(test12) file2.addChild(test21) file2.addChild(test22) root.addChild(file1) root.addChild(file2) } @Test fun testSuccessPass() { root.children.forEach { file -> file.children.forEach { test -> test.setStarted() test.setFinished() } } Assert.assertEquals(TestStateInfo.Magnitude.PASSED_INDEX, root.calculateAndReturnMagnitude()) Assert.assertEquals("Test tree:\n" + "[root](+)\n" + ".file1(+)\n" + "..test11(+)\n" + "..test12(+)\n" + ".file2(+)\n" + "..test21(+)\n" + "..test22(+)\n", tree) } @Test fun testFailedOne() { root.children.forEach { file -> file.children.forEach { test -> test.setStarted() if (test.name == test11) test.setTestFailed("fail", null, false) else test.setFinished() } } Assert.assertEquals(TestStateInfo.Magnitude.FAILED_INDEX, root.calculateAndReturnMagnitude()) Assert.assertEquals("Test tree:\n" + "[root](-)\n" + ".file1(-)\n" + "..test11(-)\n" + "..test12(+)\n" + ".file2(+)\n" + "..test21(+)\n" + "..test22(+)\n", tree) } @Test fun testTerminatedOne() { root.children.forEach { file -> file.children.forEach { test -> test.setStarted() if (test.name != test11) { test.setFinished() } } } Assert.assertEquals(TestStateInfo.Magnitude.TERMINATED_INDEX, root.calculateAndReturnMagnitude()) Assert.assertEquals("Test tree:\n" + "[root][T]\n" + ".file1[T]\n" + "..test11[T]\n" + "..test12(+)\n" + ".file2(+)\n" + "..test21(+)\n" + "..test22(+)\n", tree) } @Test fun testIgnoredAll() { root.children.forEach { file -> file.children.forEach { test -> test.setStarted() test.setTestIgnored("for a good reason", null) } } Assert.assertEquals(TestStateInfo.Magnitude.IGNORED_INDEX, root.calculateAndReturnMagnitude()) Assert.assertEquals("Test tree:\n" + "[root](~)\n" + ".file1(~)\n" + "..test11(~)\n" + "..test12(~)\n" + ".file2(~)\n" + "..test21(~)\n" + "..test22(~)\n", tree) } }
python/testSrc/com/jetbrains/python/testing/PyTestMagnitudeTest.kt
2468379748
// IS_APPLICABLE: true fun foo() { bar(2) <caret>{it * 3} } fun bar(a: Int, b: (Int) -> Int) { b(a) }
plugins/kotlin/idea/tests/testData/intentions/moveLambdaInsideParentheses/moveLambda2.kt
2103192192
// "Remove 'inline' modifier" "true" class C { internal fun foo() = true inline fun bar(baz: () -> Unit) { if (<caret>foo()) { baz() } } }
plugins/kotlin/idea/tests/testData/quickfix/callFromPublicInline/nonPublic/internalFunction3.kt
3423580292
package com.quran.mobile.recitation.presenter import com.quran.data.di.AppScope import com.quran.recitation.presenter.RecitationSettings import com.squareup.anvil.annotations.ContributesBinding import javax.inject.Inject import javax.inject.Singleton @Singleton @ContributesBinding(scope = AppScope::class, boundType = RecitationSettings::class) class RecitationSettingsImpl @Inject constructor() : RecitationSettings { override fun isRecitationEnabled() = false override fun toggleAyahVisibility() {} }
feature/recitation/src/main/java/com/quran/mobile/recitation/presenter/RecitationSettingsImpl.kt
2719174493
package uy.kohesive.iac.examples.aws.lambdas fun String.ensureSingleLine(): String = this.replace('\n', ' ')
aws-examples/lambdas/src/main/kotlin/uy/kohesive/iac/examples/aws/lambdas/Util.kt
3293669603
package de.fabmax.kool.modules.ui2 import de.fabmax.kool.math.toRad import de.fabmax.kool.scene.geometry.MeshBuilder import kotlin.math.cos import kotlin.math.sin fun MeshBuilder.arrow(centerX: Float, centerY: Float, size: Float, rotation: Float) { val si = size * 0.3f * 0.7f val so = size * 0.5f * 0.7f val off = size * 0.15f * 0.7f val m11 = cos((rotation - 45).toRad()) val m12 = -sin((rotation - 45).toRad()) val m21 = sin((rotation - 45).toRad()) val m22 = m11 val x1 = -so - off; val y1 = so - off val x2 = so - off; val y2 = so - off val x3 = so - off; val y3 = -so - off val x4 = si - off; val y4 = -so - off val x5 = si - off; val y5 = si - off val x6 = -so - off; val y6 = si - off val i1 = vertex { set(centerX + m11 * x1 + m12 * y1, centerY + m21 * x1 + m22 * y1, 0f) } val i2 = vertex { set(centerX + m11 * x2 + m12 * y2, centerY + m21 * x2 + m22 * y2, 0f) } val i3 = vertex { set(centerX + m11 * x3 + m12 * y3, centerY + m21 * x3 + m22 * y3, 0f) } val i4 = vertex { set(centerX + m11 * x4 + m12 * y4, centerY + m21 * x4 + m22 * y4, 0f) } val i5 = vertex { set(centerX + m11 * x5 + m12 * y5, centerY + m21 * x5 + m22 * y5, 0f) } val i6 = vertex { set(centerX + m11 * x6 + m12 * y6, centerY + m21 * x6 + m22 * y6, 0f) } addTriIndices(i1, i2, i6) addTriIndices(i6, i2, i5) addTriIndices(i5, i2, i3) addTriIndices(i5, i3, i4) }
kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/ui2/MeshBuilderUiExtensions.kt
1921344043
package de.fabmax.kool.modules.audio.synth /** * @author fabmax */ class Snare(val bpm: Float) : SampleNode() { private val osc = Oscillator(Wave.SQUARE, 175f).apply { gain = 0.156f } private val lowPass = LowPassFilter(30f, this) override fun generate(dt: Float): Float { val s = osc.next(dt) + noise(0.73f) val pc2 = ((t + 0.5) % (60f / bpm)).toFloat() var pc1 = 120f if ((t % 2) > 1) { pc1 = 105f } return lowPass.filter(perc(s, pc1, pc2) * 0.6f) * 5 } }
kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/audio/synth/Snare.kt
2990014297
package de.fabmax.kool.modules.gltf import kotlinx.serialization.Serializable import kotlinx.serialization.Transient /** * Image data used to create a texture. Image can be referenced by URI or bufferView index. mimeType is required in the * latter case. * * @param uri The uri of the image. * @param mimeType The image's MIME type. * @param bufferView The index of the bufferView that contains the image. Use this instead of the image's uri property. * @param name The user-defined name of this object. */ @Serializable data class GltfImage( var uri: String? = null, val mimeType: String? = null, val bufferView: Int = -1, val name: String? = null ) { @Transient var bufferViewRef: GltfBufferView? = null }
kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/gltf/GltfImage.kt
3123801629
package com.viartemev.requestmapper.annotations.spring import com.intellij.psi.PsiAnnotation import com.nhaarman.mockito_kotlin.mock import org.amshove.kluent.shouldBeEqualTo import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe object PostMappingSpek : Spek({ describe("PostMapping") { context("extractMethod") { it("should return POST") { val annotation = mock<PsiAnnotation> {} PostMapping(annotation).extractMethod() shouldBeEqualTo "POST" } } } })
src/test/kotlin/com/viartemev/requestmapper/annotations/spring/PostMappingSpek.kt
2125002846
package info.nightscout.androidaps.plugins.pump.danaR.comm import info.nightscout.androidaps.danar.comm.MsgHistoryNewDone import org.junit.Test import org.junit.runner.RunWith import org.powermock.modules.junit4.PowerMockRunner @RunWith(PowerMockRunner::class) class MsgHistoryNewDoneTest : DanaRTestBase() { @Test fun runTest() { val packet = MsgHistoryNewDone(injector) // nothing left to test } }
app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryNewDoneTest.kt
985939146
// "Convert to anonymous object" "true" interface I { fun foo(): String } fun test() { val i = <caret>I({ "" }) }
plugins/kotlin/idea/tests/testData/quickfix/convertToAnonymousObject/lambdaInParentheses.kt
2637593445
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.core.script.configuration.loader import com.intellij.openapi.vfs.VirtualFile import org.jetbrains.kotlin.idea.core.script.configuration.cache.ScriptConfigurationFileAttributeCache import org.jetbrains.kotlin.idea.core.script.configuration.cache.ScriptConfigurationSnapshot interface ScriptConfigurationLoadingContext { fun getCachedConfiguration(file: VirtualFile): ScriptConfigurationSnapshot? /** * Show notification about new configuration with suggestion to apply it. * User may disable this notifications, in this case [saveNewConfiguration] should be called * * If configuration is null, then the result will be treated as failed, and * reports will be displayed immediately. * * @sample DefaultScriptConfigurationLoader.loadDependencies */ fun suggestNewConfiguration( file: VirtualFile, newResult: ScriptConfigurationSnapshot ) /** * Save [newResult] for [file] into caches and update highlighting. * * @sample ScriptConfigurationFileAttributeCache.loadDependencies */ fun saveNewConfiguration( file: VirtualFile, newResult: ScriptConfigurationSnapshot ) }
plugins/kotlin/base/scripting/src/org/jetbrains/kotlin/idea/core/script/configuration/loader/ScriptConfigurationLoadingContext.kt
1832686192
// SET_TRUE: ALIGN_MULTILINE_EXTENDS_LIST enum class EnumTest { ENTRY(); <caret> } // WITHOUT_CUSTOM_LINE_INDENT_PROVIDER
plugins/kotlin/idea/tests/testData/indentationOnNewline/InEnumAfterSemicolon.kt
446071177
// HIGHLIGHT: INFORMATION // WITH_RUNTIME fun test(list: List<Int>): List<Int> { return list .filter<caret> { it > 1 } .map { it * 2 } .map { it * 3 } .map { it * 4 } }
plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/convertCallChainIntoSequence/simple2.kt
3259816075
// WITH_RUNTIME // PARAM_TYPES: kotlin.Int // PARAM_DESCRIPTOR: val z: kotlin.Int defined in test // SIBLING: fun test(): () -> Int { val z = 1 return { <selection>println(z) z + 1</selection> } } fun foo1(a: Int): Int { val t = println(a) return a + 1 } fun foo2(a: Int) { println(a) a + 1 }
plugins/kotlin/idea/tests/testData/refactoring/extractFunction/duplicates/outputValueAndUnitMatching.kt
2498201566
/* * Copyright (c) 2017. Rei Matsushita * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See * the License for the specific language governing permissions and limitations under the License. */ package me.rei_m.hbfavmaterial.viewmodel.widget.fragment import android.arch.lifecycle.ViewModel import android.arch.lifecycle.ViewModelProvider import android.databinding.Observable import android.databinding.ObservableArrayList import android.databinding.ObservableBoolean import android.view.View import android.widget.AbsListView import android.widget.AdapterView import io.reactivex.disposables.CompositeDisposable import io.reactivex.subjects.BehaviorSubject import io.reactivex.subjects.PublishSubject import me.rei_m.hbfavmaterial.constant.ReadAfterFilter import me.rei_m.hbfavmaterial.model.UserBookmarkModel import me.rei_m.hbfavmaterial.model.entity.Bookmark class OthersBookmarkFragmentViewModel(private val userBookmarkModel: UserBookmarkModel, private val bookmarkUserId: String) : ViewModel() { val bookmarkList: ObservableArrayList<Bookmark> = ObservableArrayList() val hasNextPage: ObservableBoolean = ObservableBoolean(false) val isVisibleEmpty: ObservableBoolean = ObservableBoolean(false) val isVisibleProgress: ObservableBoolean = ObservableBoolean(false) val isRefreshing: ObservableBoolean = ObservableBoolean(false) val isVisibleError: ObservableBoolean = ObservableBoolean(false) private var hasNextPageUpdatedEventSubject = BehaviorSubject.create<Boolean>() val hasNextPageUpdatedEvent: io.reactivex.Observable<Boolean> = hasNextPageUpdatedEventSubject private val onItemClickEventSubject = PublishSubject.create<Bookmark>() val onItemClickEvent: io.reactivex.Observable<Bookmark> = onItemClickEventSubject val onRaiseGetNextPageErrorEvent = userBookmarkModel.isRaisedGetNextPageError val onRaiseRefreshErrorEvent = userBookmarkModel.isRaisedRefreshError private val disposable: CompositeDisposable = CompositeDisposable() private val hasNextPageChangedCallback = object : Observable.OnPropertyChangedCallback() { override fun onPropertyChanged(sender: Observable?, propertyId: Int) { hasNextPageUpdatedEventSubject.onNext(hasNextPage.get()) } } init { disposable.addAll(userBookmarkModel.bookmarkList.subscribe { if (it.isEmpty()) { bookmarkList.clear() } else { bookmarkList.addAll(it - bookmarkList) } isVisibleEmpty.set(bookmarkList.isEmpty()) }, userBookmarkModel.hasNextPage.subscribe { hasNextPage.set(it) }, userBookmarkModel.isLoading.subscribe { isVisibleProgress.set(it) }, userBookmarkModel.isRefreshing.subscribe { isRefreshing.set(it) }, userBookmarkModel.isRaisedError.subscribe { isVisibleError.set(it) }) hasNextPage.addOnPropertyChangedCallback(hasNextPageChangedCallback) userBookmarkModel.getList(bookmarkUserId, ReadAfterFilter.ALL) } override fun onCleared() { hasNextPage.removeOnPropertyChangedCallback(hasNextPageChangedCallback) disposable.dispose() super.onCleared() } @Suppress("UNUSED_PARAMETER") fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { onItemClickEventSubject.onNext(bookmarkList[position]) } @Suppress("UNUSED_PARAMETER") fun onScroll(listView: AbsListView, firstVisibleItem: Int, visibleItemCount: Int, totalItemCount: Int) { if (0 < totalItemCount && totalItemCount == firstVisibleItem + visibleItemCount) { userBookmarkModel.getNextPage(bookmarkUserId) } } fun onRefresh() { userBookmarkModel.refreshList(bookmarkUserId) } class Factory(private val userBookmarkModel: UserBookmarkModel, private val userId: String) : ViewModelProvider.Factory { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel?> create(modelClass: Class<T>): T { if (modelClass.isAssignableFrom(OthersBookmarkFragmentViewModel::class.java)) { return OthersBookmarkFragmentViewModel(userBookmarkModel, userId) as T } throw IllegalArgumentException("Unknown class name") } } }
app/src/main/kotlin/me/rei_m/hbfavmaterial/viewmodel/widget/fragment/OthersBookmarkFragmentViewModel.kt
801651836
// "Add getter and setter" "true" // WITH_RUNTIME class Test { var x: Int<caret> }
plugins/kotlin/idea/tests/testData/quickfix/addPropertyAccessors/var.kt
1209957744
package torille.fi.lurkforreddit.comments import android.content.Intent import android.net.Uri import android.os.Bundle import android.support.v4.content.ContextCompat import android.support.v7.widget.LinearLayoutManager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import dagger.android.support.DaggerFragment import kotlinx.android.synthetic.main.fragment_comments.* import timber.log.Timber import torille.fi.lurkforreddit.R import torille.fi.lurkforreddit.data.models.view.Comment import torille.fi.lurkforreddit.data.models.view.Post import torille.fi.lurkforreddit.utils.AppLinkActivity import javax.inject.Inject class CommentFragment @Inject constructor() : DaggerFragment(), CommentContract.View { @Inject internal lateinit var post: Post @Inject internal lateinit var actionsListener: CommentContract.Presenter @Inject @JvmField var singleCommentThread: Boolean = false private lateinit var commentAdapter: CommentRecyclerViewAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) commentAdapter = CommentRecyclerViewAdapter( mutableListOf(post), clickListener, ContextCompat.getColor(context!!, R.color.colorAccent) ) } override fun onResume() { super.onResume() actionsListener.takeView(this) } override fun onDestroy() { super.onDestroy() actionsListener.dropView() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_comments, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) context?.let { context -> commentRecyclerView.setHasFixedSize(true) commentRecyclerView.addItemDecoration( CommentsItemDecoration( ContextCompat.getDrawable( context, R.drawable.comment_item_decorator )!! ) ) commentRecyclerView.layoutManager = LinearLayoutManager(context) commentRecyclerView.adapter = commentAdapter refreshLayout.setColorSchemeColors( ContextCompat.getColor(context, R.color.colorPrimary), ContextCompat.getColor(context, R.color.colorAccent), ContextCompat.getColor(context, R.color.colorPrimaryDark) ) refreshLayout.setOnRefreshListener { actionsListener.loadComments( post.permaLink, singleCommentThread ) } } } override fun showComments(comments: List<Any>) { commentAdapter.replaceData(comments) } override fun showProgressbarAt(position: Int, level: Int) { commentAdapter.addProgressbar(position, level) } override fun hideProgressbarAt(position: Int) { commentAdapter.removeAt(position) } override fun addCommentsAt(comments: List<Comment>, position: Int) { if (!comments.isEmpty()) { commentAdapter.addAllCommentsTo(position, comments) } } override fun showError(errorText: String) { Toast.makeText(context, errorText, Toast.LENGTH_SHORT).show() } override fun showErrorAt(position: Int) { commentAdapter.changeToErrorAt(position) } override fun setProgressIndicator(active: Boolean) { refreshLayout?.post { refreshLayout.isRefreshing = active } } /** * Listener for clicks on notes in the RecyclerView. */ private val clickListener = object : CommentClickListener { override fun onClick(parentComment: Comment, linkId: String, position: Int) { actionsListener.loadMoreCommentsAt(parentComment, linkId, position) } override fun onContinueThreadClick(permaLinkurl: String) { Timber.d("Opening comments for $permaLinkurl") val intent = Intent(context, AppLinkActivity::class.java) intent.data = Uri.parse(permaLinkurl) startActivity(intent) } } internal interface CommentClickListener { fun onClick(parentComment: Comment, linkId: String, position: Int) fun onContinueThreadClick(permaLinkurl: String) } }
app/src/main/java/torille/fi/lurkforreddit/comments/CommentFragment.kt
1931954775
// "Add 'return' to last expression" "false" // WITH_RUNTIME // ACTION: Introduce local variable // ACTION: Remove explicitly specified return type of enclosing function 'some' // ERROR: A 'return' expression required in a function with a block body ('{...}') // ERROR: Unresolved reference: FunctionReference fun some(): Any { FunctionReference::class }<caret>
plugins/kotlin/idea/tests/testData/quickfix/addReturnToLastExpressionInFunction/typeError2.kt
1355195602
import library.sample.pairAdd fun foo() { val p = Pair(10, 20) val x = pairAdd(p) println("x=$x") }
plugins/kotlin/jps/jps-plugin/tests/testData/general/KotlinJavaScriptProjectWithLibraryNoCopy/src/test1.kt
3027501925
package com.mounacheikhna.nearby.ui import android.content.Context import android.support.design.widget.FloatingActionButton import android.support.v4.view.ViewCompat import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import android.widget.Checkable import android.widget.ImageButton import android.widget.LinearLayout import com.mounacheikhna.nearby.R /** * A {@link Checkable} {@link FloatingActionButton} that toggle its state. */ class CheckableFab: FloatingActionButton, Checkable { private var isChecked = false private var minOffset: Int = 0 public constructor(context: Context) : super(context) { init(); } public constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { init(); } public constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { init(); } private fun init() { setOnClickListener({ toggle() }) } fun setOffset(offset: Int) { var offset = offset offset = Math.max(minOffset, offset) if (translationY != offset.toFloat()) { translationY = offset.toFloat() ViewCompat.postInvalidateOnAnimation(this) } } fun setMinOffset(minOffset: Int) { this.minOffset = minOffset } override fun isChecked(): Boolean { return isChecked } override fun setChecked(isChecked: Boolean) { if (this.isChecked != isChecked) { this.isChecked = isChecked refreshDrawableState() } } override fun toggle() { setChecked(!isChecked) jumpDrawablesToCurrentState() } override fun onCreateDrawableState(extraSpace: Int): IntArray { val drawableState = super.onCreateDrawableState(extraSpace + 1) if (isChecked()) { View.mergeDrawableStates(drawableState, CHECKED_STATE_SET) } return drawableState } companion object { private val CHECKED_STATE_SET = intArrayOf(android.R.attr.state_checked) } }
app/src/main/kotlin/com/mounacheikhna/nearby/ui/CheckableFab.kt
3357433051
fun some() { do<caret> { } while (true) }
plugins/kotlin/idea/tests/testData/indentationOnNewline/controlFlowConstructions/DoWithBraces.kt
3452087366
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.asJava import com.intellij.psi.JavaPsiFacade import com.intellij.psi.search.GlobalSearchScope import com.intellij.testFramework.LightProjectDescriptor import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase import org.jetbrains.kotlin.idea.test.KotlinLightProjectDescriptor import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.KtFile import org.junit.Assert import org.junit.internal.runners.JUnit38ClassRunner import org.junit.runner.RunWith @RunWith(JUnit38ClassRunner::class) class KotlinLightClassInheritorTest : KotlinLightCodeInsightFixtureTestCase() { fun testAnnotation() { doTestInheritorByText("annotation class A", "java.lang.annotation.Annotation", false) } fun testEnum() { doTestInheritorByText("enum class A", "java.lang.Enum", false) } fun testIterable() { doTestInheritorByText("abstract class A<T> : Iterable<T>", "java.lang.Iterable", false) } fun testIterableDeep() { doTestInheritorByText("abstract class A<T> : List<T>", "java.lang.Iterable", true) } fun testObjectDeep() { doTestInheritorByText("abstract class A<T> : List<T>", "java.lang.Object", true) } fun testClassOnSelfDeep() { doTestInheritorByText("class A", "A", checkDeep = true, result = false) } private fun doTestInheritorByText(text: String, superQName: String, checkDeep: Boolean, result: Boolean = true) { val file = myFixture.configureByText("A.kt", text) as KtFile val ktClass = file.declarations.filterIsInstance<KtClass>().single() val psiClass = KotlinAsJavaSupport.getInstance(project).getLightClass(ktClass)!! val baseClass = JavaPsiFacade.getInstance(project).findClass(superQName, GlobalSearchScope.allScope(project))!! Assert.assertEquals(psiClass.isInheritor(baseClass, checkDeep), result) } override fun getProjectDescriptor(): LightProjectDescriptor = KotlinLightProjectDescriptor.INSTANCE }
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/asJava/KotlinLightClassInheritorTest.kt
2968123847
package com.github.kerubistan.kerub.utils.junix.packagemanager.zypper import com.github.kerubistan.kerub.host.execute import org.apache.sshd.client.session.ClientSession object Zypper { fun installPackage(session: ClientSession, vararg packs: String) { require(packs.isNotEmpty()) session.execute("zypper -n install ${packs.joinToString(separator = " ")}") } fun uninstallPackage(session: ClientSession, vararg packs: String) { require(packs.isNotEmpty()) session.execute("zypper -n remove ${packs.joinToString(separator = " ")}") } }
src/main/kotlin/com/github/kerubistan/kerub/utils/junix/packagemanager/zypper/Zypper.kt
940224218
package vgrechka.spew import vgrechka.* //object SpewForDBStuff { // @JvmStatic // fun main(args: Array<String>) { // spewForInputFiles(listOf("%FE%/db-stuff/src/db-stuff.kt")) // clog("OK") // } //} // //object SpewForAlrauneEntities { // @JvmStatic // fun main(args: Array<String>) { // GlobalSpewContext.opts = SpewForInputFileOptions(annotations = false) // spewForInputFiles(listOf("%FE%/alraune/alraune-back/src/alraune-entities.kt")) // clog("OK") // } //}
1/spew/src/main/java/spew-run-configs-1.kt
562275898
package alraune import alraune.entity.* import pieces100.* import vgrechka.* import kotlin.math.max class OoWriterBiddingOrderDetailsPage { companion object { val path = "/bidding-order-details" val conversationTabId = "Conversation" fun href(orderId: Long) = hrefThunk(orderId).makeHref() fun hrefThunk(orderId: Long) = HrefThunk(path) { it.longId.set(orderId) } } val c = AlCSS.fartus1 val getParams = GetParams() val order = dbSelectOrderOrBailOut(getParamOrBailOut(getParams.longId)) init {init()} fun init() { val titlePrefix = t("TOTE", "Пиздоторги: ") btfDocumentTitle(titlePrefix + t("TOTE", "Заказ ${AlText.numString(order.id)}")) if (order.state != Order.State.LookingForWriters) { oo(div("По этому заказу торгов (уже) нет")) return } Context1.get().withProjectStuff({it.copy( composeOrderParams_showCustomerInfo = false)}) { val ovb = OrderViewBoobs(order) ovb.ooTitle(prefix = titlePrefix) oo(composeBidBanner()) ovb.ooTabs(hrefThunk(order.id)) { it.tabs += Tabopezdal.Tab(conversationTabId, t("TOTE", "Общение"), ooContent = { ooApplicantConversation(order, rctx0.al.user) } ) } } btfStartStalenessWatcher() } fun composeBidBanner(): Renderable { // ce82cbc6-a172-41d4-823b-2b5a754b8583 val state = order.computeUserBiddingState(rctx0.al.user) val money = state?.money return !ComposeActionBanner() .message(div().with { if (money == null) oo(div() .add("Принимаем заявки: ") .add(span( displayMoney(order.data.bidding!!.minWriterMoney) + " " + AlText0.endash + " " + displayMoney(order.data.bidding!!.maxWriterMoney)).style("font-weight: bold;")) .add(" Желаешь запрячься?")) else oo(div() .add("Ты хочешь сделать это за ") .add(span(displayMoney(money)).style("font-weight: bold;"))) }) .backgroundColor(Color.Gray200) .leftBorderColor(Color.Gray500) .accept { it.buttonBarWithTicker.addOpenFormModalButton( title = "Задать вопрос", level = AlButtonStyle.Default, modalWithScripts = bakeModal2(order.toHandle())) it.buttonBarWithTicker.addOpenFormModalButton( title = if (money == null) "Предложить цену" else "Изменить цену", level = AlButtonStyle.Success, modalWithScripts = bakeModal3(order.toHandle())) if (money != null) { it.buttonBarWithTicker.addOpenFormModalButton( title = "Передумал делать", level = AlButtonStyle.Danger, modalWithScripts = bakeModal4(order.toHandle())) } } } } fun doCommentDuringBidding(toUser: User? = null, orderHandle: OrderHandle, fs: CommentFields) { updateOrderSimple(orderHandle, ::new_Order_Operation_CommentDuringBidding) { it.order.data.biddingActions.add(new_Order_BiddingAction( kind = Order.BiddingAction.Kind.Comment, userId = rctx0.al.user.id, commentRecipientId = toUser?.id, time = it.now, money = null, comment = fs.comment.value(), isCancelation = false)) } } fun doBid(orderHandle: OrderHandle, fs: BidFields) { updateOrderSimple(orderHandle, ::new_Order_Operation_Bid) { it.order.data.biddingActions.add(new_Order_BiddingAction( kind = Order.BiddingAction.Kind.Bid, userId = rctx0.al.user.id, commentRecipientId = null, time = it.now, money = fs.money.value().toInt(), comment = fs.comment.value(), isCancelation = false)) } } fun doCancelBid(orderHandle: OrderHandle, fs: CommentFields) { updateOrderSimple(orderHandle, ::new_Order_Operation_CancelBid) { it.order.data.biddingActions.add(new_Order_BiddingAction( kind = Order.BiddingAction.Kind.Cancel, userId = rctx0.al.user.id, commentRecipientId = null, time = it.now, money = null, comment = fs.comment.value(), isCancelation = true)) } } fun ooApplicantConversation(order: Order, applicant: User) { val pageSize = AlConst.pageSize var bids = order.data.biddingActions.filter {it.userId == applicant.id || it.commentRecipientId == applicant.id} if (GetParams().ordering.get() == Ordering.NewerFirst) bids = bids.reversed() oo(dance(object : ComposePaginatedShit<Order.BiddingAction>( object : PaginationPussy<Order.BiddingAction> { override fun pageSize() = pageSize override fun selectItems(offset: Long): List<Order.BiddingAction> { val fromIndex = Math.toIntExact(offset) val toIndex = Math.toIntExact(offset + pageSize) val size = bids.size return bids.subList(clamp(fromIndex, 0, max(size - 1, 0)), clamp(toIndex, 0, size)) } override fun count() = bids.size.toLong() }) { override fun initShitGivenItems(items: List<Order.BiddingAction>) {} override fun renderItem(item: Order.BiddingAction, index: Int): AlTag { val sender = rctx0.al.dbCache.user(item.userId) val iconWithStyle = Iconography.iconWithStyle(sender) return div().with { ooItemTitle( iconWithStyle = iconWithStyle, title = sender.fullNameOrEmail() + ": " + when { item.isCancelation -> t("TOTE", "Отмена") item.money == null -> t("TOTE", "Комментарий") else -> t("TOTE", "Заявка") }, tinySubtitle = TimePile.kievTimeString(item.time), afterTinySubtitle = { if (item.isCancelation) oo(composeRedBombForItemTitle()) }, buildDropdown = {}, amendTitleBarDiv = {gimmeName1(index, it, iconWithStyle)}) oo(div().style("position: relative;").with { oo(div().style("position: absolute; right: 0px; top: 0px;").with { }) // 0fe1d8cd-73a5-4780-b37c-8f6161c29eb0 item.money?.let {m-> oo(div().style("font-weight: bold; text-decoration: underline; margin-bottom: 0.5em;") .add(FA.dollar().appendStyle("margin-right: 0.5em;")) .add("Деньги: $m грн.")) } oo(composePreWrapDiv(item.comment)) }) } } override fun makePageHref(pageFrom1: Int) = defaultPaginationPageHref(pageFrom1) })) } fun gimmeName1(index: Int, tag: AlTag, iconWithStyle: FAIconWithStyle) { if (index > 0) tag.appendClassName(iconWithStyle.nonFirstItemClass) } //fun ooApplicantConversation_killme(order: Order, applicant: User) { // oo(!object : OoUsualPaginatedShit<Bid>( // itemClass = Bid::class, table = Bid.Meta.table, // notDeleted = false) { // // override fun composeItem(item: Bid): AlTag { // val sender = rctx.dbCache.user(item.userId) // val iconWithStyle = Iconography.iconWithStyle(sender) // return div().className(iconWithStyle.spacer).with { // ooItemTitle( // iconWithStyle = iconWithStyle, // title = sender.fullNameOrEmail() + ": " + // when { // item.data.isCancelation -> t("TOTE", "Отмена") // item.money == null -> t("TOTE", "Комментарий") // else -> t("TOTE", "Заявка") // }, // tinySubtitle = AlText.numString(item.id) + ", " + TimePile.kievTimeString(item.time), // afterTinySubtitle = { // if (item.data.isCancelation) // oo(composeRedBombForItemTitle()) // }, // buildDropdown = {}) // // oo(div().style("position: relative;").with { // oo(div().style("position: absolute; right: 0px; top: 0px;").with { // }) // // // 0fe1d8cd-73a5-4780-b37c-8f6161c29eb0 // item.money?.let {m-> // oo(div().style("font-weight: bold; text-decoration: underline; margin-bottom: 0.5em;") // .add(FA.dollar().appendStyle("margin-right: 0.5em;")) // .add("Деньги: $m грн.")) // } // // oo(composePreWrapDiv(item.data.comment)) // }) // } // } // // override fun shitIntoWhere(q: AlQueryBuilder) { // q.text("and ${Bid.Meta.orderId} =", order.id) // q.text("and (${Bid.Meta.userId} =", applicant.id) // q.text(" or ${Bid.Meta.commentRecipientId} =", applicant.id) // q.text(" )") // } // }) //} fun bakeModal2(orderHandle: OrderHandle): ShitWithContext<ModalShit, Context1> { return !object : Kate<CommentFields>( modalTitle = t("TOTE", "Вопрос"), submitButtonTitle = t("TOTE", "Запостить"), submitButtonLevel = AlButtonStyle.Primary) { override fun setInitialFields(fs: CommentFields) {} override fun serveGivenValidFields(fs: CommentFields) { doCommentDuringBidding(toUser = null, orderHandle = orderHandle, fs = fs) reloadToConversationTab(orderHandle.id) } override fun makeFields() = CommentFields() override fun ooModalBody(fs: CommentFields) { oo(fs.comment.begin().focused().compose()) } } } fun reloadToConversationTab(orderId: Long) { btfEval(jsProgressyNavigate(OoWriterBiddingOrderDetailsPage.hrefThunk(orderId).makeHref { it.tab.set(OoWriterBiddingOrderDetailsPage.conversationTabId) }, replaceState = true)) } fun bakeModal3(orderHandle: OrderHandle): ShitWithContext<ModalShit, Context1> { return !object : Kate<BidFields>( modalTitle = t("TOTE", "Заявка"), submitButtonTitle = t("TOTE", "Хочу"), submitButtonLevel = AlButtonStyle.Primary) { override fun setInitialFields(fs: BidFields) { fs.comment.set("Без блядских комментариев") } override fun serveGivenValidFields(fs: BidFields) { doBid(orderHandle, fs) reloadToConversationTab(orderHandle.id) } override fun makeFields() = BidFields(orderHandle.id) override fun ooModalBody(fs: BidFields) { oo(fs.money.begin().focused().compose()) oo(fs.comment.begin().compose()) } } } fun bakeModal4(orderHandle: OrderHandle): ShitWithContext<ModalShit, Context1> { return !object : Kate<CommentFields>( modalTitle = t("TOTE", "Отмена заявки"), submitButtonTitle = t("TOTE", "Не хочу работать"), submitButtonLevel = AlButtonStyle.Danger) { override fun decorateModal(it: ComposeModalContent) {it.redLeftMargin()} override fun setInitialFields(fs: CommentFields) { fs.comment.set("Я ленивый засранец") } override fun serveGivenValidFields(fs: CommentFields) { doCancelBid(orderHandle, fs) reloadToConversationTab(orderHandle.id) } override fun makeFields() = CommentFields() override fun ooModalBody(fs: CommentFields) { oo(fs.comment.begin().focused().compose()) } } }
alraune/alraune/src/main/java/alraune/OoWriterBiddingOrderDetailsPage.kt
3838159762
package org.penella.query import org.penella.structures.triples.Triple import java.util.* /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Created by alisle on 11/1/16. */ class Query(val outputs : Array<String>, val variables : Array<String>, val triples : Array<Triple>) { override fun equals(other: Any?): Boolean { if(other !is Query) { return false } val otherQuery : Query = other if(!Arrays.equals(outputs, otherQuery.outputs)) { return false } if(!Arrays.equals(variables, otherQuery.variables)) { return false } if(!Arrays.equals(triples, otherQuery.triples)) { return false } return true } }
src/main/java/org/penella/query/Query.kt
4097945102
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.j2k.ast import org.jetbrains.kotlin.j2k.CodeBuilder import org.jetbrains.kotlin.j2k.append abstract class Statement : Element() { object Empty : Statement() { override fun generateCode(builder: CodeBuilder) { } override val isEmpty: Boolean get() = true } } class DeclarationStatement(val elements: List<Element>) : Statement() { override fun generateCode(builder: CodeBuilder) { builder.append(elements, "\n") } } class ExpressionListStatement(val expressions: List<Expression>) : Expression() { override fun generateCode(builder: CodeBuilder) { builder.append(expressions, "\n") } } class LabeledStatement(val name: Identifier, val statement: Element) : Statement() { override fun generateCode(builder: CodeBuilder) { builder append name append "@" append " " append statement } } class ReturnStatement(val expression: Expression, val label: Identifier? = null) : Statement() { override fun generateCode(builder: CodeBuilder) { builder append "return" if (label != null) { builder append "@" append label } builder append " " append expression } } class IfStatement( val condition: Expression, val thenStatement: Element, val elseStatement: Element, singleLine: Boolean ) : Expression() { private val br = if (singleLine) " " else "\n" private val brAfterElse = if (singleLine || elseStatement is IfStatement) " " else "\n" override fun generateCode(builder: CodeBuilder) { builder append "if (" append condition append ")" append br append thenStatement.wrapToBlockIfRequired() if (!elseStatement.isEmpty) { builder append br append "else" append brAfterElse append elseStatement.wrapToBlockIfRequired() } else if (thenStatement.isEmpty) { builder append ";" } } } // Loops -------------------------------------------------------------------------------------------------- class WhileStatement(val condition: Expression, val body: Element, singleLine: Boolean) : Statement() { private val br = if (singleLine) " " else "\n" override fun generateCode(builder: CodeBuilder) { builder append "while (" append condition append ")" append br append body.wrapToBlockIfRequired() if (body.isEmpty) { builder append ";" } } } class DoWhileStatement(val condition: Expression, val body: Element, singleLine: Boolean) : Statement() { private val br = if (singleLine) " " else "\n" override fun generateCode(builder: CodeBuilder) { builder append "do" append br append body.wrapToBlockIfRequired() append br append "while (" append condition append ")" } } class ForeachStatement( val variableName: Identifier, val explicitVariableType: Type?, val collection: Expression, val body: Element, singleLine: Boolean ) : Statement() { private val br = if (singleLine) " " else "\n" override fun generateCode(builder: CodeBuilder) { builder append "for (" append variableName if (explicitVariableType != null) { builder append ":" append explicitVariableType } builder append " in " append collection append ")" append br append body.wrapToBlockIfRequired() if (body.isEmpty) { builder append ";" } } } class BreakStatement(val label: Identifier = Identifier.Empty) : Statement() { override fun generateCode(builder: CodeBuilder) { builder.append("break").appendWithPrefix(label, "@") } } class ContinueStatement(val label: Identifier = Identifier.Empty) : Statement() { override fun generateCode(builder: CodeBuilder) { builder.append("continue").appendWithPrefix(label, "@") } } // Exceptions ---------------------------------------------------------------------------------------------- class TryStatement(val block: Block, val catches: List<CatchStatement>, val finallyBlock: Block) : Statement() { override fun generateCode(builder: CodeBuilder) { builder.append("try\n").append(block).append("\n").append(catches, "\n").append("\n") if (!finallyBlock.isEmpty) { builder append "finally\n" append finallyBlock } } } class ThrowStatement(val expression: Expression) : Expression() { override fun generateCode(builder: CodeBuilder) { builder append "throw " append expression } } class CatchStatement(val variable: FunctionParameter, val block: Block) : Statement() { override fun generateCode(builder: CodeBuilder) { builder append "catch (" append variable append ") " append block } } // when -------------------------------------------------------------------------------------------------- class WhenStatement(val subject: Expression, val caseContainers: List<WhenEntry>) : Statement() { override fun generateCode(builder: CodeBuilder) { builder.append("when (").append(subject).append(") {\n").append(caseContainers, "\n").append("\n}") } } class WhenEntry(val selectors: List<WhenEntrySelector>, val body: Statement) : Statement() { override fun generateCode(builder: CodeBuilder) { builder.append(selectors, ", ").append(" -> ").append(body) } } abstract class WhenEntrySelector : Statement() class ValueWhenEntrySelector(val expression: Expression) : WhenEntrySelector() { override fun generateCode(builder: CodeBuilder) { builder.append(expression) } } class ElseWhenEntrySelector : WhenEntrySelector() { override fun generateCode(builder: CodeBuilder) { builder.append("else") } } // Other ------------------------------------------------------------------------------------------------------ class SynchronizedStatement(val expression: Expression, val block: Block) : Statement() { override fun generateCode(builder: CodeBuilder) { builder append "synchronized (" append expression append ") " append block } }
plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/ast/Statements.kt
2523995680
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.slicer import com.intellij.openapi.project.Project import com.intellij.psi.PsiComment import com.intellij.psi.PsiElement import com.intellij.psi.PsiMethod import com.intellij.psi.search.SearchScope import com.intellij.psi.util.parentOfType import com.intellij.slicer.JavaSliceUsage import com.intellij.slicer.SliceUsage import com.intellij.usageView.UsageInfo import com.intellij.util.Processor import org.jetbrains.kotlin.asJava.namedUnwrappedElement import org.jetbrains.kotlin.cfg.pseudocode.PseudoValue import org.jetbrains.kotlin.cfg.pseudocode.Pseudocode import org.jetbrains.kotlin.cfg.containingDeclarationForPseudocode import org.jetbrains.kotlin.cfg.pseudocode.getContainingPseudocode import org.jetbrains.kotlin.cfg.pseudocode.instructions.KtElementInstruction import org.jetbrains.kotlin.cfg.pseudocode.instructions.eval.* import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.base.psi.hasInlineModifier import org.jetbrains.kotlin.idea.base.searching.usages.KotlinFunctionFindUsagesOptions import org.jetbrains.kotlin.idea.base.searching.usages.KotlinPropertyFindUsagesOptions import org.jetbrains.kotlin.idea.base.searching.usages.processAllExactUsages import org.jetbrains.kotlin.idea.base.searching.usages.processAllUsages import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde import org.jetbrains.kotlin.idea.core.getDeepestSuperDeclarations import org.jetbrains.kotlin.idea.search.declarationsSearch.HierarchySearchRequest import org.jetbrains.kotlin.idea.search.declarationsSearch.searchOverriders import org.jetbrains.kotlin.idea.util.actualsForExpected import org.jetbrains.kotlin.idea.util.expectedDescriptor import org.jetbrains.kotlin.idea.util.isExpectDeclaration import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.contains import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.parents import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue import org.jetbrains.kotlin.resolve.source.getPsi import org.jetbrains.kotlin.util.OperatorNameConventions import org.jetbrains.kotlin.utils.addIfNotNull abstract class Slicer( protected val element: KtElement, protected val processor: Processor<in SliceUsage>, protected val parentUsage: KotlinSliceUsage ) { abstract fun processChildren(forcedExpressionMode: Boolean) protected val analysisScope: SearchScope = parentUsage.scope.toSearchScope() protected val mode: KotlinSliceAnalysisMode = parentUsage.mode protected val project = element.project protected class PseudocodeCache { private val computedPseudocodes = HashMap<KtElement, Pseudocode>() operator fun get(element: KtElement): Pseudocode? { val container = element.containingDeclarationForPseudocode ?: return null return computedPseudocodes.getOrPut(container) { container.getContainingPseudocode(container.analyzeWithContent())?.apply { computedPseudocodes[container] = this } ?: return null } } } protected val pseudocodeCache = PseudocodeCache() protected fun PsiElement.passToProcessor(mode: KotlinSliceAnalysisMode = [email protected]) { processor.process(KotlinSliceUsage(this, parentUsage, mode, false)) } protected fun PsiElement.passToProcessorAsValue(mode: KotlinSliceAnalysisMode = [email protected]) { processor.process(KotlinSliceUsage(this, parentUsage, mode, forcedExpressionMode = true)) } protected fun PsiElement.passToProcessorInCallMode( callElement: KtElement, mode: KotlinSliceAnalysisMode = [email protected], withOverriders: Boolean = false ) { val newMode = when (this) { is KtNamedFunction -> this.callMode(callElement, mode) is KtParameter -> ownerFunction.callMode(callElement, mode) is KtTypeReference -> { val declaration = parent require(declaration is KtCallableDeclaration) require(this == declaration.receiverTypeReference) declaration.callMode(callElement, mode) } else -> mode } if (withOverriders) { passDeclarationToProcessorWithOverriders(newMode) } else { passToProcessor(newMode) } } protected fun PsiElement.passDeclarationToProcessorWithOverriders(mode: KotlinSliceAnalysisMode = [email protected]) { passToProcessor(mode) HierarchySearchRequest(this, analysisScope) .searchOverriders() .forEach { it.namedUnwrappedElement?.passToProcessor(mode) } if (this is KtCallableDeclaration && isExpectDeclaration()) { resolveToDescriptorIfAny() ?.actualsForExpected() ?.forEach { (it as? DeclarationDescriptorWithSource)?.toPsi()?.passToProcessor(mode) } } } protected open fun processCalls( callable: KtCallableDeclaration, includeOverriders: Boolean, sliceProducer: SliceProducer, ) { if (callable is KtFunctionLiteral || callable is KtFunction && callable.name == null) { callable.passToProcessorAsValue(mode.withBehaviour(LambdaCallsBehaviour(sliceProducer))) return } val options = when (callable) { is KtFunction -> { KotlinFunctionFindUsagesOptions(project).apply { isSearchForTextOccurrences = false isSkipImportStatements = true searchScope = analysisScope } } is KtProperty -> { KotlinPropertyFindUsagesOptions(project).apply { isSearchForTextOccurrences = false isSkipImportStatements = true searchScope = analysisScope } } else -> return } val descriptor = callable.resolveToDescriptorIfAny() as? CallableMemberDescriptor ?: return val superDescriptors = if (includeOverriders) { descriptor.getDeepestSuperDeclarations() } else { mutableListOf<CallableMemberDescriptor>().apply { add(descriptor) addAll(DescriptorUtils.getAllOverriddenDeclarations(descriptor)) if (descriptor.isActual) { addIfNotNull(descriptor.expectedDescriptor() as CallableMemberDescriptor?) } } } for (superDescriptor in superDescriptors) { val declaration = superDescriptor.toPsi() ?: continue when (declaration) { is KtDeclaration -> { val usageProcessor: (UsageInfo) -> Unit = processor@{ usageInfo -> val element = usageInfo.element ?: return@processor if (element.parentOfType<PsiComment>() != null) return@processor val sliceUsage = KotlinSliceUsage(element, parentUsage, mode, false) sliceProducer.produceAndProcess(sliceUsage, mode, parentUsage, processor) } if (includeOverriders) { declaration.processAllUsages(options, usageProcessor) } else { declaration.processAllExactUsages(options, usageProcessor) } } is PsiMethod -> { val sliceUsage = JavaSliceUsage.createRootUsage(declaration, parentUsage.params) sliceProducer.produceAndProcess(sliceUsage, mode, parentUsage, processor) } else -> { val sliceUsage = KotlinSliceUsage(declaration, parentUsage, mode, false) sliceProducer.produceAndProcess(sliceUsage, mode, parentUsage, processor) } } } } protected enum class AccessKind { READ_ONLY, WRITE_ONLY, WRITE_WITH_OPTIONAL_READ, READ_OR_WRITE } protected fun processVariableAccesses( declaration: KtCallableDeclaration, scope: SearchScope, kind: AccessKind, usageProcessor: (UsageInfo) -> Unit ) { val options = KotlinPropertyFindUsagesOptions(project).apply { isReadAccess = kind == AccessKind.READ_ONLY || kind == AccessKind.READ_OR_WRITE isWriteAccess = kind == AccessKind.WRITE_ONLY || kind == AccessKind.WRITE_WITH_OPTIONAL_READ || kind == AccessKind.READ_OR_WRITE isReadWriteAccess = kind == AccessKind.WRITE_WITH_OPTIONAL_READ || kind == AccessKind.READ_OR_WRITE isSearchForTextOccurrences = false isSkipImportStatements = true searchScope = scope } val allDeclarations = mutableListOf(declaration) val descriptor = declaration.resolveToDescriptorIfAny() if (descriptor is CallableMemberDescriptor) { val additionalDescriptors = if (descriptor.isActual) { listOfNotNull(descriptor.expectedDescriptor() as? CallableMemberDescriptor) } else { DescriptorUtils.getAllOverriddenDeclarations(descriptor) } additionalDescriptors.mapNotNullTo(allDeclarations) { it.toPsi() as? KtCallableDeclaration } } allDeclarations.forEach { it.processAllExactUsages(options) { usageInfo -> if (!shouldIgnoreVariableUsage(usageInfo)) { usageProcessor.invoke(usageInfo) } } } } // ignore parameter usages in function contract private fun shouldIgnoreVariableUsage(usage: UsageInfo): Boolean { val element = usage.element ?: return true return element.parents.any { it is KtCallExpression && (it.calleeExpression as? KtSimpleNameExpression)?.getReferencedName() == "contract" && it.resolveToCall()?.resultingDescriptor?.fqNameOrNull()?.asString() == "kotlin.contracts.contract" } } protected fun canProcessParameter(parameter: KtParameter) = !parameter.isVarArg protected fun processExtensionReceiverUsages( declaration: KtCallableDeclaration, body: KtExpression?, mode: KotlinSliceAnalysisMode, ) { if (body == null) return //TODO: overriders val resolutionFacade = declaration.getResolutionFacade() val callableDescriptor = declaration.resolveToDescriptorIfAny(resolutionFacade) as? CallableDescriptor ?: return val extensionReceiver = callableDescriptor.extensionReceiverParameter ?: return body.forEachDescendantOfType<KtThisExpression> { thisExpression -> val receiverDescriptor = thisExpression.resolveToCall(resolutionFacade)?.resultingDescriptor if (receiverDescriptor == extensionReceiver) { thisExpression.passToProcessor(mode) } } // process implicit receiver usages val pseudocode = pseudocodeCache[body] if (pseudocode != null) { for (instruction in pseudocode.instructions) { if (instruction is MagicInstruction && instruction.kind == MagicKind.IMPLICIT_RECEIVER) { val receiverPseudoValue = instruction.outputValue pseudocode.getUsages(receiverPseudoValue).forEach { receiverUseInstruction -> if (receiverUseInstruction is KtElementInstruction) { receiverPseudoValue.processIfReceiverValue( receiverUseInstruction, mode, filter = { receiverValue, resolvedCall -> receiverValue == resolvedCall.extensionReceiver && (receiverValue as? ImplicitReceiver)?.declarationDescriptor == callableDescriptor } ) } } } } } } protected fun PseudoValue.processIfReceiverValue( instruction: KtElementInstruction, mode: KotlinSliceAnalysisMode, filter: (ReceiverValue, ResolvedCall<out CallableDescriptor>) -> Boolean = { _, _ -> true } ): Boolean { val receiverValue = (instruction as? InstructionWithReceivers)?.receiverValues?.get(this) ?: return false val resolvedCall = instruction.element.resolveToCall() ?: return true if (!filter(receiverValue, resolvedCall)) return true val descriptor = resolvedCall.resultingDescriptor if (descriptor.isImplicitInvokeFunction()) { when (receiverValue) { resolvedCall.dispatchReceiver -> { if (mode.currentBehaviour is LambdaCallsBehaviour) { instruction.element.passToProcessor(mode) } } resolvedCall.extensionReceiver -> { val dispatchReceiver = resolvedCall.dispatchReceiver ?: return true val dispatchReceiverPseudoValue = instruction.receiverValues.entries .singleOrNull { it.value == dispatchReceiver }?.key ?: return true val createdAt = dispatchReceiverPseudoValue.createdAt val accessedDescriptor = (createdAt as ReadValueInstruction?)?.target?.accessedDescriptor if (accessedDescriptor is VariableDescriptor) { accessedDescriptor.toPsi()?.passToProcessor(mode.withBehaviour(LambdaReceiverInflowBehaviour)) } } } } else { if (receiverValue == resolvedCall.extensionReceiver) { (descriptor.toPsi() as? KtCallableDeclaration)?.receiverTypeReference ?.passToProcessorInCallMode(instruction.element, mode) } } return true } protected fun DeclarationDescriptor.toPsi(): PsiElement? { return descriptorToPsi(this, project, analysisScope) } companion object { protected fun KtDeclaration?.callMode(callElement: KtElement, defaultMode: KotlinSliceAnalysisMode): KotlinSliceAnalysisMode { return if (this is KtNamedFunction && hasInlineModifier()) defaultMode.withInlineFunctionCall(callElement, this) else defaultMode } fun descriptorToPsi(descriptor: DeclarationDescriptor, project: Project, analysisScope: SearchScope): PsiElement? { val declaration = DescriptorToSourceUtilsIde.getAnyDeclaration(project, descriptor) ?: return null if (analysisScope.contains(declaration)) return declaration.navigationElement // we ignore access scope for inline declarations val isInline = when (declaration) { is KtNamedFunction -> declaration.hasInlineModifier() is KtParameter -> declaration.ownerFunction?.hasInlineModifier() == true else -> false } return if (isInline) declaration.navigationElement else null } } } fun CallableDescriptor.isImplicitInvokeFunction(): Boolean { if (this !is FunctionDescriptor) return false if (!isOperator) return false if (name != OperatorNameConventions.INVOKE) return false return source.getPsi() == null }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/slicer/Slicer.kt
3388899469
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.build import com.google.common.io.Files import java.io.BufferedWriter import java.io.Writer import kotlin.text.Charsets.UTF_8 import org.gradle.api.DefaultTask import org.gradle.api.file.DirectoryProperty import org.gradle.api.tasks.CacheableTask import org.gradle.api.tasks.Input import org.gradle.api.tasks.OutputDirectory import org.gradle.api.tasks.TaskAction /** * Task that parses the contents of a given library group file (usually [LibraryGroups]) and writes * the groups that are atomic to a text file. The file is then used by Lint. */ @CacheableTask abstract class ExportAtomicLibraryGroupsToTextTask : DefaultTask() { @get:[Input] lateinit var libraryGroups: Map<String, LibraryGroup> @get:OutputDirectory abstract val outputDir: DirectoryProperty @TaskAction fun exec() { // This must match the definition in BanInappropriateExperimentalUsage.kt val filename = "atomic-library-groups.txt" val textOutputFile = outputDir.file(filename).get().asFile val writer: Writer = BufferedWriter(Files.newWriter(textOutputFile, UTF_8)) libraryGroups.forEach { (_, libraryGroup) -> if (libraryGroup.requireSameVersion) { writer.write("${libraryGroup.group}\n") } } writer.close() } }
buildSrc/public/src/main/kotlin/androidx/build/ExportAtomicLibraryGroupsToTextTask.kt
3135327345
package com.kamer.orny.di.app import android.content.Context import com.kamer.orny.app.App import dagger.Binds import dagger.Module @Module abstract class AppModule { @Binds abstract fun bindApplicationContext(application: App): Context }
app/src/main/kotlin/com/kamer/orny/di/app/AppModule.kt
1742245108
package com.sedsoftware.yaptalker.presentation.model.base data class SinglePostParsedModel( val content: MutableList<PostContentModel>, val images: MutableList<String>, var videos: List<String>, var videosRaw: List<String>, var videosLinks: List<String>, var videoTypes: List<String> )
app/src/main/java/com/sedsoftware/yaptalker/presentation/model/base/SinglePostParsedModel.kt
455813292
// INTENTION_CLASS: org.jetbrains.kotlin.android.intention.AddActivityToManifest // NOT_AVAILABLE package com.myapp import android.app.Activity class Test { inner class <caret>MyActivity : Activity() }
plugins/kotlin/idea/tests/testData/android/intention/addActivityToManifest/inner.kt
2905827804
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.nastradamus.model import com.fasterxml.jackson.annotation.JsonProperty enum class TestStatus(status: String) { SUCCESS("success"), FAILED("failed"), IGNORED("ignored"), UNKNOWN("unknown"); val status: String = status.lowercase() companion object { fun fromString(input: String): TestStatus { return values().single { input.lowercase() == it.status } } } } data class TestResultEntity( val name: String, val status: TestStatus, @JsonProperty("run_order") val runOrder: Int, val duration: Long // in milliseconds )
platform/testFramework/core/src/com/intellij/nastradamus/model/TestResultEntity.kt
3906572887
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.plugins.gradle.service import com.intellij.openapi.util.io.FileUtil import com.intellij.testFramework.LightIdeaTestCase import org.gradle.StartParameter import org.gradle.util.GradleVersion import org.gradle.wrapper.PathAssembler import org.gradle.wrapper.WrapperConfiguration import org.gradle.wrapper.WrapperExecutor import org.jetbrains.plugins.gradle.settings.DistributionType import org.jetbrains.plugins.gradle.settings.GradleProjectSettings import java.io.File import java.net.URI import java.util.* abstract class GradleInstallationManagerTestCase : LightIdeaTestCase() { fun doTestGradleVersion(expectedVersion: GradleVersion, distributionType: DistributionType, wrapperVersionToGenerate: GradleVersion?) { val settings = GradleProjectSettings().apply { externalProjectPath = createUniqueTempDirectory() this.distributionType = distributionType if (wrapperVersionToGenerate != null) { gradleHome = generateFakeGradleWrapper(externalProjectPath, wrapperVersionToGenerate) } } val actualVersion = settings.resolveGradleVersion() assertEquals(expectedVersion, actualVersion) } private fun createUniqueTempDirectory(): String { val tempDirectory = FileUtil.join(FileUtil.getTempDirectory(), UUID.randomUUID().toString()) FileUtil.createDirectory(File(tempDirectory)) return tempDirectory } private fun generateFakeGradleWrapper(externalProjectPath: String, version: GradleVersion): String { val wrapperConfiguration = WrapperConfiguration() wrapperConfiguration.distribution = URI("http://gradle-${version.version}.com") val wrapperHome = FileUtil.join(externalProjectPath, "gradle", "wrapper") val wrapperJar = FileUtil.join(wrapperHome, "gradle-wrapper.jar") val wrapperProperties = FileUtil.join(wrapperHome, "gradle-wrapper.properties") val gradleUserHome = StartParameter.DEFAULT_GRADLE_USER_HOME val distributionPath = getLocalDistributionDir(gradleUserHome, File(externalProjectPath), wrapperConfiguration) val gradleHome = FileUtil.join(distributionPath, "gradle-${version.version}") val gradleJarFile = FileUtil.join(gradleHome, "lib", "gradle-${version.version}.jar") FileUtil.createDirectory(gradleUserHome) FileUtil.createIfNotExists(File(wrapperJar)) FileUtil.createIfNotExists(File(wrapperProperties)) FileUtil.createIfNotExists(File(gradleJarFile)) storeWrapperProperties(wrapperProperties, wrapperConfiguration) return gradleHome } private fun getLocalDistributionDir(gradleUserHome: File, projectPath: File, wrapperConfiguration: WrapperConfiguration): String { val pathAssembler = PathAssembler(gradleUserHome, projectPath) val localDistribution = pathAssembler.getDistribution(wrapperConfiguration) return localDistribution.distributionDir.path } private fun storeWrapperProperties(wrapperProperties: String, wrapperConfiguration: WrapperConfiguration) { File(wrapperProperties).outputStream().use { val properties = Properties() properties.setProperty(WrapperExecutor.DISTRIBUTION_URL_PROPERTY, wrapperConfiguration.distribution.toString()) properties.setProperty(WrapperExecutor.DISTRIBUTION_BASE_PROPERTY, wrapperConfiguration.distributionBase) properties.setProperty(WrapperExecutor.DISTRIBUTION_PATH_PROPERTY, wrapperConfiguration.distributionPath) properties.setProperty(WrapperExecutor.ZIP_STORE_BASE_PROPERTY, wrapperConfiguration.zipBase) properties.setProperty(WrapperExecutor.ZIP_STORE_PATH_PROPERTY, wrapperConfiguration.zipPath) properties.store(it, null) } } }
plugins/gradle/testSources/org/jetbrains/plugins/gradle/service/GradleInstallationManagerTestCase.kt
1937845618
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.java.refactoring import com.intellij.codeInsight.template.impl.TemplateManagerImpl import com.intellij.codeInsight.template.impl.TemplateState import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.TextRange import com.intellij.pom.java.LanguageLevel import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.extractMethod.newImpl.MethodExtractor import com.intellij.refactoring.extractMethod.newImpl.inplace.DuplicatesMethodExtractor import com.intellij.refactoring.listeners.RefactoringEventData import com.intellij.refactoring.listeners.RefactoringEventListener import com.intellij.refactoring.util.CommonRefactoringUtil.RefactoringErrorHintException import com.intellij.testFramework.IdeaTestUtil import com.intellij.testFramework.LightJavaCodeInsightTestCase import com.intellij.util.ui.UIUtil import org.jetbrains.annotations.NonNls class ExtractMethodAndDuplicatesInplaceTest: LightJavaCodeInsightTestCase() { private val BASE_PATH: @NonNls String = "/refactoring/extractMethodAndDuplicatesInplace" fun testStatement(){ doTest() } fun testConflictedNamesFiltered(){ doTest() } fun testVariableGetterSuggested(){ doTest() } fun testExactDuplicates(){ doTest() } fun testInvalidRename(){ doTest(changedName = "invalid! name", checkResults = false) require(getActiveTemplate() != null) } fun testConflictRename(){ doTest(changedName = "conflict", checkResults = false) require(getActiveTemplate() != null) } fun testValidRename(){ doTest(changedName = "valid") require(getActiveTemplate() == null) } fun testGeneratedDefault(){ doTest() } fun testRenamedExactDuplicate(){ doTest(changedName = "renamed") } fun testRenamedParametrizedDuplicate(){ doTest(changedName = "average") } fun testStaticMustBePlaced(){ doTest() } fun testShortenClassReferences(){ IdeaTestUtil.withLevel(module, LanguageLevel.JDK_11) { doTest() } } fun testThreeDuplicates(){ doTest(changedName = "sayHello") } fun testParameterGrouping(){ doTest() } fun testConditionalExitPoint(){ doTest() } fun testRuntimeCatchMayChangeSemantic1(){ assertThrows(RefactoringErrorHintException::class.java, JavaRefactoringBundle.message("extract.method.error.many.exits")) { doTest() } } fun testRuntimeCatchMayChangeSemantic2(){ assertThrows(RefactoringErrorHintException::class.java, JavaRefactoringBundle.message("extract.method.error.many.exits")) { doTest() } } fun testRuntimeCatchWithLastAssignment(){ doTest() } fun testSpecificCatch(){ doTest() } fun testExpressionDuplicates(){ doTest() } fun testArrayFoldingWithDuplicate(){ doTest() } fun testFoldReturnExpression(){ doTest() } fun testOverlappingRanges(){ doTest() } fun testConditionalYield(){ doTest() } fun testYieldWithDuplicate(){ doTest() } fun testDisabledOnSwitchRules(){ assertThrows(RefactoringErrorHintException::class.java, RefactoringBundle.message("selected.block.should.represent.a.set.of.statements.or.an.expression")) { doTest() } } fun testNormalizedOnSwitchRule(){ doTest() } fun testExpressionStatementInSwitchExpression(){ doTest() } fun testExpressionStatementInSwitchStatement(){ doTest() } fun testIDEA278872(){ doTest() } fun testLocalAssignmentDuplicates(){ doTest() } fun testWrongLocalAssignmentDuplicates(){ doTest() } fun testDuplicateWithLocalMethodReference(){ doTest() } fun testDuplicateWithAnonymousMethodReference(){ doTest() } fun testDuplicateWithAnonymousFieldReference(){ doTest() } fun testDuplicateWithLocalReferenceInLambda(){ doTest() } fun testAvoidChangeSignatureForLocalRefsInPattern(){ doTest() } fun testAvoidChangeSignatureForLocalRefsInCandidate(){ doTest() } fun testDiamondTypesConsideredAsEqual(){ doTest() } fun testDuplicatedExpressionAndChangeSignature(){ doTest() } fun testChangedVariableDeclaredOnce(){ doTest() } fun testDuplicatedWithDeclinedChangeSignature(){ val default = DuplicatesMethodExtractor.changeSignatureDefault try { DuplicatesMethodExtractor.changeSignatureDefault = false doTest() } finally { DuplicatesMethodExtractor.changeSignatureDefault = default } } fun testDuplicatedButDeclined(){ val default = DuplicatesMethodExtractor.replaceDuplicatesDefault try { DuplicatesMethodExtractor.replaceDuplicatesDefault = false doTest() } finally { DuplicatesMethodExtractor.replaceDuplicatesDefault = default } } fun testTemplateRenamesInsertedCallOnly(){ doTest(changedName = "renamed") } fun testRefactoringListener(){ templateTest { configureByFile("$BASE_PATH/${getTestName(false)}.java") var startReceived = false var doneReceived = false val connection = project.messageBus.connect() Disposer.register(testRootDisposable, connection) connection.subscribe(RefactoringEventListener.REFACTORING_EVENT_TOPIC, object : RefactoringEventListener { override fun refactoringStarted(refactoringId: String, beforeData: RefactoringEventData?) { startReceived = true } override fun refactoringDone(refactoringId: String, afterData: RefactoringEventData?) { doneReceived = true } override fun conflictsDetected(refactoringId: String, conflictsData: RefactoringEventData) = Unit override fun undoRefactoring(refactoringId: String) = Unit }) val template = startRefactoring(editor) require(startReceived) finishTemplate(template) require(doneReceived) } } private fun doTest(checkResults: Boolean = true, changedName: String? = null){ templateTest { configureByFile("$BASE_PATH/${getTestName(false)}.java") val template = startRefactoring(editor) if (changedName != null) { renameTemplate(template, changedName) } finishTemplate(template) if (checkResults) { checkResultByFile("$BASE_PATH/${getTestName(false)}_after.java") } } } private fun startRefactoring(editor: Editor): TemplateState { val selection = with(editor.selectionModel) { TextRange(selectionStart, selectionEnd) } MethodExtractor().doExtract(file, selection) val templateState = getActiveTemplate() require(templateState != null) { "Failed to start refactoring" } return templateState } private fun getActiveTemplate() = TemplateManagerImpl.getTemplateState(editor) private fun finishTemplate(templateState: TemplateState){ try { templateState.gotoEnd(false) UIUtil.dispatchAllInvocationEvents() } catch (ignore: RefactoringErrorHintException) { } } private fun renameTemplate(templateState: TemplateState, name: String) { WriteCommandAction.runWriteCommandAction(project) { val range = templateState.currentVariableRange!! editor.document.replaceString(range.startOffset, range.endOffset, name) } } private inline fun templateTest(test: () -> Unit) { val disposable = Disposer.newDisposable() try { TemplateManagerImpl.setTemplateTesting(disposable) test() } finally { Disposer.dispose(disposable) } } override fun tearDown() { try { val template = getActiveTemplate() if (template != null) Disposer.dispose(template) } catch (e: Throwable) { addSuppressedException(e) } finally { super.tearDown() } } }
java/java-tests/testSrc/com/intellij/java/refactoring/ExtractMethodAndDuplicatesInplaceTest.kt
3346024605
class Foo /** * [Foo.<caret>test] */ fun test() {} // REF_EMPTY
plugins/kotlin/idea/tests/testData/kdoc/resolve/OnlyMembersFromClass.kt
2607866793
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.workspaceModel.storage.impl import com.intellij.serialization.ObjectSerializer import com.intellij.serialization.ReadConfiguration import com.intellij.serialization.WriteConfiguration import com.intellij.util.containers.BidirectionalMultiMap import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.impl.indices.* import com.intellij.workspaceModel.storage.url.VirtualFileUrl import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap import java.io.InputStream import java.io.OutputStream class IonSerializer(virtualFileManager: VirtualFileUrlManager) : EntityStorageSerializer { override val serializerDataFormatVersion: String = "v1" override fun serializeCache(stream: OutputStream, storage: WorkspaceEntityStorage): SerializationResult { storage as WorkspaceEntityStorageImpl val configuration = WriteConfiguration(allowAnySubTypes = true) val ion = ObjectSerializer.instance ion.write(storage.entitiesByType, stream, configuration) ion.write(storage.refs, stream, configuration) ion.write(storage.indexes.softLinks, stream, configuration) ion.write(storage.indexes.virtualFileIndex.entityId2VirtualFileUrl, stream, configuration) ion.write(storage.indexes.virtualFileIndex.vfu2EntityId, stream, configuration) ion.write(storage.indexes.virtualFileIndex.entityId2JarDir, stream, configuration) ion.write(storage.indexes.entitySourceIndex, stream, configuration) ion.write(storage.indexes.persistentIdIndex, stream, configuration) return SerializationResult.Success } override fun deserializeCache(stream: InputStream): WorkspaceEntityStorageBuilder? { val configuration = ReadConfiguration(allowAnySubTypes = true) val ion = ObjectSerializer.instance // Read entity data and references val entitiesBarrel = ion.read(ImmutableEntitiesBarrel::class.java, stream, configuration) val refsTable = ion.read(RefsTable::class.java, stream, configuration) val softLinks = ion.read(MultimapStorageIndex::class.java, stream, configuration) val entityId2VirtualFileUrlInfo = ion.read(Object2ObjectOpenHashMap::class.java, stream, configuration) as EntityId2Vfu val vfu2VirtualFileUrlInfo = ion.read(Object2ObjectOpenHashMap::class.java, stream, configuration) as Vfu2EntityId val entityId2JarDir = ion.read(BidirectionalMultiMap::class.java, stream, configuration) as BidirectionalMultiMap<EntityId, VirtualFileUrl> val virtualFileIndex = VirtualFileIndex(entityId2VirtualFileUrlInfo, vfu2VirtualFileUrlInfo, entityId2JarDir) val entitySourceIndex = ion.read(EntityStorageInternalIndex::class.java, stream, configuration) as EntityStorageInternalIndex<EntitySource> val persistentIdIndex = ion.read(EntityStorageInternalIndex::class.java, stream, configuration) as PersistentIdInternalIndex val storageIndexes = StorageIndexes(softLinks, virtualFileIndex, entitySourceIndex, persistentIdIndex) val storage = WorkspaceEntityStorageImpl(entitiesBarrel, refsTable, storageIndexes) val builder = WorkspaceEntityStorageBuilderImpl.from(storage) builder.entitiesByType.entityFamilies.forEach { family -> family?.entities?.asSequence()?.filterNotNull()?.forEach { entityData -> builder.createAddEvent(entityData) } } return builder } }
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/IonSerializer.kt
919034254
/* * Copyright 2012-2016 Dmitri Pisarenko * * WWW: http://altruix.cc * E-Mail: [email protected] * Skype: dp118m (voice calls must be scheduled in advance) * * Physical address: * * 4-i Rostovskii pereulok 2/1/20 * 119121 Moscow * Russian Federation * * This file is part of econsim-tr01. * * econsim-tr01 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * econsim-tr01 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with econsim-tr01. If not, see <http://www.gnu.org/licenses/>. * */ package cc.altruix.econsimtr01.ch03 import cc.altruix.econsimtr01.DefaultAgent /** * Created by pisarenko on 17.05.2016. */ class Shack : DefaultAgent(Shack.ID) { companion object { val ID = "Shack" } }
src/main/java/cc/altruix/econsimtr01/ch03/Shack.kt
2387550247
fun test() { val a = 44;<caret> } // WITHOUT_CUSTOM_LINE_INDENT_PROVIDER
plugins/kotlin/idea/tests/testData/indentationOnNewline/Semicolon.kt
2274364490
package com.zhou.android.kotlin import android.content.Intent import android.content.IntentFilter import android.os.Bundle import android.util.Log import android.widget.Button import com.zhou.android.R import com.zhou.android.common.BaseActivity import com.zhou.android.common.Tools /** * Created by mxz on 2019/7/25. */ class ThrowExceptionActivity : BaseActivity() { lateinit var receiver: ExceptionReceiver var fragment1 = TextFragment() var fragment2 = TextFragment() override fun setContentView() { setContentView(R.layout.activity_throw_exception) } override fun init() { Tools.printActivityStack(this) receiver = ExceptionReceiver() registerReceiver(receiver, IntentFilter("playSound")) supportFragmentManager.beginTransaction() .add(R.id.fragment1, fragment1)//在重建app后出现被重叠,即旧fragment没有被销毁 .replace(R.id.fragment2, fragment2)//重建后,即使旧没有被销毁,也能把旧移除替换新的进去 .commit() } override fun addListener() { findViewById<Button>(R.id.btnCopy).setOnClickListener { startActivity(Intent(ThrowExceptionActivity@ this, ThrowExceptionActivity::class.java)) } findViewById<Button>(R.id.btnException).setOnClickListener { throw NullPointerException("Exception from ThrowExceptionActivity") } findViewById<Button>(R.id.btnError).setOnClickListener { throw Error("Error from ThrowExceptionActivity") } findViewById<Button>(R.id.btnPlay).setOnClickListener { sendBroadcast(Intent("playSound")) } findViewById<Button>(R.id.btnOther).setOnClickListener { startActivity(Intent(ThrowExceptionActivity@ this, AnalysisDecorActivity::class.java)) } } override fun onDestroy() { super.onDestroy() Log.i("zhou", "ThrowExceptionActivity onDestroy") unregisterReceiver(receiver) } override fun onRestoreInstanceState(savedInstanceState: Bundle) { super.onRestoreInstanceState(savedInstanceState) Log.i("zhou", "onRestoreInstanceState") fragment1.setText("onRestoreInstanceState1") fragment2.setText("onRestoreInstanceState2") } }
app/src/main/java/com/zhou/android/kotlin/ThrowExceptionActivity.kt
3347070707
package com.intellij.ide.starter.teamcity import com.intellij.ide.starter.ci.CIServer import com.intellij.ide.starter.utils.generifyErrorMessage import com.intellij.ide.starter.utils.logOutput import java.io.File import java.nio.file.Path import java.util.* object TeamCityCIServer : CIServer { private val systemProperties by lazy { loadProperties(System.getenv("TEAMCITY_BUILD_PROPERTIES_FILE")) } override val isBuildRunningOnCI = System.getenv("TEAMCITY_VERSION") != null override val buildNumber by lazy { System.getenv("BUILD_NUMBER") ?: "" } override val branchName by lazy { buildParams["teamcity.build.branch"] ?: "" } val configName by lazy { systemProperties["teamcity.buildConfName"] } override val buildParams by lazy { loadProperties(systemProperties["teamcity.configuration.properties.file"]) } override fun publishArtifact(source: Path, artifactPath: String, artifactName: String) { TeamCityClient.publishTeamCityArtifacts(source = source, artifactPath = artifactPath, artifactName = artifactName) } override fun reportTestFailure(testName: String, message: String, details: String) { val flowId = UUID.randomUUID().toString() val generifiedTestName = generifyErrorMessage(testName).processStringForTC() logOutput(String.format("##teamcity[testStarted name='%s' flowId='%s']", generifiedTestName, flowId)) logOutput(String.format( "##teamcity[testFailed name='%s' message='%s' details='%s' flowId='%s']", generifiedTestName, message.processStringForTC(), details.processStringForTC(), flowId )) logOutput(String.format("##teamcity[testFinished name='%s' flowId='%s']", generifiedTestName, flowId)) } fun getExistingParameter(name: String): String { return buildParams[name] ?: error("Parameter $name is not specified in the build!") } private val isDefaultBranch by lazy { //see https://www.jetbrains.com/help/teamcity/predefined-build-parameters.html#PredefinedBuildParameters-Branch-RelatedParameters hasBooleanProperty("teamcity.build.branch.is_default", default = false) } val isPersonalBuild by lazy { systemProperties["build.is.personal"].equals("true", ignoreCase = true) } val buildId by lazy { buildParams["teamcity.build.id"] ?: run { require(!isBuildRunningOnCI) "LOCAL_RUN_SNAPSHOT" } } val teamcityAgentName by lazy { buildParams["teamcity.agent.name"] } val teamcityCloudProfile by lazy { buildParams["system.cloud.profile_id"] } val buildTypeId by lazy { systemProperties["teamcity.buildType.id"] } val isSpecialBuild: Boolean get() { if (!isBuildRunningOnCI) { logOutput("[Metrics Publishing] Not running build on TeamCity => DISABLED") return true } if (isPersonalBuild) { logOutput("[Metrics Publishing] Personal builds are ignored => DISABLED") return true } if (!isDefaultBranch) { logOutput("[Metrics Publishing] Non default branches builds are ignored => DISABLED") return true } return false } fun hasBooleanProperty(key: String, default: Boolean) = buildParams[key]?.equals("true", ignoreCase = true) ?: default fun setStatusTextPrefix(text: String) { logOutput(" ##teamcity[buildStatus text='$text {build.status.text}'] ") } fun reportTeamCityStatistics(key: String, value: Int) { logOutput(" ##teamcity[buildStatisticValue key='${key}' value='${value}']") } fun reportTeamCityStatistics(key: String, value: Long) { logOutput(" ##teamcity[buildStatisticValue key='${key}' value='${value}']") } private fun String.processStringForTC(): String { return this.substring(0, Math.min(7000, this.length)) .replace("\\|", "||") .replace("\\[", "|[") .replace("]", "|]") .replace("\n", "|n") .replace("'", "|'") .replace("\r", "|r") } private fun loadProperties(file: String?) = try { File(file ?: throw Error("No file!")).bufferedReader().use { val map = mutableMapOf<String, String>() val ps = Properties() ps.load(it) ps.forEach { k, v -> if (k != null && v != null) { map[k.toString()] = v.toString() } } map } } catch (t: Throwable) { emptyMap() } }
tools/intellij.ide.starter/src/com/intellij/ide/starter/teamcity/TeamCityCIServer.kt
682340092
package alraune.operations import alraune.* import alraune.entity.* import vgrechka.* import java.io.File class AlCtl_TransferDb : AlCtlCommandWithNamedConfigs<AlCtl_TransferDb.Config>(Config::class) { class Config( val sedExecutable: String, val pgDumpExecutable: String, val psqlExecutable: String, val tempDbDumpFile: String, val srcDb: DatabaseParams, val destDb: DatabaseParams) override fun configs() = privateConfigs() override fun danceConfigured() { val c = config clog("Dumping source DB") NoisyExec() .env("PGPASSWORD", c.srcDb.password) .dance( c.pgDumpExecutable, "-U", c.srcDb.user, "-h", c.srcDb.host, "-p", c.srcDb.port.toString(), "--no-owner", "--clean", "--if-exists", "-f", c.tempDbDumpFile, "--exclude-table-data=${AlLogEntry.Meta.table}", c.srcDb.name) // val dumpFile = File(c.tempDbDumpFile) // dumpFile.writeText(dumpFile.readText() + """ // """) clog("Patching dump a little bit") NoisyExec() .also { if (isWindowsOS()) // Windows sed has a bug which leaves junk files in working directory it.workingDir("c:/tmp") } .dance( c.sedExecutable, "-i", "s/^CREATE EXTENSION/-- CREATE EXTENSION/g;" + " s/^COMMENT ON EXTENSION/-- COMMENT ON EXTENSION/g;" + " s/^DROP EXTENSION/-- DROP EXTENSION/g;" + " s/^CREATE SCHEMA/-- CREATE SCHEMA/g;" + " s/^COMMENT ON SCHEMA/-- COMMENT ON SCHEMA/g;" + " s/^DROP SCHEMA/-- DROP SCHEMA/g;" + " s/^GRANT ALL ON SCHEMA/-- GRANT ALL ON SCHEMA/g", c.tempDbDumpFile) clog("Applying dump to destination DB") NoisyExec() .env("PGPASSWORD", c.destDb.password) .dance( c.psqlExecutable, "-q", "-U", c.destDb.user, "-h", c.destDb.host, "-p", c.destDb.port.toString(), "--set", "ON_ERROR_STOP=on", "-f", c.tempDbDumpFile, c.destDb.name) clog("\nOK") } }
alraune/alraune/src/main/java/alraune/operations/AlCtl_TransferDb.kt
515838358
// FIR_IDENTICAL // FIR_COMPARISON class A { @Deprecated("") o<caret> } // ELEMENT_TEXT: "override fun equals(other: Any?): Boolean {...}"
plugins/kotlin/completion/tests/testData/handlers/basic/override/KeepAnnotationBefore.kt
722150176
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.renderers import com.intellij.openapi.util.NlsSafe import com.intellij.ui.JBColor import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle import com.jetbrains.packagesearch.intellij.plugin.normalizeWhitespace import com.jetbrains.packagesearch.intellij.plugin.ui.PackageSearchUI import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.PackagesTableItem import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.TagComponent import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.colors import com.jetbrains.packagesearch.intellij.plugin.ui.util.scaled import com.jetbrains.packagesearch.intellij.plugin.ui.util.scaledInsets import net.miginfocom.layout.AC import net.miginfocom.layout.BoundSize import net.miginfocom.layout.CC import net.miginfocom.layout.DimConstraint import net.miginfocom.layout.LC import net.miginfocom.layout.UnitValue import net.miginfocom.swing.MigLayout import java.awt.Dimension import java.awt.Graphics import javax.swing.JLabel import javax.swing.JPanel import javax.swing.JTable import javax.swing.table.TableCellRenderer @Suppress("MagicNumber") // Swing dimension constants internal object PackageNameCellRenderer : TableCellRenderer { private val layoutConstraints = LC().align("left", "center") .scaledInsets(left = 8, right = 0) private val componentGapX = 4.scaled() private val columnConstraints = AC().apply { gap(componentGapX.toString()) constaints = arrayOf( DimConstraint().apply { gap(componentGapX.toString()) size = BoundSize(UnitValue(150F, UnitValue.PIXEL, ""), "") }, DimConstraint().apply { gapBefore = BoundSize(UnitValue(componentGapX / 2F), "") } ) } private val tagForeground = JBColor.namedColor("PackageSearch.PackageTag.foreground", 0x808080, 0x9C9C9C) private val tagBackground = JBColor.namedColor("PackageSearch.PackageTag.background", 0xE5E5E5, 0x666B6E) private val tagForegroundSelected = JBColor.namedColor("PackageSearch.PackageTagSelected.foreground", 0xFFFFFF, 0xFFFFFF) private val tagBackgroundSelected = JBColor.namedColor("PackageSearch.PackageTagSelected.background", 0x4395E2, 0x78ADE2) private fun componentConstraint(x: Int = 0, y: Int = 0, gapAfter: Int? = null): CC = CC().apply { cellX = x cellY = y if (gapAfter != null) gapAfter(gapAfter.toString()) } override fun getTableCellRendererComponent( table: JTable, value: Any, isSelected: Boolean, hasFocus: Boolean, row: Int, column: Int ): JPanel { val columnWidth = table.tableHeader.columnModel.getColumn(0).width return when (value as PackagesTableItem<*>) { is PackagesTableItem.InstalledPackage -> { val packageModel = value.packageModel val name: String? = packageModel.remoteInfo?.name.normalizeWhitespace() val rawIdentifier = packageModel.identifier.rawValue createNamePanel(columnWidth, name, rawIdentifier, packageModel.isKotlinMultiplatform, isSelected).apply { table.colors.applyTo(this, isSelected) } } is PackagesTableItem.InstallablePackage -> { val packageModel = value.packageModel val name: String? = packageModel.remoteInfo?.name.normalizeWhitespace() val rawIdentifier = packageModel.identifier.rawValue createNamePanel(columnWidth, name, rawIdentifier, packageModel.isKotlinMultiplatform, isSelected).apply { table.colors.applyTo(this, isSelected) if (!isSelected) background = PackageSearchUI.ListRowHighlightBackground } } } } private fun createNamePanel( columnWidth: Int, @NlsSafe name: String?, @NlsSafe identifier: String, isKotlinMultiplatform: Boolean, isSelected: Boolean ) = TagPaintingJPanel(columnWidth, isSelected).apply { if (!name.isNullOrBlank() && name != identifier) { add( JLabel(name).apply { foreground = PackageSearchUI.getTextColorPrimary(isSelected) }, componentConstraint(gapAfter = componentGapX) ) add( JLabel(identifier).apply { foreground = PackageSearchUI.getTextColorSecondary(isSelected) }, componentConstraint().gapAfter("0:push") ) } else { add( JLabel(identifier).apply { foreground = PackageSearchUI.getTextColorPrimary(isSelected) }, componentConstraint() ) } if (isKotlinMultiplatform) { add( TagComponent(PackageSearchBundle.message("packagesearch.terminology.kotlinMultiplatform")) .apply { isVisible = false }, componentConstraint(1, 0) ) } } // This is a hack; ideally we should have this done by the layout itself, // but MigLayout wasn't cooperating // TODO Use a custom layout to do this in a less hacky fashion private class TagPaintingJPanel(private val columnWidth: Int, private val isSelected: Boolean) : JPanel( MigLayout(layoutConstraints.width("${columnWidth}px!"), columnConstraints) ) { init { size = Dimension(columnWidth, height) maximumSize = Dimension(columnWidth, Int.MAX_VALUE) } override fun paintChildren(g: Graphics) { super.paintChildren(g) val tagComponent = components.find { it is TagComponent } as? TagComponent ?: return val tagX = columnWidth - tagComponent.width val tagY = height / 2 - tagComponent.height / 2 g.apply { // We first paint over the gap between the text and the tag, to have a pretend margin if needed color = background fillRect(tagX - componentGapX, 0, columnWidth - tagX, height) // Then we manually translate the tag to the right-hand side of the row and paint it translate(tagX, tagY) tagComponent.apply { isVisible = true foreground = JBColor.namedColor("Plugins.tagForeground", if (isSelected) tagForegroundSelected else tagForeground) background = JBColor.namedColor("Plugins.tagBackground", if (isSelected) tagBackgroundSelected else tagBackground) paint(g) } } } } }
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packages/columns/renderers/PackageNameCellRenderer.kt
752366168
val a: String = "" val b: String? = "" class MyClass { val x: String = "" val y: String? = "" fun foo() { val s: String = "" val t: String? = "" if (b != null) { <caret> } } }
plugins/kotlin/live-templates/tests/testData/inn.exp.kt
3844684814
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.structuralsearch.search.filters import org.jetbrains.kotlin.idea.structuralsearch.KotlinSSResourceInspectionTest class KotlinSSCountFilterTest : KotlinSSResourceInspectionTest() { override fun getBasePath(): String = "countFilter" // isApplicableMinCount fun testMinProperty() { doTest("var '_ = '_{0,0}", """ class A { <warning descr="SSR">lateinit var x: String</warning> var y = 1 fun init() { x = "a" } } """.trimIndent()) } fun testMinDotQualifierExpression() { doTest("'_{0,0}.'_", """ class A { companion object { const val FOO = 3.14 } } fun main() { val a = A.FOO <warning descr="SSR">print(Int.hashCode())</warning> <warning descr="SSR">print(<warning descr="SSR">a</warning>)</warning> } """.trimIndent()) } fun testMinFunctionTypeReference() { doTest("fun '_{0,0}.'_()", """ class One fun One.myFun() {} <warning descr="SSR">fun myFun() {}</warning> """.trimIndent()) } fun testMinCallableReferenceExpression() { doTest("'_{0,0}::'_", """ fun Int.isOddExtension() = this % 2 != 0 class MyClazz { fun isOddMember(x: Int) = x % 2 != 0 fun constructorReference(init: () -> MyClazz) { print(init) } fun foo() { val functionTwo: (Int) -> Boolean = Int::isOddExtension val functionOne: (Int) -> Boolean = <warning descr="SSR">::isOddMember</warning> constructorReference(<warning descr="SSR">::MyClazz</warning>) print(functionOne(1) == functionTwo(2)) } } """.trimIndent()) } fun testMinWhenExpression() { doTest("when ('_{0,0}) {}", """ fun foo() { print(<warning descr="SSR">when (1) { in 0..3 -> 2 else -> 3 }</warning>) print(<warning descr="SSR">when { else -> true }</warning>) } """.trimIndent()) } fun testMinConstructorCallee() { doTest("class '_ : '_{0,0}('_*)", """ <warning descr="SSR">open class Foo</warning> class Bar: Foo() """.trimIndent()) } fun testMinSuperType() { doTest("class '_ : '_{0,0}()", """ <warning descr="SSR">open class A</warning> class B : A() """.trimIndent()) } // isApplicableMaxCount fun testMaxDestructuringDeclarationEntry() { doTest("for (('_{3,3}) in '_) { '_* }", """ data class Foo(val foo1: Int, val foo2: Int) data class Bar(val bar1: String, val bar2: String, val bar3: String) fun foo() = Foo(1, 2) fun bar() = Bar("a", "b", "c") fun main() { val (f1, f2) = foo() val (b1, b2, b3) = bar() print(f1 + f2) print(b1 + b2 + b3) val l1 = listOf(Foo(1, 1)) for ((x1, x2) in l1) { print(x1 + x2) } val l2 = listOf(Bar("a", "a", "a")) <warning descr="SSR">for ((x1, x2, x3) in l2) { print(x1 + x2 + x3) }</warning> for (i in 1..2) { print(i) } } """.trimIndent()) } fun testMaxWhenConditionWithExpression() { doTest("when ('_?) { '_{2,2} -> '_ }", """ fun foo(): Int { fun f() {} <warning descr="SSR">when (1) { in 1..10 -> f() in 11..20 -> f() }</warning> val x1 = when { else -> 1 } val x2 = <warning descr="SSR">when { <warning>1 < 2</warning> -> 3 else -> 1 }</warning> val x3 = when { <warning>1 < 3</warning> -> 1 <warning>2 > 1</warning> -> 4 else -> 1 } return x1 + x2 + x3 } """.trimIndent()) } // isApplicableMinMaxCount fun testMmClassBodyElement() { doTest(""" class '_Class { var '_Field{0,2} = '_Init? } """.trimIndent(), """ <warning descr="SSR">class A</warning> <warning descr="SSR">class B { var x = 1 }</warning> <warning descr="SSR">class C { var x = 1 var y = "1" }</warning> class D { var x = 1 var y = "1" var z = false } """.trimIndent() ) } fun testMmParameter() { doTest("fun '_('_{0,2})", """ <warning descr="SSR">fun foo1() {}</warning> <warning descr="SSR">fun foo2(p1: Int) { print(p1) }</warning> <warning descr="SSR">fun foo3(p1: Int, p2: Int) { print(p1 + p2) }</warning> fun bar(p1: Int, p2: Int, p3: Int) { print(p1 + p2 + p3) } """.trimIndent()) } fun testMmTypeParameter() { doTest("fun <'_{0,2}> '_('_*)", """ <warning descr="SSR">fun foo1() {}</warning> <warning descr="SSR">fun <A> foo2(x: A) { x.hashCode() }</warning> <warning descr="SSR">fun <A, B> foo3(x: A, y: B) { x.hashCode() + y.hashCode() }</warning> fun <A, B, C> bar(x: A, y: B, z: C) { x.hashCode() + y.hashCode() + z.hashCode() } """.trimIndent()) } fun testMmTypeParameterFunctionType() { doTest("fun '_('_ : ('_{0,2}) -> '_)", """ <warning descr="SSR">fun foo1(x : () -> Unit) { print(x) }</warning> <warning descr="SSR">fun foo2(x : (Int) -> Unit) { print(x) }</warning> <warning descr="SSR">fun foo3(x : (Int, String) -> Unit) { print(x) }</warning> fun bar(x : (Int, String, Boolean) -> Unit) { print(x) } """.trimIndent()) } fun testMmTypeReference() { doTest("val '_ : ('_{0,2}) -> '_", """ <warning descr="SSR">val foo1 : () -> String = { "" }</warning> <warning descr="SSR">val foo2 : (Int) -> String = { x -> "${"$"}x" }</warning> <warning descr="SSR">val foo3 : (Int, String) -> String = { x, y -> "${"$"}x${"$"}y" }</warning> val bar : (Int, String, Boolean) -> String = { x, y, z -> "${"$"}x${"$"}y${"$"}z" } """.trimIndent()) } fun testMmSuperTypeEntry() { doTest("class '_ : '_{0,2}", """ interface IOne interface ITwo interface IThree <warning descr="SSR">open class A</warning> <warning descr="SSR">class B : IOne</warning> <warning descr="SSR">class B2 : IOne, A()</warning> <warning descr="SSR">class C : IOne, ITwo</warning> <warning descr="SSR">class C2 : IOne, ITwo, A()</warning> class D : IOne, ITwo, IThree class D2 : IOne, ITwo, IThree, A() """.trimIndent()) } fun testMmValueArgument() { doTest("listOf('_{0,2})", """ val foo1: List<Int> = <warning descr="SSR">listOf()</warning> val foo2 = <warning descr="SSR">listOf(1)</warning> val foo3 = <warning descr="SSR">listOf(1, 2)</warning> val bar = listOf(1, 2, 3) """.trimIndent()) } fun testMmStatementInDoWhile() { doTest("do { '_{0,2} } while ('_)", """ fun foo() { var x = 0 <warning descr="SSR">do { } while (false)</warning> <warning descr="SSR">do { x += 1 } while (false)</warning> <warning descr="SSR">do { x += 1 x *= 2 } while (false)</warning> do { x += 1 x *= 2 x *= x } while (false) print(x) } """.trimIndent()) } fun testMmStatementInBlock() { doTest("fun '_('_*) { '_{0,2} }", """ <warning descr="SSR">fun foo1() {}</warning> <warning descr="SSR">fun foo2() { print(1) }</warning> <warning descr="SSR">fun foo3() { print(1) print(2) }</warning> fun bar() { print(1) print(2) print(3) } """.trimIndent()) } fun testMmAnnotation() { doTest("@'_{0,2} class '_", """ <warning descr="SSR">annotation class FirstAnnotation</warning> <warning descr="SSR">annotation class SecondAnnotation</warning> <warning descr="SSR">annotation class ThirdAnnotation</warning> <warning descr="SSR">class ZeroClass</warning> <warning descr="SSR">@FirstAnnotation class FirstClass</warning> <warning descr="SSR">@FirstAnnotation @SecondAnnotation class SecondClass</warning> @FirstAnnotation @SecondAnnotation @ThirdAnnotation class ThirdClass """.trimIndent()) } fun testMmSimpleNameStringTemplateEntry() { doTest(""" "$$'_{0,2}" """, """ val foo1 = <warning descr="SSR">""</warning> val foo2 = <warning descr="SSR">"foo"</warning> val foo3 = <warning descr="SSR">"foo${"$"}foo1"</warning> val bar = "foo${"$"}foo1${"$"}foo2" """.trimIndent()) } fun testMmTypeProjection() { doTest("fun '_('_ : '_<'_{0,2}>)", """ class X<A> {} class Y<A, B> {} class Z<A, B, C> {} <warning descr="SSR">fun foo1(par: Int) { print(par) }</warning> <warning descr="SSR">fun foo2(par: X<String>) { print(par) }</warning> <warning descr="SSR">fun foo3(par: Y<String, Int>) { print(par) }</warning> fun bar(par: Z<String, Int, Boolean>) { print(par) } """.trimIndent()) } fun testMmKDocTag() { doTest(""" /** * @'_{0,2} */ """.trimIndent(), """ <warning descr="SSR">/** * lorem */</warning> <warning descr="SSR">/** * ipsum * @a */</warning> <warning descr="SSR">/** * dolor * @a * @b */</warning> /** * sit * @a * @b * @c */ """.trimIndent()) } // Misc fun testZeroLambdaParameter() { doTest("{ '_{0,0} -> '_ }", """ val p0: () -> Int = <warning descr="SSR">{ 31 }</warning> val p1: (Int) -> Int = { x -> x } val p1b: (Int) -> Int = <warning descr="SSR">{ it }</warning> val p2: (Int, Int) -> Int = { x, y -> x + y } val p3: (Int, Int, Int) -> Int = { x, y, z -> x + y + z } """.trimIndent()) } fun testOneLambdaParameter() { doTest("{ '_{1,1} -> '_ }", """ val p0: () -> Int = { 31 } val p1: (Int) -> Int = <warning descr="SSR">{ x -> x }</warning> val p1b: (Int) -> Int = <warning descr="SSR">{ it }</warning> val p2: (Int, Int) -> Int = { x, y -> x + y } val p3: (Int, Int, Int) -> Int = { x, y, z -> x + y + z } """.trimIndent()) } fun testMmLambdaParameter() { doTest("{ '_{0,2} -> '_ }", """ val p0: () -> Int = <warning descr="SSR">{ 31 }</warning> val p1: (Int) -> Int = <warning descr="SSR">{ x -> x }</warning> val p1b: (Int) -> Int = <warning descr="SSR">{ it }</warning> val p2: (Int, Int) -> Int = <warning descr="SSR">{ x, y -> x + y }</warning> val p3: (Int, Int, Int) -> Int = { x, y, z -> x + y + z } """.trimIndent()) } }
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/structuralsearch/search/filters/KotlinSSCountFilterTest.kt
911356103
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("BlockingMethodInNonBlockingContext") package org.jetbrains.intellij.build.impl import com.intellij.diagnostic.telemetry.useWithScope2 import com.intellij.openapi.util.SystemInfoRt import com.intellij.util.lang.JavaVersion import io.opentelemetry.api.trace.Span import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.launch import org.apache.commons.compress.archivers.zip.ZipFile import org.apache.commons.compress.utils.SeekableInMemoryByteChannel import org.jetbrains.intellij.build.BuildMessages import org.jetbrains.intellij.build.TraceManager.spanBuilder import java.io.BufferedInputStream import java.io.DataInputStream import java.io.InputStream import java.nio.channels.FileChannel import java.nio.file.Files import java.nio.file.Path import java.nio.file.StandardOpenOption import java.util.* import java.util.concurrent.ConcurrentLinkedQueue import java.util.concurrent.atomic.AtomicInteger import java.util.zip.ZipException /** * <p> * Recursively checks .class files in directories and .jar/.zip files to ensure that their versions * do not exceed limits specified in the config map. * </p> * <p> * The config map contains pairs of path prefixes (relative to the check root) to version limits. * The limits are Java version strings (<code>"1.3"</code>, <code>"8"</code> etc.); * empty strings are ignored (making the check always pass). * The map must contain an empty path prefix (<code>""</code>) denoting the default version limit. * </p> * <p>Example: <code>["": "1.8", "lib/idea_rt.jar": "1.3"]</code>.</p> */ internal suspend fun checkClassFiles(versionCheckConfig: Map<String, String>, forbiddenSubPaths: List<String>, root: Path, messages: BuildMessages) { spanBuilder("verify class files") .setAttribute("ruleCount", versionCheckConfig.size.toLong()) .setAttribute("forbiddenSubPathCount", forbiddenSubPaths.size.toLong()) .setAttribute("root", root.toString()) .useWithScope2 { val rules = ArrayList<Rule>(versionCheckConfig.size) for (entry in versionCheckConfig.entries) { rules.add(Rule(path = entry.key, version = classVersion(entry.value))) } rules.sortWith { o1, o2 -> (-o1.path.length).compareTo(-o2.path.length) } check(rules.isEmpty() || rules.last().path.isEmpty()) { throw ClassFileCheckError("Invalid configuration: missing default version $rules") } val defaultVersion = rules.lastOrNull()?.version check(defaultVersion == null || rules.dropLast(1).none { it.version == defaultVersion }) { throw ClassFileCheckError("Redundant rules with default version: " + rules.dropLast(1).filter { it.version == defaultVersion }) } val checker = ClassFileChecker(rules, forbiddenSubPaths) val errors = ConcurrentLinkedQueue<String>() if (Files.isDirectory(root)) { coroutineScope { checker.apply { visitDirectory(root, "", errors) } } } else { checker.visitFile(root, "", errors) } check(rules.isEmpty() || checker.checkedClassCount.get() != 0) { throw ClassFileCheckError("No classes found under $root - please check the configuration") } val errorCount = errors.size Span.current() .setAttribute("checkedClasses", checker.checkedClassCount.get().toLong()) .setAttribute("checkedJarCount", checker.checkedJarCount.get().toLong()) .setAttribute("errorCount", errorCount.toLong()) for (error in errors) { messages.warning("---\n$error") } check(errorCount == 0) { throw ClassFileCheckError("Failed with $errorCount problems", errors) } val unusedRules = rules.filter { !it.wasUsed } check(unusedRules.isEmpty()) { throw ClassFileCheckError("Class version check rules for the following paths don't match any files, probably entries in " + "ProductProperties::versionCheckerConfig are out of date:\n${unusedRules.joinToString(separator = "\n")}") } } } class ClassFileCheckError(message: String, val errors: Collection<String> = emptyList()) : Exception(message) private val READ = EnumSet.of(StandardOpenOption.READ) private class ClassFileChecker(private val versionRules: List<Rule>, private val forbiddenSubPaths: List<String>) { val checkedJarCount = AtomicInteger() val checkedClassCount = AtomicInteger() fun CoroutineScope.visitDirectory(directory: Path, relPath: String, errors: MutableCollection<String>) { Files.newDirectoryStream(directory).use { dirStream -> // closure must be used, otherwise variables are not captured by FJT for (child in dirStream) { if (Files.isDirectory(child)) { launch { visitDirectory(directory = child, relPath = join(relPath, "/", child.fileName.toString()), errors = errors) } } else { launch { visitFile(file = child, relPath = join(relPath, "/", child.fileName.toString()), errors = errors) } } } } } fun visitFile(file: Path, relPath: String, errors: MutableCollection<String>) { val fullPath = file.toString() if (fullPath.endsWith(".zip") || fullPath.endsWith(".jar")) { visitZip(fullPath, relPath, ZipFile(FileChannel.open(file, READ)), errors) } else if (fullPath.endsWith(".class")) { checkIfSubPathIsForbidden(relPath, errors) val contentCheckRequired = versionRules.isNotEmpty() && !fullPath.endsWith("module-info.class") && !isMultiVersion(fullPath) if (contentCheckRequired) { BufferedInputStream(Files.newInputStream(file)).use { checkVersion(relPath, it, errors) } } } } // use ZipFile - avoid a lot of small lookups to read entry headers (ZipFile uses central directory) private fun visitZip(zipPath: String, zipRelPath: String, file: ZipFile, errors: MutableCollection<String>) { file.use { checkedJarCount.incrementAndGet() val entries = file.entries while (entries.hasMoreElements()) { val entry = entries.nextElement() if (entry.isDirectory) { continue } val name = entry.name if (name.endsWith(".zip") || name.endsWith(".jar")) { val childZipPath = "$zipPath!/$name" try { visitZip(zipPath = childZipPath, zipRelPath = join(zipRelPath, "!/", name), file = ZipFile(SeekableInMemoryByteChannel(file.getInputStream(entry).readAllBytes())), errors = errors) } catch (e: ZipException) { throw RuntimeException("Cannot read $childZipPath", e) } } else if (name.endsWith(".class")) { val relPath = join(zipRelPath, "!/", name) checkIfSubPathIsForbidden(relPath, errors) val contentCheckRequired = versionRules.isNotEmpty() && !name.endsWith("module-info.class") && !isMultiVersion(name) if (contentCheckRequired) { checkVersion(relPath, file.getInputStream(entry), errors) } } } } } private fun checkIfSubPathIsForbidden(relPath: String, errors: MutableCollection<String>) { for (f in forbiddenSubPaths) { if (relPath.contains(f)) { errors.add("$relPath: .class file has a forbidden sub-path: $f") } } } private fun checkVersion(path: String, stream: InputStream, errors: MutableCollection<String>) { checkedClassCount.incrementAndGet() val dataStream = DataInputStream(stream) if (dataStream.readInt() != 0xCAFEBABE.toInt() || dataStream.skipBytes(3) != 3) { errors.add("$path: invalid .class file header") return } val major = dataStream.readUnsignedByte() if (major < 44 || major >= 100) { errors.add("$path: suspicious .class file version: $major") return } val rule = versionRules.first { it.path.isEmpty() || path.startsWith(it.path) } rule.wasUsed = true val expected = rule.version @Suppress("ConvertTwoComparisonsToRangeCheck") if (expected > 0 && major > expected) { errors.add("$path: .class file version $major exceeds expected $expected") } } } private fun isMultiVersion(path: String): Boolean { return path.startsWith("META-INF/versions/") || path.contains("/META-INF/versions/") || (SystemInfoRt.isWindows && path.contains("\\META-INF\\versions\\")) } private fun classVersion(version: String) = if (version.isEmpty()) -1 else JavaVersion.parse(version).feature + 44 // 1.1 = 45 private fun join(prefix: String, separator: String, suffix: String) = if (prefix.isEmpty()) suffix else (prefix + separator + suffix) private data class Rule(@JvmField val path: String, @JvmField val version: Int) { @Volatile @JvmField var wasUsed = false }
platform/build-scripts/src/org/jetbrains/intellij/build/impl/ClassFileChecker.kt
159166611
// FLOW: IN val Any.extensionProp: Any get() = this fun foo() { val <caret>x = "".extensionProp }
plugins/kotlin/idea/tests/testData/slicer/inflow/thisInExtensionProperty.kt
2291068601
import android.app.Activity import com.myapp.R fun Activity.getSuperGreenColor() = getColor(R.color.<caret>super_green)
plugins/kotlin/idea/tests/testData/android/resourceIntention/createColorValueResource/simpleFunction/main.kt
1652007973
// FIR_IDENTICAL interface T { fun getFoo(): String = "" } interface U { fun getFoo(): String } class C1 : T, U { <caret> }
plugins/kotlin/idea/tests/testData/codeInsight/overrideImplement/abstractAndNonAbstractInheritedFromInterface.kt
4069546323
internal class Test { val int: Int get() { val b: Byte = 10 return b.toInt() } }
plugins/kotlin/j2k/old/tests/testData/fileOrElement/issues/kt-794.kt
523012732
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.maven.buildtool.quickfix import com.intellij.build.issue.BuildIssueQuickFix import com.intellij.ide.actions.ShowSettingsUtilImpl import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.project.Project import org.jetbrains.idea.maven.execution.MavenRunnerConfigurable import java.util.concurrent.CompletableFuture class OpenMavenRunnerSettingsQuickFix(val search: String?) : BuildIssueQuickFix { constructor() : this(null) override val id: String = "open_maven_runner_settings_quick_fix" override fun runQuickFix(project: Project, dataContext: DataContext): CompletableFuture<*> { ApplicationManager.getApplication().invokeLater { ShowSettingsUtilImpl.showSettingsDialog(project, MavenRunnerConfigurable.SETTINGS_ID, search) } return CompletableFuture.completedFuture(null) } }
plugins/maven/src/main/java/org/jetbrains/idea/maven/buildtool/quickfix/OpenMavenRunnerSettingsQuickFix.kt
3182095722