From d517276a06bebbf5890a0c2709d8fc356ca2c8d0 Mon Sep 17 00:00:00 2001 From: Mikhail Glukhikh Date: Mon, 6 May 2019 17:13:33 +0300 Subject: [PATCH] Apply "unnamed boolean literal" to idea & J2K + other style fixes --- .../fir/backend/Fir2IrDeclarationStorage.kt | 2 +- .../deserialization/FirMemberDeserializer.kt | 44 +++--- .../kotlin/fir/resolve/calls/Synthetics.kt | 30 ++-- .../impl/FirLibrarySymbolProviderImpl.kt | 6 +- .../transformers/FirBodyResolveTransformer.kt | 8 +- .../navigation/SourceNavigationHelper.kt | 14 +- .../idea/stubindex/KotlinSourceFilterScope.kt | 103 ++++++++++--- .../GroovyBuildScriptManipulator.kt | 23 ++- .../compilation/CodeFragmentCompiler.kt | 13 +- .../KotlinJsr223JvmScriptEngine4Idea.kt | 45 +++--- .../kotlin/idea/parameterInfo/TypeHints.kt | 2 +- .../idea/quickfix/AddAnnotationTargetFix.kt | 2 +- .../callableBuilder/CallableInfo.kt | 2 +- .../crossLanguage/ChangeMethodParameters.kt | 4 +- .../KotlinChangeSignatureUsageProcessor.kt | 7 +- .../KotlinAwareDelegatingMoveDestination.kt | 21 ++- .../MoveKotlinDeclarationsProcessor.kt | 65 ++++---- .../idea/refactoring/move/moveFilesUtil.kt | 66 ++++---- .../kotlin/idea/refactoring/move/moveUtils.kt | 2 +- .../kotlin/idea/refactoring/renderingUtils.kt | 30 ++-- .../kotlin/j2k/AnnotationConverter.kt | 4 +- .../org/jetbrains/kotlin/j2k/CodeConverter.kt | 2 +- j2k/src/org/jetbrains/kotlin/j2k/Converter.kt | 24 +-- .../jetbrains/kotlin/j2k/propertyDetection.kt | 142 ++++++++++-------- .../src/org/jetbrains/kotlin/nj2k/psiUtils.kt | 5 +- 25 files changed, 388 insertions(+), 278 deletions(-) diff --git a/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/Fir2IrDeclarationStorage.kt b/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/Fir2IrDeclarationStorage.kt index b2b526f188b..dae6c41b0da 100644 --- a/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/Fir2IrDeclarationStorage.kt +++ b/compiler/fir/fir2ir/src/org/jetbrains/kotlin/fir/backend/Fir2IrDeclarationStorage.kt @@ -300,7 +300,7 @@ class Fir2IrDeclarationStorage( startOffset, endOffset, origin, symbol, constructor.name, constructor.visibility, constructor.returnTypeRef.toIrType(session, this), - false, false, isPrimary + isInline = false, isExternal = false, isPrimary = isPrimary ).bindAndDeclareParameters(constructor, descriptor, setParent, shouldLeaveScope) } } diff --git a/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/deserialization/FirMemberDeserializer.kt b/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/deserialization/FirMemberDeserializer.kt index b349a5e3945..68f38d992e1 100644 --- a/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/deserialization/FirMemberDeserializer.kt +++ b/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/deserialization/FirMemberDeserializer.kt @@ -167,18 +167,18 @@ class FirMemberDeserializer(private val c: FirDeserializationContext) { callableName, ProtoEnumFlags.visibility(Flags.VISIBILITY.get(flags)), ProtoEnumFlags.modality(Flags.MODALITY.get(flags)), - Flags.IS_EXPECT_PROPERTY.get(flags), - false, - false, - Flags.IS_CONST.get(flags), - Flags.IS_LATEINIT.get(flags), - proto.receiverType(c.typeTable)?.toTypeRef(local), - returnTypeRef, - Flags.IS_VAR.get(flags), - null, - FirDefaultPropertyGetter(c.session, null, returnTypeRef, ProtoEnumFlags.visibility(Flags.VISIBILITY.get(getterFlags))), - FirDefaultPropertySetter(c.session, null, returnTypeRef, ProtoEnumFlags.visibility(Flags.VISIBILITY.get(setterFlags))), - null + isExpect = Flags.IS_EXPECT_PROPERTY.get(flags), + isActual = false, + isOverride = false, + isConst = Flags.IS_CONST.get(flags), + isLateInit = Flags.IS_LATEINIT.get(flags), + receiverTypeRef = proto.receiverType(c.typeTable)?.toTypeRef(local), + returnTypeRef = returnTypeRef, + isVar = Flags.IS_VAR.get(flags), + initializer = null, + getter = FirDefaultPropertyGetter(c.session, null, returnTypeRef, ProtoEnumFlags.visibility(Flags.VISIBILITY.get(getterFlags))), + setter = FirDefaultPropertySetter(c.session, null, returnTypeRef, ProtoEnumFlags.visibility(Flags.VISIBILITY.get(setterFlags))), + delegate = null ).apply { typeParameters += local.typeDeserializer.ownTypeParameters.map { it.firUnsafe() } annotations += c.annotationDeserializer.loadPropertyAnnotations(proto, local.nameResolver) @@ -209,16 +209,16 @@ class FirMemberDeserializer(private val c: FirDeserializationContext) { ProtoEnumFlags.visibility(Flags.VISIBILITY.get(flags)), ProtoEnumFlags.modality(Flags.MODALITY.get(flags)), Flags.IS_EXPECT_FUNCTION.get(flags), - false, - false, - Flags.IS_OPERATOR.get(flags), - Flags.IS_INFIX.get(flags), - Flags.IS_INLINE.get(flags), - Flags.IS_TAILREC.get(flags), - Flags.IS_EXTERNAL_FUNCTION.get(flags), - Flags.IS_SUSPEND.get(flags), - proto.receiverType(local.typeTable)?.toTypeRef(local), - proto.returnType(local.typeTable).toTypeRef(local) + isActual = false, + isOverride = false, + isOperator = Flags.IS_OPERATOR.get(flags), + isInfix = Flags.IS_INFIX.get(flags), + isInline = Flags.IS_INLINE.get(flags), + isTailRec = Flags.IS_TAILREC.get(flags), + isExternal = Flags.IS_EXTERNAL_FUNCTION.get(flags), + isSuspend = Flags.IS_SUSPEND.get(flags), + receiverTypeRef = proto.receiverType(local.typeTable)?.toTypeRef(local), + returnTypeRef = proto.returnType(local.typeTable).toTypeRef(local) ).apply { typeParameters += local.typeDeserializer.ownTypeParameters.map { it.firUnsafe() } valueParameters += local.memberDeserializer.valueParameters(proto.valueParameterList) diff --git a/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/calls/Synthetics.kt b/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/calls/Synthetics.kt index a88a6307017..2e55c6b607a 100644 --- a/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/calls/Synthetics.kt +++ b/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/calls/Synthetics.kt @@ -22,7 +22,11 @@ interface SyntheticSymbol : ConeSymbol class SyntheticPropertySymbol(callableId: CallableId) : FirPropertySymbol(callableId), SyntheticSymbol -class FirSyntheticPropertiesScope(val session: FirSession, val baseScope: FirScope, val typeCalculator: ReturnTypeCalculator) : FirScope { +class FirSyntheticPropertiesScope( + val session: FirSession, + private val baseScope: FirScope, + private val typeCalculator: ReturnTypeCalculator +) : FirScope { val synthetic: MutableMap = mutableMapOf() @@ -47,18 +51,18 @@ class FirSyntheticPropertiesScope(val session: FirSession, val baseScope: FirSco name, fir.visibility, fir.modality, - false, - false, - false, - false, - false, - null, - returnTypeRef, - true, - null, - FirDefaultPropertyGetter(session, null, returnTypeRef, fir.visibility), - FirDefaultPropertySetter(session, null, returnTypeRef, fir.visibility), - null + isExpect = false, + isActual = false, + isOverride = false, + isConst = false, + isLateInit = false, + receiverTypeRef = null, + returnTypeRef = returnTypeRef, + isVar = true, + initializer = null, + getter = FirDefaultPropertyGetter(session, null, returnTypeRef, fir.visibility), + setter = FirDefaultPropertySetter(session, null, returnTypeRef, fir.visibility), + delegate = null ) return processor(synthetic) } diff --git a/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/impl/FirLibrarySymbolProviderImpl.kt b/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/impl/FirLibrarySymbolProviderImpl.kt index 00d3fd2094e..15b9a5244f5 100644 --- a/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/impl/FirLibrarySymbolProviderImpl.kt +++ b/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/impl/FirLibrarySymbolProviderImpl.kt @@ -169,9 +169,9 @@ class FirLibrarySymbolProviderImpl(val session: FirSession) : FirSymbolProvider relativeClassName.shortName(), Visibilities.PUBLIC, Modality.OPEN, - false, - false, - ClassKind.CLASS, + isExpect = false, + isActual = false, + classKind = ClassKind.CLASS, isInner = false, isCompanion = false, isData = false, diff --git a/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/transformers/FirBodyResolveTransformer.kt b/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/transformers/FirBodyResolveTransformer.kt index 5d8c7a2953d..22507ae8c18 100644 --- a/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/transformers/FirBodyResolveTransformer.kt +++ b/compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/transformers/FirBodyResolveTransformer.kt @@ -435,10 +435,10 @@ open class FirBodyResolveTransformer(val session: FirSession, val implicitTypeOn null, Name.identifier("it"), FirResolvedTypeRefImpl(session, null, parameters.single(), emptyList()), - null, - false, - false, - false + defaultValue = null, + isCrossinline = false, + isNoinline = false, + isVararg = false ) else -> null } diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/navigation/SourceNavigationHelper.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/navigation/SourceNavigationHelper.kt index 7bdbe9d83be..a142bf5e500 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/navigation/SourceNavigationHelper.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/navigation/SourceNavigationHelper.kt @@ -85,7 +85,7 @@ object SourceNavigationHelper { private fun Collection.union(): List = if (this.isNotEmpty()) listOf(GlobalSearchScope.union(this.toTypedArray())) else emptyList() - private fun haveRenamesInImports(files: Collection) = files.any { it.importDirectives.any { it.aliasName != null } } + private fun haveRenamesInImports(files: Collection) = files.any { file -> file.importDirectives.any { it.aliasName != null } } private fun findSpecialProperty(memberName: Name, containingClass: KtClass): KtNamedDeclaration? { // property constructor parameters @@ -191,7 +191,7 @@ object SourceNavigationHelper { ): T? { val classFqName = entity.fqName ?: return null return targetScopes(entity, navigationKind).firstNotNullResult { scope -> - index.get(classFqName.asString(), entity.project, scope).sortedBy { it.isExpectDeclaration() }.firstOrNull() + index.get(classFqName.asString(), entity.project, scope).minBy { it.isExpectDeclaration() } } } @@ -273,7 +273,15 @@ object SourceNavigationHelper { SourceNavigationHelper.NavigationKind.SOURCES_TO_CLASS_FILES -> { val file = from.containingFile if (file is KtFile && file.isCompiled) return from - if (!ProjectRootsUtil.isInContent(from, false, true, false, true, false)) return from + if (!ProjectRootsUtil.isInContent( + from, + includeProjectSource = false, + includeLibrarySource = true, + includeLibraryClasses = false, + includeScriptDependencies = true, + includeScriptsOutsideSourceRoots = false + ) + ) return from if (KtPsiUtil.isLocal(from)) return from } } diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinSourceFilterScope.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinSourceFilterScope.kt index 0588ad02a86..556cee11ec9 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinSourceFilterScope.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinSourceFilterScope.kt @@ -85,50 +85,109 @@ class KotlinSourceFilterScope private constructor( companion object { @JvmStatic - fun sourcesAndLibraries(delegate: GlobalSearchScope, project: Project) = create(delegate, true, true, true, true, true, project) + fun sourcesAndLibraries(delegate: GlobalSearchScope, project: Project) = create( + delegate, + includeProjectSourceFiles = true, + includeLibrarySourceFiles = true, + includeClassFiles = true, + includeScriptDependencies = true, + includeScriptsOutsideSourceRoots = true, + project = project + ) @JvmStatic - fun sourceAndClassFiles(delegate: GlobalSearchScope, project: Project) = create(delegate, true, false, true, true, true, project) + fun sourceAndClassFiles(delegate: GlobalSearchScope, project: Project) = create( + delegate, + includeProjectSourceFiles = true, + includeLibrarySourceFiles = false, + includeClassFiles = true, + includeScriptDependencies = true, + includeScriptsOutsideSourceRoots = true, + project = project + ) @JvmStatic - fun projectSourceAndClassFiles(delegate: GlobalSearchScope, project: Project) = create(delegate, true, false, true, false, true, project) + fun projectSourceAndClassFiles(delegate: GlobalSearchScope, project: Project) = create( + delegate, + includeProjectSourceFiles = true, + includeLibrarySourceFiles = false, + includeClassFiles = true, + includeScriptDependencies = false, + includeScriptsOutsideSourceRoots = true, + project = project + ) @JvmStatic - fun projectSources(delegate: GlobalSearchScope, project: Project) = create(delegate, true, false, false, false, true, project) + fun projectSources(delegate: GlobalSearchScope, project: Project) = create( + delegate, + includeProjectSourceFiles = true, + includeLibrarySourceFiles = false, + includeClassFiles = false, + includeScriptDependencies = false, + includeScriptsOutsideSourceRoots = true, + project = project + ) @JvmStatic - fun librarySources(delegate: GlobalSearchScope, project: Project) = create(delegate, false, true, false, true, false, project) + fun librarySources(delegate: GlobalSearchScope, project: Project) = create( + delegate, + includeProjectSourceFiles = false, + includeLibrarySourceFiles = true, + includeClassFiles = false, + includeScriptDependencies = true, + includeScriptsOutsideSourceRoots = false, + project = project + ) @JvmStatic - fun libraryClassFiles(delegate: GlobalSearchScope, project: Project) = create(delegate, false, false, true, true, false, project) + fun libraryClassFiles(delegate: GlobalSearchScope, project: Project) = create( + delegate, + includeProjectSourceFiles = false, + includeLibrarySourceFiles = false, + includeClassFiles = true, + includeScriptDependencies = true, + includeScriptsOutsideSourceRoots = false, + project = project + ) @JvmStatic - fun projectAndLibrariesSources(delegate: GlobalSearchScope, project: Project) = create(delegate, true, true, false, false, true, project) + fun projectAndLibrariesSources(delegate: GlobalSearchScope, project: Project) = create( + delegate, + includeProjectSourceFiles = true, + includeLibrarySourceFiles = true, + includeClassFiles = false, + includeScriptDependencies = false, + includeScriptsOutsideSourceRoots = true, + project = project + ) private fun create( - delegate: GlobalSearchScope, - includeProjectSourceFiles: Boolean, - includeLibrarySourceFiles: Boolean, - includeClassFiles: Boolean, - includeScriptDependencies: Boolean, - includeScriptsOutsideSourceRoots: Boolean, - project: Project + delegate: GlobalSearchScope, + includeProjectSourceFiles: Boolean, + includeLibrarySourceFiles: Boolean, + includeClassFiles: Boolean, + includeScriptDependencies: Boolean, + includeScriptsOutsideSourceRoots: Boolean, + project: Project ): GlobalSearchScope { if (delegate === GlobalSearchScope.EMPTY_SCOPE) return delegate if (delegate is KotlinSourceFilterScope) { return KotlinSourceFilterScope( - delegate.myBaseScope, - includeProjectSourceFiles = delegate.includeProjectSourceFiles && includeProjectSourceFiles, - includeLibrarySourceFiles = delegate.includeLibrarySourceFiles && includeLibrarySourceFiles, - includeClassFiles = delegate.includeClassFiles && includeClassFiles, - includeScriptDependencies = delegate.includeScriptDependencies && includeScriptDependencies, - includeScriptsOutsideSourceRoots = delegate.includeScriptsOutsideSourceRoots && includeScriptsOutsideSourceRoots, - project = project + delegate.myBaseScope, + includeProjectSourceFiles = delegate.includeProjectSourceFiles && includeProjectSourceFiles, + includeLibrarySourceFiles = delegate.includeLibrarySourceFiles && includeLibrarySourceFiles, + includeClassFiles = delegate.includeClassFiles && includeClassFiles, + includeScriptDependencies = delegate.includeScriptDependencies && includeScriptDependencies, + includeScriptsOutsideSourceRoots = delegate.includeScriptsOutsideSourceRoots && includeScriptsOutsideSourceRoots, + project = project ) } - return KotlinSourceFilterScope(delegate, includeProjectSourceFiles, includeLibrarySourceFiles, includeClassFiles, includeScriptDependencies, includeScriptsOutsideSourceRoots, project) + return KotlinSourceFilterScope( + delegate, includeProjectSourceFiles, includeLibrarySourceFiles, includeClassFiles, + includeScriptDependencies, includeScriptsOutsideSourceRoots, project + ) } } } diff --git a/idea/idea-gradle/src/org/jetbrains/kotlin/idea/configuration/GroovyBuildScriptManipulator.kt b/idea/idea-gradle/src/org/jetbrains/kotlin/idea/configuration/GroovyBuildScriptManipulator.kt index b77ef384a9b..c8d57cf2d7f 100644 --- a/idea/idea-gradle/src/org/jetbrains/kotlin/idea/configuration/GroovyBuildScriptManipulator.kt +++ b/idea/idea-gradle/src/org/jetbrains/kotlin/idea/configuration/GroovyBuildScriptManipulator.kt @@ -87,8 +87,7 @@ class GroovyBuildScriptManipulator( } } } - } - else { + } else { val applyPluginDirective = getGroovyApplyPluginDirective(kotlinPluginName) if (!containsDirective(scriptFile.text, applyPluginDirective)) { val apply = GroovyPsiElementFactory.getInstance(scriptFile.project).createExpressionFromText(applyPluginDirective) @@ -246,11 +245,11 @@ class GroovyBuildScriptManipulator( .getBlockOrCreate("resolutionStrategy") .getBlockOrCreate("eachPlugin") .addLastStatementInBlockIfNeeded( - """ - if (requested.id.id == "$pluginId") { - useModule("org.jetbrains.kotlin:kotlin-gradle-plugin:${'$'}{requested.version}") - } - """.trimIndent() + """ + if (requested.id.id == "$pluginId") { + useModule("org.jetbrains.kotlin:kotlin-gradle-plugin:${'$'}{requested.version}") + } + """.trimIndent() ) } @@ -415,9 +414,9 @@ class GroovyBuildScriptManipulator( } companion object { - private val VERSION_TEMPLATE = "\$VERSION$" + private const val VERSION_TEMPLATE = "\$VERSION$" private val VERSION = String.format("ext.kotlin_version = '%s'", VERSION_TEMPLATE) - private val GRADLE_PLUGIN_ID = "kotlin-gradle-plugin" + private const val GRADLE_PLUGIN_ID = "kotlin-gradle-plugin" private val CLASSPATH = "classpath \"$KOTLIN_GROUP_ID:$GRADLE_PLUGIN_ID:\$kotlin_version\"" private fun PsiElement.getBlockByName(name: String): GrClosableBlock? { @@ -454,13 +453,13 @@ class GroovyBuildScriptManipulator( } fun GrClosableBlock.addLastExpressionInBlockIfNeeded(expressionText: String): Boolean = - addExpressionOrStatementInBlockIfNeeded(expressionText, false, false) + addExpressionOrStatementInBlockIfNeeded(expressionText, isStatement = false, isFirst = false) fun GrClosableBlock.addLastStatementInBlockIfNeeded(expressionText: String): Boolean = - addExpressionOrStatementInBlockIfNeeded(expressionText, true, false) + addExpressionOrStatementInBlockIfNeeded(expressionText, isStatement = true, isFirst = false) private fun GrClosableBlock.addFirstExpressionInBlockIfNeeded(expressionText: String): Boolean = - addExpressionOrStatementInBlockIfNeeded(expressionText, false, true) + addExpressionOrStatementInBlockIfNeeded(expressionText, isStatement = false, isFirst = true) private fun GrClosableBlock.addExpressionOrStatementInBlockIfNeeded(text: String, isStatement: Boolean, isFirst: Boolean): Boolean { if (statements.any { StringUtil.equalsIgnoreWhitespaces(it.text, text) }) return false diff --git a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/debugger/evaluate/compilation/CodeFragmentCompiler.kt b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/debugger/evaluate/compilation/CodeFragmentCompiler.kt index 646e3bebc84..6903ee04bd6 100644 --- a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/debugger/evaluate/compilation/CodeFragmentCompiler.kt +++ b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/debugger/evaluate/compilation/CodeFragmentCompiler.kt @@ -56,7 +56,9 @@ class CodeFragmentCompiler(private val executionContext: ExecutionContext) { return runReadAction { doCompile(codeFragment, bindingContext, moduleDescriptor) } } - private fun doCompile(codeFragment: KtCodeFragment, bindingContext: BindingContext, moduleDescriptor: ModuleDescriptor): CompilationResult { + private fun doCompile( + codeFragment: KtCodeFragment, bindingContext: BindingContext, moduleDescriptor: ModuleDescriptor + ): CompilationResult { require(codeFragment is KtBlockCodeFragment || codeFragment is KtExpressionCodeFragment) { "Unsupported code fragment type: $codeFragment" } @@ -111,7 +113,7 @@ class CodeFragmentCompiler(private val executionContext: ExecutionContext) { } val ownerClassName = typeMapper.mapOwner(parameter.targetDescriptor).internalName - val lastDollarIndex = ownerClassName.lastIndexOf('$').takeIf { it >= 0} ?: continue + val lastDollarIndex = ownerClassName.lastIndexOf('$').takeIf { it >= 0 } ?: continue result[parameter.dumb] = ownerClassName.drop(lastDollarIndex) } @@ -176,7 +178,12 @@ class CodeFragmentCompiler(private val executionContext: ExecutionContext) { val parameters = parameterInfo.parameters.mapIndexed { index, parameter -> ValueParameterDescriptorImpl( methodDescriptor, null, index, Annotations.EMPTY, Name.identifier("p$index"), - parameter.targetType, false, false, false, null, SourceElement.NO_SOURCE + parameter.targetType, + declaresDefaultValue = false, + isCrossinline = false, + isNoinline = false, + varargElementType = null, + source = SourceElement.NO_SOURCE ) } diff --git a/idea/idea-repl/src/org/jetbrains/kotlin/jsr223/KotlinJsr223JvmScriptEngine4Idea.kt b/idea/idea-repl/src/org/jetbrains/kotlin/jsr223/KotlinJsr223JvmScriptEngine4Idea.kt index 22c73969c59..e14ff180fd0 100644 --- a/idea/idea-repl/src/org/jetbrains/kotlin/jsr223/KotlinJsr223JvmScriptEngine4Idea.kt +++ b/idea/idea-repl/src/org/jetbrains/kotlin/jsr223/KotlinJsr223JvmScriptEngine4Idea.kt @@ -37,11 +37,11 @@ import kotlin.reflect.KClass // TODO: need to manage resources here, i.e. call replCompiler.dispose when engine is collected class KotlinJsr223JvmScriptEngine4Idea( - factory: ScriptEngineFactory, - templateClasspath: List, - templateClassName: String, - private val getScriptArgs: (ScriptContext, Array>?) -> ScriptArgsWithTypes?, - private val scriptArgsTypes: Array>? + factory: ScriptEngineFactory, + templateClasspath: List, + templateClassName: String, + private val getScriptArgs: (ScriptContext, Array>?) -> ScriptArgsWithTypes?, + private val scriptArgsTypes: Array>? ) : KotlinJsr223JvmScriptEngineBase(factory) { private val daemon by lazy { @@ -53,28 +53,37 @@ class KotlinJsr223JvmScriptEngine4Idea( val daemonReportMessages = arrayListOf() - KotlinCompilerClient.connectToCompileService(compilerId, daemonJVMOptions, daemonOptions, DaemonReportingTargets(null, daemonReportMessages), true, true) - ?: throw ScriptException("Unable to connect to repl server:" + daemonReportMessages.joinToString("\n ", prefix = "\n ") { "${it.category.name} ${it.message}" }) + KotlinCompilerClient.connectToCompileService( + compilerId, daemonJVMOptions, daemonOptions, + DaemonReportingTargets(null, daemonReportMessages), + autostart = true, checkId = true + ) ?: throw ScriptException( + "Unable to connect to repl server:" + daemonReportMessages.joinToString("\n ", prefix = "\n ") { + "${it.category.name} ${it.message}" + } + ) } private val messageCollector = MyMessageCollector() override val replCompiler: ReplCompiler by lazy { - daemon.let { - KotlinRemoteReplCompilerClient(it, - makeAutodeletingFlagFile("idea-jsr223-repl-session"), - CompileService.TargetPlatform.JVM, - emptyArray(), - messageCollector, - templateClasspath, - templateClassName) - } + KotlinRemoteReplCompilerClient( + daemon, + makeAutodeletingFlagFile("idea-jsr223-repl-session"), + CompileService.TargetPlatform.JVM, + emptyArray(), + messageCollector, + templateClasspath, + templateClassName + ) } override fun overrideScriptArgs(context: ScriptContext): ScriptArgsWithTypes? = - getScriptArgs(getContext(), scriptArgsTypes) + getScriptArgs(getContext(), scriptArgsTypes) - private val localEvaluator: ReplFullEvaluator by lazy { GenericReplCompilingEvaluator(replCompiler, templateClasspath, Thread.currentThread().contextClassLoader) } + private val localEvaluator: ReplFullEvaluator by lazy { + GenericReplCompilingEvaluator(replCompiler, templateClasspath, Thread.currentThread().contextClassLoader) + } override val replEvaluator: ReplFullEvaluator get() = localEvaluator diff --git a/idea/src/org/jetbrains/kotlin/idea/parameterInfo/TypeHints.kt b/idea/src/org/jetbrains/kotlin/idea/parameterInfo/TypeHints.kt index 4e1db145cee..ec7ffa27fe0 100644 --- a/idea/src/org/jetbrains/kotlin/idea/parameterInfo/TypeHints.kt +++ b/idea/src/org/jetbrains/kotlin/idea/parameterInfo/TypeHints.kt @@ -113,7 +113,7 @@ fun provideTypeHint(element: KtCallableDeclaration, offset: Int): List T_MEMBER_FUNCTION } is PsiExpression -> T_EXPRESSION - is PsiField -> T_MEMBER_PROPERTY(true, false) + is PsiField -> T_MEMBER_PROPERTY(backingField = true, delegate = false) is PsiLocalVariable -> T_LOCAL_VARIABLE is PsiParameter -> T_VALUE_PARAMETER_WITHOUT_VAL else -> EMPTY diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/callableBuilder/CallableInfo.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/callableBuilder/CallableInfo.kt index 0af473cda98..1995d32de6e 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/callableBuilder/CallableInfo.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/callableBuilder/CallableInfo.kt @@ -130,7 +130,7 @@ abstract class TypeInfo(val variance: Variance) { return Collections.singletonList(callableBuilder.currentFileModule.builtIns.anyType) } val scope = getScopeForTypeApproximation(callableBuilder.config, callableBuilder.placement) - val approximations = getResolvableApproximations(scope, false, true) + val approximations = getResolvableApproximations(scope, checkTypeParameters = false, allowIntersections = true) return when (variance) { Variance.IN_VARIANCE -> approximations.toList() else -> listOf(approximations.firstOrNull() ?: this) diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/crossLanguage/ChangeMethodParameters.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/crossLanguage/ChangeMethodParameters.kt index 75701fb8f72..8e513870958 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/crossLanguage/ChangeMethodParameters.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/crossLanguage/ChangeMethodParameters.kt @@ -125,8 +125,8 @@ internal class ChangeMethodParameters( ValueParameterDescriptorImpl( this, null, index, Annotations.EMPTY, Name.identifier(parameter.name), - parameter.ktType, false, - false, false, null, SourceElement.NO_SOURCE + parameter.ktType, declaresDefaultValue = false, + isCrossinline = false, isNoinline = false, varargElementType = null, source = SourceElement.NO_SOURCE ) }, functionDescriptor.returnType, diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinChangeSignatureUsageProcessor.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinChangeSignatureUsageProcessor.kt index a6e846f8a77..570b250d3a2 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinChangeSignatureUsageProcessor.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinChangeSignatureUsageProcessor.kt @@ -210,7 +210,12 @@ class KotlinChangeSignatureUsageProcessor : ChangeSignatureUsageProcessor { val result = LinkedHashSet() val searchScope = functionPsi.useScope - val options = KotlinReferencesSearchOptions(true, false, false, false) + val options = KotlinReferencesSearchOptions( + acceptCallableOverrides = true, + acceptOverloads = false, + acceptExtensionsOfDeclarationClass = false, + acceptCompanionObjectMembers = false + ) val parameters = KotlinReferencesSearchParameters(functionPsi, searchScope, false, null, options) result.addAll(ReferencesSearch.search(parameters).findAll()) if (functionPsi is KtProperty || functionPsi is KtParameter) { diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveClassesOrPackages/KotlinAwareDelegatingMoveDestination.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveClassesOrPackages/KotlinAwareDelegatingMoveDestination.kt index e1d388c5a6a..63c655ba6b2 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveClassesOrPackages/KotlinAwareDelegatingMoveDestination.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveClassesOrPackages/KotlinAwareDelegatingMoveDestination.kt @@ -37,14 +37,14 @@ import org.jetbrains.kotlin.psi.KtNamedDeclaration import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf class KotlinAwareDelegatingMoveDestination( - private val delegate: MoveDestination, - private val targetPackage: PsiPackage?, - private val targetDirectory: PsiDirectory? + private val delegate: MoveDestination, + private val targetPackage: PsiPackage?, + private val targetDirectory: PsiDirectory? ) : MoveDestination by delegate { override fun analyzeModuleConflicts( - elements: MutableCollection, - conflicts: MultiMap, - usages: Array + elements: MutableCollection, + conflicts: MultiMap, + usages: Array ) { delegate.analyzeModuleConflicts(elements, conflicts, usages) @@ -71,7 +71,7 @@ class KotlinAwareDelegatingMoveDestination( super.visitElement(element) } } - filesToProcess.flatMap {it.declarations}.forEach { it.accept(extraElementCollector) } + filesToProcess.flatMap { it.declarations }.forEach { it.accept(extraElementCollector) } val progressIndicator = ProgressManager.getInstance().progressIndicator!! progressIndicator.pushState() @@ -80,13 +80,12 @@ class KotlinAwareDelegatingMoveDestination( try { progressIndicator.text = "Looking for Usages" for ((index, element) in extraElementsForReferenceSearch.withIndex()) { - progressIndicator.fraction = (index + 1)/extraElementsForReferenceSearch.size.toDouble() + progressIndicator.fraction = (index + 1) / extraElementsForReferenceSearch.size.toDouble() ReferencesSearch.search(element, projectScope).mapNotNullTo(extraUsages) { ref -> - createMoveUsageInfoIfPossible(ref, element, true, false) + createMoveUsageInfoIfPossible(ref, element, addImportToOriginalFile = true, isInternal = false) } } - } - finally { + } finally { progressIndicator.popState() } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveDeclarations/MoveKotlinDeclarationsProcessor.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveDeclarations/MoveKotlinDeclarationsProcessor.kt index 155fed50647..052c83daa61 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveDeclarations/MoveKotlinDeclarationsProcessor.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveDeclarations/MoveKotlinDeclarationsProcessor.kt @@ -81,8 +81,7 @@ interface Mover : (KtNamedDeclaration, KtElement) -> KtNamedDeclaration { val container = originalElement.containingClassOrObject if (container is KtObjectDeclaration && container.isCompanion() && container.declarations.singleOrNull() == originalElement) { container.deleteSingle() - } - else { + } else { originalElement.deleteSingle() } } @@ -142,11 +141,12 @@ private object ElementHashingStrategy : TObjectHashingStrategy { } class MoveKotlinDeclarationsProcessor( - val descriptor: MoveDeclarationsDescriptor, - val mover: Mover = Mover.Default) : BaseRefactoringProcessor(descriptor.project) { + val descriptor: MoveDeclarationsDescriptor, + val mover: Mover = Mover.Default +) : BaseRefactoringProcessor(descriptor.project) { companion object { - private val REFACTORING_NAME = "Move declarations" - val REFACTORING_ID = "move.kotlin.declarations" + private const val REFACTORING_NAME = "Move declarations" + const val REFACTORING_ID = "move.kotlin.declarations" } val project get() = descriptor.project @@ -155,8 +155,8 @@ class MoveKotlinDeclarationsProcessor( private val moveEntireFile = descriptor.moveSource is MoveSource.File private val elementsToMove = descriptor.moveSource.elementsToMove.filter { e -> e.parent != descriptor.moveTarget.getTargetPsiIfExists(e) } private val kotlinToLightElementsBySourceFile = elementsToMove - .groupBy { it.containingKtFile } - .mapValues { it.value.keysToMap { it.toLightElements().ifEmpty { listOf(it) } } } + .groupBy { it.containingKtFile } + .mapValues { it.value.keysToMap { it.toLightElements().ifEmpty { listOf(it) } } } private val conflicts = MultiMap() override fun getRefactoringId() = REFACTORING_ID @@ -207,23 +207,23 @@ class MoveKotlinDeclarationsProcessor( val foundReferences = HashSet() val results = ReferencesSearch - .search(lightElement, searchScope) - .mapNotNullTo(ArrayList()) { ref -> - if (foundReferences.add(ref) && elementsToMove.none { it.isAncestor(ref.element)}) { - createMoveUsageInfoIfPossible(ref, lightElement, true, false) - } - else null + .search(lightElement, searchScope) + .mapNotNullTo(ArrayList()) { ref -> + if (foundReferences.add(ref) && elementsToMove.none { it.isAncestor(ref.element)}) { + createMoveUsageInfoIfPossible(ref, lightElement, addImportToOriginalFile = true, isInternal = false) } + else null + } val name = lightElement.getKotlinFqName()?.quoteIfNeeded()?.asString() if (name != null) { TextOccurrencesUtil.findNonCodeUsages( - lightElement, - name, - descriptor.searchInCommentsAndStrings, - descriptor.searchInNonCode, - FqName(newFqName).quoteIfNeeded().asString(), - results + lightElement, + name, + descriptor.searchInCommentsAndStrings, + descriptor.searchInNonCode, + FqName(newFqName).quoteIfNeeded().asString(), + results ) } @@ -237,11 +237,11 @@ class MoveKotlinDeclarationsProcessor( val usages = ArrayList() val conflictChecker = MoveConflictChecker( - project, - elementsToMove, - descriptor.moveTarget, - elementsToMove.first(), - allElementsToMove = descriptor.allElementsToMove + project, + elementsToMove, + descriptor.moveTarget, + elementsToMove.first(), + allElementsToMove = descriptor.allElementsToMove ) for ((sourceFile, kotlinToLightElements) in kotlinToLightElementsBySourceFile) { val internalUsages = LinkedHashSet() @@ -249,12 +249,11 @@ class MoveKotlinDeclarationsProcessor( if (moveEntireFile) { val changeInfo = ContainerChangeInfo( - ContainerInfo.Package(sourceFile.packageFqName), - descriptor.moveTarget.targetContainerFqName?.let { ContainerInfo.Package(it) } ?: ContainerInfo.UnknownPackage + ContainerInfo.Package(sourceFile.packageFqName), + descriptor.moveTarget.targetContainerFqName?.let { ContainerInfo.Package(it) } ?: ContainerInfo.UnknownPackage ) internalUsages += sourceFile.getInternalReferencesToUpdateOnPackageNameChange(changeInfo) - } - else { + } else { kotlinToLightElements.keys.forEach { val packageNameInfo = descriptor.delegate.getContainerChangeInfo(it, descriptor.moveTarget) internalUsages += it.getInternalReferencesToUpdateOnPackageNameChange(packageNameInfo) @@ -284,7 +283,7 @@ class MoveKotlinDeclarationsProcessor( internal fun doPerformRefactoring(usages: List) { fun moveDeclaration(declaration: KtNamedDeclaration, moveTarget: KotlinMoveTarget): KtNamedDeclaration { val targetContainer = moveTarget.getOrCreateTargetPsi(declaration) - ?: throw AssertionError("Couldn't create Kotlin file for: ${declaration::class.java}: ${declaration.text}") + ?: throw AssertionError("Couldn't create Kotlin file for: ${declaration::class.java}: ${declaration.text}") descriptor.delegate.preprocessDeclaration(descriptor, declaration) if (moveEntireFile) return declaration return mover(declaration, targetContainer).apply { @@ -341,12 +340,10 @@ class MoveKotlinDeclarationsProcessor( usagesToProcess += newInternalUsages nonCodeUsages = postProcessMoveUsages(usagesToProcess, oldToNewElementsMapping).toTypedArray() - } - catch (e: IncorrectOperationException) { + } catch (e: IncorrectOperationException) { nonCodeUsages = null RefactoringUIUtil.processIncorrectOperation(myProject, e) - } - finally { + } finally { cleanUpInternalUsages(newInternalUsages + oldInternalUsages) } } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveFilesUtil.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveFilesUtil.kt index 1e8759398f6..ea3c6898d13 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveFilesUtil.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveFilesUtil.kt @@ -38,11 +38,11 @@ import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtFile fun invokeMoveFilesOrDirectoriesRefactoring( - moveDialog: KotlinAwareMoveFilesOrDirectoriesDialog?, - project: Project, - elements: Array, - initialTargetDirectory: PsiDirectory?, - moveCallback: MoveCallback? + moveDialog: KotlinAwareMoveFilesOrDirectoriesDialog?, + project: Project, + elements: Array, + initialTargetDirectory: PsiDirectory?, + moveCallback: MoveCallback? ) { fun closeDialog() { moveDialog?.close(DialogWrapper.CANCEL_EXIT_CODE) @@ -55,19 +55,19 @@ fun invokeMoveFilesOrDirectoriesRefactoring( try { val choice = if (elements.size > 1 || elements[0] is PsiDirectory) intArrayOf(-1) else null val elementsToMove = elements - .filterNot { - it is PsiFile - && runWriteAction { CopyFilesOrDirectoriesHandler.checkFileExist(selectedDir, choice, it, it.name, "Move") } + .filterNot { + it is PsiFile + && runWriteAction { CopyFilesOrDirectoriesHandler.checkFileExist(selectedDir, choice, it, it.name, "Move") } + } + .sortedWith( // process Kotlin files first so that light classes are updated before changing references in Java files + java.util.Comparator { o1, o2 -> + when { + o1 is KtElement && o2 !is KtElement -> -1 + o1 !is KtElement && o2 is KtElement -> 1 + else -> 0 + } } - .sortedWith( // process Kotlin files first so that light classes are updated before changing references in Java files - java.util.Comparator { o1, o2 -> - when { - o1 is KtElement && o2 !is KtElement -> -1 - o1 !is KtElement && o2 is KtElement -> 1 - else -> 0 - } - } - ) + ) elementsToMove.forEach { MoveFilesOrDirectoriesUtil.checkMove(it, selectedDir) @@ -79,22 +79,20 @@ fun invokeMoveFilesOrDirectoriesRefactoring( if (elementsToMove.isNotEmpty()) { @Suppress("UNCHECKED_CAST") val processor = KotlinAwareMoveFilesOrDirectoriesProcessor( - project, - elementsToMove as List, - selectedDir, - moveDialog?.searchReferences ?: true, - false, - false, - moveCallback, - Runnable(::closeDialog) + project, + elementsToMove as List, + selectedDir, + searchReferences = moveDialog?.searchReferences ?: true, + searchInComments = false, + searchInNonJavaFiles = false, + moveCallback = moveCallback, + prepareSuccessfulCallback = Runnable(::closeDialog) ) processor.run() - } - else { + } else { closeDialog() } - } - catch (e: IncorrectOperationException) { + } catch (e: IncorrectOperationException) { CommonRefactoringUtil.showErrorMessage(RefactoringBundle.message("error.title"), e.message, "refactoring.moveFile", project) } } @@ -102,12 +100,12 @@ fun invokeMoveFilesOrDirectoriesRefactoring( // Mostly copied from MoveFilesOrDirectoriesUtil.doMove() fun moveFilesOrDirectories( - project: Project, - elements: Array, - targetElement: PsiElement?, - moveCallback: MoveCallback? = null + project: Project, + elements: Array, + targetElement: PsiElement?, + moveCallback: MoveCallback? = null ) { - elements.forEach { if (it !is PsiFile && it !is PsiDirectory) throw IllegalArgumentException("unexpected element type: " + it) } + elements.forEach { if (it !is PsiFile && it !is PsiDirectory) throw IllegalArgumentException("unexpected element type: $it") } val targetDirectory = MoveFilesOrDirectoriesUtil.resolveToDirectory(project, targetElement) if (targetElement != null && targetDirectory == null) return diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveUtils.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveUtils.kt index 841000e5f89..81bd27d09ee 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveUtils.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveUtils.kt @@ -185,7 +185,7 @@ fun KtElement.processInternalReferencesToUpdateOnPackageNameChange( val declarationNotNull = declaration ?: return null if (isExtension || containerFqName != null || isImported) return { - createMoveUsageInfoIfPossible(it.mainReference, declarationNotNull, false, true) + createMoveUsageInfoIfPossible(it.mainReference, declarationNotNull, addImportToOriginalFile = false, isInternal = true) } return null diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/renderingUtils.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/renderingUtils.kt index e60e8443d95..f54dbc0e970 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/renderingUtils.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/renderingUtils.kt @@ -33,19 +33,20 @@ import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils fun wrapOrSkip(s: String, inCode: Boolean) = if (inCode) "$s" else s -fun formatClassDescriptor(classDescriptor: DeclarationDescriptor) = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.render(classDescriptor) +fun formatClassDescriptor(classDescriptor: DeclarationDescriptor) = + IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.render(classDescriptor) fun formatPsiClass( - psiClass: PsiClass, - markAsJava: Boolean, - inCode: Boolean + psiClass: PsiClass, + markAsJava: Boolean, + inCode: Boolean ): String { var description: String val kind = if (psiClass.isInterface) "interface " else "class " description = kind + PsiFormatUtil.formatClass( - psiClass, - PsiFormatUtilBase.SHOW_CONTAINING_CLASS or PsiFormatUtilBase.SHOW_NAME or PsiFormatUtilBase.SHOW_PARAMETERS or PsiFormatUtilBase.SHOW_TYPE + psiClass, + PsiFormatUtilBase.SHOW_CONTAINING_CLASS or PsiFormatUtilBase.SHOW_NAME or PsiFormatUtilBase.SHOW_PARAMETERS or PsiFormatUtilBase.SHOW_TYPE ) description = wrapOrSkip(description, inCode) @@ -56,8 +57,7 @@ fun formatClass(classDescriptor: DeclarationDescriptor, inCode: Boolean): String val element = DescriptorToSourceUtils.descriptorToDeclaration(classDescriptor) return if (element is PsiClass) { formatPsiClass(element, false, inCode) - } - else { + } else { wrapOrSkip(formatClassDescriptor(classDescriptor), inCode) } } @@ -66,8 +66,7 @@ fun formatFunction(functionDescriptor: DeclarationDescriptor, inCode: Boolean): val element = DescriptorToSourceUtils.descriptorToDeclaration(functionDescriptor) return if (element is PsiMethod) { formatPsiMethod(element, false, inCode) - } - else { + } else { wrapOrSkip(formatFunctionDescriptor(functionDescriptor), inCode) } } @@ -75,9 +74,9 @@ fun formatFunction(functionDescriptor: DeclarationDescriptor, inCode: Boolean): private fun formatFunctionDescriptor(functionDescriptor: DeclarationDescriptor) = DescriptorRenderer.COMPACT.render(functionDescriptor) fun formatPsiMethod( - psiMethod: PsiMethod, - showContainingClass: Boolean, - inCode: Boolean + psiMethod: PsiMethod, + showContainingClass: Boolean, + inCode: Boolean ): String { var options = PsiFormatUtilBase.SHOW_NAME or PsiFormatUtilBase.SHOW_PARAMETERS or PsiFormatUtilBase.SHOW_TYPE if (showContainingClass) { @@ -95,9 +94,8 @@ fun formatJavaOrLightMethod(method: PsiMethod): String { val originalDeclaration = method.unwrapped return if (originalDeclaration is KtDeclaration) { formatFunctionDescriptor(originalDeclaration.unsafeResolveToDescriptor()) - } - else { - formatPsiMethod(method, false, false) + } else { + formatPsiMethod(method, showContainingClass = false, inCode = false) } } diff --git a/j2k/src/org/jetbrains/kotlin/j2k/AnnotationConverter.kt b/j2k/src/org/jetbrains/kotlin/j2k/AnnotationConverter.kt index 4d257146067..d30f964f912 100644 --- a/j2k/src/org/jetbrains/kotlin/j2k/AnnotationConverter.kt +++ b/j2k/src/org/jetbrains/kotlin/j2k/AnnotationConverter.kt @@ -190,11 +190,11 @@ class AnnotationConverter(private val converter: Converter) { if (returnType is PsiArrayType && value !is PsiArrayInitializerMemberValue) { return converter.deferredElement { codeConverter -> converter.typeConverter.convertType(returnType) as ArrayType - val convertAttributeValue = convertAttributeValue(value, returnType.componentType, false, false) + val convertAttributeValue = convertAttributeValue(value, returnType.componentType, isVararg = false, isUnnamed = false) createArrayLiteralExpression(codeConverter, convertAttributeValue.toList()) } } - return converter.deferredElement(convertAttributeValue(value, returnType, false, false).single()) + return converter.deferredElement(convertAttributeValue(value, returnType, isVararg = false, isUnnamed = false).single()) } private fun convertAttributeValue(value: PsiAnnotationMemberValue?, expectedType: PsiType?, isVararg: Boolean, isUnnamed: Boolean): List<(CodeConverter) -> Expression> { diff --git a/j2k/src/org/jetbrains/kotlin/j2k/CodeConverter.kt b/j2k/src/org/jetbrains/kotlin/j2k/CodeConverter.kt index f4209beeafb..1ef52a99ae0 100644 --- a/j2k/src/org/jetbrains/kotlin/j2k/CodeConverter.kt +++ b/j2k/src/org/jetbrains/kotlin/j2k/CodeConverter.kt @@ -82,7 +82,7 @@ class CodeConverter( val explicitType = type.takeIf { settings.specifyLocalVariableTypeByDefault || converter.shouldDeclareVariableType(variable, type, isVal) } return LocalVariable(variable.declarationIdentifier(), converter.convertAnnotations(variable), - converter.convertModifiers(variable, false, false), + converter.convertModifiers(variable, isMethodInOpenClass = false, isInObject = false), explicitType, convertExpression(variable.initializer, variable.type), isVal).assignPrototype(variable) diff --git a/j2k/src/org/jetbrains/kotlin/j2k/Converter.kt b/j2k/src/org/jetbrains/kotlin/j2k/Converter.kt index 3164ba59118..3a20f569f55 100644 --- a/j2k/src/org/jetbrains/kotlin/j2k/Converter.kt +++ b/j2k/src/org/jetbrains/kotlin/j2k/Converter.kt @@ -162,7 +162,7 @@ class Converter private constructor( } val annotations = convertAnnotations(psiClass) - var modifiers = convertModifiers(psiClass, false, false) + var modifiers = convertModifiers(psiClass, isMethodInOpenClass = false, isInObject = false) val typeParameters = convertTypeParameterList(psiClass.typeParameterList) val extendsTypes = convertToNotNullableTypes(psiClass.extendsList) val implementsTypes = convertToNotNullableTypes(psiClass.implementsList) @@ -293,14 +293,20 @@ class Converter private constructor( classBody = ClassBody(null, constructorSignature, classBody.baseClassParams, classBody.members, classBody.companionObjectMembers, classBody.lBrace, classBody.rBrace, classBody.classKind) - return Class(psiClass.declarationIdentifier(), - convertAnnotations(psiClass), - convertModifiers(psiClass, false, false).with(Modifier.ANNOTATION).without(Modifier.ABSTRACT), - TypeParameterList.Empty, - listOf(), - null, - listOf(), - classBody).assignPrototype(psiClass) + return Class( + psiClass.declarationIdentifier(), + convertAnnotations(psiClass), + convertModifiers( + psiClass, + isMethodInOpenClass = false, + isInObject = false + ).with(Modifier.ANNOTATION).without(Modifier.ABSTRACT), + TypeParameterList.Empty, + listOf(), + null, + listOf(), + classBody + ).assignPrototype(psiClass) } fun convertInitializer(initializer: PsiClassInitializer): Initializer { diff --git a/j2k/src/org/jetbrains/kotlin/j2k/propertyDetection.kt b/j2k/src/org/jetbrains/kotlin/j2k/propertyDetection.kt index 5da7d32b66d..628bb4ea799 100644 --- a/j2k/src/org/jetbrains/kotlin/j2k/propertyDetection.kt +++ b/j2k/src/org/jetbrains/kotlin/j2k/propertyDetection.kt @@ -31,17 +31,17 @@ import org.jetbrains.kotlin.utils.addIfNotNull import java.util.* class PropertyInfo( - val identifier: Identifier, - val isVar: Boolean, - val psiType: PsiType, - val field: PsiField?, - val getMethod: PsiMethod?, - val setMethod: PsiMethod?, - val isGetMethodBodyFieldAccess: Boolean, - val isSetMethodBodyFieldAccess: Boolean, - val modifiers: Modifiers, - val specialSetterAccess: Modifier?, - val superInfo: SuperInfo? + val identifier: Identifier, + val isVar: Boolean, + val psiType: PsiType, + val field: PsiField?, + val getMethod: PsiMethod?, + val setMethod: PsiMethod?, + val isGetMethodBodyFieldAccess: Boolean, + val isSetMethodBodyFieldAccess: Boolean, + val modifiers: Modifiers, + val specialSetterAccess: Modifier?, + val superInfo: SuperInfo? ) { init { assert(field != null || getMethod != null || setMethod != null) @@ -79,7 +79,8 @@ class PropertyInfo( if (setMethod.body != null && !isSetMethodBodyFieldAccess) return true } - return modifiers.contains(Modifier.EXTERNAL) || modifiers.contains(Modifier.OVERRIDE) && this.field == null && !modifiers.contains(Modifier.ABSTRACT) + return modifiers.contains(Modifier.EXTERNAL) || + modifiers.contains(Modifier.OVERRIDE) && this.field == null && !modifiers.contains(Modifier.ABSTRACT) } companion object { @@ -87,7 +88,16 @@ class PropertyInfo( val isVar = field.isVar(converter.referenceSearcher) val isInObject = field.containingClass?.let { converter.shouldConvertIntoObject(it) } == true val modifiers = converter.convertModifiers(field, false, isInObject) - return PropertyInfo(field.declarationIdentifier(), isVar, field.type, field, null, null, false, false, modifiers, null, null) + return PropertyInfo( + field.declarationIdentifier(), isVar, field.type, field, + getMethod = null, + setMethod = null, + isGetMethodBodyFieldAccess = false, + isSetMethodBodyFieldAccess = false, + modifiers = modifiers, + specialSetterAccess = null, + superInfo = null + ) } } } @@ -108,10 +118,10 @@ class PropertyDetectionCache(private val converter: Converter) { sealed class SuperInfo { class Property( - val isVar: Boolean, - val name: String, - val hasAbstractModifier: Boolean - //TODO: add visibility + val isVar: Boolean, + val name: String, + val hasAbstractModifier: Boolean + //TODO: add visibility ) : SuperInfo() object Function : SuperInfo() @@ -122,8 +132,8 @@ sealed class SuperInfo { } private class PropertyDetector( - private val psiClass: PsiClass, - private val converter: Converter + private val psiClass: PsiClass, + private val converter: Converter ) { private val isOpenClass = converter.needOpenModifier(psiClass) @@ -137,8 +147,8 @@ private class PropertyDetector( dropPropertiesConflictingWithFields(memberToPropertyInfo) val mappedFields = memberToPropertyInfo.values - .mapNotNull { it.field } - .toSet() + .mapNotNull { it.field } + .toSet() // map all other fields for (field in psiClass.fields) { @@ -192,13 +202,18 @@ private class PropertyDetector( if (getterInfo != null && getterInfo.field == null) { if (!field.hasModifierProperty(PsiModifier.PRIVATE) - || converter.referenceSearcher.findVariableUsages(field, psiClass).any { PsiUtil.isAccessedForReading(it) && !it.canBeReplacedWithFieldAccess() }) { + || converter.referenceSearcher.findVariableUsages(field, psiClass).any { + PsiUtil.isAccessedForReading(it) && !it.canBeReplacedWithFieldAccess() + } + ) { field = null } - } - else if (setterInfo != null && setterInfo.field == null) { + } else if (setterInfo != null && setterInfo.field == null) { if (!field.hasModifierProperty(PsiModifier.PRIVATE) - || converter.referenceSearcher.findVariableUsages(field, psiClass).any { PsiUtil.isAccessedForWriting(it) && !it.canBeReplacedWithFieldAccess() }) { + || converter.referenceSearcher.findVariableUsages(field, psiClass).any { + PsiUtil.isAccessedForWriting(it) && !it.canBeReplacedWithFieldAccess() + } + ) { field = null } } @@ -222,24 +237,26 @@ private class PropertyDetector( val propertyAccess = modifiers.accessModifier() val setterAccess = if (setterInfo != null) - converter.convertModifiers(setterInfo.method, false, false).accessModifier() + converter.convertModifiers(setterInfo.method, isMethodInOpenClass = false, isInObject = false).accessModifier() else if (field != null && field.isVar(converter.referenceSearcher)) - converter.convertModifiers(field, false, false).accessModifier() + converter.convertModifiers(field, isMethodInOpenClass = false, isInObject = false).accessModifier() else propertyAccess val specialSetterAccess = setterAccess?.takeIf { it != propertyAccess } - val propertyInfo = PropertyInfo(Identifier.withNoPrototype(propertyName), - isVar, - type, - field, - getterInfo?.method, - setterInfo?.method, - field != null && getterInfo?.field == field, - field != null && setterInfo?.field == field, - modifiers, - specialSetterAccess, - superProperty) + val propertyInfo = PropertyInfo( + Identifier.withNoPrototype(propertyName), + isVar, + type, + field, + getterInfo?.method, + setterInfo?.method, + field != null && getterInfo?.field == field, + field != null && setterInfo?.field == field, + modifiers, + specialSetterAccess, + superProperty + ) propertyInfos.add(propertyInfo) } return propertyInfos @@ -252,8 +269,7 @@ private class PropertyDetector( if (field != null) { if (memberToPropertyInfo.containsKey(field)) { // field already in use by other property continue - } - else { + } else { memberToPropertyInfo[field] = propertyInfo } } @@ -265,8 +281,8 @@ private class PropertyDetector( } private fun detectGetters( - methodsToCheck: List>, - propertyNamesWithConflict: MutableSet + methodsToCheck: List>, + propertyNamesWithConflict: MutableSet ): Map { val propertyNameToGetterInfo = LinkedHashMap() for ((method, superInfo) in methodsToCheck) { @@ -284,9 +300,9 @@ private class PropertyDetector( } private fun detectSetters( - methodsToCheck: List>, - propertyNamesFromGetters: Set, - propertyNamesWithConflict: MutableSet + methodsToCheck: List>, + propertyNamesFromGetters: Set, + propertyNamesWithConflict: MutableSet ): Map { val propertyNameToSetterInfo = LinkedHashMap() for ((method, superInfo) in methodsToCheck) { @@ -310,9 +326,9 @@ private class PropertyDetector( //TODO: bases val prohibitedSignatures = psiClass.methods - .filter { it !in mappedMethods } - .map { it.getSignature(PsiSubstitutor.EMPTY) } - .toSet() + .filter { it !in mappedMethods } + .map { it.getSignature(PsiSubstitutor.EMPTY) } + .toSet() for (propertyInfo in propertyInfos) { if (propertyInfo.modifiers.contains(Modifier.OVERRIDE)) continue // cannot drop override @@ -327,7 +343,9 @@ private class PropertyDetector( if (propertyInfo.isVar) { val setterName = JvmAbi.setterName(propertyInfo.name) - val setterSignature = MethodSignatureUtil.createMethodSignature(setterName, arrayOf(propertyInfo.psiType), emptyArray(), PsiSubstitutor.EMPTY) + val setterSignature = MethodSignatureUtil.createMethodSignature( + setterName, arrayOf(propertyInfo.psiType), emptyArray(), PsiSubstitutor.EMPTY + ) if (setterSignature in prohibitedSignatures) { memberToPropertyInfo.dropProperty(propertyInfo) continue @@ -367,7 +385,9 @@ private class PropertyDetector( } private fun convertModifiers(field: PsiField?, getMethod: PsiMethod?, setMethod: PsiMethod?, isOverride: Boolean): Modifiers { - val fieldModifiers = field?.let { converter.convertModifiers(it, false, false) } ?: Modifiers.Empty + val fieldModifiers = field?.let { + converter.convertModifiers(it, isMethodInOpenClass = false, isInObject = false) + } ?: Modifiers.Empty val getterModifiers = getMethod?.let { converter.convertModifiers(it, isOpenClass, false) } ?: Modifiers.Empty val setterModifiers = setMethod?.let { converter.convertModifiers(it, isOpenClass, false) } ?: Modifiers.Empty @@ -395,16 +415,16 @@ private class PropertyDetector( } val prototypes = listOfNotNull(field, getMethod, setMethod) - .map { PrototypeInfo(it, CommentsAndSpacesInheritance.NO_SPACES) } + .map { PrototypeInfo(it, CommentsAndSpacesInheritance.NO_SPACES) } return Modifiers(modifiers).assignPrototypes(*prototypes.toTypedArray()) } private class AccessorInfo( - val method: PsiMethod, - val field: PsiField?, - val kind: AccessorKind, - val propertyName: String, - val superProperty: SuperInfo.Property? + val method: PsiMethod, + val field: PsiField?, + val kind: AccessorKind, + val propertyName: String, + val superProperty: SuperInfo.Property? ) private fun getGetterInfo(method: PsiMethod, superProperty: SuperInfo.Property?): AccessorInfo? { @@ -432,8 +452,11 @@ private class PropertyDetector( return when { converter.inConversionScope(containingClass) -> { val propertyInfo = converter.propertyDetectionCache[containingClass][superMethod] - if (propertyInfo != null) SuperInfo.Property(propertyInfo.isVar, propertyInfo.name, propertyInfo.modifiers.contains(Modifier.ABSTRACT)) - else SuperInfo.Function + if (propertyInfo != null) { + SuperInfo.Property(propertyInfo.isVar, propertyInfo.name, propertyInfo.modifiers.contains(Modifier.ABSTRACT)) + } else { + SuperInfo.Function + } } superMethod is KtLightMethod -> { val origin = superMethod.kotlinOrigin @@ -510,8 +533,7 @@ private class PropertyDetector( val refExpr = expression as? PsiReferenceExpression ?: return null if (static) { if (!refExpr.isQualifierEmptyOrClass(psiClass)) return null - } - else { + } else { if (!refExpr.isQualifierEmptyOrThis()) return null } val field = refExpr.resolve() as? PsiField ?: return null diff --git a/nj2k/src/org/jetbrains/kotlin/nj2k/psiUtils.kt b/nj2k/src/org/jetbrains/kotlin/nj2k/psiUtils.kt index 083cd0949ab..e0f21784e48 100644 --- a/nj2k/src/org/jetbrains/kotlin/nj2k/psiUtils.kt +++ b/nj2k/src/org/jetbrains/kotlin/nj2k/psiUtils.kt @@ -21,8 +21,7 @@ import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf //copied from old j2k fun canKeepEqEq(left: PsiExpression, right: PsiExpression?): Boolean { if (left.isNullLiteral() || (right?.isNullLiteral() == true)) return true - val type = left.type - when (type) { + when (val type = left.type) { is PsiPrimitiveType, is PsiArrayType -> return true is PsiClassType -> { @@ -84,7 +83,7 @@ fun PsiMember.modality(assignNonCodeElements: ((JKNonCodeElementsListOwner, PsiE private fun PsiMember.handleProtectedVisibility(referenceSearcher: ReferenceSearcher): Visibility { val originalClass = containingClass ?: return Visibility.PROTECTED // Search for usages only in Java because java-protected member cannot be used in Kotlin from same package - val usages = referenceSearcher.findUsagesForExternalCodeProcessing(this, true, false) + val usages = referenceSearcher.findUsagesForExternalCodeProcessing(this, searchJava = true, searchKotlin = false) return if (usages.any { !allowProtected(it.element, this, originalClass) }) Visibility.PUBLIC