idea: cleanup code

This commit is contained in:
Dmitry Gridin
2019-12-13 22:11:25 +07:00
parent e77d8657f4
commit 8dbbd64beb
897 changed files with 13161 additions and 18514 deletions
@@ -1,17 +1,6 @@
/*
* Copyright 2010-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.
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.console
@@ -20,8 +9,8 @@ import com.intellij.openapi.util.TextRange
class CommandHistory {
class Entry(
val entryText: String,
val rangeInHistoryDocument: TextRange
val entryText: String,
val rangeInHistoryDocument: TextRange
)
private val entries = arrayListOf<Entry>()
@@ -37,21 +26,17 @@ class CommandHistory {
listeners.forEach { it.onNewEntry(entry) }
}
fun lastUnprocessedEntry(): Entry? {
return if (processedEntriesCount < size) {
get(processedEntriesCount)
}
else {
null
}
fun lastUnprocessedEntry(): Entry? = if (processedEntriesCount < size) {
get(processedEntriesCount)
} else {
null
}
fun entryProcessed() {
processedEntriesCount++
}
val size: Int
get() = entries.size
val size: Int get() = entries.size
}
interface HistoryUpdateListener {
@@ -1,17 +1,6 @@
/*
* Copyright 2010-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.
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.console
@@ -26,9 +15,8 @@ import java.awt.event.KeyEvent
import kotlin.math.max
import kotlin.math.min
class HistoryKeyListener(
private val project: Project, private val consoleEditor: EditorEx, private val history: CommandHistory
) : KeyAdapter(), HistoryUpdateListener {
class HistoryKeyListener(private val project: Project, private val consoleEditor: EditorEx, private val history: CommandHistory) :
KeyAdapter(), HistoryUpdateListener {
private var historyPos = 0
private var prevCaretOffset = -1
private var unfinishedCommand = ""
@@ -1,17 +1,6 @@
/*
* Copyright 2010-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.
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.console
@@ -26,7 +15,7 @@ import org.jetbrains.kotlin.utils.PathUtil
import java.io.File
import java.util.concurrent.ConcurrentHashMap
private val REPL_TITLE = "Kotlin REPL"
private const val REPL_TITLE = "Kotlin REPL"
class KotlinConsoleKeeper(val project: Project) {
private val consoleMap: MutableMap<VirtualFile, KotlinConsoleRunner> = ConcurrentHashMap()
@@ -45,7 +34,8 @@ class KotlinConsoleKeeper(val project: Project) {
}
companion object {
@JvmStatic fun getInstance(project: Project) = ServiceManager.getService(project, KotlinConsoleKeeper::class.java)
@JvmStatic
fun getInstance(project: Project) = ServiceManager.getService(project, KotlinConsoleKeeper::class.java)
fun createReplCommandLine(project: Project, module: Module?): GeneralCommandLine {
val javaParameters = JavaParametersBuilder(project)
@@ -1,17 +1,6 @@
/*
* Copyright 2010-2017 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.
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.console
@@ -61,10 +50,10 @@ import org.jetbrains.kotlin.idea.caches.project.forcedModuleInfo
import org.jetbrains.kotlin.idea.caches.project.productionSourceInfo
import org.jetbrains.kotlin.idea.caches.project.testSourceInfo
import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor
import org.jetbrains.kotlin.idea.caches.trackers.KOTLIN_CONSOLE_KEY
import org.jetbrains.kotlin.idea.core.script.ScriptDefinitionContributor
import org.jetbrains.kotlin.idea.core.script.ScriptDefinitionSourceAsContributor
import org.jetbrains.kotlin.idea.core.script.ScriptDefinitionsManager
import org.jetbrains.kotlin.idea.caches.trackers.KOTLIN_CONSOLE_KEY
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.parsing.KotlinParserDefinition
@@ -81,15 +70,15 @@ import java.util.concurrent.TimeUnit
import kotlin.properties.Delegates
import kotlin.script.experimental.jvm.defaultJvmScriptingHostConfiguration
private val KOTLIN_SHELL_EXECUTE_ACTION_ID = "KotlinShellExecute"
private const val KOTLIN_SHELL_EXECUTE_ACTION_ID = "KotlinShellExecute"
class KotlinConsoleRunner(
val module: Module,
private val cmdLine: GeneralCommandLine,
internal val previousCompilationFailed: Boolean,
myProject: Project,
title: String,
path: String?
val module: Module,
private val cmdLine: GeneralCommandLine,
internal val previousCompilationFailed: Boolean,
myProject: Project,
title: String,
path: String?
) : AbstractConsoleRunnerWithHistory<LanguageConsoleView>(myProject, title, path) {
private val replState = ReplState()
@@ -181,9 +170,9 @@ class KotlinConsoleRunner(
override fun createProcessHandler(process: Process): OSProcessHandler {
val processHandler = ReplOutputHandler(
this,
process,
cmdLine.commandLineString
this,
process,
cmdLine.commandLineString
)
val consoleFile = consoleView.virtualFile
val keeper = KotlinConsoleKeeper.getInstance(project)
@@ -197,24 +186,25 @@ class KotlinConsoleRunner(
override fun runExecuteAction(consoleView: LanguageConsoleView) = executor.executeCommand()
}
override fun fillToolBarActions(toolbarActions: DefaultActionGroup,
defaultExecutor: Executor,
contentDescriptor: RunContentDescriptor
override fun fillToolBarActions(
toolbarActions: DefaultActionGroup,
defaultExecutor: Executor,
contentDescriptor: RunContentDescriptor
): List<AnAction> {
disposableDescriptor = contentDescriptor
compilerHelper = ConsoleCompilerHelper(project, module, defaultExecutor, contentDescriptor)
val actionList = arrayListOf<AnAction>(
BuildAndRestartConsoleAction(this),
createConsoleExecAction(consoleExecuteActionHandler),
createCloseAction(defaultExecutor, contentDescriptor)
BuildAndRestartConsoleAction(this),
createConsoleExecAction(consoleExecuteActionHandler),
createCloseAction(defaultExecutor, contentDescriptor)
)
toolbarActions.addAll(actionList)
return actionList
}
override fun createConsoleExecAction(consoleExecuteActionHandler: ProcessBackedConsoleExecuteActionHandler)
= ConsoleExecuteAction(consoleView, consoleExecuteActionHandler, KOTLIN_SHELL_EXECUTE_ACTION_ID, consoleExecuteActionHandler)
override fun createConsoleExecAction(consoleExecuteActionHandler: ProcessBackedConsoleExecuteActionHandler) =
ConsoleExecuteAction(consoleView, consoleExecuteActionHandler, KOTLIN_SHELL_EXECUTE_ACTION_ID, consoleExecuteActionHandler)
override fun constructConsoleTitle(title: String) = "$title (in module ${module.name})"
@@ -260,13 +250,14 @@ class KotlinConsoleRunner(
val indicator = ConsoleIndicatorRenderer(iconWithTooltip)
val editorMarkup = editor.markupModel
val indicatorHighlighter = editorMarkup.addRangeHighlighter(
0, editor.document.textLength, HighlighterLayer.LAST, null, HighlighterTargetArea.LINES_IN_RANGE
0, editor.document.textLength, HighlighterLayer.LAST, null, HighlighterTargetArea.LINES_IN_RANGE
)
return indicatorHighlighter.apply { gutterIconRenderer = indicator }
}
@TestOnly fun dispose() {
@TestOnly
fun dispose() {
processHandler.destroyProcess()
consoleTerminated.await(1, TimeUnit.SECONDS)
Disposer.dispose(disposableDescriptor)
@@ -283,8 +274,12 @@ class KotlinConsoleRunner(
charset = CharsetToolkit.UTF8_CHARSET
isWritable = false
}
val psiFile = (PsiFileFactory.getInstance(project) as PsiFileFactoryImpl).trySetupPsiForFile(virtualFile, KotlinLanguage.INSTANCE, true, false) as KtFile?
?: error("Failed to setup PSI for file:\n$text")
val psiFile = (PsiFileFactory.getInstance(project) as PsiFileFactoryImpl).trySetupPsiForFile(
virtualFile,
KotlinLanguage.INSTANCE,
true,
false
) as KtFile? ?: error("Failed to setup PSI for file:\n$text")
replState.submitLine(psiFile)
configureFileDependencies(psiFile)
@@ -304,12 +299,11 @@ class KotlinConsoleRunner(
}
private fun configureFileDependencies(psiFile: KtFile) {
psiFile.forcedModuleInfo = module.testSourceInfo() ?: module.productionSourceInfo() ?:
NotUnderContentRootModuleInfo
psiFile.forcedModuleInfo = module.testSourceInfo() ?: module.productionSourceInfo() ?: NotUnderContentRootModuleInfo
}
}
class ConsoleScriptDefinitionContributor: ScriptDefinitionSourceAsContributor {
class ConsoleScriptDefinitionContributor : ScriptDefinitionSourceAsContributor {
val definitionsSet = ContainerUtil.newConcurrentSet<ScriptDefinition>()
@@ -1,17 +1,6 @@
/*
* Copyright 2010-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.
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.console
@@ -28,19 +17,18 @@ object ReplColors {
val EDITOR_GUTTER_COLOR: JBColor = JBColor(Gray.xCF, Gray.x31)
val PLACEHOLDER_COLOR: JBColor = JBColor.LIGHT_GRAY
val WARNING_INFO_CONTENT_TYPE: ConsoleViewContentType =
ConsoleViewContentType(
"KOTLIN_CONSOLE_WARNING_INFO",
TextAttributes().apply { fontType = Font.ITALIC; foregroundColor = JBColor.RED }
)
val INITIAL_PROMPT_CONTENT_TYPE: ConsoleViewContentType =
ConsoleViewContentType(
"KOTLIN_CONSOLE_INITIAL_PROMPT",
TextAttributes().apply { fontType = Font.BOLD }
)
val USER_OUTPUT_CONTENT_TYPE: ConsoleViewContentType =
ConsoleViewContentType(
"KOTLIN_CONSOLE_USER_OUTPUT",
TextAttributes().apply { fontType = Font.ITALIC; foregroundColor = Colors.DARK_GREEN }
)
val WARNING_INFO_CONTENT_TYPE: ConsoleViewContentType = ConsoleViewContentType(
"KOTLIN_CONSOLE_WARNING_INFO",
TextAttributes().apply { fontType = Font.ITALIC; foregroundColor = JBColor.RED }
)
val INITIAL_PROMPT_CONTENT_TYPE: ConsoleViewContentType = ConsoleViewContentType(
"KOTLIN_CONSOLE_INITIAL_PROMPT",
TextAttributes().apply { fontType = Font.BOLD }
)
val USER_OUTPUT_CONTENT_TYPE: ConsoleViewContentType = ConsoleViewContentType(
"KOTLIN_CONSOLE_USER_OUTPUT",
TextAttributes().apply { fontType = Font.ITALIC; foregroundColor = Colors.DARK_GREEN }
)
}
@@ -1,17 +1,6 @@
/*
* Copyright 2010-2016 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.
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.console
@@ -35,9 +24,9 @@ import javax.xml.parsers.DocumentBuilderFactory
data class SeverityDetails(val severity: Severity, val description: String, val range: TextRange)
class ReplOutputHandler(
private val runner: KotlinConsoleRunner,
process: Process,
commandLine: String
private val runner: KotlinConsoleRunner,
process: Process,
commandLine: String
) : OSProcessHandler(process, commandLine) {
private var isBuildInfoChecked = false
@@ -58,8 +47,7 @@ class ReplOutputHandler(
handleReplMessage(resultingText)
inputBuffer.setLength(0)
}
}
else {
} else {
super.notifyTextAvailable(text, key)
}
}
@@ -68,8 +56,7 @@ class ReplOutputHandler(
if (text.isBlank()) return
val output = try {
factory.newDocumentBuilder().parse(strToSource(text))
}
catch (e: Exception) {
} catch (e: Exception) {
logError(ReplOutputHandler::class.java, "Couldn't parse REPL output: $text", e)
return
}
@@ -79,17 +66,17 @@ class ReplOutputHandler(
val content = root.textContent.replUnescapeLineBreaks().replNormalizeLineBreaks()
when (outputType) {
INITIAL_PROMPT -> buildWarningIfNeededBeforeInit(content)
HELP_PROMPT -> outputProcessor.printHelp(content)
USER_OUTPUT -> outputProcessor.printUserOutput(content)
REPL_RESULT -> outputProcessor.printResultWithGutterIcon(content)
READLINE_START -> runner.isReadLineMode = true
READLINE_END -> runner.isReadLineMode = false
INITIAL_PROMPT -> buildWarningIfNeededBeforeInit(content)
HELP_PROMPT -> outputProcessor.printHelp(content)
USER_OUTPUT -> outputProcessor.printUserOutput(content)
REPL_RESULT -> outputProcessor.printResultWithGutterIcon(content)
READLINE_START -> runner.isReadLineMode = true
READLINE_END -> runner.isReadLineMode = false
REPL_INCOMPLETE,
COMPILE_ERROR -> outputProcessor.highlightCompilerErrors(createCompilerMessages(content))
RUNTIME_ERROR -> outputProcessor.printRuntimeError("${content.trim()}\n")
INTERNAL_ERROR -> outputProcessor.printInternalErrorMessage(content)
SUCCESS -> runner.commandHistory.lastUnprocessedEntry()?.entryText?.let { runner.successfulLine(it) }
COMPILE_ERROR -> outputProcessor.highlightCompilerErrors(createCompilerMessages(content))
RUNTIME_ERROR -> outputProcessor.printRuntimeError("${content.trim()}\n")
INTERNAL_ERROR -> outputProcessor.printInternalErrorMessage(content)
SUCCESS -> runner.commandHistory.lastUnprocessedEntry()?.entryText?.let { runner.successfulLine(it) }
null -> logError(ReplOutputHandler::class.java, "Unexpected output type:\n$outputType")
}
@@ -113,7 +100,7 @@ class ReplOutputHandler(
val report = factory.newDocumentBuilder().parse(strToSource(runtimeErrorsReport, Charsets.UTF_16))
val entries = report.getElementsByTagName("reportEntry")
for (i in 0..entries.length - 1) {
for (i in 0 until entries.length) {
val reportEntry = entries.item(i) as Element
val severityLevel = reportEntry.getAttribute("severity").toSeverity()
@@ -128,9 +115,9 @@ class ReplOutputHandler(
}
private fun String.toSeverity() = when (this) {
"ERROR" -> Severity.ERROR
"ERROR" -> Severity.ERROR
"WARNING" -> Severity.WARNING
"INFO" -> Severity.INFO
else -> throw IllegalArgumentException("Unsupported Severity: '$this'") // this case shouldn't occur
"INFO" -> Severity.INFO
else -> throw IllegalArgumentException("Unsupported Severity: '$this'") // this case shouldn't occur
}
}
@@ -1,17 +1,6 @@
/*
* Copyright 2010-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.
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.console.actions
@@ -40,7 +29,7 @@ class ConsoleModuleDialog(private val project: Project) {
val moduleGroup = DefaultActionGroup(moduleActions)
val modulePopup = JBPopupFactory.getInstance().createActionGroupPopup(
TITLE, moduleGroup, dataContext, JBPopupFactory.ActionSelectionAid.SPEEDSEARCH, true, ActionPlaces.UNKNOWN
TITLE, moduleGroup, dataContext, JBPopupFactory.ActionSelectionAid.SPEEDSEARCH, true, ActionPlaces.UNKNOWN
)
modulePopup.showCenteredInCurrentWindow(project)
@@ -1,17 +1,6 @@
/*
* Copyright 2010-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.
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.console.actions
@@ -54,7 +43,7 @@ class KtExecuteCommandAction(private val consoleFile: VirtualFile) : AnAction()
}
class BuildAndRestartConsoleAction(
private val runner: KotlinConsoleRunner
private val runner: KotlinConsoleRunner
) : AnAction("Build and restart", "Build module '${runner.module.name}' and restart", AllIcons.Actions.Restart) {
override fun actionPerformed(e: AnActionEvent) = runner.compilerHelper.compileModule()
@@ -1,17 +1,6 @@
/*
* Copyright 2010-2016 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.
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.jsr223
@@ -20,7 +9,6 @@ import org.jetbrains.kotlin.cli.common.repl.KotlinJsr223JvmScriptEngineFactoryBa
import org.jetbrains.kotlin.cli.common.repl.ScriptArgsWithTypes
import org.jetbrains.kotlin.script.util.KotlinJars
import org.jetbrains.kotlin.script.util.scriptCompilationClasspathFromContextOrStlib
import org.jetbrains.kotlin.utils.PathUtil
import javax.script.ScriptContext
import javax.script.ScriptEngine
@@ -28,12 +16,12 @@ import javax.script.ScriptEngine
class KotlinJsr223StandardScriptEngineFactory4Idea : KotlinJsr223JvmScriptEngineFactoryBase() {
override fun getScriptEngine(): ScriptEngine =
KotlinJsr223JvmScriptEngine4Idea(
this,
scriptCompilationClasspathFromContextOrStlib(wholeClasspath = true) + KotlinJars.kotlinScriptStandardJars,
"kotlin.script.templates.standard.ScriptTemplateWithBindings",
{ ctx, argTypes -> ScriptArgsWithTypes(arrayOf(ctx.getBindings(ScriptContext.ENGINE_SCOPE)), argTypes ?: emptyArray()) },
arrayOf(Map::class)
)
KotlinJsr223JvmScriptEngine4Idea(
this,
scriptCompilationClasspathFromContextOrStlib(wholeClasspath = true) + KotlinJars.kotlinScriptStandardJars,
"kotlin.script.templates.standard.ScriptTemplateWithBindings",
{ ctx, argTypes -> ScriptArgsWithTypes(arrayOf(ctx.getBindings(ScriptContext.ENGINE_SCOPE)), argTypes ?: emptyArray()) },
arrayOf(Map::class)
)
}