compiler: cleanup 'public', property access syntax

This commit is contained in:
Dmitry Jemerov
2016-01-07 17:57:35 +01:00
parent b72ea1ff07
commit 117a0d8b7b
488 changed files with 3147 additions and 3287 deletions
@@ -16,7 +16,7 @@
package org.jetbrains.kotlin.cli.common
public val KOTLIN_COMPILER_ENVIRONMENT_KEEPALIVE_PROPERTY = "kotlin.environment.keepalive"
val KOTLIN_COMPILER_ENVIRONMENT_KEEPALIVE_PROPERTY = "kotlin.environment.keepalive"
fun String?.toBooleanLenient(): Boolean? = when (this?.toLowerCase()) {
@@ -16,21 +16,19 @@
package org.jetbrains.kotlin.cli.common.messages
public data class CompilerMessageLocation private constructor(
public val path: String?,
public val line: Int,
public val column: Int,
public val lineContent: String?
data class CompilerMessageLocation private constructor(
val path: String?,
val line: Int,
val column: Int,
val lineContent: String?
) {
override fun toString(): String =
path + (if (line != -1 || column != -1) " ($line:$column)" else "")
companion object {
@JvmField
public val NO_LOCATION: CompilerMessageLocation = CompilerMessageLocation(null, -1, -1, null)
@JvmField val NO_LOCATION: CompilerMessageLocation = CompilerMessageLocation(null, -1, -1, null)
@JvmStatic
public fun create(
@JvmStatic fun create(
path: String?,
line: Int,
column: Int,
@@ -20,7 +20,7 @@ import org.jetbrains.kotlin.modules.Module
import org.jetbrains.kotlin.modules.JavaRootPath
import java.util.*
public class ModuleBuilder(
class ModuleBuilder(
private val name: String,
private val outputDir: String,
private val type: String
@@ -30,19 +30,19 @@ public class ModuleBuilder(
private val javaSourceRoots = ArrayList<JavaRootPath>()
private val friendDirs = ArrayList<String>()
public fun addSourceFiles(pattern: String) {
fun addSourceFiles(pattern: String) {
sourceFiles.add(pattern)
}
public fun addClasspathEntry(name: String) {
fun addClasspathEntry(name: String) {
classpathRoots.add(name)
}
public fun addJavaSourceRoot(rootPath: JavaRootPath) {
fun addJavaSourceRoot(rootPath: JavaRootPath) {
javaSourceRoots.add(rootPath)
}
public fun addFriendDir(friendDir: String) {
fun addFriendDir(friendDir: String) {
friendDirs.add(friendDir)
}
@@ -20,7 +20,7 @@ import java.io.File
import java.io.FileNotFoundException
import java.util.*
public object Main {
object Main {
private val KOTLIN_HOME: File
init {
@@ -99,8 +99,7 @@ public object Main {
runner.run(classpath, arguments)
}
@JvmStatic
public fun main(args: Array<String>) {
@JvmStatic fun main(args: Array<String>) {
try {
run(args)
}
@@ -23,9 +23,9 @@ import org.jetbrains.kotlin.diagnostics.DiagnosticUtils
/**
* This class behaviour is the same as [MessageCollector.report] in [AnalyzerWithCompilerReport.reportDiagnostic].
*/
public class DefaultDiagnosticReporter(override val messageCollector: MessageCollector) : MessageCollectorBasedReporter
class DefaultDiagnosticReporter(override val messageCollector: MessageCollector) : MessageCollectorBasedReporter
public interface MessageCollectorBasedReporter : DiagnosticMessageReporter {
interface MessageCollectorBasedReporter : DiagnosticMessageReporter {
val messageCollector: MessageCollector
@@ -19,6 +19,6 @@ package org.jetbrains.kotlin.cli.common.messages
import com.intellij.psi.PsiFile
import org.jetbrains.kotlin.diagnostics.Diagnostic
public interface DiagnosticMessageReporter {
interface DiagnosticMessageReporter {
fun report(diagnostic: Diagnostic, file: PsiFile, render: String)
}
@@ -24,7 +24,7 @@ import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import java.io.File
import com.intellij.openapi.util.io.FileUtil
public fun OutputFileCollection.writeAll(outputDir: File, report: (sources: List<File>, output: File) -> Unit) {
fun OutputFileCollection.writeAll(outputDir: File, report: (sources: List<File>, output: File) -> Unit) {
for (file in asList()) {
val sources = file.sourceFiles
val output = File(outputDir, file.relativePath)
@@ -35,11 +35,11 @@ public fun OutputFileCollection.writeAll(outputDir: File, report: (sources: List
private val REPORT_NOTHING = { sources: List<File>, output: File -> }
public fun OutputFileCollection.writeAllTo(outputDir: File) {
fun OutputFileCollection.writeAllTo(outputDir: File) {
writeAll(outputDir, REPORT_NOTHING)
}
public fun OutputFileCollection.writeAll(outputDir: File, messageCollector: MessageCollector) {
fun OutputFileCollection.writeAll(outputDir: File, messageCollector: MessageCollector) {
writeAll(outputDir) { sources, output ->
messageCollector.report(CompilerMessageSeverity.OUTPUT, OutputMessageUtil.formatOutputMessage(sources, output), CompilerMessageLocation.NO_LOCATION)
}
@@ -45,7 +45,7 @@ import java.io.File
import java.lang.management.ManagementFactory
import java.util.concurrent.TimeUnit
public open class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
open class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
override fun doExecute(arguments: K2JVMCompilerArguments, services: Services, messageCollector: MessageCollector, rootDisposable: Disposable): ExitCode {
val messageSeverityCollector = MessageSeverityCollector(messageCollector)
@@ -54,7 +54,7 @@ public open class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
else
PathUtil.getKotlinPathsForCompiler()
messageSeverityCollector.report(CompilerMessageSeverity.LOGGING, "Using Kotlin home directory " + paths.getHomePath(), CompilerMessageLocation.NO_LOCATION)
messageSeverityCollector.report(CompilerMessageSeverity.LOGGING, "Using Kotlin home directory " + paths.homePath, CompilerMessageLocation.NO_LOCATION)
PerformanceCounter.setTimeCounterEnabled(arguments.reportPerf);
val configuration = CompilerConfiguration()
@@ -108,7 +108,7 @@ public open class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
for (arg in arguments.freeArgs) {
configuration.addKotlinSourceRoot(arg)
val file = File(arg)
if (file.isDirectory()) {
if (file.isDirectory) {
configuration.addJavaSourceRoot(file)
}
}
@@ -159,14 +159,14 @@ public open class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
messageSeverityCollector.report(CompilerMessageSeverity.WARNING, "The '-d' option with a directory destination is ignored because '-module' is specified", CompilerMessageLocation.NO_LOCATION)
}
val directory = File(arguments.module).getAbsoluteFile().getParentFile()
val directory = File(arguments.module).absoluteFile.parentFile
val compilerConfiguration = KotlinToJVMBytecodeCompiler.createCompilerConfiguration(configuration, moduleScript.getModules(), directory)
val compilerConfiguration = KotlinToJVMBytecodeCompiler.createCompilerConfiguration(configuration, moduleScript.modules, directory)
environment = createCoreEnvironment(rootDisposable, compilerConfiguration)
if (messageSeverityCollector.anyReported(CompilerMessageSeverity.ERROR)) return COMPILATION_ERROR
KotlinToJVMBytecodeCompiler.compileModules(environment, configuration, moduleScript.getModules(), directory, jar, friendPaths, arguments.includeRuntime)
KotlinToJVMBytecodeCompiler.compileModules(environment, configuration, moduleScript.modules, directory, jar, friendPaths, arguments.includeRuntime)
}
else if (arguments.script) {
val scriptArgs = arguments.freeArgs.subList(1, arguments.freeArgs.size)
@@ -200,7 +200,7 @@ public open class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
return OK
}
catch (e: CompilationException) {
messageSeverityCollector.report(CompilerMessageSeverity.EXCEPTION, OutputMessageUtil.renderException(e), MessageUtil.psiElementToMessageLocation(e.getElement()))
messageSeverityCollector.report(CompilerMessageSeverity.EXCEPTION, OutputMessageUtil.renderException(e), MessageUtil.psiElementToMessageLocation(e.element))
return INTERNAL_ERROR
}
@@ -235,18 +235,17 @@ public open class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
private var elapsedJITTime = 0L
private var shouldReportPerf = true
public fun resetInitStartTime() {
fun resetInitStartTime() {
if (initStartNanos == 0L) {
initStartNanos = System.nanoTime()
}
}
@JvmStatic
public fun main(args: Array<String>) {
@JvmStatic fun main(args: Array<String>) {
CLICompiler.doMain(K2JVMCompiler(), args)
}
public fun reportPerf(configuration: CompilerConfiguration, message: String) {
fun reportPerf(configuration: CompilerConfiguration, message: String) {
if (!shouldReportPerf) return
val collector = configuration[CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY]!!
@@ -255,17 +254,17 @@ public open class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
fun reportGCTime(configuration: CompilerConfiguration) {
ManagementFactory.getGarbageCollectorMXBeans().forEach {
val currentTime = it.getCollectionTime()
val elapsedTime = elapsedGCTime.getOrElse(it.getName()) { 0 }
val currentTime = it.collectionTime
val elapsedTime = elapsedGCTime.getOrElse(it.name) { 0 }
val time = currentTime - elapsedTime
reportPerf(configuration, "GC time for ${it.getName()} is $time ms")
elapsedGCTime[it.getName()] = currentTime
reportPerf(configuration, "GC time for ${it.name} is $time ms")
elapsedGCTime[it.name] = currentTime
}
}
fun reportCompilationTime(configuration: CompilerConfiguration) {
val bean = ManagementFactory.getCompilationMXBean() ?: return
val currentTime = bean.getTotalCompilationTime()
val currentTime = bean.totalCompilationTime
reportPerf(configuration, "JIT time is ${currentTime - elapsedJITTime} ms")
elapsedJITTime = currentTime
}
@@ -284,7 +283,7 @@ public open class K2JVMCompiler : CLICompiler<K2JVMCompilerArguments>() {
classpath.addAll(arguments.classpath.split(File.pathSeparatorChar).map { File(it) })
}
if (!arguments.noStdlib) {
classpath.add(paths.getRuntimePath())
classpath.add(paths.runtimePath)
}
return classpath
}
@@ -26,7 +26,7 @@ import java.net.URLClassLoader
import java.util.*
public object PluginCliParser {
object PluginCliParser {
@JvmStatic
fun loadPlugins(arguments: CommonCompilerArguments, configuration: CompilerConfiguration) {
@@ -35,7 +35,7 @@ public object PluginCliParser {
?.map { File(it).toURI().toURL() }
?.toTypedArray()
?: arrayOf<URL>(),
javaClass.getClassLoader()
javaClass.classLoader
)
val componentRegistrars = ServiceLoader.load(ComponentRegistrar::class.java, classLoader).toArrayList()
@@ -93,7 +93,7 @@ public object PluginCliParser {
}
}
private class PluginURLClassLoader(urls: Array<URL>, parent: ClassLoader) : ClassLoader(Thread.currentThread().getContextClassLoader()) {
private class PluginURLClassLoader(urls: Array<URL>, parent: ClassLoader) : ClassLoader(Thread.currentThread().contextClassLoader) {
private val childClassLoader: SelfThenParentURLClassLoader = SelfThenParentURLClassLoader(urls, parent)
@Synchronized
@@ -62,7 +62,7 @@ import kotlin.properties.Delegates
* To mitigate this, CliLightClassGenerationSupport hold a trace that is shared between the analyzer and JetLightClasses
*/
public class CliLightClassGenerationSupport(project: Project) : LightClassGenerationSupport(), CodeAnalyzerInitializer {
class CliLightClassGenerationSupport(project: Project) : LightClassGenerationSupport(), CodeAnalyzerInitializer {
private val psiManager = PsiManager.getInstance(project)
private var bindingContext: BindingContext by Delegates.notNull()
private var module: ModuleDescriptor by Delegates.notNull()
@@ -172,7 +172,7 @@ public class CliLightClassGenerationSupport(project: Project) : LightClassGenera
return NoScopeRecordCliBindingTrace()
}
public class NoScopeRecordCliBindingTrace : CliBindingTrace() {
class NoScopeRecordCliBindingTrace : CliBindingTrace() {
override fun <K, V> record(slice: WritableSlice<K, V>, key: K, value: V) {
if (slice === BindingContext.LEXICAL_SCOPE) {
// In the compiler there's no need to keep scopes
@@ -186,14 +186,14 @@ public class CliLightClassGenerationSupport(project: Project) : LightClassGenera
}
}
public open class CliBindingTrace @TestOnly constructor() : BindingTraceContext() {
open class CliBindingTrace @TestOnly constructor() : BindingTraceContext() {
private var kotlinCodeAnalyzer: KotlinCodeAnalyzer? = null
override fun toString(): String {
return CliBindingTrace::class.java.name
}
public fun setKotlinCodeAnalyzer(kotlinCodeAnalyzer: KotlinCodeAnalyzer) {
fun setKotlinCodeAnalyzer(kotlinCodeAnalyzer: KotlinCodeAnalyzer) {
this.kotlinCodeAnalyzer = kotlinCodeAnalyzer
}
@@ -20,13 +20,13 @@ import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.kotlin.load.kotlin.VirtualFileKotlinClassFinder
import org.jetbrains.kotlin.name.ClassId
public class JvmCliVirtualFileFinder(private val index: JvmDependenciesIndex) : VirtualFileKotlinClassFinder() {
class JvmCliVirtualFileFinder(private val index: JvmDependenciesIndex) : VirtualFileKotlinClassFinder() {
override fun findVirtualFileWithHeader(classId: ClassId): VirtualFile? {
val classFileName = classId.getRelativeClassName().asString().replace('.', '$')
val classFileName = classId.relativeClassName.asString().replace('.', '$')
return index.findClass(classId, acceptedRootTypes = JavaRoot.OnlyBinary) { dir, rootType ->
dir.findChild("$classFileName.class")?.let {
if (it.isValid()) it else null
if (it.isValid) it else null
}
}
}
@@ -20,6 +20,6 @@ import com.intellij.psi.search.GlobalSearchScope
import org.jetbrains.kotlin.load.kotlin.JvmVirtualFileFinder
import org.jetbrains.kotlin.load.kotlin.JvmVirtualFileFinderFactory
public class JvmCliVirtualFileFinderFactory(private val index: JvmDependenciesIndex) : JvmVirtualFileFinderFactory {
class JvmCliVirtualFileFinderFactory(private val index: JvmDependenciesIndex) : JvmVirtualFileFinderFactory {
override fun create(scope: GlobalSearchScope): JvmVirtualFileFinder = JvmCliVirtualFileFinder(index)
}
@@ -24,22 +24,22 @@ import java.util.ArrayList
import java.util.EnumSet
import java.util.HashMap
public data class JavaRoot(public val file: VirtualFile, public val type: JavaRoot.RootType, public val prefixFqName: FqName? = null) {
public enum class RootType {
data class JavaRoot(val file: VirtualFile, val type: JavaRoot.RootType, val prefixFqName: FqName? = null) {
enum class RootType {
SOURCE,
BINARY
}
companion object RootTypes {
public val OnlyBinary: Set<RootType> = EnumSet.of(RootType.BINARY)
public val SourceAndBinary: Set<RootType> = EnumSet.of(RootType.BINARY, RootType.SOURCE)
val OnlyBinary: Set<RootType> = EnumSet.of(RootType.BINARY)
val SourceAndBinary: Set<RootType> = EnumSet.of(RootType.BINARY, RootType.SOURCE)
}
}
// speeds up finding files/classes in classpath/java source roots
// NOT THREADSAFE, needs to be adapted/removed if we want compiler to be multithreaded
// the main idea of this class is for each package to store roots which contains it to avoid excessive file system traversal
public class JvmDependenciesIndex(_roots: List<JavaRoot>) {
class JvmDependenciesIndex(_roots: List<JavaRoot>) {
//these fields are computed based on _roots passed to constructor which are filled in later
private val roots: List<JavaRoot> by lazy { _roots.toList() }
@@ -78,7 +78,7 @@ public class JvmDependenciesIndex(_roots: List<JavaRoot>) {
// findClassGivenDirectory MUST check whether the class with this classId exists in given package
public fun <T : Any> findClass(
fun <T : Any> findClass(
classId: ClassId,
acceptedRootTypes: Set<JavaRoot.RootType> = JavaRoot.SourceAndBinary,
findClassGivenDirectory: (VirtualFile, JavaRoot.RootType) -> T?
@@ -89,7 +89,7 @@ public class JvmDependenciesIndex(_roots: List<JavaRoot>) {
}
}
public fun traverseDirectoriesInPackage(
fun traverseDirectoriesInPackage(
packageFqName: FqName,
acceptedRootTypes: Set<JavaRoot.RootType> = JavaRoot.SourceAndBinary,
continueSearch: (VirtualFile, JavaRoot.RootType) -> Boolean
@@ -23,7 +23,7 @@ import org.jetbrains.kotlin.descriptors.PackagePartProvider
import org.jetbrains.kotlin.load.kotlin.ModuleMapping
import java.io.EOFException
public class JvmPackagePartProvider(val env: KotlinCoreEnvironment) : PackagePartProvider {
class JvmPackagePartProvider(val env: KotlinCoreEnvironment) : PackagePartProvider {
val roots by lazy {
env.configuration.getList(CommonConfigurationKeys.CONTENT_ROOTS).
@@ -33,19 +33,19 @@ import org.jetbrains.kotlin.util.PerformanceCounter
import java.util.ArrayList
import kotlin.properties.Delegates
public class KotlinCliJavaFileManagerImpl(private val myPsiManager: PsiManager)
class KotlinCliJavaFileManagerImpl(private val myPsiManager: PsiManager)
: CoreJavaFileManager(myPsiManager), KotlinCliJavaFileManager {
private val perfCounter = PerformanceCounter.create("Find Java class")
private var index: JvmDependenciesIndex by Delegates.notNull()
public fun initIndex(packagesCache: JvmDependenciesIndex) {
fun initIndex(packagesCache: JvmDependenciesIndex) {
this.index = packagesCache
}
public override fun findClass(classId: ClassId, searchScope: GlobalSearchScope): PsiClass? {
override fun findClass(classId: ClassId, searchScope: GlobalSearchScope): PsiClass? {
return perfCounter.time {
val classNameWithInnerClasses = classId.getRelativeClassName().asString()
val classNameWithInnerClasses = classId.relativeClassName.asString()
index.findClass(classId) { dir, type ->
findClassGivenPackage(searchScope, dir, classNameWithInnerClasses, type)
}
@@ -65,8 +65,8 @@ public class KotlinCliJavaFileManagerImpl(private val myPsiManager: PsiManager)
val classIdAsTopLevelClass = qName.toSafeTopLevelClassId() ?: return@time super.findClasses(qName, scope)
val result = ArrayList<PsiClass>()
val classNameWithInnerClasses = classIdAsTopLevelClass.getRelativeClassName().asString()
index.traverseDirectoriesInPackage(classIdAsTopLevelClass.getPackageFqName()) { dir, rootType ->
val classNameWithInnerClasses = classIdAsTopLevelClass.relativeClassName.asString()
index.traverseDirectoriesInPackage(classIdAsTopLevelClass.packageFqName) { dir, rootType ->
val psiClass = findClassGivenPackage(scope, dir, classNameWithInnerClasses, rootType)
if (psiClass != null) {
result.add(psiClass)
@@ -108,8 +108,8 @@ public class KotlinCliJavaFileManagerImpl(private val myPsiManager: PsiManager)
JavaRoot.RootType.SOURCE -> packageDir.findChild("$topLevelClassName.java")
} ?: return null
if (!vFile.isValid()) {
LOG.error("Invalid child of valid parent: ${vFile.getPath()}; ${packageDir.isValid()} path=${packageDir.getPath()}")
if (!vFile.isValid) {
LOG.error("Invalid child of valid parent: ${vFile.path}; ${packageDir.isValid} path=${packageDir.path}")
return null
}
if (vFile !in scope) {
@@ -124,7 +124,7 @@ public class KotlinCliJavaFileManagerImpl(private val myPsiManager: PsiManager)
private val LOG = Logger.getInstance(KotlinCliJavaFileManagerImpl::class.java)
private fun findClassInPsiFile(classNameWithInnerClassesDotSeparated: String, file: PsiClassOwner): PsiClass? {
for (topLevelClass in file.getClasses()) {
for (topLevelClass in file.classes) {
val candidate = findClassByTopLevelClass(classNameWithInnerClassesDotSeparated, topLevelClass)
if (candidate != null) {
return candidate
@@ -135,11 +135,11 @@ public class KotlinCliJavaFileManagerImpl(private val myPsiManager: PsiManager)
private fun findClassByTopLevelClass(className: String, topLevelClass: PsiClass): PsiClass? {
if (className.indexOf('.') < 0) {
return if (className == topLevelClass.getName()) topLevelClass else null
return if (className == topLevelClass.name) topLevelClass else null
}
val segments = StringUtil.split(className, ".").iterator()
if (!segments.hasNext() || segments.next() != topLevelClass.getName()) {
if (!segments.hasNext() || segments.next() != topLevelClass.name) {
return null
}
var curClass = topLevelClass
@@ -94,7 +94,7 @@ import org.jetbrains.kotlin.utils.PathUtil
import java.io.File
import java.util.*
public class KotlinCoreEnvironment private constructor(
class KotlinCoreEnvironment private constructor(
parentDisposable: Disposable,
applicationEnvironment: JavaCoreApplicationEnvironment,
configuration: CompilerConfiguration
@@ -108,7 +108,7 @@ public class KotlinCoreEnvironment private constructor(
private val sourceFiles = ArrayList<KtFile>()
private val javaRoots = ArrayList<JavaRoot>()
public val configuration: CompilerConfiguration = configuration.copy().let {
val configuration: CompilerConfiguration = configuration.copy().let {
it.setReadOnly(true)
it
}
@@ -118,7 +118,7 @@ public class KotlinCoreEnvironment private constructor(
}
init {
val project = projectEnvironment.getProject()
val project = projectEnvironment.project
project.registerService(DeclarationProviderFactoryService::class.java, CliDeclarationProviderFactoryService(sourceFiles))
project.registerService(ModuleVisibilityManager::class.java, CliModuleVisibilityManagerImpl())
@@ -136,7 +136,7 @@ public class KotlinCoreEnvironment private constructor(
}))
sourceFiles.sortedWith(object : Comparator<KtFile> {
override fun compare(o1: KtFile, o2: KtFile): Int {
return o1.getVirtualFile().getPath().compareTo(o2.getVirtualFile().getPath(), ignoreCase = true)
return o1.virtualFile.path.compareTo(o2.virtualFile.path, ignoreCase = true)
}
})
@@ -157,20 +157,20 @@ public class KotlinCoreEnvironment private constructor(
}
private val applicationEnvironment: CoreApplicationEnvironment
get() = projectEnvironment.getEnvironment()
get() = projectEnvironment.environment
public val application: MockApplication
get() = applicationEnvironment.getApplication()
val application: MockApplication
get() = applicationEnvironment.application
public val project: Project
get() = projectEnvironment.getProject()
val project: Project
get() = projectEnvironment.project
public val sourceLinesOfCode: Int by lazy { countLinesOfCode(sourceFiles) }
val sourceLinesOfCode: Int by lazy { countLinesOfCode(sourceFiles) }
public fun countLinesOfCode(sourceFiles: List<KtFile>): Int =
fun countLinesOfCode(sourceFiles: List<KtFile>): Int =
sourceFiles.sumBy {
val text = it.getText()
StringUtil.getLineBreakCount(it.getText()) + (if (StringUtil.endsWithLineBreak(text)) 0 else 1)
val text = it.text
StringUtil.getLineBreakCount(it.text) + (if (StringUtil.endsWithLineBreak(text)) 0 else 1)
}
private fun fillClasspath(configuration: CompilerConfiguration) {
@@ -203,10 +203,10 @@ public class KotlinCoreEnvironment private constructor(
fun contentRootToVirtualFile(root: JvmContentRoot): VirtualFile? {
when (root) {
is JvmClasspathRoot -> {
return if (root.file.isFile()) findJarRoot(root) else findLocalDirectory(root)
return if (root.file.isFile) findJarRoot(root) else findLocalDirectory(root)
}
is JavaSourceRoot -> {
return if (root.file.isDirectory()) findLocalDirectory(root) else null
return if (root.file.isDirectory) findLocalDirectory(root) else null
}
else -> throw IllegalStateException("Unexpected root: $root")
}
@@ -214,7 +214,7 @@ public class KotlinCoreEnvironment private constructor(
private fun findLocalDirectory(root: JvmContentRoot): VirtualFile? {
val path = root.file
val localFile = applicationEnvironment.getLocalFileSystem().findFileByPath(path.getAbsolutePath())
val localFile = applicationEnvironment.localFileSystem.findFileByPath(path.absolutePath)
if (localFile == null) {
report(WARNING, "Classpath entry points to a non-existent location: $path")
return null
@@ -224,7 +224,7 @@ public class KotlinCoreEnvironment private constructor(
private fun findJarRoot(root: JvmClasspathRoot): VirtualFile? {
val path = root.file
val jarFile = applicationEnvironment.getJarFileSystem().findFileByPath("${path}!/")
val jarFile = applicationEnvironment.jarFileSystem.findFileByPath("${path}!/")
if (jarFile == null) {
report(WARNING, "Classpath entry points to a file that is not a JAR archive: $path")
return null
@@ -244,7 +244,7 @@ public class KotlinCoreEnvironment private constructor(
return uniqueSourceRoots
}
public fun getSourceFiles(): List<KtFile> = sourceFiles
fun getSourceFiles(): List<KtFile> = sourceFiles
private fun report(severity: CompilerMessageSeverity, message: String) {
val messageCollector = configuration.get(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY)
@@ -258,8 +258,7 @@ public class KotlinCoreEnvironment private constructor(
private var ourApplicationEnvironment: JavaCoreApplicationEnvironment? = null
private var ourProjectCount = 0
@JvmStatic
public fun createForProduction(
@JvmStatic fun createForProduction(
parentDisposable: Disposable, configuration: CompilerConfiguration, configFilePaths: List<String>
): KotlinCoreEnvironment {
val appEnv = getOrCreateApplicationEnvironmentForProduction(configuration, configFilePaths)
@@ -287,8 +286,7 @@ public class KotlinCoreEnvironment private constructor(
}
@TestOnly
@JvmStatic
public fun createForTests(
@JvmStatic fun createForTests(
parentDisposable: Disposable, configuration: CompilerConfiguration, extensionConfigs: List<String>
): KotlinCoreEnvironment {
// Tests are supposed to create a single project and dispose it right after use
@@ -296,7 +294,7 @@ public class KotlinCoreEnvironment private constructor(
}
// used in the daemon for jar cache cleanup
public val applicationEnvironment: JavaCoreApplicationEnvironment? get() = ourApplicationEnvironment
val applicationEnvironment: JavaCoreApplicationEnvironment? get() = ourApplicationEnvironment
private fun getOrCreateApplicationEnvironmentForProduction(configuration: CompilerConfiguration, configFilePaths: List<String>): JavaCoreApplicationEnvironment {
synchronized (APPLICATION_LOCK) {
@@ -317,11 +315,11 @@ public class KotlinCoreEnvironment private constructor(
}
}
public fun disposeApplicationEnvironment() {
fun disposeApplicationEnvironment() {
synchronized (APPLICATION_LOCK) {
val environment = ourApplicationEnvironment ?: return
ourApplicationEnvironment = null
Disposer.dispose(environment.getParentDisposable())
Disposer.dispose(environment.parentDisposable)
}
}
@@ -356,15 +354,15 @@ public class KotlinCoreEnvironment private constructor(
private fun registerApplicationExtensionPointsAndExtensionsFrom(configuration: CompilerConfiguration, configFilePath: String) {
val locator = configuration.get(JVMConfigurationKeys.COMPILER_JAR_LOCATOR)
var pluginRoot = if (locator == null) PathUtil.getPathUtilJar() else locator.getCompilerJar()
var pluginRoot = if (locator == null) PathUtil.getPathUtilJar() else locator.compilerJar
val app = ApplicationManager.getApplication()
val parentFile = pluginRoot.getParentFile()
val parentFile = pluginRoot.parentFile
if (pluginRoot.isDirectory() && app != null && app.isUnitTestMode()
&& FileUtil.toCanonicalPath(parentFile.getPath()).endsWith("out/production")) {
if (pluginRoot.isDirectory && app != null && app.isUnitTestMode
&& FileUtil.toCanonicalPath(parentFile.path).endsWith("out/production")) {
// hack for load extensions when compiler run directly from out directory(e.g. in tests)
val srcDir = parentFile.getParentFile().getParentFile()
val srcDir = parentFile.parentFile.parentFile
pluginRoot = File(srcDir, "idea/src")
}
@@ -378,14 +376,13 @@ public class KotlinCoreEnvironment private constructor(
}
// made public for Upsource
@JvmStatic
public fun registerApplicationServices(applicationEnvironment: JavaCoreApplicationEnvironment) {
@JvmStatic fun registerApplicationServices(applicationEnvironment: JavaCoreApplicationEnvironment) {
with(applicationEnvironment) {
registerFileType(KotlinFileType.INSTANCE, "kt")
registerFileType(KotlinFileType.INSTANCE, KotlinParserDefinition.STD_SCRIPT_SUFFIX)
registerParserDefinition(KotlinParserDefinition())
getApplication().registerService(KotlinBinaryClassCache::class.java, KotlinBinaryClassCache())
getApplication().registerService(JavaClassSupers::class.java, JavaClassSupersImpl::class.java)
application.registerService(KotlinBinaryClassCache::class.java, KotlinBinaryClassCache())
application.registerService(JavaClassSupers::class.java, JavaClassSupersImpl::class.java)
}
}
@@ -395,9 +392,8 @@ public class KotlinCoreEnvironment private constructor(
}
// made public for Upsource
@JvmStatic
public fun registerProjectServices(projectEnvironment: JavaCoreProjectEnvironment) {
with (projectEnvironment.getProject()) {
@JvmStatic fun registerProjectServices(projectEnvironment: JavaCoreProjectEnvironment) {
with (projectEnvironment.project) {
registerService(KotlinScriptDefinitionProvider::class.java, KotlinScriptDefinitionProvider())
registerService(KotlinJavaPsiFacade::class.java, KotlinJavaPsiFacade(this))
registerService(KtLightClassForFacade.FacadeStubCache::class.java, KtLightClassForFacade.FacadeStubCache(this))
@@ -405,7 +401,7 @@ public class KotlinCoreEnvironment private constructor(
}
private fun registerProjectServicesForCLI(projectEnvironment: JavaCoreProjectEnvironment) {
with (projectEnvironment.getProject()) {
with (projectEnvironment.project) {
registerService(CoreJavaFileManager::class.java, ServiceManager.getService(this, JavaFileManager::class.java) as CoreJavaFileManager)
val cliLightClassGenerationSupport = CliLightClassGenerationSupport(this)
@@ -25,5 +25,5 @@ open class KotlinCoreProjectEnvironment(
disposable: Disposable,
applicationEnvironment: JavaCoreApplicationEnvironment
) : JavaCoreProjectEnvironment(disposable, applicationEnvironment) {
override fun createCoreFileManager() = KotlinCliJavaFileManagerImpl(PsiManager.getInstance(getProject()))
override fun createCoreFileManager() = KotlinCliJavaFileManagerImpl(PsiManager.getInstance(project))
}
@@ -21,29 +21,27 @@ import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.config.ContentRoot
import java.io.File
public data class JvmClasspathRoot(public override val file: File): JvmContentRoot
data class JvmClasspathRoot(override val file: File): JvmContentRoot
public data class JavaSourceRoot(public override val file: File, public val packagePrefix: String?): JvmContentRoot
data class JavaSourceRoot(override val file: File, val packagePrefix: String?): JvmContentRoot
public interface JvmContentRoot : ContentRoot {
public val file: File
interface JvmContentRoot : ContentRoot {
val file: File
}
public fun CompilerConfiguration.addJvmClasspathRoot(file: File) {
fun CompilerConfiguration.addJvmClasspathRoot(file: File) {
add(CommonConfigurationKeys.CONTENT_ROOTS, JvmClasspathRoot(file))
}
public fun CompilerConfiguration.addJvmClasspathRoots(files: List<File>): Unit = files.forEach { addJvmClasspathRoot(it) }
fun CompilerConfiguration.addJvmClasspathRoots(files: List<File>): Unit = files.forEach { addJvmClasspathRoot(it) }
public val CompilerConfiguration.jvmClasspathRoots: List<File>
val CompilerConfiguration.jvmClasspathRoots: List<File>
get() {
return get(CommonConfigurationKeys.CONTENT_ROOTS)?.filterIsInstance<JvmClasspathRoot>()?.map { it.file } ?: emptyList()
}
@JvmOverloads
public fun CompilerConfiguration.addJavaSourceRoot(file: File, packagePrefix: String? = null) {
@JvmOverloads fun CompilerConfiguration.addJavaSourceRoot(file: File, packagePrefix: String? = null) {
add(CommonConfigurationKeys.CONTENT_ROOTS, JavaSourceRoot(file, packagePrefix))
}
@JvmOverloads
public fun CompilerConfiguration.addJavaSourceRoots(files: List<File>, packagePrefix: String? = null): Unit = files.forEach { addJavaSourceRoot(it, packagePrefix) }
@JvmOverloads fun CompilerConfiguration.addJavaSourceRoots(files: List<File>, packagePrefix: String? = null): Unit = files.forEach { addJavaSourceRoot(it, packagePrefix) }
@@ -18,4 +18,4 @@ package org.jetbrains.kotlin.cli.jvm.config
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment
public fun KotlinCoreEnvironment.getModuleName(): String = configuration.get(JVMConfigurationKeys.MODULE_NAME)!!
fun KotlinCoreEnvironment.getModuleName(): String = configuration.get(JVMConfigurationKeys.MODULE_NAME)!!
@@ -18,6 +18,6 @@ package org.jetbrains.kotlin.cli.jvm.repl.messages
import org.jetbrains.kotlin.cli.common.messages.DiagnosticMessageReporter
public interface DiagnosticMessageHolder : DiagnosticMessageReporter {
interface DiagnosticMessageHolder : DiagnosticMessageReporter {
val renderedDiagnostics: String
}
@@ -20,7 +20,7 @@ import org.jetbrains.kotlin.utils.rethrow
import java.io.PrintWriter
import java.io.StringWriter
public class ReplErrorLogger(private val ideMode: Boolean, private val replWriter: ReplWriter) {
class ReplErrorLogger(private val ideMode: Boolean, private val replWriter: ReplWriter) {
fun logException(e: Throwable?) {
if (ideMode) {
val errorStringWriter = StringWriter()
@@ -23,7 +23,7 @@ import org.jetbrains.kotlin.diagnostics.DiagnosticUtils
import org.w3c.dom.ls.DOMImplementationLS
import javax.xml.parsers.DocumentBuilderFactory
public class ReplIdeDiagnosticMessageHolder : DiagnosticMessageHolder {
class ReplIdeDiagnosticMessageHolder : DiagnosticMessageHolder {
private val diagnostics = arrayListOf<Pair<Diagnostic, String>>()
override fun report(diagnostic: Diagnostic, file: PsiFile, render: String) {
@@ -19,7 +19,7 @@ package org.jetbrains.kotlin.cli.jvm.repl.messages
import java.io.ByteArrayOutputStream
import java.io.InputStream
public class ReplSystemInWrapper(
class ReplSystemInWrapper(
private val stdin: InputStream,
private val replWriter: ReplWriter
) : InputStream() {
@@ -23,7 +23,7 @@ import java.io.PrintStream
val END_LINE: String = LineSeparator.getSystemLineSeparator().separatorString
val XML_PREAMBLE = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
public class ReplSystemOutWrapperForIde(standardOut: PrintStream) : PrintStream(standardOut, true), ReplWriter {
class ReplSystemOutWrapperForIde(standardOut: PrintStream) : PrintStream(standardOut, true), ReplWriter {
private enum class EscapeType {
INITIAL_PROMPT,
HELP_PROMPT,
@@ -21,7 +21,7 @@ import java.io.ByteArrayOutputStream
import java.io.PrintStream
import java.nio.ByteBuffer
public class ReplTerminalDiagnosticMessageHolder() : MessageCollectorBasedReporter, DiagnosticMessageHolder {
class ReplTerminalDiagnosticMessageHolder() : MessageCollectorBasedReporter, DiagnosticMessageHolder {
private val outputStream = ByteArrayOutputStream()
override val messageCollector = PrintingMessageCollector(PrintStream(outputStream), MessageRenderer.WITHOUT_PATHS, false)
@@ -23,8 +23,8 @@ import java.io.ByteArrayInputStream
import javax.xml.parsers.DocumentBuilderFactory
// using '#' to avoid collisions with xml escaping
public val SOURCE_CHARS: Array<String> = arrayOf("\n", "#")
public val XML_REPLACEMENTS: Array<String> = arrayOf("#n", "#diez")
val SOURCE_CHARS: Array<String> = arrayOf("\n", "#")
val XML_REPLACEMENTS: Array<String> = arrayOf("#n", "#diez")
fun parseXml(inputMessage: String): String {
fun strToSource(s: String) = InputSource(ByteArrayInputStream(s.toByteArray()))
@@ -21,7 +21,7 @@ import jline.console.history.FileHistory
import org.jetbrains.kotlin.cli.jvm.repl.ReplFromTerminal
import java.io.File
public class ConsoleReplCommandReader : ReplCommandReader {
class ConsoleReplCommandReader : ReplCommandReader {
private val consoleReader = ConsoleReader("kotlin", System.`in`, System.`out`, null).apply {
isHistoryEnabled = true
expandEvents = false
@@ -18,7 +18,7 @@ package org.jetbrains.kotlin.cli.jvm.repl.reader
import org.jetbrains.kotlin.cli.jvm.repl.ReplFromTerminal
public class IdeReplCommandReader : ReplCommandReader {
class IdeReplCommandReader : ReplCommandReader {
override fun readLine(next: ReplFromTerminal.WhatNextAfterOneLine) = readLine()
override fun flushHistory() = Unit
}
@@ -18,7 +18,7 @@ package org.jetbrains.kotlin.cli.jvm.repl.reader
import org.jetbrains.kotlin.cli.jvm.repl.ReplFromTerminal
public interface ReplCommandReader {
public fun readLine(next: ReplFromTerminal.WhatNextAfterOneLine): String?
public fun flushHistory()
interface ReplCommandReader {
fun readLine(next: ReplFromTerminal.WhatNextAfterOneLine): String?
fun flushHistory()
}