diff --git a/idea/fir-view/src/FirExplorerToolWindow.kt b/idea/fir-view/src/FirExplorerToolWindow.kt index 4daa094230e..8ef6848d905 100644 --- a/idea/fir-view/src/FirExplorerToolWindow.kt +++ b/idea/fir-view/src/FirExplorerToolWindow.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -125,7 +125,6 @@ class FirExplorerToolWindow(private val project: Project, private val toolWindow val psi = (data as? FirElement)?.psi if (data is FirElement && psi != null) { if (FileDocumentManager.getInstance().getFile(currentEditor.document) == psi.containingFile.virtualFile) { - rangeHighlightMarkers += currentEditor.markupModel.addRangeHighlighter( psi.startOffset, min(currentEditor.document.textLength, psi.endOffset), @@ -288,8 +287,7 @@ private fun KType.renderSimple(): String { } return buildString { - val classifier = classifier - when (classifier) { + when (val classifier = classifier) { is KClass<*> -> append(classifier.simpleName) is KTypeParameter -> append(classifier.name) } diff --git a/idea/ide-common/src/org/jetbrains/kotlin/idea/analysis/AnalyzerUtil.kt b/idea/ide-common/src/org/jetbrains/kotlin/idea/analysis/AnalyzerUtil.kt index 330ce3da4e6..9661e14ff21 100644 --- a/idea/ide-common/src/org/jetbrains/kotlin/idea/analysis/AnalyzerUtil.kt +++ b/idea/ide-common/src/org/jetbrains/kotlin/idea/analysis/AnalyzerUtil.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.analysis @@ -37,15 +26,16 @@ import org.jetbrains.kotlin.types.expressions.ExpressionTypingServices import org.jetbrains.kotlin.types.expressions.KotlinTypeInfo import org.jetbrains.kotlin.types.expressions.PreliminaryDeclarationVisitor -@JvmOverloads fun KtExpression.computeTypeInfoInContext( - scope: LexicalScope, - contextExpression: KtExpression = this, - trace: BindingTrace = BindingTraceContext(), - dataFlowInfo: DataFlowInfo = DataFlowInfo.EMPTY, - expectedType: KotlinType = TypeUtils.NO_EXPECTED_TYPE, - isStatement: Boolean = false, - contextDependency: ContextDependency = ContextDependency.INDEPENDENT, - expressionTypingServices: ExpressionTypingServices = contextExpression.getResolutionFacade().frontendService() +@JvmOverloads +fun KtExpression.computeTypeInfoInContext( + scope: LexicalScope, + contextExpression: KtExpression = this, + trace: BindingTrace = BindingTraceContext(), + dataFlowInfo: DataFlowInfo = DataFlowInfo.EMPTY, + expectedType: KotlinType = TypeUtils.NO_EXPECTED_TYPE, + isStatement: Boolean = false, + contextDependency: ContextDependency = ContextDependency.INDEPENDENT, + expressionTypingServices: ExpressionTypingServices = contextExpression.getResolutionFacade().frontendService() ): KotlinTypeInfo { PreliminaryDeclarationVisitor.createForExpression(this, trace, expressionTypingServices.languageVersionSettings) return expressionTypingServices.getTypeInfo( @@ -53,52 +43,63 @@ import org.jetbrains.kotlin.types.expressions.PreliminaryDeclarationVisitor ) } -@JvmOverloads fun KtExpression.analyzeInContext( - scope: LexicalScope, - contextExpression: KtExpression = this, - trace: BindingTrace = BindingTraceContext(), - dataFlowInfo: DataFlowInfo = DataFlowInfo.EMPTY, - expectedType: KotlinType = TypeUtils.NO_EXPECTED_TYPE, - isStatement: Boolean = false, - contextDependency: ContextDependency = ContextDependency.INDEPENDENT, - expressionTypingServices: ExpressionTypingServices = contextExpression.getResolutionFacade().frontendService() +@JvmOverloads +fun KtExpression.analyzeInContext( + scope: LexicalScope, + contextExpression: KtExpression = this, + trace: BindingTrace = BindingTraceContext(), + dataFlowInfo: DataFlowInfo = DataFlowInfo.EMPTY, + expectedType: KotlinType = TypeUtils.NO_EXPECTED_TYPE, + isStatement: Boolean = false, + contextDependency: ContextDependency = ContextDependency.INDEPENDENT, + expressionTypingServices: ExpressionTypingServices = contextExpression.getResolutionFacade().frontendService() ): BindingContext { - computeTypeInfoInContext(scope, contextExpression, trace, dataFlowInfo, expectedType, isStatement, contextDependency, expressionTypingServices) + computeTypeInfoInContext( + scope, + contextExpression, + trace, + dataFlowInfo, + expectedType, + isStatement, + contextDependency, + expressionTypingServices + ) return trace.bindingContext } -@JvmOverloads fun KtExpression.computeTypeInContext( - scope: LexicalScope, - contextExpression: KtExpression = this, - trace: BindingTrace = BindingTraceContext(), - dataFlowInfo: DataFlowInfo = DataFlowInfo.EMPTY, - expectedType: KotlinType = TypeUtils.NO_EXPECTED_TYPE -): KotlinType? { - return computeTypeInfoInContext(scope, contextExpression, trace, dataFlowInfo, expectedType).type -} +@JvmOverloads +fun KtExpression.computeTypeInContext( + scope: LexicalScope, + contextExpression: KtExpression = this, + trace: BindingTrace = BindingTraceContext(), + dataFlowInfo: DataFlowInfo = DataFlowInfo.EMPTY, + expectedType: KotlinType = TypeUtils.NO_EXPECTED_TYPE +): KotlinType? = computeTypeInfoInContext(scope, contextExpression, trace, dataFlowInfo, expectedType).type -@JvmOverloads fun KtExpression.analyzeAsReplacement( - expressionToBeReplaced: KtExpression, - bindingContext: BindingContext, - scope: LexicalScope, - trace: BindingTrace = DelegatingBindingTrace(bindingContext, "Temporary trace for analyzeAsReplacement()"), - contextDependency: ContextDependency = ContextDependency.INDEPENDENT -): BindingContext { - return analyzeInContext(scope, - expressionToBeReplaced, - dataFlowInfo = bindingContext.getDataFlowInfoBefore(expressionToBeReplaced), - expectedType = bindingContext[BindingContext.EXPECTED_EXPRESSION_TYPE, expressionToBeReplaced] ?: TypeUtils.NO_EXPECTED_TYPE, - isStatement = expressionToBeReplaced.isUsedAsStatement(bindingContext), - trace = trace, - contextDependency = contextDependency) -} +@JvmOverloads +fun KtExpression.analyzeAsReplacement( + expressionToBeReplaced: KtExpression, + bindingContext: BindingContext, + scope: LexicalScope, + trace: BindingTrace = DelegatingBindingTrace(bindingContext, "Temporary trace for analyzeAsReplacement()"), + contextDependency: ContextDependency = ContextDependency.INDEPENDENT +): BindingContext = analyzeInContext( + scope, + expressionToBeReplaced, + dataFlowInfo = bindingContext.getDataFlowInfoBefore(expressionToBeReplaced), + expectedType = bindingContext[BindingContext.EXPECTED_EXPRESSION_TYPE, expressionToBeReplaced] ?: TypeUtils.NO_EXPECTED_TYPE, + isStatement = expressionToBeReplaced.isUsedAsStatement(bindingContext), + trace = trace, + contextDependency = contextDependency +) -@JvmOverloads fun KtExpression.analyzeAsReplacement( - expressionToBeReplaced: KtExpression, - bindingContext: BindingContext, - resolutionFacade: ResolutionFacade = expressionToBeReplaced.getResolutionFacade(), - trace: BindingTrace = DelegatingBindingTrace(bindingContext, "Temporary trace for analyzeAsReplacement()"), - contextDependency: ContextDependency = ContextDependency.INDEPENDENT +@JvmOverloads +fun KtExpression.analyzeAsReplacement( + expressionToBeReplaced: KtExpression, + bindingContext: BindingContext, + resolutionFacade: ResolutionFacade = expressionToBeReplaced.getResolutionFacade(), + trace: BindingTrace = DelegatingBindingTrace(bindingContext, "Temporary trace for analyzeAsReplacement()"), + contextDependency: ContextDependency = ContextDependency.INDEPENDENT ): BindingContext { val scope = expressionToBeReplaced.getResolutionScope(bindingContext, resolutionFacade) return analyzeAsReplacement(expressionToBeReplaced, bindingContext, scope, trace, contextDependency) diff --git a/idea/ide-common/src/org/jetbrains/kotlin/idea/caches/resolve/resolutionApi.kt b/idea/ide-common/src/org/jetbrains/kotlin/idea/caches/resolve/resolutionApi.kt index 24f69ebf324..e76a8b8b157 100644 --- a/idea/ide-common/src/org/jetbrains/kotlin/idea/caches/resolve/resolutionApi.kt +++ b/idea/ide-common/src/org/jetbrains/kotlin/idea/caches/resolve/resolutionApi.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @file:JvmName("ResolutionUtils") @@ -20,7 +9,8 @@ package org.jetbrains.kotlin.idea.caches.resolve import org.jetbrains.kotlin.analyzer.AnalysisResult import org.jetbrains.kotlin.caches.resolve.KotlinCacheService -import org.jetbrains.kotlin.descriptors.* +import org.jetbrains.kotlin.descriptors.DeclarationDescriptor +import org.jetbrains.kotlin.descriptors.ModuleDescriptor import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* @@ -165,7 +155,8 @@ inline fun T.analyzeWithContent(): BindingContext where T : KtDeclar * @ref [org.jetbrains.kotlin.idea.caches.resolve.PerFileAnalysisCache] */ fun KtFile.analyzeWithAllCompilerChecks(vararg extraFiles: KtFile): AnalysisResult = - KotlinCacheService.getInstance(project).getResolutionFacade(listOf(this) + extraFiles.toList()).analyzeWithAllCompilerChecks(listOf(this)) + KotlinCacheService.getInstance(project).getResolutionFacade(listOf(this) + extraFiles.toList()) + .analyzeWithAllCompilerChecks(listOf(this)) /** * This function is expected to produce the same result as compiler for the given element and its children (including diagnostics, @@ -187,13 +178,18 @@ fun KtElement.analyzeWithAllCompilerChecks(): AnalysisResult = getResolutionFaca // this method don't check visibility and collect all descriptors with given fqName fun ResolutionFacade.resolveImportReference( - moduleDescriptor: ModuleDescriptor, - fqName: FqName + moduleDescriptor: ModuleDescriptor, + fqName: FqName ): Collection { val importDirective = KtPsiFactory(project).createImportDirective(ImportPath(fqName, false)) val qualifiedExpressionResolver = this.getFrontendService(moduleDescriptor, QualifiedExpressionResolver::class.java) return qualifiedExpressionResolver.processImportReference( - importDirective, moduleDescriptor, BindingTraceContext(), excludedImportNames = emptyList(), packageFragmentForVisibilityCheck = null)?.getContributedDescriptors() ?: emptyList() + importDirective, + moduleDescriptor, + BindingTraceContext(), + excludedImportNames = emptyList(), + packageFragmentForVisibilityCheck = null + )?.getContributedDescriptors() ?: emptyList() } @Suppress("DEPRECATION") diff --git a/idea/ide-common/src/org/jetbrains/kotlin/idea/codeInsight/ReferenceVariantsHelper.kt b/idea/ide-common/src/org/jetbrains/kotlin/idea/codeInsight/ReferenceVariantsHelper.kt index 99dc68cec1c..edd5897faa4 100644 --- a/idea/ide-common/src/org/jetbrains/kotlin/idea/codeInsight/ReferenceVariantsHelper.kt +++ b/idea/ide-common/src/org/jetbrains/kotlin/idea/codeInsight/ReferenceVariantsHelper.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.codeInsight @@ -241,9 +230,10 @@ class ReferenceVariantsHelper( if (callType == CallType.SUPER_MEMBERS) { // we need to unwrap fake overrides in case of "super." because ShadowedDeclarationsFilter does not work correctly return descriptors.flatMapTo(LinkedHashSet()) { - if (it is CallableMemberDescriptor && it.kind == CallableMemberDescriptor.Kind.FAKE_OVERRIDE) it.overriddenDescriptors else listOf( - it - ) + if (it is CallableMemberDescriptor && it.kind == CallableMemberDescriptor.Kind.FAKE_OVERRIDE) + it.overriddenDescriptors + else + listOf(it) } } @@ -479,8 +469,9 @@ fun ResolutionScope.collectSyntheticStaticMembersAndConstructors( nameFilter: (Name) -> Boolean ): List { val syntheticScopes = resolutionFacade.getFrontendService(SyntheticScopes::class.java) - return (syntheticScopes.forceEnableSamAdapters().collectSyntheticStaticFunctions(this) + syntheticScopes.collectSyntheticConstructors(this)) - .filter { kindFilter.accepts(it) && nameFilter(it.name) } + return (syntheticScopes.forceEnableSamAdapters().collectSyntheticStaticFunctions(this) + syntheticScopes.collectSyntheticConstructors( + this + )).filter { kindFilter.accepts(it) && nameFilter(it.name) } } // New Inference disables scope with synthetic SAM-adapters because it uses conversions for resolution diff --git a/idea/ide-common/src/org/jetbrains/kotlin/idea/kdoc/SampleResolutionService.kt b/idea/ide-common/src/org/jetbrains/kotlin/idea/kdoc/SampleResolutionService.kt index 3a918910a1a..db364164fc0 100644 --- a/idea/ide-common/src/org/jetbrains/kotlin/idea/kdoc/SampleResolutionService.kt +++ b/idea/ide-common/src/org/jetbrains/kotlin/idea/kdoc/SampleResolutionService.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.kdoc @@ -22,14 +11,24 @@ import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.resolve.BindingContext interface SampleResolutionService { - fun resolveSample(context: BindingContext, fromDescriptor: DeclarationDescriptor, resolutionFacade: ResolutionFacade, qualifiedName: List): Collection + fun resolveSample( + context: BindingContext, + fromDescriptor: DeclarationDescriptor, + resolutionFacade: ResolutionFacade, + qualifiedName: List + ): Collection companion object { /** * It's internal implementation, please use [resolveKDocSampleLink], or [resolveKDocLink] */ - internal fun resolveSample(context: BindingContext, fromDescriptor: DeclarationDescriptor, resolutionFacade: ResolutionFacade, qualifiedName: List): Collection { + internal fun resolveSample( + context: BindingContext, + fromDescriptor: DeclarationDescriptor, + resolutionFacade: ResolutionFacade, + qualifiedName: List + ): Collection { val instance = ServiceManager.getService(resolutionFacade.project, SampleResolutionService::class.java) return instance?.resolveSample(context, fromDescriptor, resolutionFacade, qualifiedName) ?: emptyList() } diff --git a/idea/ide-common/src/org/jetbrains/kotlin/idea/kdoc/resolveKDocLink.kt b/idea/ide-common/src/org/jetbrains/kotlin/idea/kdoc/resolveKDocLink.kt index dbb3d38fb19..20ef2a09f1c 100644 --- a/idea/ide-common/src/org/jetbrains/kotlin/idea/kdoc/resolveKDocLink.kt +++ b/idea/ide-common/src/org/jetbrains/kotlin/idea/kdoc/resolveKDocLink.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.kdoc @@ -46,17 +35,16 @@ import org.jetbrains.kotlin.utils.SmartList import org.jetbrains.kotlin.utils.addIfNotNull fun resolveKDocLink( - context: BindingContext, - resolutionFacade: ResolutionFacade, - fromDescriptor: DeclarationDescriptor, - fromSubjectOfTag: KDocTag?, - qualifiedName: List -): Collection = - when (fromSubjectOfTag?.knownTag) { - KDocKnownTag.PARAM -> resolveParamLink(fromDescriptor, qualifiedName) - KDocKnownTag.SAMPLE -> resolveKDocSampleLink(context, resolutionFacade, fromDescriptor, qualifiedName) - else -> resolveDefaultKDocLink(context, resolutionFacade, fromDescriptor, qualifiedName) - } + context: BindingContext, + resolutionFacade: ResolutionFacade, + fromDescriptor: DeclarationDescriptor, + fromSubjectOfTag: KDocTag?, + qualifiedName: List +): Collection = when (fromSubjectOfTag?.knownTag) { + KDocKnownTag.PARAM -> resolveParamLink(fromDescriptor, qualifiedName) + KDocKnownTag.SAMPLE -> resolveKDocSampleLink(context, resolutionFacade, fromDescriptor, qualifiedName) + else -> resolveDefaultKDocLink(context, resolutionFacade, fromDescriptor, qualifiedName) +} fun getParamDescriptors(fromDescriptor: DeclarationDescriptor): List { @@ -89,10 +77,10 @@ private fun resolveParamLink(fromDescriptor: DeclarationDescriptor, qualifiedNam } fun resolveKDocSampleLink( - context: BindingContext, - resolutionFacade: ResolutionFacade, - fromDescriptor: DeclarationDescriptor, - qualifiedName: List + context: BindingContext, + resolutionFacade: ResolutionFacade, + fromDescriptor: DeclarationDescriptor, + qualifiedName: List ): Collection { val resolvedViaService = SampleResolutionService.resolveSample(context, fromDescriptor, resolutionFacade, qualifiedName) @@ -102,10 +90,10 @@ fun resolveKDocSampleLink( } private fun resolveDefaultKDocLink( - context: BindingContext, - resolutionFacade: ResolutionFacade, - fromDescriptor: DeclarationDescriptor, - qualifiedName: List + context: BindingContext, + resolutionFacade: ResolutionFacade, + fromDescriptor: DeclarationDescriptor, + qualifiedName: List ): Collection { val contextScope = getKDocLinkResolutionScope(resolutionFacade, fromDescriptor) @@ -137,14 +125,19 @@ private fun resolveDefaultKDocLink( val factory = KtPsiFactory(resolutionFacade.project) // TODO escape identifiers val codeFragment = factory.createExpressionCodeFragment(qualifiedName.joinToString("."), contextElement) - val qualifiedExpression = codeFragment.findElementAt(codeFragment.textLength - 1)?.getStrictParentOfType() ?: return emptyList() - val (descriptor, memberName) = qualifiedExpressionResolver.resolveClassOrPackageInQualifiedExpression(qualifiedExpression, contextScope, context) + val qualifiedExpression = + codeFragment.findElementAt(codeFragment.textLength - 1)?.getStrictParentOfType() ?: return emptyList() + val (descriptor, memberName) = qualifiedExpressionResolver.resolveClassOrPackageInQualifiedExpression( + qualifiedExpression, + contextScope, + context + ) if (descriptor == null) return emptyList() if (memberName != null) { val memberScope = getKDocLinkMemberScope(descriptor, contextScope) return memberScope.getContributedFunctions(memberName, NoLookupLocation.FROM_IDE) + - memberScope.getContributedVariables(memberName, NoLookupLocation.FROM_IDE) + - listOfNotNull(memberScope.getContributedClassifier(memberName, NoLookupLocation.FROM_IDE)) + memberScope.getContributedVariables(memberName, NoLookupLocation.FROM_IDE) + + listOfNotNull(memberScope.getContributedClassifier(memberName, NoLookupLocation.FROM_IDE)) } return listOf(descriptor) } @@ -155,16 +148,18 @@ private fun getPackageInnerScope(descriptor: PackageFragmentDescriptor): MemberS private fun getClassInnerScope(outerScope: LexicalScope, descriptor: ClassDescriptor): LexicalScope { - val headerScope = LexicalScopeImpl(outerScope, descriptor, false, descriptor.thisAsReceiverParameter, - LexicalScopeKind.SYNTHETIC) { + val headerScope = LexicalScopeImpl( + outerScope, descriptor, false, descriptor.thisAsReceiverParameter, + LexicalScopeKind.SYNTHETIC + ) { descriptor.declaredTypeParameters.forEach { addClassifierDescriptor(it) } descriptor.constructors.forEach { addFunctionDescriptor(it) } } val scopeChain = listOfNotNull( - descriptor.defaultType.memberScope, - descriptor.staticScope, - descriptor.companionObjectDescriptor?.defaultType?.memberScope + descriptor.defaultType.memberScope, + descriptor.staticScope, + descriptor.companionObjectDescriptor?.defaultType?.memberScope ) return LexicalChainedScope(headerScope, descriptor, false, null, LexicalScopeKind.SYNTHETIC, scopeChain) } @@ -180,9 +175,10 @@ fun getKDocLinkResolutionScope(resolutionFacade: ResolutionFacade, contextDescri is ClassDescriptor -> getClassInnerScope(getOuterScope(contextDescriptor, resolutionFacade), contextDescriptor) - is FunctionDescriptor -> - FunctionDescriptorUtil.getFunctionInnerScope(getOuterScope(contextDescriptor, resolutionFacade), - contextDescriptor, LocalRedeclarationChecker.DO_NOTHING) + is FunctionDescriptor -> FunctionDescriptorUtil.getFunctionInnerScope( + getOuterScope(contextDescriptor, resolutionFacade), + contextDescriptor, LocalRedeclarationChecker.DO_NOTHING + ) is PropertyDescriptor -> ScopeUtils.makeScopeForPropertyHeader(getOuterScope(contextDescriptor, resolutionFacade), contextDescriptor) @@ -197,13 +193,14 @@ fun getKDocLinkResolutionScope(resolutionFacade: ResolutionFacade, contextDescri private fun getOuterScope(descriptor: DeclarationDescriptorWithSource, resolutionFacade: ResolutionFacade): LexicalScope { val parent = descriptor.containingDeclaration!! if (parent is PackageFragmentDescriptor) { - val containingFile = (descriptor.source as? PsiSourceElement)?.psi?.containingFile as? KtFile - ?: return LexicalScope.Base(ImportingScope.Empty, parent) + val containingFile = (descriptor.source as? PsiSourceElement)?.psi?.containingFile as? KtFile ?: return LexicalScope.Base( + ImportingScope.Empty, + parent + ) val kotlinCacheService = ServiceManager.getService(containingFile.project, KotlinCacheService::class.java) val facadeToUse = kotlinCacheService?.getResolutionFacade(listOf(containingFile)) ?: resolutionFacade return facadeToUse.getFileResolutionScope(containingFile) - } - else { + } else { return getKDocLinkResolutionScope(resolutionFacade, parent) } } @@ -215,12 +212,14 @@ fun getKDocLinkMemberScope(descriptor: DeclarationDescriptor, contextScope: Lexi is PackageViewDescriptor -> descriptor.memberScope is ClassDescriptor -> { - ChainedMemberScope("Member scope for KDoc resolve", listOfNotNull( + ChainedMemberScope( + "Member scope for KDoc resolve", listOfNotNull( descriptor.unsubstitutedMemberScope, descriptor.staticScope, descriptor.companionObjectDescriptor?.unsubstitutedMemberScope, ExtensionsScope(descriptor, contextScope) - )) + ) + ) } else -> MemberScope.Empty @@ -228,40 +227,53 @@ fun getKDocLinkMemberScope(descriptor: DeclarationDescriptor, contextScope: Lexi } private class ExtensionsScope( - private val receiverClass: ClassDescriptor, - private val contextScope: LexicalScope + private val receiverClass: ClassDescriptor, + private val contextScope: LexicalScope ) : MemberScope { private val receiverTypes = listOf(receiverClass.defaultType) override fun getContributedFunctions(name: Name, location: LookupLocation): Collection { - return contextScope.collectFunctions(name, location) - .flatMap { if (it is SimpleFunctionDescriptor && it.isExtension) it.substituteExtensionIfCallable(receiverTypes, CallType.DOT) else emptyList() } + return contextScope.collectFunctions(name, location).flatMap { + if (it is SimpleFunctionDescriptor && it.isExtension) it.substituteExtensionIfCallable( + receiverTypes, + CallType.DOT + ) else emptyList() + } } override fun getContributedVariables(name: Name, location: LookupLocation): Collection { - return contextScope.collectVariables(name, location) - .flatMap { if (it is PropertyDescriptor && it.isExtension) it.substituteExtensionIfCallable(receiverTypes, CallType.DOT) else emptyList() } + return contextScope.collectVariables(name, location).flatMap { + if (it is PropertyDescriptor && it.isExtension) it.substituteExtensionIfCallable( + receiverTypes, + CallType.DOT + ) else emptyList() + } } override fun getContributedClassifier(name: Name, location: LookupLocation): ClassifierDescriptor? = null - override fun getContributedDescriptors(kindFilter: DescriptorKindFilter, nameFilter: (Name) -> Boolean): Collection { + override fun getContributedDescriptors( + kindFilter: DescriptorKindFilter, + nameFilter: (Name) -> Boolean + ): Collection { if (DescriptorKindExclude.Extensions in kindFilter.excludes) return emptyList() - return contextScope.collectDescriptorsFiltered(kindFilter exclude DescriptorKindExclude.NonExtensions, nameFilter, changeNamesForAliased = true) - .flatMap { if (it is CallableDescriptor && it.isExtension) it.substituteExtensionIfCallable(receiverTypes, CallType.DOT) else emptyList() } + return contextScope.collectDescriptorsFiltered( + kindFilter exclude DescriptorKindExclude.NonExtensions, + nameFilter, + changeNamesForAliased = true + ).flatMap { + if (it is CallableDescriptor && it.isExtension) it.substituteExtensionIfCallable( + receiverTypes, + CallType.DOT + ) else emptyList() + } } - override fun getFunctionNames(): Set { - return getContributedDescriptors(kindFilter = DescriptorKindFilter.FUNCTIONS) - .map { it.name } - .toSet() - } + override fun getFunctionNames(): Set = + getContributedDescriptors(kindFilter = DescriptorKindFilter.FUNCTIONS).map { it.name }.toSet() - override fun getVariableNames(): Set { - return getContributedDescriptors(kindFilter = DescriptorKindFilter.VARIABLES) - .map { it.name } - .toSet() - } + override fun getVariableNames(): Set = + getContributedDescriptors(kindFilter = DescriptorKindFilter.VARIABLES).map { it.name }.toSet() override fun getClassifierNames() = null diff --git a/idea/ide-common/src/org/jetbrains/kotlin/idea/refactoring/introduce/ExtractableSubstringInfo.kt b/idea/ide-common/src/org/jetbrains/kotlin/idea/refactoring/introduce/ExtractableSubstringInfo.kt index d69f144e0b0..2316e1331c0 100644 --- a/idea/ide-common/src/org/jetbrains/kotlin/idea/refactoring/introduce/ExtractableSubstringInfo.kt +++ b/idea/ide-common/src/org/jetbrains/kotlin/idea/refactoring/introduce/ExtractableSubstringInfo.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.introduce @@ -35,11 +24,11 @@ import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.TypeUtils class ExtractableSubstringInfo( - val startEntry: KtStringTemplateEntry, - val endEntry: KtStringTemplateEntry, - val prefix: String, - val suffix: String, - type: KotlinType? = null + val startEntry: KtStringTemplateEntry, + val endEntry: KtStringTemplateEntry, + val prefix: String, + val suffix: String, + type: KotlinType? = null ) { private fun guessLiteralType(literal: String): KotlinType { val facade = template.getResolutionFacade() diff --git a/idea/ide-common/src/org/jetbrains/kotlin/idea/resolve/ResolutionFacade.kt b/idea/ide-common/src/org/jetbrains/kotlin/idea/resolve/ResolutionFacade.kt index 969a1d81d47..b938fa38087 100644 --- a/idea/ide-common/src/org/jetbrains/kotlin/idea/resolve/ResolutionFacade.kt +++ b/idea/ide-common/src/org/jetbrains/kotlin/idea/resolve/ResolutionFacade.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.resolve @@ -51,8 +40,6 @@ interface ResolutionFacade { } -inline fun ResolutionFacade.frontendService(): T - = this.getFrontendService(T::class.java) +inline fun ResolutionFacade.frontendService(): T = this.getFrontendService(T::class.java) -inline fun ResolutionFacade.ideService(): T - = this.getIdeService(T::class.java) \ No newline at end of file +inline fun ResolutionFacade.ideService(): T = this.getIdeService(T::class.java) \ No newline at end of file diff --git a/idea/ide-common/src/org/jetbrains/kotlin/idea/util/CallType.kt b/idea/ide-common/src/org/jetbrains/kotlin/idea/util/CallType.kt index f8b736c85c7..fc235c90576 100644 --- a/idea/ide-common/src/org/jetbrains/kotlin/idea/util/CallType.kt +++ b/idea/ide-common/src/org/jetbrains/kotlin/idea/util/CallType.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.util @@ -146,7 +135,8 @@ sealed class CallTypeAndReceiver(CallType.PACKAGE_DIRECTIVE, receiver) + class PACKAGE_DIRECTIVE(receiver: KtExpression?) : + CallTypeAndReceiver(CallType.PACKAGE_DIRECTIVE, receiver) class TYPE(receiver: KtExpression?) : CallTypeAndReceiver(CallType.TYPE, receiver) class DELEGATE(receiver: KtExpression?) : CallTypeAndReceiver(CallType.DELEGATE, receiver) diff --git a/idea/ide-common/src/org/jetbrains/kotlin/idea/util/FuzzyType.kt b/idea/ide-common/src/org/jetbrains/kotlin/idea/util/FuzzyType.kt index cceb1daeede..b19ba14be7b 100644 --- a/idea/ide-common/src/org/jetbrains/kotlin/idea/util/FuzzyType.kt +++ b/idea/ide-common/src/org/jetbrains/kotlin/idea/util/FuzzyType.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @file:JvmName("FuzzyTypeUtils") @@ -27,7 +16,6 @@ import org.jetbrains.kotlin.resolve.calls.inference.constraintPosition.Constrain import org.jetbrains.kotlin.types.* import org.jetbrains.kotlin.types.checker.StrictEqualityTypeChecker import org.jetbrains.kotlin.types.typeUtil.* -import org.jetbrains.kotlin.utils.addToStdlib.safeAs import java.util.* fun CallableDescriptor.fuzzyReturnType() = returnType?.toFuzzyType(typeParameters) @@ -67,8 +55,8 @@ fun FuzzyType.presentationType(): KotlinType { fun KotlinType.toFuzzyType(freeParameters: Collection) = FuzzyType(this, freeParameters) class FuzzyType( - val type: KotlinType, - freeParameters: Collection + val type: KotlinType, + freeParameters: Collection ) { val freeParameters: Set @@ -79,12 +67,10 @@ class FuzzyType( if (usedTypeParameters.isNotEmpty()) { val originalFreeParameters = freeParameters.map { it.toOriginal() }.toSet() this.freeParameters = usedTypeParameters.filter { it.toOriginal() in originalFreeParameters }.toSet() - } - else { + } else { this.freeParameters = emptySet() } - } - else { + } else { this.freeParameters = emptySet() } } @@ -115,17 +101,13 @@ class FuzzyType( } } - fun checkIsSubtypeOf(otherType: FuzzyType): TypeSubstitutor? - = matchedSubstitutor(otherType, MatchKind.IS_SUBTYPE) + fun checkIsSubtypeOf(otherType: FuzzyType): TypeSubstitutor? = matchedSubstitutor(otherType, MatchKind.IS_SUBTYPE) - fun checkIsSuperTypeOf(otherType: FuzzyType): TypeSubstitutor? - = matchedSubstitutor(otherType, MatchKind.IS_SUPERTYPE) + fun checkIsSuperTypeOf(otherType: FuzzyType): TypeSubstitutor? = matchedSubstitutor(otherType, MatchKind.IS_SUPERTYPE) - fun checkIsSubtypeOf(otherType: KotlinType): TypeSubstitutor? - = checkIsSubtypeOf(otherType.toFuzzyType(emptyList())) + fun checkIsSubtypeOf(otherType: KotlinType): TypeSubstitutor? = checkIsSubtypeOf(otherType.toFuzzyType(emptyList())) - fun checkIsSuperTypeOf(otherType: KotlinType): TypeSubstitutor? - = checkIsSuperTypeOf(otherType.toFuzzyType(emptyList())) + fun checkIsSuperTypeOf(otherType: KotlinType): TypeSubstitutor? = checkIsSuperTypeOf(otherType.toFuzzyType(emptyList())) private enum class MatchKind { IS_SUBTYPE, @@ -181,14 +163,14 @@ class FuzzyType( }.buildSubstitutor() val substitutionMap: Map = constraintSystem.typeVariables - .map { it.originalTypeParameter } - .associateBy( - keySelector = { it.typeConstructor }, - valueTransform = { - val typeProjection = TypeProjectionImpl(Variance.INVARIANT, it.defaultType) - val substitutedProjection = substitutorToKeepCapturedTypes.substitute(typeProjection) - substitutedProjection?.takeUnless { ErrorUtils.containsUninferredParameter(it.type) } ?: typeProjection - }) + .map { it.originalTypeParameter } + .associateBy( + keySelector = { it.typeConstructor }, + valueTransform = { + val typeProjection = TypeProjectionImpl(Variance.INVARIANT, it.defaultType) + val substitutedProjection = substitutorToKeepCapturedTypes.substitute(typeProjection) + substitutedProjection?.takeUnless { ErrorUtils.containsUninferredParameter(it.type) } ?: typeProjection + }) return TypeConstructorSubstitution.createByConstructorsMap(substitutionMap, approximateCapturedTypes = true).buildSubstitutor() } } @@ -199,7 +181,10 @@ fun TypeSubstitution.hasConflictWith(other: TypeSubstitution, freeParameters: Co val type = parameter.defaultType val substituted1 = this[type] ?: return@any false val substituted2 = other[type] ?: return@any false - !StrictEqualityTypeChecker.strictEqualTypes(substituted1.type.unwrap(), substituted2.type.unwrap()) || substituted1.projectionKind != substituted2.projectionKind + !StrictEqualityTypeChecker.strictEqualTypes( + substituted1.type.unwrap(), + substituted2.type.unwrap() + ) || substituted1.projectionKind != substituted2.projectionKind } } diff --git a/idea/ide-common/src/org/jetbrains/kotlin/idea/util/ImportInsertHelper.kt b/idea/ide-common/src/org/jetbrains/kotlin/idea/util/ImportInsertHelper.kt index 26ab2e57d07..a6eefab4777 100644 --- a/idea/ide-common/src/org/jetbrains/kotlin/idea/util/ImportInsertHelper.kt +++ b/idea/ide-common/src/org/jetbrains/kotlin/idea/util/ImportInsertHelper.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.util @@ -33,11 +22,16 @@ abstract class ImportInsertHelper { abstract val importSortComparator: Comparator - abstract fun importDescriptor(file: KtFile, descriptor: DeclarationDescriptor, forceAllUnderImport: Boolean = false): ImportDescriptorResult + abstract fun importDescriptor( + file: KtFile, + descriptor: DeclarationDescriptor, + forceAllUnderImport: Boolean = false + ): ImportDescriptorResult companion object { - @JvmStatic fun getInstance(project: Project): ImportInsertHelper - = ServiceManager.getService(project, ImportInsertHelper::class.java) + @JvmStatic + fun getInstance(project: Project): ImportInsertHelper = + ServiceManager.getService(project, ImportInsertHelper::class.java) } } diff --git a/idea/ide-common/src/org/jetbrains/kotlin/idea/util/NotPropertyList.kt b/idea/ide-common/src/org/jetbrains/kotlin/idea/util/NotPropertyList.kt index f102e7e07a2..a2db2379782 100644 --- a/idea/ide-common/src/org/jetbrains/kotlin/idea/util/NotPropertyList.kt +++ b/idea/ide-common/src/org/jetbrains/kotlin/idea/util/NotPropertyList.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.util @@ -29,4 +18,4 @@ fun FunctionDescriptor.shouldNotConvertToProperty(notProperties: Set) = - getMethod.shouldNotConvertToProperty(set) || setMethod?.shouldNotConvertToProperty(set) ?: false \ No newline at end of file + getMethod.shouldNotConvertToProperty(set) || setMethod?.shouldNotConvertToProperty(set) ?: false \ No newline at end of file diff --git a/idea/ide-common/src/org/jetbrains/kotlin/idea/util/ShadowedDeclarationsFilter.kt b/idea/ide-common/src/org/jetbrains/kotlin/idea/util/ShadowedDeclarationsFilter.kt index c172301280c..7900d7274c2 100644 --- a/idea/ide-common/src/org/jetbrains/kotlin/idea/util/ShadowedDeclarationsFilter.kt +++ b/idea/ide-common/src/org/jetbrains/kotlin/idea/util/ShadowedDeclarationsFilter.kt @@ -1,23 +1,11 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.util import com.intellij.psi.PsiElement -import org.jetbrains.kotlin.config.LanguageVersionSettings import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.imports.importableFqName import org.jetbrains.kotlin.idea.resolve.ResolutionFacade @@ -40,17 +28,17 @@ import org.jetbrains.kotlin.util.descriptorsEqualWithSubstitution import java.util.* class ShadowedDeclarationsFilter( - private val bindingContext: BindingContext, - private val resolutionFacade: ResolutionFacade, - private val context: PsiElement, - private val explicitReceiverValue: ReceiverValue? + private val bindingContext: BindingContext, + private val resolutionFacade: ResolutionFacade, + private val context: PsiElement, + private val explicitReceiverValue: ReceiverValue? ) { companion object { fun create( - bindingContext: BindingContext, - resolutionFacade: ResolutionFacade, - context: PsiElement, - callTypeAndReceiver: CallTypeAndReceiver<*, *> + bindingContext: BindingContext, + resolutionFacade: ResolutionFacade, + context: PsiElement, + callTypeAndReceiver: CallTypeAndReceiver<*, *> ): ShadowedDeclarationsFilter? { val receiverExpression = when (callTypeAndReceiver) { is CallTypeAndReceiver.DEFAULT -> null @@ -73,20 +61,16 @@ class ShadowedDeclarationsFilter( private val psiFactory = KtPsiFactory(resolutionFacade.project) private val dummyExpressionFactory = DummyExpressionFactory(psiFactory) - fun filter(declarations: Collection): Collection { - return declarations - .groupBy { signature(it) } - .values - .flatMap { group -> filterEqualSignatureGroup(group) } - } + fun filter(declarations: Collection): Collection = + declarations.groupBy { signature(it) }.values.flatMap { group -> filterEqualSignatureGroup(group) } fun createNonImportedDeclarationsFilter( - importedDeclarations: Collection + importedDeclarations: Collection ): (Collection) -> Collection { val importedDeclarationsSet = importedDeclarations.toSet() val importedDeclarationsBySignature = importedDeclarationsSet.groupBy { signature(it) } - return filter@ { declarations -> + return filter@{ declarations -> // optimization if (declarations.size == 1 && importedDeclarationsBySignature[signature(declarations.single())] == null) return@filter declarations @@ -103,19 +87,18 @@ class ShadowedDeclarationsFilter( } } - private fun signature(descriptor: DeclarationDescriptor): Any = - when (descriptor) { - is SimpleFunctionDescriptor -> FunctionSignature(descriptor) - is VariableDescriptor -> descriptor.name - is ClassDescriptor -> descriptor.importableFqName ?: descriptor - else -> descriptor - } + private fun signature(descriptor: DeclarationDescriptor): Any = when (descriptor) { + is SimpleFunctionDescriptor -> FunctionSignature(descriptor) + is VariableDescriptor -> descriptor.name + is ClassDescriptor -> descriptor.importableFqName ?: descriptor + else -> descriptor + } private fun packageName(descriptor: DeclarationDescriptor) = descriptor.importableFqName?.parent() private fun filterEqualSignatureGroup( - descriptors: Collection, - descriptorsToImport: Collection = emptyList() + descriptors: Collection, + descriptorsToImport: Collection = emptyList() ): Collection { if (descriptors.size == 1) return descriptors @@ -143,7 +126,8 @@ class ShadowedDeclarationsFilter( } val firstVarargIndex = parameters.withIndex().firstOrNull { it.value.varargElementType != null }?.index - val useNamedFromIndex = if (firstVarargIndex != null && firstVarargIndex != parameters.lastIndex) firstVarargIndex else parameters.size + val useNamedFromIndex = + if (firstVarargIndex != null && firstVarargIndex != parameters.lastIndex) firstVarargIndex else parameters.size class DummyArgument(val index: Int) : ValueArgument { private val expression = dummyArgumentExpressions[index] @@ -153,8 +137,7 @@ class ShadowedDeclarationsFilter( override val asName = parameters[index].name override val referenceExpression = null } - } - else { + } else { null } @@ -206,17 +189,23 @@ class ShadowedDeclarationsFilter( } val dataFlowInfo = bindingContext.getDataFlowInfoBefore(context) - val context = BasicCallResolutionContext.create(bindingTrace, scope, newCall, TypeUtils.NO_EXPECTED_TYPE, dataFlowInfo, - ContextDependency.INDEPENDENT, CheckArgumentTypesMode.CHECK_VALUE_ARGUMENTS, - false, /* languageVersionSettings */ resolutionFacade.frontendService(), - resolutionFacade.frontendService()) + val context = BasicCallResolutionContext.create( + bindingTrace, scope, newCall, TypeUtils.NO_EXPECTED_TYPE, dataFlowInfo, + ContextDependency.INDEPENDENT, CheckArgumentTypesMode.CHECK_VALUE_ARGUMENTS, + false, /* languageVersionSettings */ resolutionFacade.frontendService(), + resolutionFacade.frontendService() + ) val callResolver = resolutionFacade.frontendService() val results = if (isFunction) callResolver.resolveFunctionCall(context) else callResolver.resolveSimpleProperty(context) val resultingDescriptors = results.resultingCalls.map { it.resultingDescriptor } val resultingOriginals = resultingDescriptors.mapTo(HashSet()) { it.original } val filtered = descriptors.filter { candidateDescriptor -> - candidateDescriptor.original in resultingOriginals /* optimization */ - && resultingDescriptors.any { descriptorsEqualWithSubstitution(it, candidateDescriptor) } + candidateDescriptor.original in resultingOriginals /* optimization */ && resultingDescriptors.any { + descriptorsEqualWithSubstitution( + it, + candidateDescriptor + ) + } } return if (filtered.isNotEmpty()) filtered else descriptors /* something went wrong, none of our declarations among resolve candidates, let's not filter anything */ } diff --git a/idea/ide-common/src/org/jetbrains/kotlin/idea/util/TypeUtils.kt b/idea/ide-common/src/org/jetbrains/kotlin/idea/util/TypeUtils.kt index ab552c830ba..4716d2042ba 100644 --- a/idea/ide-common/src/org/jetbrains/kotlin/idea/util/TypeUtils.kt +++ b/idea/ide-common/src/org/jetbrains/kotlin/idea/util/TypeUtils.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @file:JvmName("TypeUtils") @@ -69,9 +58,8 @@ private fun KotlinType.approximateNonDynamicFlexibleTypes( approximation = if (nullability() == TypeNullability.NOT_NULL) approximation.makeNullableAsSpecified(false) else approximation - if (approximation.isMarkedNullable && !flexible.lowerBound.isMarkedNullable && TypeUtils.isTypeParameter(approximation) && TypeUtils.hasNullableSuperType( - approximation - ) + if (approximation.isMarkedNullable && !flexible.lowerBound + .isMarkedNullable && TypeUtils.isTypeParameter(approximation) && TypeUtils.hasNullableSuperType(approximation) ) { approximation = approximation.makeNullableAsSpecified(false) } diff --git a/idea/ide-common/src/org/jetbrains/kotlin/idea/util/Utils.kt b/idea/ide-common/src/org/jetbrains/kotlin/idea/util/Utils.kt index 589ddc45c52..62f334d6752 100644 --- a/idea/ide-common/src/org/jetbrains/kotlin/idea/util/Utils.kt +++ b/idea/ide-common/src/org/jetbrains/kotlin/idea/util/Utils.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.util @@ -56,14 +45,21 @@ fun KtFunctionLiteral.findLabelAndCall(): Pair { } fun SmartCastManager.getSmartCastVariantsWithLessSpecificExcluded( - receiverToCast: ReceiverValue, - bindingContext: BindingContext, - containingDeclarationOrModule: DeclarationDescriptor, - dataFlowInfo: DataFlowInfo, - languageVersionSettings: LanguageVersionSettings, - dataFlowValueFactory: DataFlowValueFactory + receiverToCast: ReceiverValue, + bindingContext: BindingContext, + containingDeclarationOrModule: DeclarationDescriptor, + dataFlowInfo: DataFlowInfo, + languageVersionSettings: LanguageVersionSettings, + dataFlowValueFactory: DataFlowValueFactory ): List { - val variants = getSmartCastVariants(receiverToCast, bindingContext, containingDeclarationOrModule, dataFlowInfo, languageVersionSettings, dataFlowValueFactory) + val variants = getSmartCastVariants( + receiverToCast, + bindingContext, + containingDeclarationOrModule, + dataFlowInfo, + languageVersionSettings, + dataFlowValueFactory + ) return variants.filter { type -> variants.all { another -> another === type || chooseMoreSpecific(type, another).let { it == null || it === type } } } diff --git a/idea/ide-common/src/org/jetbrains/kotlin/idea/util/extensionsUtils.kt b/idea/ide-common/src/org/jetbrains/kotlin/idea/util/extensionsUtils.kt index 8f694ebf7d1..39f3bcb2b16 100644 --- a/idea/ide-common/src/org/jetbrains/kotlin/idea/util/extensionsUtils.kt +++ b/idea/ide-common/src/org/jetbrains/kotlin/idea/util/extensionsUtils.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @file:JvmName("ExtensionUtils") @@ -33,8 +22,8 @@ import org.jetbrains.kotlin.types.typeUtil.makeNotNullable import org.jetbrains.kotlin.types.typeUtil.nullability fun TCallable.substituteExtensionIfCallable( - receiverTypes: Collection, - callType: CallType<*> + receiverTypes: Collection, + callType: CallType<*> ): Collection { if (!callType.descriptorKindFilter.accepts(this)) return listOf() @@ -44,22 +33,20 @@ fun TCallable.substituteExtensionIfCallable( } val extensionReceiverType = fuzzyExtensionReceiverType()!! - val substitutors = types - .mapNotNull { - var substitutor = extensionReceiverType.checkIsSuperTypeOf(it) - // check if we may fail due to receiver expression being nullable - if (substitutor == null && it.nullability() == TypeNullability.NULLABLE && extensionReceiverType.nullability() == TypeNullability.NOT_NULL) { - substitutor = extensionReceiverType.checkIsSuperTypeOf(it.makeNotNullable()) - } - substitutor - } + val substitutors = types.mapNotNull { + var substitutor = extensionReceiverType.checkIsSuperTypeOf(it) + // check if we may fail due to receiver expression being nullable + if (substitutor == null && it.nullability() == TypeNullability.NULLABLE && extensionReceiverType.nullability() == TypeNullability.NOT_NULL) { + substitutor = extensionReceiverType.checkIsSuperTypeOf(it.makeNotNullable()) + } + substitutor + } return if (typeParameters.isEmpty()) { // optimization for non-generic callables if (substitutors.any()) listOf(this) else listOf() - } - else { + } else { substitutors - .mapNotNull { @Suppress("UNCHECKED_CAST") (substitute(it) as TCallable?) } - .toList() + .mapNotNull { @Suppress("UNCHECKED_CAST") (substitute(it) as TCallable?) } + .toList() } } @@ -76,20 +63,16 @@ fun ReceiverValue?.getThisReceiverOwner(bindingContext: BindingContext): Declara } } -fun ReceiverValue?.getReceiverTargetDescriptor(bindingContext: BindingContext): DeclarationDescriptor? { - return when (this) { - is ExpressionReceiver -> { - val expression = KtPsiUtil.deparenthesize(this.expression) - val refExpression = when (expression) { - is KtThisExpression -> expression.instanceReference - is KtReferenceExpression -> expression - else -> null - } ?: return null - bindingContext[BindingContext.REFERENCE_TARGET, refExpression] - } - - is ImplicitReceiver -> this.declarationDescriptor - +fun ReceiverValue?.getReceiverTargetDescriptor(bindingContext: BindingContext): DeclarationDescriptor? = when (this) { + is ExpressionReceiver -> when (val expression = KtPsiUtil.deparenthesize(this.expression)) { + is KtThisExpression -> expression.instanceReference + is KtReferenceExpression -> expression else -> null + }?.let { referenceExpression -> + bindingContext[BindingContext.REFERENCE_TARGET, referenceExpression] } + + is ImplicitReceiver -> this.declarationDescriptor + + else -> null } diff --git a/idea/ide-common/src/org/jetbrains/kotlin/idea/util/implicitReceiversUtils.kt b/idea/ide-common/src/org/jetbrains/kotlin/idea/util/implicitReceiversUtils.kt index 4aa80468357..0c2b50031de 100644 --- a/idea/ide-common/src/org/jetbrains/kotlin/idea/util/implicitReceiversUtils.kt +++ b/idea/ide-common/src/org/jetbrains/kotlin/idea/util/implicitReceiversUtils.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.util @@ -42,14 +31,10 @@ interface ReceiverExpressionFactory { fun createExpression(psiFactory: KtPsiFactory, shortThis: Boolean = true): KtExpression } -fun LexicalScope.getFactoryForImplicitReceiverWithSubtypeOf(receiverType: KotlinType): ReceiverExpressionFactory? { - return getImplicitReceiversWithInstanceToExpression() - .entries - .firstOrNull { (receiverDescriptor, _) -> - receiverDescriptor.type.isSubtypeOf(receiverType) - } - ?.value -} +fun LexicalScope.getFactoryForImplicitReceiverWithSubtypeOf(receiverType: KotlinType): ReceiverExpressionFactory? = + getImplicitReceiversWithInstanceToExpression().entries.firstOrNull { (receiverDescriptor, _) -> + receiverDescriptor.type.isSubtypeOf(receiverType) + }?.value fun LexicalScope.getImplicitReceiversWithInstanceToExpression( excludeShadowedByDslMarkers: Boolean = false diff --git a/idea/ide-common/src/org/jetbrains/kotlin/idea/util/psi/patternMatching/KotlinPsiRange.kt b/idea/ide-common/src/org/jetbrains/kotlin/idea/util/psi/patternMatching/KotlinPsiRange.kt index 04c3cb04df5..8dfbbbcd1ff 100644 --- a/idea/ide-common/src/org/jetbrains/kotlin/idea/util/psi/patternMatching/KotlinPsiRange.kt +++ b/idea/ide-common/src/org/jetbrains/kotlin/idea/util/psi/patternMatching/KotlinPsiRange.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.util.psi.patternMatching @@ -34,7 +23,7 @@ interface KotlinPsiRange { override fun getTextRange(): TextRange = TextRange.EMPTY_RANGE } - class ListRange(override val elements: List): KotlinPsiRange { + class ListRange(override val elements: List) : KotlinPsiRange { val startElement: PsiElement = elements.first() val endElement: PsiElement = elements.last() @@ -63,29 +52,28 @@ interface KotlinPsiRange { val matches = ArrayList() scope.accept( - object: KtTreeVisitorVoid() { - override fun visitKtElement(element: KtElement) { - val range = element - .siblings() - .filter(SIGNIFICANT_FILTER) - .take(elements.size) - .toList() - .toRange() + object : KtTreeVisitorVoid() { + override fun visitKtElement(element: KtElement) { + val range = element + .siblings() + .filter(SIGNIFICANT_FILTER) + .take(elements.size) + .toList() + .toRange() - val result = unifier.unify(range, this@KotlinPsiRange) + val result = unifier.unify(range, this@KotlinPsiRange) - if (result is UnificationResult.StronglyMatched) { + if (result is UnificationResult.StronglyMatched) { + matches.add(result) + } else { + val matchCountSoFar = matches.size + super.visitKtElement(element) + if (result is UnificationResult.WeaklyMatched && matches.size == matchCountSoFar) { matches.add(result) } - else { - val matchCountSoFar = matches.size - super.visitKtElement(element) - if (result is UnificationResult.WeaklyMatched && matches.size == matchCountSoFar) { - matches.add(result) - } - } } } + } ) return matches } diff --git a/idea/ide-common/src/org/jetbrains/kotlin/idea/util/psi/patternMatching/KotlinPsiUnifier.kt b/idea/ide-common/src/org/jetbrains/kotlin/idea/util/psi/patternMatching/KotlinPsiUnifier.kt index 21ce4a65473..a39908b1e94 100644 --- a/idea/ide-common/src/org/jetbrains/kotlin/idea/util/psi/patternMatching/KotlinPsiUnifier.kt +++ b/idea/ide-common/src/org/jetbrains/kotlin/idea/util/psi/patternMatching/KotlinPsiUnifier.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.util.psi.patternMatching @@ -71,43 +60,43 @@ interface UnificationResult { override val status: Status get() = UNMATCHED } - interface Matched: UnificationResult { + interface Matched : UnificationResult { val range: KotlinPsiRange val substitution: Map override val status: Status get() = MATCHED } class StronglyMatched( - override val range: KotlinPsiRange, - override val substitution: Map - ): Matched + override val range: KotlinPsiRange, + override val substitution: Map + ) : Matched class WeaklyMatched( - override val range: KotlinPsiRange, - override val substitution: Map, - val weakMatches: Map - ): Matched + override val range: KotlinPsiRange, + override val substitution: Map, + val weakMatches: Map + ) : Matched val status: Status val matched: Boolean get() = status != UNMATCHED } class UnifierParameter( - val descriptor: DeclarationDescriptor, - val expectedType: KotlinType? + val descriptor: DeclarationDescriptor, + val expectedType: KotlinType? ) class KotlinPsiUnifier( - parameters: Collection = Collections.emptySet(), - val allowWeakMatches: Boolean = false + parameters: Collection = Collections.emptySet(), + val allowWeakMatches: Boolean = false ) { companion object { val DEFAULT = KotlinPsiUnifier() } private inner class Context( - val originalTarget: KotlinPsiRange, - val originalPattern: KotlinPsiRange + val originalTarget: KotlinPsiRange, + val originalPattern: KotlinPsiRange ) { val patternContext: BindingContext = originalPattern.getBindingContext() val targetContext: BindingContext = originalTarget.getBindingContext() @@ -155,7 +144,7 @@ class KotlinPsiUnifier( private fun matchCalls(call1: Call, call2: Call): Boolean { return matchReceivers(call1.explicitReceiver, call2.explicitReceiver) && - matchReceivers(call1.dispatchReceiver, call2.dispatchReceiver) + matchReceivers(call1.dispatchReceiver, call2.dispatchReceiver) } private fun matchArguments(arg1: ValueArgument, arg2: ValueArgument): Status { @@ -210,25 +199,23 @@ class KotlinPsiUnifier( fun checkImplicitReceiver(implicitCall: ResolvedCall<*>, explicitCall: ResolvedCall<*>): Boolean { val (implicitReceiver, explicitReceiver) = - when (explicitCall.explicitReceiverKind) { - ExplicitReceiverKind.EXTENSION_RECEIVER -> - (implicitCall.extensionReceiver as? ImplicitReceiver) to - (explicitCall.extensionReceiver as? ExpressionReceiver) + when (explicitCall.explicitReceiverKind) { + ExplicitReceiverKind.EXTENSION_RECEIVER -> + (implicitCall.extensionReceiver as? ImplicitReceiver) to (explicitCall.extensionReceiver as? ExpressionReceiver) - ExplicitReceiverKind.DISPATCH_RECEIVER -> - (implicitCall.dispatchReceiver as? ImplicitReceiver) to - (explicitCall.dispatchReceiver as? ExpressionReceiver) + ExplicitReceiverKind.DISPATCH_RECEIVER -> + (implicitCall.dispatchReceiver as? ImplicitReceiver) to (explicitCall.dispatchReceiver as? ExpressionReceiver) - else -> - null to null - } + else -> + null to null + } val thisExpression = explicitReceiver?.expression as? KtThisExpression if (implicitReceiver == null || thisExpression == null) return false return matchDescriptors( - implicitReceiver.declarationDescriptor, - thisExpression.getAdjustedResolvedCall()?.candidateDescriptor?.containingDeclaration + implicitReceiver.declarationDescriptor, + thisExpression.getAdjustedResolvedCall()?.candidateDescriptor?.containingDeclaration ) } @@ -236,7 +223,10 @@ class KotlinPsiUnifier( return when { rc1.explicitReceiverKind == rc2.explicitReceiverKind -> { matchReceivers(rc1.extensionReceiver, rc2.extensionReceiver) && - (rc1.explicitReceiverKind == ExplicitReceiverKind.BOTH_RECEIVERS || matchReceivers(rc1.dispatchReceiver, rc2.dispatchReceiver)) + (rc1.explicitReceiverKind == ExplicitReceiverKind.BOTH_RECEIVERS || matchReceivers( + rc1.dispatchReceiver, + rc2.dispatchReceiver + )) } rc1.explicitReceiverKind == ExplicitReceiverKind.NO_EXPLICIT_RECEIVER -> checkImplicitReceiver(rc1, rc2) @@ -279,8 +269,7 @@ class KotlinPsiUnifier( private fun KtElement.getAdjustedResolvedCall(): ResolvedCall<*>? { val rc = if (this is KtArrayAccessExpression) { bindingContext[BindingContext.INDEXED_LVALUE_GET, this] - } - else { + } else { getResolvedCall(bindingContext)?.let { when { it !is VariableAsFunctionResolvedCall -> it @@ -330,15 +319,20 @@ class KotlinPsiUnifier( } private fun matchTypes( - type1: KotlinType?, - type2: KotlinType?, - typeRef1: KtTypeReference? = null, - typeRef2: KtTypeReference? = null + type1: KotlinType?, + type2: KotlinType?, + typeRef1: KtTypeReference? = null, + typeRef2: KtTypeReference? = null ): Status? { if (type1 != null && type2 != null) { val unwrappedType1 = type1.unwrap() val unwrappedType2 = type2.unwrap() - if (unwrappedType1 !== type1 || unwrappedType2 !== type2) return matchTypes(unwrappedType1, unwrappedType2, typeRef1, typeRef2) + if (unwrappedType1 !== type1 || unwrappedType2 !== type2) return matchTypes( + unwrappedType1, + unwrappedType2, + typeRef1, + typeRef2 + ) if (type1.isError || type2.isError) return null if (type1 is AbbreviatedType != type2 is AbbreviatedType) return UNMATCHED @@ -348,16 +342,18 @@ class KotlinPsiUnifier( if (type1.isMarkedNullable != type2.isMarkedNullable) return UNMATCHED if (!matchDescriptors( type1.constructor.declarationDescriptor, - type2.constructor.declarationDescriptor)) return UNMATCHED + type2.constructor.declarationDescriptor + ) + ) return UNMATCHED val args1 = type1.arguments val args2 = type2.arguments if (args1.size != args2.size) return UNMATCHED if (!args1.withIndex().all { p -> - val (i, arg1) = p - val arg2 = args2[i] - matchTypeArguments(i, arg1, arg2, typeRef1, typeRef2) - }) return UNMATCHED + val (i, arg1) = p + val arg2 = args2[i] + matchTypeArguments(i, arg1, arg2, typeRef1, typeRef2) + }) return UNMATCHED return MATCHED } @@ -366,11 +362,11 @@ class KotlinPsiUnifier( } private fun matchTypeArguments( - argIndex: Int, - arg1: TypeProjection, - arg2: TypeProjection, - typeRef1: KtTypeReference?, - typeRef2: KtTypeReference? + argIndex: Int, + arg1: TypeProjection, + arg2: TypeProjection, + typeRef1: KtTypeReference?, + typeRef2: KtTypeReference? ): Boolean { val typeArgRef1 = typeRef1?.typeElement?.typeArgumentsAsTypes?.getOrNull(argIndex) val typeArgRef2 = typeRef2?.typeElement?.typeArgumentsAsTypes?.getOrNull(argIndex) @@ -382,11 +378,10 @@ class KotlinPsiUnifier( val status = if (!checkEquivalence && typeRef1 != null && typeRef2 != null) { val typePsi1 = argType1.constructor.declarationDescriptor?.source?.getPsi() val typePsi2 = argType2.constructor.declarationDescriptor?.source?.getPsi() - descriptorToParameter[typePsi1]?.let { substitute(it, typeArgRef2) } ?: - descriptorToParameter[typePsi2]?.let { substitute(it, typeArgRef1) } ?: - matchTypes(argType1, argType2, typeArgRef1, typeArgRef2) - } - else matchTypes(argType1, argType2, typeArgRef1, typeArgRef2) + descriptorToParameter[typePsi1]?.let { substitute(it, typeArgRef2) } + ?: descriptorToParameter[typePsi2]?.let { substitute(it, typeArgRef1) } + ?: matchTypes(argType1, argType2, typeArgRef1, typeArgRef2) + } else matchTypes(argType1, argType2, typeArgRef1, typeArgRef2) return status == MATCHED } @@ -413,12 +408,11 @@ class KotlinPsiUnifier( else -> false } - private fun KtBinaryExpression.matchComplexAssignmentWithSimple(simple: KtBinaryExpression): Status? { - return when { - doUnify(left, simple.left) == UNMATCHED -> UNMATCHED + private fun KtBinaryExpression.matchComplexAssignmentWithSimple(simple: KtBinaryExpression): Status? = + when (doUnify(left, simple.left)) { + UNMATCHED -> UNMATCHED else -> simple.right?.let { matchCalls(this, it) } ?: UNMATCHED } - } private fun KtBinaryExpression.matchAssignment(e: KtElement): Status? { val operationType = operationReference.getReferencedNameElementType() as KtToken @@ -435,11 +429,13 @@ class KotlinPsiUnifier( val setResolvedCall = bindingContext[BindingContext.INDEXED_LVALUE_SET, lhs] val resolvedCallToMatch = e.getAdjustedResolvedCall() - return if (setResolvedCall == null || resolvedCallToMatch == null) null else matchResolvedCalls(setResolvedCall, resolvedCallToMatch) + return if (setResolvedCall == null || resolvedCallToMatch == null) null else matchResolvedCalls( + setResolvedCall, + resolvedCallToMatch + ) } - val assignResolvedCall = getAdjustedResolvedCall() - if (assignResolvedCall == null) return UNMATCHED + val assignResolvedCall = getAdjustedResolvedCall() ?: return UNMATCHED val operationName = OperatorConventions.getNameForOperationSymbol(operationType) if (assignResolvedCall.resultingDescriptor?.name == operationName) return matchCalls(this, e) @@ -456,13 +452,11 @@ class KotlinPsiUnifier( private fun PsiElement.isIncrement(): Boolean { val parent = parent - return parent is KtUnaryExpression - && this == parent.operationReference - && ((parent.operationToken as KtToken) in OperatorConventions.INCREMENT_OPERATIONS) + return parent is KtUnaryExpression && this == parent.operationReference && ((parent.operationToken as KtToken) in OperatorConventions.INCREMENT_OPERATIONS) } private fun KtCallableReferenceExpression.hasExpressionReceiver(): Boolean = - bindingContext[BindingContext.DOUBLE_COLON_LHS, receiverExpression] is DoubleColonLHS.Expression + bindingContext[BindingContext.DOUBLE_COLON_LHS, receiverExpression] is DoubleColonLHS.Expression private fun matchCallableReferences(e1: KtCallableReferenceExpression, e2: KtCallableReferenceExpression): Status? { if (e1.hasExpressionReceiver() || e2.hasExpressionReceiver()) return null @@ -510,10 +504,11 @@ class KotlinPsiUnifier( } private fun matchCallables( - decl1: KtDeclaration, - decl2: KtDeclaration, - desc1: CallableDescriptor, - desc2: CallableDescriptor): Status? { + decl1: KtDeclaration, + decl2: KtDeclaration, + desc1: CallableDescriptor, + desc2: CallableDescriptor + ): Status? { fun needToCompareReturnTypes(): Boolean { if (decl1 !is KtCallableDeclaration) return true return decl1.typeReference != null || (decl2 as KtCallableDeclaration).typeReference != null @@ -527,8 +522,11 @@ class KotlinPsiUnifier( val type1 = desc1.returnType val type2 = desc2.returnType - if (type1 != type2 - && (type1 == null || type2 == null || type1.isError || type2.isError || matchTypes(type1, type2) != MATCHED)) { + if (type1 != type2 && (type1 == null || type2 == null || type1.isError || type2.isError || matchTypes( + type1, + type2 + ) != MATCHED) + ) { return UNMATCHED } } @@ -540,14 +538,14 @@ class KotlinPsiUnifier( val params2 = desc2.valueParameters val zippedParams = params1.zip(params2) val parametersMatch = - (params1.size == params2.size) && zippedParams.all { matchTypes(it.first.type, it.second.type) == MATCHED } + (params1.size == params2.size) && zippedParams.all { matchTypes(it.first.type, it.second.type) == MATCHED } if (!parametersMatch) return UNMATCHED zippedParams.forEach { declarationPatternsToTargets.putValue(it.first, it.second) } return doUnify( - (decl1 as? KtTypeParameterListOwner)?.typeParameters?.toRange() ?: Empty, - (decl2 as? KtTypeParameterListOwner)?.typeParameters?.toRange() ?: Empty + (decl1 as? KtTypeParameterListOwner)?.typeParameters?.toRange() ?: Empty, + (decl2 as? KtTypeParameterListOwner)?.typeParameters?.toRange() ?: Empty ) and when (decl1) { is KtDeclarationWithBody -> doUnify(decl1.bodyExpression, (decl2 as KtDeclarationWithBody).bodyExpression) @@ -570,14 +568,19 @@ class KotlinPsiUnifier( return parent is KtClassBody || parent is KtFile } - private fun matchNames(decl1: KtDeclaration, decl2: KtDeclaration, desc1: DeclarationDescriptor, desc2: DeclarationDescriptor): Boolean { + private fun matchNames( + decl1: KtDeclaration, + decl2: KtDeclaration, + desc1: DeclarationDescriptor, + desc2: DeclarationDescriptor + ): Boolean { return (!decl1.isNameRelevant() && !decl2.isNameRelevant()) || desc1.name == desc2.name } - private fun matchContainedDescriptors( - declarations1: List, - declarations2: List, - matchPair: (Pair) -> Boolean + private fun matchContainedDescriptors( + declarations1: List, + declarations2: List, + matchPair: (Pair) -> Boolean ): Boolean { val zippedParams = declarations1.zip(declarations2) if (declarations1.size != declarations2.size || !zippedParams.all { matchPair(it) }) return false @@ -587,13 +590,14 @@ class KotlinPsiUnifier( } private fun matchClasses( - decl1: KtClassOrObject, - decl2: KtClassOrObject, - desc1: ClassDescriptor, - desc2: ClassDescriptor): Status? { + decl1: KtClassOrObject, + decl2: KtClassOrObject, + desc1: ClassDescriptor, + desc2: ClassDescriptor + ): Status? { class OrderInfo( - val orderSensitive: List, - val orderInsensitive: List + val orderSensitive: List, + val orderInsensitive: List ) fun getMemberOrderInfo(cls: KtClassOrObject): OrderInfo { @@ -610,9 +614,8 @@ class KotlinPsiUnifier( } fun resolveAndSortDeclarationsByDescriptor(declarations: List): List> { - return declarations - .map { it to it.bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, it] } - .sortedBy { it.second?.let { IdeDescriptorRenderers.SOURCE_CODE.render(it) } ?: "" } + return declarations.map { it to it.bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, it] } + .sortedBy { it.second?.let { descriptor -> IdeDescriptorRenderers.SOURCE_CODE.render(descriptor) } ?: "" } } fun sortDeclarationsByElementType(declarations: List): List { @@ -642,7 +645,10 @@ class KotlinPsiUnifier( return UNMATCHED } - val status = doUnify((decl1 as? KtClass)?.getPrimaryConstructorParameterList(), (decl2 as? KtClass)?.getPrimaryConstructorParameterList()) and + val status = doUnify( + (decl1 as? KtClass)?.getPrimaryConstructorParameterList(), + (decl2 as? KtClass)?.getPrimaryConstructorParameterList() + ) and doUnify((decl1 as? KtClass)?.typeParameterList, (decl2 as? KtClass)?.typeParameterList) and doUnify(delegationInfo1.orderSensitive.toRange(), delegationInfo2.orderSensitive.toRange()) if (status == UNMATCHED) return UNMATCHED @@ -654,19 +660,20 @@ class KotlinPsiUnifier( val sortedMembers2 = resolveAndSortDeclarationsByDescriptor(membersInfo2.orderInsensitive) if ((sortedMembers1.size != sortedMembers2.size)) return UNMATCHED if (sortedMembers1.zip(sortedMembers2).any { - val (d1, d2) = it - (matchDeclarations(d1.first, d2.first, d1.second, d2.second) ?: doUnify(d1.first, d2.first)) == UNMATCHED - }) return UNMATCHED + val (d1, d2) = it + (matchDeclarations(d1.first, d2.first, d1.second, d2.second) ?: doUnify(d1.first, d2.first)) == UNMATCHED + } + ) return UNMATCHED return doUnify( - sortDeclarationsByElementType(membersInfo1.orderSensitive).toRange(), - sortDeclarationsByElementType(membersInfo2.orderSensitive).toRange() + sortDeclarationsByElementType(membersInfo1.orderSensitive).toRange(), + sortDeclarationsByElementType(membersInfo2.orderSensitive).toRange() ) } private fun matchTypeParameters( - desc1: TypeParameterDescriptor, - desc2: TypeParameterDescriptor + desc1: TypeParameterDescriptor, + desc2: TypeParameterDescriptor ): Status { if (desc1.variance != desc2.variance) return UNMATCHED if (!matchTypes(desc1.upperBounds, desc2.upperBounds)) return UNMATCHED @@ -682,18 +689,22 @@ class KotlinPsiUnifier( } private fun matchDeclarations( - decl1: KtDeclaration, - decl2: KtDeclaration, - desc1: DeclarationDescriptor?, - desc2: DeclarationDescriptor?): Status? { + decl1: KtDeclaration, + decl2: KtDeclaration, + desc1: DeclarationDescriptor?, + desc2: DeclarationDescriptor? + ): Status? { if (decl1::class.java != decl2::class.java) return UNMATCHED if (desc1 == null || desc2 == null) { - if (decl1 is KtParameter + return if (decl1 is KtParameter && decl2 is KtParameter && decl1.getStrictParentOfType() != null - && decl2.getStrictParentOfType() != null) return null - return UNMATCHED + && decl2.getStrictParentOfType() != null + ) + null + else + UNMATCHED } if (ErrorUtils.isError(desc1) || ErrorUtils.isError(desc2)) return UNMATCHED if (desc1::class.java != desc2::class.java) return UNMATCHED @@ -801,8 +812,7 @@ class KotlinPsiUnifier( val patternText = pattern.startEntry.text.substring(prefixLength) if (!targetEntryText.endsWith(patternText)) continue targetEntryText.substring(0, targetEntryText.length - patternText.length) - } - else "" + } else "" val lastTargetEntry = targetEntries[index + patternEntries.lastIndex] @@ -813,8 +823,7 @@ class KotlinPsiUnifier( val lastTargetEntryText = lastTargetEntry.text if (!lastTargetEntryText.startsWith(patternText)) continue lastTargetEntryText.substring(patternText.length) - } - else "" + } else "" val fromIndex = if (matchStartByText) 1 else 0 val toIndex = if (matchEndByText) patternEntries.lastIndex - 1 else patternEntries.lastIndex @@ -846,8 +855,7 @@ class KotlinPsiUnifier( } } - private fun ASTNode.getChildrenRange(): KotlinPsiRange = - getChildren(null).mapNotNull { it.psi }.toRange() + private fun ASTNode.getChildrenRange(): KotlinPsiRange = getChildren(null).mapNotNull { it.psi }.toRange() private fun PsiElement.unwrapWeakly(): KtElement? { return when { @@ -860,8 +868,8 @@ class KotlinPsiUnifier( } private fun doUnifyWeakly( - targetElement: KtElement, - patternElement: KtElement + targetElement: KtElement, + patternElement: KtElement ): Status { if (!allowWeakMatches) return UNMATCHED @@ -878,10 +886,9 @@ class KotlinPsiUnifier( return status } - private fun substitute(parameter: UnifierParameter, targetElement: PsiElement?): Status { - val existingArgument = substitution[parameter] - return when { - existingArgument == null -> { + private fun substitute(parameter: UnifierParameter, targetElement: PsiElement?): Status = + when (val existingArgument = substitution[parameter]) { + null -> { substitution[parameter] = targetElement as KtElement MATCHED } @@ -893,11 +900,10 @@ class KotlinPsiUnifier( status } } - } fun doUnify( - targetElement: PsiElement?, - patternElement: PsiElement? + targetElement: PsiElement?, + patternElement: PsiElement? ): Status { val targetElementUnwrapped = targetElement?.unwrap() val patternElementUnwrapped = patternElement?.unwrap() @@ -922,8 +928,7 @@ class KotlinPsiUnifier( if (referencedPatternDeclaration != null && parameter != null) { if (targetElementUnwrapped is KtExpression) { if (!targetElementUnwrapped.checkType(parameter)) return UNMATCHED - } - else if (targetElementUnwrapped !is KtUserType) return UNMATCHED + } else if (targetElementUnwrapped !is KtUserType) return UNMATCHED return substitute(parameter, targetElementUnwrapped) } @@ -958,12 +963,10 @@ class KotlinPsiUnifier( private val descriptorToParameter = parameters.associateBy { (it.descriptor as? DeclarationDescriptorWithSource)?.source?.getPsi() } - private fun PsiElement.unwrap(): PsiElement? { - return when (this) { - is KtExpression -> KtPsiUtil.deparenthesize(this) - is KtStringTemplateEntryWithExpression -> KtPsiUtil.deparenthesize(expression) - else -> this - } + private fun PsiElement.unwrap(): PsiElement? = when (this) { + is KtExpression -> KtPsiUtil.deparenthesize(this) + is KtStringTemplateEntryWithExpression -> KtPsiUtil.deparenthesize(expression) + else -> this } private fun PsiElement.unquotedText(): String { @@ -975,8 +978,7 @@ class KotlinPsiUnifier( return with(Context(target, pattern)) { val status = doUnify(target, pattern) when { - substitution.size != descriptorToParameter.size -> - Unmatched + substitution.size != descriptorToParameter.size -> Unmatched status == MATCHED -> { val targetRange = targetSubstringInfo?.createExpression()?.toRange() ?: target if (weakMatches.isEmpty()) { @@ -985,14 +987,13 @@ class KotlinPsiUnifier( WeaklyMatched(targetRange, substitution, weakMatches) } } - else -> - Unmatched + else -> Unmatched } } } fun unify(targetElement: PsiElement?, patternElement: PsiElement?): UnificationResult = - unify(targetElement.toRange(), patternElement.toRange()) + unify(targetElement.toRange(), patternElement.toRange()) } fun PsiElement?.matches(e: PsiElement?): Boolean = KotlinPsiUnifier.DEFAULT.unify(this, e).matched diff --git a/idea/ide-common/src/org/jetbrains/kotlin/idea/util/scopeUtils.kt b/idea/ide-common/src/org/jetbrains/kotlin/idea/util/scopeUtils.kt index a30fe937077..693bc6e5679 100644 --- a/idea/ide-common/src/org/jetbrains/kotlin/idea/util/scopeUtils.kt +++ b/idea/ide-common/src/org/jetbrains/kotlin/idea/util/scopeUtils.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @file:JvmName("ScopeUtils") @@ -44,13 +33,15 @@ fun LexicalScope.getAllAccessibleVariables(name: Name): Collection { - return getImplicitReceiversWithInstance().flatMap { it.type.memberScope.getContributedFunctions(name, NoLookupLocation.FROM_IDE) } + - collectFunctions(name, NoLookupLocation.FROM_IDE) + return getImplicitReceiversWithInstance().flatMap { + it.type.memberScope.getContributedFunctions(name, NoLookupLocation.FROM_IDE) + } + collectFunctions(name, NoLookupLocation.FROM_IDE) } -fun LexicalScope.getVariablesFromImplicitReceivers(name: Name): Collection = getImplicitReceiversWithInstance().flatMap { - it.type.memberScope.getContributedVariables(name, NoLookupLocation.FROM_IDE) -} +fun LexicalScope.getVariablesFromImplicitReceivers(name: Name): Collection = + getImplicitReceiversWithInstance().flatMap { + it.type.memberScope.getContributedVariables(name, NoLookupLocation.FROM_IDE) + } fun LexicalScope.getVariableFromImplicitReceivers(name: Name): VariableDescriptor? { getImplicitReceiversWithInstance().forEach { @@ -80,12 +71,12 @@ fun PsiElement.getResolutionScope(bindingContext: BindingContext): LexicalScope? return null } -fun PsiElement.getResolutionScope(bindingContext: BindingContext, resolutionFacade: ResolutionFacade/*TODO: get rid of this parameter*/): LexicalScope { - return getResolutionScope(bindingContext) ?: - when (containingFile) { - is KtFile -> resolutionFacade.getFileResolutionScope(containingFile as KtFile) - else -> error("Not in KtFile") - } +fun PsiElement.getResolutionScope( + bindingContext: BindingContext, + resolutionFacade: ResolutionFacade/*TODO: get rid of this parameter*/ +): LexicalScope = getResolutionScope(bindingContext) ?: when (containingFile) { + is KtFile -> resolutionFacade.getFileResolutionScope(containingFile as KtFile) + else -> error("Not in KtFile") } fun KtElement.getResolutionScope(): LexicalScope { diff --git a/idea/ide-common/src/org/jetbrains/kotlin/resolve/lazy/BodyResolveMode.kt b/idea/ide-common/src/org/jetbrains/kotlin/resolve/lazy/BodyResolveMode.kt index cd0ce553238..a8486aa84c8 100644 --- a/idea/ide-common/src/org/jetbrains/kotlin/resolve/lazy/BodyResolveMode.kt +++ b/idea/ide-common/src/org/jetbrains/kotlin/resolve/lazy/BodyResolveMode.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.resolve.lazy @@ -21,12 +10,16 @@ import org.jetbrains.kotlin.resolve.BindingTraceFilter enum class BodyResolveMode(val bindingTraceFilter: BindingTraceFilter, val doControlFlowAnalysis: Boolean) { // All body statements are analyzed, diagnostics included FULL(BindingTraceFilter.ACCEPT_ALL, doControlFlowAnalysis = true), + // Analyzes only dependent statements, including all declaration statements (difference from PARTIAL_WITH_CFA) PARTIAL_FOR_COMPLETION(BindingTraceFilter.NO_DIAGNOSTICS, doControlFlowAnalysis = true), + // Analyzes only dependent statements, diagnostics included PARTIAL_WITH_DIAGNOSTICS(BindingTraceFilter.ACCEPT_ALL, doControlFlowAnalysis = true), + // Analyzes only dependent statements, performs control flow analysis (mostly needed for isUsedAsExpression / AsStatement) PARTIAL_WITH_CFA(BindingTraceFilter.NO_DIAGNOSTICS, doControlFlowAnalysis = true), + // Analyzes only dependent statements, including only used declaration statements, does not perform control flow analysis PARTIAL(BindingTraceFilter.NO_DIAGNOSTICS, doControlFlowAnalysis = false) diff --git a/idea/ide-common/src/org/jetbrains/kotlin/resolve/lazy/PartialBodyResolveFilter.kt b/idea/ide-common/src/org/jetbrains/kotlin/resolve/lazy/PartialBodyResolveFilter.kt index ea6cf202d19..c821f721263 100644 --- a/idea/ide-common/src/org/jetbrains/kotlin/resolve/lazy/PartialBodyResolveFilter.kt +++ b/idea/ide-common/src/org/jetbrains/kotlin/resolve/lazy/PartialBodyResolveFilter.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.resolve.lazy @@ -31,9 +20,9 @@ import java.util.* //TODO: do resolve anonymous object's body class PartialBodyResolveFilter( - elementsToResolve: Collection, - private val declaration: KtDeclaration, - forCompletion: Boolean + elementsToResolve: Collection, + private val declaration: KtDeclaration, + forCompletion: Boolean ) : StatementFilter() { private val statementMarks = StatementMarks() @@ -59,8 +48,7 @@ class PartialBodyResolveFilter( if (name != null) { if (declaration is KtNamedFunction) { contextNothingFunctionNames.add(name) - } - else { + } else { contextNothingVariableNames.add(name) } } @@ -91,12 +79,11 @@ class PartialBodyResolveFilter( if (name != null && nameFilter(name)) { statementMarks.mark(statement, MarkLevel.NEED_REFERENCE_RESOLVE) } - } - else if (statement is KtDestructuringDeclaration) { + } else if (statement is KtDestructuringDeclaration) { if (statement.entries.any { - val name = it.name - name != null && nameFilter(name) - }) { + val name = it.name + name != null && nameFilter(name) + }) { statementMarks.mark(statement, MarkLevel.NEED_REFERENCE_RESOLVE) } } @@ -116,8 +103,8 @@ class PartialBodyResolveFilter( if (!smartCastPlaces.isEmpty()) { //TODO: do we really need correct resolve for ALL smart cast places? smartCastPlaces.values - .flatten() - .forEach { statementMarks.mark(it, MarkLevel.NEED_REFERENCE_RESOLVE) } + .flatten() + .forEach { statementMarks.mark(it, MarkLevel.NEED_REFERENCE_RESOLVE) } updateNameFilter() } } @@ -140,8 +127,8 @@ class PartialBodyResolveFilter( * Returns map from smart-cast expression names (variable name or qualified variable name) to places. */ private fun potentialSmartCastPlaces( - statement: KtExpression, - filter: (SmartCastName) -> Boolean = { true } + statement: KtExpression, + filter: (SmartCastName) -> Boolean = { true } ): Map> { val map = HashMap>(0) @@ -235,9 +222,9 @@ class PartialBodyResolveFilter( if (thenBranch != null && elseBranch != null) { val thenCasts = potentialSmartCastPlaces(thenBranch, filter) - if (!thenCasts.isEmpty()) { + if (thenCasts.isNotEmpty()) { val elseCasts = potentialSmartCastPlaces(elseBranch) { filter(it) && thenCasts.containsKey(it) } - if (!elseCasts.isEmpty()) { + if (elseCasts.isNotEmpty()) { for ((name, places) in thenCasts) { if (elseCasts.containsKey(name)) { // need filtering by cast names in else-branch addPlaces(name, places) @@ -262,8 +249,7 @@ class PartialBodyResolveFilter( // we need to enter the body only for "while(true)" if (condition.isTrueConstant()) { expression.acceptChildren(this) - } - else { + } else { condition?.accept(this) } } @@ -406,8 +392,7 @@ class PartialBodyResolveFilter( insideLoopLevel++ loop.body?.accept(this) insideLoopLevel-- - } - else { + } else { // do not make sense to search exits inside while-loop as not necessary enter it at all condition.accept(this) } @@ -451,8 +436,7 @@ class PartialBodyResolveFilter( if (expression.operationToken == KtTokens.ELVIS) { // do not search exits after "?:" expression.left?.accept(this) - } - else { + } else { super.visitBinaryExpression(expression) } } @@ -473,8 +457,8 @@ class PartialBodyResolveFilter( } private data class SmartCastName( - private val receiverName: SmartCastName?, - private val selectorName: String? /* null means "this" (and receiverName should be null */ + private val receiverName: SmartCastName?, + private val selectorName: String? /* null means "this" (and receiverName should be null */ ) { init { if (selectorName == null) { @@ -482,7 +466,7 @@ class PartialBodyResolveFilter( } } - override fun toString(): String = if (receiverName != null) receiverName.toString() + "." + selectorName else selectorName ?: "this" + override fun toString(): String = if (receiverName != null) "$receiverName.$selectorName" else selectorName ?: "this" fun affectsNames(nameFilter: (String) -> Boolean): Boolean { if (selectorName == null) return true @@ -533,8 +517,7 @@ class PartialBodyResolveFilter( if (names == null) return if (filter.names == null) { names = null - } - else { + } else { names!!.addAll(filter.names!!) } } @@ -562,42 +545,38 @@ class PartialBodyResolveFilter( private fun KtExpression?.isNullLiteral() = this?.node?.elementType == KtNodeTypes.NULL - private fun KtExpression?.isTrueConstant() - = this != null && node?.elementType == KtNodeTypes.BOOLEAN_CONSTANT && text == "true" + private fun KtExpression?.isTrueConstant() = this != null && node?.elementType == KtNodeTypes.BOOLEAN_CONSTANT && text == "true" private fun T?.singletonOrEmptySet(): Set = if (this != null) setOf(this) else setOf() //TODO: review logic - private fun isValueNeeded(expression: KtExpression): Boolean { - val parent = expression.parent - return when (parent) { - is KtBlockExpression -> expression == parent.lastStatement() && isValueNeeded(parent) + private fun isValueNeeded(expression: KtExpression): Boolean = when (val parent = expression.parent) { + is KtBlockExpression -> expression == parent.lastStatement() && isValueNeeded(parent) - is KtContainerNode -> { //TODO - not quite correct - val pparent = parent.parent as? KtExpression - pparent != null && isValueNeeded(pparent) - } - - is KtDeclarationWithBody -> { - if (expression == parent.bodyExpression) - !parent.hasBlockBody() && !parent.hasDeclaredReturnType() - else - true - } - - is KtAnonymousInitializer -> false - - else -> true + is KtContainerNode -> { //TODO - not quite correct + val pparent = parent.parent as? KtExpression + pparent != null && isValueNeeded(pparent) } + + is KtDeclarationWithBody -> { + if (expression == parent.bodyExpression) + !parent.hasBlockBody() && !parent.hasDeclaredReturnType() + else + true + } + + is KtAnonymousInitializer -> false + + else -> true } - private fun KtBlockExpression.lastStatement(): KtExpression? - = lastChild?.siblings(forward = false)?.firstIsInstanceOrNull() + private fun KtBlockExpression.lastStatement(): KtExpression? = + lastChild?.siblings(forward = false)?.firstIsInstanceOrNull() private fun PsiElement.isStatement() = this is KtExpression && parent is KtBlockExpression - private fun KtTypeReference?.containsProbablyNothing() - = this?.typeElement?.anyDescendantOfType { it.isProbablyNothing() } ?: false + private fun KtTypeReference?.containsProbablyNothing() = + this?.typeElement?.anyDescendantOfType { it.isProbablyNothing() } ?: false } private inner class StatementMarks { @@ -627,18 +606,16 @@ class PartialBodyResolveFilter( } } - fun statementMark(statement: KtExpression): MarkLevel - = statementMarks[statement] ?: MarkLevel.NONE + fun statementMark(statement: KtExpression): MarkLevel = statementMarks[statement] ?: MarkLevel.NONE - fun allMarkedStatements(): Collection - = statementMarks.keys + fun allMarkedStatements(): Collection = statementMarks.keys fun lastMarkedStatement(block: KtBlockExpression, minLevel: MarkLevel): KtExpression? { val level = blockLevels[block] ?: MarkLevel.NONE if (level < minLevel) return null // optimization return block.lastChild.siblings(forward = false) - .filterIsInstance() - .first { statementMark(it) >= minLevel } + .filterIsInstance() + .first { statementMark(it) >= minLevel } } } } diff --git a/idea/ide-common/src/org/jetbrains/kotlin/resolve/scopes/ExplicitImportsScope.kt b/idea/ide-common/src/org/jetbrains/kotlin/resolve/scopes/ExplicitImportsScope.kt index b9fb969d86d..34347c16210 100644 --- a/idea/ide-common/src/org/jetbrains/kotlin/resolve/scopes/ExplicitImportsScope.kt +++ b/idea/ide-common/src/org/jetbrains/kotlin/resolve/scopes/ExplicitImportsScope.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.resolve.scopes @@ -23,20 +12,22 @@ import org.jetbrains.kotlin.utils.Printer import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull class ExplicitImportsScope(private val descriptors: Collection) : BaseImportingScope(null) { - override fun getContributedClassifier(name: Name, location: LookupLocation) - = descriptors.filter { it.name == name }.firstIsInstanceOrNull() + override fun getContributedClassifier(name: Name, location: LookupLocation) = + descriptors.filter { it.name == name }.firstIsInstanceOrNull() - override fun getContributedPackage(name: Name) - = descriptors.filter { it.name == name }.firstIsInstanceOrNull() + override fun getContributedPackage(name: Name) = descriptors.filter { it.name == name }.firstIsInstanceOrNull() - override fun getContributedVariables(name: Name, location: LookupLocation) - = descriptors.filter { it.name == name }.filterIsInstance() + override fun getContributedVariables(name: Name, location: LookupLocation) = + descriptors.filter { it.name == name }.filterIsInstance() - override fun getContributedFunctions(name: Name, location: LookupLocation) - = descriptors.filter { it.name == name }.filterIsInstance() + override fun getContributedFunctions(name: Name, location: LookupLocation) = + descriptors.filter { it.name == name }.filterIsInstance() - override fun getContributedDescriptors(kindFilter: DescriptorKindFilter, nameFilter: (Name) -> Boolean, changeNamesForAliased: Boolean) - = descriptors + override fun getContributedDescriptors( + kindFilter: DescriptorKindFilter, + nameFilter: (Name) -> Boolean, + changeNamesForAliased: Boolean + ) = descriptors override fun computeImportedNames() = descriptors.mapTo(hashSetOf()) { it.name } diff --git a/idea/ide-common/src/org/jetbrains/kotlin/util/descriptorUtils.kt b/idea/ide-common/src/org/jetbrains/kotlin/util/descriptorUtils.kt index 68534752387..60ff18cf662 100644 --- a/idea/ide-common/src/org/jetbrains/kotlin/util/descriptorUtils.kt +++ b/idea/ide-common/src/org/jetbrains/kotlin/util/descriptorUtils.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.util @@ -31,9 +20,9 @@ import org.jetbrains.kotlin.types.checker.KotlinTypeCheckerImpl import org.jetbrains.kotlin.types.typeUtil.equalTypesOrNulls fun descriptorsEqualWithSubstitution( - descriptor1: DeclarationDescriptor?, - descriptor2: DeclarationDescriptor?, - checkOriginals: Boolean = true + descriptor1: DeclarationDescriptor?, + descriptor2: DeclarationDescriptor?, + checkOriginals: Boolean = true ): Boolean { if (descriptor1 == descriptor2) return true if (descriptor1 == null || descriptor2 == null) return false @@ -41,14 +30,15 @@ fun descriptorsEqualWithSubstitution( if (descriptor1 !is CallableDescriptor) return true descriptor2 as CallableDescriptor - val typeChecker = KotlinTypeCheckerImpl.withAxioms(object: KotlinTypeChecker.TypeConstructorEquality { + val typeChecker = KotlinTypeCheckerImpl.withAxioms(object : KotlinTypeChecker.TypeConstructorEquality { override fun equals(a: TypeConstructor, b: TypeConstructor): Boolean { val typeParam1 = a.declarationDescriptor as? TypeParameterDescriptor val typeParam2 = b.declarationDescriptor as? TypeParameterDescriptor if (typeParam1 != null && typeParam2 != null && typeParam1.containingDeclaration == descriptor1 - && typeParam2.containingDeclaration == descriptor2) { + && typeParam2.containingDeclaration == descriptor2 + ) { return typeParam1.index == typeParam2.index } @@ -68,25 +58,25 @@ fun descriptorsEqualWithSubstitution( } fun ClassDescriptor.findCallableMemberBySignature( - signature: CallableMemberDescriptor, - allowOverridabilityConflicts: Boolean = false + signature: CallableMemberDescriptor, + allowOverridabilityConflicts: Boolean = false ): CallableMemberDescriptor? { val descriptorKind = if (signature is FunctionDescriptor) DescriptorKindFilter.FUNCTIONS else DescriptorKindFilter.VARIABLES return defaultType.memberScope - .getContributedDescriptors(descriptorKind) - .filterIsInstance() - .firstOrNull { - if (it.containingDeclaration != this) return@firstOrNull false - val overridability = OverridingUtil.DEFAULT.isOverridableBy(it as CallableDescriptor, signature, null).result - overridability == OVERRIDABLE || (allowOverridabilityConflicts && overridability == CONFLICT) - } + .getContributedDescriptors(descriptorKind) + .filterIsInstance() + .firstOrNull { + if (it.containingDeclaration != this) return@firstOrNull false + val overridability = OverridingUtil.DEFAULT.isOverridableBy(it as CallableDescriptor, signature, null).result + overridability == OVERRIDABLE || (allowOverridabilityConflicts && overridability == CONFLICT) + } } fun TypeConstructor.supertypesWithAny(): Collection { val supertypes = supertypes - val noSuperClass = supertypes - .map { it.constructor.declarationDescriptor as? ClassDescriptor } - .all { it == null || it.kind == ClassKind.INTERFACE } + val noSuperClass = supertypes.map { it.constructor.declarationDescriptor as? ClassDescriptor }.all { + it == null || it.kind == ClassKind.INTERFACE + } return if (noSuperClass) supertypes + builtIns.anyType else supertypes } diff --git a/idea/ide-common/src/org/jetbrains/kotlin/util/substitutionUtils.kt b/idea/ide-common/src/org/jetbrains/kotlin/util/substitutionUtils.kt index 0a919cc6d0c..7c343b563b1 100644 --- a/idea/ide-common/src/org/jetbrains/kotlin/util/substitutionUtils.kt +++ b/idea/ide-common/src/org/jetbrains/kotlin/util/substitutionUtils.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.types.substitutions @@ -20,7 +9,7 @@ import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.types.* import org.jetbrains.kotlin.types.checker.TypeCheckingProcedure -import java.util.LinkedHashMap +import java.util.* fun getTypeSubstitution(baseType: KotlinType, derivedType: KotlinType): LinkedHashMap? { val substitutedType = TypeCheckingProcedure.findCorrespondingSupertype(derivedType, baseType) ?: return null @@ -34,8 +23,8 @@ fun getTypeSubstitution(baseType: KotlinType, derivedType: KotlinType): LinkedHa } fun getCallableSubstitution( - baseCallable: CallableDescriptor, - derivedCallable: CallableDescriptor + baseCallable: CallableDescriptor, + derivedCallable: CallableDescriptor ): MutableMap? { val baseClass = baseCallable.containingDeclaration as? ClassDescriptor ?: return null val derivedClass = derivedCallable.containingDeclaration as? ClassDescriptor ?: return null @@ -49,8 +38,8 @@ fun getCallableSubstitution( } fun getCallableSubstitutor( - baseCallable: CallableDescriptor, - derivedCallable: CallableDescriptor + baseCallable: CallableDescriptor, + derivedCallable: CallableDescriptor ): TypeSubstitutor? { return getCallableSubstitution(baseCallable, derivedCallable)?.let { TypeSubstitutor.create(it) } } diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/KotlinIconProvider.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/KotlinIconProvider.kt index d6e64babe2d..b7c7b2d939d 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/KotlinIconProvider.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/KotlinIconProvider.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea @@ -107,7 +96,7 @@ class KotlinIconProvider : IconProvider(), DumbAware { return PlatformIcons.PUBLIC_ICON } - fun PsiElement.getBaseIcon(): Icon? = when(this) { + fun PsiElement.getBaseIcon(): Icon? = when (this) { is KtPackageDirective -> PlatformIcons.PACKAGE_ICON is KtLightClassForFacade -> KotlinIcons.FILE is KtLightClassForDecompiledDeclaration -> { @@ -136,8 +125,7 @@ class KotlinIconProvider : IconProvider(), DumbAware { is KtParameter -> { if (KtPsiUtil.getClassIfParameterIsProperty(this) != null) { if (isMutable) KotlinIcons.FIELD_VAR else KotlinIcons.FIELD_VAL - } - else + } else KotlinIcons.PARAMETER } is KtProperty -> if (isVar) KotlinIcons.FIELD_VAR else KotlinIcons.FIELD_VAL diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/KotlinShortNamesCache.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/KotlinShortNamesCache.kt index 56d936210b3..2238c07b313 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/KotlinShortNamesCache.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/KotlinShortNamesCache.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.caches @@ -97,7 +86,8 @@ class KotlinShortNamesCache(private val project: Project) : PsiShortNamesCache() LOG.error( "A declaration obtained from index has non-matching name:" + "\nin index: $name" + - "\ndeclared: ${fqName.shortName()}($fqName)") + "\ndeclared: ${fqName.shortName()}($fqName)" + ) return@Processor true } diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/PerModulePackageCacheService.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/PerModulePackageCacheService.kt index 321501904f9..36d7798a645 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/PerModulePackageCacheService.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/PerModulePackageCacheService.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -47,7 +47,7 @@ import org.jetbrains.kotlin.psi.psiUtil.getParentOfType import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ConcurrentMap -class KotlinPackageContentModificationListener(private val project: Project): Disposable { +class KotlinPackageContentModificationListener(private val project: Project) : Disposable { val connection = project.messageBus.connect() init { @@ -63,8 +63,7 @@ class KotlinPackageContentModificationListener(private val project: Project): Di if (events.size >= FULL_DROP_THRESHOLD) { service.onTooComplexChange() } else { - events - .asSequence() + events.asSequence() .filter(::isRelevant) .filter { (it.isValid || it !is VFileCreateEvent) && it.file != null } .filter { @@ -303,7 +302,9 @@ class PerModulePackageCacheService(private val project: Project) : Disposable { pendingKtFileChanges.processPending { file -> if (file.virtualFile != null && file.virtualFile !in projectScope) { - LOG.debugIfEnabled(project) { "Skip $file without vFile, or not in scope: ${file.virtualFile?.let { it !in projectScope }}" } + LOG.debugIfEnabled(project) { + "Skip $file without vFile, or not in scope: ${file.virtualFile?.let { it !in projectScope }}" + } return@processPending } val nullableModuleInfo = file.getNullableModuleInfo() diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/lightClasses/IDELightClassContexts.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/lightClasses/IDELightClassContexts.kt index a6b9376a894..1dce10cc689 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/lightClasses/IDELightClassContexts.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/lightClasses/IDELightClassContexts.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.caches.lightClasses @@ -111,7 +100,12 @@ internal object IDELightClassContexts { "Class descriptor was not found for ${classOrObject.getElementTextWithContext()}" } ForceResolveUtil.forceResolveAllContents(classDescriptor) - return IDELightClassConstructionContext(bindingContext, resolutionFacade.moduleDescriptor, classOrObject.languageVersionSettings, EXACT) + return IDELightClassConstructionContext( + bindingContext, + resolutionFacade.moduleDescriptor, + classOrObject.languageVersionSettings, + EXACT + ) } fun contextForLocalClassOrObject(classOrObject: KtClassOrObject): LightClassConstructionContext { @@ -122,12 +116,22 @@ internal object IDELightClassContexts { if (descriptor == null) { LOG.warn("No class descriptor in context for class: " + classOrObject.getElementTextWithContext()) - return IDELightClassConstructionContext(bindingContext, resolutionFacade.moduleDescriptor, classOrObject.languageVersionSettings, EXACT) + return IDELightClassConstructionContext( + bindingContext, + resolutionFacade.moduleDescriptor, + classOrObject.languageVersionSettings, + EXACT + ) } ForceResolveUtil.forceResolveAllContents(descriptor) - return IDELightClassConstructionContext(bindingContext, resolutionFacade.moduleDescriptor, classOrObject.languageVersionSettings, EXACT) + return IDELightClassConstructionContext( + bindingContext, + resolutionFacade.moduleDescriptor, + classOrObject.languageVersionSettings, + EXACT + ) } @@ -135,7 +139,12 @@ internal object IDELightClassContexts { val resolveSession = files.first().getResolutionFacade().getFrontendService(ResolveSession::class.java) forceResolvePackageDeclarations(files, resolveSession) - return IDELightClassConstructionContext(resolveSession.bindingContext, resolveSession.moduleDescriptor, files.first().languageVersionSettings, EXACT) + return IDELightClassConstructionContext( + resolveSession.bindingContext, + resolveSession.moduleDescriptor, + files.first().languageVersionSettings, + EXACT + ) } fun contextForScript(script: KtScript): LightClassConstructionContext { @@ -145,7 +154,12 @@ internal object IDELightClassContexts { val descriptor = bindingContext[BindingContext.SCRIPT, script] if (descriptor == null) { LOG.warn("No script descriptor in context for script: " + script.getElementTextWithContext()) - return IDELightClassConstructionContext(bindingContext, resolutionFacade.moduleDescriptor, script.languageVersionSettings, EXACT) + return IDELightClassConstructionContext( + bindingContext, + resolutionFacade.moduleDescriptor, + script.languageVersionSettings, + EXACT + ) } ForceResolveUtil.forceResolveAllContents(descriptor) @@ -167,7 +181,12 @@ internal object IDELightClassContexts { ForceResolveUtil.forceResolveAllContents(descriptor) - return IDELightClassConstructionContext(resolveSession.bindingContext, resolveSession.moduleDescriptor, classOrObject.languageVersionSettings, LIGHT) + return IDELightClassConstructionContext( + resolveSession.bindingContext, + resolveSession.moduleDescriptor, + classOrObject.languageVersionSettings, + LIGHT + ) } fun lightContextForFacade(files: List): LightClassConstructionContext { @@ -176,7 +195,12 @@ internal object IDELightClassContexts { forceResolvePackageDeclarations(files, resolveSession) - return IDELightClassConstructionContext(resolveSession.bindingContext, resolveSession.moduleDescriptor, files.first().languageVersionSettings, LIGHT) + return IDELightClassConstructionContext( + resolveSession.bindingContext, + resolveSession.moduleDescriptor, + files.first().languageVersionSettings, + LIGHT + ) } private fun isDummyResolveApplicable(classOrObject: KtClassOrObject): Boolean { @@ -384,7 +408,7 @@ internal object IDELightClassContexts { private val codegenAffectingAnnotations: CodegenAffectingAnnotations, private val callResolver: CallResolver, private val languageVersionSettings: LanguageVersionSettings, - private val dataFlowValueFactory: DataFlowValueFactory,constantExpressionEvaluator: ConstantExpressionEvaluator, + private val dataFlowValueFactory: DataFlowValueFactory, constantExpressionEvaluator: ConstantExpressionEvaluator, storageManager: StorageManager ) : AnnotationResolverImpl(callResolver, constantExpressionEvaluator, storageManager) { @@ -404,7 +428,7 @@ internal object IDELightClassContexts { trace: BindingTrace ): OverloadResolutionResults { val annotationConstructor = annotationClassByEntry(annotationEntry)?.constructors?.singleOrNull() - ?: return super.resolveAnnotationCall(annotationEntry, scope, trace) + ?: return super.resolveAnnotationCall(annotationEntry, scope, trace) @Suppress("UNCHECKED_CAST") return callResolver.resolveConstructorCall( diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/lightClasses/KtFakeLightClass.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/lightClasses/KtFakeLightClass.kt index 07170db018e..9ef7293221e 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/lightClasses/KtFakeLightClass.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/lightClasses/KtFakeLightClass.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.caches.lightClasses @@ -108,10 +97,10 @@ private object DummyJavaPsiFactory { val canonicalText = GenericsUtil.getVariableTypeByExpressionType(returnType).getCanonicalText(true) val file = createDummyJavaFile(project, "class _Dummy_ { public $canonicalText $name() {\n} }") val klass = file.classes.singleOrNull() - ?: throw IncorrectOperationException("Class was not created. Method name: $name; return type: $canonicalText") + ?: throw IncorrectOperationException("Class was not created. Method name: $name; return type: $canonicalText") return klass.methods.singleOrNull() - ?: throw IncorrectOperationException("Method was not created. Method name: $name; return type: $canonicalText") + ?: throw IncorrectOperationException("Method was not created. Method name: $name; return type: $canonicalText") } fun createDummyClass(project: Project): PsiClass = PsiElementFactory.SERVICE.getInstance(project).createClass("dummy") diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/lightClasses/KtLightClassForDecompiledDeclaration.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/lightClasses/KtLightClassForDecompiledDeclaration.kt index 785aa492b7c..8fb08f37718 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/lightClasses/KtLightClassForDecompiledDeclaration.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/lightClasses/KtLightClassForDecompiledDeclaration.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.caches.lightClasses @@ -40,8 +29,9 @@ class KtLightClassForDecompiledDeclaration( override fun getOwnInnerClasses(): List { val nestedClasses = kotlinOrigin?.declarations?.filterIsInstance() ?: emptyList() return clsDelegate.ownInnerClasses.map { innerClsClass -> - KtLightClassForDecompiledDeclaration(innerClsClass as ClsClassImpl, - nestedClasses.firstOrNull { innerClsClass.name == it.name }, file + KtLightClassForDecompiledDeclaration( + innerClsClass as ClsClassImpl, + nestedClasses.firstOrNull { innerClsClass.name == it.name }, file ) } } diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/lightClasses/LazyLightClassDataHolder.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/lightClasses/LazyLightClassDataHolder.kt index f71d3c181af..0f4a1fc89fe 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/lightClasses/LazyLightClassDataHolder.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/lightClasses/LazyLightClassDataHolder.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2017 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -184,6 +184,7 @@ sealed class LazyLightClassDataHolder( } private val PsiMember.debugName - get() = "${this::class.java.simpleName}:${this.name} ${this.memberIndex}" + if (this is PsiMethod) " (with ${parameterList.parametersCount} parameters)" else "" + get() = "${this::class.java + .simpleName}:${this.name} ${this.memberIndex}" + if (this is PsiMethod) " (with ${parameterList.parametersCount} parameters)" else "" var KtClassOrObject.hasLightClassMatchingErrors: Boolean by NotNullableUserDataProperty(Key.create("LIGHT_CLASS_MATCHING_ERRORS"), false) diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/project/IdeaModuleInfos.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/project/IdeaModuleInfos.kt index 04fe67dfe0d..895a2bbbe13 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/project/IdeaModuleInfos.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/project/IdeaModuleInfos.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -233,8 +233,11 @@ fun Module.testSourceInfo(): ModuleTestSourceInfo? = if (hasTestRoots()) ModuleT internal fun Module.correspondingModuleInfos(): List = listOf(testSourceInfo(), productionSourceInfo()).filterNotNull() -private fun Module.hasProductionRoots() = hasRootsOfType(JavaSourceRootType.SOURCE) || hasRootsOfType(SourceKotlinRootType) || (isNewMPPModule && sourceType == SourceType.PRODUCTION) -private fun Module.hasTestRoots() = hasRootsOfType(JavaSourceRootType.TEST_SOURCE) || hasRootsOfType(TestSourceKotlinRootType) || (isNewMPPModule && sourceType == SourceType.TEST) +private fun Module.hasProductionRoots() = + hasRootsOfType(JavaSourceRootType.SOURCE) || hasRootsOfType(SourceKotlinRootType) || (isNewMPPModule && sourceType == SourceType.PRODUCTION) + +private fun Module.hasTestRoots() = + hasRootsOfType(JavaSourceRootType.TEST_SOURCE) || hasRootsOfType(TestSourceKotlinRootType) || (isNewMPPModule && sourceType == SourceType.TEST) private fun Module.hasRootsOfType(sourceRootType: JpsModuleSourceRootType<*>): Boolean = rootManager.contentEntries.any { it.getSourceFolders(sourceRootType).isNotEmpty() } @@ -322,7 +325,8 @@ open class LibraryInfo(val project: Project, val library: Library) : IdeaModuleI override fun hashCode(): Int = 43 * library.hashCode() } -data class LibrarySourceInfo(val project: Project, val library: Library, override val binariesModuleInfo: BinaryModuleInfo) : IdeaModuleInfo, SourceForBinaryModuleInfo { +data class LibrarySourceInfo(val project: Project, val library: Library, override val binariesModuleInfo: BinaryModuleInfo) : + IdeaModuleInfo, SourceForBinaryModuleInfo { override val name: Name = Name.special("") @@ -330,7 +334,8 @@ data class LibrarySourceInfo(val project: Project, val library: Library, overrid LibrarySourceScope( project, library - ), project) + ), project + ) override fun modulesWhoseInternalsAreVisible(): Collection { return createLibraryInfo(project, library) diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/project/getModuleInfo.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/project/getModuleInfo.kt index 6e1c5b727cf..6180f5e1fd5 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/project/getModuleInfo.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/project/getModuleInfo.kt @@ -101,14 +101,14 @@ private sealed class ModuleInfoCollector( LOG.error("Could not find correct module information.\nReason: $reason") NotUnderContentRootModuleInfo }, - virtualFileProcessor = processor@ { project, virtualFile, isLibrarySource -> + virtualFileProcessor = processor@{ project, virtualFile, isLibrarySource -> collectInfosByVirtualFile( project, virtualFile, - isLibrarySource, - { - return@processor it ?: NotUnderContentRootModuleInfo - }) + isLibrarySource + ) { + return@processor it ?: NotUnderContentRootModuleInfo + } } ) @@ -118,12 +118,12 @@ private sealed class ModuleInfoCollector( LOG.warn("Could not find correct module information.\nReason: $reason") null }, - virtualFileProcessor = processor@ { project, virtualFile, isLibrarySource -> + virtualFileProcessor = processor@{ project, virtualFile, isLibrarySource -> collectInfosByVirtualFile( project, virtualFile, - isLibrarySource, - { return@processor it }) + isLibrarySource + ) { return@processor it } } ) @@ -138,8 +138,8 @@ private sealed class ModuleInfoCollector( collectInfosByVirtualFile( project, virtualFile, - isLibrarySource, - { yieldIfNotNull(it) }) + isLibrarySource + ) { yieldIfNotNull(it) } } } ) diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/project/multiplatformUtil.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/project/multiplatformUtil.kt index a36b8393285..796968c7d4a 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/project/multiplatformUtil.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/project/multiplatformUtil.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -103,7 +103,10 @@ val Module.implementedModules: List KotlinMultiplatformVersion.M2 -> { rootManager.dependencies.filter { // TODO: remove additional android check - it.isNewMPPModule && it.platform.isCommon() && it.externalProjectId == externalProjectId && (isAndroidModule() || it.isTestModule == isTestModule) + it.isNewMPPModule && + it.platform.isCommon() && + it.externalProjectId == externalProjectId && + (isAndroidModule() || it.isTestModule == isTestModule) } } diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/resolve/PerFileAnalysisCache.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/resolve/PerFileAnalysisCache.kt index 768c59eb254..9f7065f5887 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/resolve/PerFileAnalysisCache.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/resolve/PerFileAnalysisCache.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.caches.resolve @@ -224,7 +213,8 @@ internal class PerFileAnalysisCache(val file: KtFile, componentProvider: Compone } } -private class MergedDiagnostics(val diagnostics: Collection, override val modificationTracker: ModificationTracker) : Diagnostics { +private class MergedDiagnostics(val diagnostics: Collection, override val modificationTracker: ModificationTracker) : + Diagnostics { @Suppress("UNCHECKED_CAST") private val elementsCache = DiagnosticsElementsCache(this) { true } diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/resolve/ProjectResolutionFacade.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/resolve/ProjectResolutionFacade.kt index e348f05c0de..6edac8645d9 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/resolve/ProjectResolutionFacade.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/resolve/ProjectResolutionFacade.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.caches.resolve @@ -69,8 +58,9 @@ internal class ProjectResolutionFacade( } } - val allDependencies = - resolverForProjectDependencies + listOf(KotlinCodeBlockModificationListener.getInstance(project).kotlinOutOfCodeBlockTracker) + val allDependencies = resolverForProjectDependencies + listOf( + KotlinCodeBlockModificationListener.getInstance(project).kotlinOutOfCodeBlockTracker + ) CachedValueProvider.Result.create(results, allDependencies) }, false ) @@ -114,8 +104,8 @@ internal class ProjectResolutionFacade( internal fun resolverForElement(element: PsiElement): ResolverForModule { val infos = element.getModuleInfos() return infos.asIterable().firstNotNullResult { cachedResolverForProject.tryGetResolverForModule(it) } - ?: cachedResolverForProject.tryGetResolverForModule(NotUnderContentRootModuleInfo) - ?: cachedResolverForProject.diagnoseUnknownModuleInfo(infos.toList()) + ?: cachedResolverForProject.tryGetResolverForModule(NotUnderContentRootModuleInfo) + ?: cachedResolverForProject.diagnoseUnknownModuleInfo(infos.toList()) } internal fun resolverForDescriptor(moduleDescriptor: ModuleDescriptor) = diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/resolve/ResolutionFacadeWithDebugInfo.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/resolve/ResolutionFacadeWithDebugInfo.kt index 24f34240e33..edc3621b204 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/resolve/ResolutionFacadeWithDebugInfo.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/resolve/ResolutionFacadeWithDebugInfo.kt @@ -1,5 +1,5 @@ /* - * Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -19,11 +19,11 @@ import org.jetbrains.kotlin.descriptors.ModuleDescriptor import org.jetbrains.kotlin.idea.caches.project.IdeaModuleInfo import org.jetbrains.kotlin.idea.caches.project.getNullableModuleInfo import org.jetbrains.kotlin.idea.resolve.ResolutionFacade +import org.jetbrains.kotlin.platform.TargetPlatform import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.resolve.BindingContext -import org.jetbrains.kotlin.platform.TargetPlatform import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments @@ -205,7 +205,8 @@ private fun StringBuilder.appendElement(element: PsiElement) { val moduleName = ifIndexReady { ModuleUtil.findModuleForFile(virtualFile, element.project)?.name ?: "null" }?.result info( "ideaModule", - moduleName ?: "") + moduleName ?: "" + ) } } diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/resolve/util/scopeUtils.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/resolve/util/scopeUtils.kt index ec89b92afab..72be1c756df 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/resolve/util/scopeUtils.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/resolve/util/scopeUtils.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -34,8 +34,13 @@ fun getResolveScope(file: KtFile): GlobalSearchScope { } return when (file.getModuleInfo()) { - is ModuleSourceInfo -> enlargedSearchScope(KotlinSourceFilterScope.projectSourceAndClassFiles(file.resolveScope, file.project), file) - is ScriptModuleInfo -> file.getModuleInfo().dependencies().map { it.contentScope() }.let { GlobalSearchScope.union(it.toTypedArray()) } + is ModuleSourceInfo -> enlargedSearchScope( + KotlinSourceFilterScope.projectSourceAndClassFiles(file.resolveScope, file.project), + file + ) + is ScriptModuleInfo -> file.getModuleInfo().dependencies().map { it.contentScope() }.let { + GlobalSearchScope.union(it.toTypedArray()) + } else -> GlobalSearchScope.EMPTY_SCOPE } } diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/trackers/psiModificationTrackerCompat.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/trackers/psiModificationTrackerCompat.kt index e7426b9b021..b44a384d3cb 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/trackers/psiModificationTrackerCompat.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/trackers/psiModificationTrackerCompat.kt @@ -9,4 +9,5 @@ import com.intellij.psi.impl.PsiModificationTrackerImpl // BUNCH: 191 @Suppress("unused") -val PsiModificationTrackerImpl.isEnableLanguageTrackerCompat get() = true \ No newline at end of file +val PsiModificationTrackerImpl.isEnableLanguageTrackerCompat + get() = true \ No newline at end of file diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/codeInsight/DescriptorToSourceUtilsIde.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/codeInsight/DescriptorToSourceUtilsIde.kt index f67095973cb..6bd2bcbf7db 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/codeInsight/DescriptorToSourceUtilsIde.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/codeInsight/DescriptorToSourceUtilsIde.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.codeInsight @@ -33,9 +22,9 @@ object DescriptorToSourceUtilsIde { // Returns all PSI elements for descriptor. It can find declarations in builtins or decompiled code. fun getAllDeclarations( - project: Project, - targetDescriptor: DeclarationDescriptor, - builtInsSearchScope: GlobalSearchScope? = null + project: Project, + targetDescriptor: DeclarationDescriptor, + builtInsSearchScope: GlobalSearchScope? = null ): Collection { val result = getDeclarationsStream(project, targetDescriptor, builtInsSearchScope).toHashSet() // filter out elements which are navigate to some other element of the result @@ -44,15 +33,15 @@ object DescriptorToSourceUtilsIde { } private fun getDeclarationsStream( - project: Project, targetDescriptor: DeclarationDescriptor, builtInsSearchScope: GlobalSearchScope? = null + project: Project, targetDescriptor: DeclarationDescriptor, builtInsSearchScope: GlobalSearchScope? = null ): Sequence { val effectiveReferencedDescriptors = DescriptorToSourceUtils.getEffectiveReferencedDescriptors(targetDescriptor).asSequence() return effectiveReferencedDescriptors.flatMap { effectiveReferenced -> // References in library sources should be resolved to corresponding decompiled declarations, // therefore we put both source declaration and decompiled declaration to stream, and afterwards we filter it in getAllDeclarations sequenceOfLazyValues( - { DescriptorToSourceUtils.getSourceFromDescriptor(effectiveReferenced) }, - { findDecompiledDeclaration(project, effectiveReferenced, builtInsSearchScope) } + { DescriptorToSourceUtils.getSourceFromDescriptor(effectiveReferenced) }, + { findDecompiledDeclaration(project, effectiveReferenced, builtInsSearchScope) } ) }.filterNotNull() } diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/compiler/configuration/BaseKotlinCompilerSettings.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/compiler/configuration/BaseKotlinCompilerSettings.kt index 6ec219a5af6..3a04e607ca9 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/compiler/configuration/BaseKotlinCompilerSettings.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/compiler/configuration/BaseKotlinCompilerSettings.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.compiler.configuration @@ -32,7 +21,8 @@ import org.jetbrains.kotlin.cli.common.arguments.* import org.jetbrains.kotlin.idea.syncPublisherWithDisposeCheck import kotlin.reflect.KClass -abstract class BaseKotlinCompilerSettings protected constructor(private val project: Project) : PersistentStateComponent, Cloneable { +abstract class BaseKotlinCompilerSettings protected constructor(private val project: Project) : + PersistentStateComponent, Cloneable { // Based on com.intellij.util.xmlb.SkipDefaultValuesSerializationFilters private object DefaultValuesFilter : SerializationFilterBase() { private val defaultBeans = THashMap, Any>() diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/compiler/configuration/KotlinCommonCompilerArgumentsHolder.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/compiler/configuration/KotlinCommonCompilerArgumentsHolder.kt index 3cdeb705111..55ff6948c4a 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/compiler/configuration/KotlinCommonCompilerArgumentsHolder.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/compiler/configuration/KotlinCommonCompilerArgumentsHolder.kt @@ -1,24 +1,14 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.compiler.configuration -import com.intellij.openapi.components.* +import com.intellij.openapi.components.ServiceManager +import com.intellij.openapi.components.State +import com.intellij.openapi.components.Storage import com.intellij.openapi.project.Project -import com.intellij.util.text.VersionComparatorUtil import org.jdom.Element import org.jetbrains.kotlin.cli.common.arguments.CommonCompilerArguments import org.jetbrains.kotlin.cli.common.arguments.setApiVersionToLanguageVersionIfNeeded @@ -49,6 +39,6 @@ class KotlinCommonCompilerArgumentsHolder(project: Project) : BaseKotlinCompiler companion object { fun getInstance(project: Project) = - ServiceManager.getService(project, KotlinCommonCompilerArgumentsHolder::class.java)!! + ServiceManager.getService(project, KotlinCommonCompilerArgumentsHolder::class.java)!! } } diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/compiler/configuration/KotlinCompilerSettings.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/compiler/configuration/KotlinCompilerSettings.kt index b836ef4c5bc..b06ae92893d 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/compiler/configuration/KotlinCompilerSettings.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/compiler/configuration/KotlinCompilerSettings.kt @@ -1,22 +1,13 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.compiler.configuration -import com.intellij.openapi.components.* +import com.intellij.openapi.components.ServiceManager +import com.intellij.openapi.components.State +import com.intellij.openapi.components.Storage import com.intellij.openapi.project.Project import org.jetbrains.kotlin.config.CompilerSettings import org.jetbrains.kotlin.config.SettingConstants @@ -27,7 +18,6 @@ class KotlinCompilerSettings(project: Project) : BaseKotlinCompilerSettings KtDecompiledFile? + manager: PsiManager, + file: VirtualFile, + physical: Boolean, + private val factory: (KotlinDecompiledFileViewProvider) -> KtDecompiledFile? ) : SingleRootFileViewProvider(manager, file, physical, KotlinLanguage.INSTANCE) { - val content : LockedClearableLazyValue = LockedClearableLazyValue(Any()) { + val content: LockedClearableLazyValue = LockedClearableLazyValue(Any()) { val psiFile = createFile(manager.project, file, KotlinFileType.INSTANCE) val text = psiFile?.text ?: "" DebugUtil.startPsiModification("Invalidating throw-away copy of file that was used for getting text") try { (psiFile as? PsiFileImpl)?.markInvalidated() - } - finally { + } finally { DebugUtil.finishPsiModification() } diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/KtDecompiledFile.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/KtDecompiledFile.kt index ff680527950..0f862afe0b7 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/KtDecompiledFile.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/KtDecompiledFile.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.decompiler @@ -25,8 +14,8 @@ import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.utils.concurrent.block.LockedClearableLazyValue open class KtDecompiledFile( - private val provider: KotlinDecompiledFileViewProvider, - buildDecompiledText: (VirtualFile) -> DecompiledText + private val provider: KotlinDecompiledFileViewProvider, + buildDecompiledText: (VirtualFile) -> DecompiledText ) : KtFile(provider, true) { private val decompiledText = LockedClearableLazyValue(Any()) { diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/classFile/DeserializerForClassfileDecompiler.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/classFile/DeserializerForClassfileDecompiler.kt index 3275bfa8a2e..8c76f59c692 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/classFile/DeserializerForClassfileDecompiler.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/classFile/DeserializerForClassfileDecompiler.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.decompiler.classFile @@ -51,8 +40,8 @@ fun DeserializerForClassfileDecompiler(classFile: VirtualFile): DeserializerForC } class DeserializerForClassfileDecompiler( - packageDirectory: VirtualFile, - directoryPackageFqName: FqName + packageDirectory: VirtualFile, + directoryPackageFqName: FqName ) : DeserializerForDecompilerBase(directoryPackageFqName) { override val builtIns: KotlinBuiltIns get() = DefaultBuiltIns.Instance @@ -64,7 +53,7 @@ class DeserializerForClassfileDecompiler( val classDataFinder = DirectoryBasedDataFinder(classFinder, LOG) val notFoundClasses = NotFoundClasses(storageManager, moduleDescriptor) val annotationAndConstantLoader = - BinaryClassAnnotationAndConstantLoaderImpl(moduleDescriptor, notFoundClasses, storageManager, classFinder) + BinaryClassAnnotationAndConstantLoaderImpl(moduleDescriptor, notFoundClasses, storageManager, classFinder) val configuration = object : DeserializationConfiguration { override val readDeserializedContracts: Boolean @@ -72,11 +61,11 @@ class DeserializerForClassfileDecompiler( } deserializationComponents = DeserializationComponents( - storageManager, moduleDescriptor, configuration, classDataFinder, annotationAndConstantLoader, - packageFragmentProvider, ResolveEverythingToKotlinAnyLocalClassifierResolver(builtIns), LoggingErrorReporter(LOG), - LookupTracker.DO_NOTHING, JavaFlexibleTypeDeserializer, emptyList(), notFoundClasses, - ContractDeserializerImpl(configuration, storageManager), - extensionRegistryLite = JvmProtoBufUtil.EXTENSION_REGISTRY + storageManager, moduleDescriptor, configuration, classDataFinder, annotationAndConstantLoader, + packageFragmentProvider, ResolveEverythingToKotlinAnyLocalClassifierResolver(builtIns), LoggingErrorReporter(LOG), + LookupTracker.DO_NOTHING, JavaFlexibleTypeDeserializer, emptyList(), notFoundClasses, + ContractDeserializerImpl(configuration, storageManager), + extensionRegistryLite = JvmProtoBufUtil.EXTENSION_REGISTRY ) } @@ -108,8 +97,8 @@ class DeserializerForClassfileDecompiler( } class DirectoryBasedClassFinder( - val packageDirectory: VirtualFile, - val directoryPackageFqName: FqName + val packageDirectory: VirtualFile, + val directoryPackageFqName: FqName ) : KotlinClassFinder { override fun findKotlinClassOrContent(javaClass: JavaClass) = findKotlinClassOrContent(javaClass.classId!!) @@ -136,8 +125,8 @@ class DirectoryBasedClassFinder( } class DirectoryBasedDataFinder( - val classFinder: DirectoryBasedClassFinder, - val log: Logger + val classFinder: DirectoryBasedClassFinder, + val log: Logger ) : ClassDataFinder { override fun findClassData(classId: ClassId): ClassData? { val binaryClass = classFinder.findKotlinClass(classId) ?: return null diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/classFile/KotlinClassFileDecompiler.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/classFile/KotlinClassFileDecompiler.kt index 8301227cb5e..42ee4630d90 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/classFile/KotlinClassFileDecompiler.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/classFile/KotlinClassFileDecompiler.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.decompiler.classFile @@ -64,8 +53,8 @@ private val decompilerRendererForClassFiles = DescriptorRenderer.withOptions { } fun buildDecompiledTextForClassFile( - classFile: VirtualFile, - resolver: ResolverForDecompiler = DeserializerForClassfileDecompiler(classFile) + classFile: VirtualFile, + resolver: ResolverForDecompiler = DeserializerForClassfileDecompiler(classFile) ): DecompiledText { val classHeader = IDEKotlinBinaryClassCache.getInstance().getKotlinBinaryClassHeaderData(classFile) @@ -77,9 +66,10 @@ fun buildDecompiledTextForClassFile( return createIncompatibleAbiVersionDecompiledText(JvmMetadataVersion.INSTANCE, classHeader.metadataVersion) } - fun buildText(declarations: List) = - buildDecompiledText(classHeader.packageName?.let(::FqName) ?: classId.packageFqName, - declarations, decompilerRendererForClassFiles, listOf(ByDescriptorIndexer, BySignatureIndexer)) + fun buildText(declarations: List) = buildDecompiledText( + classHeader.packageName?.let(::FqName) ?: classId.packageFqName, + declarations, decompilerRendererForClassFiles, listOf(ByDescriptorIndexer, BySignatureIndexer) + ) return when (classHeader.kind) { KotlinClassHeader.Kind.FILE_FACADE -> diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/classFile/KotlinClsStubBuilder.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/classFile/KotlinClsStubBuilder.kt index 9200a5c0325..1ad52966eac 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/classFile/KotlinClsStubBuilder.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/classFile/KotlinClsStubBuilder.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.decompiler.classFile @@ -103,7 +92,7 @@ open class KotlinClsStubBuilder : ClsStubBuilder() { val (nameResolver, packageProto) = JvmProtoBufUtil.readPackageDataFrom(annotationData, strings) val context = components.createContext(nameResolver, packageFqName, TypeTable(packageProto.typeTable)) val fqName = header.packageName?.let { ClassId(FqName(it), classId.relativeClassName, classId.isLocal).asSingleFqName() } - ?: classId.asSingleFqName() + ?: classId.asSingleFqName() createFileFacadeStub(packageProto, fqName, context) } else -> throw IllegalStateException("Should have processed " + file.path + " with header $header") @@ -130,9 +119,9 @@ open class KotlinClsStubBuilder : ClsStubBuilder() { } class AnnotationLoaderForClassFileStubBuilder( - kotlinClassFinder: KotlinClassFinder, - private val cachedFile: VirtualFile, - private val cachedFileContent: ByteArray + kotlinClassFinder: KotlinClassFinder, + private val cachedFile: VirtualFile, + private val cachedFileContent: ByteArray ) : AbstractBinaryClassAnnotationAndConstantLoader(LockBasedStorageManager.NO_LOCKS, kotlinClassFinder) { override fun getCachedFileContent(kotlinClass: KotlinJvmBinaryClass): ByteArray? { @@ -142,15 +131,14 @@ class AnnotationLoaderForClassFileStubBuilder( return null } - override fun loadTypeAnnotation(proto: ProtoBuf.Annotation, nameResolver: NameResolver): ClassId = - nameResolver.getClassId(proto.id) + override fun loadTypeAnnotation(proto: ProtoBuf.Annotation, nameResolver: NameResolver): ClassId = nameResolver.getClassId(proto.id) override fun loadConstant(desc: String, initializer: Any) = null override fun transformToUnsignedConstant(constant: Unit) = null override fun loadAnnotation( - annotationClassId: ClassId, source: SourceElement, result: MutableList + annotationClassId: ClassId, source: SourceElement, result: MutableList ): KotlinJvmBinaryClass.AnnotationArgumentVisitor? { result.add(annotationClassId) return null diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/common/AnnotationLoaderForStubBuilderImpl.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/common/AnnotationLoaderForStubBuilderImpl.kt index c7615d56037..813dbcc9b7a 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/common/AnnotationLoaderForStubBuilderImpl.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/common/AnnotationLoaderForStubBuilderImpl.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.decompiler.common @@ -28,16 +17,16 @@ import org.jetbrains.kotlin.serialization.deserialization.getClassId import org.jetbrains.kotlin.types.KotlinType class AnnotationLoaderForStubBuilderImpl( - private val protocol: SerializerExtensionProtocol + private val protocol: SerializerExtensionProtocol ) : AnnotationAndConstantLoader { override fun loadClassAnnotations(container: ProtoContainer.Class): List = - container.classProto.getExtension(protocol.classAnnotation).orEmpty().map { container.nameResolver.getClassId(it.id) } + container.classProto.getExtension(protocol.classAnnotation).orEmpty().map { container.nameResolver.getClassId(it.id) } override fun loadCallableAnnotations( - container: ProtoContainer, - proto: MessageLite, - kind: AnnotatedCallableKind + container: ProtoContainer, + proto: MessageLite, + kind: AnnotatedCallableKind ): List { val annotations = when (proto) { is ProtoBuf.Constructor -> proto.getExtension(protocol.constructorAnnotation) @@ -60,35 +49,36 @@ class AnnotationLoaderForStubBuilderImpl( emptyList() override fun loadEnumEntryAnnotations(container: ProtoContainer, proto: ProtoBuf.EnumEntry): List = - proto.getExtension(protocol.enumEntryAnnotation).orEmpty().map { container.nameResolver.getClassId(it.id) } + proto.getExtension(protocol.enumEntryAnnotation).orEmpty().map { container.nameResolver.getClassId(it.id) } override fun loadValueParameterAnnotations( - container: ProtoContainer, - callableProto: MessageLite, - kind: AnnotatedCallableKind, - parameterIndex: Int, - proto: ProtoBuf.ValueParameter + container: ProtoContainer, + callableProto: MessageLite, + kind: AnnotatedCallableKind, + parameterIndex: Int, + proto: ProtoBuf.ValueParameter ): List = - proto.getExtension(protocol.parameterAnnotation).orEmpty().map { container.nameResolver.getClassId(it.id) } + proto.getExtension(protocol.parameterAnnotation).orEmpty().map { container.nameResolver.getClassId(it.id) } override fun loadExtensionReceiverParameterAnnotations( - container: ProtoContainer, - proto: MessageLite, - kind: AnnotatedCallableKind + container: ProtoContainer, + proto: MessageLite, + kind: AnnotatedCallableKind ): List = emptyList() override fun loadTypeAnnotations( - proto: ProtoBuf.Type, - nameResolver: NameResolver + proto: ProtoBuf.Type, + nameResolver: NameResolver ): List = - proto.getExtension(protocol.typeAnnotation).orEmpty().map { nameResolver.getClassId(it.id) } + proto.getExtension(protocol.typeAnnotation).orEmpty().map { nameResolver.getClassId(it.id) } override fun loadTypeParameterAnnotations(proto: ProtoBuf.TypeParameter, nameResolver: NameResolver): List = proto.getExtension(protocol.typeParameterAnnotation).orEmpty().map { nameResolver.getClassId(it.id) } override fun loadPropertyConstant( - container: ProtoContainer, - proto: ProtoBuf.Property, - expectedType: KotlinType - ) {} + container: ProtoContainer, + proto: ProtoBuf.Property, + expectedType: KotlinType + ) { + } } diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/common/KotlinMetadataDecompiler.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/common/KotlinMetadataDecompiler.kt index fdda5d8eaf0..89d16e3fda1 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/common/KotlinMetadataDecompiler.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/common/KotlinMetadataDecompiler.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.decompiler.common @@ -101,8 +90,8 @@ abstract class KotlinMetadataDecompiler( is FileWithMetadata.Compatible -> { val packageFqName = file.packageFqName val resolver = KotlinMetadataDeserializerForDecompiler( - packageFqName, file.proto, file.nameResolver, file.version, - serializerProtocol(), flexibleTypeDeserializer + packageFqName, file.proto, file.nameResolver, file.version, + serializerProtocol(), flexibleTypeDeserializer ) val declarations = arrayListOf() declarations.addAll(resolver.resolveDeclarationsInFacade(packageFqName)) diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/common/KotlinMetadataDeserializerForDecompiler.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/common/KotlinMetadataDeserializerForDecompiler.kt index 641205ba27c..7c1ce11b3f2 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/common/KotlinMetadataDeserializerForDecompiler.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/common/KotlinMetadataDeserializerForDecompiler.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.decompiler.common @@ -34,12 +23,12 @@ import org.jetbrains.kotlin.serialization.deserialization.* import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedPackageMemberScope class KotlinMetadataDeserializerForDecompiler( - packageFqName: FqName, - private val proto: ProtoBuf.PackageFragment, - private val nameResolver: NameResolver, - private val metadataVersion: BinaryVersion, - serializerProtocol: SerializerExtensionProtocol, - flexibleTypeDeserializer: FlexibleTypeDeserializer + packageFqName: FqName, + private val proto: ProtoBuf.PackageFragment, + private val nameResolver: NameResolver, + private val metadataVersion: BinaryVersion, + serializerProtocol: SerializerExtensionProtocol, + flexibleTypeDeserializer: FlexibleTypeDeserializer ) : DeserializerForDecompilerBase(packageFqName) { override val builtIns: KotlinBuiltIns get() = DefaultBuiltIns.Instance @@ -49,13 +38,13 @@ class KotlinMetadataDeserializerForDecompiler( val notFoundClasses = NotFoundClasses(storageManager, moduleDescriptor) deserializationComponents = DeserializationComponents( - storageManager, moduleDescriptor, DeserializationConfiguration.Default, - ProtoBasedClassDataFinder(proto, nameResolver, metadataVersion), - AnnotationAndConstantLoaderImpl(moduleDescriptor, notFoundClasses, serializerProtocol), packageFragmentProvider, - ResolveEverythingToKotlinAnyLocalClassifierResolver(builtIns), LoggingErrorReporter(LOG), - LookupTracker.DO_NOTHING, flexibleTypeDeserializer, emptyList(), notFoundClasses, - ContractDeserializer.DEFAULT, - extensionRegistryLite = serializerProtocol.extensionRegistry + storageManager, moduleDescriptor, DeserializationConfiguration.Default, + ProtoBasedClassDataFinder(proto, nameResolver, metadataVersion), + AnnotationAndConstantLoaderImpl(moduleDescriptor, notFoundClasses, serializerProtocol), packageFragmentProvider, + ResolveEverythingToKotlinAnyLocalClassifierResolver(builtIns), LoggingErrorReporter(LOG), + LookupTracker.DO_NOTHING, flexibleTypeDeserializer, emptyList(), notFoundClasses, + ContractDeserializer.DEFAULT, + extensionRegistryLite = serializerProtocol.extensionRegistry ) } diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/common/KotlinMetadataStubBuilder.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/common/KotlinMetadataStubBuilder.kt index cdd0f1e5eba..a6529c054b2 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/common/KotlinMetadataStubBuilder.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/common/KotlinMetadataStubBuilder.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.decompiler.common @@ -30,10 +19,10 @@ import org.jetbrains.kotlin.serialization.deserialization.ProtoContainer import org.jetbrains.kotlin.serialization.deserialization.getClassId open class KotlinMetadataStubBuilder( - private val version: Int, - private val fileType: FileType, - private val serializerProtocol: () -> SerializerExtensionProtocol, - private val readFile: (VirtualFile, ByteArray) -> FileWithMetadata? + private val version: Int, + private val fileType: FileType, + private val serializerProtocol: () -> SerializerExtensionProtocol, + private val readFile: (VirtualFile, ByteArray) -> FileWithMetadata? ) : ClsStubBuilder() { override fun getStubVersion() = ClassFileStubBuilder.STUB_VERSION + version @@ -51,21 +40,21 @@ open class KotlinMetadataStubBuilder( val packageFqName = file.packageFqName val nameResolver = file.nameResolver val components = ClsStubBuilderComponents( - ProtoBasedClassDataFinder(file.proto, nameResolver, file.version), - AnnotationLoaderForStubBuilderImpl(serializerProtocol()), - virtualFile + ProtoBasedClassDataFinder(file.proto, nameResolver, file.version), + AnnotationLoaderForStubBuilderImpl(serializerProtocol()), + virtualFile ) val context = components.createContext(nameResolver, packageFqName, TypeTable(packageProto.typeTable)) val fileStub = createFileStub(packageFqName, isScript = false) createDeclarationsStubs( - fileStub, context, - ProtoContainer.Package(packageFqName, context.nameResolver, context.typeTable, source = null), - packageProto + fileStub, context, + ProtoContainer.Package(packageFqName, context.nameResolver, context.typeTable, source = null), + packageProto ) for (classProto in file.classesToDecompile) { createClassStub( - fileStub, classProto, nameResolver, nameResolver.getClassId(classProto.fqName), source = null, context = context + fileStub, classProto, nameResolver, nameResolver.getClassId(classProto.fqName), source = null, context = context ) } return fileStub diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/common/incompatibleAbiVersion.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/common/incompatibleAbiVersion.kt index af50a45b31e..b5a0228aa0a 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/common/incompatibleAbiVersion.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/common/incompatibleAbiVersion.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.decompiler.common @@ -20,21 +9,19 @@ import org.jetbrains.kotlin.idea.decompiler.textBuilder.DecompiledText import org.jetbrains.kotlin.idea.decompiler.textBuilder.DecompiledTextIndex import org.jetbrains.kotlin.metadata.deserialization.BinaryVersion -private val FILE_ABI_VERSION_MARKER: String = "FILE_ABI" -private val CURRENT_ABI_VERSION_MARKER: String = "CURRENT_ABI" +private const val FILE_ABI_VERSION_MARKER: String = "FILE_ABI" +private const val CURRENT_ABI_VERSION_MARKER: String = "CURRENT_ABI" -val INCOMPATIBLE_ABI_VERSION_GENERAL_COMMENT: String = "// This class file was compiled with different version of Kotlin compiler and can't be decompiled." -private val INCOMPATIBLE_ABI_VERSION_COMMENT: String = - "$INCOMPATIBLE_ABI_VERSION_GENERAL_COMMENT\n" + +val INCOMPATIBLE_ABI_VERSION_GENERAL_COMMENT: String = + "// This class file was compiled with different version of Kotlin compiler and can't be decompiled." + +private val INCOMPATIBLE_ABI_VERSION_COMMENT: String = "$INCOMPATIBLE_ABI_VERSION_GENERAL_COMMENT\n" + "//\n" + "// Current compiler ABI version is $CURRENT_ABI_VERSION_MARKER\n" + "// File ABI version is $FILE_ABI_VERSION_MARKER" -fun createIncompatibleAbiVersionDecompiledText(expectedVersion: V, actualVersion: V): DecompiledText { - return DecompiledText( - INCOMPATIBLE_ABI_VERSION_COMMENT - .replace(CURRENT_ABI_VERSION_MARKER, expectedVersion.toString()) - .replace(FILE_ABI_VERSION_MARKER, actualVersion.toString()), - DecompiledTextIndex.Empty - ) -} +fun createIncompatibleAbiVersionDecompiledText(expectedVersion: V, actualVersion: V): DecompiledText = DecompiledText( + INCOMPATIBLE_ABI_VERSION_COMMENT.replace(CURRENT_ABI_VERSION_MARKER, expectedVersion.toString()) + .replace(FILE_ABI_VERSION_MARKER, actualVersion.toString()), + DecompiledTextIndex.Empty +) diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/navigation/KotlinDeclarationNavigationPolicyImpl.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/navigation/KotlinDeclarationNavigationPolicyImpl.kt index 0f2cdfa8fa9..e617ec32d7c 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/navigation/KotlinDeclarationNavigationPolicyImpl.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/navigation/KotlinDeclarationNavigationPolicyImpl.kt @@ -1,29 +1,15 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.decompiler.navigation import org.jetbrains.kotlin.psi.KotlinDeclarationNavigationPolicy -import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtDeclaration -import com.intellij.openapi.project.DumbService class KotlinDeclarationNavigationPolicyImpl : KotlinDeclarationNavigationPolicy { - override fun getOriginalElement(declaration: KtDeclaration) = - SourceNavigationHelper.getOriginalElement(declaration) - override fun getNavigationElement(declaration: KtDeclaration) = - SourceNavigationHelper.getNavigationElement(declaration) + override fun getOriginalElement(declaration: KtDeclaration) = SourceNavigationHelper.getOriginalElement(declaration) + + override fun getNavigationElement(declaration: KtDeclaration) = SourceNavigationHelper.getNavigationElement(declaration) } diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/navigation/findDecompiledDeclaration.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/navigation/findDecompiledDeclaration.kt index a306fa19336..5c60cd48d21 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/navigation/findDecompiledDeclaration.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/navigation/findDecompiledDeclaration.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.decompiler.navigation @@ -46,10 +35,10 @@ import org.jetbrains.kotlin.types.ErrorUtils import java.util.* fun findDecompiledDeclaration( - project: Project, - referencedDescriptor: DeclarationDescriptor, - // TODO: should not require explicitly specified scope to search for builtIns, use SourceElement to provide such information - builtInsSearchScope: GlobalSearchScope? + project: Project, + referencedDescriptor: DeclarationDescriptor, + // TODO: should not require explicitly specified scope to search for builtIns, use SourceElement to provide such information + builtInsSearchScope: GlobalSearchScope? ): KtDeclaration? { if (ErrorUtils.isError(referencedDescriptor)) return null if (isLocal(referencedDescriptor)) return null @@ -63,9 +52,9 @@ fun findDecompiledDeclaration( if (KotlinBuiltIns.isBuiltIn(referencedDescriptor)) { // builtin module does not contain information about it's origin return builtInsSearchScope?.let { findInScope(referencedDescriptor, it) } - // fallback on searching everywhere since builtIns are accessible from any context - ?: findInScope(referencedDescriptor, GlobalSearchScope.allScope(project)) - ?: findInScope(referencedDescriptor, EverythingGlobalScope(project)) + // fallback on searching everywhere since builtIns are accessible from any context + ?: findInScope(referencedDescriptor, GlobalSearchScope.allScope(project)) + ?: findInScope(referencedDescriptor, EverythingGlobalScope(project)) } return null } @@ -73,31 +62,27 @@ fun findDecompiledDeclaration( private fun findInScope(referencedDescriptor: DeclarationDescriptor, scope: GlobalSearchScope): KtDeclaration? { val project = scope.project ?: return null val decompiledFiles = findCandidateDeclarationsInIndex( - referencedDescriptor, KotlinSourceFilterScope.libraryClassFiles(scope, project), project + referencedDescriptor, KotlinSourceFilterScope.libraryClassFiles(scope, project), project ).mapNotNullTo(LinkedHashSet()) { it?.containingFile as? KtDecompiledFile } - return decompiledFiles.asSequence().mapNotNull { - file -> + return decompiledFiles.asSequence().mapNotNull { file -> ByDescriptorIndexer.getDeclarationForDescriptor(referencedDescriptor, file) }.firstOrNull() } -private fun isLocal(descriptor: DeclarationDescriptor): Boolean { - return if (descriptor is ParameterDescriptor) { - isLocal(descriptor.containingDeclaration) - } - else { - DescriptorUtils.isLocal(descriptor) - } +private fun isLocal(descriptor: DeclarationDescriptor): Boolean = if (descriptor is ParameterDescriptor) { + isLocal(descriptor.containingDeclaration) +} else { + DescriptorUtils.isLocal(descriptor) } private fun findCandidateDeclarationsInIndex( - referencedDescriptor: DeclarationDescriptor, - scope: GlobalSearchScope, - project: Project + referencedDescriptor: DeclarationDescriptor, + scope: GlobalSearchScope, + project: Project ): Collection { val containingClass = DescriptorUtils.getParentOfType(referencedDescriptor, ClassDescriptor::class.java, false) if (containingClass != null) { @@ -105,7 +90,7 @@ private fun findCandidateDeclarationsInIndex( } val topLevelDeclaration = - DescriptorUtils.getParentOfType(referencedDescriptor, PropertyDescriptor::class.java, false) as DeclarationDescriptor? + DescriptorUtils.getParentOfType(referencedDescriptor, PropertyDescriptor::class.java, false) as DeclarationDescriptor? ?: DescriptorUtils.getParentOfType(referencedDescriptor, TypeAliasConstructorDescriptor::class.java, false)?.typeAliasDescriptor ?: DescriptorUtils.getParentOfType(referencedDescriptor, FunctionDescriptor::class.java, false) ?: DescriptorUtils.getParentOfType(referencedDescriptor, TypeAliasDescriptor::class.java, false) @@ -143,8 +128,10 @@ object ByDescriptorIndexer : DecompiledTextIndexer { val callable = original.containingDeclaration val callableDeclaration = getDeclarationForDescriptor(callable, file) as? KtCallableDeclaration ?: return null if (original.index >= callableDeclaration.valueParameters.size) { - LOG.error("Parameter count mismatch for ${DescriptorRenderer.DEBUG_TEXT.render(callable)}[${original.index}] vs " + - callableDeclaration.valueParameterList?.text) + LOG.error( + "Parameter count mismatch for ${DescriptorRenderer.DEBUG_TEXT.render(callable)}[${original.index}] vs " + + callableDeclaration.valueParameterList?.text + ) return null } return callableDeclaration.valueParameters[original.index] @@ -158,8 +145,12 @@ object ByDescriptorIndexer : DecompiledTextIndexer { val descriptorKey = original.toStringKey() if (!file.isContentsLoaded && original is MemberDescriptor) { - val hasDeclarationByKey = file.hasDeclarationWithKey(this, descriptorKey) || - (getBuiltinsDescriptorKey(descriptor)?.let { file.hasDeclarationWithKey(this, it) } ?: false) + val hasDeclarationByKey = file.hasDeclarationWithKey(this, descriptorKey) || (getBuiltinsDescriptorKey(descriptor)?.let { + file.hasDeclarationWithKey( + this, + it + ) + } ?: false) if (hasDeclarationByKey) { val declarationContainer: KtDeclarationContainer? = when { DescriptorUtils.isTopLevelDeclaration(original) -> file @@ -190,7 +181,7 @@ object ByDescriptorIndexer : DecompiledTextIndexer { if (!JvmBuiltInsSettings.isSerializableInJava(classFqName)) return null val builtInDescriptor = - DefaultBuiltIns.Instance.builtInsModule.resolveTopLevelClass(classFqName.toSafe(), NoLookupLocation.FROM_IDE) + DefaultBuiltIns.Instance.builtInsModule.resolveTopLevelClass(classFqName.toSafe(), NoLookupLocation.FROM_IDE) return builtInDescriptor?.toStringKey() } diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/CallableClsStubBuilder.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/CallableClsStubBuilder.kt index b3d41763fc4..506bc686f73 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/CallableClsStubBuilder.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/CallableClsStubBuilder.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.decompiler.stubBuilder @@ -38,22 +27,23 @@ import org.jetbrains.kotlin.serialization.deserialization.ProtoContainer import org.jetbrains.kotlin.serialization.deserialization.getName fun createDeclarationsStubs( - parentStub: StubElement, - outerContext: ClsStubBuilderContext, - protoContainer: ProtoContainer, - packageProto: ProtoBuf.Package + parentStub: StubElement, + outerContext: ClsStubBuilderContext, + protoContainer: ProtoContainer, + packageProto: ProtoBuf.Package ) { createDeclarationsStubs( - parentStub, outerContext, protoContainer, packageProto.functionList, packageProto.propertyList, packageProto.typeAliasList) + parentStub, outerContext, protoContainer, packageProto.functionList, packageProto.propertyList, packageProto.typeAliasList + ) } fun createDeclarationsStubs( - parentStub: StubElement, - outerContext: ClsStubBuilderContext, - protoContainer: ProtoContainer, - functionProtos: List, - propertyProtos: List, - typeAliasesProtos: List + parentStub: StubElement, + outerContext: ClsStubBuilderContext, + protoContainer: ProtoContainer, + functionProtos: List, + propertyProtos: List, + typeAliasesProtos: List ) { for (propertyProto in propertyProtos) { if (!shouldSkip(propertyProto.flags, outerContext.nameResolver.getName(propertyProto.name))) { @@ -72,10 +62,10 @@ fun createDeclarationsStubs( } fun createConstructorStub( - parentStub: StubElement, - constructorProto: ProtoBuf.Constructor, - outerContext: ClsStubBuilderContext, - protoContainer: ProtoContainer + parentStub: StubElement, + constructorProto: ProtoBuf.Constructor, + outerContext: ClsStubBuilderContext, + protoContainer: ProtoContainer ) { ConstructorClsStubBuilder(parentStub, outerContext, protoContainer, constructorProto).build() } @@ -90,10 +80,10 @@ private fun shouldSkip(flags: Int, name: Name): Boolean { } abstract class CallableClsStubBuilder( - parent: StubElement, - outerContext: ClsStubBuilderContext, - protected val protoContainer: ProtoContainer, - private val typeParameters: List + parent: StubElement, + outerContext: ClsStubBuilderContext, + protected val protoContainer: ProtoContainer, + private val typeParameters: List ) { protected val c = outerContext.child(typeParameters) protected val typeStubBuilder = TypeClsStubBuilder(c) @@ -134,10 +124,10 @@ abstract class CallableClsStubBuilder( } private class FunctionClsStubBuilder( - parent: StubElement, - outerContext: ClsStubBuilderContext, - protoContainer: ProtoContainer, - private val functionProto: ProtoBuf.Function + parent: StubElement, + outerContext: ClsStubBuilderContext, + protoContainer: ProtoContainer, + private val functionProto: ProtoBuf.Function ) : CallableClsStubBuilder(parent, outerContext, protoContainer, functionProto.typeParameterList) { override val receiverType: ProtoBuf.Type? get() = functionProto.receiverType(c.typeTable) @@ -145,8 +135,8 @@ private class FunctionClsStubBuilder( override val receiverAnnotations: List get() { return c.components.annotationLoader - .loadExtensionReceiverParameterAnnotations(protoContainer, functionProto, AnnotatedCallableKind.FUNCTION) - .map { ClassIdWithTarget(it, AnnotationUseSiteTarget.RECEIVER) } + .loadExtensionReceiverParameterAnnotations(protoContainer, functionProto, AnnotatedCallableKind.FUNCTION) + .map { ClassIdWithTarget(it, AnnotationUseSiteTarget.RECEIVER) } } override val returnType: ProtoBuf.Type? @@ -159,12 +149,12 @@ private class FunctionClsStubBuilder( override fun createModifierListStub() { val modalityModifier = if (isTopLevel) listOf() else listOf(MODALITY) val modifierListStubImpl = createModifierListStubForDeclaration( - callableStub, functionProto.flags, - listOf(VISIBILITY, OPERATOR, INFIX, EXTERNAL_FUN, INLINE, TAILREC, SUSPEND) + modalityModifier + callableStub, functionProto.flags, + listOf(VISIBILITY, OPERATOR, INFIX, EXTERNAL_FUN, INLINE, TAILREC, SUSPEND) + modalityModifier ) val annotationIds = c.components.annotationLoader.loadCallableAnnotations( - protoContainer, functionProto, AnnotatedCallableKind.FUNCTION + protoContainer, functionProto, AnnotatedCallableKind.FUNCTION ) createAnnotationStubs(annotationIds, modifierListStubImpl) } @@ -173,24 +163,24 @@ private class FunctionClsStubBuilder( val callableName = c.nameResolver.getName(functionProto.name) return KotlinFunctionStubImpl( - parent, - callableName.ref(), - isTopLevel, - c.containerFqName.child(callableName), - isExtension = functionProto.hasReceiver(), - hasBlockBody = true, - hasBody = Flags.MODALITY.get(functionProto.flags) != Modality.ABSTRACT, - hasTypeParameterListBeforeFunctionName = functionProto.typeParameterList.isNotEmpty(), - mayHaveContract = functionProto.hasContract() + parent, + callableName.ref(), + isTopLevel, + c.containerFqName.child(callableName), + isExtension = functionProto.hasReceiver(), + hasBlockBody = true, + hasBody = Flags.MODALITY.get(functionProto.flags) != Modality.ABSTRACT, + hasTypeParameterListBeforeFunctionName = functionProto.typeParameterList.isNotEmpty(), + mayHaveContract = functionProto.hasContract() ) } } private class PropertyClsStubBuilder( - parent: StubElement, - outerContext: ClsStubBuilderContext, - protoContainer: ProtoContainer, - private val propertyProto: ProtoBuf.Property + parent: StubElement, + outerContext: ClsStubBuilderContext, + protoContainer: ProtoContainer, + private val propertyProto: ProtoBuf.Property ) : CallableClsStubBuilder(parent, outerContext, protoContainer, propertyProto.typeParameterList) { private val isVar = Flags.IS_VAR.get(propertyProto.flags) @@ -198,11 +188,9 @@ private class PropertyClsStubBuilder( get() = propertyProto.receiverType(c.typeTable) override val receiverAnnotations: List - get() { - return c.components.annotationLoader - .loadExtensionReceiverParameterAnnotations(protoContainer, propertyProto, AnnotatedCallableKind.PROPERTY_GETTER) - .map { ClassIdWithTarget(it, AnnotationUseSiteTarget.RECEIVER) } - } + get() = c.components.annotationLoader + .loadExtensionReceiverParameterAnnotations(protoContainer, propertyProto, AnnotatedCallableKind.PROPERTY_GETTER) + .map { ClassIdWithTarget(it, AnnotationUseSiteTarget.RECEIVER) } override val returnType: ProtoBuf.Type? get() = propertyProto.returnType(c.typeTable) @@ -215,8 +203,8 @@ private class PropertyClsStubBuilder( val modalityModifier = if (isTopLevel) listOf() else listOf(MODALITY) val modifierListStubImpl = createModifierListStubForDeclaration( - callableStub, propertyProto.flags, - listOf(VISIBILITY, LATEINIT, EXTERNAL_PROPERTY) + constModifier + modalityModifier + callableStub, propertyProto.flags, + listOf(VISIBILITY, LATEINIT, EXTERNAL_PROPERTY) + constModifier + modalityModifier ) val propertyAnnotations = @@ -236,25 +224,25 @@ private class PropertyClsStubBuilder( val callableName = c.nameResolver.getName(propertyProto.name) return KotlinPropertyStubImpl( - parent, - callableName.ref(), - isVar, - isTopLevel, - hasDelegate = false, - hasDelegateExpression = false, - hasInitializer = false, - isExtension = propertyProto.hasReceiver(), - hasReturnTypeRef = true, - fqName = c.containerFqName.child(callableName) + parent, + callableName.ref(), + isVar, + isTopLevel, + hasDelegate = false, + hasDelegateExpression = false, + hasInitializer = false, + isExtension = propertyProto.hasReceiver(), + hasReturnTypeRef = true, + fqName = c.containerFqName.child(callableName) ) } } private class ConstructorClsStubBuilder( - parent: StubElement, - outerContext: ClsStubBuilderContext, - protoContainer: ProtoContainer, - private val constructorProto: ProtoBuf.Constructor + parent: StubElement, + outerContext: ClsStubBuilderContext, + protoContainer: ProtoContainer, + private val constructorProto: ProtoBuf.Constructor ) : CallableClsStubBuilder(parent, outerContext, protoContainer, emptyList()) { override val receiverType: ProtoBuf.Type? get() = null @@ -273,7 +261,7 @@ private class ConstructorClsStubBuilder( val modifierListStubImpl = createModifierListStubForDeclaration(callableStub, constructorProto.flags, listOf(VISIBILITY)) val annotationIds = c.components.annotationLoader.loadCallableAnnotations( - protoContainer, constructorProto, AnnotatedCallableKind.FUNCTION + protoContainer, constructorProto, AnnotatedCallableKind.FUNCTION ) createAnnotationStubs(annotationIds, modifierListStubImpl) } diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/ClassClsStubBuilder.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/ClassClsStubBuilder.kt index d2f81ffe731..5e33587e154 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/ClassClsStubBuilder.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/ClassClsStubBuilder.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.decompiler.stubBuilder @@ -45,46 +34,47 @@ import org.jetbrains.kotlin.serialization.deserialization.getClassId import org.jetbrains.kotlin.serialization.deserialization.getName fun createClassStub( - parent: StubElement, - classProto: ProtoBuf.Class, - nameResolver: NameResolver, - classId: ClassId, - source: SourceElement?, - context: ClsStubBuilderContext + parent: StubElement, + classProto: ProtoBuf.Class, + nameResolver: NameResolver, + classId: ClassId, + source: SourceElement?, + context: ClsStubBuilderContext ) { ClassClsStubBuilder(parent, classProto, nameResolver, classId, source, context).build() } private class ClassClsStubBuilder( - private val parentStub: StubElement, - private val classProto: ProtoBuf.Class, - nameResolver: NameResolver, - private val classId: ClassId, - source: SourceElement?, - outerContext: ClsStubBuilderContext + private val parentStub: StubElement, + private val classProto: ProtoBuf.Class, + nameResolver: NameResolver, + private val classId: ClassId, + source: SourceElement?, + outerContext: ClsStubBuilderContext ) { private val thisAsProtoContainer = ProtoContainer.Class( - classProto, nameResolver, TypeTable(classProto.typeTable), source, outerContext.protoContainer + classProto, nameResolver, TypeTable(classProto.typeTable), source, outerContext.protoContainer ) private val classKind = thisAsProtoContainer.kind private val c = outerContext.child( - classProto.typeParameterList, classId.shortClassName, nameResolver, thisAsProtoContainer.typeTable, thisAsProtoContainer + classProto.typeParameterList, classId.shortClassName, nameResolver, thisAsProtoContainer.typeTable, thisAsProtoContainer ) private val typeStubBuilder = TypeClsStubBuilder(c) private val supertypeIds = run { val supertypeIds = classProto.supertypes(c.typeTable).map { c.nameResolver.getClassId(it.className) } //empty supertype list if single supertype is Any - if (supertypeIds.singleOrNull()?.let { KotlinBuiltIns.FQ_NAMES.any == it.asSingleFqName().toUnsafe() } ?: false) { + if (supertypeIds.singleOrNull()?.let { KotlinBuiltIns.FQ_NAMES.any == it.asSingleFqName().toUnsafe() } == true) { listOf() - } - else { + } else { supertypeIds } } - private val companionObjectName = - if (classProto.hasCompanionObjectName()) c.nameResolver.getName(classProto.companionObjectName) else null + private val companionObjectName = if (classProto.hasCompanionObjectName()) + c.nameResolver.getName(classProto.companionObjectName) + else + null private val classOrObjectStub = createClassOrObjectStubAndModifierListStub() @@ -134,24 +124,24 @@ private class ClassClsStubBuilder( return when (classKind) { ProtoBuf.Class.Kind.OBJECT, ProtoBuf.Class.Kind.COMPANION_OBJECT -> { KotlinObjectStubImpl( - parentStub, shortName, fqName, superTypeRefs, - isTopLevel = !classId.isNestedClass, - isDefault = isCompanionObject, - isLocal = false, - isObjectLiteral = false + parentStub, shortName, fqName, superTypeRefs, + isTopLevel = !classId.isNestedClass, + isDefault = isCompanionObject, + isLocal = false, + isObjectLiteral = false ) } else -> { KotlinClassStubImpl( - KtClassElementType.getStubType(classKind == ProtoBuf.Class.Kind.ENUM_ENTRY), - parentStub, - fqName.ref(), - shortName, - superTypeRefs, - isInterface = classKind == ProtoBuf.Class.Kind.INTERFACE, - isEnumEntry = classKind == ProtoBuf.Class.Kind.ENUM_ENTRY, - isLocal = false, - isTopLevel = !classId.isNestedClass + KtClassElementType.getStubType(classKind == ProtoBuf.Class.Kind.ENUM_ENTRY), + parentStub, + fqName.ref(), + shortName, + superTypeRefs, + isInterface = classKind == ProtoBuf.Class.Kind.INTERFACE, + isEnumEntry = classKind == ProtoBuf.Class.Kind.ENUM_ENTRY, + isLocal = false, + isTopLevel = !classId.isNestedClass ) } } @@ -169,12 +159,11 @@ private class ClassClsStubBuilder( // if single supertype is any then no delegation specifier list is needed if (supertypeIds.isEmpty()) return - val delegationSpecifierListStub = - KotlinPlaceHolderStubImpl(classOrObjectStub, KtStubElementTypes.SUPER_TYPE_LIST) + val delegationSpecifierListStub = KotlinPlaceHolderStubImpl(classOrObjectStub, KtStubElementTypes.SUPER_TYPE_LIST) classProto.supertypes(c.typeTable).forEach { type -> val superClassStub = KotlinPlaceHolderStubImpl( - delegationSpecifierListStub, KtStubElementTypes.SUPER_TYPE_ENTRY + delegationSpecifierListStub, KtStubElementTypes.SUPER_TYPE_ENTRY ) typeStubBuilder.createTypeReferenceStub(superClassStub, type) } @@ -204,15 +193,15 @@ private class ClassClsStubBuilder( val name = c.nameResolver.getName(entry.name) val annotations = c.components.annotationLoader.loadEnumEntryAnnotations(thisAsProtoContainer, entry) val enumEntryStub = KotlinClassStubImpl( - KtStubElementTypes.ENUM_ENTRY, - classBody, - qualifiedName = c.containerFqName.child(name).ref(), - name = name.ref(), - superNames = arrayOf(), - isInterface = false, - isEnumEntry = true, - isLocal = false, - isTopLevel = false + KtStubElementTypes.ENUM_ENTRY, + classBody, + qualifiedName = c.containerFqName.child(name).ref(), + name = name.ref(), + superNames = arrayOf(), + isInterface = false, + isEnumEntry = true, + isLocal = false, + isTopLevel = false ) if (annotations.isNotEmpty()) { createAnnotationStubs(annotations, createEmptyModifierListStub(enumEntryStub)) @@ -228,13 +217,14 @@ private class ClassClsStubBuilder( } createDeclarationsStubs( - classBody, c, thisAsProtoContainer, classProto.functionList, classProto.propertyList, classProto.typeAliasList) + classBody, c, thisAsProtoContainer, classProto.functionList, classProto.propertyList, classProto.typeAliasList + ) } private fun isClass(): Boolean { return classKind == ProtoBuf.Class.Kind.CLASS || - classKind == ProtoBuf.Class.Kind.ENUM_CLASS || - classKind == ProtoBuf.Class.Kind.ANNOTATION_CLASS + classKind == ProtoBuf.Class.Kind.ENUM_CLASS || + classKind == ProtoBuf.Class.Kind.ANNOTATION_CLASS } private fun createInnerAndNestedClasses(classBody: KotlinPlaceHolderStubImpl) { diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/ClsStubBuilderContext.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/ClsStubBuilderContext.kt index 3db6ffcd5a1..66aa0880a1c 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/ClsStubBuilderContext.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/ClsStubBuilderContext.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.decompiler.stubBuilder @@ -32,24 +21,23 @@ import org.jetbrains.kotlin.serialization.deserialization.getName data class ClassIdWithTarget(val classId: ClassId, val target: AnnotationUseSiteTarget?) class ClsStubBuilderComponents( - val classDataFinder: ClassDataFinder, - val annotationLoader: AnnotationAndConstantLoader, - val virtualFileForDebug: VirtualFile + val classDataFinder: ClassDataFinder, + val annotationLoader: AnnotationAndConstantLoader, + val virtualFileForDebug: VirtualFile ) { fun createContext( - nameResolver: NameResolver, - packageFqName: FqName, - typeTable: TypeTable - ): ClsStubBuilderContext { - return ClsStubBuilderContext(this, nameResolver, packageFqName, EmptyTypeParameters, typeTable, protoContainer = null) - } + nameResolver: NameResolver, + packageFqName: FqName, + typeTable: TypeTable + ): ClsStubBuilderContext = + ClsStubBuilderContext(this, nameResolver, packageFqName, EmptyTypeParameters, typeTable, protoContainer = null) } interface TypeParameters { operator fun get(id: Int): Name - fun child(nameResolver: NameResolver, innerTypeParameters: List) - = TypeParametersImpl(nameResolver, innerTypeParameters, parent = this) + fun child(nameResolver: NameResolver, innerTypeParameters: List) = + TypeParametersImpl(nameResolver, innerTypeParameters, parent = this) } object EmptyTypeParameters : TypeParameters { @@ -57,9 +45,9 @@ object EmptyTypeParameters : TypeParameters { } class TypeParametersImpl( - nameResolver: NameResolver, - typeParameterProtos: Collection, - private val parent: TypeParameters + nameResolver: NameResolver, + typeParameterProtos: Collection, + private val parent: TypeParameters ) : TypeParameters { private val typeParametersById = typeParameterProtos.map { Pair(it.id, nameResolver.getName(it.name)) }.toMap() @@ -67,27 +55,25 @@ class TypeParametersImpl( } class ClsStubBuilderContext( - val components: ClsStubBuilderComponents, - val nameResolver: NameResolver, - val containerFqName: FqName, - val typeParameters: TypeParameters, - val typeTable: TypeTable, - val protoContainer: ProtoContainer.Class? + val components: ClsStubBuilderComponents, + val nameResolver: NameResolver, + val containerFqName: FqName, + val typeParameters: TypeParameters, + val typeTable: TypeTable, + val protoContainer: ProtoContainer.Class? ) internal fun ClsStubBuilderContext.child( - typeParameterList: List, - name: Name? = null, - nameResolver: NameResolver = this.nameResolver, - typeTable: TypeTable = this.typeTable, - protoContainer: ProtoContainer.Class? = this.protoContainer -): ClsStubBuilderContext { - return ClsStubBuilderContext( - this.components, - nameResolver, - if (name != null) this.containerFqName.child(name) else this.containerFqName, - this.typeParameters.child(nameResolver, typeParameterList), - typeTable, - protoContainer - ) -} + typeParameterList: List, + name: Name? = null, + nameResolver: NameResolver = this.nameResolver, + typeTable: TypeTable = this.typeTable, + protoContainer: ProtoContainer.Class? = this.protoContainer +): ClsStubBuilderContext = ClsStubBuilderContext( + this.components, + nameResolver, + if (name != null) this.containerFqName.child(name) else this.containerFqName, + this.typeParameters.child(nameResolver, typeParameterList), + typeTable, + protoContainer +) diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/TypeClsStubBuilder.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/TypeClsStubBuilder.kt index 3c45d6b8908..f130c5ff350 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/TypeClsStubBuilder.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/TypeClsStubBuilder.kt @@ -1,5 +1,5 @@ /* - * Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -36,7 +36,11 @@ import java.util.* private val ANNOTATIONS_NOT_LOADED_FOR_TYPES = setOf(KotlinBuiltIns.FQ_NAMES.parameterName) class TypeClsStubBuilder(private val c: ClsStubBuilderContext) { - fun createTypeReferenceStub(parent: StubElement, type: Type, additionalAnnotations: () -> List = { emptyList() }) { + fun createTypeReferenceStub( + parent: StubElement, + type: Type, + additionalAnnotations: () -> List = { emptyList() } + ) { val abbreviatedType = type.abbreviatedType(c.typeTable) if (abbreviatedType != null) { return createTypeReferenceStub(parent, abbreviatedType, additionalAnnotations) @@ -64,9 +68,10 @@ class TypeClsStubBuilder(private val c: ClsStubBuilderContext) { } } - private fun nullableTypeParent(parent: KotlinStubBaseImpl<*>, type: Type): KotlinStubBaseImpl<*> = - if (type.nullable) KotlinPlaceHolderStubImpl(parent, KtStubElementTypes.NULLABLE_TYPE) - else parent + private fun nullableTypeParent(parent: KotlinStubBaseImpl<*>, type: Type): KotlinStubBaseImpl<*> = if (type.nullable) + KotlinPlaceHolderStubImpl(parent, KtStubElementTypes.NULLABLE_TYPE) + else + parent private fun createTypeParameterStub(parent: KotlinStubBaseImpl<*>, type: Type, name: Name, annotations: List) { createTypeAnnotationStubs(parent, type, annotations) @@ -88,11 +93,11 @@ class TypeClsStubBuilder(private val c: ClsStubBuilderContext) { } val classId = c.nameResolver.getClassId(if (type.hasClassName()) type.className else type.typeAliasName) - val shouldBuildAsFunctionType = isBuiltinFunctionClass(classId) - && type.argumentList.none { it.projection == Projection.STAR } + val shouldBuildAsFunctionType = isBuiltinFunctionClass(classId) && type.argumentList.none { it.projection == Projection.STAR } if (shouldBuildAsFunctionType) { - val (extensionAnnotations, notExtensionAnnotations) = - annotations.partition { it.classId.asSingleFqName() == KotlinBuiltIns.FQ_NAMES.extensionFunctionType } + val (extensionAnnotations, notExtensionAnnotations) = annotations.partition { + it.classId.asSingleFqName() == KotlinBuiltIns.FQ_NAMES.extensionFunctionType + } val isExtension = extensionAnnotations.isNotEmpty() val isSuspend = Flags.SUSPEND_TYPE.get(type.flags) @@ -101,8 +106,7 @@ class TypeClsStubBuilder(private val c: ClsStubBuilderContext) { val wrapper = nullableTypeParent(parent, type) createTypeAnnotationStubs(wrapper, type, notExtensionAnnotations) wrapper - } - else { + } else { createTypeAnnotationStubs(parent, type, notExtensionAnnotations) nullableTypeParent(parent, type) } @@ -116,8 +120,7 @@ class TypeClsStubBuilder(private val c: ClsStubBuilderContext) { val outerTypeChain = generateSequence(type) { it.outerType(c.typeTable) }.toList() - createStubForTypeName(classId, nullableTypeParent(parent, type)) { - userTypeStub, index -> + createStubForTypeName(classId, nullableTypeParent(parent, type)) { userTypeStub, index -> outerTypeChain.getOrNull(index)?.let { createTypeArgumentListStub(userTypeStub, it.argumentList) } } } @@ -165,19 +168,24 @@ class TypeClsStubBuilder(private val c: ClsStubBuilderContext) { Projection.STAR -> KtProjectionKind.STAR } - private fun createFunctionTypeStub(parent: StubElement, type: Type, isExtensionFunctionType: Boolean, isSuspend: Boolean) { + private fun createFunctionTypeStub( + parent: StubElement, + type: Type, + isExtensionFunctionType: Boolean, + isSuspend: Boolean + ) { val typeArgumentList = type.argumentList val functionType = KotlinPlaceHolderStubImpl(parent, KtStubElementTypes.FUNCTION_TYPE) if (isExtensionFunctionType) { - val functionTypeReceiverStub - = KotlinPlaceHolderStubImpl(functionType, KtStubElementTypes.FUNCTION_TYPE_RECEIVER) + val functionTypeReceiverStub = + KotlinPlaceHolderStubImpl(functionType, KtStubElementTypes.FUNCTION_TYPE_RECEIVER) val receiverTypeProto = typeArgumentList.first().type(c.typeTable)!! createTypeReferenceStub(functionTypeReceiverStub, receiverTypeProto) } val parameterList = KotlinPlaceHolderStubImpl(functionType, KtStubElementTypes.VALUE_PARAMETER_LIST) - val typeArgumentsWithoutReceiverAndReturnType - = typeArgumentList.subList(if (isExtensionFunctionType) 1 else 0, typeArgumentList.size - 1) + val typeArgumentsWithoutReceiverAndReturnType = + typeArgumentList.subList(if (isExtensionFunctionType) 1 else 0, typeArgumentList.size - 1) var suspendParameterType: Type? = null for ((index, argument) in typeArgumentsWithoutReceiverAndReturnType.withIndex()) { @@ -197,7 +205,7 @@ class TypeClsStubBuilder(private val c: ClsStubBuilderContext) { } } val parameter = KotlinParameterStubImpl( - parameterList, fqName = null, name = null, isMutable = false, hasValOrVar = false, hasDefaultValue = false + parameterList, fqName = null, name = null, isMutable = false, hasValOrVar = false, hasDefaultValue = false ) createTypeReferenceStub(parameter, argument.type(c.typeTable)!!) @@ -207,41 +215,46 @@ class TypeClsStubBuilder(private val c: ClsStubBuilderContext) { if (suspendParameterType == null) { val returnType = typeArgumentList.last().type(c.typeTable)!! createTypeReferenceStub(functionType, returnType) - } - else { + } else { val continuationArgumentType = suspendParameterType.getArgument(0).type(c.typeTable)!! createTypeReferenceStub(functionType, continuationArgumentType) } } fun createValueParameterListStub( - parent: StubElement, - callableProto: MessageLite, - parameters: List, - container: ProtoContainer + parent: StubElement, + callableProto: MessageLite, + parameters: List, + container: ProtoContainer ) { val parameterListStub = KotlinPlaceHolderStubImpl(parent, KtStubElementTypes.VALUE_PARAMETER_LIST) for ((index, valueParameterProto) in parameters.withIndex()) { val name = c.nameResolver.getName(valueParameterProto.name) val parameterStub = KotlinParameterStubImpl( - parameterListStub, - name = name.ref(), - fqName = null, - hasDefaultValue = false, - hasValOrVar = false, - isMutable = false + parameterListStub, + name = name.ref(), + fqName = null, + hasDefaultValue = false, + hasValOrVar = false, + isMutable = false ) val varargElementType = valueParameterProto.varargElementType(c.typeTable) val typeProto = varargElementType ?: valueParameterProto.type(c.typeTable) val modifiers = arrayListOf() - if (varargElementType != null) { modifiers.add(KtTokens.VARARG_KEYWORD) } - if (Flags.IS_CROSSINLINE.get(valueParameterProto.flags)) { modifiers.add(KtTokens.CROSSINLINE_KEYWORD) } - if (Flags.IS_NOINLINE.get(valueParameterProto.flags)) { modifiers.add(KtTokens.NOINLINE_KEYWORD) } + if (varargElementType != null) { + modifiers.add(KtTokens.VARARG_KEYWORD) + } + if (Flags.IS_CROSSINLINE.get(valueParameterProto.flags)) { + modifiers.add(KtTokens.CROSSINLINE_KEYWORD) + } + if (Flags.IS_NOINLINE.get(valueParameterProto.flags)) { + modifiers.add(KtTokens.NOINLINE_KEYWORD) + } val modifierList = createModifierListStub(parameterStub, modifiers) val parameterAnnotations = c.components.annotationLoader.loadValueParameterAnnotations( - container, callableProto, callableProto.annotatedCallableKind, index, valueParameterProto + container, callableProto, callableProto.annotatedCallableKind, index, valueParameterProto ) if (parameterAnnotations.isNotEmpty()) { createAnnotationStubs(parameterAnnotations, modifierList ?: createEmptyModifierListStub(parameterStub)) @@ -252,8 +265,8 @@ class TypeClsStubBuilder(private val c: ClsStubBuilderContext) { } fun createTypeParameterListStub( - parent: StubElement, - typeParameterProtoList: List + parent: StubElement, + typeParameterProtoList: List ): List> { if (typeParameterProtoList.isEmpty()) return listOf() @@ -262,10 +275,10 @@ class TypeClsStubBuilder(private val c: ClsStubBuilderContext) { for (proto in typeParameterProtoList) { val name = c.nameResolver.getName(proto.name) val typeParameterStub = KotlinTypeParameterStubImpl( - typeParameterListStub, - name = name.ref(), - isInVariance = proto.variance == Variance.IN, - isOutVariance = proto.variance == Variance.OUT + typeParameterListStub, + name = name.ref(), + isInVariance = proto.variance == Variance.IN, + isOutVariance = proto.variance == Variance.OUT ) createTypeParameterModifierListStub(typeParameterStub, proto) val upperBoundProtos = proto.upperBounds(c.typeTable) @@ -281,8 +294,8 @@ class TypeClsStubBuilder(private val c: ClsStubBuilderContext) { } fun createTypeConstraintListStub( - parent: StubElement, - protosForTypeConstraintList: List> + parent: StubElement, + protosForTypeConstraintList: List> ) { if (protosForTypeConstraintList.isEmpty()) { return @@ -296,15 +309,17 @@ class TypeClsStubBuilder(private val c: ClsStubBuilderContext) { } private fun createTypeParameterModifierListStub( - typeParameterStub: KotlinTypeParameterStubImpl, - typeParameterProto: ProtoBuf.TypeParameter + typeParameterStub: KotlinTypeParameterStubImpl, + typeParameterProto: ProtoBuf.TypeParameter ) { val modifiers = ArrayList() when (typeParameterProto.variance) { Variance.IN -> modifiers.add(KtTokens.IN_KEYWORD) Variance.OUT -> modifiers.add(KtTokens.OUT_KEYWORD) - Variance.INV -> { /* do nothing */ } - null -> { /* do nothing */ } + Variance.INV -> { /* do nothing */ + } + null -> { /* do nothing */ + } } if (typeParameterProto.reified) { modifiers.add(KtTokens.REIFIED_KEYWORD) @@ -315,14 +330,15 @@ class TypeClsStubBuilder(private val c: ClsStubBuilderContext) { val annotations = c.components.annotationLoader.loadTypeParameterAnnotations(typeParameterProto, c.nameResolver) if (annotations.isNotEmpty()) { createAnnotationStubs( - annotations, - modifierList ?: createEmptyModifierListStub(typeParameterStub)) + annotations, + modifierList ?: createEmptyModifierListStub(typeParameterStub) + ) } } private fun Type.isDefaultUpperBound(): Boolean { return this.hasClassName() && - c.nameResolver.getClassId(className).let { KotlinBuiltIns.FQ_NAMES.any == it.asSingleFqName().toUnsafe() } && - this.nullable + c.nameResolver.getClassId(className).let { KotlinBuiltIns.FQ_NAMES.any == it.asSingleFqName().toUnsafe() } && + this.nullable } } diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/clsStubBuilding.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/clsStubBuilding.kt index fc088d7d443..d1ad7d6c849 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/clsStubBuilding.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/clsStubBuilding.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.decompiler.stubBuilder @@ -43,11 +32,11 @@ import org.jetbrains.kotlin.serialization.deserialization.AnnotatedCallableKind import org.jetbrains.kotlin.serialization.deserialization.ProtoContainer fun createTopLevelClassStub( - classId: ClassId, - classProto: ProtoBuf.Class, - source: SourceElement?, - context: ClsStubBuilderContext, - isScript: Boolean + classId: ClassId, + classProto: ProtoBuf.Class, + source: SourceElement?, + context: ClsStubBuilderContext, + isScript: Boolean ): KotlinFileStubImpl { val fileStub = createFileStub(classId.packageFqName, isScript) createClassStub(fileStub, classProto, context.nameResolver, classId, source, context) @@ -55,21 +44,22 @@ fun createTopLevelClassStub( } fun createPackageFacadeStub( - packageProto: ProtoBuf.Package, - packageFqName: FqName, - c: ClsStubBuilderContext + packageProto: ProtoBuf.Package, + packageFqName: FqName, + c: ClsStubBuilderContext ): KotlinFileStubImpl { val fileStub = KotlinFileStubForIde.forFile(packageFqName, isScript = false) setupFileStub(fileStub, packageFqName) createDeclarationsStubs( - fileStub, c, ProtoContainer.Package(packageFqName, c.nameResolver, c.typeTable, source = null), packageProto) + fileStub, c, ProtoContainer.Package(packageFqName, c.nameResolver, c.typeTable, source = null), packageProto + ) return fileStub } fun createFileFacadeStub( - packageProto: ProtoBuf.Package, - facadeFqName: FqName, - c: ClsStubBuilderContext + packageProto: ProtoBuf.Package, + facadeFqName: FqName, + c: ClsStubBuilderContext ): KotlinFileStubImpl { val packageFqName = facadeFqName.parent() val fileStub = KotlinFileStubForIde.forFileFacadeStub(facadeFqName) @@ -83,10 +73,10 @@ fun createFileFacadeStub( } fun createMultifileClassStub( - header: KotlinClassHeader, - partFiles: List, - facadeFqName: FqName, - components: ClsStubBuilderComponents + header: KotlinClassHeader, + partFiles: List, + facadeFqName: FqName, + components: ClsStubBuilderComponents ): KotlinFileStubImpl { val packageFqName = facadeFqName.parent() val partNames = header.data?.asList()?.map { it.substringAfterLast('/') } @@ -143,15 +133,15 @@ fun createStubForPackageName(packageDirectiveStub: KotlinPlaceHolderStubImpl, - bindTypeArguments: (KotlinUserTypeStub, Int) -> Unit = { _, _ -> } + typeClassId: ClassId, + parent: StubElement, + bindTypeArguments: (KotlinUserTypeStub, Int) -> Unit = { _, _ -> } ): KotlinUserTypeStub { val substituteWithAny = typeClassId.isLocal - val fqName = - if (substituteWithAny) KotlinBuiltIns.FQ_NAMES.any - else typeClassId.asSingleFqName().toUnsafe() + val fqName = if (substituteWithAny) KotlinBuiltIns.FQ_NAMES.any + else typeClassId.asSingleFqName().toUnsafe() + val segments = fqName.pathSegments().asReversed() assert(segments.isNotEmpty()) @@ -172,10 +162,10 @@ fun createStubForTypeName( } fun createModifierListStubForDeclaration( - parent: StubElement, - flags: Int, - flagsToTranslate: List = listOf(), - additionalModifiers: List = listOf() + parent: StubElement, + flags: Int, + flagsToTranslate: List = listOf(), + additionalModifiers: List = listOf() ): KotlinModifierListStubImpl { assert(flagsToTranslate.isNotEmpty()) @@ -184,24 +174,24 @@ fun createModifierListStubForDeclaration( } fun createModifierListStub( - parent: StubElement, - modifiers: Collection + parent: StubElement, + modifiers: Collection ): KotlinModifierListStubImpl? { if (modifiers.isEmpty()) { return null } return KotlinModifierListStubImpl( - parent, - ModifierMaskUtils.computeMask { it in modifiers }, - KtStubElementTypes.MODIFIER_LIST + parent, + ModifierMaskUtils.computeMask { it in modifiers }, + KtStubElementTypes.MODIFIER_LIST ) } fun createEmptyModifierListStub(parent: KotlinStubBaseImpl<*>): KotlinModifierListStubImpl { return KotlinModifierListStubImpl( - parent, - ModifierMaskUtils.computeMask { false }, - KtStubElementTypes.MODIFIER_LIST + parent, + ModifierMaskUtils.computeMask { false }, + KtStubElementTypes.MODIFIER_LIST ) } @@ -210,34 +200,33 @@ fun createAnnotationStubs(annotationIds: List, parent: KotlinStubBaseIm } fun createTargetedAnnotationStubs( - annotationIds: List, - parent: KotlinStubBaseImpl<*> + annotationIds: List, + parent: KotlinStubBaseImpl<*> ) { if (annotationIds.isEmpty()) return annotationIds.forEach { annotation -> val (annotationClassId, target) = annotation val annotationEntryStubImpl = KotlinAnnotationEntryStubImpl( - parent, - shortName = annotationClassId.shortClassName.ref(), - hasValueArguments = false + parent, + shortName = annotationClassId.shortClassName.ref(), + hasValueArguments = false ) if (target != null) { KotlinAnnotationUseSiteTargetStubImpl(annotationEntryStubImpl, StringRef.fromString(target.name)!!) } - val constructorCallee = KotlinPlaceHolderStubImpl(annotationEntryStubImpl, KtStubElementTypes.CONSTRUCTOR_CALLEE) + val constructorCallee = + KotlinPlaceHolderStubImpl(annotationEntryStubImpl, KtStubElementTypes.CONSTRUCTOR_CALLEE) val typeReference = KotlinPlaceHolderStubImpl(constructorCallee, KtStubElementTypes.TYPE_REFERENCE) createStubForTypeName(annotationClassId, typeReference) } } val MessageLite.annotatedCallableKind: AnnotatedCallableKind - get() { - return when (this) { - is ProtoBuf.Property -> AnnotatedCallableKind.PROPERTY - is ProtoBuf.Function, is ProtoBuf.Constructor -> AnnotatedCallableKind.FUNCTION - else -> throw IllegalStateException("Unsupported message: $this") - } + get() = when (this) { + is ProtoBuf.Property -> AnnotatedCallableKind.PROPERTY + is ProtoBuf.Function, is ProtoBuf.Constructor -> AnnotatedCallableKind.FUNCTION + else -> throw IllegalStateException("Unsupported message: $this") } fun Name.ref() = StringRef.fromString(this.asString())!! diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/flags/flags.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/flags/flags.kt index c842f7917aa..39cc268279e 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/flags/flags.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/flags/flags.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.decompiler.stubBuilder.flags @@ -66,12 +55,12 @@ val TAILREC = createBooleanFlagToModifier(Flags.IS_TAILREC, KtTokens.TAILREC_KEY val SUSPEND = createBooleanFlagToModifier(Flags.IS_SUSPEND, KtTokens.SUSPEND_KEYWORD) private fun createBooleanFlagToModifier( - flagField: Flags.BooleanFlagField, ktModifierKeywordToken: KtModifierKeywordToken + flagField: Flags.BooleanFlagField, ktModifierKeywordToken: KtModifierKeywordToken ): FlagsToModifiers = BooleanFlagToModifier(flagField, ktModifierKeywordToken) private class BooleanFlagToModifier( - private val flagField: Flags.BooleanFlagField, - private val ktModifierKeywordToken: KtModifierKeywordToken + private val flagField: Flags.BooleanFlagField, + private val ktModifierKeywordToken: KtModifierKeywordToken ) : FlagsToModifiers() { override fun getModifiers(flags: Int): KtModifierKeywordToken? = if (flagField.get(flags)) ktModifierKeywordToken else null } diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/typeAliasClsStubBuilding.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/typeAliasClsStubBuilding.kt index c2a0ed1356d..7f901610d6d 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/typeAliasClsStubBuilding.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/stubBuilder/typeAliasClsStubBuilding.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.decompiler.stubBuilder @@ -21,18 +10,18 @@ import com.intellij.psi.stubs.StubElement import org.jetbrains.kotlin.idea.decompiler.stubBuilder.flags.VISIBILITY import org.jetbrains.kotlin.metadata.ProtoBuf import org.jetbrains.kotlin.metadata.deserialization.Flags +import org.jetbrains.kotlin.metadata.deserialization.underlyingType import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.psi.stubs.impl.KotlinTypeAliasStubImpl import org.jetbrains.kotlin.serialization.deserialization.ProtoContainer import org.jetbrains.kotlin.serialization.deserialization.getClassId import org.jetbrains.kotlin.serialization.deserialization.getName -import org.jetbrains.kotlin.metadata.deserialization.underlyingType fun createTypeAliasStub( - parent: StubElement, - typeAliasProto: ProtoBuf.TypeAlias, - protoContainer: ProtoContainer, - context: ClsStubBuilderContext + parent: StubElement, + typeAliasProto: ProtoBuf.TypeAlias, + protoContainer: ProtoContainer, + context: ClsStubBuilderContext ) { val shortName = context.nameResolver.getName(typeAliasProto.name) @@ -41,10 +30,10 @@ fun createTypeAliasStub( is ProtoContainer.Package -> ClassId.topLevel(protoContainer.fqName.child(shortName)) } - val typeAlias = - KotlinTypeAliasStubImpl( - parent, classId.shortClassName.ref(), classId.asSingleFqName().ref(), - isTopLevel = !classId.isNestedClass) + val typeAlias = KotlinTypeAliasStubImpl( + parent, classId.shortClassName.ref(), classId.asSingleFqName().ref(), + isTopLevel = !classId.isNestedClass + ) val modifierList = createModifierListStubForDeclaration(typeAlias, typeAliasProto.flags, arrayListOf(VISIBILITY), listOf()) diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/textBuilder/DecompiledText.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/textBuilder/DecompiledText.kt index e3452ba32ad..aca146c19a4 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/textBuilder/DecompiledText.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/textBuilder/DecompiledText.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.decompiler.textBuilder @@ -22,7 +11,7 @@ import org.jetbrains.kotlin.utils.keysToMap data class DecompiledText(val text: String, val index: DecompiledTextIndex) -interface DecompiledTextIndexer { +interface DecompiledTextIndexer { fun indexDescriptor(descriptor: DeclarationDescriptor): Collection } @@ -33,16 +22,14 @@ class DecompiledTextIndex(private val indexers: Collection - val correspondingMap = indexerToMap[mapper]!! + val correspondingMap = indexerToMap.getValue(mapper) mapper.indexDescriptor(descriptor).forEach { key -> correspondingMap[key] = textRange } } } - fun getRange(mapper: DecompiledTextIndexer, key: T): TextRange? { - return indexerToMap[mapper]?.get(key) - } + fun getRange(mapper: DecompiledTextIndexer, key: T): TextRange? = indexerToMap[mapper]?.get(key) companion object { val Empty = DecompiledTextIndex(listOf()) diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/textBuilder/DeserializerForDecompilerBase.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/textBuilder/DeserializerForDecompilerBase.kt index 7534cfff79d..579d0d43652 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/textBuilder/DeserializerForDecompilerBase.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/textBuilder/DeserializerForDecompilerBase.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.decompiler.textBuilder @@ -52,7 +41,7 @@ abstract class DeserializerForDecompilerBase(val directoryPackageFqName: FqName) override fun resolveTopLevelClass(classId: ClassId) = deserializationComponents.deserializeClass(classId) protected fun createDummyPackageFragment(fqName: FqName): MutablePackageFragmentDescriptor = - MutablePackageFragmentDescriptor(moduleDescriptor, fqName) + MutablePackageFragmentDescriptor(moduleDescriptor, fqName) private fun createDummyModule(name: String) = ModuleDescriptorImpl(Name.special("<$name>"), storageManager, builtIns) diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/textBuilder/buildDecompiledText.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/textBuilder/buildDecompiledText.kt index a50e18fbb1f..dc585353333 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/textBuilder/buildDecompiledText.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/decompiler/textBuilder/buildDecompiledText.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.decompiler.textBuilder @@ -29,10 +18,10 @@ import org.jetbrains.kotlin.resolve.DescriptorUtils.isEnumEntry import org.jetbrains.kotlin.resolve.descriptorUtil.secondaryConstructors import org.jetbrains.kotlin.types.isFlexible -private val DECOMPILED_CODE_COMMENT = "/* compiled code */" -private val DECOMPILED_COMMENT_FOR_PARAMETER = "/* = compiled code */" -private val FLEXIBLE_TYPE_COMMENT = "/* platform type */" -private val DECOMPILED_CONTRACT_STUB = "contract { /* compiled contract */ }" +private const val DECOMPILED_CODE_COMMENT = "/* compiled code */" +private const val DECOMPILED_COMMENT_FOR_PARAMETER = "/* = compiled code */" +private const val FLEXIBLE_TYPE_COMMENT = "/* platform type */" +private const val DECOMPILED_CONTRACT_STUB = "contract { /* compiled contract */ }" fun DescriptorRendererOptions.defaultDecompilerRendererOptions() { withDefinedIn = false @@ -45,10 +34,10 @@ fun DescriptorRendererOptions.defaultDecompilerRendererOptions() { } fun buildDecompiledText( - packageFqName: FqName, - descriptors: List, - descriptorRenderer: DescriptorRenderer, - indexers: Collection> = listOf(ByDescriptorIndexer) + packageFqName: FqName, + descriptors: List, + descriptorRenderer: DescriptorRenderer, + indexers: Collection> = listOf(ByDescriptorIndexer) ): DecompiledText { val builder = StringBuilder() @@ -75,8 +64,7 @@ fun buildDecompiledText( } builder.append(descriptor.name.asString()) builder.append(if (lastEnumEntry!!) ";" else ",") - } - else { + } else { builder.append(descriptorRenderer.render(descriptor).replace("= ...", DECOMPILED_COMMENT_FOR_PARAMETER)) } var endOffset = builder.length @@ -98,25 +86,22 @@ fun buildDecompiledText( } append(DECOMPILED_CODE_COMMENT).append(" }") } - } - else { + } else { // descriptor instanceof PropertyDescriptor builder.append(" ").append(DECOMPILED_CODE_COMMENT) } endOffset = builder.length } - } - else if (descriptor is ClassDescriptor && !isEnumEntry(descriptor)) { + } else if (descriptor is ClassDescriptor && !isEnumEntry(descriptor)) { builder.append(" {\n") - val subindent = indent + " " + val subindent = "$indent " var firstPassed = false fun newlineExceptFirst() { if (firstPassed) { builder.append("\n") - } - else { + } else { firstPassed = true } } @@ -147,7 +132,8 @@ fun buildDecompiledText( if (member is CallableMemberDescriptor && member.kind != CallableMemberDescriptor.Kind.DECLARATION //TODO: not synthesized and component like - && !DataClassDescriptorResolver.isComponentLike(member.name)) { + && !DataClassDescriptorResolver.isComponentLike(member.name) + ) { continue } newlineExceptFirst() diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/facet/KotlinVersionInfoProvider.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/facet/KotlinVersionInfoProvider.kt index d5535b305ce..f9c1bac3b16 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/facet/KotlinVersionInfoProvider.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/facet/KotlinVersionInfoProvider.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.facet @@ -20,11 +9,13 @@ import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.module.Module import com.intellij.openapi.roots.ModuleRootModel import com.intellij.util.text.VersionComparatorUtil -import org.jetbrains.kotlin.config.* -import org.jetbrains.kotlin.platform.IdePlatformKind -import org.jetbrains.kotlin.platform.orDefault +import org.jetbrains.kotlin.config.ApiVersion +import org.jetbrains.kotlin.config.KotlinFacetSettingsProvider +import org.jetbrains.kotlin.config.LanguageVersion import org.jetbrains.kotlin.config.VersionView +import org.jetbrains.kotlin.platform.IdePlatformKind import org.jetbrains.kotlin.platform.idePlatformKind +import org.jetbrains.kotlin.platform.orDefault interface KotlinVersionInfoProvider { companion object { @@ -43,18 +34,16 @@ fun getRuntimeLibraryVersions( module: Module, rootModel: ModuleRootModel?, platformKind: IdePlatformKind<*> -): Collection { - return KotlinVersionInfoProvider.EP_NAME - .extensions - .map { it.getLibraryVersions(module, platformKind, rootModel) } - .firstOrNull { it.isNotEmpty() } ?: emptyList() -} +): Collection = KotlinVersionInfoProvider.EP_NAME + .extensions + .map { it.getLibraryVersions(module, platformKind, rootModel) } + .firstOrNull { it.isNotEmpty() } ?: emptyList() fun getLibraryLanguageLevel( - module: Module, - rootModel: ModuleRootModel?, - platformKind: IdePlatformKind<*>?, - coerceRuntimeLibraryVersionToReleased: Boolean = true + module: Module, + rootModel: ModuleRootModel?, + platformKind: IdePlatformKind<*>?, + coerceRuntimeLibraryVersionToReleased: Boolean = true ): LanguageVersion { val minVersion = getRuntimeLibraryVersions(module, rootModel, platformKind.orDefault()) .addReleaseVersionIfNecessary(coerceRuntimeLibraryVersionToReleased) diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/findUsages/UsageTypeUtils.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/findUsages/UsageTypeUtils.kt index 278fcfc3eae..c47830f5d00 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/findUsages/UsageTypeUtils.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/findUsages/UsageTypeUtils.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.findUsages @@ -44,14 +33,10 @@ object UsageTypeUtils { val context = refExpr.analyze(BodyResolveMode.PARTIAL) - fun getCommonUsageType(): UsageTypeEnum? { - return when { - refExpr.getNonStrictParentOfType() != null -> - CLASS_IMPORT - refExpr.getParentOfTypeAndBranch(){ callableReference } != null -> - CALLABLE_REFERENCE - else -> null - } + fun getCommonUsageType(): UsageTypeEnum? = when { + refExpr.getNonStrictParentOfType() != null -> CLASS_IMPORT + refExpr.getParentOfTypeAndBranch() { callableReference } != null -> CALLABLE_REFERENCE + else -> null } fun getClassUsageType(): UsageTypeEnum? { @@ -79,26 +64,18 @@ object UsageTypeUtils { } return when { - refExpr.getParentOfTypeAndBranch(){ extendsBound } != null - || refExpr.getParentOfTypeAndBranch(){ boundTypeReference } != null -> - TYPE_CONSTRAINT + refExpr.getParentOfTypeAndBranch() { extendsBound } != null || refExpr.getParentOfTypeAndBranch() { boundTypeReference } != null -> TYPE_CONSTRAINT - refExpr is KtSuperTypeListEntry - || refExpr.getParentOfTypeAndBranch(){ typeReference } != null -> - SUPER_TYPE + refExpr is KtSuperTypeListEntry || refExpr.getParentOfTypeAndBranch() { typeReference } != null -> SUPER_TYPE - refExpr.getParentOfTypeAndBranch(){ typeReference } != null -> - VALUE_PARAMETER_TYPE + refExpr.getParentOfTypeAndBranch() { typeReference } != null -> VALUE_PARAMETER_TYPE - refExpr.getParentOfTypeAndBranch(){ typeReference } != null - || refExpr.getParentOfTypeAndBranch(){ typeReference } != null -> - IS + refExpr.getParentOfTypeAndBranch() { typeReference } != null || refExpr.getParentOfTypeAndBranch() { typeReference } != null -> IS - with(refExpr.getParentOfTypeAndBranch(){ right }) { + with(refExpr.getParentOfTypeAndBranch() { right }) { val opType = this?.operationReference?.getReferencedNameElementType() opType == KtTokens.AS_KEYWORD || opType == KtTokens.AS_SAFE - } -> - CLASS_CAST_TO + } -> CLASS_CAST_TO with(refExpr.getNonStrictParentOfType()) { when { @@ -110,26 +87,21 @@ object UsageTypeUtils { } else -> { selectorExpression == refExpr - && getParentOfTypeAndBranch(strict = true) { receiverExpression } != null + && getParentOfTypeAndBranch(strict = true) { receiverExpression } != null } } - } -> - CLASS_OBJECT_ACCESS + } -> CLASS_OBJECT_ACCESS - refExpr.getParentOfTypeAndBranch(){ superTypeQualifier } != null -> - SUPER_TYPE_QUALIFIER + refExpr.getParentOfTypeAndBranch() { superTypeQualifier } != null -> SUPER_TYPE_QUALIFIER - refExpr.getParentOfTypeAndBranch { getTypeReference() } != null -> - TYPE_ALIAS + refExpr.getParentOfTypeAndBranch { getTypeReference() } != null -> TYPE_ALIAS else -> null } } fun getVariableUsageType(): UsageTypeEnum? { - if (refExpr.getParentOfTypeAndBranch(){ delegateExpression } != null) { - return DELEGATE - } + if (refExpr.getParentOfTypeAndBranch() { delegateExpression } != null) return DELEGATE if (refExpr.parent is KtValueArgumentName) return NAMED_ARGUMENT @@ -165,43 +137,32 @@ object UsageTypeUtils { } return when { - refExpr.getParentOfTypeAndBranch(){ typeReference } != null -> - SUPER_TYPE + refExpr.getParentOfTypeAndBranch() { typeReference } != null -> SUPER_TYPE - descriptor is ConstructorDescriptor - && refExpr.getParentOfTypeAndBranch(){ typeReference } != null -> - ANNOTATION + descriptor is ConstructorDescriptor && refExpr.getParentOfTypeAndBranch() { typeReference } != null -> ANNOTATION - with(refExpr.getParentOfTypeAndBranch(){ calleeExpression }) { + with(refExpr.getParentOfTypeAndBranch() { calleeExpression }) { this?.calleeExpression is KtSimpleNameExpression - } -> - if (descriptor is ConstructorDescriptor) CLASS_NEW_OPERATOR else FUNCTION_CALL + } -> if (descriptor is ConstructorDescriptor) CLASS_NEW_OPERATOR else FUNCTION_CALL - refExpr.getParentOfTypeAndBranch(){ operationReference } != null || - refExpr.getParentOfTypeAndBranch(){ operationReference } != null || - refExpr.getParentOfTypeAndBranch(){ operationReference } != null -> - FUNCTION_CALL + refExpr.getParentOfTypeAndBranch() { operationReference } != null || refExpr.getParentOfTypeAndBranch() { operationReference } != null || refExpr.getParentOfTypeAndBranch() { operationReference } != null -> FUNCTION_CALL else -> null } } - fun getPackageUsageType(): UsageTypeEnum? { - return when { - refExpr.getNonStrictParentOfType() != null -> PACKAGE_DIRECTIVE - refExpr.getNonStrictParentOfType() != null -> PACKAGE_MEMBER_ACCESS - else -> getClassUsageType() - } + fun getPackageUsageType(): UsageTypeEnum? = when { + refExpr.getNonStrictParentOfType() != null -> PACKAGE_DIRECTIVE + refExpr.getNonStrictParentOfType() != null -> PACKAGE_MEMBER_ACCESS + else -> getClassUsageType() } val usageType = getCommonUsageType() if (usageType != null) return usageType - val descriptor = context[BindingContext.REFERENCE_TARGET, refExpr] - - return when (descriptor) { + return when (val descriptor = context[BindingContext.REFERENCE_TARGET, refExpr]) { is ClassifierDescriptor -> when { - // Treat object accesses as variables to simulate the old behaviour (when variables were created for objects) + // Treat object accesses as variables to simulate the old behaviour (when variables were created for objects) DescriptorUtils.isNonCompanionObject(descriptor) || DescriptorUtils.isEnumEntry(descriptor) -> getVariableUsageType() DescriptorUtils.isCompanionObject(descriptor) -> COMPANION_OBJECT_ACCESS else -> getClassUsageType() diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/framework/CommonLibraryType.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/framework/CommonLibraryType.kt index 846dd975612..2b351446871 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/framework/CommonLibraryType.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/framework/CommonLibraryType.kt @@ -1,5 +1,5 @@ /* - * Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -19,9 +19,11 @@ object CommonLibraryType : LibraryType(CommonLibraryKind override fun getCreateActionName() = null - override fun createNewLibrary(parentComponent: JComponent, - contextDirectory: VirtualFile?, - project: Project): NewLibraryConfiguration? = null + override fun createNewLibrary( + parentComponent: JComponent, + contextDirectory: VirtualFile?, + project: Project + ): NewLibraryConfiguration? = null override fun getIcon(properties: DummyLibraryProperties?) = KotlinIcons.MPP } diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/framework/JsLibraryStdDetectionUtil.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/framework/JsLibraryStdDetectionUtil.kt index ae5b88639ad..ad95caf596a 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/framework/JsLibraryStdDetectionUtil.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/framework/JsLibraryStdDetectionUtil.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.framework @@ -28,7 +17,6 @@ import com.intellij.openapi.vfs.VirtualFile import org.jetbrains.kotlin.utils.LibraryUtils import org.jetbrains.kotlin.utils.PathUtil import java.io.File -import java.util.* import java.util.jar.Attributes object JsLibraryStdDetectionUtil { @@ -56,7 +44,8 @@ object JsLibraryStdDetectionUtil { val name = root.url.substringBefore("!/").substringAfterLast('/') if (name == PathUtil.JS_LIB_JAR_NAME || name == PathUtil.JS_LIB_10_JAR_NAME || PathUtil.KOTLIN_STDLIB_JS_JAR_PATTERN.matcher(name).matches() || - PathUtil.KOTLIN_JS_LIBRARY_JAR_PATTERN.matcher(name).matches()) { + PathUtil.KOTLIN_JS_LIBRARY_JAR_PATTERN.matcher(name).matches() + ) { val jar = VfsUtilCore.getVirtualFileForJar(root) ?: continue var isJSStdLib = jar.getUserData(IS_JS_LIBRARY_STD_LIB) diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/BeforeResolveHighlightingVisitor.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/BeforeResolveHighlightingVisitor.kt index d88b30117de..2f14b5c1ff3 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/BeforeResolveHighlightingVisitor.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/BeforeResolveHighlightingVisitor.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.highlighter @@ -82,7 +71,8 @@ internal class BeforeResolveHighlightingVisitor(holder: AnnotationHolder) : High override fun visitArgument(argument: KtValueArgument) { val argumentName = argument.getArgumentName() ?: return val eq = argument.equalsToken ?: return - createInfoAnnotation(TextRange(argumentName.startOffset, eq.endOffset), null).textAttributes = KotlinHighlightingColors.NAMED_ARGUMENT + createInfoAnnotation(TextRange(argumentName.startOffset, eq.endOffset), null).textAttributes = + KotlinHighlightingColors.NAMED_ARGUMENT } override fun visitExpressionWithLabel(expression: KtExpressionWithLabel) { diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/DebugInfoAnnotator.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/DebugInfoAnnotator.kt index 6c65cb92e73..cae41ef0d0a 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/DebugInfoAnnotator.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/DebugInfoAnnotator.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.highlighter @@ -45,7 +34,7 @@ class DebugInfoAnnotator : Annotator { DebugInfoUtil.markDebugAnnotations(element, bindingContext, object : DebugInfoUtil.DebugInfoReporter() { override fun reportElementWithErrorType(expression: KtReferenceExpression) { holder.createErrorAnnotation(expression, "[DEBUG] Resolved to error element").textAttributes = - KotlinHighlightingColors.RESOLVED_TO_ERROR + KotlinHighlightingColors.RESOLVED_TO_ERROR } override fun reportMissingUnresolved(expression: KtReferenceExpression) { @@ -56,9 +45,8 @@ class DebugInfoAnnotator : Annotator { } override fun reportUnresolvedWithTarget(expression: KtReferenceExpression, target: String) { - holder.createErrorAnnotation(expression, "[DEBUG] Reference marked as unresolved is actually resolved to " + target) - .textAttributes = - KotlinHighlightingColors.DEBUG_INFO + holder.createErrorAnnotation(expression, "[DEBUG] Reference marked as unresolved is actually resolved to $target") + .textAttributes = KotlinHighlightingColors.DEBUG_INFO } }) } catch (e: ProcessCanceledException) { @@ -74,6 +62,7 @@ class DebugInfoAnnotator : Annotator { companion object { val isDebugInfoEnabled: Boolean - get() = ApplicationManager.getApplication().isInternal && (KotlinPluginUtil.isSnapshotVersion() || KotlinPluginUtil.isDevVersion()) + get() = ApplicationManager.getApplication() + .isInternal && (KotlinPluginUtil.isSnapshotVersion() || KotlinPluginUtil.isDevVersion()) } } diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/FunctionsHighlightingVisitor.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/FunctionsHighlightingVisitor.kt index 15c6b179039..2b4f147e7ff 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/FunctionsHighlightingVisitor.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/FunctionsHighlightingVisitor.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.highlighter @@ -37,7 +26,7 @@ import org.jetbrains.kotlin.serialization.deserialization.KOTLIN_SUSPEND_BUILT_I import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult internal class FunctionsHighlightingVisitor(holder: AnnotationHolder, bindingContext: BindingContext) : - AfterAnalysisHighlightingVisitor(holder, bindingContext) { + AfterAnalysisHighlightingVisitor(holder, bindingContext) { override fun visitNamedFunction(function: KtNamedFunction) { function.nameIdentifier?.let { highlightName(it, FUNCTION_DECLARATION) } diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/HighlighterExtension.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/HighlighterExtension.kt index 06375492163..b7f2f0dc4c7 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/HighlighterExtension.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/HighlighterExtension.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.highlighter @@ -25,8 +14,8 @@ import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall abstract class HighlighterExtension { abstract fun highlightDeclaration(elementToHighlight: PsiElement, descriptor: DeclarationDescriptor): TextAttributesKey? - open fun highlightCall(elementToHighlight: PsiElement, resolvedCall: ResolvedCall<*>): TextAttributesKey? - = highlightDeclaration(elementToHighlight, resolvedCall.resultingDescriptor) + open fun highlightCall(elementToHighlight: PsiElement, resolvedCall: ResolvedCall<*>): TextAttributesKey? = + highlightDeclaration(elementToHighlight, resolvedCall.resultingDescriptor) companion object { val EP_NAME = ExtensionPointName.create("org.jetbrains.kotlin.highlighterExtension") diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/IdeRenderers.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/IdeRenderers.kt index df13139940f..c2935a337bf 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/IdeRenderers.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/IdeRenderers.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.highlighter @@ -40,7 +29,7 @@ object IdeRenderers { @JvmField val HTML_RENDER_TYPE = SmartTypeRenderer(DescriptorRenderer.HTML.withOptions { parameterNamesInFunctionalTypes = false - modifiers = DescriptorRendererModifier.ALL_EXCEPT_ANNOTATIONS + modifiers = DescriptorRendererModifier.ALL_EXCEPT_ANNOTATIONS }) @JvmField @@ -86,7 +75,8 @@ object IdeRenderers { val context = RenderingContext.of(descriptors) val conflicts = descriptors.joinToString("") { "
  • " + HTML.render(it, context) + "
  • \n" } - "The following declarations have the same JVM signature (${data.signature.name}${data.signature.desc}):
    \n
      \n$conflicts
    " + "The following declarations have the same JVM signature (${data.signature.name}${data.signature + .desc}):
    \n
      \n$conflicts
    " } @JvmField @@ -98,8 +88,12 @@ object IdeRenderers { val HTML = DescriptorRenderer.HTML.withOptions { modifiers = DescriptorRendererModifier.ALL_EXCEPT_ANNOTATIONS }.asRenderer() - @JvmField val HTML_WITH_ANNOTATIONS = DescriptorRenderer.HTML.withOptions { + + @JvmField + val HTML_WITH_ANNOTATIONS = DescriptorRenderer.HTML.withOptions { modifiers = DescriptorRendererModifier.ALL }.asRenderer() - @JvmField val HTML_WITH_ANNOTATIONS_WHITELIST = DescriptorRenderer.HTML.withAnnotationsWhitelist() + + @JvmField + val HTML_WITH_ANNOTATIONS_WHITELIST = DescriptorRenderer.HTML.withAnnotationsWhitelist() } diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/KotlinBeforeResolveHighlightingPass.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/KotlinBeforeResolveHighlightingPass.kt index 6c886f8b315..ffa13718fe9 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/KotlinBeforeResolveHighlightingPass.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/KotlinBeforeResolveHighlightingPass.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.highlighter @@ -35,16 +24,17 @@ import com.intellij.psi.PsiRecursiveElementVisitor import org.jetbrains.kotlin.psi.KtFile class KotlinBeforeResolveHighlightingPass( - private val file: KtFile, - document: Document + private val file: KtFile, + document: Document ) : TextEditorHighlightingPass(file.project, document), DumbAware { - @Volatile private var annotationHolder: AnnotationHolderImpl? = null + @Volatile + private var annotationHolder: AnnotationHolderImpl? = null override fun doCollectInformation(progress: ProgressIndicator) { val annotationHolder = AnnotationHolderImpl(AnnotationSession(file)) val visitor = BeforeResolveHighlightingVisitor(annotationHolder) - file.accept(object : PsiRecursiveElementVisitor(){ + file.accept(object : PsiRecursiveElementVisitor() { override fun visitElement(element: PsiElement) { super.visitElement(element) element.accept(visitor) @@ -64,7 +54,13 @@ class KotlinBeforeResolveHighlightingPass( class Factory(registrar: TextEditorHighlightingPassRegistrar) : ProjectComponent, TextEditorHighlightingPassFactory { init { - registrar.registerTextEditorHighlightingPass(this, TextEditorHighlightingPassRegistrar.Anchor.BEFORE, Pass.UPDATE_FOLDING, false, false) + registrar.registerTextEditorHighlightingPass( + this, + TextEditorHighlightingPassRegistrar.Anchor.BEFORE, + Pass.UPDATE_FOLDING, + false, + false + ) } override fun createHighlightingPass(file: PsiFile, editor: Editor): TextEditorHighlightingPass? { diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/KotlinSuppressableWarningProblemGroup.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/KotlinSuppressableWarningProblemGroup.kt index 018ef971ed6..0c1d3ead38d 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/KotlinSuppressableWarningProblemGroup.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/KotlinSuppressableWarningProblemGroup.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.highlighter @@ -28,11 +17,11 @@ import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import java.util.* class KotlinSuppressableWarningProblemGroup( - private val diagnosticFactory: DiagnosticFactory<*> + private val diagnosticFactory: DiagnosticFactory<*> ) : SuppressableProblemGroup { init { - assert (diagnosticFactory.severity == Severity.WARNING) + assert(diagnosticFactory.severity == Severity.WARNING) } override fun getProblemName() = diagnosticFactory.name @@ -47,7 +36,7 @@ class KotlinSuppressableWarningProblemGroup( } fun createSuppressWarningActions(element: PsiElement, diagnosticFactory: DiagnosticFactory<*>): List = - createSuppressWarningActions(element, diagnosticFactory.severity, diagnosticFactory.name) + createSuppressWarningActions(element, diagnosticFactory.severity, diagnosticFactory.name) fun createSuppressWarningActions(element: PsiElement, severity: Severity, suppressionKey: String): List { @@ -71,15 +60,17 @@ fun createSuppressWarningActions(element: PsiElement, severity: Severity, suppre // Add suppress action at first statement if (current.parent is KtBlockExpression || current.parent is KtDestructuringDeclaration) { val kind = if (current.parent is KtBlockExpression) "statement" else "initializer" - actions.add(KotlinSuppressIntentionAction(current, suppressionKey, - AnnotationHostKind(kind, "", true))) + actions.add( + KotlinSuppressIntentionAction(current, suppressionKey, AnnotationHostKind(kind, "", true)) + ) suppressAtStatementAllowed = false } } current is KtFile -> { - actions.add(KotlinSuppressIntentionAction(current, suppressionKey, - AnnotationHostKind("file", current.name, true))) + actions.add( + KotlinSuppressIntentionAction(current, suppressionKey, AnnotationHostKind("file", current.name, true)) + ) suppressAtStatementAllowed = false } } @@ -101,8 +92,8 @@ private object DeclarationKindDetector : KtVisitor() override fun visitProperty(d: KtProperty, data: Unit?) = detect(d, d.valOrVarKeyword.text!!) - override fun visitDestructuringDeclaration(d: KtDestructuringDeclaration, data: Unit?) = detect(d, d.valOrVarKeyword?.text ?: "val", - name = d.entries.joinToString(", ", "(", ")") { it.name!! }) + override fun visitDestructuringDeclaration(d: KtDestructuringDeclaration, data: Unit?) = + detect(d, d.valOrVarKeyword?.text ?: "val", name = d.entries.joinToString(", ", "(", ")") { it.name!! }) override fun visitTypeParameter(d: KtTypeParameter, data: Unit?) = detect(d, "type parameter", newLineNeeded = false) @@ -110,7 +101,8 @@ private object DeclarationKindDetector : KtVisitor() override fun visitParameter(d: KtParameter, data: Unit?) = detect(d, "parameter", newLineNeeded = false) - override fun visitSecondaryConstructor(constructor: KtSecondaryConstructor, data: Unit?) = detect(constructor, "secondary constructor of") + override fun visitSecondaryConstructor(constructor: KtSecondaryConstructor, data: Unit?) = + detect(constructor, "secondary constructor of") override fun visitObjectDeclaration(d: KtObjectDeclaration, data: Unit?): AnnotationHostKind? { if (d.isCompanion()) return detect(d, "companion object", name = "${d.name} of ${d.getStrictParentOfType()?.name}") @@ -118,6 +110,10 @@ private object DeclarationKindDetector : KtVisitor() return detect(d, "object") } - private fun detect(declaration: KtDeclaration, kind: String, name: String = declaration.name ?: "", newLineNeeded: Boolean = true) - = AnnotationHostKind(kind, name, newLineNeeded) + private fun detect( + declaration: KtDeclaration, + kind: String, + name: String = declaration.name ?: "", + newLineNeeded: Boolean = true + ) = AnnotationHostKind(kind, name, newLineNeeded) } diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/PropertiesHighlightingVisitor.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/PropertiesHighlightingVisitor.kt index d027ce0adf8..0482489f441 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/PropertiesHighlightingVisitor.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/PropertiesHighlightingVisitor.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -91,26 +91,24 @@ internal class PropertiesHighlightingVisitor(holder: AnnotationHolder, bindingCo } } - private fun attributeKeyByPropertyType(descriptor: PropertyDescriptor): TextAttributesKey? { - return when { - descriptor.isDynamic() -> - // The property is set in VariablesHighlightingVisitor - null + private fun attributeKeyByPropertyType(descriptor: PropertyDescriptor): TextAttributesKey? = when { + descriptor.isDynamic() -> + // The property is set in VariablesHighlightingVisitor + null - KotlinHighlightingUtil.hasExtensionReceiverParameter(descriptor) -> - if (descriptor.isSynthesized) SYNTHETIC_EXTENSION_PROPERTY else EXTENSION_PROPERTY + KotlinHighlightingUtil.hasExtensionReceiverParameter(descriptor) -> + if (descriptor.isSynthesized) SYNTHETIC_EXTENSION_PROPERTY else EXTENSION_PROPERTY - DescriptorUtils.isStaticDeclaration(descriptor) -> - if(KotlinHighlightingUtil.hasCustomPropertyDeclaration(descriptor)) - PACKAGE_PROPERTY_CUSTOM_PROPERTY_DECLARATION - else - PACKAGE_PROPERTY + DescriptorUtils.isStaticDeclaration(descriptor) -> + if (KotlinHighlightingUtil.hasCustomPropertyDeclaration(descriptor)) + PACKAGE_PROPERTY_CUSTOM_PROPERTY_DECLARATION + else + PACKAGE_PROPERTY - else -> - if (KotlinHighlightingUtil.hasCustomPropertyDeclaration(descriptor)) - INSTANCE_PROPERTY_CUSTOM_PROPERTY_DECLARATION - else - INSTANCE_PROPERTY - } + else -> + if (KotlinHighlightingUtil.hasCustomPropertyDeclaration(descriptor)) + INSTANCE_PROPERTY_CUSTOM_PROPERTY_DECLARATION + else + INSTANCE_PROPERTY } } diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/VariablesHighlightingVisitor.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/VariablesHighlightingVisitor.kt index ab228cef8c9..d5e9b684c6c 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/VariablesHighlightingVisitor.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/VariablesHighlightingVisitor.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.highlighter @@ -37,8 +26,8 @@ import org.jetbrains.kotlin.resolve.scopes.receivers.ExtensionReceiver import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitClassReceiver import org.jetbrains.kotlin.types.expressions.CaptureKind -internal class VariablesHighlightingVisitor(holder: AnnotationHolder, bindingContext: BindingContext) - : AfterAnalysisHighlightingVisitor(holder, bindingContext) { +internal class VariablesHighlightingVisitor(holder: AnnotationHolder, bindingContext: BindingContext) : + AfterAnalysisHighlightingVisitor(holder, bindingContext) { override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { val target = bindingContext.get(REFERENCE_TARGET, expression) ?: return @@ -91,31 +80,32 @@ internal class VariablesHighlightingVisitor(holder: AnnotationHolder, bindingCon is ImplicitClassReceiver -> "Implicit receiver" else -> "Unknown receiver" } - createInfoAnnotation(expression, - "$receiverName smart cast to " + DescriptorRenderer.FQ_NAMES_IN_TYPES.renderType(type)) - .textAttributes = SMART_CAST_RECEIVER + createInfoAnnotation( + expression, + "$receiverName smart cast to " + DescriptorRenderer.FQ_NAMES_IN_TYPES.renderType(type) + ).textAttributes = SMART_CAST_RECEIVER } } val nullSmartCast = bindingContext.get(SMARTCAST_NULL, expression) == true if (nullSmartCast) { - createInfoAnnotation(expression, "Always null") - .textAttributes = SMART_CONSTANT + createInfoAnnotation(expression, "Always null").textAttributes = SMART_CONSTANT } val smartCast = bindingContext.get(SMARTCAST, expression) if (smartCast != null) { val defaultType = smartCast.defaultType if (defaultType != null) { - createInfoAnnotation(getSmartCastTarget(expression), - "Smart cast to " + DescriptorRenderer.FQ_NAMES_IN_TYPES.renderType(defaultType)) - .textAttributes = SMART_CAST_VALUE - } - else if (smartCast is MultipleSmartCasts) { + createInfoAnnotation( + getSmartCastTarget(expression), + "Smart cast to " + DescriptorRenderer.FQ_NAMES_IN_TYPES.renderType(defaultType) + ).textAttributes = SMART_CAST_VALUE + } else if (smartCast is MultipleSmartCasts) { for ((call, type) in smartCast.map) { - createInfoAnnotation(getSmartCastTarget(expression), - "Smart cast to ${DescriptorRenderer.FQ_NAMES_IN_TYPES.renderType(type)} (for $call call)") - .textAttributes = SMART_CAST_VALUE + createInfoAnnotation( + getSmartCastTarget(expression), + "Smart cast to ${DescriptorRenderer.FQ_NAMES_IN_TYPES.renderType(type)} (for $call call)" + ).textAttributes = SMART_CAST_VALUE } } } @@ -166,11 +156,13 @@ internal class VariablesHighlightingVisitor(holder: AnnotationHolder, bindingCon if (descriptor is PropertyDescriptor && KotlinHighlightingUtil.hasCustomPropertyDeclaration(descriptor)) { val isStaticDeclaration = DescriptorUtils.isStaticDeclaration(descriptor) - highlightName(elementToHighlight, - if (isStaticDeclaration) - PACKAGE_PROPERTY_CUSTOM_PROPERTY_DECLARATION - else - INSTANCE_PROPERTY_CUSTOM_PROPERTY_DECLARATION) + highlightName( + elementToHighlight, + if (isStaticDeclaration) + PACKAGE_PROPERTY_CUSTOM_PROPERTY_DECLARATION + else + INSTANCE_PROPERTY_CUSTOM_PROPERTY_DECLARATION + ) } } } diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/renderersUtil.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/renderersUtil.kt index ac6307e1e26..11a98a504c2 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/renderersUtil.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/renderersUtil.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.highlighter.renderersUtil @@ -32,8 +21,8 @@ import org.jetbrains.kotlin.resolve.calls.components.hasDefaultValue import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall import org.jetbrains.kotlin.types.ErrorUtils -private val RED_TEMPLATE = "%s" -private val STRONG_TEMPLATE = "%s" +private const val RED_TEMPLATE = "%s" +private const val STRONG_TEMPLATE = "%s" fun renderStrong(o: Any): String = STRONG_TEMPLATE.format(o) @@ -59,21 +48,19 @@ fun renderResolvedCall(resolvedCall: ResolvedCall<*>, context: RenderingContext) fun renderParameter(parameter: ValueParameterDescriptor): String { val varargElementType = parameter.varargElementType val parameterType = varargElementType ?: parameter.type - val renderedParameter = - (if (varargElementType != null) "vararg " else "") + + val renderedParameter = (if (varargElementType != null) "vararg " else "") + typeRenderer.render(parameterType, context) + if (parameter.hasDefaultValue()) " = ..." else "" - if (resolvedCall.hasTypeMismatchErrorOnParameter(parameter)) { - return renderError(renderedParameter) - } - return renderedParameter + return if (resolvedCall.hasTypeMismatchErrorOnParameter(parameter)) + renderError(renderedParameter) + else + renderedParameter } fun appendTypeParametersSubstitution() { val parametersToArgumentsMap = resolvedCall.typeArguments fun TypeParameterDescriptor.isInferred(): Boolean { - val typeArgument = parametersToArgumentsMap[this] - if (typeArgument == null) return false + val typeArgument = parametersToArgumentsMap[this] ?: return false return !ErrorUtils.isUninferredParameter(typeArgument) } @@ -81,16 +68,16 @@ fun renderResolvedCall(resolvedCall: ResolvedCall<*>, context: RenderingContext) val (inferredTypeParameters, notInferredTypeParameters) = typeParameters.partition(TypeParameterDescriptor::isInferred) append("
    $indentwhere ") - if (!notInferredTypeParameters.isEmpty()) { + if (notInferredTypeParameters.isNotEmpty()) { append(notInferredTypeParameters.joinToString { typeParameter -> renderError(typeParameter.name) }) append(" cannot be inferred") - if (!inferredTypeParameters.isEmpty()) { + if (inferredTypeParameters.isNotEmpty()) { append("; ") } } val typeParameterToTypeArgumentMap = resolvedCall.typeArguments - if (!inferredTypeParameters.isEmpty()) { + if (inferredTypeParameters.isNotEmpty()) { append(inferredTypeParameters.joinToString { typeParameter -> "${typeParameter.name} = ${typeRenderer.render(typeParameterToTypeArgumentMap[typeParameter]!!, context)}" }) @@ -106,13 +93,12 @@ fun renderResolvedCall(resolvedCall: ResolvedCall<*>, context: RenderingContext) append(resultingDescriptor.valueParameters.joinToString(transform = ::renderParameter)) append(if (resolvedCall.hasUnmappedArguments()) renderError(")") else ")") - if (!resolvedCall.candidateDescriptor.typeParameters.isEmpty()) { + if (resolvedCall.candidateDescriptor.typeParameters.isNotEmpty()) { appendTypeParametersSubstitution() append(" for
    $indent") // candidate descriptor is not in context of the rest of the message append(descriptorRenderer.render(resolvedCall.candidateDescriptor, RenderingContext.of(resolvedCall.candidateDescriptor))) - } - else { + } else { append(" defined in ") val containingDeclaration = resultingDescriptor.containingDeclaration val fqName = DescriptorUtils.getFqName(containingDeclaration) diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/inspections/IntentionBasedInspection.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/inspections/IntentionBasedInspection.kt index 30374ab3d91..8559dc7d7f3 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/inspections/IntentionBasedInspection.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/inspections/IntentionBasedInspection.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.inspections @@ -43,8 +32,8 @@ import kotlin.reflect.KClass // thus making the original purpose useless. // The class still can be used, if you want to create a pair for existing intention with additional checker abstract class IntentionBasedInspection private constructor( - private val intentionInfo: IntentionData, - protected open val problemText: String? + private val intentionInfo: IntentionData, + protected open val problemText: String? ) : AbstractKotlinInspection() { val intention: SelfTargetingRangeIntention by lazy { @@ -57,33 +46,32 @@ abstract class IntentionBasedInspection private construct @Suppress("DEPRECATION") @Deprecated("Please do not use for new inspections. Use AbstractKotlinInspection as base class for them") constructor( - intention: KClass>, - problemText: String? = null + intention: KClass>, + problemText: String? = null ) : this(IntentionData(intention), problemText) constructor( - intention: KClass>, - additionalChecker: (TElement, IntentionBasedInspection) -> Boolean, - problemText: String? = null + intention: KClass>, + additionalChecker: (TElement, IntentionBasedInspection) -> Boolean, + problemText: String? = null ) : this(IntentionData(intention, additionalChecker), problemText) constructor( - intention: KClass>, - additionalChecker: (TElement) -> Boolean, - problemText: String? = null - ) : this(IntentionData(intention, { element, _ -> additionalChecker(element) } ), problemText) - + intention: KClass>, + additionalChecker: (TElement) -> Boolean, + problemText: String? = null + ) : this(IntentionData(intention) { element, _ -> additionalChecker(element) }, problemText) data class IntentionData( - val intention: KClass>, - val additionalChecker: (TElement, IntentionBasedInspection) -> Boolean = { _, _ -> true } + val intention: KClass>, + val additionalChecker: (TElement, IntentionBasedInspection) -> Boolean = { _, _ -> true } ) open fun additionalFixes(element: TElement): List? = null open fun inspectionTarget(element: TElement): PsiElement? = null - + open fun inspectionProblemText(element: TElement): String? = null private fun PsiElement.toRange(baseElement: PsiElement): TextRange { @@ -127,12 +115,12 @@ abstract class IntentionBasedInspection private construct additionalFixes(targetElement)?.let { allFixes.addAll(it) } if (!allFixes.isEmpty()) { holder.registerProblemWithoutOfflineInformation( - targetElement, - inspectionProblemText(element) ?: problemText ?: allFixes.first().name, - isOnTheFly, - problemHighlightType(targetElement), - range, - *allFixes.toTypedArray() + targetElement, + inspectionProblemText(element) ?: problemText ?: allFixes.first().name, + isOnTheFly, + problemHighlightType(targetElement), + range, + *allFixes.toTypedArray() ) } } @@ -141,25 +129,23 @@ abstract class IntentionBasedInspection private construct } protected open fun problemHighlightType(element: TElement): ProblemHighlightType = - ProblemHighlightType.GENERIC_ERROR_OR_WARNING + ProblemHighlightType.GENERIC_ERROR_OR_WARNING private fun createQuickFix( - intention: SelfTargetingRangeIntention, - additionalChecker: (TElement, IntentionBasedInspection) -> Boolean, - targetElement: TElement - ): IntentionBasedQuickFix { - return when (intention) { - is LowPriorityAction -> LowPriorityIntentionBasedQuickFix(intention, additionalChecker, targetElement) - is HighPriorityAction -> HighPriorityIntentionBasedQuickFix(intention, additionalChecker, targetElement) - else -> IntentionBasedQuickFix(intention, additionalChecker, targetElement) - } + intention: SelfTargetingRangeIntention, + additionalChecker: (TElement, IntentionBasedInspection) -> Boolean, + targetElement: TElement + ): IntentionBasedQuickFix = when (intention) { + is LowPriorityAction -> LowPriorityIntentionBasedQuickFix(intention, additionalChecker, targetElement) + is HighPriorityAction -> HighPriorityIntentionBasedQuickFix(intention, additionalChecker, targetElement) + else -> IntentionBasedQuickFix(intention, additionalChecker, targetElement) } /* we implement IntentionAction to provide isAvailable which will be used to hide outdated items and make sure we never call 'invoke' for such item */ internal open inner class IntentionBasedQuickFix( - val intention: SelfTargetingRangeIntention, - private val additionalChecker: (TElement, IntentionBasedInspection) -> Boolean, - targetElement: TElement + val intention: SelfTargetingRangeIntention, + private val additionalChecker: (TElement, IntentionBasedInspection) -> Boolean, + targetElement: TElement ) : LocalQuickFixOnPsiElement(targetElement), IntentionAction { private val text = intention.text @@ -200,15 +186,15 @@ abstract class IntentionBasedInspection private construct } private inner class LowPriorityIntentionBasedQuickFix( - intention: SelfTargetingRangeIntention, - additionalChecker: (TElement, IntentionBasedInspection) -> Boolean, - targetElement: TElement + intention: SelfTargetingRangeIntention, + additionalChecker: (TElement, IntentionBasedInspection) -> Boolean, + targetElement: TElement ) : IntentionBasedQuickFix(intention, additionalChecker, targetElement), LowPriorityAction private inner class HighPriorityIntentionBasedQuickFix( - intention: SelfTargetingRangeIntention, - additionalChecker: (TElement, IntentionBasedInspection) -> Boolean, - targetElement: TElement + intention: SelfTargetingRangeIntention, + additionalChecker: (TElement, IntentionBasedInspection) -> Boolean, + targetElement: TElement ) : IntentionBasedQuickFix(intention, additionalChecker, targetElement), HighPriorityAction } diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/intentions/OperatorToFunctionIntention.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/intentions/OperatorToFunctionIntention.kt index 039c51e05a9..97673e42c42 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/intentions/OperatorToFunctionIntention.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/intentions/OperatorToFunctionIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions @@ -21,7 +10,8 @@ import com.intellij.psi.PsiElement import org.jetbrains.kotlin.KtNodeTypes import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.descriptors.FunctionDescriptor -import org.jetbrains.kotlin.idea.caches.resolve.* +import org.jetbrains.kotlin.idea.caches.resolve.analyze +import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.project.languageVersionSettings import org.jetbrains.kotlin.idea.references.ReferenceAccess import org.jetbrains.kotlin.idea.references.readWriteAccess @@ -89,23 +79,23 @@ class OperatorToFunctionIntention : private fun isApplicableCall(element: KtCallExpression, caretOffset: Int): Boolean { val lbrace = (element.valueArgumentList?.leftParenthesis - ?: element.lambdaArguments.firstOrNull()?.getLambdaExpression()?.leftCurlyBrace - ?: return false) as PsiElement + ?: element.lambdaArguments.firstOrNull()?.getLambdaExpression()?.leftCurlyBrace + ?: return false) as PsiElement if (!lbrace.textRange.containsOffset(caretOffset)) return false val resolvedCall = element.resolveToCall(BodyResolveMode.FULL) val descriptor = resolvedCall?.resultingDescriptor if (descriptor is FunctionDescriptor && descriptor.getName() == OperatorNameConventions.INVOKE) { if (element.parent is KtDotQualifiedExpression && - element.calleeExpression?.text == OperatorNameConventions.INVOKE.asString()) return false + element.calleeExpression?.text == OperatorNameConventions.INVOKE.asString() + ) return false return element.valueArgumentList != null || element.lambdaArguments.isNotEmpty() } return false } private fun convertUnary(element: KtUnaryExpression): KtExpression { - val op = element.operationReference.getReferencedNameElementType() - val operatorName = when (op) { + val operatorName = when (element.operationReference.getReferencedNameElementType()) { KtTokens.PLUSPLUS, KtTokens.MINUSMINUS -> return convertUnaryWithAssignFix(element) KtTokens.PLUS -> OperatorNameConventions.UNARY_PLUS KtTokens.MINUS -> OperatorNameConventions.UNARY_MINUS @@ -118,8 +108,7 @@ class OperatorToFunctionIntention : } private fun convertUnaryWithAssignFix(element: KtUnaryExpression): KtExpression { - val op = element.operationReference.getReferencedNameElementType() - val operatorName = when (op) { + val operatorName = when (element.operationReference.getReferencedNameElementType()) { KtTokens.PLUSPLUS -> OperatorNameConventions.INC KtTokens.MINUSMINUS -> OperatorNameConventions.DEC else -> return element @@ -208,7 +197,8 @@ class OperatorToFunctionIntention : private fun isAssignmentLeftSide(element: KtArrayAccessExpression): Boolean { val parent = element.parent - return parent is KtBinaryExpression && parent.operationReference.getReferencedNameElementType() == KtTokens.EQ && element == parent.left + return parent is KtBinaryExpression && + parent.operationReference.getReferencedNameElementType() == KtTokens.EQ && element == parent.left } //TODO: don't use creation by plain text @@ -218,8 +208,8 @@ class OperatorToFunctionIntention : val argumentString = arguments?.text?.removeSurrounding("(", ")") val funcLitArgs = element.lambdaArguments val calleeText = callee.text - val transformation = "$calleeText.${OperatorNameConventions.INVOKE.asString()}" + - (if (argumentString == null) "()" else "($argumentString)") + val transformation = + "$calleeText.${OperatorNameConventions.INVOKE.asString()}" + (if (argumentString == null) "()" else "($argumentString)") val transformed = KtPsiFactory(element).createExpression(transformation) val callExpression = transformed.getCalleeExpressionIfAny()?.parent as? KtCallExpression if (callExpression != null) { diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/intentions/SelfTargetingIntention.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/intentions/SelfTargetingIntention.kt index 9af8286bc91..ac34372b3ca 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/intentions/SelfTargetingIntention.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/intentions/SelfTargetingIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions @@ -36,9 +25,9 @@ import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf @Suppress("EqualsOrHashCode") abstract class SelfTargetingIntention( - val elementType: Class, - private var text: String, - private val familyName: String = text + val elementType: Class, + private var text: String, + private val familyName: String = text ) : IntentionAction { protected val defaultText: String = text @@ -85,8 +74,7 @@ abstract class SelfTargetingIntention( return getTarget(offset, file) } - protected open fun allowCaretInsideElement(element: PsiElement): Boolean = - element !is KtBlockExpression + protected open fun allowCaretInsideElement(element: PsiElement): Boolean = element !is KtBlockExpression final override fun isAvailable(project: Project, editor: Editor, file: PsiFile): Boolean { if (ApplicationManager.getApplication().isUnitTestMode) { @@ -94,8 +82,7 @@ abstract class SelfTargetingIntention( } try { return getTarget(editor, file) != null - } - finally { + } finally { CREATE_BY_PATTERN_MAY_NOT_REFORMAT = false } } @@ -126,9 +113,9 @@ abstract class SelfTargetingIntention( } abstract class SelfTargetingRangeIntention( - elementType: Class, - text: String, - familyName: String = text + elementType: Class, + text: String, + familyName: String = text ) : SelfTargetingIntention(elementType, text, familyName) { abstract fun applicabilityRange(element: TElement): TextRange? @@ -140,9 +127,9 @@ abstract class SelfTargetingRangeIntention( } abstract class SelfTargetingOffsetIndependentIntention( - elementType: Class, - text: String, - familyName: String = text + elementType: Class, + text: String, + familyName: String = text ) : SelfTargetingRangeIntention(elementType, text, familyName) { abstract fun isApplicableTo(element: TElement): Boolean diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/kdoc/IdeSampleResolutionService.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/kdoc/IdeSampleResolutionService.kt index 0e8c6947d6f..00b558d6599 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/kdoc/IdeSampleResolutionService.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/kdoc/IdeSampleResolutionService.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.kdoc @@ -20,8 +9,8 @@ import com.intellij.openapi.project.Project import com.intellij.psi.search.GlobalSearchScope import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.annotations.Annotations -import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny +import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.idea.stubindex.* import org.jetbrains.kotlin.incremental.components.LookupLocation @@ -37,7 +26,12 @@ import org.jetbrains.kotlin.utils.Printer class IdeSampleResolutionService(val project: Project) : SampleResolutionService { - override fun resolveSample(context: BindingContext, fromDescriptor: DeclarationDescriptor, resolutionFacade: ResolutionFacade, qualifiedName: List): Collection { + override fun resolveSample( + context: BindingContext, + fromDescriptor: DeclarationDescriptor, + resolutionFacade: ResolutionFacade, + qualifiedName: List + ): Collection { val scope = KotlinSourceFilterScope.projectAndLibrariesSources(GlobalSearchScope.projectScope(project), project) @@ -48,10 +42,9 @@ class IdeSampleResolutionService(val project: Project) : SampleResolutionService val functions = KotlinFunctionShortNameIndex.getInstance().get(shortName, project, scope).asSequence() val classes = KotlinClassShortNameIndex.getInstance().get(shortName, project, scope).asSequence() - val descriptors = (functions + classes) - .filter { it.fqName == targetFqName } - .map { it.unsafeResolveToDescriptor(BodyResolveMode.PARTIAL) } // TODO Filter out not visible due dependencies config descriptors - .toList() + val descriptors = (functions + classes).filter { it.fqName == targetFqName } + .map { it.unsafeResolveToDescriptor(BodyResolveMode.PARTIAL) } // TODO Filter out not visible due dependencies config descriptors + .toList() if (descriptors.isNotEmpty()) return descriptors @@ -63,16 +56,21 @@ class IdeSampleResolutionService(val project: Project) : SampleResolutionService private fun shouldNotBeCalled(): Nothing = throw UnsupportedOperationException("Synthetic PVD for KDoc link resolution") -private class GlobalSyntheticPackageViewDescriptor(override val fqName: FqName, private val project: Project, private val scope: GlobalSearchScope) : PackageViewDescriptor { +private class GlobalSyntheticPackageViewDescriptor( + override val fqName: FqName, + private val project: Project, + private val scope: GlobalSearchScope +) : PackageViewDescriptor { override fun getContainingDeclaration(): PackageViewDescriptor? = - if (fqName.isOneSegmentFQN()) null else GlobalSyntheticPackageViewDescriptor(fqName.parent(), project, scope) + if (fqName.isOneSegmentFQN()) null else GlobalSyntheticPackageViewDescriptor(fqName.parent(), project, scope) override val memberScope: MemberScope = object : MemberScope { override fun getContributedVariables(name: Name, location: LookupLocation): Collection = shouldNotBeCalled() - override fun getContributedFunctions(name: Name, location: LookupLocation): Collection = shouldNotBeCalled() + override fun getContributedFunctions(name: Name, location: LookupLocation): Collection = + shouldNotBeCalled() override fun getFunctionNames(): Set = shouldNotBeCalled() override fun getVariableNames(): Set = shouldNotBeCalled() @@ -87,33 +85,35 @@ private class GlobalSyntheticPackageViewDescriptor(override val fqName: FqName, fun getClassesByNameFilter(nameFilter: (Name) -> Boolean) = KotlinFullClassNameIndex.getInstance() - .getAllKeys(project) - .asSequence() - .filter { it.startsWith(fqName.asString()) } - .map(::FqName) - .filter { it.isChildOf(fqName) } - .filter { nameFilter(it.shortName()) } - .flatMap { KotlinFullClassNameIndex.getInstance()[it.asString(), project, scope].asSequence() } - .map { it.resolveToDescriptorIfAny() } + .getAllKeys(project) + .asSequence() + .filter { it.startsWith(fqName.asString()) } + .map(::FqName) + .filter { it.isChildOf(fqName) } + .filter { nameFilter(it.shortName()) } + .flatMap { KotlinFullClassNameIndex.getInstance()[it.asString(), project, scope].asSequence() } + .map { it.resolveToDescriptorIfAny() } fun getFunctionsByNameFilter(nameFilter: (Name) -> Boolean) = KotlinTopLevelFunctionFqnNameIndex.getInstance() - .getAllKeys(project) - .asSequence() - .filter { it.startsWith(fqName.asString()) } - .map(::FqName) - .filter { it.isChildOf(fqName) } - .filter { nameFilter(it.shortName()) } - .flatMap { KotlinTopLevelFunctionFqnNameIndex.getInstance()[it.asString(), project, scope].asSequence() } - .map { it.resolveToDescriptorIfAny() as? DeclarationDescriptor } + .getAllKeys(project) + .asSequence() + .filter { it.startsWith(fqName.asString()) } + .map(::FqName) + .filter { it.isChildOf(fqName) } + .filter { nameFilter(it.shortName()) } + .flatMap { KotlinTopLevelFunctionFqnNameIndex.getInstance()[it.asString(), project, scope].asSequence() } + .map { it.resolveToDescriptorIfAny() as? DeclarationDescriptor } - fun getSubpackages(nameFilter: (Name) -> Boolean) = - PackageIndexUtil.getSubPackageFqNames(fqName, scope, project, nameFilter) - .map { GlobalSyntheticPackageViewDescriptor(it, project, scope) } + fun getSubpackages(nameFilter: (Name) -> Boolean) = PackageIndexUtil.getSubPackageFqNames(fqName, scope, project, nameFilter) + .map { GlobalSyntheticPackageViewDescriptor(it, project, scope) } - override fun getContributedDescriptors(kindFilter: DescriptorKindFilter, nameFilter: (Name) -> Boolean): Collection - = (getClassesByNameFilter(nameFilter) - + getFunctionsByNameFilter(nameFilter) - + getSubpackages(nameFilter)).filterNotNull().toList() + override fun getContributedDescriptors( + kindFilter: DescriptorKindFilter, + nameFilter: (Name) -> Boolean + ): Collection = (getClassesByNameFilter(nameFilter) + + getFunctionsByNameFilter(nameFilter) + + getSubpackages(nameFilter) + ).filterNotNull().toList() } override val module: ModuleDescriptor diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/kdoc/KDocUnresolvedReferenceInspection.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/kdoc/KDocUnresolvedReferenceInspection.kt index b463617ac18..8bdddb794c6 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/kdoc/KDocUnresolvedReferenceInspection.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/kdoc/KDocUnresolvedReferenceInspection.kt @@ -1,33 +1,22 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.kdoc -import org.jetbrains.kotlin.idea.inspections.AbstractKotlinInspection import com.intellij.codeInspection.ProblemsHolder -import com.intellij.psi.PsiElementVisitor import com.intellij.psi.PsiElement +import com.intellij.psi.PsiElementVisitor +import org.jetbrains.kotlin.idea.inspections.AbstractKotlinInspection import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.kdoc.psi.impl.KDocName -class KDocUnresolvedReferenceInspection(): AbstractKotlinInspection() { +class KDocUnresolvedReferenceInspection() : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor = KDocUnresolvedReferenceVisitor(holder) - private class KDocUnresolvedReferenceVisitor(private val holder: ProblemsHolder): PsiElementVisitor() { + private class KDocUnresolvedReferenceVisitor(private val holder: ProblemsHolder) : PsiElementVisitor() { override fun visitElement(element: PsiElement) { if (element is KDocName) { val ref = element.mainReference diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/modules/IdeJavaModuleResolver.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/modules/IdeJavaModuleResolver.kt index af5b8c58008..ee5ceffc023 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/modules/IdeJavaModuleResolver.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/modules/IdeJavaModuleResolver.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.modules @@ -20,18 +9,15 @@ import com.intellij.codeInsight.daemon.impl.analysis.JavaModuleGraphUtil import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiJavaModule -import com.intellij.psi.PsiManager import com.intellij.psi.impl.light.LightJavaModule -import org.jetbrains.annotations.NotNull import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.resolve.jvm.modules.JavaModuleResolver class IdeJavaModuleResolver(private val project: Project) : JavaModuleResolver { - private fun findJavaModule(file: VirtualFile): PsiJavaModule? = - ModuleHighlightUtil2.getModuleDescriptor(file, project) + private fun findJavaModule(file: VirtualFile): PsiJavaModule? = ModuleHighlightUtil2.getModuleDescriptor(file, project) override fun checkAccessibility( - fileFromOurModule: VirtualFile?, referencedFile: VirtualFile, referencedPackage: FqName? + fileFromOurModule: VirtualFile?, referencedFile: VirtualFile, referencedPackage: FqName? ): JavaModuleResolver.AccessError? { val ourModule = fileFromOurModule?.let(this::findJavaModule) val theirModule = findJavaModule(referencedFile) @@ -64,5 +50,5 @@ class IdeJavaModuleResolver(private val project: Project) : JavaModuleResolver { // Returns whether or not [source] exports [packageName] to [target] private fun exports(source: PsiJavaModule, packageName: String, target: PsiJavaModule): Boolean = - source is LightJavaModule || JavaModuleGraphUtil.exports(source, packageName, target) + source is LightJavaModule || JavaModuleGraphUtil.exports(source, packageName, target) } diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/project/IdeaLocalDescriptorResolver.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/project/IdeaLocalDescriptorResolver.kt index 37b9f5cd0a7..e7eebfbaab4 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/project/IdeaLocalDescriptorResolver.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/project/IdeaLocalDescriptorResolver.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.project @@ -20,30 +9,31 @@ import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.idea.stubindex.resolve.PluginDeclarationProviderFactory import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.resolve.BindingContext +import org.jetbrains.kotlin.resolve.lazy.AbsentDescriptorHandler import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.lazy.LocalDescriptorResolver -import org.jetbrains.kotlin.resolve.lazy.AbsentDescriptorHandler import org.jetbrains.kotlin.resolve.lazy.NoDescriptorForDeclarationException import org.jetbrains.kotlin.resolve.lazy.declarations.DeclarationProviderFactory class IdeaLocalDescriptorResolver( - private val resolveElementCache: ResolveElementCache, - private val absentDescriptorHandler: AbsentDescriptorHandler + private val resolveElementCache: ResolveElementCache, + private val absentDescriptorHandler: AbsentDescriptorHandler ) : LocalDescriptorResolver { override fun resolveLocalDeclaration(declaration: KtDeclaration): DeclarationDescriptor { val context = resolveElementCache.resolveToElements(listOf(declaration), BodyResolveMode.FULL) - return context.get(BindingContext.DECLARATION_TO_DESCRIPTOR, declaration) - ?: absentDescriptorHandler.diagnoseDescriptorNotFound(declaration) + return context.get(BindingContext.DECLARATION_TO_DESCRIPTOR, declaration) ?: absentDescriptorHandler.diagnoseDescriptorNotFound( + declaration + ) } } class IdeaAbsentDescriptorHandler( - private val declarationProviderFactory: DeclarationProviderFactory + private val declarationProviderFactory: DeclarationProviderFactory ) : AbsentDescriptorHandler { override fun diagnoseDescriptorNotFound(declaration: KtDeclaration): DeclarationDescriptor { throw NoDescriptorForDeclarationException( - declaration, - (declarationProviderFactory as? PluginDeclarationProviderFactory)?.debugToString() + declaration, + (declarationProviderFactory as? PluginDeclarationProviderFactory)?.debugToString() ) } } \ No newline at end of file diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/project/ResolveElementCache.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/project/ResolveElementCache.kt index 8892a2fe463..fce4f6f7ce7 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/project/ResolveElementCache.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/project/ResolveElementCache.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.project @@ -61,8 +50,8 @@ class ResolveElementCache( private fun modificationStamp(resolveElement: KtElement): Long? { val file = resolveElement.containingFile return when { - // for non-physical file we don't get OUT_OF_CODE_BLOCK_MODIFICATION_COUNT increased and must reset - // data on any modification of the file + // for non-physical file we don't get OUT_OF_CODE_BLOCK_MODIFICATION_COUNT increased and must reset + // data on any modification of the file !file.isPhysical -> file.modificationStamp resolveElement is KtDeclaration && KotlinCodeBlockModificationListener.isBlockDeclaration(resolveElement) -> resolveElement.getModificationStamp() @@ -493,7 +482,7 @@ class ResolveElementCache( if (declaration is KtClass) { if (modifierList == declaration.primaryConstructorModifierList) { descriptor = (descriptor as ClassDescriptor).unsubstitutedPrimaryConstructor - ?: error("No constructor found: ${declaration.getText()}") + ?: error("No constructor found: ${declaration.getText()}") } } @@ -641,10 +630,7 @@ class ResolveElementCache( val classDescriptor = resolveSession.resolveToDescriptor(klass) as ClassDescriptor val constructorDescriptor = classDescriptor.unsubstitutedPrimaryConstructor - ?: error( - "Can't get primary constructor for descriptor '$classDescriptor' " + - "in from class '${klass.getElementTextWithContext()}'" - ) + ?: error("Can't get primary constructor for descriptor '$classDescriptor' in from class '${klass.getElementTextWithContext()}'") ForceResolveUtil.forceResolveAllContents(constructorDescriptor) val primaryConstructor = klass.primaryConstructor diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/quickfix/KotlinIntentionActionsFactory.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/quickfix/KotlinIntentionActionsFactory.kt index 2ce59735b22..1e7ada56f70 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/quickfix/KotlinIntentionActionsFactory.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/quickfix/KotlinIntentionActionsFactory.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -26,13 +15,13 @@ abstract class KotlinIntentionActionsFactory { protected abstract fun doCreateActions(diagnostic: Diagnostic): List protected open fun doCreateActionsForAllProblems( - sameTypeDiagnostics: Collection): List = emptyList() + sameTypeDiagnostics: Collection + ): List = emptyList() - fun createActions(diagnostic: Diagnostic): List = - createActions(listOfNotNull(diagnostic), false) + fun createActions(diagnostic: Diagnostic): List = createActions(listOfNotNull(diagnostic), false) fun createActionsForAllProblems(sameTypeDiagnostics: Collection): List = - createActions(sameTypeDiagnostics, true) + createActions(sameTypeDiagnostics, true) private fun createActions(sameTypeDiagnostics: Collection, createForAll: Boolean): List { if (sameTypeDiagnostics.isEmpty()) return emptyList() diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/quickfix/QuickFixes.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/quickfix/QuickFixes.kt index 24a3e6b8b34..9d5fbf23b41 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/quickfix/QuickFixes.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/quickfix/QuickFixes.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -25,7 +14,8 @@ import com.intellij.openapi.extensions.Extensions import org.jetbrains.kotlin.diagnostics.DiagnosticFactory class QuickFixes { - private val factories: Multimap, KotlinIntentionActionsFactory> = HashMultimap.create, KotlinIntentionActionsFactory>() + private val factories: Multimap, KotlinIntentionActionsFactory> = + HashMultimap.create, KotlinIntentionActionsFactory>() private val actions: Multimap, IntentionAction> = HashMultimap.create, IntentionAction>() init { diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/quickfix/TypeAccessibilityCheckerImpl.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/quickfix/TypeAccessibilityCheckerImpl.kt index 33dbaeabe59..41ef465cefd 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/quickfix/TypeAccessibilityCheckerImpl.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/quickfix/TypeAccessibilityCheckerImpl.kt @@ -99,7 +99,8 @@ private tailrec fun DeclarationDescriptor.additionalClasses(existingClasses: Col private fun DeclarationDescriptor.collectAllTypes(): Sequence { return when (this) { - is ClassConstructorDescriptor -> valueParameters.asSequence().map(ValueParameterDescriptor::getType).flatMap(KotlinType::collectAllTypes) + is ClassConstructorDescriptor -> valueParameters.asSequence().map(ValueParameterDescriptor::getType) + .flatMap(KotlinType::collectAllTypes) is ClassDescriptor -> if (isInline) unsubstitutedPrimaryConstructor?.collectAllTypes().orEmpty() else { emptySequence() } + declaredTypeParameters.asSequence().flatMap(DeclarationDescriptor::collectAllTypes) + sequenceOf(fqNameOrNull()) diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/references/KotlinDefaultAnnotationMethodImplicitReferenceContributor.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/references/KotlinDefaultAnnotationMethodImplicitReferenceContributor.kt index a58446bef9a..8e5115058ab 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/references/KotlinDefaultAnnotationMethodImplicitReferenceContributor.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/references/KotlinDefaultAnnotationMethodImplicitReferenceContributor.kt @@ -70,8 +70,7 @@ internal class KotlinDefaultAnnotationMethodImplicitReferenceContributor : Kotli override fun registerReferenceProviders(registrar: KotlinPsiReferenceRegistrar) { registrar.registerProvider { if (it.isNamed()) return@registerProvider null - val annotationEntry = it.getParentOfTypeAndBranch { valueArgumentList } - ?: return@registerProvider null + val annotationEntry = it.getParentOfTypeAndBranch { valueArgumentList } ?: return@registerProvider null if (annotationEntry.valueArguments.size != 1) return@registerProvider null ReferenceImpl(it) diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/references/KtArrayAccessReference.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/references/KtArrayAccessReference.kt index 86b7bae9557..0627b742d1d 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/references/KtArrayAccessReference.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/references/KtArrayAccessReference.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.references @@ -26,7 +15,10 @@ import org.jetbrains.kotlin.idea.core.replaced import org.jetbrains.kotlin.lexer.KtToken import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.Name -import org.jetbrains.kotlin.psi.* +import org.jetbrains.kotlin.psi.KtArrayAccessExpression +import org.jetbrains.kotlin.psi.KtPsiFactory +import org.jetbrains.kotlin.psi.KtQualifiedExpression +import org.jetbrains.kotlin.psi.buildExpression import org.jetbrains.kotlin.psi.psiUtil.getPossiblyQualifiedCallExpression import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.BindingContext.INDEXED_LVALUE_GET @@ -63,8 +55,7 @@ class KtArrayAccessReference( appendExpression(arrayExpression.receiverExpression) appendFixedText(arrayExpression.operationSign.value) appendExpression(arrayExpression.selectorExpression) - } - else { + } else { appendExpression(arrayExpression) } diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/references/KtCollectionLiteralReference.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/references/KtCollectionLiteralReference.kt index f11237eb056..60696d190b0 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/references/KtCollectionLiteralReference.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/references/KtCollectionLiteralReference.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.references @@ -25,11 +14,11 @@ import org.jetbrains.kotlin.psi.KtCollectionLiteralExpression import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.CollectionLiteralResolver -class KtCollectionLiteralReference(expression: KtCollectionLiteralExpression) : KtSimpleReference(expression), MultiRangeReference { +class KtCollectionLiteralReference(expression: KtCollectionLiteralExpression) : + KtSimpleReference(expression), MultiRangeReference { companion object { private val COLLECTION_LITERAL_CALL_NAMES = - CollectionLiteralResolver.PRIMITIVE_TYPE_TO_ARRAY.values + - CollectionLiteralResolver.ARRAY_OF_FUNCTION + CollectionLiteralResolver.PRIMITIVE_TYPE_TO_ARRAY.values + CollectionLiteralResolver.ARRAY_OF_FUNCTION } override fun getRangeInElement(): TextRange = element.normalizeRange() diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/references/KtDestructuringDeclarationReference.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/references/KtDestructuringDeclarationReference.kt index 52a60fc3bf4..d9eb1100ce4 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/references/KtDestructuringDeclarationReference.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/references/KtDestructuringDeclarationReference.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.references @@ -27,7 +16,8 @@ import org.jetbrains.kotlin.psi.KtDestructuringDeclaration import org.jetbrains.kotlin.psi.KtDestructuringDeclarationEntry import org.jetbrains.kotlin.resolve.BindingContext -class KtDestructuringDeclarationReference(element: KtDestructuringDeclarationEntry) : AbstractKtReference(element) { +class KtDestructuringDeclarationReference(element: KtDestructuringDeclarationEntry) : + AbstractKtReference(element) { override fun getTargetDescriptors(context: BindingContext): Collection { return listOfNotNull(context[BindingContext.COMPONENT_RESOLVED_CALL, element]?.candidateDescriptor) } @@ -36,7 +26,9 @@ class KtDestructuringDeclarationReference(element: KtDestructuringDeclarationEnt override fun canRename(): Boolean { val bindingContext = expression.analyze() //TODO: should it use full body resolve? - return resolveToDescriptors(bindingContext).all { it is CallableMemberDescriptor && it.kind == CallableMemberDescriptor.Kind.SYNTHESIZED} + return resolveToDescriptors(bindingContext).all { + it is CallableMemberDescriptor && it.kind == CallableMemberDescriptor.Kind.SYNTHESIZED + } } override fun handleElementRename(newElementName: String): PsiElement? { diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/references/KtForLoopInReference.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/references/KtForLoopInReference.kt index 1556989c966..d4c856f99da 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/references/KtForLoopInReference.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/references/KtForLoopInReference.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.references @@ -42,15 +31,15 @@ class KtForLoopInReference(element: KtForExpression) : KtMultiReference { - expression.replaced(KtPsiFactory(expression).createSimpleName(SpecialNames.DEFAULT_NAME_FOR_COMPANION_OBJECT.asString())) - } + is KtUserType -> expression.replaced( + KtPsiFactory(expression).createSimpleName( + SpecialNames.DEFAULT_NAME_FOR_COMPANION_OBJECT.asString() + ) + ) else -> expression } } @@ -296,7 +298,9 @@ class KtSimpleNameReference(expression: KtSimpleNameExpression) : KtSimpleRefere val importDirective = file.findImportByAlias(name) ?: return null val fqName = importDirective.importedFqName ?: return null val importedDescriptors = file.resolveImportReference(fqName).map { it.unwrap() } - if (getTargetDescriptors(element.analyze(BodyResolveMode.PARTIAL)).any { it.unwrap().getImportableDescriptor() in importedDescriptors }) { + if (getTargetDescriptors(element.analyze(BodyResolveMode.PARTIAL)).any { + it.unwrap().getImportableDescriptor() in importedDescriptors + }) { return importDirective.alias } return null diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/references/SyntheticPropertyAccessorReference.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/references/SyntheticPropertyAccessorReference.kt index fc7364b7cf5..7116ed7eb17 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/references/SyntheticPropertyAccessorReference.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/references/SyntheticPropertyAccessorReference.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.references @@ -38,7 +27,7 @@ import org.jetbrains.kotlin.types.expressions.OperatorConventions import org.jetbrains.kotlin.utils.addIfNotNull sealed class SyntheticPropertyAccessorReference(expression: KtNameReferenceExpression, private val getter: Boolean) : - KtSimpleReference(expression) { + KtSimpleReference(expression) { override fun getTargetDescriptors(context: BindingContext): Collection { val descriptors = super.getTargetDescriptors(context) if (descriptors.none { it is SyntheticJavaPropertyDescriptor }) return emptyList() @@ -115,10 +104,10 @@ sealed class SyntheticPropertyAccessorReference(expression: KtNameReferenceExpre //TODO: it's not correct //TODO: setIsY -> setIsIsY bug SyntheticJavaPropertyDescriptor.propertyNameBySetMethodName( - newNameAsName, - withIsPrefix = expression.getReferencedNameAsName().asString().startsWith( - "is" - ) + newNameAsName, + withIsPrefix = expression.getReferencedNameAsName().asString().startsWith( + "is" + ) ) } // get/set becomes ordinary method @@ -162,16 +151,16 @@ sealed class SyntheticPropertyAccessorReference(expression: KtNameReferenceExpre } else { val anchor = parent.parentsWithSelf.firstOrNull { it.parent == context } val validator = NewDeclarationNameValidator( - context, - anchor, - NewDeclarationNameValidator.Target.VARIABLES + context, + anchor, + NewDeclarationNameValidator.Target.VARIABLES ) val varName = KotlinNameSuggester.suggestNamesByExpressionAndType( - unaryExpr, - null, - unaryExpr.analyze(), - validator, - "p" + unaryExpr, + null, + unaryExpr.analyze(), + validator, + "p" ).first() val isPrefix = unaryExpr is KtPrefixExpression val varInitializer = if (isPrefix) incDecValue else originalValue diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/references/referenceUtil.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/references/referenceUtil.kt index 1850bbdb64c..ecd09b6ae0d 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/references/referenceUtil.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/references/referenceUtil.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.references @@ -89,9 +78,12 @@ fun DeclarationDescriptor.findPsiDeclarations(project: Project, resolveScope: Gl fun Collection.fqNameFilter() = filter { it.fqName == fqName } return when (this) { is DeserializedClassDescriptor -> KotlinFullClassNameIndex.getInstance()[fqName.asString(), project, resolveScope] - is DeserializedTypeAliasDescriptor -> KotlinTypeAliasShortNameIndex.getInstance()[fqName.shortName().asString(), project, resolveScope].fqNameFilter() - is DeserializedSimpleFunctionDescriptor, is FunctionImportedFromObject -> KotlinFunctionShortNameIndex.getInstance()[fqName.shortName().asString(), project, resolveScope].fqNameFilter() - is DeserializedPropertyDescriptor, is PropertyImportedFromObject -> KotlinPropertyShortNameIndex.getInstance()[fqName.shortName().asString(), project, resolveScope].fqNameFilter() + is DeserializedTypeAliasDescriptor -> KotlinTypeAliasShortNameIndex.getInstance()[fqName.shortName() + .asString(), project, resolveScope].fqNameFilter() + is DeserializedSimpleFunctionDescriptor, is FunctionImportedFromObject -> KotlinFunctionShortNameIndex.getInstance()[fqName.shortName() + .asString(), project, resolveScope].fqNameFilter() + is DeserializedPropertyDescriptor, is PropertyImportedFromObject -> KotlinPropertyShortNameIndex.getInstance()[fqName.shortName() + .asString(), project, resolveScope].fqNameFilter() is DeclarationDescriptorWithSource -> listOfNotNull(source.getPsi()) else -> emptyList() } diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/search/PsiBasedClassResolver.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/search/PsiBasedClassResolver.kt index fed894d6bd9..0d588123b02 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/search/PsiBasedClassResolver.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/search/PsiBasedClassResolver.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.search @@ -48,10 +37,12 @@ import java.util.concurrent.atomic.AtomicInteger class PsiBasedClassResolver @TestOnly constructor(private val targetClassFqName: String) { private val targetShortName = targetClassFqName.substringAfterLast('.') private val targetPackage = targetClassFqName.substringBeforeLast('.', "") + /** * Qualified names of packages which contain classes with the same short name as the target class. */ private val conflictingPackages = mutableListOf() + /** * Qualified names of packages which contain typealiases with the same short name as the target class * (which may or may not resolve to the target class). @@ -64,8 +55,10 @@ class PsiBasedClassResolver @TestOnly constructor(private val targetClassFqName: companion object { @get:TestOnly val attempts = AtomicInteger() + @get:TestOnly val trueHits = AtomicInteger() + @get:TestOnly val falseHits = AtomicInteger() diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/search/usagesSearch/ExpressionsOfTypeProcessor.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/search/usagesSearch/ExpressionsOfTypeProcessor.kt index 4bc7974c732..5b0244517fe 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/search/usagesSearch/ExpressionsOfTypeProcessor.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/search/usagesSearch/ExpressionsOfTypeProcessor.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.search.usagesSearch @@ -256,7 +245,8 @@ class ExpressionsOfTypeProcessor( val element = reference.element val document = PsiDocumentManager.getInstance(project).getDocument(element.containingFile) val lineAndCol = PsiDiagnosticUtils.offsetToLineAndColumn(document, element.startOffset) - return "Unsupported reference: '${element.text}' in ${element.containingFile.name} line ${lineAndCol.line} column ${lineAndCol.column}" + return "Unsupported reference: '${element.text}' in ${element.containingFile + .name} line ${lineAndCol.line} column ${lineAndCol.column}" } private enum class ReferenceProcessor(val handler: (ExpressionsOfTypeProcessor, PsiReference) -> Boolean) { @@ -473,7 +463,8 @@ class ExpressionsOfTypeProcessor( val scope = GlobalSearchScope.projectScope(project).excludeFileTypes(KotlinFileType.INSTANCE, XmlFileType.INSTANCE) testLog { "Searched references to ${logPresentation(psiClass)} in non-Kotlin files" } searchReferences(psiClass, scope) { reference -> - if (reference.element.language != JavaLanguage.INSTANCE) { // reference in some JVM language can be method parameter (but we don't know) + // reference in some JVM language can be method parameter (but we don't know) + if (reference.element.language != JavaLanguage.INSTANCE) { downShiftToPlainSearch(reference) return@searchReferences false } @@ -496,8 +487,7 @@ class ExpressionsOfTypeProcessor( when (element) { is KtReferenceExpression -> { - val parent = element.parent - when (parent) { + when (val parent = element.parent) { is KtUserType -> { // usage in type return processClassUsageInUserType(parent) } @@ -561,8 +551,7 @@ class ExpressionsOfTypeProcessor( private fun processClassUsageInUserType(userType: KtUserType): Boolean { val typeRef = userType.parents.lastOrNull { it is KtTypeReference } - val typeRefParent = typeRef?.parent - when (typeRefParent) { + when (val typeRefParent = typeRef?.parent) { is KtCallableDeclaration -> { when (typeRef) { typeRefParent.typeReference -> { // usage in type of callable declaration @@ -802,8 +791,7 @@ class ExpressionsOfTypeProcessor( possibleMatchHandler(element) } - val parent = element.parent - when (parent) { + when (val parent = element.parent) { is KtDestructuringDeclaration -> { // "val (x, y) = " processSuspiciousDeclaration(parent) break@ParentsLoop @@ -895,8 +883,7 @@ class ExpressionsOfTypeProcessor( //TODO: code is quite similar to PartialBodyResolveFilter.isValueNeeded private fun KtExpression.mayTypeAffectAncestors(): Boolean { - val parent = this.parent - when (parent) { + when (val parent = this.parent) { is KtBlockExpression -> { return this == parent.statements.last() && parent.mayTypeAffectAncestors() } diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/search/usagesSearch/operators/OperatorReferenceSearcher.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/search/usagesSearch/operators/OperatorReferenceSearcher.kt index 6dec754e3c5..0c2e6b138e4 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/search/usagesSearch/operators/OperatorReferenceSearcher.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/search/usagesSearch/operators/OperatorReferenceSearcher.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.search.usagesSearch.operators @@ -216,7 +205,7 @@ abstract class OperatorReferenceSearcher( is KtDeclaration -> targetDeclaration.resolveToDescriptorIfAny(BodyResolveMode.FULL) is PsiMember -> targetDeclaration.getJavaOrKotlinMemberDescriptor() else -> null - } as? FunctionDescriptor + } as? FunctionDescriptor } fun run() { diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/IndexUtils.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/IndexUtils.kt index 59f8d25c672..ee91744e70f 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/IndexUtils.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/IndexUtils.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.stubindex @@ -114,8 +103,7 @@ fun indexInternals(stub: KotlinCallableStubBase<*>, sink: IndexSink) { if (stub.isTopLevel()) return - if (modifierListStub.hasModifier(KtTokens.OPEN_KEYWORD) - || modifierListStub.hasModifier(KtTokens.ABSTRACT_KEYWORD)) { + if (modifierListStub.hasModifier(KtTokens.OPEN_KEYWORD) || modifierListStub.hasModifier(KtTokens.ABSTRACT_KEYWORD)) { sink.occurrence(KotlinOverridableInternalMembersShortNameIndex.Instance.key, name) } } diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinFileFacadeClassByPackageIndex.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinFileFacadeClassByPackageIndex.kt index 8fed76a2853..e98fded3823 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinFileFacadeClassByPackageIndex.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinFileFacadeClassByPackageIndex.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.stubindex @@ -27,13 +16,15 @@ class KotlinFileFacadeClassByPackageIndex private constructor() : StringStubInde override fun getKey(): StubIndexKey = KEY override fun get(key: String, project: Project, scope: GlobalSearchScope) = - StubIndex.getElements(KEY, key, project, scope, KtFile::class.java) + StubIndex.getElements(KEY, key, project, scope, KtFile::class.java) companion object { private val KEY = KotlinIndexUtil.createIndexKey(KotlinFileFacadeClassByPackageIndex::class.java) - @JvmField val INSTANCE: KotlinFileFacadeClassByPackageIndex = KotlinFileFacadeClassByPackageIndex() + @JvmField + val INSTANCE: KotlinFileFacadeClassByPackageIndex = KotlinFileFacadeClassByPackageIndex() - @JvmStatic fun getInstance(): KotlinFileFacadeClassByPackageIndex = INSTANCE + @JvmStatic + fun getInstance(): KotlinFileFacadeClassByPackageIndex = INSTANCE } } \ No newline at end of file diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinFileFacadeFqNameIndex.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinFileFacadeFqNameIndex.kt index 9fbfdf0628c..6d9cd06f928 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinFileFacadeFqNameIndex.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinFileFacadeFqNameIndex.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.stubindex @@ -27,13 +16,15 @@ class KotlinFileFacadeFqNameIndex private constructor() : StringStubIndexExtensi override fun getKey(): StubIndexKey = KEY override fun get(key: String, project: Project, scope: GlobalSearchScope) = - StubIndex.getElements(KEY, key, project, scope, KtFile::class.java) + StubIndex.getElements(KEY, key, project, scope, KtFile::class.java) companion object { private val KEY = KotlinIndexUtil.createIndexKey(KotlinFileFacadeFqNameIndex::class.java) - @JvmField val INSTANCE: KotlinFileFacadeFqNameIndex = KotlinFileFacadeFqNameIndex() + @JvmField + val INSTANCE: KotlinFileFacadeFqNameIndex = KotlinFileFacadeFqNameIndex() - @JvmStatic fun getInstance(): KotlinFileFacadeFqNameIndex = INSTANCE + @JvmStatic + fun getInstance(): KotlinFileFacadeFqNameIndex = INSTANCE } } \ No newline at end of file diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinFileFacadeShortNameIndex.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinFileFacadeShortNameIndex.kt index ca32fea31c7..a1dfe26c002 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinFileFacadeShortNameIndex.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinFileFacadeShortNameIndex.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.stubindex @@ -27,13 +16,15 @@ class KotlinFileFacadeShortNameIndex private constructor() : StringStubIndexExte override fun getKey(): StubIndexKey = KEY override fun get(key: String, project: Project, scope: GlobalSearchScope) = - StubIndex.getElements(KEY, key, project, scope, KtFile::class.java) + StubIndex.getElements(KEY, key, project, scope, KtFile::class.java) companion object { private val KEY = KotlinIndexUtil.createIndexKey(KotlinFileFacadeShortNameIndex::class.java) - @JvmField val INSTANCE: KotlinFileFacadeShortNameIndex = KotlinFileFacadeShortNameIndex() + @JvmField + val INSTANCE: KotlinFileFacadeShortNameIndex = KotlinFileFacadeShortNameIndex() - @JvmStatic fun getInstance(): KotlinFileFacadeShortNameIndex = INSTANCE + @JvmStatic + fun getInstance(): KotlinFileFacadeShortNameIndex = INSTANCE } } \ No newline at end of file diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinFilePartClassIndex.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinFilePartClassIndex.kt index 2deff8a17dc..c0629ceee28 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinFilePartClassIndex.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinFilePartClassIndex.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.stubindex @@ -28,13 +17,15 @@ class KotlinFilePartClassIndex private constructor() : StringStubIndexExtension< override fun getKey(): StubIndexKey = KEY override fun get(key: String, project: Project, scope: GlobalSearchScope) = - StubIndex.getElements(KEY, key, project, scope, KtFile::class.java) + StubIndex.getElements(KEY, key, project, scope, KtFile::class.java) companion object { private val KEY = KotlinIndexUtil.createIndexKey(KotlinFilePartClassIndex::class.java) - @JvmField val INSTANCE: KotlinFilePartClassIndex = KotlinFilePartClassIndex() + @JvmField + val INSTANCE: KotlinFilePartClassIndex = KotlinFilePartClassIndex() - @JvmStatic fun getInstance(): KotlinFilePartClassIndex = INSTANCE + @JvmStatic + fun getInstance(): KotlinFilePartClassIndex = INSTANCE } } \ No newline at end of file diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinFileStubForIde.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinFileStubForIde.kt index c218930919e..b45645a1aaf 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinFileStubForIde.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinFileStubForIde.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.stubindex @@ -25,12 +14,12 @@ import org.jetbrains.kotlin.psi.stubs.KotlinFileStub import org.jetbrains.kotlin.psi.stubs.impl.KotlinFileStubImpl class KotlinFileStubForIde( - jetFile: KtFile?, - packageName: StringRef, - isScript: Boolean, - private val facadeFqNameRef: StringRef?, - val partSimpleName: StringRef?, - val facadePartSimpleNames: List? + jetFile: KtFile?, + packageName: StringRef, + isScript: Boolean, + private val facadeFqNameRef: StringRef?, + val partSimpleName: StringRef?, + val facadePartSimpleNames: List? ) : KotlinFileStubImpl(jetFile, packageName, isScript), KotlinFileStub, PsiClassHolderFileStub { private fun StringRef.relativeToPackage() = getPackageFqName().child(Name.identifier(this.string)) @@ -40,33 +29,42 @@ class KotlinFileStubForIde( val facadeFqName: FqName? get() = facadeFqNameRef?.let { FqName(it.string) } - constructor(jetFile: KtFile?, packageName: String, isScript: Boolean) - : this(jetFile, StringRef.fromString(packageName)!!, isScript, null, null, null) + constructor(jetFile: KtFile?, packageName: String, isScript: Boolean) : this( + jetFile, + StringRef.fromString(packageName)!!, + isScript, + null, + null, + null + ) companion object { - fun forFile(packageFqName: FqName, isScript: Boolean): KotlinFileStubImpl = - KotlinFileStubForIde(jetFile = null, - packageName = StringRef.fromString(packageFqName.asString())!!, - facadeFqNameRef = null, - partSimpleName = null, - facadePartSimpleNames = null, - isScript = isScript) + fun forFile(packageFqName: FqName, isScript: Boolean): KotlinFileStubImpl = KotlinFileStubForIde( + jetFile = null, + packageName = StringRef.fromString(packageFqName.asString())!!, + facadeFqNameRef = null, + partSimpleName = null, + facadePartSimpleNames = null, + isScript = isScript + ) - fun forFileFacadeStub(facadeFqName: FqName): KotlinFileStubImpl = - KotlinFileStubForIde(jetFile = null, - packageName = facadeFqName.parent().stringRef(), - facadeFqNameRef = facadeFqName.stringRef(), - partSimpleName = facadeFqName.shortName().stringRef(), - facadePartSimpleNames = null, - isScript = false) + fun forFileFacadeStub(facadeFqName: FqName): KotlinFileStubImpl = KotlinFileStubForIde( + jetFile = null, + packageName = facadeFqName.parent().stringRef(), + facadeFqNameRef = facadeFqName.stringRef(), + partSimpleName = facadeFqName.shortName().stringRef(), + facadePartSimpleNames = null, + isScript = false + ) - fun forMultifileClassStub(facadeFqName: FqName, partNames: List?): KotlinFileStubImpl = - KotlinFileStubForIde(jetFile = null, - packageName = facadeFqName.parent().stringRef(), - facadeFqNameRef = facadeFqName.stringRef(), - partSimpleName = null, - facadePartSimpleNames = partNames?.map { StringRef.fromString(it) }, - isScript = false) + fun forMultifileClassStub(facadeFqName: FqName, partNames: List?): KotlinFileStubImpl = KotlinFileStubForIde( + jetFile = null, + packageName = facadeFqName.parent().stringRef(), + facadeFqNameRef = facadeFqName.stringRef(), + partSimpleName = null, + facadePartSimpleNames = partNames?.map { StringRef.fromString(it) }, + isScript = false + ) private fun FqName.stringRef() = StringRef.fromString(asString())!! private fun Name.stringRef() = StringRef.fromString(asString())!! diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinMultifileClassPartIndex.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinMultifileClassPartIndex.kt index a8c1afb08c0..57ecd04e1ca 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinMultifileClassPartIndex.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinMultifileClassPartIndex.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.stubindex @@ -28,13 +17,15 @@ class KotlinMultifileClassPartIndex private constructor() : StringStubIndexExten override fun getKey(): StubIndexKey = KEY override fun get(key: String, project: Project, scope: GlobalSearchScope) = - StubIndex.getElements(KEY, key, project, scope, KtFile::class.java) + StubIndex.getElements(KEY, key, project, scope, KtFile::class.java) companion object { private val KEY = KotlinIndexUtil.createIndexKey(KotlinMultifileClassPartIndex::class.java) - @JvmField val INSTANCE: KotlinMultifileClassPartIndex = KotlinMultifileClassPartIndex() + @JvmField + val INSTANCE: KotlinMultifileClassPartIndex = KotlinMultifileClassPartIndex() - @JvmStatic fun getInstance(): KotlinMultifileClassPartIndex = INSTANCE + @JvmStatic + fun getInstance(): KotlinMultifileClassPartIndex = INSTANCE } } \ No newline at end of file diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinTopLevelExtensionsByReceiverTypeIndex.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinTopLevelExtensionsByReceiverTypeIndex.kt index 40f55b58e19..0497743fdb1 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinTopLevelExtensionsByReceiverTypeIndex.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinTopLevelExtensionsByReceiverTypeIndex.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.stubindex @@ -26,12 +15,13 @@ class KotlinTopLevelExtensionsByReceiverTypeIndex private constructor() : String override fun getKey() = KEY - override fun get(s: String, project: Project, scope: GlobalSearchScope) - = StubIndex.getElements(KEY, s, project, scope, KtCallableDeclaration::class.java) + override fun get(s: String, project: Project, scope: GlobalSearchScope) = + StubIndex.getElements(KEY, s, project, scope, KtCallableDeclaration::class.java) companion object { - private val KEY = KotlinIndexUtil.createIndexKey(KotlinTopLevelExtensionsByReceiverTypeIndex::class.java) - private val SEPARATOR = '\n' + private val KEY = + KotlinIndexUtil.createIndexKey(KotlinTopLevelExtensionsByReceiverTypeIndex::class.java) + private const val SEPARATOR = '\n' val INSTANCE: KotlinTopLevelExtensionsByReceiverTypeIndex = KotlinTopLevelExtensionsByReceiverTypeIndex() diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinTopLevelTypeAliasByPackageIndex.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinTopLevelTypeAliasByPackageIndex.kt index 0a49aecaaca..e2d3144906b 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinTopLevelTypeAliasByPackageIndex.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinTopLevelTypeAliasByPackageIndex.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.stubindex @@ -27,15 +16,16 @@ class KotlinTopLevelTypeAliasByPackageIndex : StringStubIndexExtension = KEY override fun get(s: String, project: Project, scope: GlobalSearchScope): Collection = - StubIndex.getElements( - KEY, s, project, - scope, KtTypeAlias::class.java - ) + StubIndex.getElements( + KEY, s, project, + scope, KtTypeAlias::class.java + ) companion object { val KEY = KotlinIndexUtil.createIndexKey(KotlinTopLevelTypeAliasByPackageIndex::class.java) val INSTANCE = KotlinTopLevelTypeAliasByPackageIndex() - @JvmStatic fun getInstance() = INSTANCE + @JvmStatic + fun getInstance() = INSTANCE } } \ No newline at end of file diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinTopLevelTypeAliasFqNameIndex.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinTopLevelTypeAliasFqNameIndex.kt index eaec0b47ae4..24fdeb56e84 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinTopLevelTypeAliasFqNameIndex.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinTopLevelTypeAliasFqNameIndex.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.stubindex @@ -27,16 +16,17 @@ class KotlinTopLevelTypeAliasFqNameIndex : StringStubIndexExtension override fun getKey(): StubIndexKey = KEY override fun get(s: String, project: Project, scope: GlobalSearchScope): Collection = - StubIndex.getElements( - KEY, s, project, - scope, KtTypeAlias::class.java - ) + StubIndex.getElements( + KEY, s, project, + scope, KtTypeAlias::class.java + ) companion object { val KEY = KotlinIndexUtil.createIndexKey(KotlinTopLevelTypeAliasFqNameIndex::class.java) val INSTANCE = KotlinTopLevelTypeAliasFqNameIndex() - @JvmStatic fun getInstance() = INSTANCE + @JvmStatic + fun getInstance() = INSTANCE } } diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinTypeAliasByExpansionShortNameIndex.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinTypeAliasByExpansionShortNameIndex.kt index 806bdb85e3f..5ae410348f0 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinTypeAliasByExpansionShortNameIndex.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/KotlinTypeAliasByExpansionShortNameIndex.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.stubindex @@ -33,6 +22,7 @@ class KotlinTypeAliasByExpansionShortNameIndex : StringStubIndexExtension Boolean + @JvmStatic + fun getSubPackageFqNames( + packageFqName: FqName, + scope: GlobalSearchScope, + project: Project, + nameFilter: (Name) -> Boolean ): Collection { return SubpackagesIndexService.getInstance(project).getSubpackages(packageFqName, scope, nameFilter) } - @JvmStatic fun findFilesWithExactPackage( - packageFqName: FqName, - searchScope: GlobalSearchScope, - project: Project + @JvmStatic + fun findFilesWithExactPackage( + packageFqName: FqName, + searchScope: GlobalSearchScope, + project: Project ): Collection { return KotlinExactPackagesIndex.getInstance().get(packageFqName.asString(), project, searchScope) } - @JvmStatic fun packageExists( - packageFqName: FqName, - searchScope: GlobalSearchScope, - project: Project + @JvmStatic + fun packageExists( + packageFqName: FqName, + searchScope: GlobalSearchScope, + project: Project ): Boolean { val subpackagesIndex = SubpackagesIndexService.getInstance(project) @@ -56,18 +48,21 @@ object PackageIndexUtil { } return containsFilesWithExactPackage(packageFqName, searchScope, project) || - subpackagesIndex.hasSubpackages(packageFqName, searchScope) + subpackagesIndex.hasSubpackages(packageFqName, searchScope) } - @JvmStatic fun containsFilesWithExactPackage( - packageFqName: FqName, - searchScope: GlobalSearchScope, - project: Project + @JvmStatic + fun containsFilesWithExactPackage( + packageFqName: FqName, + searchScope: GlobalSearchScope, + project: Project ): Boolean { - val ids = StubIndex.getInstance().getContainingIds(KotlinExactPackagesIndex.getInstance().key, - packageFqName.asString(), - project, - searchScope) + val ids = StubIndex.getInstance().getContainingIds( + KotlinExactPackagesIndex.getInstance().key, + packageFqName.asString(), + project, + searchScope + ) val fs = PersistentFS.getInstance() as PersistentFSImpl while (ids.hasNext()) { val file = fs.findFileByIdIfCached(ids.next()) diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/StaticFacadeIndexUtil.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/StaticFacadeIndexUtil.kt index b6249011af3..fd50f8f074a 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/StaticFacadeIndexUtil.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/StaticFacadeIndexUtil.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.stubindex @@ -26,19 +15,22 @@ import org.jetbrains.kotlin.psi.KtFile object StaticFacadeIndexUtil { // TODO change as we introduce multi-file facades (this will require a separate index) - @JvmStatic fun findFilesForFilePart( - partFqName: FqName, - searchScope: GlobalSearchScope, - project: Project - ) : Collection = runReadAction { + @JvmStatic + fun findFilesForFilePart( + partFqName: FqName, + searchScope: GlobalSearchScope, + project: Project + ): Collection = runReadAction { PackagePartClassUtils.getFilesWithCallables( - KotlinFileFacadeFqNameIndex.INSTANCE.get(partFqName.asString(), project, searchScope)) + KotlinFileFacadeFqNameIndex.INSTANCE.get(partFqName.asString(), project, searchScope) + ) } - @JvmStatic fun getMultifileClassForPart( - partFqName: FqName, - searchScope: GlobalSearchScope, - project: Project + @JvmStatic + fun getMultifileClassForPart( + partFqName: FqName, + searchScope: GlobalSearchScope, + project: Project ): Collection = runReadAction { KotlinMultifileClassPartIndex.INSTANCE.get(partFqName.asString(), project, searchScope) } diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/SubpackagesIndexService.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/SubpackagesIndexService.kt index dfb9eace5ee..82d3aa7b935 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/SubpackagesIndexService.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/SubpackagesIndexService.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.stubindex @@ -30,12 +19,13 @@ import java.util.* class SubpackagesIndexService(private val project: Project) { private val cachedValue = CachedValuesManager.getManager(project).createCachedValue( - { - CachedValueProvider.Result( - SubpackagesIndex(KotlinExactPackagesIndex.getInstance().getAllKeys(project)), - KotlinCodeBlockModificationListener.getInstance(project).kotlinOutOfCodeBlockTracker) - }, - false + { + CachedValueProvider.Result( + SubpackagesIndex(KotlinExactPackagesIndex.getInstance().getAllKeys(project)), + KotlinCodeBlockModificationListener.getInstance(project).kotlinOutOfCodeBlockTracker + ) + }, + false ) inner class SubpackagesIndex(allPackageFqNames: Collection) { diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/resolve/StubBasedPackageMemberDeclarationProvider.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/resolve/StubBasedPackageMemberDeclarationProvider.kt index bbd99a95c8f..d4cccaddd84 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/resolve/StubBasedPackageMemberDeclarationProvider.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/stubindex/resolve/StubBasedPackageMemberDeclarationProvider.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.stubindex.resolve @@ -35,9 +24,9 @@ import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter import java.util.* class StubBasedPackageMemberDeclarationProvider( - private val fqName: FqName, - private val project: Project, - private val searchScope: GlobalSearchScope + private val fqName: FqName, + private val project: Project, + private val searchScope: GlobalSearchScope ) : PackageMemberDeclarationProvider { override fun getDeclarations(kindFilter: DescriptorKindFilter, nameFilter: (Name) -> Boolean): List { @@ -65,10 +54,10 @@ class StubBasedPackageMemberDeclarationProvider( private val declarationNames_: Set by lazy(LazyThreadSafetyMode.PUBLICATION) { FileBasedIndex.getInstance() - .getValues(KotlinPackageSourcesMemberNamesIndex.KEY, fqName.asString(), searchScope) - .flatMapTo(hashSetOf()) { - it.map { stringName -> Name.identifier(stringName).safeNameForLazyResolve() } - } + .getValues(KotlinPackageSourcesMemberNamesIndex.KEY, fqName.asString(), searchScope) + .flatMapTo(hashSetOf()) { + it.map { stringName -> Name.identifier(stringName).safeNameForLazyResolve() } + } } override fun getDeclarationNames() = declarationNames_ diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/util/ProjectRootsUtil.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/util/ProjectRootsUtil.kt index 6133de1dd3c..28e962e6598 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/util/ProjectRootsUtil.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/util/ProjectRootsUtil.kt @@ -38,7 +38,7 @@ import kotlin.script.experimental.api.ide abstract class KotlinBinaryExtension(val fileType: FileType) { companion object { val EP_NAME: ExtensionPointName = - ExtensionPointName.create("org.jetbrains.kotlin.binaryExtension") + ExtensionPointName.create("org.jetbrains.kotlin.binaryExtension") val kotlinBinaries: List by lazy(LazyThreadSafetyMode.NONE) { EP_NAME.extensions.map { it.fileType } @@ -46,10 +46,10 @@ abstract class KotlinBinaryExtension(val fileType: FileType) { } } -class JavaClassBinary: KotlinBinaryExtension(JavaClassFileType.INSTANCE) -class KotlinBuiltInBinary: KotlinBinaryExtension(KotlinBuiltInFileType) -class KotlinModuleBinary: KotlinBinaryExtension(KotlinModuleFileType.INSTANCE) -class KotlinJsMetaBinary: KotlinBinaryExtension(KotlinJavaScriptMetaFileType) +class JavaClassBinary : KotlinBinaryExtension(JavaClassFileType.INSTANCE) +class KotlinBuiltInBinary : KotlinBinaryExtension(KotlinBuiltInFileType) +class KotlinModuleBinary : KotlinBinaryExtension(KotlinModuleFileType.INSTANCE) +class KotlinJsMetaBinary : KotlinBinaryExtension(KotlinJavaScriptMetaFileType) fun FileType.isKotlinBinary(): Boolean = this in KotlinBinaryExtension.kotlinBinaries @@ -149,31 +149,30 @@ object ProjectRootsUtil { return false } - @JvmStatic fun isInContent( - element: PsiElement, - includeProjectSource: Boolean, - includeLibrarySource: Boolean, - includeLibraryClasses: Boolean, - includeScriptDependencies: Boolean, - includeScriptsOutsideSourceRoots: Boolean - ): Boolean { - return runReadAction { - val virtualFile = when (element) { - is PsiDirectory -> element.virtualFile - else -> element.containingFile?.virtualFile - } ?: return@runReadAction false + @JvmStatic + fun isInContent( + element: PsiElement, + includeProjectSource: Boolean, + includeLibrarySource: Boolean, + includeLibraryClasses: Boolean, + includeScriptDependencies: Boolean, + includeScriptsOutsideSourceRoots: Boolean + ): Boolean = runReadAction { + val virtualFile = when (element) { + is PsiDirectory -> element.virtualFile + else -> element.containingFile?.virtualFile + } ?: return@runReadAction false - val project = element.project - return@runReadAction isInContent( - project, - virtualFile, - includeProjectSource, - includeLibrarySource, - includeLibraryClasses, - includeScriptDependencies, - includeScriptsOutsideSourceRoots - ) - } + val project = element.project + return@runReadAction isInContent( + project, + virtualFile, + includeProjectSource, + includeLibrarySource, + includeLibraryClasses, + includeScriptDependencies, + includeScriptsOutsideSourceRoots + ) } @JvmOverloads diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/util/PsiPrecedences.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/util/PsiPrecedences.kt index 6b5b043671a..6617f0b2126 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/util/PsiPrecedences.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/util/PsiPrecedences.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.util @@ -29,6 +18,7 @@ object PsiPrecedences { private val LOG = Logger.getInstance(PsiPrecedences::class.java) private val precedence: Map + init { val builder = HashMap() for ((i, record) in KotlinExpressionParsing.Precedence.values().withIndex()) { @@ -53,10 +43,9 @@ object PsiPrecedences { val operation = expression.operationReference.getReferencedNameElementType() val precedenceNumber = precedence[operation] if (precedenceNumber == null) { - LOG.error("No precedence for operation: " + operation) + LOG.error("No precedence for operation: $operation") precedence.size - } - else precedenceNumber + } else precedenceNumber } else -> PRECEDENCE_OF_ATOMIC_EXPRESSION } diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/util/stringUtil.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/util/stringUtil.kt index 1edac055985..74d8d523fa6 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/util/stringUtil.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/util/stringUtil.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.util.string @@ -22,8 +11,7 @@ fun String.collapseSpaces(): String { for (c in this) { if (c.isWhitespace()) { haveSpaces = true - } - else { + } else { if (haveSpaces) { builder.append(" ") haveSpaces = false @@ -36,7 +24,7 @@ fun String.collapseSpaces(): String { // -------------------- copied from EscapeUtils.java -------------------- -private val ESCAPE_CHAR = '\\' +private const val ESCAPE_CHAR = '\\' private fun calcExpectedJoinedSize(list: Collection) = list.size - 1 + list.sumBy { it.length } @@ -51,8 +39,7 @@ fun Collection.joinWithEscape(delimiterChar: Char): String { out.append(delimiterChar) } first = false - for (i in 0 until s.length) { - val ch = s[i] + for (ch in s) { if (ch == delimiterChar || ch == ESCAPE_CHAR) { out.append(ESCAPE_CHAR) } diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/vfilefinder/IDEVirtualFileFinder.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/vfilefinder/IDEVirtualFileFinder.kt index 200235a8730..155c9da0eb5 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/vfilefinder/IDEVirtualFileFinder.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/vfilefinder/IDEVirtualFileFinder.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.vfilefinder @@ -33,8 +22,7 @@ class IDEVirtualFileFinder(private val scope: GlobalSearchScope) : VirtualFileFi return try { file.inputStream - } - catch (e: FileNotFoundException) { + } catch (e: FileNotFoundException) { null } } @@ -50,8 +38,7 @@ class IDEVirtualFileFinder(private val scope: GlobalSearchScope) : VirtualFileFi } } - override fun findVirtualFileWithHeader(classId: ClassId): VirtualFile? = - findVirtualFileWithHeader(classId, KotlinClassFileIndex.KEY) + override fun findVirtualFileWithHeader(classId: ClassId): VirtualFile? = findVirtualFileWithHeader(classId, KotlinClassFileIndex.KEY) private fun findVirtualFileWithHeader(classId: ClassId, key: ID): VirtualFile? = FileBasedIndex.getInstance().getContainingFiles(key, classId.asSingleFqName(), scope).firstOrNull() diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/vfilefinder/KotlinModuleMappingIndex.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/vfilefinder/KotlinModuleMappingIndex.kt index 0484e47154b..2ea73bb1c6f 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/vfilefinder/KotlinModuleMappingIndex.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/vfilefinder/KotlinModuleMappingIndex.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.vfilefinder @@ -42,15 +31,14 @@ object KotlinModuleMappingIndex : FileBasedIndexExtension( } private val VALUE_EXTERNALIZER = object : DataExternalizer { - override fun read(input: DataInput): PackageParts? = - PackageParts(IOUtil.readUTF(input)).apply { - val partInternalNames = IOUtil.readStringList(input) - val facadeInternalNames = IOUtil.readStringList(input) - for ((partName, facadeName) in partInternalNames zip facadeInternalNames) { - addPart(partName, if (facadeName.isNotEmpty()) facadeName else null) - } - IOUtil.readStringList(input).forEach(this::addMetadataPart) - } + override fun read(input: DataInput): PackageParts? = PackageParts(IOUtil.readUTF(input)).apply { + val partInternalNames = IOUtil.readStringList(input) + val facadeInternalNames = IOUtil.readStringList(input) + for ((partName, facadeName) in partInternalNames zip facadeInternalNames) { + addPart(partName, if (facadeName.isNotEmpty()) facadeName else null) + } + IOUtil.readStringList(input).forEach(this::addMetadataPart) + } override fun save(out: DataOutput, value: PackageParts) { IOUtil.writeUTF(out, value.packageFqName) @@ -68,8 +56,9 @@ object KotlinModuleMappingIndex : FileBasedIndexExtension( override fun getValueExternalizer() = VALUE_EXTERNALIZER - override fun getInputFilter(): FileBasedIndex.InputFilter = - FileBasedIndex.InputFilter { file -> file.extension == ModuleMapping.MAPPING_FILE_EXT } + override fun getInputFilter(): FileBasedIndex.InputFilter = FileBasedIndex.InputFilter { file -> + file.extension == ModuleMapping.MAPPING_FILE_EXT + } override fun getVersion(): Int = 5 diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/vfilefinder/fileIndexes.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/vfilefinder/fileIndexes.kt index f2e0bbc5930..65ce04bfc24 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/vfilefinder/fileIndexes.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/vfilefinder/fileIndexes.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.vfilefinder @@ -41,7 +30,7 @@ import java.util.* abstract class KotlinFileIndexBase(classOfIndex: Class) : ScalarIndexExtension() { val KEY: ID = ID.create(classOfIndex.canonicalName) - private val KEY_DESCRIPTOR : KeyDescriptor = object : KeyDescriptor { + private val KEY_DESCRIPTOR: KeyDescriptor = object : KeyDescriptor { override fun save(output: DataOutput, value: FqName) = IOUtil.writeUTF(output, value.asString()) override fun read(input: DataInput) = FqName(IOUtil.readUTF(input)) @@ -60,26 +49,24 @@ abstract class KotlinFileIndexBase(classOfIndex: Class) : ScalarIndexExten override fun getKeyDescriptor() = KEY_DESCRIPTOR protected fun indexer(f: (FileContent) -> FqName?): DataIndexer = - // See KT-11323 - DataIndexer { - try { - val fqName = f(it) - if (fqName != null) { - Collections.singletonMap(fqName, null) - } - else { - emptyMap() - } - } - catch (e: Throwable) { - LOG.warn("Error while indexing file " + it.fileName, e) + // See KT-11323 + DataIndexer { + try { + val fqName = f(it) + if (fqName != null) { + Collections.singletonMap(fqName, null) + } else { emptyMap() } + } catch (e: Throwable) { + LOG.warn("Error while indexing file " + it.fileName, e) + emptyMap() } + } } fun KotlinFileIndexBase.hasSomethingInPackage(fqName: FqName, scope: GlobalSearchScope): Boolean = - !FileBasedIndex.getInstance().processValues(name, fqName, null, { _, _ -> false }, scope) + !FileBasedIndex.getInstance().processValues(name, fqName, null, { _, _ -> false }, scope) object KotlinClassFileIndex : KotlinFileIndexBase(KotlinClassFileIndex::class.java) { @@ -89,7 +76,7 @@ object KotlinClassFileIndex : KotlinFileIndexBase(KotlinCl override fun getVersion() = VERSION - private val VERSION = 3 + private const val VERSION = 3 private val INDEXER = indexer { fileContent -> val headerInfo = IDEKotlinBinaryClassCache.getInstance().getKotlinBinaryClassHeaderData(fileContent.file, fileContent.content) @@ -105,18 +92,18 @@ object KotlinJavaScriptMetaFileIndex : KotlinFileIndexBase val stream = ByteArrayInputStream(fileContent.content) if (JsMetadataVersion.readFrom(stream).isCompatible()) { FqName(JsProtoBuf.Header.parseDelimitedFrom(stream).packageFqName) - } - else null + } else null } } -open class KotlinMetadataFileIndexBase(classOfIndex: Class, indexFunction: (ClassId) -> FqName) : KotlinFileIndexBase(classOfIndex) { +open class KotlinMetadataFileIndexBase(classOfIndex: Class, indexFunction: (ClassId) -> FqName) : + KotlinFileIndexBase(classOfIndex) { override fun getIndexer() = INDEXER override fun getInputFilter() = FileBasedIndex.InputFilter { file -> file.fileType == KotlinBuiltInFileType } @@ -126,21 +113,29 @@ open class KotlinMetadataFileIndexBase(classOfIndex: Class, indexFunction: private val VERSION = 1 private val INDEXER = indexer { fileContent -> - if (fileContent.fileType == KotlinBuiltInFileType && fileContent.fileName.endsWith(MetadataPackageFragment.DOT_METADATA_FILE_EXTENSION)) { + if (fileContent.fileType == KotlinBuiltInFileType && + fileContent.fileName.endsWith(MetadataPackageFragment.DOT_METADATA_FILE_EXTENSION) + ) { val builtins = BuiltInDefinitionFile.read(fileContent.content, fileContent.file.parent) (builtins as? BuiltInDefinitionFile)?.let { builtinDefFile -> val proto = builtinDefFile.proto proto.class_List.singleOrNull()?.let { cls -> indexFunction(builtinDefFile.nameResolver.getClassId(cls.fqName)) - } ?: indexFunction(ClassId(builtinDefFile.packageFqName, - Name.identifier(fileContent.fileName.substringBeforeLast(MetadataPackageFragment.DOT_METADATA_FILE_EXTENSION)))) + } ?: indexFunction( + ClassId( + builtinDefFile.packageFqName, + Name.identifier(fileContent.fileName.substringBeforeLast(MetadataPackageFragment.DOT_METADATA_FILE_EXTENSION)) + ) + ) } } else null } } object KotlinMetadataFileIndex : KotlinMetadataFileIndexBase( - KotlinMetadataFileIndex::class.java, ClassId::asSingleFqName) + KotlinMetadataFileIndex::class.java, ClassId::asSingleFqName +) object KotlinMetadataFilePackageIndex : KotlinMetadataFileIndexBase( - KotlinMetadataFilePackageIndex::class.java, ClassId::getPackageFqName) + KotlinMetadataFilePackageIndex::class.java, ClassId::getPackageFqName +) diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/plugin/references/SimpleNameReferenceExtension.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/plugin/references/SimpleNameReferenceExtension.kt index a45daa1d86f..3cd47fd97f1 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/plugin/references/SimpleNameReferenceExtension.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/plugin/references/SimpleNameReferenceExtension.kt @@ -1,30 +1,19 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.plugin.references import com.intellij.openapi.extensions.ExtensionPointName -import org.jetbrains.kotlin.idea.references.KtSimpleNameReference import com.intellij.psi.PsiElement +import org.jetbrains.kotlin.idea.references.KtSimpleNameReference import org.jetbrains.kotlin.psi.KtPsiFactory interface SimpleNameReferenceExtension { companion object { val EP_NAME: ExtensionPointName = - ExtensionPointName.create("org.jetbrains.kotlin.simpleNameReferenceExtension") + ExtensionPointName.create("org.jetbrains.kotlin.simpleNameReferenceExtension") } fun isReferenceTo(reference: KtSimpleNameReference, element: PsiElement): Boolean diff --git a/idea/idea-android/idea-android-output-parser/src/org/jetbrains/kotlin/android/KotlinOutputParserHelper.kt b/idea/idea-android/idea-android-output-parser/src/org/jetbrains/kotlin/android/KotlinOutputParserHelper.kt index ef17be84f86..33ddaa10d83 100644 --- a/idea/idea-android/idea-android-output-parser/src/org/jetbrains/kotlin/android/KotlinOutputParserHelper.kt +++ b/idea/idea-android/idea-android-output-parser/src/org/jetbrains/kotlin/android/KotlinOutputParserHelper.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.android @@ -63,8 +52,7 @@ fun parse(lineText: String, reader: OutputLineReader, messages: MutableList= 0 && substring(0, colonIndex1).startsWithSeverityPrefix()) // Next Kotlin message - || StringUtil.containsIgnoreCase(this, "FAILURE") - || StringUtil.containsIgnoreCase(this, "FAILED") + || (colonIndex1 >= 0 && substring(0, colonIndex1).startsWithSeverityPrefix()) // Next Kotlin message + || StringUtil.containsIgnoreCase(this, "FAILURE") + || StringUtil.containsIgnoreCase(this, "FAILED") } private fun String.startsWithSeverityPrefix() = getMessageKind(this) != Message.Kind.UNKNOWN @@ -130,7 +117,7 @@ private fun Int.skipDriveOnWin(line: String): Int { } private val KAPT_ERROR_WHILE_ANNOTATION_PROCESSING_MARKER_TEXT = - KaptError::class.java.canonicalName + ": " + KaptError.Kind.ERROR_RAISED.message + KaptError::class.java.canonicalName + ": " + KaptError.Kind.ERROR_RAISED.message private fun isKaptErrorWhileAnnotationProcessing(message: Message): Boolean { if (message.kind != Message.Kind.ERROR) return false @@ -138,7 +125,7 @@ private fun isKaptErrorWhileAnnotationProcessing(message: Message): Boolean { val messageText = message.text return messageText.startsWith(IllegalStateException::class.java.name) - && messageText.contains(KAPT_ERROR_WHILE_ANNOTATION_PROCESSING_MARKER_TEXT) + && messageText.contains(KAPT_ERROR_WHILE_ANNOTATION_PROCESSING_MARKER_TEXT) } private fun addMessage(message: Message, messages: MutableList): Boolean { diff --git a/idea/idea-android/src/org/jetbrains/kotlin/android/AndroidResourceReferenceAnnotator.kt b/idea/idea-android/src/org/jetbrains/kotlin/android/AndroidResourceReferenceAnnotator.kt index 8cedcb81250..2f2e34812ea 100644 --- a/idea/idea-android/src/org/jetbrains/kotlin/android/AndroidResourceReferenceAnnotator.kt +++ b/idea/idea-android/src/org/jetbrains/kotlin/android/AndroidResourceReferenceAnnotator.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.android @@ -45,11 +34,13 @@ class AndroidResourceReferenceAnnotator : Annotator { val referenceType = referenceTarget.getResourceReferenceType() val configuration = pickConfiguration(androidFacet, androidFacet.module, element.containingFile) ?: return - val resourceValue = findResourceValue(resourceType, - reference.text, - referenceType == FRAMEWORK, - androidFacet.module, - configuration) ?: return + val resourceValue = findResourceValue( + resourceType, + reference.text, + referenceType == FRAMEWORK, + androidFacet.module, + configuration + ) ?: return val resourceResolver = configuration.resourceResolver ?: return @@ -59,8 +50,7 @@ class AndroidResourceReferenceAnnotator : Annotator { val annotation = holder.createInfoAnnotation(element, null) annotation.gutterIconRenderer = ColorRenderer(element, color) } - } - else { + } else { var file = ResourceHelper.resolveDrawable(resourceResolver, resourceValue, element.project) if (file != null && file.path.endsWith(SdkConstants.DOT_XML)) { file = pickBitmapFromXml(file, resourceResolver, element.project) @@ -74,5 +64,5 @@ class AndroidResourceReferenceAnnotator : Annotator { } private fun KtReferenceExpression.getResourceReferenceTargetDescriptor(): JavaPropertyDescriptor? = - resolveToCall()?.resultingDescriptor as? JavaPropertyDescriptor + resolveToCall()?.resultingDescriptor as? JavaPropertyDescriptor } diff --git a/idea/idea-android/src/org/jetbrains/kotlin/android/AndroidUtil.kt b/idea/idea-android/src/org/jetbrains/kotlin/android/AndroidUtil.kt index d78c4394d69..dd856c89118 100644 --- a/idea/idea-android/src/org/jetbrains/kotlin/android/AndroidUtil.kt +++ b/idea/idea-android/src/org/jetbrains/kotlin/android/AndroidUtil.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.android @@ -86,8 +75,7 @@ internal fun JavaPropertyDescriptor.getResourceReferenceType(): AndroidPsiUtils. if (R_CLASS == rClass.name.asString()) { return if ((rClass.containingDeclaration as? PackageFragmentDescriptor)?.fqName?.asString() == ANDROID_PKG) { FRAMEWORK - } - else { + } else { APP } } @@ -95,11 +83,13 @@ internal fun JavaPropertyDescriptor.getResourceReferenceType(): AndroidPsiUtils. return NONE } -internal fun getReferredResourceOrManifestField(facet: AndroidFacet, expression: KtSimpleNameExpression, localOnly: Boolean) - = getReferredResourceOrManifestField(facet, expression, null, localOnly) +internal fun getReferredResourceOrManifestField(facet: AndroidFacet, expression: KtSimpleNameExpression, localOnly: Boolean) = + getReferredResourceOrManifestField(facet, expression, null, localOnly) -internal fun getReferredResourceOrManifestField(facet: AndroidFacet, expression: KtSimpleNameExpression, - className: String?, localOnly: Boolean): AndroidResourceUtil.MyReferredResourceFieldInfo? { +internal fun getReferredResourceOrManifestField( + facet: AndroidFacet, expression: KtSimpleNameExpression, + className: String?, localOnly: Boolean +): AndroidResourceUtil.MyReferredResourceFieldInfo? { val resFieldName = expression.getReferencedName() val resClassReference = expression.getPreviousInQualifiedChain() as? KtSimpleNameExpression ?: return null val resClassName = resClassReference.getReferencedName() @@ -110,7 +100,7 @@ internal fun getReferredResourceOrManifestField(facet: AndroidFacet, expression: val rClassReference = resClassReference.getPreviousInQualifiedChain() as? KtSimpleNameExpression ?: return null val rClassDescriptor = rClassReference.analyze(BodyResolveMode.PARTIAL) - .get(BindingContext.REFERENCE_TARGET, rClassReference) as? ClassDescriptor ?: return null + .get(BindingContext.REFERENCE_TARGET, rClassReference) as? ClassDescriptor ?: return null val rClassShortName = rClassDescriptor.name.asString() val fromManifest = AndroidUtils.MANIFEST_CLASS_NAME == rClassShortName diff --git a/idea/idea-android/src/org/jetbrains/kotlin/android/KotlinAndroidLineMarkerProvider.kt b/idea/idea-android/src/org/jetbrains/kotlin/android/KotlinAndroidLineMarkerProvider.kt index 09d7d37e255..c9c9ee33ffc 100644 --- a/idea/idea-android/src/org/jetbrains/kotlin/android/KotlinAndroidLineMarkerProvider.kt +++ b/idea/idea-android/src/org/jetbrains/kotlin/android/KotlinAndroidLineMarkerProvider.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.android @@ -62,24 +51,26 @@ class KotlinAndroidLineMarkerProvider : LineMarkerProvider { } return LineMarkerInfo( - nameIdentifier, - nameIdentifier.textRange, - AllIcons.FileTypes.Xml, - Pass.LINE_MARKERS, - Function { "Related XML file" }, - GutterIconNavigationHandler { e: MouseEvent, _: PsiElement -> - NavigationUtil - .getRelatedItemsPopup( - manifestItems + collectGoToRelatedLayoutItems(androidFacet), - "Go to Related Files") - .show(RelativePoint(e)) - }, - GutterIconRenderer.Alignment.RIGHT) + nameIdentifier, + nameIdentifier.textRange, + AllIcons.FileTypes.Xml, + Pass.LINE_MARKERS, + Function { "Related XML file" }, + GutterIconNavigationHandler { e: MouseEvent, _: PsiElement -> + NavigationUtil + .getRelatedItemsPopup( + manifestItems + collectGoToRelatedLayoutItems(androidFacet), + "Go to Related Files" + ) + .show(RelativePoint(e)) + }, + GutterIconRenderer.Alignment.RIGHT + ) } private fun KtClass.collectGoToRelatedLayoutItems(androidFacet: AndroidFacet): List { val resources = mutableSetOf() - accept(object: KtVisitorVoid() { + accept(object : KtVisitorVoid() { override fun visitKtElement(element: KtElement) { element.acceptChildren(this) } @@ -96,11 +87,8 @@ class KotlinAndroidLineMarkerProvider : LineMarkerProvider { return } - val files = ModuleResourceManagers - .getInstance(androidFacet) - .localResourceManager - .findResourcesByFieldName(resClassName, info.fieldName) - .filterIsInstance() + val files = ModuleResourceManagers.getInstance(androidFacet).localResourceManager + .findResourcesByFieldName(resClassName, info.fieldName).filterIsInstance() resources.addAll(files) } @@ -110,7 +98,7 @@ class KotlinAndroidLineMarkerProvider : LineMarkerProvider { } private fun KtClass.collectGoToRelatedManifestItems(manifest: Manifest): List = - findComponentDeclarationInManifest(manifest)?.xmlAttributeValue?.let { listOf(GotoManifestItem(it)) } ?: emptyList() + findComponentDeclarationInManifest(manifest)?.xmlAttributeValue?.let { listOf(GotoManifestItem(it)) } ?: emptyList() private class GotoManifestItem(attributeValue: XmlAttributeValue) : GotoRelatedItem(attributeValue) { override fun getCustomName(): String? = "AndroidManifest.xml" @@ -124,10 +112,11 @@ class KotlinAndroidLineMarkerProvider : LineMarkerProvider { companion object { private val CLASSES_WITH_LAYOUT_XML = arrayOf( - SdkConstants.CLASS_ACTIVITY, - SdkConstants.CLASS_FRAGMENT, - SdkConstants.CLASS_V4_FRAGMENT, - "android.widget.Adapter") + SdkConstants.CLASS_ACTIVITY, + SdkConstants.CLASS_FRAGMENT, + SdkConstants.CLASS_V4_FRAGMENT, + "android.widget.Adapter" + ) private fun KtClass.isClassWithLayoutXml(): Boolean { val type = (unsafeResolveToDescriptor(BodyResolveMode.PARTIAL) as? ClassDescriptor)?.defaultType ?: return false diff --git a/idea/idea-android/src/org/jetbrains/kotlin/android/ParcelableUtil.kt b/idea/idea-android/src/org/jetbrains/kotlin/android/ParcelableUtil.kt index b3ea233794f..125cf811be2 100644 --- a/idea/idea-android/src/org/jetbrains/kotlin/android/ParcelableUtil.kt +++ b/idea/idea-android/src/org/jetbrains/kotlin/android/ParcelableUtil.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.android @@ -44,8 +33,7 @@ import org.jetbrains.kotlin.types.KotlinType private val CREATOR_NAME = "CREATOR" private val PARCEL_NAME = "parcel" -private val CREATOR_TEXT = - "companion object $CREATOR_NAME : android.os.Parcelable.Creator<%1\$s> {\n" + +private val CREATOR_TEXT = "companion object $CREATOR_NAME : android.os.Parcelable.Creator<%1\$s> {\n" + " override fun createFromParcel($PARCEL_NAME: $CLASS_PARCEL): %1\$s {\n" + " return %1\$s($PARCEL_NAME)\n" + " }\n\n" + @@ -56,7 +44,7 @@ private val CREATOR_TEXT = private val WRITE_TO_PARCEL_TEXT = "override fun writeToParcel($PARCEL_NAME: $CLASS_PARCEL, flags: Int) {\n}" private val WRITE_TO_PARCEL_SUPER_CALL_TEXT = "super.writeToParcel($PARCEL_NAME, flags)" private val WRITE_TO_PARCEL_WITH_SUPER_TEXT = - "override fun writeToParcel($PARCEL_NAME: $CLASS_PARCEL, flags: Int) {\n$WRITE_TO_PARCEL_SUPER_CALL_TEXT\n}" + "override fun writeToParcel($PARCEL_NAME: $CLASS_PARCEL, flags: Int) {\n$WRITE_TO_PARCEL_SUPER_CALL_TEXT\n}" private val DESCRIBE_CONTENTS_TEXT = "override fun describeContents(): Int {\nreturn 0\n}" private val CONSTRUCTOR_TEXT = "constructor($PARCEL_NAME: $CLASS_PARCEL)" @@ -65,8 +53,7 @@ private val PARCELIZE_FQNAME = FqName(Parcelize::class.java.name) //TODO add test fun KtClass.isParcelize() = findAnnotation(PARCELIZE_FQNAME) != null -fun KtClass.canAddParcelable(): Boolean = - findParcelableSupertype() == null +fun KtClass.canAddParcelable(): Boolean = findParcelableSupertype() == null || findCreator() == null || findConstructorFromParcel() == null || findWriteToParcel() == null @@ -74,8 +61,7 @@ fun KtClass.canAddParcelable(): Boolean = fun KtClass.canRedoParcelable(): Boolean = canRemoveParcelable() -fun KtClass.canRemoveParcelable(): Boolean = - findParcelableSupertype()?.takeIf { it.typeReference?.isParcelableReference() ?: false } +fun KtClass.canRemoveParcelable(): Boolean = findParcelableSupertype()?.takeIf { it.typeReference?.isParcelableReference() ?: false } ?: findCreator() ?: findConstructorFromParcel() ?: findWriteToParcel() @@ -130,7 +116,7 @@ private fun KtClass.findParcelableSupertype(): KtSuperTypeListEntry? = getSuperT private fun KtSuperTypeList.findParcelable() = entries?.find { it.typeReference?.isParcelableSuccessorReference() ?: false } private fun KtTypeReference.isParcelableSuccessorReference() = - analyze(BodyResolveMode.PARTIAL)[BindingContext.TYPE, this]?.isSubclassOfParcelable() ?: false + analyze(BodyResolveMode.PARTIAL)[BindingContext.TYPE, this]?.isSubclassOfParcelable() ?: false private fun KtClass.superExtendsParcelable() = superTypeListEntries.find { it.typeReference?.extendsParcelable() ?: false } != null @@ -161,7 +147,8 @@ private fun KtExpression.isReadFromParcelPropertyAssignment(): Boolean { private fun KtExpression.isReadFromParcel(): Boolean { val reference = firstChild as? KtReferenceExpression - ?: (firstChild as? KtDotQualifiedExpression)?.getLeftMostReceiverExpression() as? KtReferenceExpression ?: return false + ?: (firstChild as? KtDotQualifiedExpression)?.getLeftMostReceiverExpression() as? KtReferenceExpression + ?: return false val target = reference.resolveToCall()?.resultingDescriptor ?: return false return (target as? ParameterDescriptor)?.type?.fqNameEquals(CLASS_PARCEL) ?: false } @@ -174,21 +161,17 @@ private fun KtClass.addFieldWrites(function: KtFunction, factory: KtPsiFactory, val propertyParameterDescriptors = primaryConstructor?.valueParameters?.mapNotNull { it.propertyDescriptor } ?: emptyList() - val propertyDescriptors = declarations - .filter { it.isParcelableProperty() } - .mapNotNull { it.descriptor as? PropertyDescriptor } + val propertyDescriptors = declarations.filter { it.isParcelableProperty() }.mapNotNull { it.descriptor as? PropertyDescriptor } val parcelName = function.valueParameters[0].name ?: return val flagsName = function.valueParameters[1].name ?: return - val blockText = - (propertyParameterDescriptors + propertyDescriptors) - .mapNotNull { it.formatWriteToParcel(parcelName, flagsName) } - .joinToString(separator = "\n") + val blockText = (propertyParameterDescriptors + propertyDescriptors).mapNotNull { it.formatWriteToParcel(parcelName, flagsName) } + .joinToString(separator = "\n") val block = factory.createBlock( - if (callSuper) - WRITE_TO_PARCEL_SUPER_CALL_TEXT + if (blockText.isNotBlank()) "\n$blockText" else "" - else blockText + if (callSuper) + WRITE_TO_PARCEL_SUPER_CALL_TEXT + if (blockText.isNotBlank()) "\n$blockText" else "" + else blockText ) bodyExpression.replace(block) @@ -201,16 +184,14 @@ private fun KtClass.addFieldReads(constructor: KtConstructor<*>, factory: KtPsiF } val parcelName = constructor.getValueParameters().firstOrNull()?.name ?: return - val parcelableProperties = declarations - .filter { it.isParcelableProperty() } - .mapNotNull { it.descriptor as? PropertyDescriptor } + val parcelableProperties = declarations.filter { it.isParcelableProperty() }.mapNotNull { it.descriptor as? PropertyDescriptor } if (parcelableProperties.isEmpty()) { return } - val blockText = parcelableProperties - .mapNotNull { descriptor -> descriptor.formatReadFromParcel(parcelName)?.let { "${descriptor.name} = $it" } } + val blockText = + parcelableProperties.mapNotNull { descriptor -> descriptor.formatReadFromParcel(parcelName)?.let { "${descriptor.name} = $it" } } .joinToString(separator = "\n") val block = factory.createBlock(blockText) @@ -222,32 +203,28 @@ private fun KtClass.addFieldReads(constructor: KtConstructor<*>, factory: KtPsiF addNewLineBeforeDeclaration() addToShorteningWaitSet() } - } - else { + } else { bodyExpression?.replace(block) ?: constructor.add(block) } } -private fun KtDeclaration.isParcelableProperty(): Boolean = - this is KtProperty && isVar && !hasDelegate() && !isTransient() && getter == null && setter == null +private fun KtDeclaration.isParcelableProperty(): Boolean = + this is KtProperty && isVar && !hasDelegate() && !isTransient() && getter == null && setter == null private fun KtProperty.isTransient() = annotationEntries.find { it.isTransientAnnotation() } != null private fun KtAnnotationEntry.isTransientAnnotation(): Boolean = typeReference?.analyze(BodyResolveMode.PARTIAL)?.get(BindingContext.TYPE, typeReference)?.fqNameEquals("kotlin.jvm.Transient") ?: false -private fun KtExpression.isCallToSuperWriteToParcel() = - this is KtDotQualifiedExpression +private fun KtExpression.isCallToSuperWriteToParcel() = this is KtDotQualifiedExpression && receiverExpression is KtSuperExpression && (selectorExpression as? KtCallExpression)?.calleeExpression?.text == "writeToParcel" -private fun KtBlockExpression.isEmptyWriteToParcel(callSuper: Boolean): Boolean = - if (callSuper) { - statements.isEmpty() || statements.size == 1 && statements.first().isCallToSuperWriteToParcel() - } - else { - statements.isEmpty() - } +private fun KtBlockExpression.isEmptyWriteToParcel(callSuper: Boolean): Boolean = if (callSuper) { + statements.isEmpty() || statements.size == 1 && statements.first().isCallToSuperWriteToParcel() +} else { + statements.isEmpty() +} private fun PropertyDescriptor.formatReadFromParcel(parcelName: String): String? { val type = returnType ?: return null @@ -301,8 +278,7 @@ private fun PropertyDescriptor.formatWriteToParcel(parcelName: String, flagsName if (type.isMarkedNullable) { if (KotlinBuiltIns.isPrimitiveTypeOrNullablePrimitiveType(type)) { return "$parcelName.writeValue($name)" - } - else if (KotlinBuiltIns.isCharSequenceOrNullableCharSequence(type)) { + } else if (KotlinBuiltIns.isCharSequenceOrNullableCharSequence(type)) { return "$parcelName.writeString($name?.toString())" } } @@ -373,26 +349,26 @@ private fun KtClass.createSecondaryConstructor(factory: KtPsiFactory): KtConstru } val argumentList = arguments.joinToString( - prefix = if (arguments.size > 1) "(\n" else "(", - postfix = ")", - separator = if (arguments.size > 1) ",\n" else ", ") + prefix = if (arguments.size > 1) "(\n" else "(", + postfix = ")", + separator = if (arguments.size > 1) ",\n" else ", " + ) "$CONSTRUCTOR_TEXT :this$argumentList {\n}" } ?: "$CONSTRUCTOR_TEXT {\n}" - val constructor = factory.createSecondaryConstructor(constructorText) + val constructor = factory.createSecondaryConstructor(constructorText) val lastProperty = declarations.findLast { it is KtProperty } return if (lastProperty != null) { addDeclarationAfter(constructor, lastProperty).apply { addNewLineBeforeDeclaration() } - } - else { + } else { val firstFunction = declarations.find { it is KtFunction } addDeclarationBefore(constructor, firstFunction).apply { addNewLineBeforeDeclaration() } } } private fun KtTypeReference.extendsParcelable(): Boolean = - analyze(BodyResolveMode.PARTIAL)[BindingContext.TYPE, this]?.isSubclassOfParcelable(true) ?: false + analyze(BodyResolveMode.PARTIAL)[BindingContext.TYPE, this]?.isSubclassOfParcelable(true) ?: false private fun KtClass.findWriteToParcel() = declarations.find { it.isWriteToParcel() } @@ -415,8 +391,8 @@ private fun KtClass.findOrCreateWriteToParcel(factory: KtPsiFactory, callSuper: private fun KtClass.findDescribeContents() = declarations.find { it.isDescribeContents() } private fun KtDeclaration.isDescribeContents(): Boolean = this is KtFunction && - name == "describeContents" && - valueParameters.isEmpty() + name == "describeContents" && + valueParameters.isEmpty() private fun KtClass.findOrCreateDescribeContents(factory: KtPsiFactory): KtFunction { findDescribeContents()?.let { @@ -442,7 +418,7 @@ private fun KtParameter.isParcelParameter(): Boolean = typeReference?.fqNameEqua private fun KtTypeReference.isParcelableReference() = fqNameEquals(CLASS_PARCELABLE) private fun KtTypeReference.fqNameEquals(fqName: String) = - analyze(BodyResolveMode.PARTIAL)[BindingContext.TYPE, this]?.fqNameEquals(fqName) ?: false + analyze(BodyResolveMode.PARTIAL)[BindingContext.TYPE, this]?.fqNameEquals(fqName) ?: false private fun KotlinType.getName() = constructor.declarationDescriptor?.name @@ -453,25 +429,25 @@ private fun KotlinType.isSubclassOfParcelable(strict: Boolean = false): Boolean private fun KotlinType.isIBinder(): Boolean = fqNameEquals("android.os.IBinder") private fun KotlinType.isArrayOfParcelable(): Boolean = - KotlinBuiltIns.isArray(this) && arguments.singleOrNull()?.type?.isSubclassOfParcelable(true) ?: false + KotlinBuiltIns.isArray(this) && arguments.singleOrNull()?.type?.isSubclassOfParcelable(true) ?: false private fun KotlinType.isArrayOfIBinder(): Boolean = - KotlinBuiltIns.isArray(this) && arguments.singleOrNull()?.type?.isIBinder() ?: false + KotlinBuiltIns.isArray(this) && arguments.singleOrNull()?.type?.isIBinder() ?: false private fun KotlinType.isArrayOfString(): Boolean = - KotlinBuiltIns.isArray(this) && KotlinBuiltIns.isStringOrNullableString(arguments.singleOrNull()?.type) + KotlinBuiltIns.isArray(this) && KotlinBuiltIns.isStringOrNullableString(arguments.singleOrNull()?.type) private fun KotlinType.isListOfString(): Boolean = - KotlinBuiltIns.isListOrNullableList(this) && KotlinBuiltIns.isStringOrNullableString(arguments.singleOrNull()?.type) + KotlinBuiltIns.isListOrNullableList(this) && KotlinBuiltIns.isStringOrNullableString(arguments.singleOrNull()?.type) private fun KotlinType.isListOfParcelable(): Boolean = - KotlinBuiltIns.isListOrNullableList(this) && arguments.singleOrNull()?.type?.isSubclassOfParcelable(true) ?: false + KotlinBuiltIns.isListOrNullableList(this) && arguments.singleOrNull()?.type?.isSubclassOfParcelable(true) ?: false private fun KotlinType.isListOfIBinder(): Boolean = - KotlinBuiltIns.isListOrNullableList(this) && arguments.singleOrNull()?.type?.isIBinder() ?: false + KotlinBuiltIns.isListOrNullableList(this) && arguments.singleOrNull()?.type?.isIBinder() ?: false private fun KotlinType.isSparseBooleanArray(): Boolean = fqNameEquals("android.util.SparseBooleanArray") private fun KotlinType.isBundle(): Boolean = fqNameEquals("android.os.Bundle") -private fun T.addNewLineBeforeDeclaration() = parent.addBefore(KtPsiFactory(this).createNewLine(), this) \ No newline at end of file +private fun T.addNewLineBeforeDeclaration() = parent.addBefore(KtPsiFactory(this).createNewLine(), this) \ No newline at end of file diff --git a/idea/idea-android/src/org/jetbrains/kotlin/android/configure/AndroidGradleModelFacade.kt b/idea/idea-android/src/org/jetbrains/kotlin/android/configure/AndroidGradleModelFacade.kt index 66844edbb00..525f982b037 100644 --- a/idea/idea-android/src/org/jetbrains/kotlin/android/configure/AndroidGradleModelFacade.kt +++ b/idea/idea-android/src/org/jetbrains/kotlin/android/configure/AndroidGradleModelFacade.kt @@ -1,5 +1,5 @@ /* - * Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -56,8 +56,8 @@ class AndroidGradleModelFacade : KotlinGradleModelFacade { // com.android.builder.model.Library.getProject() is not present in 2.1.0 private val Library.projectSafe: String? - get() = try { - project - } catch(e: UnsupportedMethodException) { - null - } \ No newline at end of file + get() = try { + project + } catch (e: UnsupportedMethodException) { + null + } \ No newline at end of file diff --git a/idea/idea-android/src/org/jetbrains/kotlin/android/configure/KotlinAndroidGradleLibraryDataService.kt b/idea/idea-android/src/org/jetbrains/kotlin/android/configure/KotlinAndroidGradleLibraryDataService.kt index 4988b342bd8..1c0f518c235 100644 --- a/idea/idea-android/src/org/jetbrains/kotlin/android/configure/KotlinAndroidGradleLibraryDataService.kt +++ b/idea/idea-android/src/org/jetbrains/kotlin/android/configure/KotlinAndroidGradleLibraryDataService.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.android.configure @@ -37,10 +26,10 @@ class KotlinAndroidGradleLibraryDataService : AbstractProjectDataService>, - projectData: ProjectData?, - project: Project, - modelsProvider: IdeModifiableModelsProvider + toImport: MutableCollection>, + projectData: ProjectData?, + project: Project, + modelsProvider: IdeModifiableModelsProvider ) { for (dataNode in toImport) { @Suppress("UNCHECKED_CAST") diff --git a/idea/idea-android/src/org/jetbrains/kotlin/android/configure/KotlinAndroidGradleMPPModuleDataService.kt b/idea/idea-android/src/org/jetbrains/kotlin/android/configure/KotlinAndroidGradleMPPModuleDataService.kt index 114fb82b9ba..8e6bdd7ee39 100644 --- a/idea/idea-android/src/org/jetbrains/kotlin/android/configure/KotlinAndroidGradleMPPModuleDataService.kt +++ b/idea/idea-android/src/org/jetbrains/kotlin/android/configure/KotlinAndroidGradleMPPModuleDataService.kt @@ -1,5 +1,5 @@ /* - * Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -91,11 +91,13 @@ class KotlinAndroidGradleMPPModuleDataService : AbstractProjectDataService val module = modelsProvider.findIdeModule(node.data) ?: return diff --git a/idea/idea-android/src/org/jetbrains/kotlin/android/configure/KotlinAndroidGradleModuleConfigurator.kt b/idea/idea-android/src/org/jetbrains/kotlin/android/configure/KotlinAndroidGradleModuleConfigurator.kt index 4fbb8125914..c105fb4309c 100644 --- a/idea/idea-android/src/org/jetbrains/kotlin/android/configure/KotlinAndroidGradleModuleConfigurator.kt +++ b/idea/idea-android/src/org/jetbrains/kotlin/android/configure/KotlinAndroidGradleModuleConfigurator.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -44,8 +44,7 @@ class KotlinAndroidGradleModuleConfigurator internal constructor() : KotlinWithG val jvmTarget = getJvmTarget(sdk, version) return if (isTopLevelProjectFile) { manipulator.configureProjectBuildScript(kotlinPluginName, version) - } - else { + } else { manipulator.configureModuleBuildScript( kotlinPluginName, getKotlinPluginExpression(file.isKtDsl()), diff --git a/idea/idea-android/src/org/jetbrains/kotlin/android/debugger/AndroidDexerImpl.kt b/idea/idea-android/src/org/jetbrains/kotlin/android/debugger/AndroidDexerImpl.kt index 40c99f83900..cf1278d986e 100644 --- a/idea/idea-android/src/org/jetbrains/kotlin/android/debugger/AndroidDexerImpl.kt +++ b/idea/idea-android/src/org/jetbrains/kotlin/android/debugger/AndroidDexerImpl.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.android.debugger @@ -30,23 +19,26 @@ import java.net.URLClassLoader import java.security.ProtectionDomain class AndroidDexerImpl(val project: Project) : AndroidDexer { - private val cachedDexWrapper = CachedValuesManager.getManager(project).createCachedValue({ - val dexWrapper = doGetAndroidDexFile()?.let { dexJarFile -> - val androidDexWrapperName = AndroidDexWrapper::class.java.canonicalName - val classBytes = this.javaClass.classLoader.getResource( - androidDexWrapperName.replace('.', '/') + ".class").readBytes() + private val cachedDexWrapper = CachedValuesManager.getManager(project).createCachedValue( + { + val dexWrapper = doGetAndroidDexFile()?.let { dexJarFile -> + val androidDexWrapperName = AndroidDexWrapper::class.java.canonicalName + val classBytes = this.javaClass.classLoader.getResource( + androidDexWrapperName.replace('.', '/') + ".class" + ).readBytes() - val dexClassLoader = object : URLClassLoader(arrayOf(dexJarFile.toURI().toURL()), this::class.java.classLoader) { - init { - defineClass(androidDexWrapperName, classBytes, 0, classBytes.size, null as ProtectionDomain?) + val dexClassLoader = object : URLClassLoader(arrayOf(dexJarFile.toURI().toURL()), this::class.java.classLoader) { + init { + defineClass(androidDexWrapperName, classBytes, 0, classBytes.size, null as ProtectionDomain?) + } } + + Class.forName(androidDexWrapperName, true, dexClassLoader).newInstance() } - Class.forName(androidDexWrapperName, true, dexClassLoader).newInstance() - } - - CachedValueProvider.Result.createSingleDependency(dexWrapper, ProjectRootModificationTracker.getInstance(project)) - }, /* trackValue = */ false) + CachedValueProvider.Result.createSingleDependency(dexWrapper, ProjectRootModificationTracker.getInstance(project)) + }, /* trackValue = */ false + ) override fun dex(classes: Collection): ByteArray? { val dexWrapper = cachedDexWrapper.value @@ -59,8 +51,8 @@ class AndroidDexerImpl(val project: Project) : AndroidDexer { val androidFacet = AndroidFacet.getInstance(module) ?: continue val sdkData = AndroidSdkData.getSdkData(androidFacet) ?: continue val latestBuildTool = sdkData.getLatestBuildTool(/* allowPreview = */ false) - ?: sdkData.getLatestBuildTool(/* allowPreview = */ true) - ?: continue + ?: sdkData.getLatestBuildTool(/* allowPreview = */ true) + ?: continue val dxJar = File(latestBuildTool.location, "lib/dx.jar") if (dxJar.exists()) { diff --git a/idea/idea-android/src/org/jetbrains/kotlin/android/folding/ResourceFoldingBuilder.kt b/idea/idea-android/src/org/jetbrains/kotlin/android/folding/ResourceFoldingBuilder.kt index 30255ec65f7..3f51d402985 100644 --- a/idea/idea-android/src/org/jetbrains/kotlin/android/folding/ResourceFoldingBuilder.kt +++ b/idea/idea-android/src/org/jetbrains/kotlin/android/folding/ResourceFoldingBuilder.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.android.folding @@ -48,10 +37,12 @@ class ResourceFoldingBuilder : FoldingBuilderEx() { private val FORMAT = Pattern.compile("%(\\d+\\$)?([-+#, 0(<]*)?(\\d+)?(\\.\\d+)?([tT])?([a-zA-Z%])") private val FOLD_MAX_LENGTH = 60 private val UNIT_TEST_MODE: Boolean = ApplicationManager.getApplication().isUnitTestMode - private val RESOURCE_TYPES = listOf(ResourceType.STRING, - ResourceType.DIMEN, - ResourceType.INTEGER, - ResourceType.PLURALS) + private val RESOURCE_TYPES = listOf( + ResourceType.STRING, + ResourceType.DIMEN, + ResourceType.INTEGER, + ResourceType.PLURALS + ) } private val isFoldingEnabled = AndroidFoldingSettings.getInstance().isCollapseAndroidStrings @@ -115,10 +106,10 @@ class ResourceFoldingBuilder : FoldingBuilderEx() { private fun UCallExpression.isFoldableGetResourceValueCall(): Boolean { return methodName == "getString" || - methodName == "getText" || - methodName == "getInteger" || - methodName?.startsWith("getDimension") ?: false || - methodName?.startsWith("getQuantityString") ?: false + methodName == "getText" || + methodName == "getInteger" || + methodName?.startsWith("getDimension") ?: false || + methodName?.startsWith("getQuantityString") ?: false } private fun PsiElement.getAndroidResourceType(): ResourceType? { @@ -141,8 +132,7 @@ class ResourceFoldingBuilder : FoldingBuilderEx() { if (resourceType == ResourceType.STRING || resourceType == ResourceType.PLURALS) { return '"' + StringUtil.shortenTextWithEllipsis(text, FOLD_MAX_LENGTH - 2, 0) + '"' - } - else if (text.length <= 1) { + } else if (text.length <= 1) { // Don't just inline empty or one-character replacements: they can't be expanded by a mouse click // so are hard to use without knowing about the folding keyboard shortcut to toggle folding. // This is similar to how IntelliJ 14 handles call parameters @@ -153,9 +143,10 @@ class ResourceFoldingBuilder : FoldingBuilderEx() { } private tailrec fun LocalResourceRepository.getResourceValue( - type: ResourceType, - name: String, - referenceConfig: FolderConfiguration): String? { + type: ResourceType, + name: String, + referenceConfig: FolderConfiguration + ): String? { val value = getConfiguredValue(type, name, referenceConfig)?.value ?: return null if (!value.startsWith('@')) { return value @@ -215,8 +206,7 @@ class ResourceFoldingBuilder : FoldingBuilderEx() { numberString = numberString.substring(0, numberString.length - 1) number = Integer.parseInt(numberString) nextNumber = number + 1 - } - else { + } else { number = nextNumber++ } @@ -237,8 +227,7 @@ class ResourceFoldingBuilder : FoldingBuilderEx() { sb.append('}') start = index } - } - else { + } else { var i = start val n = formatString.length while (i < n) { diff --git a/idea/idea-android/src/org/jetbrains/kotlin/android/inspection/IllegalIdentifierInspection.kt b/idea/idea-android/src/org/jetbrains/kotlin/android/inspection/IllegalIdentifierInspection.kt index a976937c986..7fec512ab1d 100644 --- a/idea/idea-android/src/org/jetbrains/kotlin/android/inspection/IllegalIdentifierInspection.kt +++ b/idea/idea-android/src/org/jetbrains/kotlin/android/inspection/IllegalIdentifierInspection.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.android.inspection @@ -82,7 +71,7 @@ class IllegalIdentifierInspection : AbstractKotlinInspection() { val currentGenerationId = ProjectRootModificationTracker.getInstance(module.project).modificationCount val junitTestPaths = module.getUserData(JunitPaths) ?.takeIf { it.generationId == currentGenerationId } - ?: JunitPaths(getJunitTestPaths(module), currentGenerationId).also { module.putUserData(JunitPaths, it) } + ?: JunitPaths(getJunitTestPaths(module), currentGenerationId).also { module.putUserData(JunitPaths, it) } if (junitTestPaths.paths.any { containingFile.startsWith(it) }) { return true diff --git a/idea/idea-android/src/org/jetbrains/kotlin/android/inspection/TypeParameterFindViewByIdInspection.kt b/idea/idea-android/src/org/jetbrains/kotlin/android/inspection/TypeParameterFindViewByIdInspection.kt index a71ac0416b7..72ec794efc0 100644 --- a/idea/idea-android/src/org/jetbrains/kotlin/android/inspection/TypeParameterFindViewByIdInspection.kt +++ b/idea/idea-android/src/org/jetbrains/kotlin/android/inspection/TypeParameterFindViewByIdInspection.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.android.inspection @@ -30,9 +19,9 @@ import org.jetbrains.kotlin.psi.psiUtil.addTypeArgument class TypeParameterFindViewByIdInspection : AbstractKotlinInspection(), CleanupLocalInspectionTool { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor { val compileSdk = AndroidFacet.getInstance(session.file) - ?.let { facet -> AndroidModuleInfo.getInstance(facet) } - ?.buildSdkVersion - ?.apiLevel + ?.let { facet -> AndroidModuleInfo.getInstance(facet) } + ?.buildSdkVersion + ?.apiLevel if (compileSdk == null || compileSdk < 26) { return KtVisitorVoid() @@ -53,9 +42,10 @@ class TypeParameterFindViewByIdInspection : AbstractKotlinInspection(), CleanupL } holder.registerProblem( - parentCast, - "Can be converted to findViewById<$typeText>(...)", - ConvertCastToFindViewByIdWithTypeParameter()) + parentCast, + "Can be converted to findViewById<$typeText>(...)", + ConvertCastToFindViewByIdWithTypeParameter() + ) } } } @@ -78,6 +68,6 @@ class TypeParameterFindViewByIdInspection : AbstractKotlinInspection(), CleanupL companion object { fun KtTypeReference.getTypeTextWithoutQuestionMark(): String? = - (typeElement as? KtNullableType)?.innerType?.text ?: typeElement?.text + (typeElement as? KtNullableType)?.innerType?.text ?: typeElement?.text } } \ No newline at end of file diff --git a/idea/idea-android/src/org/jetbrains/kotlin/android/intention/AbstractRegisterComponentAction.kt b/idea/idea-android/src/org/jetbrains/kotlin/android/intention/AbstractRegisterComponentAction.kt index fe9a39b88cc..eb9508207ad 100644 --- a/idea/idea-android/src/org/jetbrains/kotlin/android/intention/AbstractRegisterComponentAction.kt +++ b/idea/idea-android/src/org/jetbrains/kotlin/android/intention/AbstractRegisterComponentAction.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.android.intention @@ -37,13 +26,13 @@ abstract class AbstractRegisterComponentAction(text: String) : SelfTargetingInte val androidFacet = AndroidFacet.getInstance(element.containingFile) ?: return false val manifest = androidFacet.manifest ?: return false return !element.isLocal && - !element.isAbstract() && - !element.isPrivate() && - !element.isProtected() && - !element.isInner() && - !element.name.isNullOrEmpty() && - !element.insideBody(caretOffset) && - isApplicableTo(element, manifest) + !element.isAbstract() && + !element.isPrivate() && + !element.isProtected() && + !element.isInner() && + !element.name.isNullOrEmpty() && + !element.insideBody(caretOffset) && + isApplicableTo(element, manifest) } final override fun applyTo(element: KtClass, editor: Editor?) { diff --git a/idea/idea-android/src/org/jetbrains/kotlin/android/intention/AddActivityToManifest.kt b/idea/idea-android/src/org/jetbrains/kotlin/android/intention/AddActivityToManifest.kt index 7115bb951db..a9f8cad40f9 100644 --- a/idea/idea-android/src/org/jetbrains/kotlin/android/intention/AddActivityToManifest.kt +++ b/idea/idea-android/src/org/jetbrains/kotlin/android/intention/AddActivityToManifest.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.android.intention @@ -29,7 +18,7 @@ import org.jetbrains.kotlin.asJava.toLightClass class AddActivityToManifest : AbstractRegisterComponentAction("Add activity to manifest") { override fun isApplicableTo(element: KtClass, manifest: Manifest): Boolean = - element.isSubclassOfActivity() && !element.isRegisteredActivity(manifest) + element.isSubclassOfActivity() && !element.isRegisteredActivity(manifest) override fun applyTo(element: KtClass, manifest: Manifest) = runWriteAction { val psiClass = element.toLightClass() ?: return@runWriteAction @@ -41,5 +30,5 @@ class AddActivityToManifest : AbstractRegisterComponentAction("Add activity to m } private fun KtClass.isSubclassOfActivity() = - (descriptor as? ClassDescriptor)?.defaultType?.isSubclassOf(SdkConstants.CLASS_ACTIVITY, true) ?: false + (descriptor as? ClassDescriptor)?.defaultType?.isSubclassOf(SdkConstants.CLASS_ACTIVITY, true) ?: false } \ No newline at end of file diff --git a/idea/idea-android/src/org/jetbrains/kotlin/android/intention/AddBroadcastReceiverToManifest.kt b/idea/idea-android/src/org/jetbrains/kotlin/android/intention/AddBroadcastReceiverToManifest.kt index 0a59238be30..769e77b8278 100644 --- a/idea/idea-android/src/org/jetbrains/kotlin/android/intention/AddBroadcastReceiverToManifest.kt +++ b/idea/idea-android/src/org/jetbrains/kotlin/android/intention/AddBroadcastReceiverToManifest.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.android.intention @@ -41,5 +30,5 @@ class AddBroadcastReceiverToManifest : AbstractRegisterComponentAction("Add broa } private fun KtClass.isSubclassOfBroadcastReceiver() = - (descriptor as? ClassDescriptor)?.defaultType?.isSubclassOf(SdkConstants.CLASS_BROADCASTRECEIVER, true) ?: false + (descriptor as? ClassDescriptor)?.defaultType?.isSubclassOf(SdkConstants.CLASS_BROADCASTRECEIVER, true) ?: false } \ No newline at end of file diff --git a/idea/idea-android/src/org/jetbrains/kotlin/android/intention/AddServiceToManifest.kt b/idea/idea-android/src/org/jetbrains/kotlin/android/intention/AddServiceToManifest.kt index c2089a66199..a3fb08afa2a 100644 --- a/idea/idea-android/src/org/jetbrains/kotlin/android/intention/AddServiceToManifest.kt +++ b/idea/idea-android/src/org/jetbrains/kotlin/android/intention/AddServiceToManifest.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.android.intention @@ -29,7 +18,7 @@ import org.jetbrains.kotlin.psi.KtClass class AddServiceToManifest : AbstractRegisterComponentAction("Add service to manifest") { override fun isApplicableTo(element: KtClass, manifest: Manifest): Boolean = - element.isSubclassOfService() && !element.isRegisteredService(manifest) + element.isSubclassOfService() && !element.isRegisteredService(manifest) override fun applyTo(element: KtClass, manifest: Manifest) = runWriteAction { val psiClass = element.toLightClass() ?: return@runWriteAction @@ -41,5 +30,5 @@ class AddServiceToManifest : AbstractRegisterComponentAction("Add service to man } private fun KtClass.isSubclassOfService() = - (descriptor as? ClassDescriptor)?.defaultType?.isSubclassOf(SdkConstants.CLASS_SERVICE, true) ?: false + (descriptor as? ClassDescriptor)?.defaultType?.isSubclassOf(SdkConstants.CLASS_SERVICE, true) ?: false } \ No newline at end of file diff --git a/idea/idea-android/src/org/jetbrains/kotlin/android/intention/CreateXmlResourceParameters.kt b/idea/idea-android/src/org/jetbrains/kotlin/android/intention/CreateXmlResourceParameters.kt index 206131aece6..1f69f4ad08b 100644 --- a/idea/idea-android/src/org/jetbrains/kotlin/android/intention/CreateXmlResourceParameters.kt +++ b/idea/idea-android/src/org/jetbrains/kotlin/android/intention/CreateXmlResourceParameters.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.android.intention @@ -22,8 +11,10 @@ import com.intellij.openapi.vfs.VirtualFile val CREATE_XML_RESOURCE_PARAMETERS_NAME_KEY = Key("CREATE_XML_RESOURCE_PARAMETERS_NAME_KEY") -class CreateXmlResourceParameters(val name: String, - val value: String, - val fileName: String, - val resourceDirectory: VirtualFile, - val directoryNames: List) \ No newline at end of file +class CreateXmlResourceParameters( + val name: String, + val value: String, + val fileName: String, + val resourceDirectory: VirtualFile, + val directoryNames: List +) \ No newline at end of file diff --git a/idea/idea-android/src/org/jetbrains/kotlin/android/intention/ImplementParcelableAction.kt b/idea/idea-android/src/org/jetbrains/kotlin/android/intention/ImplementParcelableAction.kt index 6bdb56f2436..3f69c1522aa 100644 --- a/idea/idea-android/src/org/jetbrains/kotlin/android/intention/ImplementParcelableAction.kt +++ b/idea/idea-android/src/org/jetbrains/kotlin/android/intention/ImplementParcelableAction.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.android.intention @@ -29,10 +18,9 @@ import org.jetbrains.kotlin.psi.KtClass class ImplementParcelableAction : - SelfTargetingIntention(KtClass::class.java, AndroidBundle.message("implement.parcelable.intention.text")), - HighPriorityAction { - override fun isApplicableTo(element: KtClass, caretOffset: Int): Boolean = - AndroidFacet.getInstance(element) != null && + SelfTargetingIntention(KtClass::class.java, AndroidBundle.message("implement.parcelable.intention.text")), + HighPriorityAction { + override fun isApplicableTo(element: KtClass, caretOffset: Int): Boolean = AndroidFacet.getInstance(element) != null && !element.insideBody(caretOffset) && !element.isParcelize() && element.canAddParcelable() diff --git a/idea/idea-android/src/org/jetbrains/kotlin/android/intention/KotlinAndroidAddStringResource.kt b/idea/idea-android/src/org/jetbrains/kotlin/android/intention/KotlinAndroidAddStringResource.kt index ee670d8fb77..f8a11e2c824 100644 --- a/idea/idea-android/src/org/jetbrains/kotlin/android/intention/KotlinAndroidAddStringResource.kt +++ b/idea/idea-android/src/org/jetbrains/kotlin/android/intention/KotlinAndroidAddStringResource.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.android.intention @@ -53,8 +42,10 @@ import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode -class KotlinAndroidAddStringResource : SelfTargetingIntention(KtLiteralStringTemplateEntry::class.java, - "Extract string resource") { +class KotlinAndroidAddStringResource : SelfTargetingIntention( + KtLiteralStringTemplateEntry::class.java, + "Extract string resource" +) { private companion object { private val CLASS_CONTEXT = "android.content.Context" private val CLASS_FRAGMENT = "android.app.Fragment" @@ -102,8 +93,16 @@ class KotlinAndroidAddStringResource : SelfTargetingIntention) = - (this as? KtClassOrObject)?.isSubclassOfAny(baseClasses) ?: - this.isSubclassExtensionOfAny(baseClasses) + (this as? KtClassOrObject)?.isSubclassOfAny(baseClasses) ?: this.isSubclassExtensionOfAny(baseClasses) private fun PsiElement.isSubclassExtensionOfAny(baseClasses: Collection) = - (this as? KtLambdaExpression)?.isSubclassExtensionOfAny(baseClasses) ?: - (this as? KtFunction)?.isSubclassExtensionOfAny(baseClasses) ?: - false + (this as? KtLambdaExpression)?.isSubclassExtensionOfAny(baseClasses) ?: (this as? KtFunction)?.isSubclassExtensionOfAny(baseClasses) + ?: false private fun KtClassOrObject.isObjectLiteral() = (this as? KtObjectDeclaration)?.isObjectLiteral() ?: false diff --git a/idea/idea-android/src/org/jetbrains/kotlin/android/intention/RedoParcelableAction.kt b/idea/idea-android/src/org/jetbrains/kotlin/android/intention/RedoParcelableAction.kt index aad7634fab8..5a22cc52739 100644 --- a/idea/idea-android/src/org/jetbrains/kotlin/android/intention/RedoParcelableAction.kt +++ b/idea/idea-android/src/org/jetbrains/kotlin/android/intention/RedoParcelableAction.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.android.intention @@ -29,10 +18,9 @@ import org.jetbrains.kotlin.psi.KtClass class RedoParcelableAction : - SelfTargetingIntention(KtClass::class.java, AndroidBundle.message("redo.parcelable.intention.text")), - HighPriorityAction { - override fun isApplicableTo(element: KtClass, caretOffset: Int): Boolean = - AndroidFacet.getInstance(element) != null && + SelfTargetingIntention(KtClass::class.java, AndroidBundle.message("redo.parcelable.intention.text")), + HighPriorityAction { + override fun isApplicableTo(element: KtClass, caretOffset: Int): Boolean = AndroidFacet.getInstance(element) != null && !element.insideBody(caretOffset) && !element.isParcelize() && element.canRedoParcelable() diff --git a/idea/idea-android/src/org/jetbrains/kotlin/android/intention/RemoveParcelableAction.kt b/idea/idea-android/src/org/jetbrains/kotlin/android/intention/RemoveParcelableAction.kt index f69c205cabd..35b1ae6acff 100644 --- a/idea/idea-android/src/org/jetbrains/kotlin/android/intention/RemoveParcelableAction.kt +++ b/idea/idea-android/src/org/jetbrains/kotlin/android/intention/RemoveParcelableAction.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.android.intention @@ -29,10 +18,9 @@ import org.jetbrains.kotlin.psi.KtClass class RemoveParcelableAction : - SelfTargetingIntention(KtClass::class.java, AndroidBundle.message("remove.parcelable.intention.text")), - HighPriorityAction { - override fun isApplicableTo(element: KtClass, caretOffset: Int): Boolean = - AndroidFacet.getInstance(element) != null && + SelfTargetingIntention(KtClass::class.java, AndroidBundle.message("remove.parcelable.intention.text")), + HighPriorityAction { + override fun isApplicableTo(element: KtClass, caretOffset: Int): Boolean = AndroidFacet.getInstance(element) != null && !element.insideBody(caretOffset) && !element.isParcelize() && element.canRemoveParcelable() diff --git a/idea/idea-android/src/org/jetbrains/kotlin/android/navigation/gotoResourceHelper.kt b/idea/idea-android/src/org/jetbrains/kotlin/android/navigation/gotoResourceHelper.kt index a27e8a17d90..d7bcfd9f6ba 100644 --- a/idea/idea-android/src/org/jetbrains/kotlin/android/navigation/gotoResourceHelper.kt +++ b/idea/idea-android/src/org/jetbrains/kotlin/android/navigation/gotoResourceHelper.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.android.navigation @@ -37,8 +26,8 @@ fun getReferenceExpression(element: PsiElement?): KtSimpleNameExpression? { // given 'R.a.b' returns info for all three parts of the expression 'a', 'b', 'R' fun getInfo( - referenceExpression: KtSimpleNameExpression, - facet: AndroidFacet + referenceExpression: KtSimpleNameExpression, + facet: AndroidFacet ): AndroidResourceUtil.MyReferredResourceFieldInfo? { val info = getReferredInfo(referenceExpression, facet) if (info != null) return info @@ -54,8 +43,8 @@ private fun KtExpression?.getParentQualified(): KtDotQualifiedExpression? { // returns info if passed expression is 'b' in 'R.a.b' private fun getReferredInfo( - lastPart: KtSimpleNameExpression, - facet: AndroidFacet + lastPart: KtSimpleNameExpression, + facet: AndroidFacet ): AndroidResourceUtil.MyReferredResourceFieldInfo? { val resFieldName = lastPart.getReferencedName() if (resFieldName.isEmpty()) return null @@ -87,9 +76,10 @@ private fun getReferredInfo( } val containingFile = resolvedClass.containingFile ?: return null - val isFromCorrectFile = - if (fromManifest) AndroidResourceUtil.isManifestJavaFile(facet, containingFile) - else AndroidResourceUtil.isRJavaFile(facet, containingFile) + val isFromCorrectFile = if (fromManifest) + AndroidResourceUtil.isManifestJavaFile(facet, containingFile) + else + AndroidResourceUtil.isRJavaFile(facet, containingFile) if (!isFromCorrectFile) { return null @@ -98,9 +88,8 @@ private fun getReferredInfo( return AndroidResourceUtil.MyReferredResourceFieldInfo(resClassName, resFieldName, resolvedModule, false, fromManifest) } -private fun getReceiverAsSimpleNameExpression(exp: KtSimpleNameExpression): KtSimpleNameExpression? { - val receiver = exp.getReceiverExpression() - return when (receiver) { +private fun getReceiverAsSimpleNameExpression(exp: KtSimpleNameExpression): KtSimpleNameExpression? = + when (val receiver = exp.getReceiverExpression()) { is KtSimpleNameExpression -> { receiver } @@ -109,5 +98,3 @@ private fun getReceiverAsSimpleNameExpression(exp: KtSimpleNameExpression): KtSi } else -> null } - -} diff --git a/idea/idea-android/src/org/jetbrains/kotlin/android/quickfix/AddTargetApiQuickFix.kt b/idea/idea-android/src/org/jetbrains/kotlin/android/quickfix/AddTargetApiQuickFix.kt index a05fc15de40..abbfa2be6d5 100644 --- a/idea/idea-android/src/org/jetbrains/kotlin/android/quickfix/AddTargetApiQuickFix.kt +++ b/idea/idea-android/src/org/jetbrains/kotlin/android/quickfix/AddTargetApiQuickFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.android.quickfix @@ -31,8 +20,8 @@ import org.jetbrains.kotlin.psi.* class AddTargetApiQuickFix( - val api: Int, - val useRequiresApi: Boolean + val api: Int, + val useRequiresApi: Boolean ) : AndroidLintQuickFix { private companion object { @@ -41,7 +30,7 @@ class AddTargetApiQuickFix( } override fun isApplicable(startElement: PsiElement, endElement: PsiElement, contextType: AndroidQuickfixContexts.ContextType): Boolean = - getAnnotationContainer(startElement, useRequiresApi) != null + getAnnotationContainer(startElement, useRequiresApi) != null override fun getName(): String = getAnnotationValue(false).let { if (useRequiresApi) { @@ -60,10 +49,11 @@ class AddTargetApiQuickFix( } if (annotationContainer is KtModifierListOwner) { - annotationContainer.addAnnotation( - if (useRequiresApi) FQNAME_REQUIRES_API else FQNAME_TARGET_API, - getAnnotationValue(true), - whiteSpaceText = if (annotationContainer.isNewLineNeededForAnnotation()) "\n" else " ") + annotationContainer.addAnnotation( + if (useRequiresApi) FQNAME_REQUIRES_API else FQNAME_TARGET_API, + getAnnotationValue(true), + whiteSpaceText = if (annotationContainer.isNewLineNeededForAnnotation()) "\n" else " " + ) } } @@ -82,14 +72,14 @@ class AddTargetApiQuickFix( private fun PsiElement.isRequiresApiAnnotationValidTarget(): Boolean { return this is KtClassOrObject || - (this is KtFunction && this !is KtFunctionLiteral) || - (this is KtProperty && !isLocal && hasBackingField()) || - this is KtPropertyAccessor + (this is KtFunction && this !is KtFunctionLiteral) || + (this is KtProperty && !isLocal && hasBackingField()) || + this is KtPropertyAccessor } private fun PsiElement.isTargetApiAnnotationValidTarget(): Boolean { return this is KtClassOrObject || - (this is KtFunction && this !is KtFunctionLiteral) || - this is KtPropertyAccessor + (this is KtFunction && this !is KtFunctionLiteral) || + this is KtPropertyAccessor } } \ No newline at end of file diff --git a/idea/idea-android/src/org/jetbrains/kotlin/android/quickfix/AddTargetVersionCheckQuickFix.kt b/idea/idea-android/src/org/jetbrains/kotlin/android/quickfix/AddTargetVersionCheckQuickFix.kt index d506bedc907..57e3f3ab492 100644 --- a/idea/idea-android/src/org/jetbrains/kotlin/android/quickfix/AddTargetVersionCheckQuickFix.kt +++ b/idea/idea-android/src/org/jetbrains/kotlin/android/quickfix/AddTargetVersionCheckQuickFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.android.quickfix @@ -52,9 +41,11 @@ class AddTargetVersionCheckQuickFix(val api: Int) : AndroidLintQuickFix { document.replaceString(conditionRange.startOffset, conditionRange.endOffset, conditionText) documentManager.commitDocument(document) - ShortenReferences.DEFAULT.process(documentManager.getPsiFile(document) as KtFile, - conditionRange.startOffset, - conditionRange.startOffset + conditionText.length) + ShortenReferences.DEFAULT.process( + documentManager.getPsiFile(document) as KtFile, + conditionRange.startOffset, + conditionRange.startOffset + conditionText.length + ) } override fun isApplicable(startElement: PsiElement, endElement: PsiElement, contextType: AndroidQuickfixContexts.ContextType): Boolean = @@ -72,7 +63,8 @@ class AddTargetVersionCheckQuickFix(val api: Int) : AndroidLintQuickFix { current.parent is KtPropertyAccessor || current.parent is KtProperty || current.parent is KtReturnExpression || - current.parent is KtDestructuringDeclaration) { + current.parent is KtDestructuringDeclaration + ) { break } current = PsiTreeUtil.getParentOfType(current, KtExpression::class.java, true) diff --git a/idea/idea-android/src/org/jetbrains/kotlin/android/quickfix/KotlinAndroidQuickFixProvider.kt b/idea/idea-android/src/org/jetbrains/kotlin/android/quickfix/KotlinAndroidQuickFixProvider.kt index 68feed44bda..0daf51a60db 100644 --- a/idea/idea-android/src/org/jetbrains/kotlin/android/quickfix/KotlinAndroidQuickFixProvider.kt +++ b/idea/idea-android/src/org/jetbrains/kotlin/android/quickfix/KotlinAndroidQuickFixProvider.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.android.quickfix @@ -31,11 +20,11 @@ import java.util.regex.Pattern class KotlinAndroidQuickFixProvider : AndroidLintQuickFixProvider { override fun getQuickFixes( - issue: Issue, - startElement: PsiElement, - endElement: PsiElement, - message: String, - data: Any? + issue: Issue, + startElement: PsiElement, + endElement: PsiElement, + message: String, + data: Any? ): Array { val fixes: Array = when (issue) { ApiDetector.UNSUPPORTED, ApiDetector.INLINED -> getApiQuickFixes(issue, startElement, message) diff --git a/idea/idea-android/src/org/jetbrains/kotlin/android/quickfix/SuppressLintQuickFix.kt b/idea/idea-android/src/org/jetbrains/kotlin/android/quickfix/SuppressLintQuickFix.kt index 724f718c257..a20cd0ff670 100644 --- a/idea/idea-android/src/org/jetbrains/kotlin/android/quickfix/SuppressLintQuickFix.kt +++ b/idea/idea-android/src/org/jetbrains/kotlin/android/quickfix/SuppressLintQuickFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.android.quickfix @@ -43,10 +32,10 @@ class SuppressLintQuickFix(id: String) : AndroidLintQuickFix { when (annotationContainer) { is KtModifierListOwner -> { annotationContainer.addAnnotation( - FQNAME_SUPPRESS_LINT, - argument, - whiteSpaceText = if (annotationContainer.isNewLineNeededForAnnotation()) "\n" else " ", - addToExistingAnnotation = { entry -> addArgumentToAnnotation(entry, argument) }) + FQNAME_SUPPRESS_LINT, + argument, + whiteSpaceText = if (annotationContainer.isNewLineNeededForAnnotation()) "\n" else " ", + addToExistingAnnotation = { entry -> addArgumentToAnnotation(entry, argument) }) } } } @@ -54,9 +43,9 @@ class SuppressLintQuickFix(id: String) : AndroidLintQuickFix { override fun getName(): String = AndroidBundle.message(SUPPRESS_LINT_MESSAGE, lintId) override fun isApplicable( - startElement: PsiElement, - endElement: PsiElement, - contextType: AndroidQuickfixContexts.ContextType + startElement: PsiElement, + endElement: PsiElement, + contextType: AndroidQuickfixContexts.ContextType ): Boolean = true private fun addArgumentToAnnotation(entry: KtAnnotationEntry, argument: String): Boolean { @@ -77,20 +66,21 @@ class SuppressLintQuickFix(id: String) : AndroidLintQuickFix { } private fun getLintId(intentionId: String) = - if (intentionId.startsWith(INTENTION_NAME_PREFIX)) intentionId.substring(INTENTION_NAME_PREFIX.length) else intentionId + if (intentionId.startsWith(INTENTION_NAME_PREFIX)) intentionId.substring(INTENTION_NAME_PREFIX.length) else intentionId private fun KtElement.isNewLineNeededForAnnotation(): Boolean { return !(this is KtParameter || - this is KtTypeParameter || - this is KtPropertyAccessor) + this is KtTypeParameter || + this is KtPropertyAccessor) } private fun PsiElement.isSuppressLintTarget(): Boolean { return this is KtDeclaration && - (this as? KtProperty)?.hasBackingField() ?: true && - this !is KtFunctionLiteral && - this !is KtDestructuringDeclaration + (this as? KtProperty)?.hasBackingField() ?: true && + this !is KtFunctionLiteral && + this !is KtDestructuringDeclaration } + private companion object { val INTENTION_NAME_PREFIX = "AndroidLint" val SUPPRESS_LINT_MESSAGE = "android.lint.fix.suppress.lint.api.annotation" diff --git a/idea/idea-android/tests/org/jetbrains/kotlin/android/annotator/AbstractAndroidGutterIconTest.kt b/idea/idea-android/tests/org/jetbrains/kotlin/android/annotator/AbstractAndroidGutterIconTest.kt index 71604ed4ff5..4006464c443 100644 --- a/idea/idea-android/tests/org/jetbrains/kotlin/android/annotator/AbstractAndroidGutterIconTest.kt +++ b/idea/idea-android/tests/org/jetbrains/kotlin/android/annotator/AbstractAndroidGutterIconTest.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.android.annotator @@ -61,8 +50,7 @@ abstract class AbstractAndroidGutterIconTest : KotlinAndroidTestCase() { } TestCase.assertNotNull(gutter) - } - finally { + } finally { if (withRuntime) { ConfigLibraryUtil.unConfigureKotlinRuntime(myFixture.module) } diff --git a/idea/idea-android/tests/org/jetbrains/kotlin/android/intention/AbstractAndroidIntentionTest.kt b/idea/idea-android/tests/org/jetbrains/kotlin/android/intention/AbstractAndroidIntentionTest.kt index 0612df43ce6..ab03b758dad 100644 --- a/idea/idea-android/tests/org/jetbrains/kotlin/android/intention/AbstractAndroidIntentionTest.kt +++ b/idea/idea-android/tests/org/jetbrains/kotlin/android/intention/AbstractAndroidIntentionTest.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.android.intention @@ -31,15 +20,17 @@ abstract class AbstractAndroidIntentionTest : KotlinAndroidTestCase() { val testFile = File(path) val testFileText = FileUtil.loadFile(testFile) val intentionClassName = InTextDirectivesUtils.findStringWithPrefixes(testFileText, "// INTENTION_CLASS: ") - ?: error("Intention class not found!") + ?: error("Intention class not found!") val notAvailable = InTextDirectivesUtils.isDirectiveDefined(testFileText, "// NOT_AVAILABLE") val withRuntime = InTextDirectivesUtils.isDirectiveDefined(testFileText, "// WITH_RUNTIME") val checkManifest = InTextDirectivesUtils.isDirectiveDefined(testFileText, "// CHECK_MANIFEST") try { - ConfigLibraryUtil.addLibrary(myModule, "androidExtensionsRuntime", - "dist/kotlinc/lib", arrayOf("android-extensions-runtime.jar")) + ConfigLibraryUtil.addLibrary( + myModule, "androidExtensionsRuntime", + "dist/kotlinc/lib", arrayOf("android-extensions-runtime.jar") + ) if (withRuntime) { ConfigLibraryUtil.configureKotlinRuntime(myFixture.module) } @@ -70,12 +61,10 @@ abstract class AbstractAndroidIntentionTest : KotlinAndroidTestCase() { if (checkManifest) { myFixture.checkResultByFile("AndroidManifest.xml", "$customManifestPath.expected", true) - } - else { + } else { myFixture.checkResultByFile("$path.expected") } - } - finally { + } finally { ConfigLibraryUtil.removeLibrary(myModule, "androidExtensionsRuntime") if (withRuntime) { ConfigLibraryUtil.unConfigureKotlinRuntime(myFixture.module) diff --git a/idea/idea-android/tests/org/jetbrains/kotlin/android/intention/AbstractAndroidResourceIntentionTest.kt b/idea/idea-android/tests/org/jetbrains/kotlin/android/intention/AbstractAndroidResourceIntentionTest.kt index 951b939df38..68859cc1b8c 100644 --- a/idea/idea-android/tests/org/jetbrains/kotlin/android/intention/AbstractAndroidResourceIntentionTest.kt +++ b/idea/idea-android/tests/org/jetbrains/kotlin/android/intention/AbstractAndroidResourceIntentionTest.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.android.intention @@ -52,8 +41,7 @@ abstract class AbstractAndroidResourceIntentionTest : KotlinAndroidTestCase() { if (rFile != null) { myFixture.copyFileToProject(rFile, "gen/$COM_MYAPP_PACKAGE_PATH" + PathUtil.getFileName(rFile)) - } - else { + } else { if (File(testDataPath + "/R.java").isFile) { myFixture.copyFileToProject("R.java", "gen/${COM_MYAPP_PACKAGE_PATH}R.java") } @@ -61,8 +49,7 @@ abstract class AbstractAndroidResourceIntentionTest : KotlinAndroidTestCase() { if (resDirectory != null) { myFixture.copyDirectoryToProject(resDirectory, "res") - } - else { + } else { if (File(testDataPath + "/res").isDirectory) { myFixture.copyDirectoryToProject("res", "res") } @@ -74,14 +61,12 @@ abstract class AbstractAndroidResourceIntentionTest : KotlinAndroidTestCase() { val intentionAction: IntentionAction? if (intentionClass != null) { intentionAction = Class.forName(intentionClass).newInstance() as IntentionAction - } - else if (intentionText != null) { + } else if (intentionText != null) { intentionAction = myFixture.getAvailableIntention(intentionText) if (intentionAction != null && !isApplicableExpected) { TestCase.fail("Intention action should not be available") } - } - else { + } else { intentionAction = null } diff --git a/idea/idea-android/tests/org/jetbrains/kotlin/android/lint/AbstractKotlinLintTest.kt b/idea/idea-android/tests/org/jetbrains/kotlin/android/lint/AbstractKotlinLintTest.kt index 41994477466..4888cf71466 100644 --- a/idea/idea-android/tests/org/jetbrains/kotlin/android/lint/AbstractKotlinLintTest.kt +++ b/idea/idea-android/tests/org/jetbrains/kotlin/android/lint/AbstractKotlinLintTest.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.android.lint @@ -78,8 +67,7 @@ abstract class AbstractKotlinLintTest : KotlinAndroidTestCase() { for (file in additionalResourcesDir.listFiles()) { if (file.isFile) { myFixture.copyFileToProject(file.absolutePath, file.name) - } - else if (file.isDirectory) { + } else if (file.isDirectory) { myFixture.copyDirectoryToProject(file.absolutePath, file.name) } } diff --git a/idea/idea-android/tests/org/jetbrains/kotlin/android/quickfix/AbstractAndroidLintQuickfixTest.kt b/idea/idea-android/tests/org/jetbrains/kotlin/android/quickfix/AbstractAndroidLintQuickfixTest.kt index c2f6989d0bc..36a47b0e6b3 100644 --- a/idea/idea-android/tests/org/jetbrains/kotlin/android/quickfix/AbstractAndroidLintQuickfixTest.kt +++ b/idea/idea-android/tests/org/jetbrains/kotlin/android/quickfix/AbstractAndroidLintQuickfixTest.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.android.quickfix @@ -35,7 +24,8 @@ abstract class AbstractAndroidLintQuickfixTest : KotlinAndroidTestCase() { fun doTest(path: String) { val fileText = FileUtil.loadFile(File(path), true) val intentionText = InTextDirectivesUtils.findStringWithPrefixes(fileText, "// INTENTION_TEXT: ") ?: error("Empty intention text") - val mainInspectionClassName = InTextDirectivesUtils.findStringWithPrefixes(fileText, "// INSPECTION_CLASS: ") ?: error("Empty inspection class name") + val mainInspectionClassName = + InTextDirectivesUtils.findStringWithPrefixes(fileText, "// INSPECTION_CLASS: ") ?: error("Empty inspection class name") val dependency = InTextDirectivesUtils.findStringWithPrefixes(fileText, "// DEPENDENCY: ") val intentionAvailable = !InTextDirectivesUtils.isDirectiveDefined(fileText, "// INTENTION_NOT_AVAILABLE") @@ -54,8 +44,7 @@ abstract class AbstractAndroidLintQuickfixTest : KotlinAndroidTestCase() { val intention = myFixture.getAvailableIntention(intentionText) ?: error("Failed to find intention") myFixture.launchAction(intention) myFixture.checkResultByFile(path + ".expected") - } - else { + } else { assertNull("Intention should not be available", myFixture.availableIntentions.find { it.text == intentionText }) } } diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/AllClassesCompletion.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/AllClassesCompletion.kt index 9e65e8f7663..f47a2650a65 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/AllClassesCompletion.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/AllClassesCompletion.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.completion @@ -34,19 +23,20 @@ import org.jetbrains.kotlin.idea.refactoring.fqName.getKotlinFqName import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.load.java.JvmAnnotationNames import org.jetbrains.kotlin.load.kotlin.header.KotlinClassHeader -import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.platform.jvm.isJvm +import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter import org.jetbrains.kotlin.resolve.scopes.MemberScope import org.jetbrains.kotlin.resolve.scopes.getDescriptorsFiltered -class AllClassesCompletion(private val parameters: CompletionParameters, - private val kotlinIndicesHelper: KotlinIndicesHelper, - private val prefixMatcher: PrefixMatcher, - private val resolutionFacade: ResolutionFacade, - private val kindFilter: (ClassKind) -> Boolean, - private val includeTypeAliases: Boolean, - private val includeJavaClassesNotToBeUsed: Boolean +class AllClassesCompletion( + private val parameters: CompletionParameters, + private val kotlinIndicesHelper: KotlinIndicesHelper, + private val prefixMatcher: PrefixMatcher, + private val resolutionFacade: ResolutionFacade, + private val kindFilter: (ClassKind) -> Boolean, + private val includeTypeAliases: Boolean, + private val includeJavaClassesNotToBeUsed: Boolean ) { fun collect(classifierDescriptorCollector: (ClassifierDescriptorWithTypeParameters) -> Unit, javaClassCollector: (PsiClass) -> Unit) { @@ -60,14 +50,11 @@ class AllClassesCompletion(private val parameters: CompletionParameters, } } - kotlinIndicesHelper - .getKotlinClasses({ prefixMatcher.prefixMatches(it) }, kindFilter = kindFilter) - .forEach { classifierDescriptorCollector(it) } + kotlinIndicesHelper.getKotlinClasses({ prefixMatcher.prefixMatches(it) }, kindFilter = kindFilter) + .forEach { classifierDescriptorCollector(it) } if (includeTypeAliases) { - kotlinIndicesHelper - .getTopLevelTypeAliases(prefixMatcher.asStringNameFilter()) - .forEach { classifierDescriptorCollector(it) } + kotlinIndicesHelper.getTopLevelTypeAliases(prefixMatcher.asStringNameFilter()).forEach { classifierDescriptorCollector(it) } } if (TargetPlatformDetector.getPlatform(parameters.originalFile as KtFile).isJvm()) { diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/BasicCompletionSession.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/BasicCompletionSession.kt index 7f3cf4e75de..e80869a993f 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/BasicCompletionSession.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/BasicCompletionSession.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.completion @@ -55,12 +44,12 @@ import org.jetbrains.kotlin.load.java.sam.SamConstructorDescriptor import org.jetbrains.kotlin.load.java.sam.SamConstructorDescriptorKindExclude import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name +import org.jetbrains.kotlin.platform.jvm.isJvm import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.renderer.render import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.descriptorUtil.* -import org.jetbrains.kotlin.platform.jvm.isJvm import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.scopes.DescriptorKindExclude import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter @@ -206,7 +195,9 @@ class BasicCompletionSession( // no auto-popup on typing after "val", "var" and "fun" because it's likely the name of the declaration which is being typed by user if (parameters.invocationCount == 0) { val suppressOtherCompletion = when (declaration) { - is KtNamedFunction, is KtProperty -> prefixMatcher.prefix.let { it.isEmpty() || it[0].isLowerCase() /* function name usually starts with lower case letter */ } + is KtNamedFunction, is KtProperty -> prefixMatcher.prefix.let { + it.isEmpty() || it[0].isLowerCase() /* function name usually starts with lower case letter */ + } else -> true } if (suppressOtherCompletion) return @@ -263,7 +254,9 @@ class BasicCompletionSession( } // getting root packages from scope is very slow so we do this in alternative way - if (callTypeAndReceiver.receiver == null && callTypeAndReceiver.callType.descriptorKindFilter.kindMask.and(DescriptorKindFilter.PACKAGES_MASK) != 0) { + if (callTypeAndReceiver.receiver == null && + callTypeAndReceiver.callType.descriptorKindFilter.kindMask.and(DescriptorKindFilter.PACKAGES_MASK) != 0 + ) { //TODO: move this code somewhere else? val packageNames = PackageIndexUtil.getSubPackageFqNames(FqName.ROOT, searchScope, project, prefixMatcher.asNameFilter()) .toMutableSet() @@ -471,7 +464,7 @@ class BasicCompletionSession( if (file != null) { val receiverInFile = file.findElementAt(receiver.startOffset)?.getParentOfType(false) - ?: return + ?: return receiverInFile.mainReference.bindToFqName(fqNameToImport, FORCED_SHORTENING) } } @@ -570,7 +563,7 @@ class BasicCompletionSession( if (keyword in keywordsToSkip) return@complete when (keyword) { - // if "this" is parsed correctly in the current context - insert it and all this@xxx items + // if "this" is parsed correctly in the current context - insert it and all this@xxx items "this" -> { if (expression != null) { collector.addElements( @@ -586,7 +579,7 @@ class BasicCompletionSession( } } - // if "return" is parsed correctly in the current context - insert it and all return@xxx items + // if "return" is parsed correctly in the current context - insert it and all return@xxx items "return" -> { if (expression != null) { collector.addElements(returnExpressionItems(bindingContext, expression)) diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/BasicLookupElementFactory.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/BasicLookupElementFactory.kt index 3e5834b8779..68a40845b96 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/BasicLookupElementFactory.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/BasicLookupElementFactory.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.completion @@ -31,7 +20,6 @@ import org.jetbrains.kotlin.idea.completion.handlers.KotlinFunctionInsertHandler import org.jetbrains.kotlin.idea.core.completion.DeclarationLookupObject import org.jetbrains.kotlin.idea.core.completion.PackageLookupObject import org.jetbrains.kotlin.idea.highlighter.dsl.DslHighlighterExtension -import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.load.java.JvmAbi import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor import org.jetbrains.kotlin.name.FqName @@ -46,8 +34,8 @@ import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult import java.awt.Font class BasicLookupElementFactory( - private val project: Project, - val insertHandlerProvider: InsertHandlerProvider + private val project: Project, + val insertHandlerProvider: InsertHandlerProvider ) { companion object { // we skip parameter names in functional types in most of cases for shortness @@ -58,10 +46,10 @@ class BasicLookupElementFactory( } fun createLookupElement( - descriptor: DeclarationDescriptor, - qualifyNestedClasses: Boolean = false, - includeClassTypeArguments: Boolean = true, - parametersAndTypeGrayed: Boolean = false + descriptor: DeclarationDescriptor, + qualifyNestedClasses: Boolean = false, + includeClassTypeArguments: Boolean = true, + parametersAndTypeGrayed: Boolean = false ): LookupElement { val _descriptor = if (descriptor is CallableMemberDescriptor) DescriptorUtils.unwrapFakeOverride(descriptor) @@ -70,14 +58,18 @@ class BasicLookupElementFactory( return createLookupElementUnwrappedDescriptor(_descriptor, qualifyNestedClasses, includeClassTypeArguments, parametersAndTypeGrayed) } - fun createLookupElementForJavaClass(psiClass: PsiClass, qualifyNestedClasses: Boolean = false, includeClassTypeArguments: Boolean = true): LookupElement { + fun createLookupElementForJavaClass( + psiClass: PsiClass, + qualifyNestedClasses: Boolean = false, + includeClassTypeArguments: Boolean = true + ): LookupElement { val lookupObject = object : DeclarationLookupObjectImpl(null) { override val psiElement: PsiElement? get() = psiClass + override fun getIcon(flags: Int) = psiClass.getIcon(flags) } - var element = LookupElementBuilder.create(lookupObject, psiClass.name!!) - .withInsertHandler(KotlinClassifierInsertHandler) + var element = LookupElementBuilder.create(lookupObject, psiClass.name!!).withInsertHandler(KotlinClassifierInsertHandler) val typeParams = psiClass.typeParameters if (includeClassTypeArguments && typeParams.isNotEmpty()) { @@ -123,10 +115,10 @@ class BasicLookupElementFactory( } private fun createLookupElementUnwrappedDescriptor( - descriptor: DeclarationDescriptor, - qualifyNestedClasses: Boolean, - includeClassTypeArguments: Boolean, - parametersAndTypeGrayed: Boolean + descriptor: DeclarationDescriptor, + qualifyNestedClasses: Boolean, + includeClassTypeArguments: Boolean, + parametersAndTypeGrayed: Boolean ): LookupElement { if (descriptor is JavaClassDescriptor) { val declaration = DescriptorToSourceUtilsIde.getAnyDeclaration(project, descriptor) @@ -168,8 +160,10 @@ class BasicLookupElementFactory( else -> { lookupObject = object : DeclarationLookupObjectImpl(descriptor) { override val psiElement by lazy { - DescriptorToSourceUtils.getSourceFromDescriptor(descriptor) - ?: DescriptorToSourceUtilsIde.getAnyDeclaration(project, descriptor) + DescriptorToSourceUtils.getSourceFromDescriptor(descriptor) ?: DescriptorToSourceUtilsIde.getAnyDeclaration( + project, + descriptor + ) } override fun getIcon(flags: Int) = KotlinDescriptorIconProvider.getIcon(descriptor, psiElement, flags) @@ -186,14 +180,20 @@ class BasicLookupElementFactory( when (descriptor) { is FunctionDescriptor -> { val returnType = descriptor.returnType - element = element.withTypeText(if (returnType != null) SHORT_NAMES_RENDERER.renderType(returnType) else "", parametersAndTypeGrayed) + element = element.withTypeText( + if (returnType != null) SHORT_NAMES_RENDERER.renderType(returnType) else "", + parametersAndTypeGrayed + ) val insertsLambda = (insertHandler as? KotlinFunctionInsertHandler.Normal)?.lambdaInfo != null if (insertsLambda) { element = element.appendTailText(" {...} ", parametersAndTypeGrayed) } - element = element.appendTailText(SHORT_NAMES_RENDERER.renderFunctionParameters(descriptor), parametersAndTypeGrayed || insertsLambda) + element = element.appendTailText( + SHORT_NAMES_RENDERER.renderFunctionParameters(descriptor), + parametersAndTypeGrayed || insertsLambda + ) } is VariableDescriptor -> { @@ -210,8 +210,7 @@ class BasicLookupElementFactory( if (descriptor.isArtificialImportAliasedDescriptor) { container = descriptor.original // we show original descriptor instead of container for import aliased descriptors - } - else if (qualifyNestedClasses) { + } else if (qualifyNestedClasses) { element = element.withPresentableText(SHORT_NAMES_RENDERER.renderClassifierName(descriptor)) while (container is ClassDescriptor) { @@ -287,19 +286,17 @@ class BasicLookupElementFactory( val extensionReceiver = descriptor.original.extensionReceiverParameter if (extensionReceiver != null) { - when { - descriptor is SamAdapterExtensionFunctionDescriptor -> { + when (descriptor) { + is SamAdapterExtensionFunctionDescriptor -> { // no need to show them as extensions return } - - descriptor is SyntheticJavaPropertyDescriptor -> { + is SyntheticJavaPropertyDescriptor -> { var from = descriptor.getMethod.name.asString() + "()" descriptor.setMethod?.let { from += "/" + it.name.asString() + "()" } appendTailText(" (from $from)") return } - else -> { val receiverPresentation = SHORT_NAMES_RENDERER.renderType(extensionReceiver.type) appendTailText(" for $receiverPresentation") @@ -321,8 +318,7 @@ class BasicLookupElementFactory( } descriptor.isExtension -> { - val container = descriptor.containingDeclaration - val containerPresentation = when (container) { + val containerPresentation = when (val container = descriptor.containingDeclaration) { is ClassDescriptor -> DescriptorUtils.getFqNameFromTopLevelClass(container).toString() is PackageFragmentDescriptor -> container.fqName.toString() else -> return null @@ -332,21 +328,19 @@ class BasicLookupElementFactory( else -> { val container = descriptor.containingDeclaration as? PackageFragmentDescriptor - // we show container only for global functions and properties - ?: return null + // we show container only for global functions and properties + ?: return null //TODO: it would be probably better to show it also for static declarations which are not from the current class (imported) return "(${container.fqName})" } } } - private fun LookupElement.withIconFromLookupObject(): LookupElement { - // add icon in renderElement only to pass presentation.isReal() - return object : LookupElementDecorator(this) { - override fun renderElement(presentation: LookupElementPresentation) { - super.renderElement(presentation) - presentation.icon = DefaultLookupItemRenderer.getRawIcon(this@withIconFromLookupObject, presentation.isReal) - } + // add icon in renderElement only to pass presentation.isReal() + private fun LookupElement.withIconFromLookupObject(): LookupElement = object : LookupElementDecorator(this) { + override fun renderElement(presentation: LookupElementPresentation) { + super.renderElement(presentation) + presentation.icon = DefaultLookupItemRenderer.getRawIcon(this@withIconFromLookupObject, presentation.isReal) } } } \ No newline at end of file diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/CompletionBindingContextProvider.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/CompletionBindingContextProvider.kt index ce86cf909bb..168d19273d0 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/CompletionBindingContextProvider.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/CompletionBindingContextProvider.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.completion @@ -56,21 +45,21 @@ class CompletionBindingContextProvider(project: Project) { internal var TEST_LOG: StringBuilder? = null companion object { - fun getInstance(project: Project): CompletionBindingContextProvider - = project.getComponent(CompletionBindingContextProvider::class.java) + fun getInstance(project: Project): CompletionBindingContextProvider = + project.getComponent(CompletionBindingContextProvider::class.java) var ENABLED = true } private class CompletionData( - val block: KtBlockExpression, - val prevStatement: KtExpression?, - val psiElementsBeforeAndAfter: List, - val bindingContext: BindingContext, - val moduleDescriptor: ModuleDescriptor, - val statementResolutionScope: LexicalScope, - val statementDataFlowInfo: DataFlowInfo, - val debugText: String + val block: KtBlockExpression, + val prevStatement: KtExpression?, + val psiElementsBeforeAndAfter: List, + val bindingContext: BindingContext, + val moduleDescriptor: ModuleDescriptor, + val statementResolutionScope: LexicalScope, + val statementDataFlowInfo: DataFlowInfo, + val debugText: String ) private data class PsiElementData(val element: PsiElement, val level: Int) @@ -80,7 +69,9 @@ class CompletionBindingContextProvider(project: Project) { var data: CompletionData? get() = reference?.get() - set(value) { reference = value?.let { SoftReference(it) } } + set(value) { + reference = value?.let { SoftReference(it) } + } } private var prevCompletionDataCache: CachedValue = CachedValuesManager.getManager(project).createCachedValue( @@ -94,13 +85,10 @@ class CompletionBindingContextProvider(project: Project) { ) - fun getBindingContext(position: PsiElement, resolutionFacade: ResolutionFacade): BindingContext { - return if (ENABLED) { - _getBindingContext(position, resolutionFacade) - } - else { - resolutionFacade.analyze(position.parentsWithSelf.firstIsInstance(), BodyResolveMode.PARTIAL_FOR_COMPLETION) - } + fun getBindingContext(position: PsiElement, resolutionFacade: ResolutionFacade): BindingContext = if (ENABLED) { + _getBindingContext(position, resolutionFacade) + } else { + resolutionFacade.analyze(position.parentsWithSelf.firstIsInstance(), BodyResolveMode.PARTIAL_FOR_COMPLETION) } private fun _getBindingContext(position: PsiElement, resolutionFacade: ResolutionFacade): BindingContext { @@ -130,23 +118,33 @@ class CompletionBindingContextProvider(project: Project) { LOG.debug("Reusing data from completion of \"${prevCompletionData.debugText}\"") //TODO: expected type? - val statementContext = inStatement.analyzeInContext(scope = prevCompletionData.statementResolutionScope, - contextExpression = block, - dataFlowInfo = prevCompletionData.statementDataFlowInfo, - isStatement = true) + val statementContext = inStatement.analyzeInContext( + scope = prevCompletionData.statementResolutionScope, + contextExpression = block, + dataFlowInfo = prevCompletionData.statementDataFlowInfo, + isStatement = true + ) // we do not update prevCompletionDataCache because the same data should work return CompositeBindingContext.create(listOf(statementContext, prevCompletionData.bindingContext)) } } - val bindingContext = resolutionFacade.analyze(position.parentsWithSelf.firstIsInstance(), BodyResolveMode.PARTIAL_FOR_COMPLETION) + val bindingContext = + resolutionFacade.analyze(position.parentsWithSelf.firstIsInstance(), BodyResolveMode.PARTIAL_FOR_COMPLETION) prevCompletionDataCache.value.data = if (block != null && modificationScope != null) { val resolutionScope = inStatement.getResolutionScope(bindingContext, resolutionFacade) val dataFlowInfo = bindingContext.getDataFlowInfoBefore(inStatement) - CompletionData(block, prevStatement, psiElementsBeforeAndAfter!!, bindingContext, resolutionFacade.moduleDescriptor, resolutionScope, dataFlowInfo, - debugText = position.text) - } - else { + CompletionData( + block, + prevStatement, + psiElementsBeforeAndAfter!!, + bindingContext, + resolutionFacade.moduleDescriptor, + resolutionScope, + dataFlowInfo, + debugText = position.text + ) + } else { null } diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/ContextVariablesProvider.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/ContextVariablesProvider.kt index 941982b3d2b..bb59417f55a 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/ContextVariablesProvider.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/ContextVariablesProvider.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.completion @@ -34,8 +23,8 @@ interface ContextVariablesProvider { } class RealContextVariablesProvider( - private val referenceVariantsHelper: ReferenceVariantsHelper, - private val contextElement: PsiElement + private val referenceVariantsHelper: ReferenceVariantsHelper, + private val contextElement: PsiElement ) : ContextVariablesProvider { val allFunctionTypeVariables by lazy { @@ -43,9 +32,13 @@ class RealContextVariablesProvider( } private fun collectVariables(): Collection { - val descriptorFilter = DescriptorKindFilter.VARIABLES exclude DescriptorKindExclude.Extensions // we exclude extensions by performance reasons - return referenceVariantsHelper.getReferenceVariants(contextElement, CallTypeAndReceiver.DEFAULT, descriptorFilter, nameFilter = { true }) - .map { it as VariableDescriptor } + val descriptorFilter = + DescriptorKindFilter.VARIABLES exclude DescriptorKindExclude.Extensions // we exclude extensions by performance reasons + return referenceVariantsHelper.getReferenceVariants( + contextElement, + CallTypeAndReceiver.DEFAULT, + descriptorFilter, + nameFilter = { true }).map { it as VariableDescriptor } } override fun functionTypeVariables(requiredType: FuzzyType): Collection> { diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/DeclarationLookupObjectImpl.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/DeclarationLookupObjectImpl.kt index 28853857c34..e6853f764f7 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/DeclarationLookupObjectImpl.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/DeclarationLookupObjectImpl.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.completion @@ -32,8 +21,8 @@ import org.jetbrains.kotlin.util.descriptorsEqualWithSubstitution * Position will be used for sorting */ abstract class DeclarationLookupObjectImpl( - final override val descriptor: DeclarationDescriptor? -): DeclarationLookupObject { + final override val descriptor: DeclarationDescriptor? +) : DeclarationLookupObject { override val name: Name? get() = descriptor?.name ?: (psiElement as? PsiNamedElement)?.name?.let { Name.identifier(it) } diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/DslMembersCompletion.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/DslMembersCompletion.kt index 6666123362c..064ea6dfb64 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/DslMembersCompletion.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/DslMembersCompletion.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -37,8 +37,9 @@ class DslMembersCompletion( val extensionDescriptors = indicesHelper.getCallableTopLevelExtensions( nameFilter = { prefixMatcher.prefixMatches(it) }, declarationFilter = { - (it as KtModifierListOwner).modifierList?.collectAnnotationEntriesFromStubOrPsi()?.any { it.shortName in receiverMarkersShortNames } - ?: false + (it as KtModifierListOwner).modifierList?.collectAnnotationEntriesFromStubOrPsi() + ?.any { it.shortName in receiverMarkersShortNames } + ?: false }, callTypeAndReceiver = callTypeAndReceiver, receiverTypes = listOf(nearestReceiver.type) diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/ExtensionFunctionTypeValueCompletion.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/ExtensionFunctionTypeValueCompletion.kt index 4b89c7c02da..cf1178001bc 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/ExtensionFunctionTypeValueCompletion.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/ExtensionFunctionTypeValueCompletion.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.completion @@ -32,9 +21,9 @@ import org.jetbrains.kotlin.util.OperatorNameConventions import java.util.* class ExtensionFunctionTypeValueCompletion( - private val receiverTypes: Collection, - private val callType: CallType<*>, - private val lookupElementFactory: LookupElementFactory + private val receiverTypes: Collection, + private val callType: CallType<*>, + private val lookupElementFactory: LookupElementFactory ) { data class Result(val invokeDescriptor: FunctionDescriptor, val factory: AbstractLookupElementFactory) @@ -51,7 +40,10 @@ class ExtensionFunctionTypeValueCompletion( for (invoke in createSynthesizedInvokes(invokes)) { for (substituted in invoke.substituteExtensionIfCallable(receiverTypes.map { it.type }, callType)) { val factory = object : AbstractLookupElementFactory { - override fun createStandardLookupElementsForDescriptor(descriptor: DeclarationDescriptor, useReceiverTypes: Boolean): Collection { + override fun createStandardLookupElementsForDescriptor( + descriptor: DeclarationDescriptor, + useReceiverTypes: Boolean + ): Collection { if (!useReceiverTypes) return emptyList() descriptor as FunctionDescriptor // should be descriptor for "invoke" @@ -82,11 +74,12 @@ class ExtensionFunctionTypeValueCompletion( } override fun createLookupElement( - descriptor: DeclarationDescriptor, - useReceiverTypes: Boolean, - qualifyNestedClasses: Boolean, - includeClassTypeArguments: Boolean, - parametersAndTypeGrayed: Boolean): LookupElement? = null + descriptor: DeclarationDescriptor, + useReceiverTypes: Boolean, + qualifyNestedClasses: Boolean, + includeClassTypeArguments: Boolean, + parametersAndTypeGrayed: Boolean + ): LookupElement? = null } results.add(Result(substituted, factory)) diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/FromUnresolvedNamesCompletion.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/FromUnresolvedNamesCompletion.kt index e0c65ceeba3..955430e86d4 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/FromUnresolvedNamesCompletion.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/FromUnresolvedNamesCompletion.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.completion @@ -31,8 +20,8 @@ import org.jetbrains.kotlin.psi.psiUtil.startOffset import java.util.* class FromUnresolvedNamesCompletion( - private val collector: LookupElementsCollector, - private val prefixMatcher: PrefixMatcher + private val collector: LookupElementsCollector, + private val prefixMatcher: PrefixMatcher ) { fun addNameSuggestions(scope: KtElement, afterOffset: Int?, sampleDescriptor: DeclarationDescriptor?) { val names = HashSet() @@ -50,7 +39,10 @@ class FromUnresolvedNamesCompletion( val canBeUsage = when (sampleDescriptor) { is FunctionDescriptor -> isCall // cannot use simply function name without arguments is VariableDescriptor -> true // variable can as well be used with arguments when it has invoke() - is ClassDescriptor -> if (isCall) sampleDescriptor.kind == ClassKind.CLASS else sampleDescriptor.kind.isSingleton + is ClassDescriptor -> if (isCall) + sampleDescriptor.kind == ClassKind.CLASS + else + sampleDescriptor.kind.isSingleton else -> false // what else it can be? } if (!canBeUsage) return@forEachDescendantOfType @@ -69,9 +61,8 @@ class FromUnresolvedNamesCompletion( } for (name in names.sorted()) { - val lookupElement = LookupElementBuilder.create(name) - .suppressAutoInsertion() - .assignPriority(ItemPriority.FROM_UNRESOLVED_NAME_SUGGESTION) + val lookupElement = + LookupElementBuilder.create(name).suppressAutoInsertion().assignPriority(ItemPriority.FROM_UNRESOLVED_NAME_SUGGESTION) lookupElement.putUserData(KotlinCompletionCharFilter.SUPPRESS_ITEM_SELECTION_BY_CHARS_ON_TYPING, Unit) collector.addElement(lookupElement) } diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/InsertHandlerProvider.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/InsertHandlerProvider.kt index 337fa73a8df..adea935f597 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/InsertHandlerProvider.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/InsertHandlerProvider.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.completion @@ -32,8 +21,8 @@ import org.jetbrains.kotlin.types.KotlinType import java.util.* class InsertHandlerProvider( - private val callType: CallType<*>, - expectedInfosCalculator: () -> Collection + private val callType: CallType<*>, + expectedInfosCalculator: () -> Collection ) { private val expectedInfos by lazy(LazyThreadSafetyMode.NONE) { expectedInfosCalculator() } @@ -55,8 +44,8 @@ class InsertHandlerProvider( if (getValueParametersCountFromFunctionType(parameterType) <= 1 && !parameter.hasDefaultValue()) { // otherwise additional item with lambda template is to be added return KotlinFunctionInsertHandler.Normal( - callType, needTypeArguments, inputValueArguments = false, - lambdaInfo = GenerateLambdaInfo(parameterType, false) + callType, needTypeArguments, inputValueArguments = false, + lambdaInfo = GenerateLambdaInfo(parameterType, false) ) } } @@ -126,7 +115,10 @@ class InsertHandlerProvider( if (returnType != null) { addPotentiallyInferred(returnType) - if (allTypeParametersPotentiallyInferred() && expectedInfos.any { it.fuzzyType?.checkIsSuperTypeOf(originalFunction.fuzzyReturnType()!!) != null }) { + if (allTypeParametersPotentiallyInferred() && expectedInfos.any { + it.fuzzyType?.checkIsSuperTypeOf(originalFunction.fuzzyReturnType()!!) != null + } + ) { return false } } diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/KeywordValues.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/KeywordValues.kt index 2e0da7295e9..285a9025557 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/KeywordValues.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/KeywordValues.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.completion @@ -40,22 +29,23 @@ import org.jetbrains.kotlin.types.typeUtil.isBooleanOrNullableBoolean object KeywordValues { interface Consumer { fun consume( - lookupString: String, - expectedInfoMatcher: (ExpectedInfo) -> ExpectedInfoMatch, - priority: SmartCompletionItemPriority, - factory: () -> LookupElement) + lookupString: String, + expectedInfoMatcher: (ExpectedInfo) -> ExpectedInfoMatch, + priority: SmartCompletionItemPriority, + factory: () -> LookupElement + ) } fun process( - consumer: Consumer, - callTypeAndReceiver: CallTypeAndReceiver<*, *>, - bindingContext: BindingContext, - resolutionFacade: ResolutionFacade, - moduleDescriptor: ModuleDescriptor, - isJvmModule: Boolean + consumer: Consumer, + callTypeAndReceiver: CallTypeAndReceiver<*, *>, + bindingContext: BindingContext, + resolutionFacade: ResolutionFacade, + moduleDescriptor: ModuleDescriptor, + isJvmModule: Boolean ) { if (callTypeAndReceiver is CallTypeAndReceiver.DEFAULT) { - val booleanInfoMatcher = matcher@ { info: ExpectedInfo -> + val booleanInfoMatcher = matcher@{ info: ExpectedInfo -> // no sense in true or false as if-condition or when entry for when with no subject val additionalData = info.additionalData val skipTrueFalse = when (additionalData) { @@ -72,10 +62,10 @@ object KeywordValues { else ExpectedInfoMatch.noMatch } - consumer.consume("true", booleanInfoMatcher, SmartCompletionItemPriority.TRUE) { + consumer.consume("true", booleanInfoMatcher, SmartCompletionItemPriority.TRUE) { LookupElementBuilder.create(KeywordLookupObject(), "true").bold() } - consumer.consume("false", booleanInfoMatcher, SmartCompletionItemPriority.FALSE) { + consumer.consume("false", booleanInfoMatcher, SmartCompletionItemPriority.FALSE) { LookupElementBuilder.create(KeywordLookupObject(), "false").bold() } @@ -97,7 +87,8 @@ object KeywordValues { val qualifierType = bindingContext.get(BindingContext.DOUBLE_COLON_LHS, callTypeAndReceiver.receiver!!)?.type if (qualifierType != null) { val kClassDescriptor = resolutionFacade.getFrontendService(ReflectionTypes::class.java).kClass - val classLiteralType = KotlinTypeFactory.simpleNotNullType(Annotations.EMPTY, kClassDescriptor, listOf(TypeProjectionImpl(qualifierType))) + val classLiteralType = + KotlinTypeFactory.simpleNotNullType(Annotations.EMPTY, kClassDescriptor, listOf(TypeProjectionImpl(qualifierType))) val kClassTypes = listOf(classLiteralType.toFuzzyType(emptyList())) val kClassMatcher = { info: ExpectedInfo -> kClassTypes.matchExpectedInfo(info) } consumer.consume("class", kClassMatcher, SmartCompletionItemPriority.CLASS_LITERAL) { @@ -106,17 +97,21 @@ object KeywordValues { if (isJvmModule) { val javaLangClassDescriptor = resolutionFacade.resolveImportReference(moduleDescriptor, FqName("java.lang.Class")) - .singleOrNull() as? ClassDescriptor + .singleOrNull() as? ClassDescriptor if (javaLangClassDescriptor != null) { - val javaLangClassType = KotlinTypeFactory.simpleNotNullType(Annotations.EMPTY, javaLangClassDescriptor, listOf(TypeProjectionImpl(qualifierType))) + val javaLangClassType = KotlinTypeFactory.simpleNotNullType( + Annotations.EMPTY, + javaLangClassDescriptor, + listOf(TypeProjectionImpl(qualifierType)) + ) val javaClassTypes = listOf(javaLangClassType.toFuzzyType(emptyList())) val javaClassMatcher = { info: ExpectedInfo -> javaClassTypes.matchExpectedInfo(info) } consumer.consume("class", javaClassMatcher, SmartCompletionItemPriority.CLASS_LITERAL) { LookupElementBuilder.create(KeywordLookupObject(), "class.java") - .withPresentableText("class") - .withTailText(".java") - .bold() + .withPresentableText("class") + .withTailText(".java") + .bold() } } } diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/KotlinCompletionCharFilter.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/KotlinCompletionCharFilter.kt index 82347695a25..d9222c6cbe3 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/KotlinCompletionCharFilter.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/KotlinCompletionCharFilter.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.completion @@ -26,13 +15,14 @@ class KotlinCompletionCharFilter() : CharFilter() { companion object { val ACCEPT_OPENING_BRACE: Key = Key("KotlinCompletionCharFilter.ACCEPT_OPENING_BRACE") - val SUPPRESS_ITEM_SELECTION_BY_CHARS_ON_TYPING: Key = Key("KotlinCompletionCharFilter.SUPPRESS_ITEM_SELECTION_BY_CHARS_ON_TYPING") + val SUPPRESS_ITEM_SELECTION_BY_CHARS_ON_TYPING: Key = + Key("KotlinCompletionCharFilter.SUPPRESS_ITEM_SELECTION_BY_CHARS_ON_TYPING") val HIDE_LOOKUP_ON_COLON: Key = Key("KotlinCompletionCharFilter.HIDE_LOOKUP_ON_COLON") val JUST_TYPING_PREFIX: Key = Key("KotlinCompletionCharFilter.JUST_TYPING_PREFIX") } - override fun acceptChar(c : Char, prefixLength : Int, lookup : Lookup) : Result? { + override fun acceptChar(c: Char, prefixLength: Int, lookup: Lookup): Result? { if (lookup.psiFile !is KtFile) return null if (!lookup.isCompletion) return null val isAutopopup = CompletionService.getCompletionService().currentCompletion?.isAutopopupCompletion ?: return null diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/KotlinCompletionContributor.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/KotlinCompletionContributor.kt index a3050416c1a..353225e68cf 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/KotlinCompletionContributor.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/KotlinCompletionContributor.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.completion @@ -50,11 +39,18 @@ import kotlin.math.max var KtFile.doNotComplete: Boolean? by UserDataProperty(Key.create("DO_NOT_COMPLETE")) class KotlinCompletionContributor : CompletionContributor() { - private val AFTER_NUMBER_LITERAL = psiElement().afterLeafSkipping(psiElement().withText(""), psiElement().withElementType(elementType().oneOf(KtTokens.FLOAT_LITERAL, KtTokens.INTEGER_LITERAL))) - private val AFTER_INTEGER_LITERAL_AND_DOT = psiElement().afterLeafSkipping(psiElement().withText("."), psiElement().withElementType(elementType().oneOf(KtTokens.INTEGER_LITERAL))) + private val AFTER_NUMBER_LITERAL = psiElement().afterLeafSkipping( + psiElement().withText(""), + psiElement().withElementType(elementType().oneOf(KtTokens.FLOAT_LITERAL, KtTokens.INTEGER_LITERAL)) + ) + private val AFTER_INTEGER_LITERAL_AND_DOT = psiElement().afterLeafSkipping( + psiElement().withText("."), + psiElement().withElementType(elementType().oneOf(KtTokens.INTEGER_LITERAL)) + ) companion object { - val DEFAULT_DUMMY_IDENTIFIER: String = CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED + "$" // add '$' to ignore context after the caret + val DEFAULT_DUMMY_IDENTIFIER: String = + CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED + "$" // add '$' to ignore context after the caret } init { @@ -102,15 +98,16 @@ class KotlinCompletionContributor : CompletionContributor() { isInSimpleStringTemplate(tokenBefore) -> CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED else -> specialLambdaSignatureDummyIdentifier(tokenBefore) - ?: specialExtensionReceiverDummyIdentifier(tokenBefore) - ?: specialInTypeArgsDummyIdentifier(tokenBefore) - ?: specialInArgumentListDummyIdentifier(tokenBefore) - ?: DEFAULT_DUMMY_IDENTIFIER + ?: specialExtensionReceiverDummyIdentifier(tokenBefore) + ?: specialInTypeArgsDummyIdentifier(tokenBefore) + ?: specialInArgumentListDummyIdentifier(tokenBefore) + ?: DEFAULT_DUMMY_IDENTIFIER } val tokenAt = psiFile.findElementAt(max(0, offset)) if (tokenAt != null) { - if (context.completionType == CompletionType.SMART && !isAtEndOfLine(offset, context.editor.document) /* do not use parent expression if we are at the end of line - it's probably parsed incorrectly */) { + /* do not use parent expression if we are at the end of line - it's probably parsed incorrectly */ + if (context.completionType == CompletionType.SMART && !isAtEndOfLine(offset, context.editor.document)) { var parent = tokenAt.parent if (parent is KtExpression && parent !is KtBlockExpression) { // search expression to be replaced - go up while we are the first child of parent expression @@ -130,8 +127,10 @@ class KotlinCompletionContributor : CompletionContributor() { val argumentList = (expression.parent as? KtValueArgument)?.parent as? KtValueArgumentList if (argumentList != null) { - context.offsetMap.addOffset(SmartCompletion.MULTIPLE_ARGUMENTS_REPLACEMENT_OFFSET, - argumentList.rightParenthesis?.textRange?.startOffset ?: argumentList.endOffset) + context.offsetMap.addOffset( + SmartCompletion.MULTIPLE_ARGUMENTS_REPLACEMENT_OFFSET, + argumentList.rightParenthesis?.textRange?.startOffset ?: argumentList.endOffset + ) } } } @@ -193,12 +192,16 @@ class KotlinCompletionContributor : CompletionContributor() { } private val declarationKeywords = TokenSet.create(KtTokens.FUN_KEYWORD, KtTokens.VAL_KEYWORD, KtTokens.VAR_KEYWORD) - private val declarationTokens = TokenSet.orSet(TokenSet.create(KtTokens.IDENTIFIER, KtTokens.LT, KtTokens.GT, - KtTokens.COMMA, KtTokens.DOT, KtTokens.QUEST, KtTokens.COLON, - KtTokens.IN_KEYWORD, KtTokens.OUT_KEYWORD, - KtTokens.LPAR, KtTokens.RPAR, KtTokens.ARROW, - TokenType.ERROR_ELEMENT), - KtTokens.WHITE_SPACE_OR_COMMENT_BIT_SET) + private val declarationTokens = TokenSet.orSet( + TokenSet.create( + KtTokens.IDENTIFIER, KtTokens.LT, KtTokens.GT, + KtTokens.COMMA, KtTokens.DOT, KtTokens.QUEST, KtTokens.COLON, + KtTokens.IN_KEYWORD, KtTokens.OUT_KEYWORD, + KtTokens.LPAR, KtTokens.RPAR, KtTokens.ARROW, + TokenType.ERROR_ELEMENT + ), + KtTokens.WHITE_SPACE_OR_COMMENT_BIT_SET + ) private fun specialExtensionReceiverDummyIdentifier(tokenBefore: PsiElement?): String? { var token = tokenBefore ?: return null @@ -223,8 +226,8 @@ class KotlinCompletionContributor : CompletionContributor() { val file = KtPsiFactory(tokenBefore.project).createFile(text) val declaration = file.declarations.singleOrNull() ?: return null if (declaration.textLength != text.length) return null - val containsErrorElement = !PsiTreeUtil.processElements(file, PsiElementProcessor{ it !is PsiErrorElement }) - return if (containsErrorElement) null else tail + "$" + val containsErrorElement = !PsiTreeUtil.processElements(file, PsiElementProcessor { it !is PsiErrorElement }) + return if (containsErrorElement) null else "$tail$" } if (tokenType !in declarationTokens) return null if (tokenType == KtTokens.LT) ltCount++ @@ -266,10 +269,10 @@ class KotlinCompletionContributor : CompletionContributor() { } private fun doComplete( - parameters: CompletionParameters, - toFromOriginalFileMapper: ToFromOriginalFileMapper, - result: CompletionResultSet, - lookupElementPostProcessor: ((LookupElement) -> LookupElement)? = null + parameters: CompletionParameters, + toFromOriginalFileMapper: ToFromOriginalFileMapper, + result: CompletionResultSet, + lookupElementPostProcessor: ((LookupElement) -> LookupElement)? = null ) { val name = parameters.originalFile.virtualFile?.name ?: "default.kts" completionStatsData = completionStatsData?.copy( @@ -328,20 +331,19 @@ class KotlinCompletionContributor : CompletionContributor() { if (!somethingAdded && parameters.invocationCount < 2) { // Rerun completion if nothing was found val newConfiguration = CompletionSessionConfiguration( - useBetterPrefixMatcherForNonImportedClasses = false, - nonAccessibleDeclarations = false, - javaGettersAndSetters = true, - javaClassesNotToBeUsed = false, - staticMembers = parameters.invocationCount > 0, - dataClassComponentFunctions = true + useBetterPrefixMatcherForNonImportedClasses = false, + nonAccessibleDeclarations = false, + javaGettersAndSetters = true, + javaClassesNotToBeUsed = false, + staticMembers = parameters.invocationCount > 0, + dataClassComponentFunctions = true ) val newSession = BasicCompletionSession(newConfiguration, parameters, toFromOriginalFileMapper, result) addPostProcessor(newSession) newSession.complete() } - } - else { + } else { val session = SmartCompletionSession(configuration, parameters, toFromOriginalFileMapper, result) addPostProcessor(session) session.complete() @@ -421,8 +423,7 @@ class KotlinCompletionContributor : CompletionContributor() { val targets = nameRef.getReferenceTargets(bindingContext) return if (targets.isNotEmpty() && targets.all { it is FunctionDescriptor || it is ClassDescriptor && it.kind == ClassKind.CLASS }) { CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED + ">".repeat(balance) + "$" - } - else { + } else { null } } @@ -432,16 +433,19 @@ class KotlinCompletionContributor : CompletionContributor() { val pair = unclosedTypeArgListNameAndBalance(nameToken) return if (pair == null) { Pair(nameToken, 1) - } - else { + } else { Pair(pair.first, pair.second + 1) } } - private val callTypeArgsTokens = TokenSet.orSet(TokenSet.create(KtTokens.IDENTIFIER, KtTokens.LT, KtTokens.GT, - KtTokens.COMMA, KtTokens.DOT, KtTokens.QUEST, KtTokens.COLON, - KtTokens.LPAR, KtTokens.RPAR, KtTokens.ARROW), - KtTokens.WHITE_SPACE_OR_COMMENT_BIT_SET) + private val callTypeArgsTokens = TokenSet.orSet( + TokenSet.create( + KtTokens.IDENTIFIER, KtTokens.LT, KtTokens.GT, + KtTokens.COMMA, KtTokens.DOT, KtTokens.QUEST, KtTokens.COLON, + KtTokens.LPAR, KtTokens.RPAR, KtTokens.ARROW + ), + KtTokens.WHITE_SPACE_OR_COMMENT_BIT_SET + ) // if the leaf could be located inside type argument list of a call (if parsed properly) // then it returns the call name reference this type argument list would belong to @@ -479,7 +483,7 @@ class KotlinCompletionContributor : CompletionContributor() { private fun isInUnclosedSuperQualifier(tokenBefore: PsiElement?): Boolean { if (tokenBefore == null) return false - val tokensToSkip = TokenSet.orSet(TokenSet.create(KtTokens.IDENTIFIER, KtTokens.DOT ), KtTokens.WHITE_SPACE_OR_COMMENT_BIT_SET) + val tokensToSkip = TokenSet.orSet(TokenSet.create(KtTokens.IDENTIFIER, KtTokens.DOT), KtTokens.WHITE_SPACE_OR_COMMENT_BIT_SET) val tokens = generateSequence(tokenBefore) { it.prevLeaf() } val ltToken = tokens.firstOrNull { it.node.elementType !in tokensToSkip } ?: return false if (ltToken.node.elementType != KtTokens.LT) return false @@ -497,6 +501,6 @@ abstract class KotlinCompletionExtension { companion object { val EP_NAME: ExtensionPointName = - ExtensionPointName.create("org.jetbrains.kotlin.completionExtension") + ExtensionPointName.create("org.jetbrains.kotlin.completionExtension") } } diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/KotlinExcludeFromCompletionLookupActionProvider.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/KotlinExcludeFromCompletionLookupActionProvider.kt index 094d8c6b3da..83ff315826a 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/KotlinExcludeFromCompletionLookupActionProvider.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/KotlinExcludeFromCompletionLookupActionProvider.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.completion @@ -43,8 +32,8 @@ class KotlinExcludeFromCompletionLookupActionProvider : LookupActionProvider { } private class ExcludeFromCompletionAction( - private val project: Project, - private val exclude: String + private val project: Project, + private val exclude: String ) : LookupElementAction(null, "Exclude '$exclude' from completion") { override fun performLookupAction(): Result { AddImportAction.excludeFromImport(project, exclude) diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/LambdaSignatureTemplates.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/LambdaSignatureTemplates.kt index fd1d181bdeb..8fb41cd8b11 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/LambdaSignatureTemplates.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/LambdaSignatureTemplates.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.completion @@ -46,11 +35,11 @@ import org.jetbrains.kotlin.types.TypeProjection object LambdaSignatureTemplates { fun insertTemplate( - context: InsertionContext, - placeholderRange: TextRange, - lambdaType: KotlinType, - explicitParameterTypes: Boolean, - signatureOnly: Boolean + context: InsertionContext, + placeholderRange: TextRange, + lambdaType: KotlinType, + explicitParameterTypes: Boolean, + signatureOnly: Boolean ) { // we start template later to not interfere with insertion of tail type val commandProcessor = CommandProcessor.getInstance() @@ -77,8 +66,7 @@ object LambdaSignatureTemplates { val template = buildTemplate(lambdaType, signatureOnly, explicitParameterTypes, context.project) TemplateManager.getInstance(context.project).startTemplate(context.editor, template) } - } - finally { + } finally { rangeMarker.dispose() } } @@ -114,16 +102,18 @@ object LambdaSignatureTemplates { fun explicitParameterTypesRequired(file: KtFile, placeholderRange: TextRange, lambdaType: KotlinType): Boolean { PsiDocumentManager.getInstance(file.project).commitAllDocuments() - val expression = PsiTreeUtil.findElementOfClassAtRange(file, placeholderRange.startOffset, placeholderRange.endOffset, KtExpression::class.java) - ?: return false + val expression = + PsiTreeUtil.findElementOfClassAtRange(file, placeholderRange.startOffset, placeholderRange.endOffset, KtExpression::class.java) + ?: return false val resolutionFacade = file.getResolutionFacade() val bindingContext = resolutionFacade.analyze(expression, BodyResolveMode.PARTIAL) - val expectedInfos = ExpectedInfos(bindingContext, resolutionFacade, indicesHelper = null, useHeuristicSignatures = false).calculate(expression) + val expectedInfos = + ExpectedInfos(bindingContext, resolutionFacade, indicesHelper = null, useHeuristicSignatures = false).calculate(expression) val functionTypes = expectedInfos - .mapNotNull { it.fuzzyType?.type } - .filter(KotlinType::isFunctionOrSuspendFunctionType) - .toSet() + .mapNotNull { it.fuzzyType?.type } + .filter(KotlinType::isFunctionOrSuspendFunctionType) + .toSet() return explicitParameterTypesRequired(functionTypes, lambdaType) } @@ -138,10 +128,10 @@ object LambdaSignatureTemplates { } private fun buildTemplate( - lambdaType: KotlinType, - signatureOnly: Boolean, - explicitParameterTypes: Boolean, - project: Project + lambdaType: KotlinType, + signatureOnly: Boolean, + explicitParameterTypes: Boolean, + project: Project ): Template { val parameterTypes = functionParameterTypes(lambdaType) @@ -161,14 +151,13 @@ object LambdaSignatureTemplates { } //TODO: check for names in scope val parameterName = parameterType.extractParameterNameFromFunctionTypeArgument()?.render() - val nameExpression = if (parameterName != null) { + val nameExpression = if (parameterName != null) { object : Expression() { override fun calculateResult(context: ExpressionContext?) = TextResult(parameterName) override fun calculateQuickResult(context: ExpressionContext?): Result? = TextResult(parameterName) override fun calculateLookupItems(context: ExpressionContext?) = emptyArray() } - } - else { + } else { val count = (noNameParameterCount[parameterType] ?: 0) + 1 noNameParameterCount[parameterType] = count val suffix = if (count == 1) null else "$count" @@ -176,8 +165,8 @@ object LambdaSignatureTemplates { object : Expression() { override fun calculateResult(context: ExpressionContext?) = TextResult(nameSuggestions[0]) override fun calculateQuickResult(context: ExpressionContext?): Result? = null - override fun calculateLookupItems(context: ExpressionContext?) - = nameSuggestions.map { LookupElementBuilder.create(it) }.toTypedArray() + override fun calculateLookupItems(context: ExpressionContext?) = + nameSuggestions.map { LookupElementBuilder.create(it) }.toTypedArray() } } template.addVariable(nameExpression, true) @@ -201,7 +190,7 @@ object LambdaSignatureTemplates { val suggestions = KotlinNameSuggester.suggestNamesByType(parameterType, { true }, "p") return if (suffix != null) suggestions.map { "$it$suffix" } else suggestions } - + private fun nameSuggestion(parameterType: KotlinType) = nameSuggestions(parameterType)[0] private fun functionParameterTypes(functionType: KotlinType): List { diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/LeafElementFilter.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/LeafElementFilter.kt index 1ae25dd1ba1..1c02ce4b44e 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/LeafElementFilter.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/LeafElementFilter.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.completion @@ -24,11 +13,9 @@ import com.intellij.psi.tree.IElementType class LeafElementFilter(private val elementType: IElementType) : ElementFilter { - override fun isAcceptable(element: Any?, context: PsiElement?) - = element is LeafPsiElement && element.elementType == elementType + override fun isAcceptable(element: Any?, context: PsiElement?) = element is LeafPsiElement && element.elementType == elementType - override fun isClassAcceptable(hintClass: Class<*>) - = LEAF_CLASS_FILTER.isClassAcceptable(hintClass) + override fun isClassAcceptable(hintClass: Class<*>) = LEAF_CLASS_FILTER.isClassAcceptable(hintClass) companion object { private val LEAF_CLASS_FILTER = ClassFilter(LeafPsiElement::class.java) diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/LookupElementFactory.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/LookupElementFactory.kt index 45afd667ce9..4a874324625 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/LookupElementFactory.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/LookupElementFactory.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.completion @@ -55,22 +44,22 @@ interface AbstractLookupElementFactory { fun createStandardLookupElementsForDescriptor(descriptor: DeclarationDescriptor, useReceiverTypes: Boolean): Collection fun createLookupElement( - descriptor: DeclarationDescriptor, - useReceiverTypes: Boolean, - qualifyNestedClasses: Boolean = false, - includeClassTypeArguments: Boolean = true, - parametersAndTypeGrayed: Boolean = false + descriptor: DeclarationDescriptor, + useReceiverTypes: Boolean, + qualifyNestedClasses: Boolean = false, + includeClassTypeArguments: Boolean = true, + parametersAndTypeGrayed: Boolean = false ): LookupElement? } data /* we need copy() */ class LookupElementFactory( - val basicFactory: BasicLookupElementFactory, - private val receiverTypes: Collection?, - private val callType: CallType<*>, - private val inDescriptor: DeclarationDescriptor, - private val contextVariablesProvider: ContextVariablesProvider, - private val standardLookupElementsPostProcessor: (LookupElement) -> LookupElement = { it } + val basicFactory: BasicLookupElementFactory, + private val receiverTypes: Collection?, + private val callType: CallType<*>, + private val inDescriptor: DeclarationDescriptor, + private val contextVariablesProvider: ContextVariablesProvider, + private val standardLookupElementsPostProcessor: (LookupElement) -> LookupElement = { it } ) : AbstractLookupElementFactory { companion object { fun hasSingleFunctionTypeParameter(descriptor: FunctionDescriptor): Boolean { @@ -84,18 +73,18 @@ class LookupElementFactory( val insertHandlerProvider = basicFactory.insertHandlerProvider private val superFunctions: Set by lazy { - inDescriptor.parentsWithSelf - .takeWhile { it !is ClassDescriptor } - .filterIsInstance() - .toList() - .flatMap { it.findOriginalTopMostOverriddenDescriptors() } - .toSet() + inDescriptor.parentsWithSelf.takeWhile { it !is ClassDescriptor }.filterIsInstance().toList() + .flatMap { it.findOriginalTopMostOverriddenDescriptors() }.toSet() } - override fun createStandardLookupElementsForDescriptor(descriptor: DeclarationDescriptor, useReceiverTypes: Boolean): Collection { + override fun createStandardLookupElementsForDescriptor( + descriptor: DeclarationDescriptor, + useReceiverTypes: Boolean + ): Collection { val result = SmartList() - val isNormalCall = callType == CallType.DEFAULT || callType == CallType.DOT || callType == CallType.SAFE || callType == CallType.SUPER_MEMBERS + val isNormalCall = + callType == CallType.DEFAULT || callType == CallType.DOT || callType == CallType.SAFE || callType == CallType.SUPER_MEMBERS result.add(createLookupElement(descriptor, useReceiverTypes, parametersAndTypeGrayed = !isNormalCall && callType != CallType.INFIX)) @@ -103,8 +92,7 @@ class LookupElementFactory( if (descriptor is FunctionDescriptor && isNormalCall) { if (callType != CallType.SUPER_MEMBERS) { result.addSpecialFunctionCallElements(descriptor, useReceiverTypes) - } - else if (useReceiverTypes) { + } else if (useReceiverTypes) { result.addIfNotNull(createSuperFunctionCallWithArguments(descriptor)) } } @@ -149,7 +137,14 @@ class LookupElementFactory( val insertHandler = insertHandlerProvider.insertHandler(descriptor) as KotlinFunctionInsertHandler.Normal if (insertHandler.lambdaInfo == null) { val functionParameterCount = getValueParametersCountFromFunctionType(parameterType) - add(createFunctionCallElementWithLambda(descriptor, parameterType, useReceiverTypes, explicitLambdaParameters = functionParameterCount > 1)) + add( + createFunctionCallElementWithLambda( + descriptor, + parameterType, + useReceiverTypes, + explicitLambdaParameters = functionParameterCount > 1 + ) + ) } if (isSingleParameter) { @@ -165,10 +160,10 @@ class LookupElementFactory( } private fun createFunctionCallElementWithLambda( - descriptor: FunctionDescriptor, - parameterType: KotlinType, - useReceiverTypes: Boolean, - explicitLambdaParameters: Boolean + descriptor: FunctionDescriptor, + parameterType: KotlinType, + useReceiverTypes: Boolean, + explicitLambdaParameters: Boolean ): LookupElement { var lookupElement = createLookupElement(descriptor, useReceiverTypes) val inputTypeArguments = (insertHandlerProvider.insertHandler(descriptor) as KotlinFunctionInsertHandler.Normal).inputTypeArguments @@ -182,14 +177,20 @@ class LookupElementFactory( var parametersRenderer = BasicLookupElementFactory.SHORT_NAMES_RENDERER if (descriptor.valueParameters.size > 1) { parametersRenderer = parametersRenderer.withOptions { - valueParametersHandler = object: DescriptorRenderer.ValueParametersHandler by this.valueParametersHandler { - override fun appendBeforeValueParameter(parameter: ValueParameterDescriptor, parameterIndex: Int, parameterCount: Int, builder: StringBuilder) { + valueParametersHandler = object : DescriptorRenderer.ValueParametersHandler by this.valueParametersHandler { + override fun appendBeforeValueParameter( + parameter: ValueParameterDescriptor, + parameterIndex: Int, + parameterCount: Int, + builder: StringBuilder + ) { builder.append("..., ") } } } } - val parametersPresentation = parametersRenderer.renderValueParameters(listOf(descriptor.valueParameters.last()), descriptor.hasSynthesizedParameterNames()) + val parametersPresentation = + parametersRenderer.renderValueParameters(listOf(descriptor.valueParameters.last()), descriptor.hasSynthesizedParameterNames()) lookupElement = object : LookupElementDecorator(lookupElement) { override fun renderElement(presentation: LookupElementPresentation) { @@ -202,7 +203,8 @@ class LookupElementFactory( } override fun handleInsert(context: InsertionContext) { - KotlinFunctionInsertHandler.Normal(callType, inputTypeArguments, inputValueArguments = false, lambdaInfo = lambdaInfo).handleInsert(context, this) + KotlinFunctionInsertHandler.Normal(callType, inputTypeArguments, inputValueArguments = false, lambdaInfo = lambdaInfo) + .handleInsert(context, this) } } @@ -223,7 +225,11 @@ class LookupElementFactory( return lookupElement } - private fun createFunctionCallElementWithArguments(descriptor: FunctionDescriptor, argumentText: String, useReceiverTypes: Boolean): LookupElement { + private fun createFunctionCallElementWithArguments( + descriptor: FunctionDescriptor, + argumentText: String, + useReceiverTypes: Boolean + ): LookupElement { val lookupElement = createLookupElement(descriptor, useReceiverTypes) val needTypeArguments = (insertHandlerProvider.insertHandler(descriptor) as KotlinFunctionInsertHandler.Normal).inputTypeArguments @@ -231,13 +237,15 @@ class LookupElementFactory( } private inner class FunctionCallWithArgumentsLookupElement( - originalLookupElement: LookupElement, - private val descriptor: FunctionDescriptor, - private val argumentText: String, - private val needTypeArguments: Boolean + originalLookupElement: LookupElement, + private val descriptor: FunctionDescriptor, + private val argumentText: String, + private val needTypeArguments: Boolean ) : LookupElementDecorator(originalLookupElement) { - override fun equals(other: Any?) = other is FunctionCallWithArgumentsLookupElement && delegate == other.delegate && argumentText == other.argumentText + override fun equals(other: Any?) = + other is FunctionCallWithArgumentsLookupElement && delegate == other.delegate && argumentText == other.argumentText + override fun hashCode() = delegate.hashCode() * 17 + argumentText.hashCode() override fun renderElement(presentation: LookupElementPresentation) { @@ -249,17 +257,21 @@ class LookupElementFactory( } override fun handleInsert(context: InsertionContext) { - KotlinFunctionInsertHandler.Normal(callType, inputTypeArguments = needTypeArguments, inputValueArguments = false, argumentText = argumentText) - .handleInsert(context, this) + KotlinFunctionInsertHandler.Normal( + callType, + inputTypeArguments = needTypeArguments, + inputValueArguments = false, + argumentText = argumentText + ).handleInsert(context, this) } } override fun createLookupElement( - descriptor: DeclarationDescriptor, - useReceiverTypes: Boolean, - qualifyNestedClasses: Boolean, - includeClassTypeArguments: Boolean, - parametersAndTypeGrayed: Boolean + descriptor: DeclarationDescriptor, + useReceiverTypes: Boolean, + qualifyNestedClasses: Boolean, + includeClassTypeArguments: Boolean, + parametersAndTypeGrayed: Boolean ): LookupElement { var element = basicFactory.createLookupElement(descriptor, qualifyNestedClasses, includeClassTypeArguments, parametersAndTypeGrayed) @@ -286,8 +298,7 @@ class LookupElementFactory( super.renderElement(presentation) if (style == Style.BOLD) { presentation.isItemTextBold = true - } - else { + } else { presentation.itemTextForeground = CAST_REQUIRED_COLOR // gray all tail fragments too: val fragments = presentation.tailFragments @@ -298,8 +309,7 @@ class LookupElementFactory( } } } - } - else { + } else { this } } @@ -324,15 +334,11 @@ class LookupElementFactory( if (descriptor.overriddenDescriptors.isNotEmpty()) { // Optimization: when one of direct overridden fits, then nothing can fit better - descriptor.overriddenDescriptors - .mapNotNull { it.callableWeightBasedOnReceiver(receiverTypes, onReceiverTypeMismatch = null) } - .minBy { it.enum } - ?.let { return it } + descriptor.overriddenDescriptors.mapNotNull { it.callableWeightBasedOnReceiver(receiverTypes, onReceiverTypeMismatch = null) } + .minBy { it.enum }?.let { return it } val overridden = descriptor.overriddenTreeUniqueAsSequence(useOriginal = false) - return overridden - .map { callableWeightBasic(it, receiverTypes)!! } - .minBy { it.enum }!! + return overridden.map { callableWeightBasic(it, receiverTypes)!! }.minBy { it.enum }!! } return callableWeightBasic(descriptor, receiverTypes) @@ -348,8 +354,8 @@ class LookupElementFactory( } private fun CallableDescriptor.callableWeightBasedOnReceiver( - receiverTypes: Collection, - onReceiverTypeMismatch: CallableWeight? + receiverTypes: Collection, + onReceiverTypeMismatch: CallableWeight? ): CallableWeight? { val bothReceivers = listOfNotNull(extensionReceiverParameter, dispatchReceiverParameter) @@ -357,18 +363,18 @@ class LookupElementFactory( val receiverTypesForFirstReceiver = receiverTypes.filterNot { it.implicit }.ifEmpty { receiverTypes } val weights = bothReceivers.zip(generateSequence(receiverTypesForFirstReceiver) { receiverTypes }.asIterable()) - .map { (receiverParameter, receiverTypes) -> - callableWeightBasedOnReceiver(receiverTypes, onReceiverTypeMismatch, receiverParameter) - } + .map { (receiverParameter, receiverTypes) -> + callableWeightBasedOnReceiver(receiverTypes, onReceiverTypeMismatch, receiverParameter) + } if (weights.any { it == onReceiverTypeMismatch }) return onReceiverTypeMismatch return weights.firstOrNull() } private fun CallableDescriptor.callableWeightBasedOnReceiver( - receiverTypes: Collection, - onReceiverTypeMismatch: CallableWeight?, - receiverParameter: ReceiverParameterDescriptor + receiverTypes: Collection, + onReceiverTypeMismatch: CallableWeight?, + receiverParameter: ReceiverParameterDescriptor ): CallableWeight? { if ((receiverParameter.value as? TransientReceiver)?.type?.isFunctionType == true) return null @@ -403,8 +409,8 @@ class LookupElementFactory( } private fun CallableDescriptor.callableWeightForReceiverType( - receiverType: KotlinType, - receiverParameterType: KotlinType + receiverType: KotlinType, + receiverParameterType: KotlinType ): CallableWeightEnum? = when { TypeUtils.equalTypes(receiverType, receiverParameterType) -> when { isExtensionForTypeParameter() -> CallableWeightEnum.typeParameterExtension diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/LookupElementsCollector.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/LookupElementsCollector.kt index c0378b70d92..60451cbca91 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/LookupElementsCollector.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/LookupElementsCollector.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.completion @@ -33,13 +22,13 @@ import java.util.* import kotlin.math.max class LookupElementsCollector( - private val onFlush: () -> Unit, - private val prefixMatcher: PrefixMatcher, - private val completionParameters: CompletionParameters, - resultSet: CompletionResultSet, - sorter: CompletionSorter, - private val filter: ((LookupElement) -> Boolean)?, - private val allowExpectDeclarations: Boolean + private val onFlush: () -> Unit, + private val prefixMatcher: PrefixMatcher, + private val completionParameters: CompletionParameters, + resultSet: CompletionResultSet, + sorter: CompletionSorter, + private val filter: ((LookupElement) -> Boolean)?, + private val allowExpectDeclarations: Boolean ) { var bestMatchingDegree = Int.MIN_VALUE @@ -47,9 +36,7 @@ class LookupElementsCollector( private val elements = ArrayList() - private val resultSet = resultSet - .withPrefixMatcher(prefixMatcher) - .withRelevanceSorter(sorter) + private val resultSet = resultSet.withPrefixMatcher(prefixMatcher).withRelevanceSorter(sorter) private val postProcessors = ArrayList<(LookupElement) -> LookupElement>() private val processedCallables = mutableSetOf() diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/NamedArgumentCompletion.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/NamedArgumentCompletion.kt index 3a52b95101a..12c18233c38 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/NamedArgumentCompletion.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/NamedArgumentCompletion.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.completion @@ -41,9 +30,7 @@ object NamedArgumentCompletion { val callElement = thisArgument.getStrictParentOfType() ?: return false - return callElement.valueArguments - .takeWhile { it != thisArgument } - .any { it.isNamed() } + return callElement.valueArguments.takeWhile { it != thisArgument }.any { it.isNamed() } } fun complete(collector: LookupElementsCollector, expectedInfos: Collection, callType: CallType<*>) { @@ -61,10 +48,10 @@ object NamedArgumentCompletion { val typeText = types.singleOrNull()?.let { BasicLookupElementFactory.SHORT_NAMES_RENDERER.renderType(it) } ?: "..." val nameString = name.asString() val lookupElement = LookupElementBuilder.create("$nameString =") - .withPresentableText("$nameString =") - .withTailText(" $typeText") - .withIcon(KotlinIcons.PARAMETER) - .withInsertHandler(NamedArgumentInsertHandler(name)) + .withPresentableText("$nameString =") + .withTailText(" $typeText") + .withIcon(KotlinIcons.PARAMETER) + .withInsertHandler(NamedArgumentInsertHandler(name)) lookupElement.putUserData(SmartCompletionInBasicWeigher.NAMED_ARGUMENT_KEY, Unit) collector.addElement(lookupElement) } diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/OperatorNameCompletion.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/OperatorNameCompletion.kt index 442f7720eaf..4695f77038f 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/OperatorNameCompletion.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/OperatorNameCompletion.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.completion @@ -31,28 +20,26 @@ import org.jetbrains.kotlin.util.OperatorNameConventions.SET object OperatorNameCompletion { private val additionalOperatorPresentation = mapOf( - SET to "[...] = ...", - GET to "[...]", - CONTAINS to "in !in", - COMPARE_TO to "< > <= >=", - EQUALS to "== !=", - INVOKE to "(...)" + SET to "[...] = ...", + GET to "[...]", + CONTAINS to "in !in", + COMPARE_TO to "< > <= >=", + EQUALS to "== !=", + INVOKE to "(...)" ) private fun buildLookupElement(opName: Name): LookupElement { val element = LookupElementBuilder.create(opName) val symbol = - (OperatorConventions.getOperationSymbolForName(opName) as? KtSingleValueToken)?.value ?: - additionalOperatorPresentation[opName] + (OperatorConventions.getOperationSymbolForName(opName) as? KtSingleValueToken)?.value ?: additionalOperatorPresentation[opName] if (symbol != null) return element.withTypeText(symbol) return element } fun doComplete(collector: LookupElementsCollector, descriptorNameFilter: (String) -> Boolean) { - collector.addElements(OperatorConventions.CONVENTION_NAMES - .filter { descriptorNameFilter(it.asString()) } - .map(this::buildLookupElement)) + collector.addElements(OperatorConventions.CONVENTION_NAMES.filter { descriptorNameFilter(it.asString()) } + .map(this::buildLookupElement)) } } \ No newline at end of file diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/PackageDirectiveCompletion.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/PackageDirectiveCompletion.kt index f62e02e4a81..fe50fa611c7 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/PackageDirectiveCompletion.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/PackageDirectiveCompletion.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.completion @@ -53,7 +42,10 @@ object PackageDirectiveCompletion { val packageMemberScope = resolutionFacade.moduleDescriptor.getPackage(file.packageFqName.parent()).memberScope val variants = packageMemberScope.getContributedDescriptors(DescriptorKindFilter.PACKAGES, prefixMatcher.asNameFilter()) - val lookupElementFactory = BasicLookupElementFactory(resolutionFacade.project, InsertHandlerProvider(callType = CallType.PACKAGE_DIRECTIVE, expectedInfosCalculator = { emptyList() })) + val lookupElementFactory = BasicLookupElementFactory( + resolutionFacade.project, + InsertHandlerProvider(callType = CallType.PACKAGE_DIRECTIVE, expectedInfosCalculator = { emptyList() }) + ) for (variant in variants) { val lookupElement = lookupElementFactory.createLookupElement(variant) if (!lookupElement.lookupString.contains(DUMMY_IDENTIFIER)) { diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/ReferenceVariantsCollector.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/ReferenceVariantsCollector.kt index eb533925157..d02ec6cc6d9 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/ReferenceVariantsCollector.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/ReferenceVariantsCollector.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.completion @@ -43,22 +32,24 @@ private operator fun ReferenceVariants.plus(other: ReferenceVariants): Reference } class ReferenceVariantsCollector( - private val referenceVariantsHelper: ReferenceVariantsHelper, - private val indicesHelper: KotlinIndicesHelper, - private val prefixMatcher: PrefixMatcher, - private val nameExpression: KtSimpleNameExpression, - private val callTypeAndReceiver: CallTypeAndReceiver<*, *>, - private val resolutionFacade: ResolutionFacade, - private val bindingContext: BindingContext, - private val importableFqNameClassifier: ImportableFqNameClassifier, - private val configuration: CompletionSessionConfiguration, - private val runtimeReceiver: ExpressionReceiver? = null + private val referenceVariantsHelper: ReferenceVariantsHelper, + private val indicesHelper: KotlinIndicesHelper, + private val prefixMatcher: PrefixMatcher, + private val nameExpression: KtSimpleNameExpression, + private val callTypeAndReceiver: CallTypeAndReceiver<*, *>, + private val resolutionFacade: ResolutionFacade, + private val bindingContext: BindingContext, + private val importableFqNameClassifier: ImportableFqNameClassifier, + private val configuration: CompletionSessionConfiguration, + private val runtimeReceiver: ExpressionReceiver? = null ) { - private data class FilterConfiguration internal constructor(val descriptorKindFilter: DescriptorKindFilter, - val additionalPropertyNameFilter: ((String) -> Boolean)?, - val shadowedDeclarationsFilter: ShadowedDeclarationsFilter?, - val completeExtensionsFromIndices: Boolean) + private data class FilterConfiguration internal constructor( + val descriptorKindFilter: DescriptorKindFilter, + val additionalPropertyNameFilter: ((String) -> Boolean)?, + val shadowedDeclarationsFilter: ShadowedDeclarationsFilter?, + val completeExtensionsFromIndices: Boolean + ) private val prefix = prefixMatcher.prefix private val descriptorNameFilter = prefixMatcher.asStringNameFilter() @@ -111,8 +102,9 @@ class ReferenceVariantsCollector( private fun configuration(descriptorKindFilter: DescriptorKindFilter): FilterConfiguration { val completeExtensionsFromIndices = descriptorKindFilter.kindMask.and(DescriptorKindFilter.CALLABLES_MASK) != 0 - && DescriptorKindExclude.Extensions !in descriptorKindFilter.excludes - && callTypeAndReceiver !is CallTypeAndReceiver.IMPORT_DIRECTIVE + && DescriptorKindExclude.Extensions !in descriptorKindFilter.excludes + && callTypeAndReceiver !is CallTypeAndReceiver.IMPORT_DIRECTIVE + @Suppress("NAME_SHADOWING") val descriptorKindFilter = if (completeExtensionsFromIndices) descriptorKindFilter exclude TopLevelExtensionsExclude // handled via indices @@ -120,27 +112,34 @@ class ReferenceVariantsCollector( descriptorKindFilter val getOrSetPrefix = GET_SET_PREFIXES.firstOrNull { prefix.startsWith(it) } - val additionalPropertyNameFilter: ((String) -> Boolean)? = getOrSetPrefix - ?.let { prefixMatcher.cloneWithPrefix(prefix.removePrefix(getOrSetPrefix).decapitalizeSmartForCompiler()).asStringNameFilter() } + val additionalPropertyNameFilter: ((String) -> Boolean)? = getOrSetPrefix?.let { + prefixMatcher.cloneWithPrefix(prefix.removePrefix(getOrSetPrefix).decapitalizeSmartForCompiler()).asStringNameFilter() + } val shadowedDeclarationsFilter = if (runtimeReceiver != null) ShadowedDeclarationsFilter(bindingContext, resolutionFacade, nameExpression, runtimeReceiver) else ShadowedDeclarationsFilter.create(bindingContext, resolutionFacade, nameExpression, callTypeAndReceiver) - return FilterConfiguration(descriptorKindFilter, additionalPropertyNameFilter, shadowedDeclarationsFilter, completeExtensionsFromIndices) + return FilterConfiguration( + descriptorKindFilter, + additionalPropertyNameFilter, + shadowedDeclarationsFilter, + completeExtensionsFromIndices + ) } private fun doCollectBasicVariants(filterConfiguration: FilterConfiguration): ReferenceVariants { fun getReferenceVariants(kindFilter: DescriptorKindFilter, nameFilter: (Name) -> Boolean): Collection { return referenceVariantsHelper.getReferenceVariants( - nameExpression, - kindFilter, - nameFilter, - filterOutJavaGettersAndSetters = false, - filterOutShadowed = false, - excludeNonInitializedVariable = false, - useReceiverType = runtimeReceiver?.type) + nameExpression, + kindFilter, + nameFilter, + filterOutJavaGettersAndSetters = false, + filterOutShadowed = false, + excludeNonInitializedVariable = false, + useReceiverType = runtimeReceiver?.type + ) } val basicNameFilter = descriptorNameFilter.toNameFilter() @@ -150,7 +149,10 @@ class ReferenceVariantsCollector( var basicVariants = getReferenceVariants(descriptorKindFilter, basicNameFilter) if (additionalPropertyNameFilter != null) { - basicVariants += getReferenceVariants(descriptorKindFilter.intersect(DescriptorKindFilter.VARIABLES), additionalPropertyNameFilter.toNameFilter()) + basicVariants += getReferenceVariants( + descriptorKindFilter.intersect(DescriptorKindFilter.VARIABLES), + additionalPropertyNameFilter.toNameFilter() + ) runDistinct = true } @@ -183,18 +185,22 @@ class ReferenceVariantsCollector( else indicesHelper.getCallableTopLevelExtensions(callTypeAndReceiver, nameExpression, bindingContext, nameFilter) - val (extensionsVariants, notImportedExtensions) = extensions.partition { importableFqNameClassifier.isImportableDescriptorImported(it) } + val (extensionsVariants, notImportedExtensions) = extensions.partition { + importableFqNameClassifier.isImportableDescriptorImported( + it + ) + } val notImportedDeclarationsFilter = - shadowedDeclarationsFilter?.createNonImportedDeclarationsFilter(importedDeclarations = basicVariants.imported + extensionsVariants) + shadowedDeclarationsFilter?.createNonImportedDeclarationsFilter(importedDeclarations = basicVariants.imported + extensionsVariants) val filteredImported = filterConfiguration.filterVariants(extensionsVariants + basicVariants.imported) val importedExtensionsVariants = filteredImported.filter { it !in basicVariants.imported } return ReferenceVariants( - importedExtensionsVariants, - notImportedExtensions.let { variants -> notImportedDeclarationsFilter?.invoke(variants) ?: variants } + importedExtensionsVariants, + notImportedExtensions.let { variants -> notImportedDeclarationsFilter?.invoke(variants) ?: variants } ) } @@ -226,17 +232,15 @@ class ReferenceVariantsCollector( if (descriptor.kind != CallableMemberDescriptor.Kind.DECLARATION) return false /* do not filter out synthetic extensions */ if (descriptor.isArtificialImportAliasedDescriptor) return false // do not exclude aliased descriptors - they cannot be completed via indices val containingPackage = descriptor.containingDeclaration as? PackageFragmentDescriptor ?: return false - if (containingPackage.fqName.asString().startsWith("kotlinx.android.synthetic.")) return false // TODO: temporary solution for Android synthetic extensions + // TODO: temporary solution for Android synthetic extensions + if (containingPackage.fqName.asString().startsWith("kotlinx.android.synthetic.")) return false return true } override val fullyExcludedDescriptorKinds: Int get() = 0 } - private fun isDataClassComponentFunction(descriptor: DeclarationDescriptor): Boolean { - return descriptor is FunctionDescriptor && - descriptor.isOperator && - DataClassDescriptorResolver.isComponentLike(descriptor.name) && - descriptor.kind == CallableMemberDescriptor.Kind.SYNTHESIZED - } + private fun isDataClassComponentFunction(descriptor: DeclarationDescriptor): Boolean = + descriptor is FunctionDescriptor && descriptor.isOperator && DataClassDescriptorResolver.isComponentLike(descriptor.name) && descriptor.kind == CallableMemberDescriptor.Kind + .SYNTHESIZED } diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/StaticMembersCompletion.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/StaticMembersCompletion.kt index 49c3f2a603f..c62f8d56d3d 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/StaticMembersCompletion.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/StaticMembersCompletion.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.completion @@ -39,43 +28,42 @@ import org.jetbrains.kotlin.types.KotlinType import java.util.* class StaticMembersCompletion( - private val prefixMatcher: PrefixMatcher, - private val resolutionFacade: ResolutionFacade, - private val lookupElementFactory: LookupElementFactory, - alreadyAdded: Collection, - private val isJvmModule: Boolean + private val prefixMatcher: PrefixMatcher, + private val resolutionFacade: ResolutionFacade, + private val lookupElementFactory: LookupElementFactory, + alreadyAdded: Collection, + private val isJvmModule: Boolean ) { private val alreadyAdded = alreadyAdded.mapTo(HashSet()) { if (it is ImportedFromObjectCallableDescriptor<*>) it.callableFromObject else it } - fun decoratedLookupElementFactory(itemPriority: ItemPriority): AbstractLookupElementFactory { - return object : AbstractLookupElementFactory { - override fun createStandardLookupElementsForDescriptor(descriptor: DeclarationDescriptor, useReceiverTypes: Boolean): Collection { - if (!useReceiverTypes) return emptyList() - return lookupElementFactory.createLookupElement(descriptor, useReceiverTypes = false) - .decorateAsStaticMember(descriptor, classNameAsLookupString = false) - ?.assignPriority(itemPriority) - ?.suppressAutoInsertion() - .let(::listOfNotNull) - } - - override fun createLookupElement(descriptor: DeclarationDescriptor, useReceiverTypes: Boolean, - qualifyNestedClasses: Boolean, includeClassTypeArguments: Boolean, - parametersAndTypeGrayed: Boolean) = null + fun decoratedLookupElementFactory(itemPriority: ItemPriority): AbstractLookupElementFactory = object : AbstractLookupElementFactory { + override fun createStandardLookupElementsForDescriptor( + descriptor: DeclarationDescriptor, + useReceiverTypes: Boolean + ): Collection { + if (!useReceiverTypes) return emptyList() + return lookupElementFactory.createLookupElement(descriptor, useReceiverTypes = false) + .decorateAsStaticMember(descriptor, classNameAsLookupString = false) + ?.assignPriority(itemPriority) + ?.suppressAutoInsertion() + .let(::listOfNotNull) } + + override fun createLookupElement( + descriptor: DeclarationDescriptor, useReceiverTypes: Boolean, + qualifyNestedClasses: Boolean, includeClassTypeArguments: Boolean, + parametersAndTypeGrayed: Boolean + ) = null } fun membersFromImports(file: KtFile): Collection { - val containers = file.importDirectives - .filter { !it.isAllUnder } - .mapNotNull { - it.targetDescriptors(resolutionFacade) - .map { it.containingDeclaration } - .distinct() - .singleOrNull() as? ClassDescriptor - } - .toSet() + val containers = file.importDirectives.filter { !it.isAllUnder }.mapNotNull { + it.targetDescriptors(resolutionFacade).map { descriptor -> + descriptor.containingDeclaration + }.distinct().singleOrNull() as? ClassDescriptor + }.toSet() val result = ArrayList() @@ -84,8 +72,11 @@ class StaticMembersCompletion( for (container in containers) { val memberScope = if (container.kind == ClassKind.OBJECT) container.unsubstitutedMemberScope else container.staticScope val members = - memberScope.getDescriptorsFiltered(kindFilter, nameFilter) + - memberScope.collectSyntheticStaticMembersAndConstructors(resolutionFacade, kindFilter, nameFilter) + memberScope.getDescriptorsFiltered(kindFilter, nameFilter) + memberScope.collectSyntheticStaticMembersAndConstructors( + resolutionFacade, + kindFilter, + nameFilter + ) members.filterTo(result) { it is CallableDescriptor && it !in alreadyAdded } } return result @@ -109,7 +100,7 @@ class StaticMembersCompletion( } if (isJvmModule) { - indicesHelper.processJavaStaticMembers(descriptorKindFilter, nameFilter){ + indicesHelper.processJavaStaticMembers(descriptorKindFilter, nameFilter) { if (it !in alreadyAdded) { processor(it) } @@ -132,9 +123,8 @@ class StaticMembersCompletion( fun completeFromImports(file: KtFile, collector: LookupElementsCollector) { val factory = decoratedLookupElementFactory(ItemPriority.STATIC_MEMBER_FROM_IMPORTS) - membersFromImports(file) - .flatMap { factory.createStandardLookupElementsForDescriptor(it, useReceiverTypes = true) } - .forEach { collector.addElement(it) } + membersFromImports(file).flatMap { factory.createStandardLookupElementsForDescriptor(it, useReceiverTypes = true) } + .forEach { collector.addElement(it) } } /** diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/Statisticians.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/Statisticians.kt index f36d1c7bf8d..aec613513ef 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/Statisticians.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/Statisticians.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.completion @@ -42,8 +31,7 @@ class KotlinCompletionStatistician : CompletionStatistician() { if (o.descriptor != null) { return KotlinStatisticsInfo.forDescriptor(o.descriptor!!.original, context) - } - else { + } else { val fqName = o.importableFqName ?: return StatisticsInfo.EMPTY return StatisticsInfo(context, fqName.asString()) } @@ -74,13 +62,12 @@ object KotlinStatisticsInfo { return descriptor.importableFqName?.let { StatisticsInfo("", it.asString()) } ?: StatisticsInfo.EMPTY } - val container = descriptor.containingDeclaration - val containerFqName = when (container) { - is ClassDescriptor -> container.importableFqName?.asString() - is PackageFragmentDescriptor -> container.fqName.asString() - is ModuleDescriptor -> "" - else -> null - } ?: return StatisticsInfo.EMPTY + val containerFqName = when (val container = descriptor.containingDeclaration) { + is ClassDescriptor -> container.importableFqName?.asString() + is PackageFragmentDescriptor -> container.fqName.asString() + is ModuleDescriptor -> "" + else -> null + } ?: return StatisticsInfo.EMPTY val signature = SIGNATURE_RENDERER.render(descriptor) return StatisticsInfo(context, "$containerFqName###$signature") } diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/ToFromOriginalFileMapper.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/ToFromOriginalFileMapper.kt index b48bcc4dbf2..4b03b8b4c72 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/ToFromOriginalFileMapper.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/ToFromOriginalFileMapper.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.completion @@ -25,9 +14,9 @@ import org.jetbrains.kotlin.utils.checkWithAttachment import kotlin.math.min class ToFromOriginalFileMapper private constructor( - val originalFile: KtFile, - val syntheticFile: KtFile, - val completionOffset: Int + val originalFile: KtFile, + val syntheticFile: KtFile, + val completionOffset: Int ) { companion object { fun create(parameters: CompletionParameters): ToFromOriginalFileMapper { @@ -60,7 +49,7 @@ class ToFromOriginalFileMapper private constructor( syntheticLength = syntheticText.length originalLength = originalText.length val minLength = min(originalLength, syntheticLength) - tailLength = (0..minLength-1).firstOrNull { + tailLength = (0 until minLength).firstOrNull { syntheticText[syntheticLength - it - 1] != originalText[originalLength - it - 1] } ?: minLength shift = syntheticLength - originalLength diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/Weighers.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/Weighers.kt index e256b570bfb..3155a5ac94e 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/Weighers.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/Weighers.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.completion @@ -39,8 +28,7 @@ import org.jetbrains.kotlin.resolve.findOriginalTopMostOverriddenDescriptors import org.jetbrains.kotlin.types.typeUtil.isNothing object PriorityWeigher : LookupElementWeigher("kotlin.priority") { - override fun weigh(element: LookupElement, context: WeighingContext) - = element.getUserData(ITEM_PRIORITY_KEY) ?: ItemPriority.DEFAULT + override fun weigh(element: LookupElement, context: WeighingContext) = element.getUserData(ITEM_PRIORITY_KEY) ?: ItemPriority.DEFAULT } object PreferDslMembers : LookupElementWeigher("kotlin.preferDsl") { @@ -71,7 +59,8 @@ class NotImportedWeigher(private val classifier: ImportableFqNameClassifier) : L } } -class NotImportedStaticMemberWeigher(private val classifier: ImportableFqNameClassifier) : LookupElementWeigher("kotlin.notImportedMember") { +class NotImportedStaticMemberWeigher(private val classifier: ImportableFqNameClassifier) : + LookupElementWeigher("kotlin.notImportedMember") { override fun weigh(element: LookupElement): Comparable<*>? { if (element.getUserData(ITEM_PRIORITY_KEY) != ItemPriority.STATIC_MEMBER) return null val fqName = (element.`object` as DeclarationLookupObject).importableFqName ?: return null @@ -109,8 +98,8 @@ object KotlinLookupElementProximityWeigher : CompletionWeigher() { } object SmartCompletionPriorityWeigher : LookupElementWeigher("kotlin.smartCompletionPriority") { - override fun weigh(element: LookupElement, context: WeighingContext) - = element.getUserData(SMART_COMPLETION_ITEM_PRIORITY_KEY) ?: SmartCompletionItemPriority.DEFAULT + override fun weigh(element: LookupElement, context: WeighingContext) = + element.getUserData(SMART_COMPLETION_ITEM_PRIORITY_KEY) ?: SmartCompletionItemPriority.DEFAULT } object KindWeigher : LookupElementWeigher("kotlin.kind") { @@ -197,7 +186,7 @@ object CallableWeigher : LookupElementWeigher("kotlin.callableWeight") { } } -object VariableOrFunctionWeigher : LookupElementWeigher("kotlin.variableOrFunction"){ +object VariableOrFunctionWeigher : LookupElementWeigher("kotlin.variableOrFunction") { private enum class Weight { variable, function @@ -216,7 +205,7 @@ object VariableOrFunctionWeigher : LookupElementWeigher("kotlin.variableOrFuncti /** * Decreases priority of properties when prefix starts with "get" or "set" (and the property name does not) */ -object PreferGetSetMethodsToPropertyWeigher : LookupElementWeigher("kotlin.preferGetSetMethodsToProperty", false, true){ +object PreferGetSetMethodsToPropertyWeigher : LookupElementWeigher("kotlin.preferGetSetMethodsToProperty", false, true) { override fun weigh(element: LookupElement, context: WeighingContext): Int { val property = (element.`object` as? DeclarationLookupObject)?.descriptor as? PropertyDescriptor ?: return 0 val prefixMatcher = context.itemMatcher(element) @@ -247,8 +236,7 @@ object PreferMatchingItemWeigher : LookupElementWeigher("kotlin.preferMatching", val prefix = context.itemPattern(element) if (element.lookupString != prefix) { return Weight.notExactMatch - } - else { + } else { val o = element.`object` return when (o) { is KeywordLookupObject -> Weight.keywordExactMatch @@ -270,10 +258,10 @@ object PreferMatchingItemWeigher : LookupElementWeigher("kotlin.preferMatching", } class SmartCompletionInBasicWeigher( - private val smartCompletion: SmartCompletion, - private val callTypeAndReceiver: CallTypeAndReceiver<*, *>, - private val resolutionFacade: ResolutionFacade, - private val bindingContext: BindingContext + private val smartCompletion: SmartCompletion, + private val callTypeAndReceiver: CallTypeAndReceiver<*, *>, + private val resolutionFacade: ResolutionFacade, + private val bindingContext: BindingContext ) : LookupElementWeigher("kotlin.smartInBasic", true, false) { companion object { @@ -286,8 +274,8 @@ class SmartCompletionInBasicWeigher( private val PRIORITY_COUNT = SmartCompletionItemPriority.values().size - private fun itemWeight(priority: SmartCompletionItemPriority, nameSimilarity: Int) - = (nameSimilarity.toLong() shl 32) + PRIORITY_COUNT - priority.ordinal + private fun itemWeight(priority: SmartCompletionItemPriority, nameSimilarity: Int) = + (nameSimilarity.toLong() shl 32) + PRIORITY_COUNT - priority.ordinal private val NAMED_ARGUMENT_WEIGHT = 1L @@ -316,7 +304,12 @@ class SmartCompletionInBasicWeigher( val (fuzzyTypes, name) = when (o) { is DeclarationLookupObject -> { val descriptor = o.descriptor ?: return NO_MATCH_WEIGHT - descriptor.fuzzyTypesForSmartCompletion(smartCastCalculator, callTypeAndReceiver, resolutionFacade, bindingContext) to descriptor.name + descriptor.fuzzyTypesForSmartCompletion( + smartCastCalculator, + callTypeAndReceiver, + resolutionFacade, + bindingContext + ) to descriptor.name } is ThisItemLookupObject -> smartCastCalculator.types(o.receiverParameter).map { it.toFuzzyType(emptyList()) } to null @@ -332,8 +325,7 @@ class SmartCompletionInBasicWeigher( val nameSimilarity = if (name != null) { val matchingInfos = matched.filter { it.second != ExpectedInfoMatch.noMatch }.map { it.first } calcNameSimilarity(name.asString(), matchingInfos) - } - else { + } else { 0 } @@ -346,10 +338,10 @@ class SmartCompletionInBasicWeigher( class PreferContextElementsWeigher(context: DeclarationDescriptor) : LookupElementWeigher("kotlin.preferContextElements", true, false) { private val contextElements = context.parentsWithSelf - .takeWhile { it !is PackageFragmentDescriptor } - .toList() - .flatMap { if (it is CallableDescriptor) it.findOriginalTopMostOverriddenDescriptors() else listOf(it) } - .toSet() + .takeWhile { it !is PackageFragmentDescriptor } + .toList() + .flatMap { if (it is CallableDescriptor) it.findOriginalTopMostOverriddenDescriptors() else listOf(it) } + .toSet() private val contextElementNames = contextElements.map { it.name }.toSet() override fun weigh(element: LookupElement): Boolean { diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/confidence/EnableAutopopupInStringTemplate.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/confidence/EnableAutopopupInStringTemplate.kt index e1c114362b1..23ed0ffcb3c 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/confidence/EnableAutopopupInStringTemplate.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/confidence/EnableAutopopupInStringTemplate.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.completion.confidence @@ -29,7 +18,8 @@ import org.jetbrains.kotlin.psi.psiUtil.startOffset class EnableAutopopupInStringTemplate : CompletionConfidence() { override fun shouldSkipAutopopup(contextElement: PsiElement, psiFile: PsiFile, offset: Int): ThreeState { - val stringTemplate = contextElement.prevLeaf()?.getParentOfType(strict = false) ?: return ThreeState.UNSURE + val stringTemplate = + contextElement.prevLeaf()?.getParentOfType(strict = false) ?: return ThreeState.UNSURE // "$nameRef" stringTemplate here is "$nameRef", so offset are inside template, we should show lookup if (offset in stringTemplate.startOffset until stringTemplate.endOffset) return ThreeState.NO diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/handlers/KotlinClassifierInsertHandler.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/handlers/KotlinClassifierInsertHandler.kt index 74b41e76528..b5389a35416 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/handlers/KotlinClassifierInsertHandler.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/handlers/KotlinClassifierInsertHandler.kt @@ -45,7 +45,8 @@ object KotlinClassifierInsertHandler : BaseDeclarationInsertHandler() { val document = context.document val lookupObject = item.`object` as DeclarationLookupObject - if (lookupObject.descriptor?.isArtificialImportAliasedDescriptor == true) return // never need to insert import or use qualified name for import-aliased class + // never need to insert import or use qualified name for import-aliased class + if (lookupObject.descriptor?.isArtificialImportAliasedDescriptor == true) return val qualifiedName = qualifiedName(lookupObject) diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/handlers/KotlinFunctionInsertHandler.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/handlers/KotlinFunctionInsertHandler.kt index 4e2a2cfe96e..8e5a70dee41 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/handlers/KotlinFunctionInsertHandler.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/handlers/KotlinFunctionInsertHandler.kt @@ -117,7 +117,8 @@ sealed class KotlinFunctionInsertHandler(callType: CallType<*>) : KotlinCallable val token = context.file.findElementAt(offset1)!! if (token.node.elementType == KtTokens.LT) { val parent = token.parent - if (parent is KtTypeArgumentList && parent.getText().indexOf('\n') < 0/* if type argument list is on multiple lines this is more likely wrong parsing*/) { + /* if type argument list is on multiple lines this is more likely wrong parsing*/ + if (parent is KtTypeArgumentList && parent.getText().indexOf('\n') < 0) { offset = parent.endOffset insertTypeArguments = false } diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/ArrayLiteralsInAnnotationItems.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/ArrayLiteralsInAnnotationItems.kt index a224adaf5ae..0de347dd090 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/ArrayLiteralsInAnnotationItems.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/ArrayLiteralsInAnnotationItems.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.completion.smart @@ -30,18 +19,22 @@ import org.jetbrains.kotlin.psi.psiUtil.getParentOfType object ArrayLiteralsInAnnotationItems { - private fun MutableCollection.addForUsage(expectedInfos: Collection, - position: PsiElement) { + private fun MutableCollection.addForUsage( + expectedInfos: Collection, + position: PsiElement + ) { if (position.getParentOfType(false) != null) { expectedInfos.asSequence() - .filter { it.fuzzyType?.type?.let { type -> KotlinBuiltIns.isArray(type) } == true } - .filterNot { it.itemOptions.starPrefix } - .mapTo(this) { createLookupElement() } + .filter { it.fuzzyType?.type?.let { type -> KotlinBuiltIns.isArray(type) } == true } + .filterNot { it.itemOptions.starPrefix } + .mapTo(this) { createLookupElement() } } } - private fun MutableCollection.addForDefaultArguments(expectedInfos: Collection, - position: PsiElement) { + private fun MutableCollection.addForDefaultArguments( + expectedInfos: Collection, + position: PsiElement + ) { // CLASS [MODIFIER_LIST, PRIMARY_CONSTRUCTOR [VALUE_PARAMETER_LIST [VALUE_PARAMETER [..., REFERENCE_EXPRESSION=position]]]] val valueParameter = position.parent as? KtParameter ?: return @@ -50,24 +43,20 @@ object ArrayLiteralsInAnnotationItems { val primaryConstructor = klass.primaryConstructor ?: return if (primaryConstructor.valueParameterList == valueParameter.parent) { - expectedInfos - .filter { it.fuzzyType?.type?.let { type -> KotlinBuiltIns.isArray(type) } == true } - .mapTo(this) { createLookupElement() } + expectedInfos.filter { it.fuzzyType?.type?.let { type -> KotlinBuiltIns.isArray(type) } == true } + .mapTo(this) { createLookupElement() } } } - private fun createLookupElement(): LookupElement { - return LookupElementBuilder.create("[]") - .withInsertHandler { context, _ -> - context.editor.caretModel.moveToOffset(context.tailOffset - 1) - } - .apply { putUserData(SMART_COMPLETION_ITEM_PRIORITY_KEY, SmartCompletionItemPriority.ARRAY_LITERAL_IN_ANNOTATION) } - } + private fun createLookupElement(): LookupElement = LookupElementBuilder.create("[]") + .withInsertHandler { context, _ -> + context.editor.caretModel.moveToOffset(context.tailOffset - 1) + } + .apply { putUserData(SMART_COMPLETION_ITEM_PRIORITY_KEY, SmartCompletionItemPriority.ARRAY_LITERAL_IN_ANNOTATION) } - fun collect(expectedInfos: Collection, position: PsiElement): Collection { - return mutableListOf().apply { + fun collect(expectedInfos: Collection, position: PsiElement): Collection = + mutableListOf().apply { addForUsage(expectedInfos, position) addForDefaultArguments(expectedInfos, position) } - } } \ No newline at end of file diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/ClassLiteralItems.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/ClassLiteralItems.kt index 18bead3bc39..e65d11a8be3 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/ClassLiteralItems.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/ClassLiteralItems.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.completion.smart @@ -27,8 +16,8 @@ import org.jetbrains.kotlin.idea.completion.BasicLookupElementFactory import org.jetbrains.kotlin.idea.completion.createLookupElementForType import org.jetbrains.kotlin.idea.core.ExpectedInfo import org.jetbrains.kotlin.idea.core.fuzzyType -import org.jetbrains.kotlin.idea.imports.importableFqName import org.jetbrains.kotlin.idea.core.moveCaret +import org.jetbrains.kotlin.idea.imports.importableFqName import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.Variance import org.jetbrains.kotlin.types.typeUtil.makeNotNullable @@ -36,10 +25,10 @@ import java.util.* object ClassLiteralItems { fun addToCollection( - collection: MutableCollection, - expectedInfos: Collection, - lookupElementFactory: BasicLookupElementFactory, - isJvmModule: Boolean + collection: MutableCollection, + expectedInfos: Collection, + lookupElementFactory: BasicLookupElementFactory, + isJvmModule: Boolean ) { val typeAndSuffixToExpectedInfos = LinkedHashMap, MutableList>() @@ -64,8 +53,7 @@ object ClassLiteralItems { val (type, suffix) = pair val typeToUse = if (KotlinBuiltIns.isArray(type)) { type.makeNotNullable() - } - else { + } else { val classifier = (type.constructor.declarationDescriptor as? ClassDescriptor) ?: continue classifier.defaultType } diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/LambdaItems.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/LambdaItems.kt index 7d6d0c27e35..57e09ab313b 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/LambdaItems.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/LambdaItems.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.completion.smart @@ -39,46 +28,49 @@ object LambdaItems { val functionExpectedInfos = expectedInfos.filter { it.fuzzyType?.type?.isFunctionOrSuspendFunctionType == true } if (functionExpectedInfos.isEmpty()) return - val functionTypes = functionExpectedInfos - .mapNotNull { it.fuzzyType?.type } - .toSet() + val functionTypes = functionExpectedInfos.mapNotNull { it.fuzzyType?.type }.toSet() val singleType = if (functionTypes.size == 1) functionTypes.single() else null val singleSignatureLength = singleType?.let(::getValueParametersCountFromFunctionType) val offerNoParametersLambda = singleSignatureLength == 0 || singleSignatureLength == 1 if (offerNoParametersLambda) { val lookupElement = LookupElementBuilder.create(LambdaSignatureTemplates.DEFAULT_LAMBDA_PRESENTATION) - .withInsertHandler(ArtificialElementInsertHandler("{ ", " }", false)) - .suppressAutoInsertion() - .assignSmartCompletionPriority(SmartCompletionItemPriority.LAMBDA_NO_PARAMS) - .addTailAndNameSimilarity(functionExpectedInfos) + .withInsertHandler(ArtificialElementInsertHandler("{ ", " }", false)) + .suppressAutoInsertion() + .assignSmartCompletionPriority(SmartCompletionItemPriority.LAMBDA_NO_PARAMS) + .addTailAndNameSimilarity(functionExpectedInfos) collection.add(lookupElement) } if (singleSignatureLength != 0) { for (functionType in functionTypes) { if (LambdaSignatureTemplates.explicitParameterTypesRequired(functionTypes, functionType)) { - collection.add(createLookupElement( + collection.add( + createLookupElement( functionType, functionExpectedInfos, LambdaSignatureTemplates.SignaturePresentation.NAMES_OR_TYPES, explicitParameterTypes = true - )) + ) + ) - } - else { - collection.add(createLookupElement( + } else { + collection.add( + createLookupElement( functionType, functionExpectedInfos, LambdaSignatureTemplates.SignaturePresentation.NAMES_AND_TYPES, explicitParameterTypes = true - )) - collection.add(createLookupElement( + ) + ) + collection.add( + createLookupElement( functionType, functionExpectedInfos, LambdaSignatureTemplates.SignaturePresentation.NAMES, explicitParameterTypes = false - )) + ) + ) } } } diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/LambdaSignatureItems.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/LambdaSignatureItems.kt index e8e4bd74ad3..7ccbbf45344 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/LambdaSignatureItems.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/LambdaSignatureItems.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.completion.smart @@ -35,10 +24,10 @@ import org.jetbrains.kotlin.types.KotlinType object LambdaSignatureItems { fun addToCollection( - collection: MutableCollection, - position: KtExpression, - bindingContext: BindingContext, - resolutionFacade: ResolutionFacade + collection: MutableCollection, + position: KtExpression, + bindingContext: BindingContext, + resolutionFacade: ResolutionFacade ) { val block = position.parent as? KtBlockExpression ?: return if (position != block.statements.first()) return @@ -47,18 +36,35 @@ object LambdaSignatureItems { val literalExpression = functionLiteral.parent as KtLambdaExpression val expectedFunctionTypes = ExpectedInfos(bindingContext, resolutionFacade, null).calculate(literalExpression) - .mapNotNull { it.fuzzyType?.type } - .filter { it.isFunctionOrSuspendFunctionType } - .toSet() + .mapNotNull { it.fuzzyType?.type } + .filter { it.isFunctionOrSuspendFunctionType } + .toSet() for (functionType in expectedFunctionTypes) { if (functionType.getValueParameterTypesFromFunctionType().isEmpty()) continue if (LambdaSignatureTemplates.explicitParameterTypesRequired(expectedFunctionTypes, functionType)) { - collection.add(createLookupElement(functionType, LambdaSignatureTemplates.SignaturePresentation.NAMES_OR_TYPES, explicitParameterTypes = true)) - } - else { - collection.add(createLookupElement(functionType, LambdaSignatureTemplates.SignaturePresentation.NAMES, explicitParameterTypes = false)) - collection.add(createLookupElement(functionType, LambdaSignatureTemplates.SignaturePresentation.NAMES_AND_TYPES, explicitParameterTypes = true)) + collection.add( + createLookupElement( + functionType, + LambdaSignatureTemplates.SignaturePresentation.NAMES_OR_TYPES, + explicitParameterTypes = true + ) + ) + } else { + collection.add( + createLookupElement( + functionType, + LambdaSignatureTemplates.SignaturePresentation.NAMES, + explicitParameterTypes = false + ) + ) + collection.add( + createLookupElement( + functionType, + LambdaSignatureTemplates.SignaturePresentation.NAMES_AND_TYPES, + explicitParameterTypes = true + ) + ) } } } diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/MultipleArgumentsItemProvider.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/MultipleArgumentsItemProvider.kt index 5ab8f493817..6b64a8eaeb1 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/MultipleArgumentsItemProvider.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/MultipleArgumentsItemProvider.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.completion.smart @@ -45,14 +34,16 @@ import org.jetbrains.kotlin.types.checker.KotlinTypeChecker import java.util.* class MultipleArgumentsItemProvider( - private val bindingContext: BindingContext, - private val smartCastCalculator: SmartCastCalculator, - private val resolutionFacade: ResolutionFacade + private val bindingContext: BindingContext, + private val smartCastCalculator: SmartCastCalculator, + private val resolutionFacade: ResolutionFacade ) { - fun addToCollection(collection: MutableCollection, - expectedInfos: Collection, - context: KtExpression) { + fun addToCollection( + collection: MutableCollection, + expectedInfos: Collection, + context: KtExpression + ) { val resolutionScope = context.getResolutionScope(bindingContext, resolutionFacade) val added = HashSet() @@ -69,7 +60,8 @@ class MultipleArgumentsItemProvider( for ((i, parameter) in parameters.withIndex()) { variables.add(variableInScope(parameter, resolutionScope) ?: break) - if (i > 0 && parameters.asSequence().drop(i + 1).all { it.hasDefaultValue() }) { // this is the last parameter or all others have default values + // this is the last parameter or all others have default values + if (i > 0 && parameters.asSequence().drop(i + 1).all { it.hasDefaultValue() }) { val lookupElement = createParametersLookupElement(variables, tail) if (added.add(lookupElement.lookupString)) { // check that we don't already have item with the same text collection.add(lookupElement) @@ -88,27 +80,26 @@ class MultipleArgumentsItemProvider( compoundIcon.setIcon(lastIcon, 0, 2 * firstIcon.iconWidth / 5, 0) compoundIcon.setIcon(firstIcon, 1, 0, 0) - return LookupElementBuilder - .create(variables.joinToString(", ") { it.name.render() }) //TODO: use code formatting settings - .withInsertHandler { context, _ -> - if (context.completionChar == Lookup.REPLACE_SELECT_CHAR) { - val offset = context.offsetMap.tryGetOffset(SmartCompletion.MULTIPLE_ARGUMENTS_REPLACEMENT_OFFSET) - if (offset != null) { - context.document.deleteString(context.tailOffset, offset) - } + return LookupElementBuilder.create(variables.joinToString(", ") { it.name.render() }) //TODO: use code formatting settings + .withInsertHandler { context, _ -> + if (context.completionChar == Lookup.REPLACE_SELECT_CHAR) { + val offset = context.offsetMap.tryGetOffset(SmartCompletion.MULTIPLE_ARGUMENTS_REPLACEMENT_OFFSET) + if (offset != null) { + context.document.deleteString(context.tailOffset, offset) } - } - .withIcon(compoundIcon) - .addTail(tail) - .assignSmartCompletionPriority(SmartCompletionItemPriority.MULTIPLE_ARGUMENTS_ITEM) + + } + .withIcon(compoundIcon) + .addTail(tail) + .assignSmartCompletionPriority(SmartCompletionItemPriority.MULTIPLE_ARGUMENTS_ITEM) } private fun variableInScope(parameter: ValueParameterDescriptor, scope: LexicalScope): VariableDescriptor? { val name = parameter.name //TODO: there can be more than one property with such name in scope and we should be able to select one (but we need API for this) val variable = scope.findVariable(name, NoLookupLocation.FROM_IDE) { !it.isExtension } - ?: scope.getVariableFromImplicitReceivers(name) ?: return null + ?: scope.getVariableFromImplicitReceivers(name) ?: return null return if (smartCastCalculator.types(variable).any { KotlinTypeChecker.DEFAULT.isSubtypeOf(it, parameter.type) }) variable else diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/NameSimilarity.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/NameSimilarity.kt index 4a12d15f0e4..75b152bd248 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/NameSimilarity.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/NameSimilarity.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.completion.smart @@ -27,16 +16,11 @@ import kotlin.math.min val NAME_SIMILARITY_KEY = Key("NAME_SIMILARITY_KEY") object NameSimilarityWeigher : LookupElementWeigher("kotlin.nameSimilarity") { - override fun weigh(element: LookupElement, context: WeighingContext) - = -(element.getUserData(NAME_SIMILARITY_KEY) ?: 0) + override fun weigh(element: LookupElement, context: WeighingContext) = -(element.getUserData(NAME_SIMILARITY_KEY) ?: 0) } -fun calcNameSimilarity(name: String, expectedInfos: Collection): Int { - return expectedInfos - .mapNotNull { it.expectedName } - .map { calcNameSimilarity(name, it) } - .max() ?: 0 -} +fun calcNameSimilarity(name: String, expectedInfos: Collection): Int = + expectedInfos.mapNotNull { it.expectedName }.map { calcNameSimilarity(name, it) }.max() ?: 0 private fun calcNameSimilarity(name: String, expectedName: String): Int { val words1 = NameUtil.nameToWordsLowerCase(name) @@ -51,8 +35,8 @@ private fun calcNameSimilarity(name: String, expectedName: String): Int { // count number of words matched at the end (but ignore number words - they are less important) val minWords = min(nonNumberWords1.size, nonNumberWords2.size) - val matchedTailLength = (0..minWords-1).firstOrNull { - i -> nonNumberWords1[nonNumberWords1.size - i - 1] != nonNumberWords2[nonNumberWords2.size - i - 1] + val matchedTailLength = (0 until minWords).firstOrNull { i -> + nonNumberWords1[nonNumberWords1.size - i - 1] != nonNumberWords2[nonNumberWords2.size - i - 1] } ?: minWords return matchedWords.size * 1000 + matchedTailLength diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/SmartCompletion.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/SmartCompletion.kt index 3f34ebf436b..c62a5023ae7 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/SmartCompletion.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/SmartCompletion.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.completion.smart @@ -54,18 +43,18 @@ interface InheritanceItemsSearcher { } class SmartCompletion( - private val expression: KtExpression, - private val resolutionFacade: ResolutionFacade, - private val bindingContext: BindingContext, - private val moduleDescriptor: ModuleDescriptor, - private val visibilityFilter: (DeclarationDescriptor) -> Boolean, - private val indicesHelper: KotlinIndicesHelper, - private val prefixMatcher: PrefixMatcher, - private val inheritorSearchScope: GlobalSearchScope, - private val toFromOriginalFileMapper: ToFromOriginalFileMapper, - private val callTypeAndReceiver: CallTypeAndReceiver<*, *>, - private val isJvmModule: Boolean, - private val forBasicCompletion: Boolean = false + private val expression: KtExpression, + private val resolutionFacade: ResolutionFacade, + private val bindingContext: BindingContext, + private val moduleDescriptor: ModuleDescriptor, + private val visibilityFilter: (DeclarationDescriptor) -> Boolean, + private val indicesHelper: KotlinIndicesHelper, + private val prefixMatcher: PrefixMatcher, + private val inheritorSearchScope: GlobalSearchScope, + private val toFromOriginalFileMapper: ToFromOriginalFileMapper, + private val callTypeAndReceiver: CallTypeAndReceiver<*, *>, + private val isJvmModule: Boolean, + private val forBasicCompletion: Boolean = false ) { private val expressionWithType = when (callTypeAndReceiver) { is CallTypeAndReceiver.DEFAULT -> @@ -87,13 +76,19 @@ class SmartCompletion( private val callableTypeExpectedInfo = expectedInfos.filterCallableExpected() val smartCastCalculator: SmartCastCalculator by lazy(LazyThreadSafetyMode.NONE) { - SmartCastCalculator(bindingContext, resolutionFacade.moduleDescriptor, expression, callTypeAndReceiver.receiver as? KtExpression, resolutionFacade) + SmartCastCalculator( + bindingContext, + resolutionFacade.moduleDescriptor, + expression, + callTypeAndReceiver.receiver as? KtExpression, + resolutionFacade + ) } val descriptorFilter: ((DeclarationDescriptor, AbstractLookupElementFactory) -> Collection)? = - { descriptor: DeclarationDescriptor, factory: AbstractLookupElementFactory -> - filterDescriptor(descriptor, factory).map { postProcess(it) } - }.takeIf { expectedInfos.isNotEmpty() } + { descriptor: DeclarationDescriptor, factory: AbstractLookupElementFactory -> + filterDescriptor(descriptor, factory).map { postProcess(it) } + }.takeIf { expectedInfos.isNotEmpty() } fun additionalItems(lookupElementFactory: LookupElementFactory): Pair, InheritanceItemsSearcher?> { val (items, inheritanceSearcher) = additionalItemsNoPostProcess(lookupElementFactory) @@ -142,12 +137,11 @@ class SmartCompletion( val subjectType = bindingContext.getType(subject) ?: return@lazy emptySet() val classDescriptor = TypeUtils.getClassDescriptor(subjectType) if (classDescriptor != null && DescriptorUtils.isEnumClass(classDescriptor)) { - val conditions = whenExpression.entries - .flatMap { it.conditions.toList() } - .filterIsInstance() + val conditions = + whenExpression.entries.flatMap { it.conditions.toList() }.filterIsInstance() for (condition in conditions) { - val selectorExpr = (condition.expression as? KtDotQualifiedExpression) - ?.selectorExpression as? KtReferenceExpression ?: continue + val selectorExpr = + (condition.expression as? KtDotQualifiedExpression)?.selectorExpression as? KtReferenceExpression ?: continue val target = bindingContext[BindingContext.REFERENCE_TARGET, selectorExpr] as? ClassDescriptor ?: continue if (DescriptorUtils.isEnumEntry(target)) { descriptorsToSkip.add(target) @@ -161,7 +155,10 @@ class SmartCompletion( return@lazy emptySet() } - private fun filterDescriptor(descriptor: DeclarationDescriptor, lookupElementFactory: AbstractLookupElementFactory): Collection { + private fun filterDescriptor( + descriptor: DeclarationDescriptor, + lookupElementFactory: AbstractLookupElementFactory + ): Collection { ProgressManager.checkCanceled() if (descriptor in descriptorsToSkip) return emptyList() @@ -169,7 +166,12 @@ class SmartCompletion( val types = descriptor.fuzzyTypesForSmartCompletion(smartCastCalculator, callTypeAndReceiver, resolutionFacade, bindingContext) val infoMatcher = { expectedInfo: ExpectedInfo -> types.matchExpectedInfo(expectedInfo) } - result.addLookupElements(descriptor, expectedInfos, infoMatcher, noNameSimilarityForReturnItself = callTypeAndReceiver is CallTypeAndReceiver.DEFAULT) { declarationDescriptor -> + result.addLookupElements( + descriptor, + expectedInfos, + infoMatcher, + noNameSimilarityForReturnItself = callTypeAndReceiver is CallTypeAndReceiver.DEFAULT + ) { declarationDescriptor -> lookupElementFactory.createStandardLookupElementsForDescriptor(declarationDescriptor, useReceiverTypes = true) } @@ -192,7 +194,12 @@ class SmartCompletion( if (!forBasicCompletion) { // basic completion adds keyword values on its own val keywordValueConsumer = object : KeywordValues.Consumer { - override fun consume(lookupString: String, expectedInfoMatcher: (ExpectedInfo) -> ExpectedInfoMatch, priority: SmartCompletionItemPriority, factory: () -> LookupElement) { + override fun consume( + lookupString: String, + expectedInfoMatcher: (ExpectedInfo) -> ExpectedInfoMatch, + priority: SmartCompletionItemPriority, + factory: () -> LookupElement + ) { items.addLookupElements(null, expectedInfos, expectedInfoMatcher) { val lookupElement = factory() lookupElement.putUserData(SMART_COMPLETION_ITEM_PRIORITY_KEY, priority) @@ -200,7 +207,14 @@ class SmartCompletion( } } } - KeywordValues.process(keywordValueConsumer, callTypeAndReceiver, bindingContext, resolutionFacade, moduleDescriptor, isJvmModule) + KeywordValues.process( + keywordValueConsumer, + callTypeAndReceiver, + bindingContext, + resolutionFacade, + moduleDescriptor, + isJvmModule + ) } if (expectedInfos.isNotEmpty()) { @@ -211,12 +225,24 @@ class SmartCompletion( } if (callTypeAndReceiver is CallTypeAndReceiver.DEFAULT) { - TypeInstantiationItems(resolutionFacade, bindingContext, visibilityFilter, toFromOriginalFileMapper, inheritorSearchScope, lookupElementFactory, forBasicCompletion, indicesHelper) - .addTo(items, inheritanceSearchers, expectedInfos) + TypeInstantiationItems( + resolutionFacade, + bindingContext, + visibilityFilter, + toFromOriginalFileMapper, + inheritorSearchScope, + lookupElementFactory, + forBasicCompletion, + indicesHelper + ).addTo(items, inheritanceSearchers, expectedInfos) if (expression is KtSimpleNameExpression) { - StaticMembers(bindingContext, lookupElementFactory, resolutionFacade, moduleDescriptor) - .addToCollection(items, expectedInfos, expression, descriptorsToSkip) + StaticMembers(bindingContext, lookupElementFactory, resolutionFacade, moduleDescriptor).addToCollection( + items, + expectedInfos, + expression, + descriptorsToSkip + ) } ClassLiteralItems.addToCollection(items, expectedInfos, lookupElementFactory.basicFactory, isJvmModule) @@ -235,7 +261,7 @@ class SmartCompletion( val entries = whenExpression.entries if (whenExpression.elseExpression == null && entry == entries.last() && entries.size != 1) { val lookupElement = LookupElementBuilder.create("else").bold().withTailText(" ->") - items.add(object: LookupElementDecorator(lookupElement) { + items.add(object : LookupElementDecorator(lookupElement) { override fun handleInsert(context: InsertionContext) { WithTailInsertHandler("->", spaceBefore = true, spaceAfter = true).handleInsert(context, delegate) } @@ -244,8 +270,11 @@ class SmartCompletion( } } - MultipleArgumentsItemProvider(bindingContext, smartCastCalculator, resolutionFacade) - .addToCollection(items, expectedInfos, expression) + MultipleArgumentsItemProvider(bindingContext, smartCastCalculator, resolutionFacade).addToCollection( + items, + expectedInfos, + expression + ) } } @@ -277,13 +306,16 @@ class SmartCompletion( super.handleInsert(context) } } - } - else { + } else { item } } - private fun MutableCollection.addThisItems(place: KtExpression, expectedInfos: Collection, smartCastCalculator: SmartCastCalculator) { + private fun MutableCollection.addThisItems( + place: KtExpression, + expectedInfos: Collection, + smartCastCalculator: SmartCastCalculator + ) { if (shouldCompleteThisItems(prefixMatcher)) { val items = thisExpressionItems(bindingContext, place, prefixMatcher.prefix, resolutionFacade) for (item in items) { @@ -330,8 +362,10 @@ class SmartCompletion( private fun createNamedArgumentWithValueLookupElement(name: Name, value: String, priority: SmartCompletionItemPriority): LookupElement { val lookupElement = LookupElementBuilder.create("${name.asString()} = $value") - .withIcon(KotlinIcons.PARAMETER) - .withInsertHandler({ context, _ -> context.document.replaceString(context.startOffset, context.tailOffset, "${name.render()} = $value") }) + .withIcon(KotlinIcons.PARAMETER) + .withInsertHandler { context, _ -> + context.document.replaceString(context.startOffset, context.tailOffset, "${name.render()} = $value") + } lookupElement.putUserData(SmartCompletionInBasicWeigher.NAMED_ARGUMENT_KEY, Unit) lookupElement.assignSmartCompletionPriority(priority) return lookupElement @@ -354,8 +388,8 @@ class SmartCompletion( // if expected types are too general, try to use expected type from outer calls var count = 0 while (true) { - val infos = ExpectedInfos(bindingContext, resolutionFacade, indicesHelper, useOuterCallsExpectedTypeCount = count) - .calculate(expression) + val infos = + ExpectedInfos(bindingContext, resolutionFacade, indicesHelper, useOuterCallsExpectedTypeCount = count).calculate(expression) if (count == 2 /* use two outer calls maximum */ || infos.none { it.fuzzyType?.isAlmostEverything() ?: false }) { return if (forBasicCompletion) infos.map { it.copy(tail = null) } @@ -376,7 +410,10 @@ class SmartCompletion( return null } - private fun MutableCollection.addCallableReferenceLookupElements(descriptor: DeclarationDescriptor, lookupElementFactory: AbstractLookupElementFactory) { + private fun MutableCollection.addCallableReferenceLookupElements( + descriptor: DeclarationDescriptor, + lookupElementFactory: AbstractLookupElementFactory + ) { if (callableTypeExpectedInfo.isEmpty()) return fun toLookupElement(descriptor: CallableDescriptor): LookupElement? { @@ -385,9 +422,10 @@ class SmartCompletion( val matchedExpectedInfos = callableTypeExpectedInfo.filter { it.matchingSubstitutor(callableReferenceType) != null } if (matchedExpectedInfos.isEmpty()) return null - var lookupElement = lookupElementFactory.createLookupElement(descriptor, useReceiverTypes = false, parametersAndTypeGrayed = true) - ?: return null - lookupElement = object: LookupElementDecorator(lookupElement) { + var lookupElement = + lookupElementFactory.createLookupElement(descriptor, useReceiverTypes = false, parametersAndTypeGrayed = true) + ?: return null + lookupElement = object : LookupElementDecorator(lookupElement) { override fun getLookupString() = "::" + delegate.lookupString override fun getAllLookupStrings() = setOf(lookupString) @@ -400,9 +438,8 @@ class SmartCompletion( } } - return lookupElement - .assignSmartCompletionPriority(SmartCompletionItemPriority.CALLABLE_REFERENCE) - .addTailAndNameSimilarity(matchedExpectedInfos) + return lookupElement.assignSmartCompletionPriority(SmartCompletionItemPriority.CALLABLE_REFERENCE) + .addTailAndNameSimilarity(matchedExpectedInfos) } when (descriptor) { @@ -415,19 +452,15 @@ class SmartCompletion( is ClassDescriptor -> { if (descriptor.modality != Modality.ABSTRACT && !descriptor.isInner) { - descriptor.constructors - .filter(visibilityFilter) - .mapNotNullTo(this, ::toLookupElement) + descriptor.constructors.filter(visibilityFilter).mapNotNullTo(this, ::toLookupElement) } } } } private fun buildForAsTypePosition(lookupElementFactory: BasicLookupElementFactory): Collection? { - val binaryExpression = ((expression.parent as? KtUserType) - ?.parent as? KtTypeReference) - ?.parent as? KtBinaryExpressionWithTypeRHS - ?: return null + val binaryExpression = + ((expression.parent as? KtUserType)?.parent as? KtTypeReference)?.parent as? KtBinaryExpressionWithTypeRHS ?: return null val elementType = binaryExpression.operationReference.getReferencedNameElementType() if (elementType != KtTokens.AS_KEYWORD && elementType != KtTokens.AS_SAFE) return null val expectedInfos = calcExpectedInfos(binaryExpression) diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/SmartCompletionSession.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/SmartCompletionSession.kt index ffb58972d29..1f2e6c42584 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/SmartCompletionSession.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/SmartCompletionSession.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.completion.smart @@ -39,10 +28,10 @@ import org.jetbrains.kotlin.resolve.calls.util.DelegatingCall import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter class SmartCompletionSession( - configuration: CompletionSessionConfiguration, - parameters: CompletionParameters, - toFromOriginalFileMapper: ToFromOriginalFileMapper, - resultSet: CompletionResultSet + configuration: CompletionSessionConfiguration, + parameters: CompletionParameters, + toFromOriginalFileMapper: ToFromOriginalFileMapper, + resultSet: CompletionResultSet ) : CompletionSession(configuration, parameters, toFromOriginalFileMapper, resultSet) { override val descriptorKindFilter: DescriptorKindFilter by lazy { @@ -62,9 +51,11 @@ class SmartCompletionSession( private val smartCompletion by lazy(LazyThreadSafetyMode.NONE) { expression?.let { - SmartCompletion(it, resolutionFacade, bindingContext, moduleDescriptor, isVisibleFilter, indicesHelper(false), - prefixMatcher, searchScope, toFromOriginalFileMapper, - callTypeAndReceiver, isJvmModule) + SmartCompletion( + it, resolutionFacade, bindingContext, moduleDescriptor, isVisibleFilter, indicesHelper(false), + prefixMatcher, searchScope, toFromOriginalFileMapper, + callTypeAndReceiver, isJvmModule + ) } } @@ -92,7 +83,8 @@ class SmartCompletionSession( val contextVariableTypesForReferenceVariants = filter?.let { withCollectRequiredContextVariableTypes { lookupElementFactory -> if (referenceVariantsCollector != null) { - val (imported, notImported) = referenceVariantsCollector.collectReferenceVariants(descriptorKindFilter).excludeNonInitializedVariable() + val (imported, notImported) = referenceVariantsCollector.collectReferenceVariants(descriptorKindFilter) + .excludeNonInitializedVariable() imported.forEach { collector.addElements(filter(it, lookupElementFactory)) } notImported.forEach { collector.addElements(filter(it, lookupElementFactory), notImported = true) } referenceVariantsCollector.collectingFinished() @@ -105,8 +97,11 @@ class SmartCompletionSession( val contextVariablesProvider = RealContextVariablesProvider(referenceVariantsHelper, position) withContextVariablesProvider(contextVariablesProvider) { lookupElementFactory -> if (filter != null && receiverTypes != null) { - val results = ExtensionFunctionTypeValueCompletion(receiverTypes, callTypeAndReceiver.callType, lookupElementFactory) - .processVariables(contextVariablesProvider) + val results = ExtensionFunctionTypeValueCompletion( + receiverTypes, + callTypeAndReceiver.callType, + lookupElementFactory + ).processVariables(contextVariablesProvider) for ((invokeDescriptor, factory) in results) { collector.addElements(filter(invokeDescriptor, factory)) } @@ -117,7 +112,9 @@ class SmartCompletionSession( collector.addElements(additionalItems) } - if (filter != null && contextVariableTypesForReferenceVariants!!.any { contextVariablesProvider.functionTypeVariables(it).isNotEmpty() }) { + if (filter != null && + contextVariableTypesForReferenceVariants!!.any { contextVariablesProvider.functionTypeVariables(it).isNotEmpty() } + ) { val (imported, notImported) = referenceVariantsWithSingleFunctionTypeParameter()!! imported.forEach { collector.addElements(filter(it, lookupElementFactory)) } notImported.forEach { collector.addElements(filter(it, lookupElementFactory), notImported = true) } @@ -129,13 +126,12 @@ class SmartCompletionSession( val staticMembersCompletion: StaticMembersCompletion? if (callTypeAndReceiver is CallTypeAndReceiver.DEFAULT) { val alreadyCollected = referenceVariantsCollector!!.allCollected.imported - staticMembersCompletion = StaticMembersCompletion(prefixMatcher, resolutionFacade, lookupElementFactory, alreadyCollected, isJvmModule) + staticMembersCompletion = + StaticMembersCompletion(prefixMatcher, resolutionFacade, lookupElementFactory, alreadyCollected, isJvmModule) val decoratedFactory = staticMembersCompletion.decoratedLookupElementFactory(ItemPriority.STATIC_MEMBER_FROM_IMPORTS) - staticMembersCompletion.membersFromImports(file) - .flatMap { filter(it, decoratedFactory) } - .forEach { collector.addElement(it) } - } - else { + staticMembersCompletion.membersFromImports(file).flatMap { filter(it, decoratedFactory) } + .forEach { collector.addElement(it) } + } else { staticMembersCompletion = null } @@ -152,7 +148,12 @@ class SmartCompletionSession( val variants = variantsAndFactory.first @Suppress("NAME_SHADOWING") val lookupElementFactory = variantsAndFactory.second variants.imported.forEach { collector.addElements(filter(it, lookupElementFactory).map { it.withReceiverCast() }) } - variants.notImportedExtensions.forEach { collector.addElements(filter(it, lookupElementFactory).map { it.withReceiverCast() }, notImported = true) } + variants.notImportedExtensions.forEach { + collector.addElements( + filter(it, lookupElementFactory).map { element -> element.withReceiverCast() }, + notImported = true + ) + } flushToResultSet() } } @@ -160,8 +161,8 @@ class SmartCompletionSession( if (staticMembersCompletion != null && configuration.staticMembers) { val decoratedFactory = staticMembersCompletion.decoratedLookupElementFactory(ItemPriority.STATIC_MEMBER) staticMembersCompletion.processMembersFromIndices(indicesHelper(false)) { - filter(it, decoratedFactory).forEach { - collector.addElement(it) + filter(it, decoratedFactory).forEach { element -> + collector.addElement(element) flushToResultSet() } } @@ -199,23 +200,24 @@ class SmartCompletionSession( override fun getValueArgumentList() = throw UnsupportedOperationException() } - val expectedInfos = ExpectedInfos(bindingContext, resolutionFacade, indicesHelper(false)) - .calculateForArgument(dummyCall, dummyArgument) + val expectedInfos = + ExpectedInfos(bindingContext, resolutionFacade, indicesHelper(false)).calculateForArgument(dummyCall, dummyArgument) collector.addElements(LambdaItems.collect(expectedInfos)) } } } - override fun createSorter(): CompletionSorter { - return super.createSorter() - .weighBefore(KindWeigher.toString(), NameSimilarityWeigher, SmartCompletionPriorityWeigher, CallableReferenceWeigher(callTypeAndReceiver.callType)) - } + override fun createSorter(): CompletionSorter = super.createSorter().weighBefore( + KindWeigher.toString(), + NameSimilarityWeigher, + SmartCompletionPriorityWeigher, + CallableReferenceWeigher(callTypeAndReceiver.callType) + ) - override fun createLookupElementFactory(contextVariablesProvider: ContextVariablesProvider): LookupElementFactory { - return super.createLookupElementFactory(contextVariablesProvider).copy( - standardLookupElementsPostProcessor = { wrapStandardLookupElement(it) } + override fun createLookupElementFactory(contextVariablesProvider: ContextVariablesProvider): LookupElementFactory = + super.createLookupElementFactory(contextVariablesProvider).copy( + standardLookupElementsPostProcessor = { wrapStandardLookupElement(it) } ) - } private fun wrapStandardLookupElement(lookupElement: LookupElement): LookupElement { val descriptor = (lookupElement.`object` as DeclarationLookupObject).descriptor diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/TypeInstantiationItems.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/TypeInstantiationItems.kt index b31dfaeecff..564180644da 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/TypeInstantiationItems.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/TypeInstantiationItems.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.completion.smart @@ -58,19 +47,19 @@ import org.jetbrains.kotlin.utils.addIfNotNull import java.util.* class TypeInstantiationItems( - val resolutionFacade: ResolutionFacade, - val bindingContext: BindingContext, - val visibilityFilter: (DeclarationDescriptor) -> Boolean, - val toFromOriginalFileMapper: ToFromOriginalFileMapper, - val inheritorSearchScope: GlobalSearchScope, - val lookupElementFactory: LookupElementFactory, - val forOrdinaryCompletion: Boolean, - val indicesHelper: KotlinIndicesHelper + val resolutionFacade: ResolutionFacade, + val bindingContext: BindingContext, + val visibilityFilter: (DeclarationDescriptor) -> Boolean, + val toFromOriginalFileMapper: ToFromOriginalFileMapper, + val inheritorSearchScope: GlobalSearchScope, + val lookupElementFactory: LookupElementFactory, + val forOrdinaryCompletion: Boolean, + val indicesHelper: KotlinIndicesHelper ) { fun addTo( - items: MutableCollection, - inheritanceSearchers: MutableCollection, - expectedInfos: Collection + items: MutableCollection, + inheritanceSearchers: MutableCollection, + expectedInfos: Collection ) { val expectedInfosGrouped = LinkedHashMap>() for (expectedInfo in expectedInfos) { @@ -86,10 +75,10 @@ class TypeInstantiationItems( } private fun addTo( - items: MutableCollection, - inheritanceSearchers: MutableCollection, - fuzzyType: FuzzyType, - tail: Tail? + items: MutableCollection, + inheritanceSearchers: MutableCollection, + fuzzyType: FuzzyType, + tail: Tail? ) { if (fuzzyType.type.isFunctionType) return // do not show "object: ..." for function types @@ -115,7 +104,8 @@ class TypeInstantiationItems( val javaClassId = JavaToKotlinClassMap.mapKotlinToJava(DescriptorUtils.getFqName(classifier)) if (javaClassId != null) { - val javaAnalog = resolutionFacade.moduleDescriptor.resolveTopLevelClass(javaClassId.asSingleFqName(), NoLookupLocation.FROM_IDE) + val javaAnalog = + resolutionFacade.moduleDescriptor.resolveTopLevelClass(javaClassId.asSingleFqName(), NoLookupLocation.FROM_IDE) if (javaAnalog != null) { inheritanceSearchers.addInheritorSearcher(javaAnalog, classDescriptor, typeArgs, fuzzyType.freeParameters, tail) } @@ -124,7 +114,11 @@ class TypeInstantiationItems( } private fun MutableCollection.addInheritorSearcher( - descriptor: ClassDescriptor, kotlinClassDescriptor: ClassDescriptor, typeArgs: List, freeParameters: Collection, tail: Tail? + descriptor: ClassDescriptor, + kotlinClassDescriptor: ClassDescriptor, + typeArgs: List, + freeParameters: Collection, + tail: Tail? ) { val _declaration = DescriptorToSourceUtilsIde.getAnyDeclaration(resolutionFacade.project, descriptor) ?: return val declaration = if (_declaration is KtDeclaration) @@ -176,11 +170,11 @@ class TypeInstantiationItems( // drop "in" and "out" from type arguments - they cannot be used in constructor call val typeArgsToUse = typeArgs.map { TypeProjectionImpl(Variance.INVARIANT, it.type) } - val allTypeArgsKnown = fuzzyType.freeParameters.isEmpty() || typeArgs.none { it.type.areTypeParametersUsedInside(fuzzyType.freeParameters) } + val allTypeArgsKnown = + fuzzyType.freeParameters.isEmpty() || typeArgs.none { it.type.areTypeParametersUsedInside(fuzzyType.freeParameters) } itemText += if (allTypeArgsKnown) { IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderTypeArguments(typeArgsToUse) - } - else { + } else { "<...>" } @@ -210,8 +204,7 @@ class TypeInstantiationItems( shortenReferences(context, startOffset, startOffset + text.length) ImplementMembersHandler().invoke(context.project, context.editor, context.file, true) - } - else { + } else { context.editor.caretModel.moveToOffset(startOffset + text1.length + 1) // put caret into "<>" shortenReferences(context, startOffset, startOffset + text.length) @@ -219,8 +212,7 @@ class TypeInstantiationItems( } lookupElement = lookupElement.suppressAutoInsertion() lookupElement = lookupElement.assignSmartCompletionPriority(SmartCompletionItemPriority.ANONYMOUS_OBJECT) - } - else { + } else { //TODO: when constructor has one parameter of lambda type with more than one parameter, generate special additional item signatureText = when (visibleConstructors.size) { 0 -> "()" @@ -228,7 +220,8 @@ class TypeInstantiationItems( 1 -> { val constructor = visibleConstructors.single() val substitutor = TypeSubstitutor.create(fuzzyType.presentationType()) - val substitutedConstructor = constructor.substitute(substitutor) ?: constructor // render original signature if failed to substitute + val substitutedConstructor = constructor.substitute(substitutor) + ?: constructor // render original signature if failed to substitute BasicLookupElementFactory.SHORT_NAMES_RENDERER.renderFunctionParameters(substitutedConstructor) } @@ -236,24 +229,33 @@ class TypeInstantiationItems( } val baseInsertHandler = when (visibleConstructors.size) { - 0 -> KotlinFunctionInsertHandler.Normal(CallType.DEFAULT, inputTypeArguments = false, inputValueArguments = false, argumentsOnly = true) + 0 -> KotlinFunctionInsertHandler.Normal( + CallType.DEFAULT, + inputTypeArguments = false, + inputValueArguments = false, + argumentsOnly = true + ) - 1 -> (lookupElementFactory.insertHandlerProvider.insertHandler(visibleConstructors.single()) as KotlinFunctionInsertHandler.Normal) - .copy(argumentsOnly = true) + 1 -> (lookupElementFactory.insertHandlerProvider + .insertHandler(visibleConstructors.single()) as KotlinFunctionInsertHandler.Normal).copy(argumentsOnly = true) - else -> KotlinFunctionInsertHandler.Normal(CallType.DEFAULT, inputTypeArguments = false, inputValueArguments = true, argumentsOnly = true) + else -> KotlinFunctionInsertHandler.Normal( + CallType.DEFAULT, + inputTypeArguments = false, + inputValueArguments = true, + argumentsOnly = true + ) } - insertHandler = object : InsertHandler { - override fun handleInsert(context: InsertionContext, item: LookupElement) { - context.document.replaceString(context.startOffset, context.tailOffset, typeText) - context.tailOffset = context.startOffset + typeText.length + insertHandler = InsertHandler { context, item -> + context.document.replaceString(context.startOffset, context.tailOffset, typeText) + context.tailOffset = context.startOffset + typeText.length - baseInsertHandler.handleInsert(context, item) + baseInsertHandler.handleInsert(context, item) - shortenReferences(context, context.startOffset, context.tailOffset) - } + shortenReferences(context, context.startOffset, context.tailOffset) } + if (baseInsertHandler.inputValueArguments) { lookupElement = lookupElement.keepOldArgumentListOnTab() } @@ -304,34 +306,39 @@ class TypeInstantiationItems( return FuzzyType(this, freeParameters).freeParameters.isNotEmpty() } - private fun addSamConstructorItem(collection: MutableCollection, - classifier: ClassifierDescriptorWithTypeParameters, - classDescriptor: ClassDescriptor?, - tail: Tail?) { + private fun addSamConstructorItem( + collection: MutableCollection, + classifier: ClassifierDescriptorWithTypeParameters, + classDescriptor: ClassDescriptor?, + tail: Tail? + ) { if (classDescriptor?.kind == ClassKind.INTERFACE) { val samConstructor = run { - val container = classifier.containingDeclaration - val scope = when (container) { + val scope = when (val container = classifier.containingDeclaration) { is PackageFragmentDescriptor -> container.getMemberScope() is ClassDescriptor -> container.unsubstitutedMemberScope else -> return } - scope.collectSyntheticStaticMembersAndConstructors(resolutionFacade, DescriptorKindFilter.FUNCTIONS, { classifier.name == it }) - .filterIsInstance() - .singleOrNull() ?: return + scope.collectSyntheticStaticMembersAndConstructors( + resolutionFacade, + DescriptorKindFilter.FUNCTIONS + ) { classifier.name == it } + .filterIsInstance() + .singleOrNull() ?: return } lookupElementFactory - .createStandardLookupElementsForDescriptor(samConstructor, useReceiverTypes = false) - .mapTo(collection) { it.assignSmartCompletionPriority(SmartCompletionItemPriority.INSTANTIATION).addTail(tail) } + .createStandardLookupElementsForDescriptor(samConstructor, useReceiverTypes = false) + .mapTo(collection) { it.assignSmartCompletionPriority(SmartCompletionItemPriority.INSTANTIATION).addTail(tail) } } } private inner class InheritanceSearcher( - private val psiClass: PsiClass, - classDescriptor: ClassDescriptor, - typeArgs: List, - private val freeParameters: Collection, - private val tail: Tail?) : InheritanceItemsSearcher { + private val psiClass: PsiClass, + classDescriptor: ClassDescriptor, + typeArgs: List, + private val freeParameters: Collection, + private val tail: Tail? + ) : InheritanceItemsSearcher { private val baseHasTypeArgs = classDescriptor.declaredTypeParameters.isNotEmpty() private val expectedType = KotlinTypeFactory.simpleNotNullType(Annotations.EMPTY, classDescriptor, typeArgs) @@ -341,9 +348,8 @@ class TypeInstantiationItems( val parameters = ClassInheritorsSearch.SearchParameters(psiClass, inheritorSearchScope, true, true, false, nameFilter) for (inheritor in ClassInheritorsSearch.search(parameters)) { val descriptor = inheritor.resolveToDescriptor( - resolutionFacade, - { toFromOriginalFileMapper.toSyntheticFile(it) } - ) ?: continue + resolutionFacade + ) { toFromOriginalFileMapper.toSyntheticFile(it) } ?: continue if (!visibilityFilter(descriptor)) continue var inheritorFuzzyType = descriptor.defaultType.toFuzzyType(descriptor.typeConstructor.parameters) diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/Utils.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/Utils.kt index 3aac49a5dad..939b571c0c9 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/Utils.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/smart/Utils.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.completion.smart @@ -23,7 +12,6 @@ import com.intellij.codeInsight.lookup.LookupElementDecorator import com.intellij.codeInsight.lookup.LookupElementPresentation import com.intellij.openapi.util.Key import org.jetbrains.kotlin.builtins.ReflectionTypes -import org.jetbrains.kotlin.builtins.isFunctionType import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.impl.LocalVariableDescriptor import org.jetbrains.kotlin.idea.completion.handlers.WithExpressionPrefixInsertHandler @@ -46,10 +34,10 @@ import org.jetbrains.kotlin.util.descriptorsEqualWithSubstitution import java.util.* class ArtificialElementInsertHandler( - private val textBeforeCaret: String, - private val textAfterCaret: String, - private val shortenRefs: Boolean -) : InsertHandler{ + private val textBeforeCaret: String, + private val textAfterCaret: String, + private val shortenRefs: Boolean +) : InsertHandler { override fun handleInsert(context: InsertionContext, item: LookupElement) { val offset = context.editor.caretModel.offset val startOffset = offset - item.lookupString.length @@ -67,38 +55,36 @@ fun mergeTails(tails: Collection): Tail? { return tails.singleOrNull() ?: tails.toSet().singleOrNull() } -fun LookupElement.addTail(tail: Tail?): LookupElement { - return when (tail) { - null -> this +fun LookupElement.addTail(tail: Tail?): LookupElement = when (tail) { + null -> this - Tail.COMMA -> object: LookupElementDecorator(this) { - override fun handleInsert(context: InsertionContext) { - WithTailInsertHandler.COMMA.handleInsert(context, delegate) - } + Tail.COMMA -> object : LookupElementDecorator(this) { + override fun handleInsert(context: InsertionContext) { + WithTailInsertHandler.COMMA.handleInsert(context, delegate) } + } - Tail.RPARENTH -> object: LookupElementDecorator(this) { - override fun handleInsert(context: InsertionContext) { - WithTailInsertHandler.RPARENTH.handleInsert(context, delegate) - } + Tail.RPARENTH -> object : LookupElementDecorator(this) { + override fun handleInsert(context: InsertionContext) { + WithTailInsertHandler.RPARENTH.handleInsert(context, delegate) } + } - Tail.RBRACKET -> object: LookupElementDecorator(this) { - override fun handleInsert(context: InsertionContext) { - WithTailInsertHandler.RBRACKET.handleInsert(context, delegate) - } + Tail.RBRACKET -> object : LookupElementDecorator(this) { + override fun handleInsert(context: InsertionContext) { + WithTailInsertHandler.RBRACKET.handleInsert(context, delegate) } + } - Tail.ELSE -> object: LookupElementDecorator(this) { - override fun handleInsert(context: InsertionContext) { - WithTailInsertHandler.ELSE.handleInsert(context, delegate) - } + Tail.ELSE -> object : LookupElementDecorator(this) { + override fun handleInsert(context: InsertionContext) { + WithTailInsertHandler.ELSE.handleInsert(context, delegate) } + } - Tail.RBRACE -> object: LookupElementDecorator(this) { - override fun handleInsert(context: InsertionContext) { - WithTailInsertHandler.RBRACE.handleInsert(context, delegate) - } + Tail.RBRACE -> object : LookupElementDecorator(this) { + override fun handleInsert(context: InsertionContext) { + WithTailInsertHandler.RBRACE.handleInsert(context, delegate) } } } @@ -121,8 +107,8 @@ fun LookupElement.withOptions(options: ItemOptions): LookupElement { } fun LookupElement.addTailAndNameSimilarity( - matchedExpectedInfos: Collection, - nameSimilarityExpectedInfos: Collection = matchedExpectedInfos + matchedExpectedInfos: Collection, + nameSimilarityExpectedInfos: Collection = matchedExpectedInfos ): LookupElement { val lookupElement = addTail(mergeTails(matchedExpectedInfos.map { it.tail })) val similarity = calcNameSimilarity(lookupElement.lookupString, nameSimilarityExpectedInfos) @@ -134,8 +120,8 @@ fun LookupElement.addTailAndNameSimilarity( class ExpectedInfoMatch private constructor( - val substitutor: TypeSubstitutor?, - val makeNotNullable: Boolean + val substitutor: TypeSubstitutor?, + val makeNotNullable: Boolean ) { fun isMatch() = substitutor != null && !makeNotNullable @@ -165,18 +151,20 @@ fun Collection.matchExpectedInfo(expectedInfo: ExpectedInfo): Expecte fun FuzzyType.matchExpectedInfo(expectedInfo: ExpectedInfo) = listOf(this).matchExpectedInfo(expectedInfo) -fun MutableCollection.addLookupElements( - descriptor: TDescriptor, - expectedInfos: Collection, - infoMatcher: (ExpectedInfo) -> ExpectedInfoMatch, - noNameSimilarityForReturnItself: Boolean = false, - lookupElementFactory: (TDescriptor) -> Collection +fun MutableCollection.addLookupElements( + descriptor: TDescriptor, + expectedInfos: Collection, + infoMatcher: (ExpectedInfo) -> ExpectedInfoMatch, + noNameSimilarityForReturnItself: Boolean = false, + lookupElementFactory: (TDescriptor) -> Collection ) { class ItemData(val descriptor: TDescriptor, val itemOptions: ItemOptions) { @Suppress("UNCHECKED_CAST") - override fun equals(other: Any?) - = descriptorsEqualWithSubstitution(this.descriptor, (other as? ItemData)?.descriptor) && itemOptions == - (other as? ItemData)?.itemOptions + override fun equals(other: Any?) = descriptorsEqualWithSubstitution( + this.descriptor, + (other as? ItemData)?.descriptor + ) && itemOptions == (other as? ItemData)?.itemOptions + override fun hashCode() = if (this.descriptor != null) this.descriptor.original.hashCode() else 0 } @@ -194,18 +182,16 @@ fun MutableCollection.addLoo } } - if (!matchedInfos.isEmpty()) { + if (matchedInfos.isNotEmpty()) { for ((itemData, infos) in matchedInfos) { val lookupElements = itemData.createLookupElements() val nameSimilarityInfos = if (noNameSimilarityForReturnItself && descriptor is CallableDescriptor) { infos.filter { (it.additionalData as? ReturnValueAdditionalData)?.callable != descriptor } // do not calculate name similarity with function itself in its return - } - else + } else infos lookupElements.mapTo(this) { it.addTailAndNameSimilarity(infos, nameSimilarityInfos) } } - } - else { + } else { for ((itemData, infos) in makeNullableInfos) { addLookupElementsForNullable({ itemData.createLookupElements() }, infos) } @@ -220,7 +206,10 @@ private fun T.substituteFixed(substitutor: TypeSubs return this.substitute(substitutor) as T } -private fun MutableCollection.addLookupElementsForNullable(factory: () -> Collection, matchedInfos: Collection) { +private fun MutableCollection.addLookupElementsForNullable( + factory: () -> Collection, + matchedInfos: Collection +) { fun LookupElement.postProcess(): LookupElement { var element = this element = element.suppressAutoInsertion() @@ -230,11 +219,12 @@ private fun MutableCollection.addLookupElementsForNullable(factor } factory().mapTo(this) { - object: LookupElementDecorator(it) { + object : LookupElementDecorator(it) { override fun renderElement(presentation: LookupElementPresentation) { super.renderElement(presentation) presentation.itemText = "!! " + presentation.itemText } + override fun handleInsert(context: InsertionContext) { WithTailInsertHandler("!!", spaceBefore = false, spaceAfter = false).handleInsert(context, delegate) } @@ -242,11 +232,12 @@ private fun MutableCollection.addLookupElementsForNullable(factor } factory().mapTo(this) { - object: LookupElementDecorator(it) { + object : LookupElementDecorator(it) { override fun renderElement(presentation: LookupElementPresentation) { super.renderElement(presentation) presentation.itemText = "?: " + presentation.itemText } + override fun handleInsert(context: InsertionContext) { WithTailInsertHandler("?:", spaceBefore = true, spaceAfter = true).handleInsert(context, delegate) //TODO: code style } @@ -258,10 +249,10 @@ fun CallableDescriptor.callableReferenceType(resolutionFacade: ResolutionFacade, if (!CallType.CALLABLE_REFERENCE.descriptorKindFilter.accepts(this)) return null // not supported by callable references return DoubleColonExpressionResolver.createKCallableTypeForReference( - this, - lhs, - resolutionFacade.getFrontendService(ReflectionTypes::class.java), - resolutionFacade.moduleDescriptor + this, + lhs, + resolutionFacade.getFrontendService(ReflectionTypes::class.java), + resolutionFacade.moduleDescriptor )?.toFuzzyType(emptyList()) } @@ -302,10 +293,10 @@ fun LookupElement.assignSmartCompletionPriority(priority: SmartCompletionItemPri var LookupElement.isProbableKeyword: Boolean by NotNullableUserDataProperty(Key.create("PROBABLE_KEYWORD_KEY"), false) fun DeclarationDescriptor.fuzzyTypesForSmartCompletion( - smartCastCalculator: SmartCastCalculator, - callTypeAndReceiver: CallTypeAndReceiver<*, *>, - resolutionFacade: ResolutionFacade, - bindingContext: BindingContext + smartCastCalculator: SmartCastCalculator, + callTypeAndReceiver: CallTypeAndReceiver<*, *>, + resolutionFacade: ResolutionFacade, + bindingContext: BindingContext ): Collection { if (callTypeAndReceiver is CallTypeAndReceiver.CALLABLE_REFERENCE) { val lhs = callTypeAndReceiver.receiver?.let { bindingContext[BindingContext.DOUBLE_COLON_LHS, it] } @@ -319,24 +310,22 @@ fun DeclarationDescriptor.fuzzyTypesForSmartCompletion( if (returnType.type.isNothing() || returnType.type.isNullableNothing() || returnType.type.isDynamic() || - returnType.isAlmostEverything()) { + returnType.isAlmostEverything() + ) { return emptyList() } return if (this is VariableDescriptor) { //TODO: generic properties! smartCastCalculator.types(this).map { it.toFuzzyType(emptyList()) } - } - else { + } else { listOf(returnType) } - } - else if (this is ClassDescriptor && kind.isSingleton) { + } else if (this is ClassDescriptor && kind.isSingleton) { return listOf(defaultType.toFuzzyType(emptyList())) - } - else { + } else { return emptyList() } } -fun Collection.filterCallableExpected() - = filter { it.fuzzyType != null && ReflectionTypes.isCallableType(it.fuzzyType!!.type) } +fun Collection.filterCallableExpected() = + filter { it.fuzzyType != null && ReflectionTypes.isCallableType(it.fuzzyType!!.type) } diff --git a/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/AbstractCompiledKotlinInJavaCompletionTest.kt b/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/AbstractCompiledKotlinInJavaCompletionTest.kt index e4a65490366..db43ec6fd0c 100644 --- a/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/AbstractCompiledKotlinInJavaCompletionTest.kt +++ b/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/AbstractCompiledKotlinInJavaCompletionTest.kt @@ -13,6 +13,7 @@ abstract class AbstractCompiledKotlinInJavaCompletionTest : KotlinFixtureComplet override fun getPlatform() = JvmPlatforms.unspecifiedJvmPlatform override fun getProjectDescriptor() = - SdkAndMockLibraryProjectDescriptor(COMPLETION_TEST_DATA_BASE_PATH + "/injava/mockLib", false) + SdkAndMockLibraryProjectDescriptor("$COMPLETION_TEST_DATA_BASE_PATH/injava/mockLib", false) + override fun defaultCompletionType() = CompletionType.BASIC } diff --git a/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/AbstractCompletionIncrementalResolveTest.kt b/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/AbstractCompletionIncrementalResolveTest.kt index 04bdc232186..7c9537903d9 100644 --- a/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/AbstractCompletionIncrementalResolveTest.kt +++ b/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/AbstractCompletionIncrementalResolveTest.kt @@ -40,10 +40,12 @@ abstract class AbstractCompletionIncrementalResolveTest : KotlinLightCodeInsight assertTrue("\"$CHANGE_MARKER\" is missing in file \"$testPath\"", changeMarkerOffset >= 0) val textToType = InTextDirectivesUtils.findArrayWithPrefixes(document.text, TYPE_DIRECTIVE_PREFIX).singleOrNull() - ?.let { StringUtil.unquoteString(it) } + ?.let { StringUtil.unquoteString(it) } val backspaceCount = InTextDirectivesUtils.getPrefixedInt(document.text, BACKSPACES_DIRECTIVE_PREFIX) - assertTrue("At least one of \"$TYPE_DIRECTIVE_PREFIX\" and \"$BACKSPACES_DIRECTIVE_PREFIX\" should be defined", - textToType != null || backspaceCount != null) + assertTrue( + "At least one of \"$TYPE_DIRECTIVE_PREFIX\" and \"$BACKSPACES_DIRECTIVE_PREFIX\" should be defined", + textToType != null || backspaceCount != null + ) val beforeMarker = document.createRangeMarker(beforeMarkerOffset, beforeMarkerOffset + BEFORE_MARKER.length) val changeMarker = document.createRangeMarker(changeMarkerOffset, changeMarkerOffset + CHANGE_MARKER.length) @@ -76,15 +78,16 @@ abstract class AbstractCompletionIncrementalResolveTest : KotlinLightCodeInsight if (caretMarker != null) { editor.caretModel.moveToOffset(caretMarker.startOffset) - } - else { + } else { editor.caretModel.moveToOffset(changeMarker.endOffset) } - testCompletion(FileUtil.loadFile(file, true), - JvmPlatforms.unspecifiedJvmPlatform, - { completionType, count -> myFixture.complete(completionType, count) }, - additionalValidDirectives = listOf(TYPE_DIRECTIVE_PREFIX, BACKSPACES_DIRECTIVE_PREFIX)) + testCompletion( + FileUtil.loadFile(file, true), + JvmPlatforms.unspecifiedJvmPlatform, + { completionType, count -> myFixture.complete(completionType, count) }, + additionalValidDirectives = listOf(TYPE_DIRECTIVE_PREFIX, BACKSPACES_DIRECTIVE_PREFIX) + ) KotlinTestUtils.assertEqualsToFile(File(file.parent, file.nameWithoutExtension + ".log"), testLog.toString()) } finally { diff --git a/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/CompletionTestUtil.kt b/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/CompletionTestUtil.kt index a75c901cc70..8d6dab55d58 100644 --- a/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/CompletionTestUtil.kt +++ b/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/CompletionTestUtil.kt @@ -36,7 +36,10 @@ fun testCompletion( val itemsNumber = ExpectedCompletionUtils.getExpectedNumber(fileText, platform) val nothingElse = ExpectedCompletionUtils.isNothingElseExpected(fileText) - Assert.assertTrue("Should be some assertions about completion", expected.size != 0 || unexpected.size != 0 || itemsNumber != null || nothingElse) + Assert.assertTrue( + "Should be some assertions about completion", + expected.size != 0 || unexpected.size != 0 || itemsNumber != null || nothingElse + ) ExpectedCompletionUtils.assertContainsRenderedItems(expected, items, ExpectedCompletionUtils.isWithOrder(fileText), nothingElse) ExpectedCompletionUtils.assertNotContainsRenderedItems(unexpected, items) @@ -57,8 +60,7 @@ private fun testWithAutoCompleteSetting(fileText: String, doTest: () -> Unit) { settings.AUTOCOMPLETE_ON_CODE_COMPLETION = autoComplete settings.AUTOCOMPLETE_ON_SMART_TYPE_COMPLETION = autoComplete doTest() - } - finally { + } finally { settings.AUTOCOMPLETE_ON_CODE_COMPLETION = oldValue1 settings.AUTOCOMPLETE_ON_SMART_TYPE_COMPLETION = oldValue2 } diff --git a/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/ExpectedCompletionUtils.kt b/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/ExpectedCompletionUtils.kt index c45a1844437..be67bc289ce 100644 --- a/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/ExpectedCompletionUtils.kt +++ b/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/ExpectedCompletionUtils.kt @@ -63,8 +63,7 @@ object ExpectedCompletionUtils { } } - fun matches(expectedProposal: CompletionProposal): Boolean - = expectedProposal.map.entries.none { it.value != map[it.key] } + fun matches(expectedProposal: CompletionProposal): Boolean = expectedProposal.map.entries.none { it.value != map[it.key] } override fun toString(): String { val jsonObject = JsonObject() @@ -75,13 +74,13 @@ object ExpectedCompletionUtils { } companion object { - val LOOKUP_STRING: String = "lookupString" - val ALL_LOOKUP_STRINGS: String = "allLookupStrings" - val PRESENTATION_ITEM_TEXT: String = "itemText" - val PRESENTATION_TYPE_TEXT: String = "typeText" - val PRESENTATION_TAIL_TEXT: String = "tailText" - val PRESENTATION_TEXT_ATTRIBUTES: String = "attributes" - val MODULE_NAME: String = "module" + const val LOOKUP_STRING: String = "lookupString" + const val ALL_LOOKUP_STRINGS: String = "allLookupStrings" + const val PRESENTATION_ITEM_TEXT: String = "itemText" + const val PRESENTATION_TYPE_TEXT: String = "typeText" + const val PRESENTATION_TAIL_TEXT: String = "tailText" + const val PRESENTATION_TEXT_ATTRIBUTES: String = "attributes" + const val MODULE_NAME: String = "module" val validKeys: Set = setOf( LOOKUP_STRING, ALL_LOOKUP_STRINGS, PRESENTATION_ITEM_TEXT, PRESENTATION_TYPE_TEXT, PRESENTATION_TAIL_TEXT, PRESENTATION_TEXT_ATTRIBUTES, MODULE_NAME @@ -89,69 +88,67 @@ object ExpectedCompletionUtils { } } - private val UNSUPPORTED_PLATFORM_MESSAGE = "Only ${JvmPlatforms.unspecifiedJvmPlatform} and ${JsPlatforms.defaultJsPlatform} platforms are supported" + private val UNSUPPORTED_PLATFORM_MESSAGE = + "Only ${JvmPlatforms.unspecifiedJvmPlatform} and ${JsPlatforms.defaultJsPlatform} platforms are supported" - private val EXIST_LINE_PREFIX = "EXIST:" + private const val EXIST_LINE_PREFIX = "EXIST:" - private val ABSENT_LINE_PREFIX = "ABSENT:" - private val ABSENT_JS_LINE_PREFIX = "ABSENT_JS:" - private val ABSENT_JAVA_LINE_PREFIX = "ABSENT_JAVA:" + private const val ABSENT_LINE_PREFIX = "ABSENT:" + private const val ABSENT_JS_LINE_PREFIX = "ABSENT_JS:" + private const val ABSENT_JAVA_LINE_PREFIX = "ABSENT_JAVA:" - private val EXIST_JAVA_ONLY_LINE_PREFIX = "EXIST_JAVA_ONLY:" - private val EXIST_JS_ONLY_LINE_PREFIX = "EXIST_JS_ONLY:" + private const val EXIST_JAVA_ONLY_LINE_PREFIX = "EXIST_JAVA_ONLY:" + private const val EXIST_JS_ONLY_LINE_PREFIX = "EXIST_JS_ONLY:" - private val NUMBER_LINE_PREFIX = "NUMBER:" - private val NUMBER_JS_LINE_PREFIX = "NUMBER_JS:" - private val NUMBER_JAVA_LINE_PREFIX = "NUMBER_JAVA:" + private const val NUMBER_LINE_PREFIX = "NUMBER:" + private const val NUMBER_JS_LINE_PREFIX = "NUMBER_JS:" + private const val NUMBER_JAVA_LINE_PREFIX = "NUMBER_JAVA:" - private val NOTHING_ELSE_PREFIX = "NOTHING_ELSE" - private val RUN_HIGHLIGHTING_BEFORE_PREFIX = "RUN_HIGHLIGHTING_BEFORE" + private const val NOTHING_ELSE_PREFIX = "NOTHING_ELSE" + private const val RUN_HIGHLIGHTING_BEFORE_PREFIX = "RUN_HIGHLIGHTING_BEFORE" - private val INVOCATION_COUNT_PREFIX = "INVOCATION_COUNT:" - private val WITH_ORDER_PREFIX = "WITH_ORDER" - private val AUTOCOMPLETE_SETTING_PREFIX = "AUTOCOMPLETE_SETTING:" + private const val INVOCATION_COUNT_PREFIX = "INVOCATION_COUNT:" + private const val WITH_ORDER_PREFIX = "WITH_ORDER" + private const val AUTOCOMPLETE_SETTING_PREFIX = "AUTOCOMPLETE_SETTING:" - val RUNTIME_TYPE: String = "RUNTIME_TYPE:" + const val RUNTIME_TYPE: String = "RUNTIME_TYPE:" - private val COMPLETION_TYPE_PREFIX = "COMPLETION_TYPE:" + private const val COMPLETION_TYPE_PREFIX = "COMPLETION_TYPE:" val KNOWN_PREFIXES: List = ImmutableList.of( - "LANGUAGE_VERSION:", - EXIST_LINE_PREFIX, - ABSENT_LINE_PREFIX, - ABSENT_JS_LINE_PREFIX, - ABSENT_JAVA_LINE_PREFIX, - EXIST_JAVA_ONLY_LINE_PREFIX, - EXIST_JS_ONLY_LINE_PREFIX, - NUMBER_LINE_PREFIX, - NUMBER_JS_LINE_PREFIX, - NUMBER_JAVA_LINE_PREFIX, - INVOCATION_COUNT_PREFIX, - WITH_ORDER_PREFIX, - AUTOCOMPLETE_SETTING_PREFIX, - NOTHING_ELSE_PREFIX, - RUN_HIGHLIGHTING_BEFORE_PREFIX, - RUNTIME_TYPE, - COMPLETION_TYPE_PREFIX, - LightClassComputationControl.LIGHT_CLASS_DIRECTIVE, - AstAccessControl.ALLOW_AST_ACCESS_DIRECTIVE) + "LANGUAGE_VERSION:", + EXIST_LINE_PREFIX, + ABSENT_LINE_PREFIX, + ABSENT_JS_LINE_PREFIX, + ABSENT_JAVA_LINE_PREFIX, + EXIST_JAVA_ONLY_LINE_PREFIX, + EXIST_JS_ONLY_LINE_PREFIX, + NUMBER_LINE_PREFIX, + NUMBER_JS_LINE_PREFIX, + NUMBER_JAVA_LINE_PREFIX, + INVOCATION_COUNT_PREFIX, + WITH_ORDER_PREFIX, + AUTOCOMPLETE_SETTING_PREFIX, + NOTHING_ELSE_PREFIX, + RUN_HIGHLIGHTING_BEFORE_PREFIX, + RUNTIME_TYPE, + COMPLETION_TYPE_PREFIX, + LightClassComputationControl.LIGHT_CLASS_DIRECTIVE, + AstAccessControl.ALLOW_AST_ACCESS_DIRECTIVE + ) - fun itemsShouldExist(fileText: String, platform: TargetPlatform?): Array { - return when { - platform.isJvm() -> processProposalAssertions(fileText, EXIST_LINE_PREFIX, EXIST_JAVA_ONLY_LINE_PREFIX) - platform.isJs() -> processProposalAssertions(fileText, EXIST_LINE_PREFIX, EXIST_JS_ONLY_LINE_PREFIX) - platform == null -> processProposalAssertions(fileText, EXIST_LINE_PREFIX) - else -> throw IllegalArgumentException(UNSUPPORTED_PLATFORM_MESSAGE) - } + fun itemsShouldExist(fileText: String, platform: TargetPlatform?): Array = when { + platform.isJvm() -> processProposalAssertions(fileText, EXIST_LINE_PREFIX, EXIST_JAVA_ONLY_LINE_PREFIX) + platform.isJs() -> processProposalAssertions(fileText, EXIST_LINE_PREFIX, EXIST_JS_ONLY_LINE_PREFIX) + platform == null -> processProposalAssertions(fileText, EXIST_LINE_PREFIX) + else -> throw IllegalArgumentException(UNSUPPORTED_PLATFORM_MESSAGE) } - fun itemsShouldAbsent(fileText: String, platform: TargetPlatform?): Array { - return when { - platform.isJvm() -> processProposalAssertions(fileText, ABSENT_LINE_PREFIX, ABSENT_JAVA_LINE_PREFIX, EXIST_JS_ONLY_LINE_PREFIX) - platform.isJs() -> processProposalAssertions(fileText, ABSENT_LINE_PREFIX, ABSENT_JS_LINE_PREFIX, EXIST_JAVA_ONLY_LINE_PREFIX) - platform == null -> processProposalAssertions(fileText, ABSENT_LINE_PREFIX) - else -> throw IllegalArgumentException(UNSUPPORTED_PLATFORM_MESSAGE) - } + fun itemsShouldAbsent(fileText: String, platform: TargetPlatform?): Array = when { + platform.isJvm() -> processProposalAssertions(fileText, ABSENT_LINE_PREFIX, ABSENT_JAVA_LINE_PREFIX, EXIST_JS_ONLY_LINE_PREFIX) + platform.isJs() -> processProposalAssertions(fileText, ABSENT_LINE_PREFIX, ABSENT_JS_LINE_PREFIX, EXIST_JAVA_ONLY_LINE_PREFIX) + platform == null -> processProposalAssertions(fileText, ABSENT_LINE_PREFIX) + else -> throw IllegalArgumentException(UNSUPPORTED_PLATFORM_MESSAGE) } fun processProposalAssertions(fileText: String, vararg prefixes: String): Array { @@ -161,16 +158,13 @@ object ExpectedCompletionUtils { val parser = JsonParser() val json: JsonElement? = try { parser.parse(proposalStr) - } - catch(t: Throwable) { + } catch (t: Throwable) { throw RuntimeException("Error parsing '$proposalStr'", t) } proposals.add(CompletionProposal(json as JsonObject)) - } - else if (proposalStr.startsWith("\"") && proposalStr.endsWith("\"")) { + } else if (proposalStr.startsWith("\"") && proposalStr.endsWith("\"")) { proposals.add(CompletionProposal(proposalStr.substring(1, proposalStr.length - 1))) - } - else { + } else { for (item in proposalStr.split(",")) { proposals.add(CompletionProposal(item.trim())) } @@ -180,50 +174,44 @@ object ExpectedCompletionUtils { return ArrayUtil.toObjectArray(proposals, CompletionProposal::class.java) } - fun getExpectedNumber(fileText: String, platform: TargetPlatform?): Int? { - return when { - platform == null -> InTextDirectivesUtils.getPrefixedInt(fileText, NUMBER_LINE_PREFIX) - platform.isJvm() -> getPlatformExpectedNumber(fileText, NUMBER_JAVA_LINE_PREFIX) - platform.isJs() -> getPlatformExpectedNumber(fileText, NUMBER_JS_LINE_PREFIX) - else -> throw IllegalArgumentException(UNSUPPORTED_PLATFORM_MESSAGE) - } + fun getExpectedNumber(fileText: String, platform: TargetPlatform?): Int? = when { + platform == null -> InTextDirectivesUtils.getPrefixedInt(fileText, NUMBER_LINE_PREFIX) + platform.isJvm() -> getPlatformExpectedNumber(fileText, NUMBER_JAVA_LINE_PREFIX) + platform.isJs() -> getPlatformExpectedNumber(fileText, NUMBER_JS_LINE_PREFIX) + else -> throw IllegalArgumentException(UNSUPPORTED_PLATFORM_MESSAGE) } - fun isNothingElseExpected(fileText: String): Boolean { - return InTextDirectivesUtils.findLinesWithPrefixesRemoved(fileText, NOTHING_ELSE_PREFIX).isNotEmpty() - } + fun isNothingElseExpected(fileText: String): Boolean = + InTextDirectivesUtils.findLinesWithPrefixesRemoved(fileText, NOTHING_ELSE_PREFIX).isNotEmpty() - fun shouldRunHighlightingBeforeCompletion(fileText: String): Boolean { - return InTextDirectivesUtils.findLinesWithPrefixesRemoved(fileText, RUN_HIGHLIGHTING_BEFORE_PREFIX).isNotEmpty() - } + fun shouldRunHighlightingBeforeCompletion(fileText: String): Boolean = + InTextDirectivesUtils.findLinesWithPrefixesRemoved(fileText, RUN_HIGHLIGHTING_BEFORE_PREFIX).isNotEmpty() - fun getInvocationCount(fileText: String): Int? { - return InTextDirectivesUtils.getPrefixedInt(fileText, INVOCATION_COUNT_PREFIX) - } + fun getInvocationCount(fileText: String): Int? = InTextDirectivesUtils.getPrefixedInt(fileText, INVOCATION_COUNT_PREFIX) - fun getCompletionType(fileText: String): CompletionType? { - val completionTypeString = InTextDirectivesUtils.findStringWithPrefixes(fileText, COMPLETION_TYPE_PREFIX) - return when (completionTypeString) { + fun getCompletionType(fileText: String): CompletionType? = + when (val completionTypeString = InTextDirectivesUtils.findStringWithPrefixes(fileText, COMPLETION_TYPE_PREFIX)) { "BASIC" -> CompletionType.BASIC "SMART" -> CompletionType.SMART null -> null else -> error("Unknown completion type: $completionTypeString") } - } - fun getAutocompleteSetting(fileText: String): Boolean? { - return InTextDirectivesUtils.getPrefixedBoolean(fileText, AUTOCOMPLETE_SETTING_PREFIX) - } + fun getAutocompleteSetting(fileText: String): Boolean? = InTextDirectivesUtils.getPrefixedBoolean(fileText, AUTOCOMPLETE_SETTING_PREFIX) - fun isWithOrder(fileText: String): Boolean { - return !InTextDirectivesUtils.findLinesWithPrefixesRemoved(fileText, WITH_ORDER_PREFIX).isEmpty() - } + fun isWithOrder(fileText: String): Boolean = + InTextDirectivesUtils.findLinesWithPrefixesRemoved(fileText, WITH_ORDER_PREFIX).isNotEmpty() fun assertDirectivesValid(fileText: String, additionalValidDirectives: Collection = emptyList()) { InTextDirectivesUtils.assertHasUnknownPrefixes(fileText, KNOWN_PREFIXES + additionalValidDirectives) } - fun assertContainsRenderedItems(expected: Array, items: Array, checkOrder: Boolean, nothingElse: Boolean) { + fun assertContainsRenderedItems( + expected: Array, + items: Array, + checkOrder: Boolean, + nothingElse: Boolean + ) { val itemsInformation = getItemsInformation(items) val allItemsString = listToString(itemsInformation) @@ -235,13 +223,15 @@ object ExpectedCompletionUtils { var isFound = false for (index in itemsInformation.indices) { - val proposal = itemsInformation.get(index) + val proposal = itemsInformation[index] if (proposal.matches(expectedProposal)) { isFound = true - Assert.assertTrue("Invalid order of existent elements in $allItemsString", - !checkOrder || index > indexOfPrevious) + Assert.assertTrue( + "Invalid order of existent elements in $allItemsString", + !checkOrder || index > indexOfPrevious + ) indexOfPrevious = index leftItems?.remove(proposal) @@ -253,14 +243,13 @@ object ExpectedCompletionUtils { if (!isFound) { if (allItemsString.isEmpty()) { Assert.fail("Completion is empty but $expectedProposal is expected") - } - else { + } else { Assert.fail("Expected $expectedProposal not found in:\n$allItemsString") } } } - if (leftItems != null && !leftItems.isEmpty()) { + if (leftItems != null && leftItems.isNotEmpty()) { Assert.fail("No items not mentioned in EXIST directives expected but some found:\n" + listToString(leftItems)) } } @@ -268,8 +257,10 @@ object ExpectedCompletionUtils { private fun getPlatformExpectedNumber(fileText: String, platformNumberPrefix: String): Int? { val prefixedInt = InTextDirectivesUtils.getPrefixedInt(fileText, platformNumberPrefix) if (prefixedInt != null) { - Assert.assertNull("There shouldn't be $NUMBER_LINE_PREFIX and $platformNumberPrefix prefixes set in same time", - InTextDirectivesUtils.getPrefixedInt(fileText, NUMBER_LINE_PREFIX)) + Assert.assertNull( + "There shouldn't be $NUMBER_LINE_PREFIX and $platformNumberPrefix prefixes set in same time", + InTextDirectivesUtils.getPrefixedInt(fileText, NUMBER_LINE_PREFIX) + ) return prefixedInt } @@ -282,8 +273,10 @@ object ExpectedCompletionUtils { for (unexpectedProposal in unexpected) { for (proposal in itemsInformation) { - Assert.assertFalse("Unexpected '$unexpectedProposal' presented in $allItemsString", - proposal.matches(unexpectedProposal)) + Assert.assertFalse( + "Unexpected '$unexpectedProposal' presented in $allItemsString", + proposal.matches(unexpectedProposal) + ) } } } @@ -296,21 +289,21 @@ object ExpectedCompletionUtils { item.renderElement(presentation) val map = HashMap() - map.put(CompletionProposal.LOOKUP_STRING, item.lookupString) + map[CompletionProposal.LOOKUP_STRING] = item.lookupString - map.put(CompletionProposal.ALL_LOOKUP_STRINGS, item.allLookupStrings.sorted().joinToString()) + map[CompletionProposal.ALL_LOOKUP_STRINGS] = item.allLookupStrings.sorted().joinToString() if (presentation.itemText != null) { - map.put(CompletionProposal.PRESENTATION_ITEM_TEXT, presentation.itemText) - map.put(CompletionProposal.PRESENTATION_TEXT_ATTRIBUTES, textAttributes(presentation)) + map[CompletionProposal.PRESENTATION_ITEM_TEXT] = presentation.itemText + map[CompletionProposal.PRESENTATION_TEXT_ATTRIBUTES] = textAttributes(presentation) } if (presentation.typeText != null) { - map.put(CompletionProposal.PRESENTATION_TYPE_TEXT, presentation.typeText) + map[CompletionProposal.PRESENTATION_TYPE_TEXT] = presentation.typeText } if (presentation.tailText != null) { - map.put(CompletionProposal.PRESENTATION_TAIL_TEXT, presentation.tailText) + map[CompletionProposal.PRESENTATION_TAIL_TEXT] = presentation.tailText } item.moduleName?.let { map.put(CompletionProposal.MODULE_NAME, it) diff --git a/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/LightClassComputationControl.kt b/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/LightClassComputationControl.kt index c4edadbba8a..0b5582d3089 100644 --- a/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/LightClassComputationControl.kt +++ b/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/LightClassComputationControl.kt @@ -20,7 +20,7 @@ import java.util.Collections.synchronizedList object LightClassComputationControl { fun testWithControl(project: Project, testText: String, testBody: () -> Unit) { val expectedLightClassFqNames = InTextDirectivesUtils.findLinesWithPrefixesRemoved( - testText, "// $LIGHT_CLASS_DIRECTIVE" + testText, "// $LIGHT_CLASS_DIRECTIVE" ).map { it.trim() } val actualFqNames = synchronizedList(ArrayList()) @@ -37,14 +37,14 @@ object LightClassComputationControl { if (expectedLightClassFqNames.toSortedSet() != synchronized(actualFqNames) { actualFqNames.toSortedSet() }) { Assert.fail( - "Expected to compute: ${expectedLightClassFqNames.prettyToString()}\n" + - "Actually computed: ${actualFqNames.prettyToString()}\n" + - "Use $LIGHT_CLASS_DIRECTIVE to specify expected light class computations" + "Expected to compute: ${expectedLightClassFqNames.prettyToString()}\n" + + "Actually computed: ${actualFqNames.prettyToString()}\n" + + "Use $LIGHT_CLASS_DIRECTIVE to specify expected light class computations" ) } } - val LIGHT_CLASS_DIRECTIVE = "LIGHT_CLASS:" + const val LIGHT_CLASS_DIRECTIVE = "LIGHT_CLASS:" private fun List.prettyToString() = if (isEmpty()) "" else joinToString() } @@ -56,8 +56,7 @@ inline fun ComponentManager.withServiceRegistered(instance: picoContainer.unregisterComponent(key) picoContainer.registerComponentInstance(key, instance) return body() - } - finally { + } finally { picoContainer.unregisterComponent(key) } } diff --git a/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/handlers/BasicCompletionHandlerTest.kt b/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/handlers/BasicCompletionHandlerTest.kt index 1057fb5314d..9650ffa2cce 100644 --- a/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/handlers/BasicCompletionHandlerTest.kt +++ b/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/handlers/BasicCompletionHandlerTest.kt @@ -14,8 +14,8 @@ import java.io.File @Deprecated("All tests from here to be moved to the generated test") @RunWith(JUnit3WithIdeaConfigurationRunner::class) -class BasicCompletionHandlerTest : CompletionHandlerTestBase(){ - private fun checkResult(){ +class BasicCompletionHandlerTest : CompletionHandlerTestBase() { + private fun checkResult() { fixture.checkResultByFile(getTestName(false) + ".kt.after") } @@ -144,7 +144,11 @@ class BasicCompletionHandlerTest : CompletionHandlerTestBase(){ fun testInfixCall() = doTest(1, "to", null, null, '\n') fun testInfixCallOnSpace() = doTest(1, "to", null, null, ' ') - fun testImportedEnumMember() { doTest(1, "AAA", null, null, '\n') } + fun testImportedEnumMember() { + doTest(1, "AAA", null, null, '\n') + } - fun testInnerClass() { doTest(1, "Inner", null, null, '\n') } + fun testInnerClass() { + doTest(1, "Inner", null, null, '\n') + } } diff --git a/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/handlers/CompletionHandlerTestBase.kt b/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/handlers/CompletionHandlerTestBase.kt index 59059c75889..936c7a14c6b 100644 --- a/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/handlers/CompletionHandlerTestBase.kt +++ b/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/handlers/CompletionHandlerTestBase.kt @@ -82,7 +82,7 @@ abstract class CompletionHandlerTestBase : KotlinLightCodeInsightFixtureTestCase return items.firstOrNull() } - var foundElement : LookupElement? = null + var foundElement: LookupElement? = null val presentation = LookupElementPresentation() for (lookupElement in items) { val lookupOk = if (lookupString != null) lookupElement.lookupString == lookupString else true @@ -93,8 +93,7 @@ abstract class CompletionHandlerTestBase : KotlinLightCodeInsightFixtureTestCase val textOk = if (itemText != null) { val itemItemText = presentation.itemText itemItemText != null && itemItemText == itemText - } - else { + } else { true } @@ -102,14 +101,20 @@ abstract class CompletionHandlerTestBase : KotlinLightCodeInsightFixtureTestCase val tailOk = if (tailText != null) { val itemTailText = presentation.tailText itemTailText != null && itemTailText == tailText - } - else { + } else { true } if (tailOk) { if (foundElement != null) { - val dump = ExpectedCompletionUtils.listToString(ExpectedCompletionUtils.getItemsInformation(arrayOf(foundElement, lookupElement))) + val dump = ExpectedCompletionUtils.listToString( + ExpectedCompletionUtils.getItemsInformation( + arrayOf( + foundElement, + lookupElement + ) + ) + ) fail("Several elements satisfy to completion restrictions:\n$dump") } @@ -134,8 +139,7 @@ abstract class CompletionHandlerTestBase : KotlinLightCodeInsightFixtureTestCase lookup.focusDegree = LookupImpl.FocusDegree.FOCUSED if (LookupEvent.isSpecialCompletionChar(completionChar)) { lookup.finishLookup(completionChar) - } - else { + } else { fixture.type(completionChar) } } diff --git a/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/handlers/SmartCompletionMultifileHandlerTest.kt b/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/handlers/SmartCompletionMultifileHandlerTest.kt index cc74d811865..9d42e99626f 100644 --- a/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/handlers/SmartCompletionMultifileHandlerTest.kt +++ b/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/handlers/SmartCompletionMultifileHandlerTest.kt @@ -16,15 +16,25 @@ import java.io.File @RunWith(JUnit3WithIdeaConfigurationRunner::class) class SmartCompletionMultifileHandlerTest : KotlinCompletionTestCase() { - fun testImportExtensionFunction() { doTest() } + fun testImportExtensionFunction() { + doTest() + } - fun testImportExtensionProperty() { doTest() } + fun testImportExtensionProperty() { + doTest() + } - fun testAnonymousObjectGenericJava() { doTest() } + fun testAnonymousObjectGenericJava() { + doTest() + } - fun testImportAnonymousObject() { doTest() } + fun testImportAnonymousObject() { + doTest() + } - fun testNestedSamAdapter() { doTest(lookupString = "Nested") } + fun testNestedSamAdapter() { + doTest(lookupString = "Nested") + } override fun setUp() { setType(CompletionType.SMART) @@ -34,7 +44,7 @@ class SmartCompletionMultifileHandlerTest : KotlinCompletionTestCase() { private fun doTest(lookupString: String? = null, itemText: String? = null) { val fileName = getTestName(false) - val fileNames = listOf(fileName + "-1.kt", fileName + "-2.kt", fileName + ".java") + val fileNames = listOf("$fileName-1.kt", "$fileName-2.kt", "$fileName.java") configureByFiles(null, *fileNames.filter { File(testDataPath + it).exists() }.toTypedArray()) @@ -58,7 +68,7 @@ class SmartCompletionMultifileHandlerTest : KotlinCompletionTestCase() { } } - checkResultByFile(fileName + ".kt.after") + checkResultByFile("$fileName.kt.after") } override fun getTestDataPath() = File(COMPLETION_TEST_DATA_BASE_PATH, "/handlers/multifile/smart/").path + File.separator diff --git a/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/ideaTestUtils.kt b/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/ideaTestUtils.kt index 110a060317d..e2c61c3d277 100644 --- a/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/ideaTestUtils.kt +++ b/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/ideaTestUtils.kt @@ -15,12 +15,11 @@ fun CodeInsightTestFixture.configureWithExtraFile(path: String, vararg extraName val noExtensionPath = FileUtil.getNameWithoutExtension(fileName) val extensions = arrayOf("kt", "java", "properties") - val extraPaths: List = extraNameParts - .flatMap { extensions.map { ext -> "$noExtensionPath$it.$ext" } } - .mapNotNull { File(testDataPath, it).takeIf { it.exists() }?.name } + val extraPaths: List = extraNameParts.flatMap { extensions.map { ext -> "$noExtensionPath$it.$ext" } } + .mapNotNull { File(testDataPath, it).takeIf { file -> file.exists() }?.name } configureByFiles(*(listOf(fileName) + extraPaths).toTypedArray()) } @Suppress("unused") // Used in kotlin-ultimate -inline fun Any?.assertInstanceOf() = UsefulTestCase.assertInstanceOf(this, T::class.java) +inline fun Any?.assertInstanceOf() = UsefulTestCase.assertInstanceOf(this, T::class.java) diff --git a/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/weighers/AbstractCompletionWeigherTest.kt b/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/weighers/AbstractCompletionWeigherTest.kt index 55401cee13f..b18bb2cf11a 100644 --- a/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/weighers/AbstractCompletionWeigherTest.kt +++ b/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/weighers/AbstractCompletionWeigherTest.kt @@ -15,9 +15,10 @@ import org.jetbrains.kotlin.idea.test.rollbackCompilerOptions import org.jetbrains.kotlin.test.InTextDirectivesUtils import org.junit.Assert -abstract class AbstractCompletionWeigherTest(val completionType: CompletionType, val relativeTestDataPath: String) : KotlinLightCodeInsightFixtureTestCase() { +abstract class AbstractCompletionWeigherTest(val completionType: CompletionType, val relativeTestDataPath: String) : + KotlinLightCodeInsightFixtureTestCase() { fun doTest(path: String) { - val pathPrefix = RELATIVE_COMPLETION_TEST_DATA_BASE_PATH + "/" + relativeTestDataPath + val pathPrefix = "$RELATIVE_COMPLETION_TEST_DATA_BASE_PATH/$relativeTestDataPath" assert(path.startsWith(pathPrefix)) val relativePath = path.removePrefix(pathPrefix) @@ -28,7 +29,7 @@ abstract class AbstractCompletionWeigherTest(val completionType: CompletionType, val configured = configureCompilerOptions(text, project, module) val items = InTextDirectivesUtils.findArrayWithPrefixes(text, "// ORDER:") - Assert.assertTrue("""Some items should be defined with "// ORDER:" directive""", !items.isEmpty()) + Assert.assertTrue("""Some items should be defined with "// ORDER:" directive""", items.isNotEmpty()) try { myFixture.complete(completionType, InTextDirectivesUtils.getPrefixedInt(text, "// INVOCATION_COUNT:") ?: 1) diff --git a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/ExpectedInfos.kt b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/ExpectedInfos.kt index ec17814f0ab..afc4c0d17b6 100644 --- a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/ExpectedInfos.kt +++ b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/ExpectedInfos.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.core @@ -84,27 +73,43 @@ class ByExpectedTypeFilter(override val fuzzyType: FuzzyType) : ByTypeFilter { data /* for copy() */ class ExpectedInfo( - val filter: ByTypeFilter, - val expectedName: String?, - val tail: Tail?, - val itemOptions: ItemOptions = ItemOptions.DEFAULT, - val additionalData: AdditionalData? = null + val filter: ByTypeFilter, + val expectedName: String?, + val tail: Tail?, + val itemOptions: ItemOptions = ItemOptions.DEFAULT, + val additionalData: AdditionalData? = null ) { // just a marker interface interface AdditionalData {} - constructor(fuzzyType: FuzzyType, expectedName: String?, tail: Tail?, itemOptions: ItemOptions = ItemOptions.DEFAULT, additionalData: AdditionalData? = null) - : this(ByExpectedTypeFilter(fuzzyType), expectedName, tail, itemOptions, additionalData) + constructor( + fuzzyType: FuzzyType, + expectedName: String?, + tail: Tail?, + itemOptions: ItemOptions = ItemOptions.DEFAULT, + additionalData: AdditionalData? = null + ) : this(ByExpectedTypeFilter(fuzzyType), expectedName, tail, itemOptions, additionalData) - constructor(type: KotlinType, expectedName: String?, tail: Tail?, itemOptions: ItemOptions = ItemOptions.DEFAULT, additionalData: AdditionalData? = null) - : this(type.toFuzzyType(emptyList()), expectedName, tail, itemOptions, additionalData) + constructor( + type: KotlinType, + expectedName: String?, + tail: Tail?, + itemOptions: ItemOptions = ItemOptions.DEFAULT, + additionalData: AdditionalData? = null + ) : this(type.toFuzzyType(emptyList()), expectedName, tail, itemOptions, additionalData) fun matchingSubstitutor(descriptorType: FuzzyType): TypeSubstitutor? = filter.matchingSubstitutor(descriptorType) fun matchingSubstitutor(descriptorType: KotlinType): TypeSubstitutor? = matchingSubstitutor(descriptorType.toFuzzyType(emptyList())) companion object { - fun createForArgument(type: KotlinType, expectedName: String?, tail: Tail?, argumentData: ArgumentPositionData, itemOptions: ItemOptions = ItemOptions.DEFAULT): ExpectedInfo { + fun createForArgument( + type: KotlinType, + expectedName: String?, + tail: Tail?, + argumentData: ArgumentPositionData, + itemOptions: ItemOptions = ItemOptions.DEFAULT + ): ExpectedInfo { return ExpectedInfo(type.toFuzzyType(argumentData.function.typeParameters), expectedName, tail, itemOptions, argumentData) } @@ -127,11 +132,11 @@ val ExpectedInfo.multipleFuzzyTypes: Collection sealed class ArgumentPositionData(val function: FunctionDescriptor, val callType: Call.CallType) : ExpectedInfo.AdditionalData { class Positional( - function: FunctionDescriptor, - callType: Call.CallType, - val argumentIndex: Int, - val isFunctionLiteralArgument: Boolean, - val namedArgumentCandidates: Collection + function: FunctionDescriptor, + callType: Call.CallType, + val argumentIndex: Int, + val isFunctionLiteralArgument: Boolean, + val namedArgumentCandidates: Collection ) : ArgumentPositionData(function, callType) class Named(function: FunctionDescriptor, callType: Call.CallType, val argumentName: Name) : ArgumentPositionData(function, callType) @@ -148,30 +153,30 @@ object PropertyDelegateAdditionalData : ExpectedInfo.AdditionalData class ComparisonOperandAdditionalData(val suppressNullLiteral: Boolean) : ExpectedInfo.AdditionalData class ExpectedInfos( - private val bindingContext: BindingContext, - private val resolutionFacade: ResolutionFacade, - private val indicesHelper: KotlinIndicesHelper?, - private val useHeuristicSignatures: Boolean = true, - private val useOuterCallsExpectedTypeCount: Int = 0 + private val bindingContext: BindingContext, + private val resolutionFacade: ResolutionFacade, + private val indicesHelper: KotlinIndicesHelper?, + private val useHeuristicSignatures: Boolean = true, + private val useOuterCallsExpectedTypeCount: Int = 0 ) { fun calculate(expressionWithType: KtExpression): Collection { val expectedInfos = calculateForArgument(expressionWithType) - ?: calculateForFunctionLiteralArgument(expressionWithType) - ?: calculateForIndexingArgument(expressionWithType) - ?: calculateForEqAndAssignment(expressionWithType) - ?: calculateForIf(expressionWithType) - ?: calculateForElvis(expressionWithType) - ?: calculateForBlockExpression(expressionWithType) - ?: calculateForWhenEntryValue(expressionWithType) - ?: calculateForExclOperand(expressionWithType) - ?: calculateForInitializer(expressionWithType) - ?: calculateForExpressionBody(expressionWithType) - ?: calculateForReturn(expressionWithType) - ?: calculateForLoopRange(expressionWithType) - ?: calculateForInOperatorArgument(expressionWithType) - ?: calculateForPropertyDelegate(expressionWithType) - ?: getFromBindingContext(expressionWithType) - ?: return emptyList() + ?: calculateForFunctionLiteralArgument(expressionWithType) + ?: calculateForIndexingArgument(expressionWithType) + ?: calculateForEqAndAssignment(expressionWithType) + ?: calculateForIf(expressionWithType) + ?: calculateForElvis(expressionWithType) + ?: calculateForBlockExpression(expressionWithType) + ?: calculateForWhenEntryValue(expressionWithType) + ?: calculateForExclOperand(expressionWithType) + ?: calculateForInitializer(expressionWithType) + ?: calculateForExpressionBody(expressionWithType) + ?: calculateForReturn(expressionWithType) + ?: calculateForLoopRange(expressionWithType) + ?: calculateForInOperatorArgument(expressionWithType) + ?: calculateForPropertyDelegate(expressionWithType) + ?: getFromBindingContext(expressionWithType) + ?: return emptyList() return expectedInfos.filterNot { it.fuzzyType?.type?.isError ?: false } } @@ -212,21 +217,22 @@ class ExpectedInfos( fun makesSenseToUseOuterCallExpectedType(info: ExpectedInfo): Boolean { val data = info.additionalData as ArgumentPositionData return info.fuzzyType != null - && info.fuzzyType!!.freeParameters.isNotEmpty() - && data.function.fuzzyReturnType()?.freeParameters?.isNotEmpty() ?: false + && info.fuzzyType!!.freeParameters.isNotEmpty() + && data.function.fuzzyReturnType()?.freeParameters?.isNotEmpty() ?: false } if (useOuterCallsExpectedTypeCount > 0 && results.any(::makesSenseToUseOuterCallExpectedType)) { val callExpression = (call.callElement as? KtExpression)?.getQualifiedExpressionForSelectorOrThis() ?: return results - val expectedFuzzyTypes = ExpectedInfos(bindingContext, resolutionFacade, indicesHelper, useHeuristicSignatures, useOuterCallsExpectedTypeCount - 1) + val expectedFuzzyTypes = + ExpectedInfos(bindingContext, resolutionFacade, indicesHelper, useHeuristicSignatures, useOuterCallsExpectedTypeCount - 1) .calculate(callExpression) .mapNotNull { it.fuzzyType } if (expectedFuzzyTypes.isEmpty() || expectedFuzzyTypes.any { it.freeParameters.isNotEmpty() }) return results return expectedFuzzyTypes - .map { it.type } - .toSet() - .flatMap { calculateForArgument(call, it, argument) } + .map { it.type } + .toSet() + .flatMap { calculateForArgument(call, it, argument) } } return results @@ -239,7 +245,8 @@ class ExpectedInfos( val argumentIndex = call.valueArguments.indexOf(argument) assert(argumentIndex >= 0) { - "Could not find argument '$argument(${argument.asElement().text})' among arguments of call: $call. Call element text: '${call.callElement.text}'" + "Could not find argument '$argument(${argument.asElement() + .text})' among arguments of call: $call. Call element text: '${call.callElement.text}'" } // leave only arguments before the current one @@ -269,11 +276,11 @@ class ExpectedInfos( } private fun MutableCollection.addExpectedInfoForCandidate( - candidate: ResolvedCall, - call: Call, - argument: ValueArgument, - argumentIndex: Int, - checkPrevArgumentsMatched: Boolean + candidate: ResolvedCall, + call: Call, + argument: ValueArgument, + argumentIndex: Int, + checkPrevArgumentsMatched: Boolean ) { // check that all arguments before the current has mappings to parameters if (!candidate.allArgumentsMapped()) return @@ -304,13 +311,11 @@ class ExpectedInfos( val argumentPositionData = if (argumentName != null) { ArgumentPositionData.Named(descriptor, callType, argumentName) - } - else { + } else { val namedArgumentCandidates = if (!isFunctionLiteralArgument && !isArrayAccess && descriptor.hasStableParameterNames()) { val usedParameters = argumentToParameter.filter { it.key != argument }.map { it.value }.toSet() descriptor.valueParameters.filter { it !in usedParameters } - } - else { + } else { emptyList() } ArgumentPositionData.Positional(descriptor, callType, argumentIndex, isFunctionLiteralArgument, namedArgumentCandidates) @@ -349,8 +354,7 @@ class ExpectedInfos( parameters.dropWhile { it != parameter }.drop(1).any(::needCommaForParameter) -> Tail.COMMA else -> null } - } - else { + } else { namedArgumentTail(argumentToParameter, argumentName, descriptor) } @@ -371,16 +375,14 @@ class ExpectedInfos( val starOptions = if (!alreadyHasStar) ItemOptions.STAR_PREFIX else ItemOptions.DEFAULT add(ExpectedInfo.createForArgument(parameterType, expectedName, varargTail, argumentPositionData, starOptions)) - } - else { + } else { if (alreadyHasStar) return if (isFunctionLiteralArgument) { if (parameterType.isFunctionOrSuspendFunctionType) { add(ExpectedInfo.createForArgument(parameterType, expectedName, null, argumentPositionData)) } - } - else { + } else { add(ExpectedInfo.createForArgument(parameterType, expectedName, tail, argumentPositionData)) } } @@ -395,13 +397,16 @@ class ExpectedInfos( return substitutedType.replace(newTypeArguments) } - private fun ResolvedCall.allArgumentsMatched() - = call.valueArguments.none { argument -> getArgumentMapping(argument).isError() && !argument.hasError() /* ignore arguments that has error type */ } + private fun ResolvedCall.allArgumentsMatched() = call.valueArguments + .none { argument -> getArgumentMapping(argument).isError() && !argument.hasError() /* ignore arguments that has error type */ } - private fun ValueArgument.hasError() - = getArgumentExpression()?.let { bindingContext.getType(it) }?.isError ?: true + private fun ValueArgument.hasError() = getArgumentExpression()?.let { bindingContext.getType(it) }?.isError ?: true - private fun namedArgumentTail(argumentToParameter: Map, argumentName: Name, descriptor: FunctionDescriptor): Tail? { + private fun namedArgumentTail( + argumentToParameter: Map, + argumentName: Name, + descriptor: FunctionDescriptor + ): Tail? { val usedParameterNames = (argumentToParameter.values.map { it.name } + listOf(argumentName)).toSet() val notUsedParameters = descriptor.valueParameters.filter { it.name !in usedParameterNames } return when { @@ -429,7 +434,8 @@ class ExpectedInfos( var additionalData: ExpectedInfo.AdditionalData? = null if (operationToken in COMPARISON_TOKENS) { // if we complete argument of == or !=, make types in expected info's nullable to allow items of nullable type too - additionalData = ComparisonOperandAdditionalData(suppressNullLiteral = expectedType.nullability() == TypeNullability.NOT_NULL) + additionalData = + ComparisonOperandAdditionalData(suppressNullLiteral = expectedType.nullability() == TypeNullability.NOT_NULL) expectedType = expectedType.makeNullable() } @@ -441,14 +447,21 @@ class ExpectedInfos( } private object NullableTypesFilter : ByTypeFilter { - override fun matchingSubstitutor(descriptorType: FuzzyType) - = if (descriptorType.type.nullability() != TypeNullability.NOT_NULL) TypeSubstitutor.EMPTY else null + override fun matchingSubstitutor(descriptorType: FuzzyType) = + if (descriptorType.type.nullability() != TypeNullability.NOT_NULL) TypeSubstitutor.EMPTY else null } private fun calculateForIf(expressionWithType: KtExpression): Collection? { val ifExpression = (expressionWithType.parent as? KtContainerNode)?.parent as? KtIfExpression ?: return null when (expressionWithType) { - ifExpression.condition -> return listOf(ExpectedInfo(resolutionFacade.moduleDescriptor.builtIns.booleanType, null, Tail.RPARENTH, additionalData = IfConditionAdditionalData)) + ifExpression.condition -> return listOf( + ExpectedInfo( + resolutionFacade.moduleDescriptor.builtIns.booleanType, + null, + Tail.RPARENTH, + additionalData = IfConditionAdditionalData + ) + ) ifExpression.then -> return calculate(ifExpression).map { ExpectedInfo(it.filter, it.expectedName, Tail.ELSE) } @@ -462,8 +475,7 @@ class ExpectedInfos( else ifExpectedInfos return filteredInfo.copyWithNoAdditionalData() - } - else if (thenType != null) { + } else if (thenType != null) { return listOf(ExpectedInfo(thenType, null, null)) } } @@ -487,8 +499,7 @@ class ExpectedInfos( else expectedInfos return filteredInfo.copyWithNoAdditionalData() - } - else if (leftTypeNotNullable != null) { + } else if (leftTypeNotNullable != null) { return listOf(ExpectedInfo(leftTypeNotNullable, null, null)) } } @@ -504,14 +515,13 @@ class ExpectedInfos( return if (functionLiteral != null) { val literalExpression = functionLiteral.parent as KtLambdaExpression calculate(literalExpression) - .mapNotNull { it.fuzzyType } - .filter { it.type.isFunctionOrSuspendFunctionType } - .map { - val returnType = it.type.getReturnTypeFromFunctionType() - ExpectedInfo(returnType.toFuzzyType(it.freeParameters), null, Tail.RBRACE) - } - } - else { + .mapNotNull { it.fuzzyType } + .filter { it.type.isFunctionOrSuspendFunctionType } + .map { + val returnType = it.type.getReturnTypeFromFunctionType() + ExpectedInfo(returnType.toFuzzyType(it.freeParameters), null, Tail.RBRACE) + } + } else { calculate(block).map { ExpectedInfo(it.filter, it.expectedName, null) } } } @@ -524,9 +534,15 @@ class ExpectedInfos( if (subject != null) { val subjectType = bindingContext.getType(subject) ?: return null return listOf(ExpectedInfo(subjectType, null, null, additionalData = WhenEntryAdditionalData(whenWithSubject = true))) - } - else { - return listOf(ExpectedInfo(resolutionFacade.moduleDescriptor.builtIns.booleanType, null, null, additionalData = WhenEntryAdditionalData(whenWithSubject = false))) + } else { + return listOf( + ExpectedInfo( + resolutionFacade.moduleDescriptor.builtIns.booleanType, + null, + null, + additionalData = WhenEntryAdditionalData(whenWithSubject = false) + ) + ) } } @@ -585,8 +601,7 @@ class ExpectedInfos( } private fun calculateForLoopRange(expressionWithType: KtExpression): Collection? { - val forExpression = (expressionWithType.parent as? KtContainerNode) - ?.parent as? KtForExpression ?: return null + val forExpression = (expressionWithType.parent as? KtContainerNode)?.parent as? KtForExpression ?: return null if (expressionWithType != forExpression.loopRange) return null val loopVar = forExpression.loopParameter @@ -630,11 +645,12 @@ class ExpectedInfos( val scope = expressionWithType.getResolutionScope(bindingContext, resolutionFacade) val propertyOwnerType = property.fuzzyExtensionReceiverType() - ?: property.dispatchReceiverParameter?.type?.toFuzzyType(emptyList()) - ?: property.builtIns.nullableNothingType.toFuzzyType(emptyList()) + ?: property.dispatchReceiverParameter?.type?.toFuzzyType(emptyList()) + ?: property.builtIns.nullableNothingType.toFuzzyType(emptyList()) val explicitPropertyType = property.fuzzyReturnType()?.takeIf { propertyDeclaration.typeReference != null } - ?: property.overriddenDescriptors.singleOrNull()?.fuzzyReturnType() // for override properties use super property type as explicit (if not specified) + ?: property.overriddenDescriptors.singleOrNull() + ?.fuzzyReturnType() // for override properties use super property type as explicit (if not specified) val typesWithGetDetector = TypesWithGetValueDetector(scope, indicesHelper, propertyOwnerType, explicitPropertyType) val typesWithSetDetector = if (property.isVar) TypesWithSetValueDetector(scope, indicesHelper, propertyOwnerType) else null @@ -644,15 +660,16 @@ class ExpectedInfos( if (typesWithSetDetector == null) return getOperatorSubstitutor - val substitutedType = getOperatorSubstitutor.substitute(descriptorType.type, Variance.INVARIANT)!!.toFuzzyType(descriptorType.freeParameters) + val substitutedType = + getOperatorSubstitutor.substitute(descriptorType.type, Variance.INVARIANT)!!.toFuzzyType(descriptorType.freeParameters) val (setValueOperator, setOperatorSubstitutor) = typesWithSetDetector.findOperator(substitutedType) ?: return null val propertyType = explicitPropertyType ?: getValueOperator.fuzzyReturnType()!! val setParamType = setValueOperator.valueParameters.last().type.toFuzzyType(setValueOperator.typeParameters) val setParamTypeSubstitutor = setParamType.checkIsSuperTypeOf(propertyType) ?: return null return getOperatorSubstitutor - .combineIfNoConflicts(setOperatorSubstitutor, descriptorType.freeParameters) - ?.combineIfNoConflicts(setParamTypeSubstitutor, descriptorType.freeParameters) + .combineIfNoConflicts(setOperatorSubstitutor, descriptorType.freeParameters) + ?.combineIfNoConflicts(setParamTypeSubstitutor, descriptorType.freeParameters) } override val multipleFuzzyTypes: Collection by lazy { @@ -692,10 +709,11 @@ class ExpectedInfos( } } - private fun String.unpluralize() - = StringUtil.unpluralize(this) + private fun String.unpluralize() = StringUtil.unpluralize(this) - private fun Collection.copyWithNoAdditionalData() = map { it.copy(additionalData = null, itemOptions = ItemOptions.DEFAULT) } + private fun Collection.copyWithNoAdditionalData() = map { + it.copy(additionalData = null, itemOptions = ItemOptions.DEFAULT) + } } val COMPARISON_TOKENS = setOf(KtTokens.EQEQ, KtTokens.EXCLEQ, KtTokens.EQEQEQ, KtTokens.EXCLEQEQEQ) diff --git a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/ImportableFqNameClassifier.kt b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/ImportableFqNameClassifier.kt index b5badfcf676..997fab25bc0 100644 --- a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/ImportableFqNameClassifier.kt +++ b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/ImportableFqNameClassifier.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.core @@ -41,7 +30,7 @@ class ImportableFqNameClassifier(private val file: KtFile) { preciseImportPackages.add(fqName.parent()) } else -> excludedImports.add(fqName) - // TODO: support aliased imports in completion + // TODO: support aliased imports in completion } } } @@ -90,5 +79,5 @@ class ImportableFqNameClassifier(private val file: KtFile) { private fun hasPreciseImportFromPackage(packageName: FqName) = packageName in preciseImportPackages } -fun isJavaClassNotToBeUsedInKotlin(fqName: FqName): Boolean - = JavaToKotlinClassMap.isJavaPlatformClass(fqName) || JavaAnnotationMapper.javaToKotlinNameMap[fqName] != null +fun isJavaClassNotToBeUsedInKotlin(fqName: FqName): Boolean = + JavaToKotlinClassMap.isJavaPlatformClass(fqName) || JavaAnnotationMapper.javaToKotlinNameMap[fqName] != null diff --git a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/IterableTypesDetection.kt b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/IterableTypesDetection.kt index 2a8449cb719..38279719593 100644 --- a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/IterableTypesDetection.kt +++ b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/IterableTypesDetection.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.core @@ -40,10 +29,10 @@ import org.jetbrains.kotlin.utils.getOrPutNullable import java.util.* class IterableTypesDetection( - private val project: Project, - private val forLoopConventionsChecker: ForLoopConventionsChecker, - private val languageVersionSettings: LanguageVersionSettings, - private val dataFlowValueFactory: DataFlowValueFactory + private val project: Project, + private val forLoopConventionsChecker: ForLoopConventionsChecker, + private val languageVersionSettings: LanguageVersionSettings, + private val dataFlowValueFactory: DataFlowValueFactory ) { companion object { private val iteratorName = Name.identifier("iterator") @@ -52,28 +41,28 @@ class IterableTypesDetection( fun createDetector(scope: LexicalScope): IterableTypesDetector { return Detector(scope) } - private inner class Detector(private val scope: LexicalScope): IterableTypesDetector { + + private inner class Detector(private val scope: LexicalScope) : IterableTypesDetector { private val cache = HashMap() private val typesWithExtensionIterator: Collection = scope - .collectFunctions(iteratorName, NoLookupLocation.FROM_IDE) - .filter { it.isValidOperator() } - .mapNotNull { it.extensionReceiverParameter?.type } + .collectFunctions(iteratorName, NoLookupLocation.FROM_IDE) + .filter { it.isValidOperator() } + .mapNotNull { it.extensionReceiverParameter?.type } override fun isIterable(type: FuzzyType, loopVarType: KotlinType?): Boolean { val elementType = elementType(type) ?: return false return loopVarType == null || elementType.checkIsSubtypeOf(loopVarType) != null } - override fun isIterable(type: KotlinType, loopVarType: KotlinType?): Boolean - = isIterable(type.toFuzzyType(emptyList()), loopVarType) + override fun isIterable(type: KotlinType, loopVarType: KotlinType?): Boolean = + isIterable(type.toFuzzyType(emptyList()), loopVarType) private fun elementType(type: FuzzyType): FuzzyType? { return cache.getOrPutNullable(type, { elementTypeNoCache(type) }) } - override fun elementType(type: KotlinType): FuzzyType? - = elementType(type.toFuzzyType(emptyList())) + override fun elementType(type: KotlinType): FuzzyType? = elementType(type.toFuzzyType(emptyList())) private fun elementTypeNoCache(type: FuzzyType): FuzzyType? { // optimization @@ -81,7 +70,8 @@ class IterableTypesDetection( val expression = KtPsiFactory(project).createExpression("fake") val context = ExpressionTypingContext.newContext( - BindingTraceContext(), scope, DataFlowInfo.EMPTY, TypeUtils.NO_EXPECTED_TYPE, languageVersionSettings, dataFlowValueFactory) + BindingTraceContext(), scope, DataFlowInfo.EMPTY, TypeUtils.NO_EXPECTED_TYPE, languageVersionSettings, dataFlowValueFactory + ) val expressionReceiver = ExpressionReceiver.create(expression, type.type, context.trace.bindingContext) val elementType = forLoopConventionsChecker.checkIterableConvention(expressionReceiver, context) return elementType?.let { it.toFuzzyType(type.freeParameters) } @@ -90,10 +80,10 @@ class IterableTypesDetection( private fun canBeIterable(type: FuzzyType): Boolean { if (type.type.constructor is IntegerLiteralTypeConstructor) return false return type.type.memberScope.getContributedFunctions(iteratorName, NoLookupLocation.FROM_IDE).isNotEmpty() || - typesWithExtensionIterator.any { - val freeParams = it.arguments.mapNotNull { it.type.constructor.declarationDescriptor as? TypeParameterDescriptor } - type.checkIsSubtypeOf(it.toFuzzyType(freeParams)) != null - } + typesWithExtensionIterator.any { + val freeParams = it.arguments.mapNotNull { it.type.constructor.declarationDescriptor as? TypeParameterDescriptor } + type.checkIsSubtypeOf(it.toFuzzyType(freeParams)) != null + } } } } diff --git a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/KotlinNameSuggestionProvider.kt b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/KotlinNameSuggestionProvider.kt index 60515e2eaed..bf012d9a998 100644 --- a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/KotlinNameSuggestionProvider.kt +++ b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/KotlinNameSuggestionProvider.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.core @@ -37,13 +26,16 @@ import org.jetbrains.kotlin.utils.SmartList import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull class KotlinNameSuggestionProvider : NameSuggestionProvider { - override fun getSuggestedNames(element: PsiElement, nameSuggestionContext: PsiElement?, result: MutableSet): SuggestedNameInfo? { + override fun getSuggestedNames( + element: PsiElement, + nameSuggestionContext: PsiElement?, + result: MutableSet + ): SuggestedNameInfo? { if (element is KtCallableDeclaration) { val context = nameSuggestionContext ?: element.parent val target = if (element is KtProperty || element is KtParameter) { NewDeclarationNameValidator.Target.VARIABLES - } - else { + } else { NewDeclarationNameValidator.Target.FUNCTIONS_AND_CLASSES } val validator = NewDeclarationNameValidator(context, element, target, listOf(element)) @@ -76,10 +68,10 @@ class KotlinNameSuggestionProvider : NameSuggestionProvider { override fun nameChosen(name: String?) { val psiVariable = element.toLightElements().firstIsInstanceOrNull() ?: return JavaStatisticsManager.incVariableNameUseCount( - name, - JavaCodeStyleManager.getInstance(element.project).getVariableKind(psiVariable), - psiVariable.name, - psiVariable.type + name, + JavaCodeStyleManager.getInstance(element.project).getVariableKind(psiVariable), + psiVariable.name, + psiVariable.type ) } } diff --git a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/NameValidators.kt b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/NameValidators.kt index ef65a482b46..e0454d4eb90 100644 --- a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/NameValidators.kt +++ b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/NameValidators.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.core @@ -42,9 +31,9 @@ import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull import java.util.* class CollectingNameValidator @JvmOverloads constructor( - existingNames: Collection = Collections.emptySet(), - private val filter: (String) -> Boolean = { true } -): (String) -> Boolean { + existingNames: Collection = Collections.emptySet(), + private val filter: (String) -> Boolean = { true } +) : (String) -> Boolean { private val existingNames = HashSet(existingNames) override fun invoke(name: String): Boolean { @@ -61,20 +50,22 @@ class CollectingNameValidator @JvmOverloads constructor( } class NewDeclarationNameValidator( - private val visibleDeclarationsContext: KtElement?, - private val checkDeclarationsIn: Sequence, - private val target: Target, - private val excludedDeclarations: List = emptyList() + private val visibleDeclarationsContext: KtElement?, + private val checkDeclarationsIn: Sequence, + private val target: Target, + private val excludedDeclarations: List = emptyList() ) : (String) -> Boolean { - constructor(container: PsiElement, - anchor: PsiElement?, - target: Target, - excludedDeclarations: List = emptyList()) - : this( - (anchor ?: container).parentsWithSelf.firstIsInstanceOrNull(), - anchor?.siblings() ?: container.allChildren, - target, - excludedDeclarations) + constructor( + container: PsiElement, + anchor: PsiElement?, + target: Target, + excludedDeclarations: List = emptyList() + ) : this( + (anchor ?: container).parentsWithSelf.firstIsInstanceOrNull(), + anchor?.siblings() ?: container.allChildren, + target, + excludedDeclarations + ) enum class Target { VARIABLES, @@ -86,7 +77,8 @@ class NewDeclarationNameValidator( if (visibleDeclarationsContext != null) { val bindingContext = visibleDeclarationsContext.analyze(BodyResolveMode.PARTIAL_FOR_COMPLETION) - val resolutionScope = visibleDeclarationsContext.getResolutionScope(bindingContext, visibleDeclarationsContext.getResolutionFacade()) + val resolutionScope = + visibleDeclarationsContext.getResolutionScope(bindingContext, visibleDeclarationsContext.getResolutionFacade()) if (resolutionScope.hasConflict(identifier)) return false } @@ -105,12 +97,12 @@ class NewDeclarationNameValidator( } } - return when(target) { + return when (target) { Target.VARIABLES -> getAllAccessibleVariables(name).any { !it.isExtension && it.isVisible() && !isExcluded(it) } Target.FUNCTIONS_AND_CLASSES -> getAllAccessibleFunctions(name).any { !it.isExtension && it.isVisible() && !isExcluded(it) } || - findClassifier(name, NoLookupLocation.FROM_IDE)?.let { it.isVisible() && !isExcluded(it) } ?: false + findClassifier(name, NoLookupLocation.FROM_IDE)?.let { it.isVisible() && !isExcluded(it) } ?: false } } @@ -118,7 +110,7 @@ class NewDeclarationNameValidator( if (this in excludedDeclarations) return false if (nameAsName != name) return false if (this is KtCallableDeclaration && receiverTypeReference != null) return false - return when(target) { + return when (target) { Target.VARIABLES -> this is KtVariableDeclaration || this is KtParameter Target.FUNCTIONS_AND_CLASSES -> this is KtNamedFunction || this is KtClassOrObject || this is KtTypeAlias } diff --git a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/NotPropertiesService.kt b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/NotPropertiesService.kt index 0a6be9dd949..aebcffefade 100644 --- a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/NotPropertiesService.kt +++ b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/NotPropertiesService.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.core @@ -30,7 +19,6 @@ interface NotPropertiesService { return ServiceManager.getService(project, NotPropertiesService::class.java) } - fun getNotProperties(element: PsiElement) = - getInstance(element.project).getNotProperties(element) + fun getNotProperties(element: PsiElement) = getInstance(element.project).getNotProperties(element) } } \ No newline at end of file diff --git a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/OptionalParametersHelper.kt b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/OptionalParametersHelper.kt index ef8f53d5c62..f595ac68376 100644 --- a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/OptionalParametersHelper.kt +++ b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/OptionalParametersHelper.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.core @@ -39,16 +28,16 @@ import java.util.* object OptionalParametersHelper { fun detectArgumentsToDropForDefaults( - resolvedCall: ResolvedCall, - project: Project, - canDrop: (ValueArgument) -> Boolean = { true } + resolvedCall: ResolvedCall, + project: Project, + canDrop: (ValueArgument) -> Boolean = { true } ): Collection { if (!resolvedCall.isReallySuccess()) return emptyList() val descriptor = resolvedCall.resultingDescriptor val parameterToDefaultValue = descriptor.valueParameters - .mapNotNull { parameter -> defaultParameterValue(parameter, project)?.let { parameter to it } } - .toMap() + .mapNotNull { parameter -> defaultParameterValue(parameter, project)?.let { parameter to it } } + .toMap() if (parameterToDefaultValue.isEmpty()) return emptyList() //TODO: drop functional literal out of parenthesis too @@ -65,7 +54,10 @@ object OptionalParametersHelper { return argumentsToDrop } - private fun ValueArgument.matchesDefault(resolvedCall: ResolvedCall, parameterToDefaultValue: Map): Boolean { + private fun ValueArgument.matchesDefault( + resolvedCall: ResolvedCall, + parameterToDefaultValue: Map + ): Boolean { val parameter = resolvedCall.getParameterForArgument(this) ?: return false val defaultValue = parameterToDefaultValue[parameter] ?: return false val expression = defaultValue.substituteArguments(resolvedCall) @@ -110,8 +102,8 @@ object OptionalParametersHelper { } data class DefaultValue( - val expression: KtExpression, - val parameterUsages: Map> + val expression: KtExpression, + val parameterUsages: Map> ) fun defaultParameterValueExpression(parameter: ValueParameterDescriptor, project: Project): KtExpression? { diff --git a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/SmartCastCalculator.kt b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/SmartCastCalculator.kt index 6e8ec39b4e4..155f75bf36e 100644 --- a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/SmartCastCalculator.kt +++ b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/SmartCastCalculator.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.core @@ -39,19 +28,20 @@ import org.jetbrains.kotlin.util.javaslang.component2 import java.util.* class SmartCastCalculator( - val bindingContext: BindingContext, - val containingDeclarationOrModule: DeclarationDescriptor, - contextElement: PsiElement, - receiver: KtExpression?, - resolutionFacade: ResolutionFacade + val bindingContext: BindingContext, + val containingDeclarationOrModule: DeclarationDescriptor, + contextElement: PsiElement, + receiver: KtExpression?, + resolutionFacade: ResolutionFacade ) { private val dataFlowValueFactory = resolutionFacade.frontendService() // keys are VariableDescriptor's and ThisReceiver's private val entityToSmartCastInfo: Map = processDataFlowInfo( - bindingContext.getDataFlowInfoBefore(contextElement), - contextElement.getResolutionScope(bindingContext, resolutionFacade), - receiver) + bindingContext.getDataFlowInfoBefore(contextElement), + contextElement.getResolutionScope(bindingContext, resolutionFacade), + receiver + ) fun types(descriptor: VariableDescriptor): Collection { val type = descriptor.returnType ?: return emptyList() @@ -80,27 +70,28 @@ class SmartCastCalculator( constructor() : this(emptyList(), false) } - private fun processDataFlowInfo(dataFlowInfo: DataFlowInfo, resolutionScope: LexicalScope?, receiver: KtExpression?): Map { + private fun processDataFlowInfo( + dataFlowInfo: DataFlowInfo, + resolutionScope: LexicalScope?, + receiver: KtExpression? + ): Map { if (dataFlowInfo == DataFlowInfo.EMPTY) return emptyMap() val dataFlowValueToEntity: (DataFlowValue) -> Any? if (receiver != null) { val receiverType = bindingContext.getType(receiver) ?: return emptyMap() val receiverIdentifierInfo = dataFlowValueFactory.createDataFlowValue( - receiver, receiverType, bindingContext, containingDeclarationOrModule + receiver, receiverType, bindingContext, containingDeclarationOrModule ).identifierInfo dataFlowValueToEntity = { value -> val identifierInfo = value.identifierInfo if (identifierInfo is IdentifierInfo.Qualified && identifierInfo.receiverInfo == receiverIdentifierInfo) { (identifierInfo.selectorInfo as? IdentifierInfo.Variable)?.variable - } - else null + } else null } - } - else { - dataFlowValueToEntity = fun (value: DataFlowValue): Any? { - val identifierInfo = value.identifierInfo - when(identifierInfo) { + } else { + dataFlowValueToEntity = fun(value: DataFlowValue): Any? { + when (val identifierInfo = value.identifierInfo) { is IdentifierInfo.Variable -> return identifierInfo.variable is IdentifierInfo.Receiver -> return identifierInfo.value as? ImplicitReceiver diff --git a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/TypesWithOperatorDetector.kt b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/TypesWithOperatorDetector.kt index a9abdef6557..f3889d1c7d5 100644 --- a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/TypesWithOperatorDetector.kt +++ b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/TypesWithOperatorDetector.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.core @@ -33,11 +22,14 @@ import org.jetbrains.kotlin.utils.addIfNotNull import java.util.* abstract class TypesWithOperatorDetector( - private val name: Name, - private val scope: LexicalScope, - private val indicesHelper: KotlinIndicesHelper? + private val name: Name, + private val scope: LexicalScope, + private val indicesHelper: KotlinIndicesHelper? ) { - protected abstract fun checkIsSuitableByType(operator: FunctionDescriptor, freeTypeParams: Collection): TypeSubstitutor? + protected abstract fun checkIsSuitableByType( + operator: FunctionDescriptor, + freeTypeParams: Collection + ): TypeSubstitutor? private val cache = HashMap?>() @@ -45,8 +37,8 @@ abstract class TypesWithOperatorDetector( val result = ArrayList() val extensionsFromScope = scope - .collectFunctions(name, NoLookupLocation.FROM_IDE) - .filter { it.extensionReceiverParameter != null } + .collectFunctions(name, NoLookupLocation.FROM_IDE) + .filter { it.extensionReceiverParameter != null } result.addSuitableOperators(extensionsFromScope) indicesHelper?.getTopLevelExtensionOperatorsByName(name.asString())?.let { result.addSuitableOperators(it) } @@ -76,15 +68,12 @@ abstract class TypesWithOperatorDetector( return this } - fun findOperator(type: FuzzyType): Pair? { - return if (cache.containsKey(type)) { - cache[type] - } - else { - val result = findOperatorNoCache(type) - cache[type] = result - result - } + fun findOperator(type: FuzzyType): Pair? = if (cache.containsKey(type)) { + cache[type] + } else { + val result = findOperatorNoCache(type) + cache[type] = result + result } private fun findOperatorNoCache(type: FuzzyType): Pair? { @@ -109,12 +98,15 @@ abstract class TypesWithOperatorDetector( } class TypesWithContainsDetector( - scope: LexicalScope, - indicesHelper: KotlinIndicesHelper?, - private val argumentType: KotlinType + scope: LexicalScope, + indicesHelper: KotlinIndicesHelper?, + private val argumentType: KotlinType ) : TypesWithOperatorDetector(OperatorNameConventions.CONTAINS, scope, indicesHelper) { - override fun checkIsSuitableByType(operator: FunctionDescriptor, freeTypeParams: Collection): TypeSubstitutor? { + override fun checkIsSuitableByType( + operator: FunctionDescriptor, + freeTypeParams: Collection + ): TypeSubstitutor? { val parameter = operator.valueParameters.single() val fuzzyParameterType = parameter.type.toFuzzyType(operator.typeParameters + freeTypeParams) return fuzzyParameterType.checkIsSuperTypeOf(argumentType) @@ -122,13 +114,16 @@ class TypesWithContainsDetector( } class TypesWithGetValueDetector( - scope: LexicalScope, - indicesHelper: KotlinIndicesHelper?, - private val propertyOwnerType: FuzzyType, - private val propertyType: FuzzyType? + scope: LexicalScope, + indicesHelper: KotlinIndicesHelper?, + private val propertyOwnerType: FuzzyType, + private val propertyType: FuzzyType? ) : TypesWithOperatorDetector(OperatorNameConventions.GET_VALUE, scope, indicesHelper) { - override fun checkIsSuitableByType(operator: FunctionDescriptor, freeTypeParams: Collection): TypeSubstitutor? { + override fun checkIsSuitableByType( + operator: FunctionDescriptor, + freeTypeParams: Collection + ): TypeSubstitutor? { val paramType = operator.valueParameters.first().type.toFuzzyType(freeTypeParams) val substitutor = paramType.checkIsSuperTypeOf(propertyOwnerType) ?: return null @@ -141,12 +136,15 @@ class TypesWithGetValueDetector( } class TypesWithSetValueDetector( - scope: LexicalScope, - indicesHelper: KotlinIndicesHelper?, - private val propertyOwnerType: FuzzyType + scope: LexicalScope, + indicesHelper: KotlinIndicesHelper?, + private val propertyOwnerType: FuzzyType ) : TypesWithOperatorDetector(OperatorNameConventions.SET_VALUE, scope, indicesHelper) { - override fun checkIsSuitableByType(operator: FunctionDescriptor, freeTypeParams: Collection): TypeSubstitutor? { + override fun checkIsSuitableByType( + operator: FunctionDescriptor, + freeTypeParams: Collection + ): TypeSubstitutor? { val paramType = operator.valueParameters.first().type.toFuzzyType(freeTypeParams) return paramType.checkIsSuperTypeOf(propertyOwnerType) } diff --git a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/descriptorUtils.kt b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/descriptorUtils.kt index a9819ae3e08..1d1019556b8 100644 --- a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/descriptorUtils.kt +++ b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/descriptorUtils.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.core @@ -28,9 +17,9 @@ import org.jetbrains.kotlin.lexer.KtModifierKeywordToken import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.resolve.BindingContext -import org.jetbrains.kotlin.resolve.descriptorUtil.isExtension import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.OverridingUtil +import org.jetbrains.kotlin.resolve.descriptorUtil.isExtension import org.jetbrains.kotlin.resolve.findOriginalTopMostOverriddenDescriptors import org.jetbrains.kotlin.resolve.scopes.LexicalScope import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver @@ -43,10 +32,10 @@ fun DeclarationDescriptorWithVisibility.isVisible(from: DeclarationDescriptor): } fun DeclarationDescriptorWithVisibility.isVisible( - context: PsiElement, - receiverExpression: KtExpression?, - bindingContext: BindingContext, - resolutionFacade: ResolutionFacade + context: PsiElement, + receiverExpression: KtExpression?, + bindingContext: BindingContext, + resolutionFacade: ResolutionFacade ): Boolean { val resolutionScope = context.getResolutionScope(bindingContext, resolutionFacade) val from = resolutionScope.ownerDescriptor @@ -54,10 +43,10 @@ fun DeclarationDescriptorWithVisibility.isVisible( } private fun DeclarationDescriptorWithVisibility.isVisible( - from: DeclarationDescriptor, - receiverExpression: KtExpression?, - bindingContext: BindingContext? = null, - resolutionScope: LexicalScope? = null + from: DeclarationDescriptor, + receiverExpression: KtExpression?, + bindingContext: BindingContext? = null, + resolutionScope: LexicalScope? = null ): Boolean { if (Visibilities.isVisibleWithAnyReceiver(this, from)) return true @@ -68,8 +57,7 @@ private fun DeclarationDescriptorWithVisibility.isVisible( val receiverType = bindingContext.getType(receiverExpression) ?: return false val explicitReceiver = ExpressionReceiver.create(receiverExpression, receiverType, bindingContext) return Visibilities.isVisible(explicitReceiver, this, from) - } - else { + } else { return resolutionScope.getImplicitReceiversHierarchy().any { Visibilities.isVisible(it.value, this, from) } @@ -116,19 +104,15 @@ fun compareDescriptors(project: Project, currentDescriptor: DeclarationDescripto return false } -fun Visibility.toKeywordToken(): KtModifierKeywordToken { - val normalized = normalize() - return when (normalized) { - Visibilities.PUBLIC -> KtTokens.PUBLIC_KEYWORD - Visibilities.PROTECTED -> KtTokens.PROTECTED_KEYWORD - Visibilities.INTERNAL -> KtTokens.INTERNAL_KEYWORD - else -> { - if (Visibilities.isPrivate(normalized)) { - KtTokens.PRIVATE_KEYWORD - } - else { - error("Unexpected visibility '$normalized'") - } +fun Visibility.toKeywordToken(): KtModifierKeywordToken = when (val normalized = normalize()) { + Visibilities.PUBLIC -> KtTokens.PUBLIC_KEYWORD + Visibilities.PROTECTED -> KtTokens.PROTECTED_KEYWORD + Visibilities.INTERNAL -> KtTokens.INTERNAL_KEYWORD + else -> { + if (Visibilities.isPrivate(normalized)) { + KtTokens.PRIVATE_KEYWORD + } else { + error("Unexpected visibility '$normalized'") } } } diff --git a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/excludedFromImportsAndCompletion.kt b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/excludedFromImportsAndCompletion.kt index b35b75fd746..2853ca7210a 100644 --- a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/excludedFromImportsAndCompletion.kt +++ b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/excludedFromImportsAndCompletion.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.core @@ -24,21 +13,20 @@ import org.jetbrains.kotlin.psi.KtFile private val exclusions = - listOf( - "kotlin.jvm.internal", - "kotlin.coroutines.experimental.intrinsics", - "kotlin.coroutines.intrinsics", - "kotlin.coroutines.experimental.jvm.internal", - "kotlin.coroutines.jvm.internal", - "kotlin.reflect.jvm.internal" - ) + listOf( + "kotlin.jvm.internal", + "kotlin.coroutines.experimental.intrinsics", + "kotlin.coroutines.intrinsics", + "kotlin.coroutines.experimental.jvm.internal", + "kotlin.coroutines.jvm.internal", + "kotlin.reflect.jvm.internal" + ) private fun shouldBeHiddenAsInternalImplementationDetail(fqName: String, locationFqName: String) = - exclusions.any { fqName.startsWith(it) } - && (locationFqName.isBlank() || !fqName.startsWith(locationFqName)) + exclusions.any { fqName.startsWith(it) } && (locationFqName.isBlank() || !fqName.startsWith(locationFqName)) fun DeclarationDescriptor.isExcludedFromAutoImport(project: Project, inFile: KtFile?): Boolean { val fqName = importableFqName?.asString() ?: return false return JavaProjectCodeInsightSettings.getSettings(project).isExcluded(fqName) || - shouldBeHiddenAsInternalImplementationDetail(fqName, inFile?.packageFqName?.asString() ?: "") + shouldBeHiddenAsInternalImplementationDetail(fqName, inFile?.packageFqName?.asString() ?: "") } diff --git a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/extension/CompletionInformationProvider.kt b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/extension/CompletionInformationProvider.kt index 4e3e6aa056c..805f6cf1c15 100644 --- a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/extension/CompletionInformationProvider.kt +++ b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/extension/CompletionInformationProvider.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ /* @@ -26,7 +15,7 @@ import org.jetbrains.kotlin.descriptors.DeclarationDescriptor interface CompletionInformationProvider { companion object { val EP_NAME: ExtensionPointName = - ExtensionPointName.create("org.jetbrains.kotlin.completionInformationProvider") + ExtensionPointName.create("org.jetbrains.kotlin.completionInformationProvider") } fun getContainerAndReceiverInformation(descriptor: DeclarationDescriptor): String? diff --git a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/fileIndexUtils.kt b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/fileIndexUtils.kt index 5ee57e8b08b..6c3875854f0 100644 --- a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/fileIndexUtils.kt +++ b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/fileIndexUtils.kt @@ -1,5 +1,5 @@ /* - * Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -10,7 +10,10 @@ import com.intellij.openapi.vfs.VirtualFile import org.jetbrains.jps.model.java.JavaResourceRootType import org.jetbrains.jps.model.java.JavaSourceRootType import org.jetbrains.jps.model.module.JpsModuleSourceRootType -import org.jetbrains.kotlin.config.* +import org.jetbrains.kotlin.config.ResourceKotlinRootType +import org.jetbrains.kotlin.config.SourceKotlinRootType +import org.jetbrains.kotlin.config.TestResourceKotlinRootType +import org.jetbrains.kotlin.config.TestSourceKotlinRootType import org.jetbrains.kotlin.idea.caches.project.SourceType import org.jetbrains.kotlin.idea.util.isInSourceContentWithoutInjected @@ -28,7 +31,7 @@ private val sourceRootTypes = setOf>( ResourceKotlinRootType ) -fun JpsModuleSourceRootType<*>.getSourceType(): SourceType? = when(this) { +fun JpsModuleSourceRootType<*>.getSourceType(): SourceType? = when (this) { in sourceRootTypes -> SourceType.PRODUCTION in testRootTypes -> SourceType.TEST else -> null diff --git a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/generateUtil.kt b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/generateUtil.kt index 3d1362033e7..4b3a5c12076 100644 --- a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/generateUtil.kt +++ b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/generateUtil.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.core @@ -231,7 +220,9 @@ fun insertMembersAfter( if (classOrObject !is KtClass) return@mapNotNullTo null @Suppress("UNCHECKED_CAST") - SmartPointerManager.createPointer(classOrObject.createPrimaryConstructorParameterListIfAbsent().addParameter(it as KtParameter) as T) + SmartPointerManager.createPointer( + classOrObject.createPrimaryConstructorParameterListIfAbsent().addParameter(it as KtParameter) as T + ) } if (otherMembers.isNotEmpty()) { diff --git a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/overrideImplement/OverrideMemberChooserObject.kt b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/overrideImplement/OverrideMemberChooserObject.kt index 4fe18499d29..7b3e506e7a7 100644 --- a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/overrideImplement/OverrideMemberChooserObject.kt +++ b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/overrideImplement/OverrideMemberChooserObject.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.core.overrideImplement @@ -182,7 +171,8 @@ fun OverrideMemberChooserObject.generateMember( targetClass.resolveToDescriptorIfAny()?.expectedDescriptors()?.filterIsInstance().orEmpty() if (expectClassDescriptors.any { expectClassDescriptor -> val expectMemberDescriptor = expectClassDescriptor.findCallableMemberBySignature(immediateSuper) - expectMemberDescriptor?.isExpect == true && expectMemberDescriptor.kind != CallableMemberDescriptor.Kind.FAKE_OVERRIDE + expectMemberDescriptor?.isExpect == true && + expectMemberDescriptor.kind != CallableMemberDescriptor.Kind.FAKE_OVERRIDE } ) { newMember.addModifier(KtTokens.ACTUAL_KEYWORD) diff --git a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/overrideImplement/OverrideMembersHandler.kt b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/overrideImplement/OverrideMembersHandler.kt index da993ff9daf..9c29de7a089 100644 --- a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/overrideImplement/OverrideMembersHandler.kt +++ b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/overrideImplement/OverrideMembersHandler.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.core.overrideImplement @@ -34,8 +23,8 @@ class OverrideMembersHandler(private val preferConstructorParameters: Boolean = if (DescriptorUtils.isInterface(descriptor) && overridden.any { descriptor.builtIns.isMemberOfAny(it) }) continue class Data( - val realSuper: CallableMemberDescriptor, - val immediateSupers: MutableList = SmartList() + val realSuper: CallableMemberDescriptor, + val immediateSupers: MutableList = SmartList() ) val byOriginalRealSupers = LinkedHashMap() @@ -49,8 +38,7 @@ class OverrideMembersHandler(private val preferConstructorParameters: Boolean = val nonAbstractRealSupers = realSupers.filter { it.modality != Modality.ABSTRACT } val realSupersToUse = if (nonAbstractRealSupers.isNotEmpty()) { nonAbstractRealSupers - } - else { + } else { listOf(realSupers.firstOrNull() ?: continue) } @@ -60,9 +48,9 @@ class OverrideMembersHandler(private val preferConstructorParameters: Boolean = val immediateSuperToUse = if (immediateSupers.size == 1) { immediateSupers.single() - } - else { - immediateSupers.singleOrNull { (it.containingDeclaration as? ClassDescriptor)?.kind == ClassKind.CLASS } ?: immediateSupers.first() + } else { + immediateSupers.singleOrNull { (it.containingDeclaration as? ClassDescriptor)?.kind == ClassKind.CLASS } + ?: immediateSupers.first() } val bodyType = when { @@ -76,7 +64,15 @@ class OverrideMembersHandler(private val preferConstructorParameters: Boolean = OverrideMemberChooserObject.BodyType.QUALIFIED_SUPER } - result.add(OverrideMemberChooserObject.create(project, realSuper, immediateSuperToUse, bodyType, preferConstructorParameters)) + result.add( + OverrideMemberChooserObject.create( + project, + realSuper, + immediateSuperToUse, + bodyType, + preferConstructorParameters + ) + ) } } } diff --git a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/psiModificationUtils.kt b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/psiModificationUtils.kt index 9d73ff790b6..8b6fb8ec829 100644 --- a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/psiModificationUtils.kt +++ b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/psiModificationUtils.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.core @@ -189,8 +178,6 @@ private fun FunctionDescriptor.allowsMoveOfLastParameterOutsideParentheses( return movableParametersOfCandidateCount == lambdaAndCallableReferencesInOriginalCallCount } - - fun KtCallExpression.moveFunctionLiteralOutsideParentheses() { assert(lambdaArguments.isEmpty()) val argumentList = valueArgumentList!! diff --git a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/templates.kt b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/templates.kt index b4c1a625a4c..eba7bcaec41 100644 --- a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/templates.kt +++ b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/templates.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.core @@ -37,11 +26,11 @@ enum class TemplateKind(val templateFileName: String) { } fun getFunctionBodyTextFromTemplate( - project: Project, - kind: TemplateKind, - name: String?, - returnType: String, - classFqName: FqName? = null + project: Project, + kind: TemplateKind, + name: String?, + returnType: String, + classFqName: FqName? = null ): String { val fileTemplate = FileTemplateManager.getInstance(project)!!.getCodeTemplate(kind.templateFileName) @@ -61,11 +50,9 @@ fun getFunctionBodyTextFromTemplate( return try { fileTemplate.getText(properties) - } - catch (e: ProcessCanceledException) { + } catch (e: ProcessCanceledException) { throw e - } - catch (e: Throwable) { + } catch (e: Throwable) { // TODO: This is dangerous. // Is there any way to avoid catching all exceptions? throw IncorrectOperationException("Failed to parse file template", e) diff --git a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/util/AttachmentUtils.kt b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/util/AttachmentUtils.kt index 4da4642a838..cd969624746 100644 --- a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/util/AttachmentUtils.kt +++ b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/util/AttachmentUtils.kt @@ -15,10 +15,16 @@ fun attachmentByPsiFile(file: PsiFile?): Attachment? { val virtualFile = file.virtualFile if (virtualFile != null) return AttachmentFactory.createAttachment(virtualFile) - val text = try { file.text - } catch(e: Exception) { null } - val name = try { file.name - } catch(e: Exception) { null } + val text = try { + file.text + } catch (e: Exception) { + null + } + val name = try { + file.name + } catch (e: Exception) { + null + } if (text != null && name != null) return Attachment(name, text) diff --git a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/util/ProgressUtil.kt b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/util/ProgressUtil.kt index 0e623a19f0a..44801db18f7 100644 --- a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/util/ProgressUtil.kt +++ b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/util/ProgressUtil.kt @@ -12,7 +12,7 @@ import com.intellij.openapi.progress.util.ProgressIndicatorUtils import com.intellij.openapi.project.Project fun runInReadActionWithWriteActionPriorityWithPCE(f: () -> T): T = - runInReadActionWithWriteActionPriority(f) ?: throw ProcessCanceledException() + runInReadActionWithWriteActionPriority(f) ?: throw ProcessCanceledException() fun runInReadActionWithWriteActionPriority(f: () -> T): T? { if (with(ApplicationManager.getApplication()) { isDispatchThread && isUnitTestMode }) { diff --git a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/util/UiUtils.kt b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/util/UiUtils.kt index 8237d48b2c6..1a2f6b45d0e 100644 --- a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/util/UiUtils.kt +++ b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/util/UiUtils.kt @@ -11,10 +11,10 @@ import javax.swing.text.JTextComponent fun JTextComponent.onTextChange(action: (DocumentEvent) -> Unit) { document.addDocumentListener( - object : DocumentAdapter() { - override fun textChanged(e: DocumentEvent) { - action(e) - } + object : DocumentAdapter() { + override fun textChanged(e: DocumentEvent) { + action(e) } + } ) } \ No newline at end of file diff --git a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/util/messages.kt b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/util/messages.kt index 1142012350d..d387a1043bf 100644 --- a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/util/messages.kt +++ b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/util/messages.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.core.util @@ -26,8 +15,7 @@ import javax.swing.Icon fun showYesNoCancelDialog(key: String, project: Project, message: String, title: String, icon: Icon, default: Int?): Int { return if (!ApplicationManager.getApplication().isUnitTestMode) { Messages.showYesNoCancelDialog(project, message, title, icon) - } - else { + } else { callInTestMode(key, default) } } @@ -44,7 +32,7 @@ fun clearDialogsResults() { dialogResults.clear() } -private fun callInTestMode(key: String, default: T?): T { +private fun callInTestMode(key: String, default: T?): T { val result = dialogResults[key] if (result != null) { dialogResults.remove(key) diff --git a/idea/idea-core/src/org/jetbrains/kotlin/idea/j2k/IdeaDocCommentConverter.kt b/idea/idea-core/src/org/jetbrains/kotlin/idea/j2k/IdeaDocCommentConverter.kt index 2f94167e766..edeb13e651a 100644 --- a/idea/idea-core/src/org/jetbrains/kotlin/idea/j2k/IdeaDocCommentConverter.kt +++ b/idea/idea-core/src/org/jetbrains/kotlin/idea/j2k/IdeaDocCommentConverter.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.j2k @@ -28,8 +17,6 @@ import com.intellij.psi.xml.XmlFile import com.intellij.psi.xml.XmlTag import com.intellij.psi.xml.XmlText import com.intellij.psi.xml.XmlTokenType -import org.jetbrains.kotlin.idea.j2k.DocCommentConverter -import org.jetbrains.kotlin.idea.j2k.content object IdeaDocCommentConverter : DocCommentConverter { override fun convertDocComment(docComment: PsiDocComment): String { @@ -55,7 +42,8 @@ object IdeaDocCommentConverter : DocCommentConverter { } val htmlFile = PsiFileFactory.getInstance(docComment.project).createFileFromText( - "javadoc.html", HtmlFileType.INSTANCE, html) + "javadoc.html", HtmlFileType.INSTANCE, html + ) val htmlToMarkdownConverter = HtmlToMarkdownConverter() htmlFile.accept(htmlToMarkdownConverter) return htmlToMarkdownConverter.result @@ -65,8 +53,7 @@ object IdeaDocCommentConverter : DocCommentConverter { elements.forEach { if (it is PsiInlineDocTag) { append(convertInlineDocTag(it)) - } - else { + } else { if (it.node?.elementType != JavaDocTokenType.DOC_COMMENT_LEADING_ASTERISKS) { append(it.text) } @@ -79,7 +66,7 @@ object IdeaDocCommentConverter : DocCommentConverter { * Returns true if the builder ends with a new-line optionally followed by some spaces */ private fun StringBuilder.endsWithNewline(): Boolean { - for (i in length-1 downTo 0) { + for (i in length - 1 downTo 0) { val c = get(i) if (c.isWhitespace()) { if (c == '\n' || c == '\r') return true @@ -109,17 +96,14 @@ object IdeaDocCommentConverter : DocCommentConverter { else -> tag.text } - private fun convertJavadocLink(link: String?): String = - if (link != null) link.substringBefore('(').replace('#', '.') else "" + private fun convertJavadocLink(link: String?): String = link?.substringBefore('(')?.replace('#', '.') ?: "" - private fun PsiDocTag.linkElement(): PsiElement? = - valueElement ?: dataElements.firstOrNull { it !is PsiWhiteSpace } + private fun PsiDocTag.linkElement(): PsiElement? = valueElement ?: dataElements.firstOrNull { it !is PsiWhiteSpace } - private fun XmlTag.attributesAsString() = - if (attributes.isNotEmpty()) - attributes.joinToString(separator = " ", prefix = " ") { it.text } - else - "" + private fun XmlTag.attributesAsString() = if (attributes.isNotEmpty()) + attributes.joinToString(separator = " ", prefix = " ") { it.text } + else + "" private class HtmlToMarkdownConverter() : XmlRecursiveElementVisitor() { private enum class ListType { Ordered, Unordered; } @@ -131,7 +115,7 @@ object IdeaDocCommentConverter : DocCommentConverter { fun prefix(text: String) = MarkdownSpan(text, "") fun preserveTag(tag: XmlTag) = - MarkdownSpan("<${tag.name}${tag.attributesAsString()}>", "") + MarkdownSpan("<${tag.name}${tag.attributesAsString()}>", "") } } @@ -169,9 +153,7 @@ object IdeaDocCommentConverter : DocCommentConverter { override fun visitElement(element: PsiElement) { super.visitElement(element) - val tokenType = element.node.elementType - - when (tokenType) { + when (element.node.elementType) { XmlTokenType.XML_DATA_CHARACTERS -> { appendPendingText() markdownBuilder.append(element.text) @@ -215,8 +197,7 @@ object IdeaDocCommentConverter : DocCommentConverter { whitespaceIsPartOfText = newValue try { block() - } - finally { + } finally { whitespaceIsPartOfText = oldValue } } @@ -243,11 +224,9 @@ object IdeaDocCommentConverter : DocCommentConverter { val docRef = tag.getAttributeValue("docref") val innerText = tag.value.text if (docRef == innerText) MarkdownSpan("[", "]") else MarkdownSpan("[", "][$docRef]") - } - else if (tag.getAttributeValue("href") != null) { + } else if (tag.getAttributeValue("href") != null) { MarkdownSpan("[", "](${tag.getAttributeValue("href") ?: ""})") - } - else { + } else { MarkdownSpan.preserveTag(tag) } } diff --git a/idea/idea-gradle-native/src/org/jetbrains/kotlin/ide/konan/KotlinNativeABICompatibilityChecker.kt b/idea/idea-gradle-native/src/org/jetbrains/kotlin/ide/konan/KotlinNativeABICompatibilityChecker.kt index 2be20ffffe1..4a09061587e 100644 --- a/idea/idea-gradle-native/src/org/jetbrains/kotlin/ide/konan/KotlinNativeABICompatibilityChecker.kt +++ b/idea/idea-gradle-native/src/org/jetbrains/kotlin/ide/konan/KotlinNativeABICompatibilityChecker.kt @@ -6,7 +6,8 @@ package org.jetbrains.kotlin.ide.konan import com.intellij.ProjectTopics -import com.intellij.notification.* +import com.intellij.notification.Notification +import com.intellij.notification.NotificationType import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.runInEdt @@ -135,7 +136,8 @@ class KotlinNativeABICompatibilityChecker(private val project: Project) : Projec is LibraryGroup.ThirdParty -> { if (libraries.size == 1) { """ - |There is a third-party library attached to the project that was compiled with $compilerVersionText Kotlin/Native compiler and can't be read in IDE: ${libraries.single().first} + |There is a third-party library attached to the project that was compiled with $compilerVersionText Kotlin/Native compiler and can't be read in IDE: ${libraries.single() + .first} | |Please edit Gradle buildfile(s) and specify library version compatible with Kotlin/Native ${bundledRuntimeVersion()}. Then re-import the project in IDE. """.trimMargin() diff --git a/idea/idea-gradle/src/org/jetbrains/kotlin/idea/KotlinJavaMPPSourceSetDataService.kt b/idea/idea-gradle/src/org/jetbrains/kotlin/idea/KotlinJavaMPPSourceSetDataService.kt index 731b4d1ea58..325e445dcf2 100644 --- a/idea/idea-gradle/src/org/jetbrains/kotlin/idea/KotlinJavaMPPSourceSetDataService.kt +++ b/idea/idea-gradle/src/org/jetbrains/kotlin/idea/KotlinJavaMPPSourceSetDataService.kt @@ -1,5 +1,5 @@ /* - * Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -17,7 +17,6 @@ import com.intellij.openapi.roots.ModuleOrderEntry import com.intellij.openapi.roots.OrderRootType import com.intellij.openapi.roots.impl.ModuleOrderEntryImpl import com.intellij.openapi.vfs.VfsUtil -import org.jetbrains.kotlin.idea.caches.project.isTestModule import org.jetbrains.kotlin.idea.configuration.KotlinTargetData import org.jetbrains.kotlin.idea.configuration.kotlinSourceSet import org.jetbrains.plugins.gradle.model.data.GradleSourceSetData @@ -48,7 +47,7 @@ class KotlinJavaMPPSourceSetDataService : AbstractProjectDataService() - moduleEntries.filter { isTestModuleById(it.moduleName, toImport) }.forEach {moduleOrderEntry -> + moduleEntries.filter { isTestModuleById(it.moduleName, toImport) }.forEach { moduleOrderEntry -> (moduleOrderEntry as? ModuleOrderEntryImpl)?.isProductionOnTestDependency = true } val libraryEntries = rootModel.orderEntries.filterIsInstance() diff --git a/idea/idea-gradle/src/org/jetbrains/kotlin/idea/inspections/gradle/DeprecatedGradleDependencyInspection.kt b/idea/idea-gradle/src/org/jetbrains/kotlin/idea/inspections/gradle/DeprecatedGradleDependencyInspection.kt index a02b8c180e8..59d290ebefc 100644 --- a/idea/idea-gradle/src/org/jetbrains/kotlin/idea/inspections/gradle/DeprecatedGradleDependencyInspection.kt +++ b/idea/idea-gradle/src/org/jetbrains/kotlin/idea/inspections/gradle/DeprecatedGradleDependencyInspection.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.inspections.gradle @@ -51,7 +40,8 @@ class DeprecatedGradleDependencyInspection : BaseInspection(), CleanupLocalInspe if (dependenciesCall.invokedExpression.text != "dependencies") return val dependencyEntries = GradleHeuristicHelper.findStatementWithPrefixes( - closure, PRODUCTION_DEPENDENCY_STATEMENTS) + closure, PRODUCTION_DEPENDENCY_STATEMENTS + ) for (dependencyStatement in dependencyEntries) { visitDependencyEntry(dependencyStatement) } diff --git a/idea/idea-gradle/src/org/jetbrains/kotlin/idea/run/AbstractKotlinTestClassGradleConfigurationProducer.kt b/idea/idea-gradle/src/org/jetbrains/kotlin/idea/run/AbstractKotlinTestClassGradleConfigurationProducer.kt index e6c40c0af8f..4f9d20a66b6 100644 --- a/idea/idea-gradle/src/org/jetbrains/kotlin/idea/run/AbstractKotlinTestClassGradleConfigurationProducer.kt +++ b/idea/idea-gradle/src/org/jetbrains/kotlin/idea/run/AbstractKotlinTestClassGradleConfigurationProducer.kt @@ -19,7 +19,8 @@ import com.intellij.psi.PsiMethod import org.jetbrains.kotlin.idea.caches.project.isNewMPPModule import org.jetbrains.kotlin.idea.project.platform import org.jetbrains.kotlin.platform.TargetPlatform -import org.jetbrains.plugins.gradle.execution.test.runner.* +import org.jetbrains.plugins.gradle.execution.test.runner.TestClassGradleConfigurationProducer +import org.jetbrains.plugins.gradle.execution.test.runner.applyTestConfiguration import org.jetbrains.plugins.gradle.service.execution.GradleRunConfiguration import org.jetbrains.plugins.gradle.util.GradleConstants import org.jetbrains.plugins.gradle.util.GradleExecutionSettingsUtil.createTestFilterFrom @@ -93,8 +94,7 @@ abstract class AbstractKotlinMultiplatformTestClassGradleConfigurationProducer : } abstract class AbstractKotlinTestClassGradleConfigurationProducer - : TestClassGradleConfigurationProducer(), KotlinGradleConfigurationProducer -{ + : TestClassGradleConfigurationProducer(), KotlinGradleConfigurationProducer { override fun getConfigurationFactory(): ConfigurationFactory { return KotlinGradleExternalTaskConfigurationType.instance.factory } diff --git a/idea/idea-gradle/src/org/jetbrains/kotlin/idea/run/AbstractKotlinTestMethodGradleConfigurationProducer.kt b/idea/idea-gradle/src/org/jetbrains/kotlin/idea/run/AbstractKotlinTestMethodGradleConfigurationProducer.kt index 2951233b0ef..195346411cc 100644 --- a/idea/idea-gradle/src/org/jetbrains/kotlin/idea/run/AbstractKotlinTestMethodGradleConfigurationProducer.kt +++ b/idea/idea-gradle/src/org/jetbrains/kotlin/idea/run/AbstractKotlinTestMethodGradleConfigurationProducer.kt @@ -96,8 +96,7 @@ abstract class AbstractKotlinMultiplatformTestMethodGradleConfigurationProducer } abstract class AbstractKotlinTestMethodGradleConfigurationProducer - : TestMethodGradleConfigurationProducer(), KotlinGradleConfigurationProducer -{ + : TestMethodGradleConfigurationProducer(), KotlinGradleConfigurationProducer { override fun getConfigurationFactory(): ConfigurationFactory { return KotlinGradleExternalTaskConfigurationType.instance.factory } diff --git a/idea/idea-gradle/src/org/jetbrains/kotlin/idea/scripting/gradle/GradleScriptDefinitionsProvider.kt b/idea/idea-gradle/src/org/jetbrains/kotlin/idea/scripting/gradle/GradleScriptDefinitionsProvider.kt index cdc6b1ae670..59affff0f2b 100644 --- a/idea/idea-gradle/src/org/jetbrains/kotlin/idea/scripting/gradle/GradleScriptDefinitionsProvider.kt +++ b/idea/idea-gradle/src/org/jetbrains/kotlin/idea/scripting/gradle/GradleScriptDefinitionsProvider.kt @@ -126,7 +126,9 @@ class GradleScriptDefinitionsContributor(private val project: Project) : ScriptD // TODO: check this against kotlin-dsl branch that uses daemon private fun kotlinStdlibAndCompiler(gradleLibDir: File): List { // additionally need compiler jar to load gradle resolver - return gradleLibDir.listFiles { file -> file.name.startsWith("kotlin-compiler-embeddable") || file.name.startsWith("kotlin-stdlib") } + return gradleLibDir.listFiles { file -> + file.name.startsWith("kotlin-compiler-embeddable") || file.name.startsWith("kotlin-stdlib") + } .firstOrNull()?.let(::listOf).orEmpty() } @@ -214,10 +216,11 @@ class GradleScriptDefinitionsContributor(private val project: Project) : ScriptD if (legacyDef.scriptExpectedLocations.contains(ScriptExpectedLocation.Project)) null else { // Expand scope for old gradle script definition - ScriptDefinition.FromLegacy(it.hostConfiguration, - GradleKotlinScriptDefinitionFromAnnotatedTemplate( - legacyDef - ) + ScriptDefinition.FromLegacy( + it.hostConfiguration, + GradleKotlinScriptDefinitionFromAnnotatedTemplate( + legacyDef + ) ) } } ?: it @@ -236,10 +239,11 @@ class GradleScriptDefinitionsContributor(private val project: Project) : ScriptD // TODO: refactor - minimize private class ErrorGradleScriptDefinition(message: String? = null) : - ScriptDefinition.FromLegacy(ScriptingHostConfiguration(defaultJvmScriptingHostConfiguration), - LegacyDefinition( - message - ) + ScriptDefinition.FromLegacy( + ScriptingHostConfiguration(defaultJvmScriptingHostConfiguration), + LegacyDefinition( + message + ) ) { private class LegacyDefinition(message: String?) : KotlinScriptDefinitionAdapterFromNewAPIBase() { diff --git a/idea/idea-j2k/src/org/jetbrains/kotlin/idea/j2k/IdeaReferenceSearcher.kt b/idea/idea-j2k/src/org/jetbrains/kotlin/idea/j2k/IdeaReferenceSearcher.kt index 8053ef63b5c..4d8f4b52511 100644 --- a/idea/idea-j2k/src/org/jetbrains/kotlin/idea/j2k/IdeaReferenceSearcher.kt +++ b/idea/idea-j2k/src/org/jetbrains/kotlin/idea/j2k/IdeaReferenceSearcher.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.j2k @@ -31,14 +20,19 @@ import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.j2k.ReferenceSearcher import java.util.* -object IdeaReferenceSearcher: ReferenceSearcher { - override fun findLocalUsages(element: PsiElement, scope: PsiElement) = ReferencesSearch.search(element, LocalSearchScope(scope)).findAll() +object IdeaReferenceSearcher : ReferenceSearcher { + override fun findLocalUsages(element: PsiElement, scope: PsiElement) = + ReferencesSearch.search(element, LocalSearchScope(scope)).findAll() override fun hasInheritors(`class`: PsiClass) = ClassInheritorsSearch.search(`class`, false).any() override fun hasOverrides(method: PsiMethod) = OverridingMethodsSearch.search(method, false).any() - override fun findUsagesForExternalCodeProcessing(element: PsiElement, searchJava: Boolean, searchKotlin: Boolean): Collection { + override fun findUsagesForExternalCodeProcessing( + element: PsiElement, + searchJava: Boolean, + searchKotlin: Boolean + ): Collection { val fileTypes = ArrayList() if (searchJava) { fileTypes.add(JavaLanguage.INSTANCE.associatedFileType!!) @@ -46,7 +40,8 @@ object IdeaReferenceSearcher: ReferenceSearcher { if (searchKotlin) { fileTypes.add(KotlinLanguage.INSTANCE.associatedFileType!!) } - val searchScope = GlobalSearchScope.getScopeRestrictedByFileTypes(GlobalSearchScope.projectScope(element.project), *fileTypes.toTypedArray()) + val searchScope = + GlobalSearchScope.getScopeRestrictedByFileTypes(GlobalSearchScope.projectScope(element.project), *fileTypes.toTypedArray()) return ReferencesSearch.search(element, searchScope).findAll() } } diff --git a/idea/idea-jps-common/src/org/jetbrains/kotlin/config/KotlinFacetSettings.kt b/idea/idea-jps-common/src/org/jetbrains/kotlin/config/KotlinFacetSettings.kt index a6264e0c63a..24f6f2eb465 100644 --- a/idea/idea-jps-common/src/org/jetbrains/kotlin/config/KotlinFacetSettings.kt +++ b/idea/idea-jps-common/src/org/jetbrains/kotlin/config/KotlinFacetSettings.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.config @@ -58,7 +47,7 @@ sealed class TargetPlatformKind( object CoroutineSupport { @JvmStatic fun byCompilerArguments(arguments: CommonCompilerArguments?): LanguageFeature.State = - byCompilerArgumentsOrNull(arguments) ?: LanguageFeature.Coroutines.defaultState + byCompilerArgumentsOrNull(arguments) ?: LanguageFeature.Coroutines.defaultState fun byCompilerArgumentsOrNull(arguments: CommonCompilerArguments?): LanguageFeature.State? = when (arguments?.coroutinesState) { CommonCompilerArguments.ENABLE -> LanguageFeature.State.ENABLED @@ -68,7 +57,7 @@ object CoroutineSupport { } fun byCompilerArgument(argument: String): LanguageFeature.State = - LanguageFeature.State.values().find { getCompilerArgument(it).equals(argument, ignoreCase = true) } + LanguageFeature.State.values().find { getCompilerArgument(it).equals(argument, ignoreCase = true) } ?: LanguageFeature.Coroutines.defaultState fun getCompilerArgument(state: LanguageFeature.State): String = when (state) { @@ -191,8 +180,7 @@ class KotlinFacetSettings { parseCommandLineArguments(compilerSettings.additionalArgumentsAsList, this) } } - } - else null + } else null } var compilerArguments: CommonCompilerArguments? = null diff --git a/idea/idea-jps-common/src/org/jetbrains/kotlin/config/facetSerialization.kt b/idea/idea-jps-common/src/org/jetbrains/kotlin/config/facetSerialization.kt index 668eb3bace5..64cb27329ed 100644 --- a/idea/idea-jps-common/src/org/jetbrains/kotlin/config/facetSerialization.kt +++ b/idea/idea-jps-common/src/org/jetbrains/kotlin/config/facetSerialization.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.config @@ -100,8 +89,7 @@ private fun readV1Config(element: Element): KotlinFacetSettings { if (useProjectSettings != null) { this.useProjectSettings = useProjectSettings - } - else { + } else { // Migration problem workaround for pre-1.1-beta releases (mainly 1.0.6) -> 1.1-rc+ // Problematic cases: 1.1-beta/1.1-beta2 -> 1.1-rc+ (useProjectSettings gets reset to false) // This heuristic detects old enough configurations: @@ -214,13 +202,11 @@ private fun readLatestConfig(element: Element): KotlinFacetSettings { } fun deserializeFacetSettings(element: Element): KotlinFacetSettings { - val version = - try { - element.getAttribute("version")?.intValue - } - catch(e: DataConversionException) { - null - } ?: KotlinFacetSettings.DEFAULT_VERSION + val version = try { + element.getAttribute("version")?.intValue + } catch (e: DataConversionException) { + null + } ?: KotlinFacetSettings.DEFAULT_VERSION return when (version) { 1 -> readV1Config(element) 2 -> readV2Config(element) @@ -290,9 +276,8 @@ private val Class<*>.normalOrdering private fun Element.restoreNormalOrdering(bean: Any) { val normalOrdering = bean.javaClass.normalOrdering val elementsToReorder = this.getContent { it is Element && it.getAttribute("name")?.value in normalOrdering } - elementsToReorder - .sortedBy { normalOrdering[it.getAttribute("name")?.value!!] } - .forEachIndexed { index, element -> elementsToReorder[index] = element.clone() } + elementsToReorder.sortedBy { normalOrdering[it.getAttribute("name")?.value!!] } + .forEachIndexed { index, element -> elementsToReorder[index] = element.clone() } } private fun buildChildElement(element: Element, tag: String, bean: Any, filter: SerializationFilter): Element { @@ -422,8 +407,7 @@ fun KotlinFacetSettings.serializeFacetSettings(element: Element) { element.setAttribute("version", versionToWrite.toString()) if (versionToWrite == 2) { writeV2Config(element) - } - else { + } else { writeLatestConfig(element) } } diff --git a/idea/idea-jps-common/src/org/jetbrains/kotlin/config/moduleSourceRootPropertiesSerializers.kt b/idea/idea-jps-common/src/org/jetbrains/kotlin/config/moduleSourceRootPropertiesSerializers.kt index e9635a4bd5a..9ae08088253 100644 --- a/idea/idea-jps-common/src/org/jetbrains/kotlin/config/moduleSourceRootPropertiesSerializers.kt +++ b/idea/idea-jps-common/src/org/jetbrains/kotlin/config/moduleSourceRootPropertiesSerializers.kt @@ -1,5 +1,5 @@ /* - * Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -13,8 +13,8 @@ import org.jetbrains.jps.model.module.JpsModuleSourceRootType import org.jetbrains.jps.model.serialization.module.JpsModuleRootModelSerializer import org.jetbrains.jps.model.serialization.module.JpsModuleSourceRootPropertiesSerializer -private val IS_GENERATED_ATTRIBUTE = "generated" -private val RELATIVE_OUTPUT_PATH_ATTRIBUTE = "relativeOutputPath" +private const val IS_GENERATED_ATTRIBUTE = "generated" +private const val RELATIVE_OUTPUT_PATH_ATTRIBUTE = "relativeOutputPath" val KOTLIN_SOURCE_ROOT_TYPE_ID = "kotlin-source" val KOTLIN_TEST_ROOT_TYPE_ID = "kotlin-test" @@ -27,13 +27,13 @@ sealed class KotlinSourceRootPropertiesSerializer( typeId: String ) : JpsModuleSourceRootPropertiesSerializer(type, typeId) { object Source : KotlinSourceRootPropertiesSerializer( - SourceKotlinRootType, - KOTLIN_SOURCE_ROOT_TYPE_ID + SourceKotlinRootType, + KOTLIN_SOURCE_ROOT_TYPE_ID ) object TestSource : KotlinSourceRootPropertiesSerializer( - TestSourceKotlinRootType, - KOTLIN_TEST_ROOT_TYPE_ID + TestSourceKotlinRootType, + KOTLIN_TEST_ROOT_TYPE_ID ) override fun loadProperties(sourceRootTag: Element): JavaSourceRootProperties { @@ -59,9 +59,10 @@ sealed class KotlinResourceRootPropertiesSerializer( typeId: String ) : JpsModuleSourceRootPropertiesSerializer(type, typeId) { object Resource : KotlinResourceRootPropertiesSerializer( - ResourceKotlinRootType, - KOTLIN_RESOURCE_ROOT_TYPE_ID + ResourceKotlinRootType, + KOTLIN_RESOURCE_ROOT_TYPE_ID ) + object TestResource : KotlinResourceRootPropertiesSerializer( TestResourceKotlinRootType, KOTLIN_TEST_RESOURCE_ROOT_TYPE_ID diff --git a/idea/idea-jps-common/src/org/jetbrains/kotlin/platform/IdePlatformKind.kt b/idea/idea-jps-common/src/org/jetbrains/kotlin/platform/IdePlatformKind.kt index 72c06542638..fe75bbad037 100644 --- a/idea/idea-jps-common/src/org/jetbrains/kotlin/platform/IdePlatformKind.kt +++ b/idea/idea-jps-common/src/org/jetbrains/kotlin/platform/IdePlatformKind.kt @@ -1,5 +1,5 @@ /* - * Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -8,9 +8,9 @@ package org.jetbrains.kotlin.platform import com.intellij.openapi.diagnostic.Logger -import org.jetbrains.kotlin.extensions.ApplicationExtensionDescriptor import org.jetbrains.kotlin.cli.common.arguments.CommonCompilerArguments import org.jetbrains.kotlin.config.isJps +import org.jetbrains.kotlin.extensions.ApplicationExtensionDescriptor import org.jetbrains.kotlin.platform.impl.CommonIdePlatformKind import org.jetbrains.kotlin.platform.impl.JsIdePlatformKind import org.jetbrains.kotlin.platform.impl.JvmIdePlatformKind @@ -75,7 +75,9 @@ val TargetPlatform.idePlatformKind: IdePlatformKind<*> get() = IdePlatformKind.ALL_KINDS.filter { it.supportsTargetPlatform(this) }.let { list -> when { list.size == 1 -> list.first() - list.size > 1 -> list.first().also { Logger.getInstance(IdePlatformKind.javaClass).warn("Found more than one IdePlatformKind [$list] for target [$this].") } + list.size > 1 -> list.first().also { + Logger.getInstance(IdePlatformKind.javaClass).warn("Found more than one IdePlatformKind [$list] for target [$this].") + } else -> error("Unknown platform $this") } } \ No newline at end of file diff --git a/idea/idea-jps-common/src/org/jetbrains/kotlin/platform/impl/JvmIdePlatformKind.kt b/idea/idea-jps-common/src/org/jetbrains/kotlin/platform/impl/JvmIdePlatformKind.kt index 8ad48e32821..a0ab9b1af92 100644 --- a/idea/idea-jps-common/src/org/jetbrains/kotlin/platform/impl/JvmIdePlatformKind.kt +++ b/idea/idea-jps-common/src/org/jetbrains/kotlin/platform/impl/JvmIdePlatformKind.kt @@ -1,5 +1,5 @@ /* - * Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -43,7 +43,9 @@ object JvmIdePlatformKind : IdePlatformKind() { return K2JVMCompilerArguments() } - val platforms: List = JvmTarget.values().map { ver -> JvmPlatforms.jvmPlatformByTargetVersion(ver) } + listOf(JvmPlatforms.unspecifiedJvmPlatform) + val platforms: List = JvmTarget.values() + .map { ver -> JvmPlatforms.jvmPlatformByTargetVersion(ver) } + listOf(JvmPlatforms.unspecifiedJvmPlatform) + override val defaultPlatform get() = JvmPlatforms.defaultJvmPlatform override val argumentsClass get() = K2JVMCompilerArguments::class.java diff --git a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/KotlinExtraSteppingFilter.kt b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/KotlinExtraSteppingFilter.kt index e0505a4725c..4d2d827de85 100644 --- a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/KotlinExtraSteppingFilter.kt +++ b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/KotlinExtraSteppingFilter.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea @@ -48,13 +37,11 @@ class KotlinExtraSteppingFilter : ExtraSteppingFilter { return false } - val sourcePosition = - try { - positionManager.getSourcePosition(location) - } - catch(e: NoDataException) { - return false - } ?: return false + val sourcePosition = try { + positionManager.getSourcePosition(location) + } catch (e: NoDataException) { + return false + } ?: return false if (isOnSuspendReturnOrReenter(location) && !isOneLineMethod(location)) { return true diff --git a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/ThreadTrackerPatcherForTeamCityTesting.kt b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/ThreadTrackerPatcherForTeamCityTesting.kt index 174f64dd332..886887081cc 100644 --- a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/ThreadTrackerPatcherForTeamCityTesting.kt +++ b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/ThreadTrackerPatcherForTeamCityTesting.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea @@ -52,8 +41,7 @@ object ThreadTrackerPatcherForTeamCityTesting { try { val wellKnownOffendersField = try { ThreadTracker::class.java.getDeclaredField("wellKnownOffenders") - } - catch (communityPropertyNotFoundEx: NoSuchFieldException) { + } catch (communityPropertyNotFoundEx: NoSuchFieldException) { ThreadTracker::class.java.declaredFields.single { Modifier.isStatic(it.modifiers) && MutableSet::class.java.isAssignableFrom(it.type) } @@ -66,12 +54,10 @@ object ThreadTrackerPatcherForTeamCityTesting { wellKnownOffenders.add("ForkJoinPool.commonPool-worker-") println("Patching ThreadTracker was successful") - } - catch (e: NoSuchFieldException) { - println("Patching ThreadTracker failed: " + e) - } - catch (e: IllegalAccessException) { - println("Patching ThreadTracker failed: " + e) + } catch (e: NoSuchFieldException) { + println("Patching ThreadTracker failed: $e") + } catch (e: IllegalAccessException) { + println("Patching ThreadTracker failed: $e") } } } \ No newline at end of file diff --git a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/actions/ConfigureKotlinInProjectAction.kt b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/actions/ConfigureKotlinInProjectAction.kt index fb6d534746a..5ee30322f8e 100644 --- a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/actions/ConfigureKotlinInProjectAction.kt +++ b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/actions/ConfigureKotlinInProjectAction.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -34,7 +34,8 @@ abstract class ConfigureKotlinInProjectAction : AnAction() { configurators.size == 1 -> configurators.first().configure(project, emptyList()) configurators.isEmpty() -> Messages.showErrorDialog("There aren't configurators available", e.presentation.text!!) else -> { - val configuratorsPopup = KotlinSetupEnvironmentNotificationProvider.createConfiguratorsPopup(project, configurators.toList()) + val configuratorsPopup = + KotlinSetupEnvironmentNotificationProvider.createConfiguratorsPopup(project, configurators.toList()) configuratorsPopup.showInBestPositionFor(e.dataContext) } } @@ -42,20 +43,22 @@ abstract class ConfigureKotlinInProjectAction : AnAction() { } -class ConfigureKotlinJsInProjectAction: ConfigureKotlinInProjectAction() { +class ConfigureKotlinJsInProjectAction : ConfigureKotlinInProjectAction() { override fun getApplicableConfigurators(project: Project) = getAbleToRunConfigurators(project).filter { it.targetPlatform.isJs() } override fun update(e: AnActionEvent) { val project = e.project - if (!PlatformUtils.isIntelliJ() && (project == null || project.allModules().all { it.getBuildSystemType() != BuildSystemType.JPS })) { + if (!PlatformUtils.isIntelliJ() && + (project == null || project.allModules().all { it.getBuildSystemType() != BuildSystemType.JPS }) + ) { e.presentation.isEnabledAndVisible = false } } } -class ConfigureKotlinJavaInProjectAction: ConfigureKotlinInProjectAction() { +class ConfigureKotlinJavaInProjectAction : ConfigureKotlinInProjectAction() { override fun getApplicableConfigurators(project: Project) = getAbleToRunConfigurators(project).filter { it.targetPlatform.isJvm() } diff --git a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/configuration/ConfigureKotlinInProjectUtils.kt b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/configuration/ConfigureKotlinInProjectUtils.kt index c82fde1b0c3..2d18c36539a 100644 --- a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/configuration/ConfigureKotlinInProjectUtils.kt +++ b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/configuration/ConfigureKotlinInProjectUtils.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -227,7 +227,8 @@ fun getConfigurationPossibilitiesForConfigureNotification( runnableConfigurators.add(configurator) } ConfigureKotlinStatus.CONFIGURED -> moduleAlreadyConfigured = true - else -> {} + else -> { + } } } if (moduleCanBeConfigured && !moduleAlreadyConfigured && !SuppressNotificationState.isKotlinNotConfiguredSuppressed( diff --git a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/configuration/ConfigureKotlinNotificationManager.kt b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/configuration/ConfigureKotlinNotificationManager.kt index 7e63d7403f9..0c19bce1fef 100644 --- a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/configuration/ConfigureKotlinNotificationManager.kt +++ b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/configuration/ConfigureKotlinNotificationManager.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -18,7 +18,7 @@ import org.jetbrains.kotlin.idea.configuration.ui.notifications.ConfigureKotlinN import java.util.concurrent.atomic.AtomicBoolean import kotlin.reflect.KClass -object ConfigureKotlinNotificationManager: KotlinSingleNotificationManager { +object ConfigureKotlinNotificationManager : KotlinSingleNotificationManager { fun notify(project: Project, excludeModules: List = emptyList()) { val notificationState = ConfigureKotlinNotification.getNotificationState(project, excludeModules) if (notificationState != null) { @@ -35,7 +35,7 @@ object ConfigureKotlinNotificationManager: KotlinSingleNotificationManager { +interface KotlinSingleNotificationManager { fun notify(project: Project, notification: T) { if (!expireOldNotifications(project, notification::class, notification)) { notification.notify(project) diff --git a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/configuration/KotlinProjectConfigurator.kt b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/configuration/KotlinProjectConfigurator.kt index 887d5e30939..c2049fb3a4e 100644 --- a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/configuration/KotlinProjectConfigurator.kt +++ b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/configuration/KotlinProjectConfigurator.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.configuration @@ -26,15 +15,17 @@ import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.idea.versions.LibraryJarDescriptor import org.jetbrains.kotlin.platform.TargetPlatform import org.jetbrains.kotlin.platform.compat.toNewPlatform -import org.jetbrains.kotlin.platform.compat.toOldPlatform enum class ConfigureKotlinStatus { /** Kotlin is correctly configured using this configurator. */ CONFIGURED, + /** The configurator is not applicable to the current project type. */ NON_APPLICABLE, + /** The configurator is applicable to the current project type and can configure Kotlin automatically. */ CAN_BE_CONFIGURED, + /** * The configurator is applicable to the current project type and Kotlin is not configured, * but the state of the project doesn't allow to configure Kotlin automatically. @@ -46,7 +37,8 @@ interface KotlinProjectConfigurator { fun getStatus(moduleSourceRootGroup: ModuleSourceRootGroup): ConfigureKotlinStatus - @JvmSuppressWildcards fun configure(project: Project, excludeModules: Collection) + @JvmSuppressWildcards + fun configure(project: Project, excludeModules: Collection) val presentableText: String @@ -70,7 +62,13 @@ interface KotlinProjectConfigurator { ) fun getTargetPlatform(): org.jetbrains.kotlin.resolve.TargetPlatform - fun updateLanguageVersion(module: Module, languageVersion: String?, apiVersion: String?, requiredStdlibVersion: ApiVersion, forTests: Boolean) + fun updateLanguageVersion( + module: Module, + languageVersion: String?, + apiVersion: String?, + requiredStdlibVersion: ApiVersion, + forTests: Boolean + ) fun changeCoroutineConfiguration(module: Module, state: LanguageFeature.State) @@ -81,7 +79,12 @@ interface KotlinProjectConfigurator { forTests: Boolean ) - fun addLibraryDependency(module: Module, element: PsiElement, library: ExternalLibraryDescriptor, libraryJarDescriptors: List) + fun addLibraryDependency( + module: Module, + element: PsiElement, + library: ExternalLibraryDescriptor, + libraryJarDescriptors: List + ) companion object { val EP_NAME = ExtensionPointName.create("org.jetbrains.kotlin.projectConfigurator") diff --git a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/configuration/KotlinWithLibraryConfigurator.kt b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/configuration/KotlinWithLibraryConfigurator.kt index 4c958593131..b0f3e130732 100644 --- a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/configuration/KotlinWithLibraryConfigurator.kt +++ b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/configuration/KotlinWithLibraryConfigurator.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -78,16 +78,16 @@ abstract class KotlinWithLibraryConfigurator protected constructor() : KotlinPro if (nonConfiguredModules.size > 1 || showPathToJarPanel) { val dialog = CreateLibraryDialogWithModules( - project, this, defaultPathToJar, showPathToJarPanel, - dialogTitle, - libraryCaption, - excludeModules) + project, this, defaultPathToJar, showPathToJarPanel, + dialogTitle, + libraryCaption, + excludeModules + ) if (!ApplicationManager.getApplication().isUnitTestMode) { dialog.show() if (!dialog.isOK) return - } - else { + } else { dialog.close(0) } @@ -115,10 +115,10 @@ abstract class KotlinWithLibraryConfigurator protected constructor() : KotlinPro } protected fun configureModule( - module: Module, - defaultPath: String, - pathFromDialog: String?, - collector: NotificationMessageCollector + module: Module, + defaultPath: String, + pathFromDialog: String?, + collector: NotificationMessageCollector ) { val classesPath = getPathToCopyFileTo(module.project, OrderRootType.CLASSES, defaultPath, pathFromDialog) val sourcesPath = getPathToCopyFileTo(module.project, OrderRootType.SOURCES, defaultPath, pathFromDialog) @@ -126,30 +126,30 @@ abstract class KotlinWithLibraryConfigurator protected constructor() : KotlinPro } open fun configureModule( - module: Module, - classesPath: String, - sourcesPath: String, - collector: NotificationMessageCollector, - forceJarState: FileState? = null, - useBundled: Boolean = false + module: Module, + classesPath: String, + sourcesPath: String, + collector: NotificationMessageCollector, + forceJarState: FileState? = null, + useBundled: Boolean = false ) { configureModuleWithLibrary(module, classesPath, sourcesPath, collector, forceJarState, useBundled) } private fun configureModuleWithLibrary( - module: Module, - classesPath: String, - sourcesPath: String, - collector: NotificationMessageCollector, - forceJarState: FileState? = null, - useBundled: Boolean = false + module: Module, + classesPath: String, + sourcesPath: String, + collector: NotificationMessageCollector, + forceJarState: FileState? = null, + useBundled: Boolean = false ) { val project = module.project val library = findAndFixBrokenKotlinLibrary(module, collector) - ?: getKotlinLibrary(module) - ?: getKotlinLibrary(project) - ?: createNewLibrary(project, collector) + ?: getKotlinLibrary(module) + ?: getKotlinLibrary(project) + ?: createNewLibrary(project, collector) val sdk = module.sdk val model = library.modifiableModel @@ -160,9 +160,11 @@ abstract class KotlinWithLibraryConfigurator protected constructor() : KotlinPro else classesPath - val runtimeState = forceJarState ?: getJarState(project, - File(dirToCopyJar, descriptor.jarName), - descriptor.orderRootType, useBundled) + val runtimeState = forceJarState ?: getJarState( + project, + File(dirToCopyJar, descriptor.jarName), + descriptor.orderRootType, useBundled + ) configureLibraryJar(model, runtimeState, dirToCopyJar, descriptor, collector) } @@ -173,11 +175,11 @@ abstract class KotlinWithLibraryConfigurator protected constructor() : KotlinPro fun configureLibraryJar( - library: Library.ModifiableModel, - jarState: FileState, - dirToCopyJarTo: String, - libraryJarDescriptor: LibraryJarDescriptor, - collector: NotificationMessageCollector + library: Library.ModifiableModel, + jarState: FileState, + dirToCopyJarTo: String, + libraryJarDescriptor: LibraryJarDescriptor, + collector: NotificationMessageCollector ) { val jarFile = if (jarState == FileState.DO_NOT_COPY) libraryJarDescriptor.getPathInPlugin() @@ -207,8 +209,8 @@ abstract class KotlinWithLibraryConfigurator protected constructor() : KotlinPro } fun getKotlinLibrary(project: Project): Library? { - return LibraryTablesRegistrar.getInstance().getLibraryTable(project).libraries.firstOrNull { isKotlinLibrary(it, project) } ?: - LibraryTablesRegistrar.getInstance().libraryTable.libraries.firstOrNull { isKotlinLibrary(it, project) } + return LibraryTablesRegistrar.getInstance().getLibraryTable(project).libraries.firstOrNull { isKotlinLibrary(it, project) } + ?: LibraryTablesRegistrar.getInstance().libraryTable.libraries.firstOrNull { isKotlinLibrary(it, project) } } @Contract("!null, _, _ -> !null") @@ -232,8 +234,7 @@ abstract class KotlinWithLibraryConfigurator protected constructor() : KotlinPro if (kotlinLibrary == null) { ModuleRootModificationUtil.addDependency(module, library, expectedDependencyScope, false) collector.addMessage(library.name + " library was added to module " + module.name) - } - else { + } else { val libraryEntry = findLibraryOrderEntry(ModuleRootManager.getInstance(module).orderEntries, kotlinLibrary) if (libraryEntry != null) { val libraryDependencyScope = libraryEntry.scope @@ -241,16 +242,17 @@ abstract class KotlinWithLibraryConfigurator protected constructor() : KotlinPro libraryEntry.scope = expectedDependencyScope collector.addMessage( - kotlinLibrary.name + " library scope has changed from " + libraryDependencyScope + - " to " + expectedDependencyScope + " for module " + module.name) + kotlinLibrary.name + " library scope has changed from " + libraryDependencyScope + + " to " + expectedDependencyScope + " for module " + module.name + ) } } } } fun createNewLibrary( - project: Project, - collector: NotificationMessageCollector + project: Project, + collector: NotificationMessageCollector ): Library { val table = LibraryTablesRegistrar.getInstance().getLibraryTable(project) val library = runWriteAction { @@ -281,7 +283,7 @@ abstract class KotlinWithLibraryConfigurator protected constructor() : KotlinPro protected fun needToChooseJarPath(project: Project): Boolean { val defaultPath = getDefaultPathToJarFile(project) return !isProjectLibraryPresent(project) && - !File(defaultPath, getLibraryJarDescriptors(null).first().jarName).exists() + !File(defaultPath, getLibraryJarDescriptors(null).first().jarName).exists() } open fun getDefaultPathToJarFile(project: Project): String { @@ -295,10 +297,10 @@ abstract class KotlinWithLibraryConfigurator protected constructor() : KotlinPro } protected fun getJarState( - project: Project, - targetFile: File, - jarType: OrderRootType, - useBundled: Boolean + project: Project, + targetFile: File, + jarType: OrderRootType, + useBundled: Boolean ): FileState = when { targetFile.exists() -> FileState.EXISTS getPathFromLibrary(project, jarType) != null -> FileState.COPY @@ -307,10 +309,10 @@ abstract class KotlinWithLibraryConfigurator protected constructor() : KotlinPro } private fun getPathToCopyFileTo( - project: Project, - jarType: OrderRootType, - defaultDir: String, - pathFromDialog: String? + project: Project, + jarType: OrderRootType, + defaultDir: String, + pathFromDialog: String? ): String { if (pathFromDialog != null) { return pathFromDialog @@ -373,18 +375,24 @@ abstract class KotlinWithLibraryConfigurator protected constructor() : KotlinPro facetSettings.languageLevel = feature.sinceVersion facetSettings.compilerSettings?.apply { additionalArguments = additionalArguments.replaceLanguageFeature( - feature, - state, - getCleanRuntimeLibraryVersion(module), - separator = " ", - quoted = false - ) + feature, + state, + getCleanRuntimeLibraryVersion(module), + separator = " ", + quoted = false + ) } } } } - override fun updateLanguageVersion(module: Module, languageVersion: String?, apiVersion: String?, requiredStdlibVersion: ApiVersion, forTests: Boolean) { + override fun updateLanguageVersion( + module: Module, + languageVersion: String?, + apiVersion: String?, + requiredStdlibVersion: ApiVersion, + forTests: Boolean + ) { val runtimeUpdateRequired = getRuntimeLibraryVersion(module)?.let { ApiVersion.parse(it) }?.let { runtimeVersion -> runtimeVersion < requiredStdlibVersion } ?: false @@ -408,7 +416,12 @@ abstract class KotlinWithLibraryConfigurator protected constructor() : KotlinPro } } - override fun addLibraryDependency(module: Module, element: PsiElement, library: ExternalLibraryDescriptor, libraryJarDescriptors: List) { + override fun addLibraryDependency( + module: Module, + element: PsiElement, + library: ExternalLibraryDescriptor, + libraryJarDescriptors: List + ) { val project = module.project val collector = createConfigureKotlinNotificationCollector(project) @@ -427,8 +440,7 @@ abstract class KotlinWithLibraryConfigurator protected constructor() : KotlinPro val libIoFile = File(libFilesDir, libraryJarDescriptor.jarName) if (libIoFile.exists()) { model.addRoot(VfsUtil.getUrlForLibraryRoot(libIoFile), libraryJarDescriptor.orderRootType) - } - else { + } else { val copied = copyFileToDir(libFile, libFilesDir, collector)!! model.addRoot(VfsUtil.getUrlForLibraryRoot(copied), libraryJarDescriptor.orderRootType) } diff --git a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/configuration/NotificationMessageCollector.kt b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/configuration/NotificationMessageCollector.kt index 5e6a451cf93..bea5ae4c4b8 100644 --- a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/configuration/NotificationMessageCollector.kt +++ b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/configuration/NotificationMessageCollector.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.configuration @@ -22,9 +11,11 @@ import com.intellij.notification.Notifications import com.intellij.openapi.project.Project import java.util.* -open class NotificationMessageCollector(private val project: Project, - private val groupDisplayId: String, - private val title: String) { +open class NotificationMessageCollector( + private val project: Project, + private val groupDisplayId: String, + private val title: String +) { private val messages = ArrayList() fun addMessage(message: String): NotificationMessageCollector { @@ -37,13 +28,14 @@ open class NotificationMessageCollector(private val project: Project, Notifications.Bus.notify(Notification(groupDisplayId, title, resultMessage, NotificationType.INFORMATION), project) } - private val resultMessage: String get() { - val singleMessage = messages.singleOrNull() - if (singleMessage != null) return singleMessage + private val resultMessage: String + get() { + val singleMessage = messages.singleOrNull() + if (singleMessage != null) return singleMessage - return messages.joinToString(separator = "

    ") - } + return messages.joinToString(separator = "

    ") + } } fun createConfigureKotlinNotificationCollector(project: Project) = - NotificationMessageCollector(project, "Configure Kotlin: info notification", "Configure Kotlin") \ No newline at end of file + NotificationMessageCollector(project, "Configure Kotlin: info notification", "Configure Kotlin") \ No newline at end of file diff --git a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/configuration/ui/notifications/ConfigureKotlinNotification.kt b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/configuration/ui/notifications/ConfigureKotlinNotification.kt index 7061fc89e52..79500caa4d2 100644 --- a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/configuration/ui/notifications/ConfigureKotlinNotification.kt +++ b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/configuration/ui/notifications/ConfigureKotlinNotification.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -54,7 +54,10 @@ class ConfigureKotlinNotification( companion object { fun getNotificationState(project: Project, excludeModules: Collection): ConfigureKotlinNotificationState? { - val (configurableModules, ableToRunConfigurators) = getConfigurationPossibilitiesForConfigureNotification(project, excludeModules) + val (configurableModules, ableToRunConfigurators) = getConfigurationPossibilitiesForConfigureNotification( + project, + excludeModules + ) if (ableToRunConfigurators.isEmpty() || configurableModules.isEmpty()) return null val isOnlyOneModule = configurableModules.size == 1 @@ -71,8 +74,7 @@ class ConfigureKotlinNotification( ) } - private fun getLink(configurator: KotlinProjectConfigurator, isOnlyOneModule: Boolean): String { - return "as Kotlin (${configurator.presentableText}) module${if(!isOnlyOneModule) "s" else ""}" - } + private fun getLink(configurator: KotlinProjectConfigurator, isOnlyOneModule: Boolean): String = + "as Kotlin (${configurator.presentableText}) module${if (!isOnlyOneModule) "s" else ""}" } } diff --git a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/facet/FrameworkLibraryValidatorWithDynamicDescription.kt b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/facet/FrameworkLibraryValidatorWithDynamicDescription.kt index 29ec77722e4..30c154e8eaf 100644 --- a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/facet/FrameworkLibraryValidatorWithDynamicDescription.kt +++ b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/facet/FrameworkLibraryValidatorWithDynamicDescription.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.facet @@ -34,10 +23,10 @@ import javax.swing.JComponent // Based on com.intellij.facet.impl.ui.libraries.FrameworkLibraryValidatorImpl class FrameworkLibraryValidatorWithDynamicDescription( - private val context: LibrariesValidatorContext, - private val validatorsManager: FacetValidatorsManager, - private val libraryCategoryName: String, - private val getPlatform: () -> TargetPlatform? + private val context: LibrariesValidatorContext, + private val validatorsManager: FacetValidatorsManager, + private val libraryCategoryName: String, + private val getPlatform: () -> TargetPlatform? ) : FrameworkLibraryValidator() { private val IdePlatformKind<*>.libraryDescription: CustomLibraryDescription? get() = this.tooling.getLibraryDescription(context.module.project) @@ -47,24 +36,25 @@ class FrameworkLibraryValidatorWithDynamicDescription( if (platform.isCommon) return true if (KotlinVersionInfoProvider.EP_NAME.extensions.any { - it.getLibraryVersions(context.module, platform, context.rootModel).isNotEmpty() - }) return true + it.getLibraryVersions(context.module, platform, context.rootModel).isNotEmpty() + } + ) return true val libraryDescription = platform.libraryDescription ?: return true val libraryKinds = libraryDescription.suitableLibraryKinds var found = false val presentationManager = LibraryPresentationManager.getInstance() context.rootModel - .orderEntries() - .using(context.modulesProvider) - .recursively() - .librariesOnly() - .forEachLibrary { library -> - if (presentationManager.isLibraryOfKind(library, context.librariesContainer, libraryKinds)) { - found = true - } - !found + .orderEntries() + .using(context.modulesProvider) + .recursively() + .librariesOnly() + .forEachLibrary { library -> + if (presentationManager.isLibraryOfKind(library, context.librariesContainer, libraryKinds)) { + found = true } + !found + } return found } @@ -87,18 +77,20 @@ class FrameworkLibraryValidatorWithDynamicDescription( } return ValidationResult( - IdeBundle.message("label.missed.libraries.text", libraryCategoryName), - LibrariesQuickFix(targetPlatform.idePlatformKind.libraryDescription!!) + IdeBundle.message("label.missed.libraries.text", libraryCategoryName), + LibrariesQuickFix(targetPlatform.idePlatformKind.libraryDescription!!) ) } private inner class LibrariesQuickFix( - private val myDescription: CustomLibraryDescription + private val myDescription: CustomLibraryDescription ) : FacetConfigurationQuickFix(IdeBundle.message("button.fix")) { override fun run(place: JComponent) { - val dialog = AddCustomLibraryDialog.createDialog(myDescription, context.librariesContainer, - context.module, context.modifiableRootModel, - null) + val dialog = AddCustomLibraryDialog.createDialog( + myDescription, context.librariesContainer, + context.module, context.modifiableRootModel, + null + ) dialog.show() validatorsManager.validate() } diff --git a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/facet/KotlinLibraryValidatorCreator.kt b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/facet/KotlinLibraryValidatorCreator.kt index 93fb850ae6d..16b43a98103 100644 --- a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/facet/KotlinLibraryValidatorCreator.kt +++ b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/facet/KotlinLibraryValidatorCreator.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.facet @@ -23,11 +12,13 @@ import com.intellij.facet.ui.FacetValidatorsManager import org.jetbrains.kotlin.idea.facet.KotlinFacetEditorGeneralTab.EditorComponent class KotlinLibraryValidatorCreator : KotlinFacetValidatorCreator() { - override fun create(editor: EditorComponent, validatorsManager: FacetValidatorsManager, editorContext: FacetEditorContext): FacetEditorValidator { - return FrameworkLibraryValidatorWithDynamicDescription( - DelegatingLibrariesValidatorContext(editorContext), - validatorsManager, - "kotlin" - ) { editor.getChosenPlatform() } - } + override fun create( + editor: EditorComponent, + validatorsManager: FacetValidatorsManager, + editorContext: FacetEditorContext + ): FacetEditorValidator = FrameworkLibraryValidatorWithDynamicDescription( + DelegatingLibrariesValidatorContext(editorContext), + validatorsManager, + "kotlin" + ) { editor.getChosenPlatform() } } \ No newline at end of file diff --git a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/filters/KotlinExceptionFilter.kt b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/filters/KotlinExceptionFilter.kt index 4b707103b18..1c8d7193432 100644 --- a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/filters/KotlinExceptionFilter.kt +++ b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/filters/KotlinExceptionFilter.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.filters @@ -77,7 +66,8 @@ class KotlinExceptionFilter(private val searchScope: GlobalSearchScope) : Filter // File can't be found by class name and file name: this can happen when smap info is already applied. // Default filter favours looking for file from class name and that can lead to wrong navigation to inline fun call file and // line from inline function definition. - val defaultLinkFileNames = defaultResult.resultItems.mapNotNullTo(HashSet()) { (it as? FileHyperlinkInfo)?.descriptor?.file?.name } + val defaultLinkFileNames = + defaultResult.resultItems.mapNotNullTo(HashSet()) { (it as? FileHyperlinkInfo)?.descriptor?.file?.name } if (!defaultLinkFileNames.contains(fileName)) { val filesByName = FilenameIndex.getFilesByName(project, fileName, searchScope).mapNotNullTo(HashSet()) { if (!it.isValid) return@mapNotNullTo null @@ -87,8 +77,7 @@ class KotlinExceptionFilter(private val searchScope: GlobalSearchScope) : Filter if (filesByName.isNotEmpty()) { return if (filesByName.size > 1) { HyperlinkInfoFactoryImpl.getInstance().createMultipleFilesHyperlinkInfo(filesByName.toList(), lineNumber, project) - } - else { + } else { OpenFileHyperlinkInfo(project, filesByName.first(), lineNumber) } } @@ -116,11 +105,14 @@ class KotlinExceptionFilter(private val searchScope: GlobalSearchScope) : Filter val inlineInfos = arrayListOf() val (inlineFunctionBodyFile, inlineFunctionBodyLine) = - mapStacktraceLineToSource(smapData, line, project, SourceLineKind.EXECUTED_LINE, searchScope) ?: return null + mapStacktraceLineToSource(smapData, line, project, SourceLineKind.EXECUTED_LINE, searchScope) ?: return null - inlineInfos.add(InlineFunctionHyperLinkInfo.InlineInfo.InlineFunctionBodyInfo( + inlineInfos.add( + InlineFunctionHyperLinkInfo.InlineInfo.InlineFunctionBodyInfo( inlineFunctionBodyFile.virtualFile, - inlineFunctionBodyLine)) + inlineFunctionBodyLine + ) + ) val inlineFunCallInfo = mapStacktraceLineToSource(smapData, line, project, SourceLineKind.CALL_LINE, searchScope) if (inlineFunCallInfo != null) { diff --git a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/framework/CommonStandardLibraryDescription.kt b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/framework/CommonStandardLibraryDescription.kt index 018deb4e012..228251c097d 100644 --- a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/framework/CommonStandardLibraryDescription.kt +++ b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/framework/CommonStandardLibraryDescription.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.framework @@ -20,8 +9,8 @@ import com.intellij.openapi.project.Project import com.intellij.openapi.roots.libraries.LibraryKind class CommonStandardLibraryDescription(project: Project?) : CustomLibraryDescriptorWithDeferredConfig( - // TODO: KotlinCommonModuleConfigurator - project, "common", LIBRARY_NAME, DIALOG_TITLE, LIBRARY_CAPTION, KOTLIN_COMMON_STDLIB_KIND, SUITABLE_LIBRARY_KINDS + // TODO: KotlinCommonModuleConfigurator + project, "common", LIBRARY_NAME, DIALOG_TITLE, LIBRARY_CAPTION, KOTLIN_COMMON_STDLIB_KIND, SUITABLE_LIBRARY_KINDS ) { companion object { val KOTLIN_COMMON_STDLIB_KIND = LibraryKind.create("kotlin-stdlib-common") diff --git a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/framework/CustomLibraryDescriptorWithDeferredConfig.kt b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/framework/CustomLibraryDescriptorWithDeferredConfig.kt index c366f15a90f..ae9ab9b1a89 100644 --- a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/framework/CustomLibraryDescriptorWithDeferredConfig.kt +++ b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/framework/CustomLibraryDescriptorWithDeferredConfig.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.framework @@ -53,15 +42,14 @@ import javax.swing.JComponent /** * @param project null when project doesn't exist yet (called from project wizard) */ -abstract class CustomLibraryDescriptorWithDeferredConfig -( - val project: Project?, - private val configuratorName: String, - private val libraryName: String, - private val dialogTitle: String, - private val modulesSeparatorCaption: String, - private val libraryKind: LibraryKind, - private val suitableLibraryKinds: Set +abstract class CustomLibraryDescriptorWithDeferredConfig( + val project: Project?, + private val configuratorName: String, + private val libraryName: String, + private val dialogTitle: String, + private val modulesSeparatorCaption: String, + private val libraryKind: LibraryKind, + private val suitableLibraryKinds: Set ) : CustomLibraryDescription() { private val projectBaseDir: VirtualFile? = project?.baseDir @@ -113,8 +101,7 @@ abstract class CustomLibraryDescriptorWithDeferredConfig } collector.showNotification() - } - finally { + } finally { model.commit() } } @@ -174,13 +161,11 @@ abstract class CustomLibraryDescriptorWithDeferredConfig } if (jarDescriptor.orderRootType == OrderRootType.SOURCES) { librarySourceFiles.add(destination) - } - else { + } else { libraryFiles.add(destination) } } - } - else { + } else { val dialog = CreateLibraryDialog(defaultPathToJarFile, dialogTitle, modulesSeparatorCaption) dialog.show() @@ -196,8 +181,7 @@ abstract class CustomLibraryDescriptorWithDeferredConfig for (jarDescriptor in jarDescriptors) { if (jarDescriptor.orderRootType == OrderRootType.SOURCES) { librarySourceFiles.add(jarDescriptor.getPathInPlugin()) - } - else { + } else { libraryFiles.add(jarDescriptor.getPathInPlugin()) } } @@ -208,25 +192,24 @@ abstract class CustomLibraryDescriptorWithDeferredConfig private val configurator: KotlinWithLibraryConfigurator get() = getConfiguratorByName(configuratorName) as KotlinWithLibraryConfigurator? - ?: error("Configurator with name ${configuratorName} should exists") + ?: error("Configurator with name $configuratorName should exists") // Implements an API added in IDEA 16 override fun createNewLibraryWithDefaultSettings(contextDirectory: VirtualFile?): NewLibraryConfiguration? { return createConfigurationFromPluginPaths() } - fun createConfigurationFromPluginPaths() = - createConfiguration(collectPathsInPlugin(OrderRootType.CLASSES), - collectPathsInPlugin(OrderRootType.SOURCES)) + fun createConfigurationFromPluginPaths() = createConfiguration( + collectPathsInPlugin(OrderRootType.CLASSES), + collectPathsInPlugin(OrderRootType.SOURCES) + ) - private fun collectPathsInPlugin(rootType: OrderRootType): List { - return configurator.getLibraryJarDescriptors(null) - .filter { it.orderRootType == rootType } - .map { it.getPathInPlugin() } - } + private fun collectPathsInPlugin(rootType: OrderRootType): List = configurator.getLibraryJarDescriptors(null) + .filter { it.orderRootType == rootType } + .map { it.getPathInPlugin() } - protected fun createConfiguration(libraryFiles: List, librarySourceFiles: List): NewLibraryConfiguration { - return object : NewLibraryConfiguration(libraryName, configurator.libraryType, DummyLibraryProperties.INSTANCE) { + protected fun createConfiguration(libraryFiles: List, librarySourceFiles: List): NewLibraryConfiguration = + object : NewLibraryConfiguration(libraryName, configurator.libraryType, DummyLibraryProperties.INSTANCE) { override fun addRoots(editor: LibraryEditor) { for (libraryFile in libraryFiles) { editor.addRoot(VfsUtil.getUrlForLibraryRoot(libraryFile), OrderRootType.CLASSES) @@ -236,7 +219,6 @@ abstract class CustomLibraryDescriptorWithDeferredConfig } } } - } companion object { diff --git a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/framework/JSLibraryStdDescription.kt b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/framework/JSLibraryStdDescription.kt index 442163cade9..0931583d5cc 100644 --- a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/framework/JSLibraryStdDescription.kt +++ b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/framework/JSLibraryStdDescription.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.framework @@ -24,15 +13,15 @@ import org.jetbrains.kotlin.idea.configuration.KotlinJsModuleConfigurator /** * @param project null when project doesn't exist yet (called from project wizard) */ -class JSLibraryStdDescription(project: Project?) : - CustomLibraryDescriptorWithDeferredConfig( - project, - KotlinJsModuleConfigurator.NAME, - LIBRARY_NAME, - DIALOG_TITLE, - LIBRARY_CAPTION, - JSLibraryKind, - SUITABLE_LIBRARY_KINDS) { +class JSLibraryStdDescription(project: Project?) : CustomLibraryDescriptorWithDeferredConfig( + project, + KotlinJsModuleConfigurator.NAME, + LIBRARY_NAME, + DIALOG_TITLE, + LIBRARY_CAPTION, + JSLibraryKind, + SUITABLE_LIBRARY_KINDS +) { @TestOnly fun createNewLibraryForTests(): NewLibraryConfiguration { diff --git a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/framework/JSLibraryType.kt b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/framework/JSLibraryType.kt index 1a0a5e55cf4..c22dbe34aae 100644 --- a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/framework/JSLibraryType.kt +++ b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/framework/JSLibraryType.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.framework @@ -39,13 +28,15 @@ class JSLibraryType : LibraryType(JSLibraryKind) { override fun getCreateActionName() = "Kotlin/JS" - override fun createNewLibrary(parentComponent: JComponent, - contextDirectory: VirtualFile?, - project: Project): NewLibraryConfiguration? { - return LibraryTypeService.getInstance().createLibraryFromFiles(RootsComponentDescriptor, - parentComponent, contextDirectory, this, - project) - } + override fun createNewLibrary( + parentComponent: JComponent, + contextDirectory: VirtualFile?, + project: Project + ): NewLibraryConfiguration? = LibraryTypeService.getInstance().createLibraryFromFiles( + RootsComponentDescriptor, + parentComponent, contextDirectory, this, + project + ) override fun getIcon(properties: DummyLibraryProperties?) = KotlinIcons.JS @@ -69,12 +60,10 @@ class JSLibraryType : LibraryType(JSLibraryKind) { override fun getRootTypes() = arrayOf(OrderRootType.CLASSES, OrderRootType.SOURCES) - override fun getRootDetectors(): List { - return arrayListOf( - JSRootFilter, - FileTypeBasedRootFilter(OrderRootType.SOURCES, false, KotlinFileType.INSTANCE, "sources") - ) - } + override fun getRootDetectors(): List = arrayListOf( + JSRootFilter, + FileTypeBasedRootFilter(OrderRootType.SOURCES, false, KotlinFileType.INSTANCE, "sources") + ) } object JSRootFilter : FileTypeBasedRootFilter(OrderRootType.CLASSES, false, PlainTextFileType.INSTANCE, "JS files") { diff --git a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/framework/JavaFrameworkSupportProvider.kt b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/framework/JavaFrameworkSupportProvider.kt index 87ce2faa004..9ffd29e80ea 100644 --- a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/framework/JavaFrameworkSupportProvider.kt +++ b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/framework/JavaFrameworkSupportProvider.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -41,13 +41,15 @@ class JavaFrameworkSupportProvider : FrameworkSupportInModuleProvider() { override fun isOnlyLibraryAdded(): Boolean = true override fun addSupport( - module: Module, - rootModel: ModifiableRootModel, - modifiableModelsProvider: ModifiableModelsProvider) { + module: Module, + rootModel: ModifiableRootModel, + modifiableModelsProvider: ModifiableModelsProvider + ) { FrameworksCompatibilityUtils.suggestRemoveIncompatibleFramework( - rootModel, - JSLibraryStdDescription.SUITABLE_LIBRARY_KINDS, - "Kotlin/\u200BJS") + rootModel, + JSLibraryStdDescription.SUITABLE_LIBRARY_KINDS, + "Kotlin/\u200BJS" + ) description!!.finishLibConfiguration(module, rootModel, false) diff --git a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/framework/JavaRuntimeLibraryDescription.kt b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/framework/JavaRuntimeLibraryDescription.kt index c57bdf8b400..69d4439c5df 100644 --- a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/framework/JavaRuntimeLibraryDescription.kt +++ b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/framework/JavaRuntimeLibraryDescription.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.framework @@ -27,14 +16,15 @@ import org.jetbrains.kotlin.idea.versions.getDefaultJvmTarget /** * @param project null when project doesn't exist yet (called from project wizard) */ -class JavaRuntimeLibraryDescription(project: Project?) : - CustomLibraryDescriptorWithDeferredConfig(project, - KotlinJavaModuleConfigurator.NAME, - LIBRARY_NAME, - DIALOG_TITLE, - LIBRARY_CAPTION, - KOTLIN_JAVA_RUNTIME_KIND, - SUITABLE_LIBRARY_KINDS) { +class JavaRuntimeLibraryDescription(project: Project?) : CustomLibraryDescriptorWithDeferredConfig( + project, + KotlinJavaModuleConfigurator.NAME, + LIBRARY_NAME, + DIALOG_TITLE, + LIBRARY_CAPTION, + KOTLIN_JAVA_RUNTIME_KIND, + SUITABLE_LIBRARY_KINDS +) { override fun configureKotlinSettings(project: Project, sdk: Sdk?) { val defaultJvmTarget = getDefaultJvmTarget(sdk, bundledRuntimeVersion()) diff --git a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/framework/KotlinModuleBuilder.kt b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/framework/KotlinModuleBuilder.kt index aba4001fe1b..3fdaf7b3e17 100644 --- a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/framework/KotlinModuleBuilder.kt +++ b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/framework/KotlinModuleBuilder.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.framework @@ -24,10 +13,10 @@ import com.intellij.openapi.projectRoots.SdkTypeId import com.intellij.openapi.roots.ModifiableRootModel import com.intellij.openapi.roots.ui.configuration.ModulesProvider import org.jetbrains.kotlin.idea.roots.migrateNonJvmSourceFolders -import org.jetbrains.kotlin.platform.TargetPlatform -import org.jetbrains.kotlin.platform.jvm.isJvm import org.jetbrains.kotlin.idea.statistics.FUSEventGroups import org.jetbrains.kotlin.idea.statistics.KotlinFUSLogger +import org.jetbrains.kotlin.platform.TargetPlatform +import org.jetbrains.kotlin.platform.jvm.isJvm import javax.swing.Icon class KotlinModuleBuilder( @@ -51,7 +40,7 @@ class KotlinModuleBuilder( return KotlinModuleSettingStep(targetPlatform, this, settingsStep, wizardContext) } - override fun isSuitableSdkType(sdkType: SdkTypeId?) = when { + override fun isSuitableSdkType(sdkType: SdkTypeId?) = when { targetPlatform.isJvm() -> super.isSuitableSdkType(sdkType) else -> sdkType is KotlinSdkType } diff --git a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/injection/KotlinLanguageInjectionSupport.kt b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/injection/KotlinLanguageInjectionSupport.kt index 9cdc6b40c9a..d452252da31 100644 --- a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/injection/KotlinLanguageInjectionSupport.kt +++ b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/injection/KotlinLanguageInjectionSupport.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.injection @@ -40,7 +29,8 @@ import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.siblings import org.jetbrains.kotlin.psi.psiUtil.startOffset -@NonNls val KOTLIN_SUPPORT_ID = "kotlin" +@NonNls +val KOTLIN_SUPPORT_ID = "kotlin" class KotlinLanguageInjectionSupport : AbstractLanguageInjectionSupport() { override fun getId(): String = KOTLIN_SUPPORT_ID @@ -117,7 +107,8 @@ class KotlinLanguageInjectionSupport : AbstractLanguageInjectionSupport() { } private fun extractStringArgumentByName(annotationEntry: KtAnnotationEntry, name: String): String? { - val namedArgument: ValueArgument = annotationEntry.valueArguments.firstOrNull { it.getArgumentName()?.asName?.asString() == name } ?: return null + val namedArgument: ValueArgument = + annotationEntry.valueArguments.firstOrNull { it.getArgumentName()?.asName?.asString() == name } ?: return null return extractStringValue(namedArgument) } @@ -152,21 +143,19 @@ private fun canInjectWithAnnotation(host: PsiElement): Boolean { return javaPsiFacade.findClass(AnnotationUtil.LANGUAGE, GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module)) != null } -private fun findElementToInjectWithAnnotation(host: KtElement): KtModifierListOwner? { - return PsiTreeUtil.getParentOfType( - host, - KtModifierListOwner::class.java, - false, /* strict */ - KtBlockExpression::class.java, KtParameterList::class.java, KtTypeParameterList::class.java /* Stop at */ - ) -} +private fun findElementToInjectWithAnnotation(host: KtElement): KtModifierListOwner? = PsiTreeUtil.getParentOfType( + host, + KtModifierListOwner::class.java, + false, /* strict */ + KtBlockExpression::class.java, KtParameterList::class.java, KtTypeParameterList::class.java /* Stop at */ +) private fun findElementToInjectWithComment(host: KtElement): KtExpression? { val parentBlockExpression = PsiTreeUtil.getParentOfType( - host, - KtBlockExpression::class.java, - true, /* strict */ - KtDeclaration::class.java /* Stop at */ + host, + KtBlockExpression::class.java, + true, /* strict */ + KtDeclaration::class.java /* Stop at */ ) ?: return null return parentBlockExpression.statements.firstOrNull { statement -> @@ -191,9 +180,7 @@ private fun addInjectionInstructionInCode(language: Language, host: PsiLanguageI // Find the place where injection can be done with one-line comment val commentBeforeAnchor: PsiElement = - modifierListOwner?.firstNonCommentChild() ?: - findElementToInjectWithComment(ktHost) ?: - return false + modifierListOwner?.firstNonCommentChild() ?: findElementToInjectWithComment(ktHost) ?: return false val psiFactory = KtPsiFactory(project) val injectComment = psiFactory.createComment("//language=" + language.id) @@ -217,18 +204,16 @@ private fun checkIsValidPlaceForInjectionWithLineComment(statement: KtExpression if (hostStart - statementStartOffset > 2) { // ... there's no non-empty valid host in between comment and e2 if (prevWalker(host, statement).asSequence().takeWhile { it != null }.any { - it is PsiLanguageInjectionHost && it.isValidHost && !StringUtil.isEmptyOrSpaces(it.text) - }) { - return false - } + it is PsiLanguageInjectionHost && it.isValidHost && !StringUtil.isEmptyOrSpaces(it.text) + } + ) return false } return true } -private fun PsiElement.firstNonCommentChild(): PsiElement? { - return firstChild.siblings().dropWhile { it is PsiComment || it is PsiWhiteSpace }.firstOrNull() -} +private fun PsiElement.firstNonCommentChild(): PsiElement? = + firstChild.siblings().dropWhile { it is PsiComment || it is PsiWhiteSpace }.firstOrNull() // Based on InjectorUtils.prevWalker private fun prevWalker(element: PsiElement, scope: PsiElement): Iterator { @@ -243,8 +228,7 @@ private fun prevWalker(element: PsiElement, scope: PsiElement): Iterator) : KotlinQuickFixAction(element) { +abstract class AddKotlinLibQuickFix( + element: KtElement, + val libraryJarDescriptors: List +) : KotlinQuickFixAction(element) { protected abstract fun getLibraryDescriptor(module: Module): MavenExternalLibraryDescriptor class MavenExternalLibraryDescriptor(groupId: String, artifactId: String, version: String) : - ExternalLibraryDescriptor(groupId, artifactId, version, version) { + ExternalLibraryDescriptor(groupId, artifactId, version, version) { override fun getLibraryClassesRoots(): List = emptyList() } diff --git a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/inspections/api/IncompatibleAPIInspection.kt b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/inspections/api/IncompatibleAPIInspection.kt index 3e840dd5f41..97961650be7 100644 --- a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/inspections/api/IncompatibleAPIInspection.kt +++ b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/inspections/api/IncompatibleAPIInspection.kt @@ -1,5 +1,5 @@ /* - * Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -67,7 +67,7 @@ class IncompatibleAPIInspection : LocalInspectionTool(), CustomSuppressableInspe element.language == JavaLanguage.INSTANCE -> { val key = HighlightDisplayKey.find(shortName) - ?: throw AssertionError("HighlightDisplayKey.find($shortName) is null. Inspection: $javaClass") + ?: throw AssertionError("HighlightDisplayKey.find($shortName) is null. Inspection: $javaClass") return SuppressManager.getInstance().createSuppressActions(key) } diff --git a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/internal/KotlinBytecodeToolWindow.kt b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/internal/KotlinBytecodeToolWindow.kt index 69a916ed445..8b3a56287e0 100644 --- a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/internal/KotlinBytecodeToolWindow.kt +++ b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/internal/KotlinBytecodeToolWindow.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -29,11 +29,7 @@ import org.jetbrains.kotlin.codegen.ClassBuilderFactories import org.jetbrains.kotlin.codegen.DefaultCodegenFactory import org.jetbrains.kotlin.codegen.KotlinCodegenFacade import org.jetbrains.kotlin.codegen.state.GenerationState -import org.jetbrains.kotlin.config.CommonConfigurationKeys -import org.jetbrains.kotlin.config.CompilerConfiguration -import org.jetbrains.kotlin.config.JVMConfigurationKeys -import org.jetbrains.kotlin.config.JvmTarget -import org.jetbrains.kotlin.config.languageVersionSettings +import org.jetbrains.kotlin.config.* import org.jetbrains.kotlin.diagnostics.rendering.DefaultErrorMessages import org.jetbrains.kotlin.idea.debugger.DebuggerUtils import org.jetbrains.kotlin.idea.project.languageVersionSettings @@ -245,7 +241,7 @@ class KotlinBytecodeToolWindow(private val myProject: Project, private val toolW val state: GenerationState try { state = compileSingleFile(ktFile, configuration) - ?: return BytecodeGenerationResult.Error("Cannot compile ${ktFile.name} to bytecode.") + ?: return BytecodeGenerationResult.Error("Cannot compile ${ktFile.name} to bytecode.") } catch (e: ProcessCanceledException) { throw e } catch (e: Exception) { @@ -289,7 +285,7 @@ class KotlinBytecodeToolWindow(private val myProject: Project, private val toolW val resolutionFacade = KotlinCacheService.getInstance(ktFile.project) .getResolutionFacadeByFile(ktFile, JvmPlatforms.unspecifiedJvmPlatform) - ?: return null + ?: return null val bindingContextForFile = resolutionFacade.analyzeWithAllCompilerChecks(listOf(ktFile)).bindingContext @@ -319,9 +315,9 @@ class KotlinBytecodeToolWindow(private val myProject: Project, private val toolW } val state = GenerationState.Builder( - ktFile.project, ClassBuilderFactories.TEST, resolutionFacade.moduleDescriptor, bindingContext, toProcess, - configuration - ) + ktFile.project, ClassBuilderFactories.TEST, resolutionFacade.moduleDescriptor, bindingContext, toProcess, + configuration + ) .generateDeclaredClassFilter(generateClassFilter) .codegenFactory( if (configuration.getBoolean(JVMConfigurationKeys.IR)) diff --git a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/properties/KotlinPropertiesReferenceContributor.kt b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/properties/KotlinPropertiesReferenceContributor.kt index dd101369e2e..1d8a13c4cb0 100644 --- a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/properties/KotlinPropertiesReferenceContributor.kt +++ b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/properties/KotlinPropertiesReferenceContributor.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.properties @@ -24,13 +13,13 @@ import org.jetbrains.kotlin.psi.KtStringTemplateExpression class KotlinPropertiesReferenceContributor : PsiReferenceContributor() { override fun registerReferenceProviders(registrar: PsiReferenceRegistrar) { registrar.registerReferenceProvider( - PlatformPatterns.psiElement(KtStringTemplateExpression::class.java), - KotlinPropertyKeyReferenceProvider + PlatformPatterns.psiElement(KtStringTemplateExpression::class.java), + KotlinPropertyKeyReferenceProvider ) registrar.registerReferenceProvider( - PlatformPatterns.psiElement(KtStringTemplateExpression::class.java), - KotlinResourceBundleNameReferenceProvider + PlatformPatterns.psiElement(KtStringTemplateExpression::class.java), + KotlinResourceBundleNameReferenceProvider ) } } \ No newline at end of file diff --git a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/properties/referenceProviders.kt b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/properties/referenceProviders.kt index 15c1f1c0f3c..89436fcaac8 100644 --- a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/properties/referenceProviders.kt +++ b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/properties/referenceProviders.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.properties @@ -66,13 +55,11 @@ private fun KtExpression.getBundleNameByContext(): String? { (parent as? KtProperty)?.let { return it.resolveToDescriptorIfAny()?.getBundleNameByAnnotation() } val bindingContext = expression.analyze(BodyResolveMode.PARTIAL) - val resolvedCall = - if (parent is KtQualifiedExpression && expression == parent.receiverExpression) { - parent.selectorExpression.getResolvedCall(bindingContext) - } - else { - expression.getParentResolvedCall(bindingContext) - } ?: return null + val resolvedCall = if (parent is KtQualifiedExpression && expression == parent.receiverExpression) { + parent.selectorExpression.getResolvedCall(bindingContext) + } else { + expression.getParentResolvedCall(bindingContext) + } ?: return null val callable = resolvedCall.resultingDescriptor if ((resolvedCall.extensionReceiver as? ExpressionReceiver)?.expression == expression) { @@ -80,9 +67,9 @@ private fun KtExpression.getBundleNameByContext(): String? { } return resolvedCall.valueArguments.entries - .singleOrNull { it.value.arguments.any { it.getArgumentExpression() == expression } } - ?.key - ?.getBundleNameByAnnotation() + .singleOrNull { it.value.arguments.any { it.getArgumentExpression() == expression } } + ?.key + ?.getBundleNameByAnnotation() } private fun KtAnnotationEntry.getPropertyKeyResolvedCall(): ResolvedCall<*>? { @@ -93,8 +80,7 @@ private fun KtAnnotationEntry.getPropertyKeyResolvedCall(): ResolvedCall<*>? { } private fun KtStringTemplateExpression.isBundleName(): Boolean { - val parent = KtPsiUtil.safeDeparenthesize(this).parent - when (parent) { + when (val parent = KtPsiUtil.safeDeparenthesize(this).parent) { is KtValueArgument -> { val resolvedCall = parent.getStrictParentOfType()?.getPropertyKeyResolvedCall() ?: return false val valueParameter = (resolvedCall.getArgumentMapping(parent) as? ArgumentMatch)?.valueParameter ?: return false @@ -106,11 +92,12 @@ private fun KtStringTemplateExpression.isBundleName(): Boolean { is KtProperty -> { val contexts = (parent.useScope as? LocalSearchScope)?.scope ?: arrayOf(parent.containingFile) return contexts.any { - it.anyDescendantOfType f@ { entry -> + it.anyDescendantOfType f@{ entry -> if (!entry.valueArguments.any { it.getArgumentName()?.asName == PROPERTY_KEY_RESOURCE_BUNDLE }) return@f false val resolvedCall = entry.getPropertyKeyResolvedCall() ?: return@f false - val parameter = resolvedCall.resultingDescriptor.valueParameters.singleOrNull { it.name == PROPERTY_KEY_RESOURCE_BUNDLE } - ?: return@f false + val parameter = + resolvedCall.resultingDescriptor.valueParameters.singleOrNull { it.name == PROPERTY_KEY_RESOURCE_BUNDLE } + ?: return@f false val valueArgument = resolvedCall.valueArguments[parameter] as? ExpressionValueArgument ?: return@f false val bundleNameExpression = valueArgument.valueArgument?.getArgumentExpression() ?: return@f false bundleNameExpression is KtSimpleNameExpression && bundleNameExpression.mainReference.resolve() == parent diff --git a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/quickfix/EnableUnsupportedFeatureFix.kt b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/quickfix/EnableUnsupportedFeatureFix.kt index 7199dfb8526..86ddef88116 100644 --- a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/quickfix/EnableUnsupportedFeatureFix.kt +++ b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/quickfix/EnableUnsupportedFeatureFix.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -33,11 +33,12 @@ import org.jetbrains.kotlin.idea.versions.updateLibraries import org.jetbrains.kotlin.psi.KtFile sealed class EnableUnsupportedFeatureFix( - element: PsiElement, - protected val feature: LanguageFeature, - protected val apiVersionOnly: Boolean + element: PsiElement, + protected val feature: LanguageFeature, + protected val apiVersionOnly: Boolean ) : KotlinQuickFixAction(element) { - class InModule(element: PsiElement, feature: LanguageFeature, apiVersionOnly: Boolean) : EnableUnsupportedFeatureFix(element, feature, apiVersionOnly) { + class InModule(element: PsiElement, feature: LanguageFeature, apiVersionOnly: Boolean) : + EnableUnsupportedFeatureFix(element, feature, apiVersionOnly) { override fun getFamilyName() = "Increase module " + if (apiVersionOnly) "API version" else "language version" override fun getText() = if (apiVersionOnly) @@ -58,18 +59,17 @@ sealed class EnableUnsupportedFeatureFix( val forTests = ModuleRootManager.getInstance(module).fileIndex.isInTestSourceContentKotlinAware(file.virtualFile) findApplicableConfigurator(module).updateLanguageVersion( - module, - if (apiVersionOnly) null else feature.sinceVersion!!.versionString, - targetApiLevel, - feature.sinceApiVersion, - forTests + module, + if (apiVersionOnly) null else feature.sinceVersion!!.versionString, + targetApiLevel, + feature.sinceApiVersion, + forTests ) } } - class InProject(element: PsiElement, feature: LanguageFeature, apiVersionOnly: Boolean) - : EnableUnsupportedFeatureFix(element, feature, apiVersionOnly) - { + class InProject(element: PsiElement, feature: LanguageFeature, apiVersionOnly: Boolean) : + EnableUnsupportedFeatureFix(element, feature, apiVersionOnly) { override fun getFamilyName() = "Increase project " + if (apiVersionOnly) "API version" else "language version" override fun getText() = if (apiVersionOnly) @@ -101,7 +101,7 @@ sealed class EnableUnsupportedFeatureFix( val sinceVersion = feature.sinceVersion ?: return null val apiVersionOnly = sinceVersion <= languageFeatureSettings.languageVersion && - feature.sinceApiVersion > languageFeatureSettings.apiVersion + feature.sinceApiVersion > languageFeatureSettings.apiVersion if (!sinceVersion.isStable && !ApplicationManager.getApplication().isInternal) { return null @@ -110,7 +110,11 @@ sealed class EnableUnsupportedFeatureFix( val module = ModuleUtilCore.findModuleForPsiElement(diagnostic.psiElement) ?: return null if (module.getBuildSystemType() == BuildSystemType.JPS) { val facetSettings = KotlinFacet.get(module)?.configuration?.settings - if (facetSettings == null || facetSettings.useProjectSettings) return InProject(diagnostic.psiElement, feature, apiVersionOnly) + if (facetSettings == null || facetSettings.useProjectSettings) return InProject( + diagnostic.psiElement, + feature, + apiVersionOnly + ) } return InModule(diagnostic.psiElement, feature, apiVersionOnly) } @@ -126,18 +130,21 @@ fun checkUpdateRuntime(project: Project, requiredVersion: ApiVersion): Boolean { } if (modulesWithOutdatedRuntime.isNotEmpty()) { if (!askUpdateRuntime(project, requiredVersion, - modulesWithOutdatedRuntime.mapNotNull { findKotlinRuntimeLibrary(it) })) return false + modulesWithOutdatedRuntime.mapNotNull { findKotlinRuntimeLibrary(it) }) + ) return false } return true } fun askUpdateRuntime(project: Project, requiredVersion: ApiVersion, librariesToUpdate: List): Boolean { if (!ApplicationManager.getApplication().isUnitTestMode) { - val rc = Messages.showOkCancelDialog(project, - "This language feature requires version $requiredVersion or later of the Kotlin runtime library. " + - "Would you like to update the runtime library in your project?", - "Update Runtime Library", - Messages.getQuestionIcon()) + val rc = Messages.showOkCancelDialog( + project, + "This language feature requires version $requiredVersion or later of the Kotlin runtime library. " + + "Would you like to update the runtime library in your project?", + "Update Runtime Library", + Messages.getQuestionIcon() + ) if (rc != Messages.OK) return false } diff --git a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/run/KotlinConsoleFilterProvider.kt b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/run/KotlinConsoleFilterProvider.kt index e574720e2ac..18fdc7a6148 100644 --- a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/run/KotlinConsoleFilterProvider.kt +++ b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/run/KotlinConsoleFilterProvider.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.run @@ -43,8 +32,8 @@ class KotlinConsoleFilter(val project: Project, val scope: GlobalSearchScope) : val pathEnd = messageSuffix.groups[1]!!.range.last + 1 val pathWithPrefix = line.substring(0, pathEnd) val pathStart = pathWithPrefix.indexOf(":\\").takeIf { it >= 0 }?.minus(1) - ?: pathWithPrefix.indexOf("/").takeIf { it >= 0 } - ?: return null + ?: pathWithPrefix.indexOf("/").takeIf { it >= 0 } + ?: return null val path = pathWithPrefix.substring(pathStart) val lineNumber = Integer.parseInt(messageSuffix.groupValues[2]) - 1 val column = Integer.parseInt(messageSuffix.groupValues[3]) - 1 diff --git a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/run/KotlinPatternConfigurationProducer.kt b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/run/KotlinPatternConfigurationProducer.kt index 8ba2b36e7fe..c70f07db87b 100644 --- a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/run/KotlinPatternConfigurationProducer.kt +++ b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/run/KotlinPatternConfigurationProducer.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.run @@ -34,18 +23,18 @@ class KotlinPatternConfigurationProducer : PatternConfigurationProducer() { } override fun setupConfigurationFromContext( - configuration: JUnitConfiguration, - context: ConfigurationContext, - sourceElement: Ref + configuration: JUnitConfiguration, + context: ConfigurationContext, + sourceElement: Ref ): Boolean { return super.setupConfigurationFromContext(configuration, context, sourceElement) } override fun collectTestMembers( - psiElements: Array, - checkAbstract: Boolean, - checkIsTest: Boolean, - collectingProcessor: PsiElementProcessor.CollectElements + psiElements: Array, + checkAbstract: Boolean, + checkIsTest: Boolean, + collectingProcessor: PsiElementProcessor.CollectElements ) { val adjustedElements = psiElements.mapNotNull { if (it is KtClassOrObject) it.toLightClass() else it }.toTypedArray() super.collectTestMembers(adjustedElements, checkAbstract, checkIsTest, collectingProcessor) @@ -53,7 +42,7 @@ class KotlinPatternConfigurationProducer : PatternConfigurationProducer() { override fun shouldReplace(self: ConfigurationFromContext, other: ConfigurationFromContext): Boolean { return other.isProducedBy(PatternConfigurationProducer::class.java) - || other.isProducedBy(TestClassConfigurationProducer::class.java) - || other.isProducedBy(KotlinJUnitRunConfigurationProducer::class.java) + || other.isProducedBy(TestClassConfigurationProducer::class.java) + || other.isProducedBy(KotlinJUnitRunConfigurationProducer::class.java) } } diff --git a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/run/script/standalone/KotlinStandaloneScriptRunConfiguration.kt b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/run/script/standalone/KotlinStandaloneScriptRunConfiguration.kt index 32fd280817b..4b03667bd94 100644 --- a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/run/script/standalone/KotlinStandaloneScriptRunConfiguration.kt +++ b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/run/script/standalone/KotlinStandaloneScriptRunConfiguration.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.run.script.standalone @@ -49,24 +38,32 @@ import java.io.File import java.util.* class KotlinStandaloneScriptRunConfiguration( - project: Project, - factory: ConfigurationFactory, - name: String? -) : KotlinRunConfiguration(name, JavaRunConfigurationModule(project, true), factory), CommonJavaRunConfigurationParameters, RefactoringListenerProvider { + project: Project, + factory: ConfigurationFactory, + name: String? +) : KotlinRunConfiguration(name, JavaRunConfigurationModule(project, true), factory), CommonJavaRunConfigurationParameters, + RefactoringListenerProvider { @JvmField var filePath: String? = null + @JvmField var vmParameters: String? = null + @JvmField var alternativeJrePath: String? = null + @JvmField var programParameters: String? = null + @JvmField var envs: MutableMap = LinkedHashMap() + @JvmField var passParentEnvs: Boolean = true + @JvmField var workingDirectory: String? = null + @JvmField var isAlternativeJrePathEnabled: Boolean = false @@ -105,13 +102,17 @@ class KotlinStandaloneScriptRunConfiguration( isAlternativeJrePathEnabled = enabled } - override fun getState(executor: Executor, environment: ExecutionEnvironment): RunProfileState = ScriptCommandLineState(environment, this) + override fun getState(executor: Executor, environment: ExecutionEnvironment): RunProfileState = + ScriptCommandLineState(environment, this) override fun suggestedName() = filePath?.substringAfterLast('/') override fun getConfigurationEditor(): SettingsEditor { val group = SettingsEditorGroup() - group.addEditor(ExecutionBundle.message("run.configuration.configuration.tab.title"), KotlinStandaloneScriptRunConfigurationEditor(project)) + group.addEditor( + ExecutionBundle.message("run.configuration.configuration.tab.title"), + KotlinStandaloneScriptRunConfigurationEditor(project) + ) JavaRunConfigurationExtensionManagerUtil.getInstance().appendEditors(this, group) return group } @@ -193,16 +194,16 @@ class KotlinStandaloneScriptRunConfiguration( } private class ScriptCommandLineState( - environment: ExecutionEnvironment, - configuration: KotlinStandaloneScriptRunConfiguration) : - BaseJavaApplicationCommandLineState(environment, configuration) { + environment: ExecutionEnvironment, + configuration: KotlinStandaloneScriptRunConfiguration +) : BaseJavaApplicationCommandLineState(environment, configuration) { override fun createJavaParameters(): JavaParameters? { val params = commonParameters() val filePath = configuration.filePath ?: throw CantRunException("Script file was not specified") - val scriptVFile = LocalFileSystem.getInstance().findFileByIoFile(File(filePath)) ?: - throw CantRunException("Script file was not found in project") + val scriptVFile = + LocalFileSystem.getInstance().findFileByIoFile(File(filePath)) ?: throw CantRunException("Script file was not found in project") params.classPath.add(PathUtil.kotlinPathsForIdeaPlugin.compilerPath) diff --git a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/run/script/standalone/KotlinStandaloneScriptRunConfigurationProducer.kt b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/run/script/standalone/KotlinStandaloneScriptRunConfigurationProducer.kt index 71019266948..eae161686b6 100644 --- a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/run/script/standalone/KotlinStandaloneScriptRunConfigurationProducer.kt +++ b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/run/script/standalone/KotlinStandaloneScriptRunConfigurationProducer.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.run.script.standalone @@ -24,11 +13,11 @@ import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.psiUtil.getParentOfType class KotlinStandaloneScriptRunConfigurationProducer : - RunConfigurationProducer(KotlinStandaloneScriptRunConfigurationType.instance) { + RunConfigurationProducer(KotlinStandaloneScriptRunConfigurationType.instance) { override fun setupConfigurationFromContext( - configuration: KotlinStandaloneScriptRunConfiguration, - context: ConfigurationContext, - sourceElement: Ref + configuration: KotlinStandaloneScriptRunConfiguration, + context: ConfigurationContext, + sourceElement: Ref ): Boolean { configuration.setupFilePath(pathFromContext(context) ?: return false) configuration.setGeneratedName() diff --git a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/run/script/standalone/KotlinStandaloneScriptRunConfigurationType.kt b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/run/script/standalone/KotlinStandaloneScriptRunConfigurationType.kt index 199423dfeec..9c7a1b6b50e 100644 --- a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/run/script/standalone/KotlinStandaloneScriptRunConfigurationType.kt +++ b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/run/script/standalone/KotlinStandaloneScriptRunConfigurationType.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.run.script.standalone @@ -21,10 +10,10 @@ import com.intellij.openapi.project.Project import org.jetbrains.kotlin.idea.KotlinIcons class KotlinStandaloneScriptRunConfigurationType : ConfigurationTypeBase( - "KotlinStandaloneScriptRunConfigurationType", - "Kotlin script", - "Run Kotlin script", - KotlinIcons.SMALL_LOGO + "KotlinStandaloneScriptRunConfigurationType", + "Kotlin script", + "Run Kotlin script", + KotlinIcons.SMALL_LOGO ) { init { addFactory(Factory(this)) diff --git a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/scratch/KtScratchFileCreationHelper.kt b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/scratch/KtScratchFileCreationHelper.kt index 5957345f143..489f5ce970c 100644 --- a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/scratch/KtScratchFileCreationHelper.kt +++ b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/scratch/KtScratchFileCreationHelper.kt @@ -1,5 +1,5 @@ /* - * Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -8,11 +8,11 @@ package org.jetbrains.kotlin.idea.scratch import com.intellij.ide.scratch.ScratchFileCreationHelper import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.project.Project -import org.jetbrains.kotlin.parsing.KotlinParserDefinition import org.jetbrains.kotlin.idea.statistics.FUSEventGroups import org.jetbrains.kotlin.idea.statistics.KotlinFUSLogger +import org.jetbrains.kotlin.parsing.KotlinParserDefinition -class KtScratchFileCreationHelper: ScratchFileCreationHelper() { +class KtScratchFileCreationHelper : ScratchFileCreationHelper() { override fun prepareText(project: Project, context: Context, dataContext: DataContext): Boolean { KotlinFUSLogger.log(FUSEventGroups.NewFileTemplate, "Kotlin Scratch") diff --git a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/scratch/actions/ScratchRunLineMarkerContributor.kt b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/scratch/actions/ScratchRunLineMarkerContributor.kt index b66051c61c7..680889927a1 100644 --- a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/scratch/actions/ScratchRunLineMarkerContributor.kt +++ b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/scratch/actions/ScratchRunLineMarkerContributor.kt @@ -1,6 +1,6 @@ /* - * Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license - * that can be found in the license/LICENSE.txt file. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.scratch.actions @@ -17,7 +17,10 @@ import com.intellij.psi.impl.source.tree.LeafPsiElement import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.idea.core.util.getLineCount import org.jetbrains.kotlin.idea.refactoring.getLineNumber -import org.jetbrains.kotlin.idea.scratch.* +import org.jetbrains.kotlin.idea.scratch.ScratchExpression +import org.jetbrains.kotlin.idea.scratch.getScratchFile +import org.jetbrains.kotlin.idea.scratch.isKotlinScratch +import org.jetbrains.kotlin.idea.scratch.isKotlinWorksheet import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.findDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.getParentOfType @@ -47,10 +50,9 @@ class ScratchRunLineMarkerContributor : RunLineMarkerContributor() { if (declaration is KtScript && element is PsiWhiteSpace) { val expression = getLastExecutedExpression(element) if (expression == null) { - if (element.getLineNumber() == element.containingFile.getLineCount() - || element.getLineNumber(false) == element.containingFile.getLineCount()) { - return Info(RunScratchFromHereAction()) - } + if (element.getLineNumber() == element.containingFile.getLineCount() || + element.getLineNumber(false) == element.containingFile.getLineCount() + ) return Info(RunScratchFromHereAction()) } } return null diff --git a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/scratch/output/ScratchOutputHandler.kt b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/scratch/output/ScratchOutputHandler.kt index 35aabef18df..ae5ef37353a 100644 --- a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/scratch/output/ScratchOutputHandler.kt +++ b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/scratch/output/ScratchOutputHandler.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.scratch.output @@ -35,7 +24,7 @@ enum class ScratchOutputType { ERROR } -open class ScratchOutputHandlerAdapter: ScratchOutputHandler { +open class ScratchOutputHandlerAdapter : ScratchOutputHandler { override fun onStart(file: ScratchFile) {} override fun handle(file: ScratchFile, expression: ScratchExpression, output: ScratchOutput) {} override fun error(file: ScratchFile, message: String) {} diff --git a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/versions/KotlinJVMRuntimeLibraryUtil.kt b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/versions/KotlinJVMRuntimeLibraryUtil.kt index a2a266769fc..c75ba802941 100644 --- a/idea/idea-jvm/src/org/jetbrains/kotlin/idea/versions/KotlinJVMRuntimeLibraryUtil.kt +++ b/idea/idea-jvm/src/org/jetbrains/kotlin/idea/versions/KotlinJVMRuntimeLibraryUtil.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -35,11 +35,11 @@ fun updateLibraries(project: Project, libraries: Collection) { val kJvmConfigurator = getConfiguratorByName(KotlinJavaModuleConfigurator.NAME) as KotlinJavaModuleConfigurator? - ?: error("Configurator with given name doesn't exists: " + KotlinJavaModuleConfigurator.NAME) + ?: error("Configurator with given name doesn't exists: " + KotlinJavaModuleConfigurator.NAME) val kJsConfigurator = getConfiguratorByName(KotlinJsModuleConfigurator.NAME) as KotlinJsModuleConfigurator? - ?: error("Configurator with given name doesn't exists: " + KotlinJsModuleConfigurator.NAME) + ?: error("Configurator with given name doesn't exists: " + KotlinJsModuleConfigurator.NAME) val collector = createConfigureKotlinNotificationCollector(project) val sdk = ProjectRootManager.getInstance(project).projectSdk diff --git a/idea/idea-live-templates/src/org/jetbrains/kotlin/idea/liveTemplates/macro/AnonymousSuperMacro.kt b/idea/idea-live-templates/src/org/jetbrains/kotlin/idea/liveTemplates/macro/AnonymousSuperMacro.kt index 1e9b6fa2f50..8c81f9129ed 100644 --- a/idea/idea-live-templates/src/org/jetbrains/kotlin/idea/liveTemplates/macro/AnonymousSuperMacro.kt +++ b/idea/idea-live-templates/src/org/jetbrains/kotlin/idea/liveTemplates/macro/AnonymousSuperMacro.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.liveTemplates.macro @@ -20,7 +9,6 @@ import com.intellij.codeInsight.lookup.LookupElement import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.codeInsight.template.Expression import com.intellij.codeInsight.template.ExpressionContext -import com.intellij.codeInsight.template.Macro import com.intellij.codeInsight.template.Result import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiNamedElement @@ -60,23 +48,25 @@ class AnonymousSuperMacro : KotlinMacro() { } private fun getSupertypes(params: Array, context: ExpressionContext): Collection { - if (params.size != 0) return emptyList() + if (params.isNotEmpty()) return emptyList() val psiDocumentManager = PsiDocumentManager.getInstance(context.project) psiDocumentManager.commitAllDocuments() val psiFile = psiDocumentManager.getPsiFile(context.editor!!.document) as? KtFile ?: return emptyList() - val expression = PsiTreeUtil.getParentOfType(psiFile.findElementAt(context.startOffset), KtExpression::class.java) ?: return emptyList() + val expression = PsiTreeUtil.getParentOfType(psiFile.findElementAt(context.startOffset), KtExpression::class.java) + ?: return emptyList() val bindingContext = expression.analyze(BodyResolveMode.FULL) val resolutionScope = expression.getResolutionScope(bindingContext, expression.getResolutionFacade()) - return resolutionScope - .collectDescriptorsFiltered(DescriptorKindFilter.NON_SINGLETON_CLASSIFIERS) - .filter { it is ClassDescriptor && - (it.modality == Modality.OPEN || it.modality == Modality.ABSTRACT) && - (it.kind == ClassKind.CLASS || it.kind == ClassKind.INTERFACE) } - .mapNotNull { DescriptorToSourceUtils.descriptorToDeclaration(it) as PsiNamedElement? } + return resolutionScope.collectDescriptorsFiltered(DescriptorKindFilter.NON_SINGLETON_CLASSIFIERS) + .filter { + it is ClassDescriptor && + (it.modality == Modality.OPEN || it.modality == Modality.ABSTRACT) && + (it.kind == ClassKind.CLASS || it.kind == ClassKind.INTERFACE) + } + .mapNotNull { DescriptorToSourceUtils.descriptorToDeclaration(it) as PsiNamedElement? } } } diff --git a/idea/idea-live-templates/src/org/jetbrains/kotlin/idea/liveTemplates/macro/BaseKotlinVariableMacro.kt b/idea/idea-live-templates/src/org/jetbrains/kotlin/idea/liveTemplates/macro/BaseKotlinVariableMacro.kt index 5009e7dd654..f213cc3711f 100644 --- a/idea/idea-live-templates/src/org/jetbrains/kotlin/idea/liveTemplates/macro/BaseKotlinVariableMacro.kt +++ b/idea/idea-live-templates/src/org/jetbrains/kotlin/idea/liveTemplates/macro/BaseKotlinVariableMacro.kt @@ -59,24 +59,36 @@ abstract class BaseKotlinVariableMacro : KotlinMacro() { val bindingContext = resolutionFacade.analyze(contextElement, BodyResolveMode.PARTIAL_FOR_COMPLETION) fun isVisible(descriptor: DeclarationDescriptor): Boolean { - return descriptor !is DeclarationDescriptorWithVisibility || descriptor.isVisible(contextElement, null, bindingContext, resolutionFacade) + return descriptor !is DeclarationDescriptorWithVisibility || descriptor.isVisible( + contextElement, + null, + bindingContext, + resolutionFacade + ) } val state = initState(contextElement, bindingContext) - val helper = ReferenceVariantsHelper(bindingContext, resolutionFacade, resolutionFacade.moduleDescriptor, ::isVisible, NotPropertiesService.getNotProperties(contextElement)) + val helper = ReferenceVariantsHelper( + bindingContext, + resolutionFacade, + resolutionFacade.moduleDescriptor, + ::isVisible, + NotPropertiesService.getNotProperties(contextElement) + ) return helper - .getReferenceVariants(contextElement, CallTypeAndReceiver.DEFAULT, DescriptorKindFilter.VARIABLES, { true }) - .map { it as VariableDescriptor } - .filter { isSuitable(it, project, state) } + .getReferenceVariants(contextElement, CallTypeAndReceiver.DEFAULT, DescriptorKindFilter.VARIABLES, { true }) + .map { it as VariableDescriptor } + .filter { isSuitable(it, project, state) } } protected abstract fun initState(contextElement: KtElement, bindingContext: BindingContext): TState protected abstract fun isSuitable( - variableDescriptor: VariableDescriptor, - project: Project, - state: TState): Boolean + variableDescriptor: VariableDescriptor, + project: Project, + state: TState + ): Boolean override fun calculateResult(params: Array, context: ExpressionContext): Result? { val vars = getVariables(params, context) diff --git a/idea/idea-live-templates/src/org/jetbrains/kotlin/idea/liveTemplates/macro/KotlinFunctionNameMacro.kt b/idea/idea-live-templates/src/org/jetbrains/kotlin/idea/liveTemplates/macro/KotlinFunctionNameMacro.kt index c79536f554c..c0a4a30326f 100644 --- a/idea/idea-live-templates/src/org/jetbrains/kotlin/idea/liveTemplates/macro/KotlinFunctionNameMacro.kt +++ b/idea/idea-live-templates/src/org/jetbrains/kotlin/idea/liveTemplates/macro/KotlinFunctionNameMacro.kt @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + package org.jetbrains.kotlin.idea.liveTemplates.macro import com.intellij.codeInsight.template.Expression diff --git a/idea/idea-live-templates/src/org/jetbrains/kotlin/idea/liveTemplates/macro/SuitableVariableMacro.kt b/idea/idea-live-templates/src/org/jetbrains/kotlin/idea/liveTemplates/macro/SuitableVariableMacro.kt index be4e44b5a75..f76b5d05a67 100644 --- a/idea/idea-live-templates/src/org/jetbrains/kotlin/idea/liveTemplates/macro/SuitableVariableMacro.kt +++ b/idea/idea-live-templates/src/org/jetbrains/kotlin/idea/liveTemplates/macro/SuitableVariableMacro.kt @@ -43,7 +43,8 @@ class SuitableVariableMacro : BaseKotlinVariableMacro types.any { expectedInfo.filter.matchingSubstitutor(it.toFuzzyType(emptyList())) != null } } + return state.expectedInfos + .any { expectedInfo -> types.any { expectedInfo.filter.matchingSubstitutor(it.toFuzzyType(emptyList())) != null } } } } diff --git a/idea/idea-maven/src/org/jetbrains/kotlin/idea/maven/KotlinMavenImporter.kt b/idea/idea-maven/src/org/jetbrains/kotlin/idea/maven/KotlinMavenImporter.kt index cb03a1362d3..da696f792ee 100644 --- a/idea/idea-maven/src/org/jetbrains/kotlin/idea/maven/KotlinMavenImporter.kt +++ b/idea/idea-maven/src/org/jetbrains/kotlin/idea/maven/KotlinMavenImporter.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.maven @@ -127,7 +116,7 @@ class KotlinMavenImporter : MavenImporter(KOTLIN_PLUGIN_GROUP_ID, KOTLIN_PLUGIN_ private fun scheduleDownloadStdlibSources(mavenProject: MavenProject, module: Module) { // TODO: here we have to process all kotlin libraries but for now we only handle standard libraries val artifacts = mavenProject.dependencyArtifactIndex.data[KOTLIN_PLUGIN_GROUP_ID]?.values?.flatMap { it.filter { it.isResolved } } - ?: emptyList() + ?: emptyList() val librariesWithNoSources = ArrayList() OrderEnumerator.orderEntries(module).forEachLibrary { library -> @@ -164,13 +153,16 @@ class KotlinMavenImporter : MavenImporter(KOTLIN_PLUGIN_GROUP_ID, KOTLIN_PLUGIN_ val explicitOutputFile = it.configurationElement?.getChild("outputFile")?.text ?: sharedOutputFile if (PomFile.KotlinGoals.Js in it.goals) { // see org.jetbrains.kotlin.maven.K2JSCompilerMojo - val outputFilePath = PathUtil.toSystemDependentName(explicitOutputFile ?: "$buildDirectory/js/${mavenProject.mavenId.artifactId}.js") + val outputFilePath = + PathUtil.toSystemDependentName(explicitOutputFile ?: "$buildDirectory/js/${mavenProject.mavenId.artifactId}.js") compilerModuleExtension.setCompilerOutputPath(parentPath(outputFilePath)) facetSettings.productionOutputPath = outputFilePath } if (PomFile.KotlinGoals.TestJs in it.goals) { // see org.jetbrains.kotlin.maven.KotlinTestJSCompilerMojo - val outputFilePath = PathUtil.toSystemDependentName(explicitOutputFile ?: "$buildDirectory/test-js/${mavenProject.mavenId.artifactId}-tests.js") + val outputFilePath = PathUtil.toSystemDependentName( + explicitOutputFile ?: "$buildDirectory/test-js/${mavenProject.mavenId.artifactId}-tests.js" + ) compilerModuleExtension.setCompilerOutputPathForTests(parentPath(outputFilePath)) facetSettings.testOutputPath = outputFilePath } @@ -184,10 +176,10 @@ class KotlinMavenImporter : MavenImporter(KOTLIN_PLUGIN_GROUP_ID, KOTLIN_PLUGIN_ ): List { val arguments = platform.createArguments() - arguments.apiVersion = configuration?.getChild("apiVersion")?.text ?: - mavenProject.properties["kotlin.compiler.apiVersion"]?.toString() - arguments.languageVersion = configuration?.getChild("languageVersion")?.text ?: - mavenProject.properties["kotlin.compiler.languageVersion"]?.toString() + arguments.apiVersion = + configuration?.getChild("apiVersion")?.text ?: mavenProject.properties["kotlin.compiler.apiVersion"]?.toString() + arguments.languageVersion = + configuration?.getChild("languageVersion")?.text ?: mavenProject.properties["kotlin.compiler.languageVersion"]?.toString() arguments.multiPlatform = configuration?.getChild("multiPlatform")?.text?.trim()?.toBoolean() ?: false arguments.suppressWarnings = configuration?.getChild("nowarn")?.text?.trim()?.toBoolean() ?: false @@ -199,8 +191,8 @@ class KotlinMavenImporter : MavenImporter(KOTLIN_PLUGIN_GROUP_ID, KOTLIN_PLUGIN_ is K2JVMCompilerArguments -> { arguments.classpath = configuration?.getChild("classpath")?.text arguments.jdkHome = configuration?.getChild("jdkHome")?.text - arguments.jvmTarget = configuration?.getChild("jvmTarget")?.text ?: - mavenProject.properties["kotlin.compiler.jvmTarget"]?.toString() + arguments.jvmTarget = + configuration?.getChild("jvmTarget")?.text ?: mavenProject.properties["kotlin.compiler.jvmTarget"]?.toString() arguments.javaParameters = configuration?.getChild("javaParameters")?.text?.toBoolean() ?: false } is K2JSCompilerArguments -> { @@ -266,7 +258,7 @@ class KotlinMavenImporter : MavenImporter(KOTLIN_PLUGIN_GROUP_ID, KOTLIN_PLUGIN_ val configuration = mavenPlugin.configurationElement val sharedArguments = getCompilerArgumentsByConfigurationElement(mavenProject, configuration, configuredPlatform) val executionArguments = mavenPlugin.executions - ?.firstOrNull { it.goals.any { it in compilationGoals } } + ?.firstOrNull { it.goals.any { s -> s in compilationGoals } } ?.configurationElement?.let { getCompilerArgumentsByConfigurationElement(mavenProject, it, configuredPlatform) } parseCompilerArgumentsToFacet(sharedArguments, emptyList(), kotlinFacet, modifiableModelsProvider) if (executionArguments != null) { @@ -338,7 +330,8 @@ class KotlinMavenImporter : MavenImporter(KOTLIN_PLUGIN_GROUP_ID, KOTLIN_PLUGIN_ .any { it in PomFile.KotlinGoals.CompileGoals && it !in PomFile.KotlinGoals.JvmGoals } val prodSourceRootType: JpsModuleSourceRootType<*> = if (isNonJvmModule) SourceKotlinRootType else JavaSourceRootType.SOURCE - val testSourceRootType: JpsModuleSourceRootType<*> = if (isNonJvmModule) TestSourceKotlinRootType else JavaSourceRootType.TEST_SOURCE + val testSourceRootType: JpsModuleSourceRootType<*> = + if (isNonJvmModule) TestSourceKotlinRootType else JavaSourceRootType.TEST_SOURCE for ((type, dir) in directories) { if (rootModel.getSourceFolder(File(dir)) == null) { @@ -392,7 +385,7 @@ private fun MavenPlugin.isKotlinPlugin() = private fun Element?.sourceDirectories(): List = this?.getChildren(KotlinMavenImporter.KOTLIN_PLUGIN_SOURCE_DIRS_CONFIG)?.flatMap { it.children ?: emptyList() }?.map { it.textTrim } - ?: emptyList() + ?: emptyList() private fun MavenPlugin.Execution.sourceType() = goals.map { if (isTestGoalName(it)) SourceType.TEST else SourceType.PROD } diff --git a/idea/idea-maven/src/org/jetbrains/kotlin/idea/maven/MavenCompletionProviders.kt b/idea/idea-maven/src/org/jetbrains/kotlin/idea/maven/MavenCompletionProviders.kt index 076f72aae82..967995c144a 100644 --- a/idea/idea-maven/src/org/jetbrains/kotlin/idea/maven/MavenCompletionProviders.kt +++ b/idea/idea-maven/src/org/jetbrains/kotlin/idea/maven/MavenCompletionProviders.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.maven @@ -24,11 +13,13 @@ import org.jetbrains.kotlin.config.JvmTarget import org.jetbrains.kotlin.config.LanguageVersion class MavenLanguageVersionsCompletionProvider : MavenFixedValueReferenceProvider( - LanguageVersion.values().filter { it.isStable || ApplicationManager.getApplication().isInternal }.map { it.versionString }.toTypedArray() + LanguageVersion.values().filter { it.isStable || ApplicationManager.getApplication().isInternal }.map { it.versionString } + .toTypedArray() ) class MavenApiVersionsCompletionProvider : MavenFixedValueReferenceProvider( - LanguageVersion.values().filter { it.isStable || ApplicationManager.getApplication().isInternal }.map { it.versionString }.toTypedArray() + LanguageVersion.values().filter { it.isStable || ApplicationManager.getApplication().isInternal }.map { it.versionString } + .toTypedArray() ) class MavenJvmTargetsCompletionProvider : MavenFixedValueReferenceProvider( diff --git a/idea/idea-maven/src/org/jetbrains/kotlin/idea/maven/PomFile.kt b/idea/idea-maven/src/org/jetbrains/kotlin/idea/maven/PomFile.kt index 9b91179d9b1..5dd2cbb6c51 100644 --- a/idea/idea-maven/src/org/jetbrains/kotlin/idea/maven/PomFile.kt +++ b/idea/idea-maven/src/org/jetbrains/kotlin/idea/maven/PomFile.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.maven @@ -56,7 +45,7 @@ class PomFile private constructor(private val xmlFile: XmlFile, val domModel: Ma constructor(xmlFile: XmlFile) : this( xmlFile, MavenDomUtil.getMavenDomProjectModel(xmlFile.project, xmlFile.virtualFile) - ?: throw IllegalStateException("No DOM model found for pom ${xmlFile.name}") + ?: throw IllegalStateException("No DOM model found for pom ${xmlFile.name}") ) private val nodesByName = HashMap() diff --git a/idea/idea-maven/src/org/jetbrains/kotlin/idea/maven/configuration/KotlinMavenConfigurator.kt b/idea/idea-maven/src/org/jetbrains/kotlin/idea/maven/configuration/KotlinMavenConfigurator.kt index 1cb029f002c..093a50c2f8e 100644 --- a/idea/idea-maven/src/org/jetbrains/kotlin/idea/maven/configuration/KotlinMavenConfigurator.kt +++ b/idea/idea-maven/src/org/jetbrains/kotlin/idea/maven/configuration/KotlinMavenConfigurator.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -59,7 +59,8 @@ protected constructor( if (psi == null || !psi.isValid || psi !is XmlFile - || psi.virtualFile == null) { + || psi.virtualFile == null + ) { return ConfigureKotlinStatus.BROKEN } @@ -82,7 +83,7 @@ protected constructor( val kotlinPluginId = kotlinPluginId(null) val kotlinPlugin = mavenProject.plugins.find { it.mavenId.equals(kotlinPluginId.groupId, kotlinPluginId.artifactId) } - ?: return ConfigureKotlinStatus.CAN_BE_CONFIGURED + ?: return ConfigureKotlinStatus.CAN_BE_CONFIGURED if (kotlinPlugin.executions.any { it.goals.any(this::isRelevantGoal) }) { return ConfigureKotlinStatus.CONFIGURED diff --git a/idea/idea-maven/src/org/jetbrains/kotlin/idea/maven/inspections/DifferentKotlinMavenVersionInspection.kt b/idea/idea-maven/src/org/jetbrains/kotlin/idea/maven/inspections/DifferentKotlinMavenVersionInspection.kt index 62f601e7541..842fd3f5e34 100644 --- a/idea/idea-maven/src/org/jetbrains/kotlin/idea/maven/inspections/DifferentKotlinMavenVersionInspection.kt +++ b/idea/idea-maven/src/org/jetbrains/kotlin/idea/maven/inspections/DifferentKotlinMavenVersionInspection.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.maven.inspections @@ -57,8 +46,9 @@ class DifferentKotlinMavenVersionInspection : DomElementsInspection goal.rawText == PomFile.KotlinGoals.Compile || goal.rawText == PomFile.KotlinGoals.Js } - && it.goals.goals.any { goal -> goal.rawText == PomFile.KotlinGoals.TestCompile || goal.rawText == PomFile.KotlinGoals.TestJs } + it.goals.goals.any { goal -> + goal.rawText == PomFile.KotlinGoals.Compile || goal.rawText == PomFile.KotlinGoals.Js + } && it.goals.goals.any { goal -> + goal.rawText == PomFile.KotlinGoals.TestCompile || goal.rawText == PomFile.KotlinGoals.TestJs + } }.forEach { badExecution -> holder.createProblem( badExecution.goals.createStableCopy(), diff --git a/idea/idea-maven/src/org/jetbrains/kotlin/idea/maven/inspections/KotlinMavenUnresolvedReferenceQuickFixProvider.kt b/idea/idea-maven/src/org/jetbrains/kotlin/idea/maven/inspections/KotlinMavenUnresolvedReferenceQuickFixProvider.kt index 677eddd6598..7b6afdf3397 100644 --- a/idea/idea-maven/src/org/jetbrains/kotlin/idea/maven/inspections/KotlinMavenUnresolvedReferenceQuickFixProvider.kt +++ b/idea/idea-maven/src/org/jetbrains/kotlin/idea/maven/inspections/KotlinMavenUnresolvedReferenceQuickFixProvider.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.maven.inspections @@ -68,7 +57,7 @@ class KotlinMavenUnresolvedReferenceQuickFixProvider : UnresolvedReferenceQuickF .importDirectives .firstOrNull { !it.isAllUnder && it.aliasName == referenced || it.importedFqName?.shortName()?.asString() == referenced } ?.let { it.importedFqName?.asString() } - ?: referenced + ?: referenced } if (name != null) { diff --git a/idea/idea-maven/src/org/jetbrains/kotlin/idea/maven/inspections/KotlinTestJUnitInspection.kt b/idea/idea-maven/src/org/jetbrains/kotlin/idea/maven/inspections/KotlinTestJUnitInspection.kt index dbf9ae6825c..555c8ba2a99 100644 --- a/idea/idea-maven/src/org/jetbrains/kotlin/idea/maven/inspections/KotlinTestJUnitInspection.kt +++ b/idea/idea-maven/src/org/jetbrains/kotlin/idea/maven/inspections/KotlinTestJUnitInspection.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.maven.inspections @@ -44,8 +33,9 @@ class KotlinTestJUnitInspection : DomElementsInspection(Ma return } - val kotlinTestDependencies = domFileElement.rootElement.dependencies - .dependencies.filter { it.groupId.rawText == KotlinMavenConfigurator.GROUP_ID && it.artifactId.rawText == KotlinJavaMavenConfigurator.TEST_LIB_ID } + val kotlinTestDependencies = domFileElement.rootElement.dependencies.dependencies.filter { + it.groupId.rawText == KotlinMavenConfigurator.GROUP_ID && it.artifactId.rawText == KotlinJavaMavenConfigurator.TEST_LIB_ID + } kotlinTestDependencies.forEach { holder.createProblem( diff --git a/idea/idea-maven/test/org/jetbrains/kotlin/idea/maven/AbstractKotlinMavenInspectionTest.kt b/idea/idea-maven/test/org/jetbrains/kotlin/idea/maven/AbstractKotlinMavenInspectionTest.kt index 3b37e625d5b..3f53555dba2 100644 --- a/idea/idea-maven/test/org/jetbrains/kotlin/idea/maven/AbstractKotlinMavenInspectionTest.kt +++ b/idea/idea-maven/test/org/jetbrains/kotlin/idea/maven/AbstractKotlinMavenInspectionTest.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.maven @@ -62,7 +51,7 @@ abstract class AbstractKotlinMavenInspectionTest : MavenImportingTestCase() { } val inspectionClassName = "".toRegex().find(pomText)?.groups?.get(1)?.value - ?: KotlinMavenPluginPhaseInspection::class.qualifiedName!! + ?: KotlinMavenPluginPhaseInspection::class.qualifiedName!! val inspectionClass = Class.forName(inspectionClassName) val matcher = "".toRegex() @@ -82,9 +71,7 @@ abstract class AbstractKotlinMavenInspectionTest : MavenImportingTestCase() { .map { SimplifiedProblemDescription(it.descriptionTemplate, it.psiElement.text.replace("\\s+".toRegex(), "")) to it } .sortedBy { it.first.text } - val actualProblemsText = actual - .map { it.first } - .joinToString("\n") { ""} + val actualProblemsText = actual.map { it.first }.joinToString("\n") { "" } assertEquals(expectedProblemsText, actualProblemsText) @@ -180,8 +167,8 @@ abstract class AbstractKotlinMavenInspectionTest : MavenImportingTestCase() { private fun mkJavaFile() { val contentEntry = getContentRoots(myProject.allModules().single().name).single() val sourceFolder = - contentEntry.getSourceFolders(JavaSourceRootType.SOURCE).singleOrNull() ?: - contentEntry.getSourceFolders(SourceKotlinRootType).singleOrNull() + contentEntry.getSourceFolders(JavaSourceRootType.SOURCE).singleOrNull() ?: contentEntry.getSourceFolders(SourceKotlinRootType) + .singleOrNull() ApplicationManager.getApplication().runWriteAction { val javaFile = sourceFolder?.file?.toPsiDirectory(myProject)?.createFile("Test.java") ?: throw IllegalStateException() javaFile.viewProvider.document!!.setText("class Test {}\n") diff --git a/idea/idea-maven/test/org/jetbrains/kotlin/idea/maven/KotlinMavenImporterTest.kt b/idea/idea-maven/test/org/jetbrains/kotlin/idea/maven/KotlinMavenImporterTest.kt index 96027766e35..375f0749c00 100644 --- a/idea/idea-maven/test/org/jetbrains/kotlin/idea/maven/KotlinMavenImporterTest.kt +++ b/idea/idea-maven/test/org/jetbrains/kotlin/idea/maven/KotlinMavenImporterTest.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.maven @@ -45,15 +34,15 @@ import org.jetbrains.kotlin.idea.framework.JSLibraryKind import org.jetbrains.kotlin.idea.framework.KotlinSdkType import org.jetbrains.kotlin.idea.project.languageVersionSettings import org.jetbrains.kotlin.idea.util.getProjectJdkTableSafe -import org.jetbrains.kotlin.psi.KtFile -import org.jetbrains.kotlin.test.JUnit3WithIdeaConfigurationRunner import org.jetbrains.kotlin.platform.CommonPlatforms import org.jetbrains.kotlin.platform.TargetPlatform import org.jetbrains.kotlin.platform.isCommon -import org.jetbrains.kotlin.platform.js.isJs -import org.jetbrains.kotlin.platform.oldFashionedDescription import org.jetbrains.kotlin.platform.js.JsPlatforms +import org.jetbrains.kotlin.platform.js.isJs import org.jetbrains.kotlin.platform.jvm.JvmPlatforms +import org.jetbrains.kotlin.platform.oldFashionedDescription +import org.jetbrains.kotlin.psi.KtFile +import org.jetbrains.kotlin.test.JUnit3WithIdeaConfigurationRunner import org.junit.Assert import org.junit.runner.RunWith import java.io.File @@ -655,7 +644,7 @@ class KotlinMavenImporterTest : MavenImportingTestCase() { createProjectSubDirs("src/main/kotlin") importProject( - """ + """ test project 1.0.0 @@ -858,7 +847,7 @@ class KotlinMavenImporterTest : MavenImportingTestCase() { fun testJsCustomOutputPaths() { createProjectSubDirs("src/main/kotlin", "src/test/kotlin") importProject( - """ + """ test project 1.0.0 @@ -918,7 +907,7 @@ class KotlinMavenImporterTest : MavenImportingTestCase() { Assert.assertEquals("$projectBasePath/test/test.js", PathUtil.toSystemIndependentName(testOutputPath)) } - with (CompilerModuleExtension.getInstance(getModule("project"))!!) { + with(CompilerModuleExtension.getInstance(getModule("project"))!!) { Assert.assertEquals("$projectBasePath/prod", PathUtil.toSystemIndependentName(compilerOutputUrl)) Assert.assertEquals("$projectBasePath/test", PathUtil.toSystemIndependentName(compilerOutputUrlForTests)) } @@ -2369,8 +2358,8 @@ class KotlinMavenImporterTest : MavenImportingTestCase() { ) val commonModule2 = createModulePom( - "my-common-module2", - """ + "my-common-module2", + """ test diff --git a/idea/idea-repl/src/org/jetbrains/kotlin/console/CommandHistory.kt b/idea/idea-repl/src/org/jetbrains/kotlin/console/CommandHistory.kt index dda6674600a..4cd60b5824c 100644 --- a/idea/idea-repl/src/org/jetbrains/kotlin/console/CommandHistory.kt +++ b/idea/idea-repl/src/org/jetbrains/kotlin/console/CommandHistory.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.console @@ -20,8 +9,8 @@ import com.intellij.openapi.util.TextRange class CommandHistory { class Entry( - val entryText: String, - val rangeInHistoryDocument: TextRange + val entryText: String, + val rangeInHistoryDocument: TextRange ) private val entries = arrayListOf() @@ -37,21 +26,17 @@ class CommandHistory { listeners.forEach { it.onNewEntry(entry) } } - fun lastUnprocessedEntry(): Entry? { - return if (processedEntriesCount < size) { - get(processedEntriesCount) - } - else { - null - } + fun lastUnprocessedEntry(): Entry? = if (processedEntriesCount < size) { + get(processedEntriesCount) + } else { + null } fun entryProcessed() { processedEntriesCount++ } - val size: Int - get() = entries.size + val size: Int get() = entries.size } interface HistoryUpdateListener { diff --git a/idea/idea-repl/src/org/jetbrains/kotlin/console/HistoryKeyListener.kt b/idea/idea-repl/src/org/jetbrains/kotlin/console/HistoryKeyListener.kt index 008425dc691..a69ce8392b9 100644 --- a/idea/idea-repl/src/org/jetbrains/kotlin/console/HistoryKeyListener.kt +++ b/idea/idea-repl/src/org/jetbrains/kotlin/console/HistoryKeyListener.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.console @@ -26,9 +15,8 @@ import java.awt.event.KeyEvent import kotlin.math.max import kotlin.math.min -class HistoryKeyListener( - private val project: Project, private val consoleEditor: EditorEx, private val history: CommandHistory -) : KeyAdapter(), HistoryUpdateListener { +class HistoryKeyListener(private val project: Project, private val consoleEditor: EditorEx, private val history: CommandHistory) : + KeyAdapter(), HistoryUpdateListener { private var historyPos = 0 private var prevCaretOffset = -1 private var unfinishedCommand = "" diff --git a/idea/idea-repl/src/org/jetbrains/kotlin/console/KotlinConsoleKeeper.kt b/idea/idea-repl/src/org/jetbrains/kotlin/console/KotlinConsoleKeeper.kt index 0edc6e2cbcf..0d19af01bc2 100644 --- a/idea/idea-repl/src/org/jetbrains/kotlin/console/KotlinConsoleKeeper.kt +++ b/idea/idea-repl/src/org/jetbrains/kotlin/console/KotlinConsoleKeeper.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.console @@ -26,7 +15,7 @@ import org.jetbrains.kotlin.utils.PathUtil import java.io.File import java.util.concurrent.ConcurrentHashMap -private val REPL_TITLE = "Kotlin REPL" +private const val REPL_TITLE = "Kotlin REPL" class KotlinConsoleKeeper(val project: Project) { private val consoleMap: MutableMap = ConcurrentHashMap() @@ -45,7 +34,8 @@ class KotlinConsoleKeeper(val project: Project) { } companion object { - @JvmStatic fun getInstance(project: Project) = ServiceManager.getService(project, KotlinConsoleKeeper::class.java) + @JvmStatic + fun getInstance(project: Project) = ServiceManager.getService(project, KotlinConsoleKeeper::class.java) fun createReplCommandLine(project: Project, module: Module?): GeneralCommandLine { val javaParameters = JavaParametersBuilder(project) diff --git a/idea/idea-repl/src/org/jetbrains/kotlin/console/KotlinConsoleRunner.kt b/idea/idea-repl/src/org/jetbrains/kotlin/console/KotlinConsoleRunner.kt index c78093b1818..1bdd3f13845 100644 --- a/idea/idea-repl/src/org/jetbrains/kotlin/console/KotlinConsoleRunner.kt +++ b/idea/idea-repl/src/org/jetbrains/kotlin/console/KotlinConsoleRunner.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.console @@ -61,10 +50,10 @@ import org.jetbrains.kotlin.idea.caches.project.forcedModuleInfo import org.jetbrains.kotlin.idea.caches.project.productionSourceInfo import org.jetbrains.kotlin.idea.caches.project.testSourceInfo import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor +import org.jetbrains.kotlin.idea.caches.trackers.KOTLIN_CONSOLE_KEY import org.jetbrains.kotlin.idea.core.script.ScriptDefinitionContributor import org.jetbrains.kotlin.idea.core.script.ScriptDefinitionSourceAsContributor import org.jetbrains.kotlin.idea.core.script.ScriptDefinitionsManager -import org.jetbrains.kotlin.idea.caches.trackers.KOTLIN_CONSOLE_KEY import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.parsing.KotlinParserDefinition @@ -81,15 +70,15 @@ import java.util.concurrent.TimeUnit import kotlin.properties.Delegates import kotlin.script.experimental.jvm.defaultJvmScriptingHostConfiguration -private val KOTLIN_SHELL_EXECUTE_ACTION_ID = "KotlinShellExecute" +private const val KOTLIN_SHELL_EXECUTE_ACTION_ID = "KotlinShellExecute" class KotlinConsoleRunner( - val module: Module, - private val cmdLine: GeneralCommandLine, - internal val previousCompilationFailed: Boolean, - myProject: Project, - title: String, - path: String? + val module: Module, + private val cmdLine: GeneralCommandLine, + internal val previousCompilationFailed: Boolean, + myProject: Project, + title: String, + path: String? ) : AbstractConsoleRunnerWithHistory(myProject, title, path) { private val replState = ReplState() @@ -181,9 +170,9 @@ class KotlinConsoleRunner( override fun createProcessHandler(process: Process): OSProcessHandler { val processHandler = ReplOutputHandler( - this, - process, - cmdLine.commandLineString + this, + process, + cmdLine.commandLineString ) val consoleFile = consoleView.virtualFile val keeper = KotlinConsoleKeeper.getInstance(project) @@ -197,24 +186,25 @@ class KotlinConsoleRunner( override fun runExecuteAction(consoleView: LanguageConsoleView) = executor.executeCommand() } - override fun fillToolBarActions(toolbarActions: DefaultActionGroup, - defaultExecutor: Executor, - contentDescriptor: RunContentDescriptor + override fun fillToolBarActions( + toolbarActions: DefaultActionGroup, + defaultExecutor: Executor, + contentDescriptor: RunContentDescriptor ): List { disposableDescriptor = contentDescriptor compilerHelper = ConsoleCompilerHelper(project, module, defaultExecutor, contentDescriptor) val actionList = arrayListOf( - BuildAndRestartConsoleAction(this), - createConsoleExecAction(consoleExecuteActionHandler), - createCloseAction(defaultExecutor, contentDescriptor) + BuildAndRestartConsoleAction(this), + createConsoleExecAction(consoleExecuteActionHandler), + createCloseAction(defaultExecutor, contentDescriptor) ) toolbarActions.addAll(actionList) return actionList } - override fun createConsoleExecAction(consoleExecuteActionHandler: ProcessBackedConsoleExecuteActionHandler) - = ConsoleExecuteAction(consoleView, consoleExecuteActionHandler, KOTLIN_SHELL_EXECUTE_ACTION_ID, consoleExecuteActionHandler) + override fun createConsoleExecAction(consoleExecuteActionHandler: ProcessBackedConsoleExecuteActionHandler) = + ConsoleExecuteAction(consoleView, consoleExecuteActionHandler, KOTLIN_SHELL_EXECUTE_ACTION_ID, consoleExecuteActionHandler) override fun constructConsoleTitle(title: String) = "$title (in module ${module.name})" @@ -260,13 +250,14 @@ class KotlinConsoleRunner( val indicator = ConsoleIndicatorRenderer(iconWithTooltip) val editorMarkup = editor.markupModel val indicatorHighlighter = editorMarkup.addRangeHighlighter( - 0, editor.document.textLength, HighlighterLayer.LAST, null, HighlighterTargetArea.LINES_IN_RANGE + 0, editor.document.textLength, HighlighterLayer.LAST, null, HighlighterTargetArea.LINES_IN_RANGE ) return indicatorHighlighter.apply { gutterIconRenderer = indicator } } - @TestOnly fun dispose() { + @TestOnly + fun dispose() { processHandler.destroyProcess() consoleTerminated.await(1, TimeUnit.SECONDS) Disposer.dispose(disposableDescriptor) @@ -283,8 +274,12 @@ class KotlinConsoleRunner( charset = CharsetToolkit.UTF8_CHARSET isWritable = false } - val psiFile = (PsiFileFactory.getInstance(project) as PsiFileFactoryImpl).trySetupPsiForFile(virtualFile, KotlinLanguage.INSTANCE, true, false) as KtFile? - ?: error("Failed to setup PSI for file:\n$text") + val psiFile = (PsiFileFactory.getInstance(project) as PsiFileFactoryImpl).trySetupPsiForFile( + virtualFile, + KotlinLanguage.INSTANCE, + true, + false + ) as KtFile? ?: error("Failed to setup PSI for file:\n$text") replState.submitLine(psiFile) configureFileDependencies(psiFile) @@ -304,12 +299,11 @@ class KotlinConsoleRunner( } private fun configureFileDependencies(psiFile: KtFile) { - psiFile.forcedModuleInfo = module.testSourceInfo() ?: module.productionSourceInfo() ?: - NotUnderContentRootModuleInfo + psiFile.forcedModuleInfo = module.testSourceInfo() ?: module.productionSourceInfo() ?: NotUnderContentRootModuleInfo } } -class ConsoleScriptDefinitionContributor: ScriptDefinitionSourceAsContributor { +class ConsoleScriptDefinitionContributor : ScriptDefinitionSourceAsContributor { val definitionsSet = ContainerUtil.newConcurrentSet() diff --git a/idea/idea-repl/src/org/jetbrains/kotlin/console/ReplColors.kt b/idea/idea-repl/src/org/jetbrains/kotlin/console/ReplColors.kt index 38183c7dbb6..ae580197302 100644 --- a/idea/idea-repl/src/org/jetbrains/kotlin/console/ReplColors.kt +++ b/idea/idea-repl/src/org/jetbrains/kotlin/console/ReplColors.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.console @@ -28,19 +17,18 @@ object ReplColors { val EDITOR_GUTTER_COLOR: JBColor = JBColor(Gray.xCF, Gray.x31) val PLACEHOLDER_COLOR: JBColor = JBColor.LIGHT_GRAY - val WARNING_INFO_CONTENT_TYPE: ConsoleViewContentType = - ConsoleViewContentType( - "KOTLIN_CONSOLE_WARNING_INFO", - TextAttributes().apply { fontType = Font.ITALIC; foregroundColor = JBColor.RED } - ) - val INITIAL_PROMPT_CONTENT_TYPE: ConsoleViewContentType = - ConsoleViewContentType( - "KOTLIN_CONSOLE_INITIAL_PROMPT", - TextAttributes().apply { fontType = Font.BOLD } - ) - val USER_OUTPUT_CONTENT_TYPE: ConsoleViewContentType = - ConsoleViewContentType( - "KOTLIN_CONSOLE_USER_OUTPUT", - TextAttributes().apply { fontType = Font.ITALIC; foregroundColor = Colors.DARK_GREEN } - ) + val WARNING_INFO_CONTENT_TYPE: ConsoleViewContentType = ConsoleViewContentType( + "KOTLIN_CONSOLE_WARNING_INFO", + TextAttributes().apply { fontType = Font.ITALIC; foregroundColor = JBColor.RED } + ) + + val INITIAL_PROMPT_CONTENT_TYPE: ConsoleViewContentType = ConsoleViewContentType( + "KOTLIN_CONSOLE_INITIAL_PROMPT", + TextAttributes().apply { fontType = Font.BOLD } + ) + + val USER_OUTPUT_CONTENT_TYPE: ConsoleViewContentType = ConsoleViewContentType( + "KOTLIN_CONSOLE_USER_OUTPUT", + TextAttributes().apply { fontType = Font.ITALIC; foregroundColor = Colors.DARK_GREEN } + ) } \ No newline at end of file diff --git a/idea/idea-repl/src/org/jetbrains/kotlin/console/ReplOutputHandler.kt b/idea/idea-repl/src/org/jetbrains/kotlin/console/ReplOutputHandler.kt index f637db8762c..22e8b5695bf 100644 --- a/idea/idea-repl/src/org/jetbrains/kotlin/console/ReplOutputHandler.kt +++ b/idea/idea-repl/src/org/jetbrains/kotlin/console/ReplOutputHandler.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.console @@ -35,9 +24,9 @@ import javax.xml.parsers.DocumentBuilderFactory data class SeverityDetails(val severity: Severity, val description: String, val range: TextRange) class ReplOutputHandler( - private val runner: KotlinConsoleRunner, - process: Process, - commandLine: String + private val runner: KotlinConsoleRunner, + process: Process, + commandLine: String ) : OSProcessHandler(process, commandLine) { private var isBuildInfoChecked = false @@ -58,8 +47,7 @@ class ReplOutputHandler( handleReplMessage(resultingText) inputBuffer.setLength(0) } - } - else { + } else { super.notifyTextAvailable(text, key) } } @@ -68,8 +56,7 @@ class ReplOutputHandler( if (text.isBlank()) return val output = try { factory.newDocumentBuilder().parse(strToSource(text)) - } - catch (e: Exception) { + } catch (e: Exception) { logError(ReplOutputHandler::class.java, "Couldn't parse REPL output: $text", e) return } @@ -79,17 +66,17 @@ class ReplOutputHandler( val content = root.textContent.replUnescapeLineBreaks().replNormalizeLineBreaks() when (outputType) { - INITIAL_PROMPT -> buildWarningIfNeededBeforeInit(content) - HELP_PROMPT -> outputProcessor.printHelp(content) - USER_OUTPUT -> outputProcessor.printUserOutput(content) - REPL_RESULT -> outputProcessor.printResultWithGutterIcon(content) - READLINE_START -> runner.isReadLineMode = true - READLINE_END -> runner.isReadLineMode = false + INITIAL_PROMPT -> buildWarningIfNeededBeforeInit(content) + HELP_PROMPT -> outputProcessor.printHelp(content) + USER_OUTPUT -> outputProcessor.printUserOutput(content) + REPL_RESULT -> outputProcessor.printResultWithGutterIcon(content) + READLINE_START -> runner.isReadLineMode = true + READLINE_END -> runner.isReadLineMode = false REPL_INCOMPLETE, - COMPILE_ERROR -> outputProcessor.highlightCompilerErrors(createCompilerMessages(content)) - RUNTIME_ERROR -> outputProcessor.printRuntimeError("${content.trim()}\n") - INTERNAL_ERROR -> outputProcessor.printInternalErrorMessage(content) - SUCCESS -> runner.commandHistory.lastUnprocessedEntry()?.entryText?.let { runner.successfulLine(it) } + COMPILE_ERROR -> outputProcessor.highlightCompilerErrors(createCompilerMessages(content)) + RUNTIME_ERROR -> outputProcessor.printRuntimeError("${content.trim()}\n") + INTERNAL_ERROR -> outputProcessor.printInternalErrorMessage(content) + SUCCESS -> runner.commandHistory.lastUnprocessedEntry()?.entryText?.let { runner.successfulLine(it) } null -> logError(ReplOutputHandler::class.java, "Unexpected output type:\n$outputType") } @@ -113,7 +100,7 @@ class ReplOutputHandler( val report = factory.newDocumentBuilder().parse(strToSource(runtimeErrorsReport, Charsets.UTF_16)) val entries = report.getElementsByTagName("reportEntry") - for (i in 0..entries.length - 1) { + for (i in 0 until entries.length) { val reportEntry = entries.item(i) as Element val severityLevel = reportEntry.getAttribute("severity").toSeverity() @@ -128,9 +115,9 @@ class ReplOutputHandler( } private fun String.toSeverity() = when (this) { - "ERROR" -> Severity.ERROR + "ERROR" -> Severity.ERROR "WARNING" -> Severity.WARNING - "INFO" -> Severity.INFO - else -> throw IllegalArgumentException("Unsupported Severity: '$this'") // this case shouldn't occur + "INFO" -> Severity.INFO + else -> throw IllegalArgumentException("Unsupported Severity: '$this'") // this case shouldn't occur } } \ No newline at end of file diff --git a/idea/idea-repl/src/org/jetbrains/kotlin/console/actions/ConsoleModuleDialog.kt b/idea/idea-repl/src/org/jetbrains/kotlin/console/actions/ConsoleModuleDialog.kt index 0a7f626503e..18a134e8185 100644 --- a/idea/idea-repl/src/org/jetbrains/kotlin/console/actions/ConsoleModuleDialog.kt +++ b/idea/idea-repl/src/org/jetbrains/kotlin/console/actions/ConsoleModuleDialog.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.console.actions @@ -40,7 +29,7 @@ class ConsoleModuleDialog(private val project: Project) { val moduleGroup = DefaultActionGroup(moduleActions) val modulePopup = JBPopupFactory.getInstance().createActionGroupPopup( - TITLE, moduleGroup, dataContext, JBPopupFactory.ActionSelectionAid.SPEEDSEARCH, true, ActionPlaces.UNKNOWN + TITLE, moduleGroup, dataContext, JBPopupFactory.ActionSelectionAid.SPEEDSEARCH, true, ActionPlaces.UNKNOWN ) modulePopup.showCenteredInCurrentWindow(project) diff --git a/idea/idea-repl/src/org/jetbrains/kotlin/console/actions/RunExecuteActions.kt b/idea/idea-repl/src/org/jetbrains/kotlin/console/actions/RunExecuteActions.kt index 6cb9ca9246e..ccbab93aa8f 100644 --- a/idea/idea-repl/src/org/jetbrains/kotlin/console/actions/RunExecuteActions.kt +++ b/idea/idea-repl/src/org/jetbrains/kotlin/console/actions/RunExecuteActions.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.console.actions @@ -54,7 +43,7 @@ class KtExecuteCommandAction(private val consoleFile: VirtualFile) : AnAction() } class BuildAndRestartConsoleAction( - private val runner: KotlinConsoleRunner + private val runner: KotlinConsoleRunner ) : AnAction("Build and restart", "Build module '${runner.module.name}' and restart", AllIcons.Actions.Restart) { override fun actionPerformed(e: AnActionEvent) = runner.compilerHelper.compileModule() diff --git a/idea/idea-repl/src/org/jetbrains/kotlin/jsr223/KotlinJsr223StandardScriptEngineFactory4Idea.kt b/idea/idea-repl/src/org/jetbrains/kotlin/jsr223/KotlinJsr223StandardScriptEngineFactory4Idea.kt index 331a46dbf63..e2ede54db88 100644 --- a/idea/idea-repl/src/org/jetbrains/kotlin/jsr223/KotlinJsr223StandardScriptEngineFactory4Idea.kt +++ b/idea/idea-repl/src/org/jetbrains/kotlin/jsr223/KotlinJsr223StandardScriptEngineFactory4Idea.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.jsr223 @@ -20,7 +9,6 @@ import org.jetbrains.kotlin.cli.common.repl.KotlinJsr223JvmScriptEngineFactoryBa import org.jetbrains.kotlin.cli.common.repl.ScriptArgsWithTypes import org.jetbrains.kotlin.script.util.KotlinJars import org.jetbrains.kotlin.script.util.scriptCompilationClasspathFromContextOrStlib -import org.jetbrains.kotlin.utils.PathUtil import javax.script.ScriptContext import javax.script.ScriptEngine @@ -28,12 +16,12 @@ import javax.script.ScriptEngine class KotlinJsr223StandardScriptEngineFactory4Idea : KotlinJsr223JvmScriptEngineFactoryBase() { override fun getScriptEngine(): ScriptEngine = - KotlinJsr223JvmScriptEngine4Idea( - this, - scriptCompilationClasspathFromContextOrStlib(wholeClasspath = true) + KotlinJars.kotlinScriptStandardJars, - "kotlin.script.templates.standard.ScriptTemplateWithBindings", - { ctx, argTypes -> ScriptArgsWithTypes(arrayOf(ctx.getBindings(ScriptContext.ENGINE_SCOPE)), argTypes ?: emptyArray()) }, - arrayOf(Map::class) - ) + KotlinJsr223JvmScriptEngine4Idea( + this, + scriptCompilationClasspathFromContextOrStlib(wholeClasspath = true) + KotlinJars.kotlinScriptStandardJars, + "kotlin.script.templates.standard.ScriptTemplateWithBindings", + { ctx, argTypes -> ScriptArgsWithTypes(arrayOf(ctx.getBindings(ScriptContext.ENGINE_SCOPE)), argTypes ?: emptyArray()) }, + arrayOf(Map::class) + ) } diff --git a/idea/idea-test-framework/test/org/jetbrains/kotlin/idea/test/AstAccessControl.kt b/idea/idea-test-framework/test/org/jetbrains/kotlin/idea/test/AstAccessControl.kt index 7b980b9fd04..ad90def44b2 100644 --- a/idea/idea-test-framework/test/org/jetbrains/kotlin/idea/test/AstAccessControl.kt +++ b/idea/idea-test-framework/test/org/jetbrains/kotlin/idea/test/AstAccessControl.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.test @@ -39,15 +28,15 @@ object AstAccessControl { } fun testWithControlledAccessToAst( - shouldFail: Boolean, allowedFile: VirtualFile, - project: Project, disposable: Disposable, testBody: () -> Unit + shouldFail: Boolean, allowedFile: VirtualFile, + project: Project, disposable: Disposable, testBody: () -> Unit ) { testWithControlledAccessToAst(shouldFail, listOf(allowedFile), project, disposable, testBody) } fun testWithControlledAccessToAst( - shouldFail: Boolean, allowedFiles: List, - project: Project, disposable: Disposable, testBody: () -> Unit + shouldFail: Boolean, allowedFiles: List, + project: Project, disposable: Disposable, testBody: () -> Unit ) { val filter = wrapWithDirectiveAllow { file -> file.fileType != KotlinFileType.INSTANCE || file in allowedFiles @@ -56,15 +45,12 @@ object AstAccessControl { execute(shouldFail, project, disposable, filter, testBody) } - fun wrapWithDirectiveAllow(allowedFiles: (VirtualFile) -> Boolean): (VirtualFile) -> Boolean { - return { file -> - if (allowedFiles(file)) { - false - } - else { - val text = VfsUtilCore.loadText(file) - !InTextDirectivesUtils.isDirectiveDefined(text, ALLOW_AST_ACCESS_DIRECTIVE) - } + fun wrapWithDirectiveAllow(allowedFiles: (VirtualFile) -> Boolean): (VirtualFile) -> Boolean = { file -> + if (allowedFiles(file)) { + false + } else { + val text = VfsUtilCore.loadText(file) + !InTextDirectivesUtils.isDirectiveDefined(text, ALLOW_AST_ACCESS_DIRECTIVE) } } @@ -72,8 +58,10 @@ object AstAccessControl { return execute(shouldFail, fixture.project, disposable, { file -> file != fixture.file.virtualFile }, testBody) } - private fun execute(shouldFail: Boolean, project: Project, disposable: Disposable, - forbidAstAccessFilter: (VirtualFile) -> Boolean, testBody: () -> T): T? { + private fun execute( + shouldFail: Boolean, project: Project, disposable: Disposable, + forbidAstAccessFilter: (VirtualFile) -> Boolean, testBody: () -> T + ): T? { val manager = (PsiManager.getInstance(project) as PsiManagerImpl) manager.setAssertOnFileLoadingFilter(VirtualFileFilter { file -> forbidAstAccessFilter(file) }, disposable) @@ -81,20 +69,20 @@ object AstAccessControl { try { val result = testBody() if (shouldFail) { - fail("This failure means that that a test that should fail (by triggering ast switch) in fact did not.\n" + - "This could happen for the following reasons:\n" + - "1. This kind of operation no longer trigger ast switch, choose better indicator test case." + - "2. Test is now misconfigured and no longer checks for ast switch, reconfigure the test.") + fail( + "This failure means that that a test that should fail (by triggering ast switch) in fact did not.\n" + + "This could happen for the following reasons:\n" + + "1. This kind of operation no longer trigger ast switch, choose better indicator test case." + + "2. Test is now misconfigured and no longer checks for ast switch, reconfigure the test." + ) } return result - } - catch (e: Throwable) { + } catch (e: Throwable) { if (!shouldFail) { throw e } - } - finally { + } finally { manager.setAssertOnFileLoadingFilter(VirtualFileFilter.NONE, disposable) } diff --git a/idea/idea-test-framework/test/org/jetbrains/kotlin/idea/test/ConfigLibraryUtil.kt b/idea/idea-test-framework/test/org/jetbrains/kotlin/idea/test/ConfigLibraryUtil.kt index 0edb1032d4a..11211344307 100644 --- a/idea/idea-test-framework/test/org/jetbrains/kotlin/idea/test/ConfigLibraryUtil.kt +++ b/idea/idea-test-framework/test/org/jetbrains/kotlin/idea/test/ConfigLibraryUtil.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.test @@ -43,10 +32,10 @@ import kotlin.test.assertNotNull * Helper for configuring kotlin runtime in tested project. */ object ConfigLibraryUtil { - private val DEFAULT_JAVA_RUNTIME_LIB_NAME = "JAVA_RUNTIME_LIB_NAME" - private val DEFAULT_KOTLIN_TEST_LIB_NAME = "KOTLIN_TEST_LIB_NAME" - private val DEFAULT_KOTLIN_JS_STDLIB_NAME = "KOTLIN_JS_STDLIB_NAME" - private val DEFAULT_KOTLIN_COMMON_STDLIB_NAME = "KOTLIN_COMMON_STDLIB_NAME" + private const val DEFAULT_JAVA_RUNTIME_LIB_NAME = "JAVA_RUNTIME_LIB_NAME" + private const val DEFAULT_KOTLIN_TEST_LIB_NAME = "KOTLIN_TEST_LIB_NAME" + private const val DEFAULT_KOTLIN_JS_STDLIB_NAME = "KOTLIN_JS_STDLIB_NAME" + private const val DEFAULT_KOTLIN_COMMON_STDLIB_NAME = "KOTLIN_COMMON_STDLIB_NAME" private fun getKotlinRuntimeLibEditor(libName: String, library: File): NewLibraryEditor { val editor = NewLibraryEditor() @@ -63,9 +52,13 @@ object ConfigLibraryUtil { fun configureKotlinJsRuntimeAndSdk(module: Module, sdk: Sdk) { configureSdk(module, sdk) - addLibrary(getKotlinRuntimeLibEditor(DEFAULT_KOTLIN_JS_STDLIB_NAME, - PathUtil.kotlinPathsForDistDirectory.jsStdLibJarPath), module, - JSLibraryKind) + addLibrary( + getKotlinRuntimeLibEditor( + DEFAULT_KOTLIN_JS_STDLIB_NAME, + PathUtil.kotlinPathsForDistDirectory.jsStdLibJarPath + ), module, + JSLibraryKind + ) } fun configureKotlinCommonRuntime(module: Module) { @@ -222,7 +215,7 @@ object ConfigLibraryUtil { } } - if (!libraryNames.isEmpty()) throw AssertionError("Couldn't find the following libraries: " + libraryNames) + if (libraryNames.isNotEmpty()) throw AssertionError("Couldn't find the following libraries: " + libraryNames) } fun configureLibrariesByDirective(module: Module, rootPath: String, fileText: String) { diff --git a/idea/idea-test-framework/test/org/jetbrains/kotlin/idea/test/DirectiveBasedActionUtils.kt b/idea/idea-test-framework/test/org/jetbrains/kotlin/idea/test/DirectiveBasedActionUtils.kt index f0f290dd24b..5cef91e6daa 100644 --- a/idea/idea-test-framework/test/org/jetbrains/kotlin/idea/test/DirectiveBasedActionUtils.kt +++ b/idea/idea-test-framework/test/org/jetbrains/kotlin/idea/test/DirectiveBasedActionUtils.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -48,9 +48,11 @@ object DirectiveBasedActionUtils { val actualActions = availableActions.map { it.text }.sorted() - UsefulTestCase.assertOrderedEquals("Some unexpected actions available at current position. Use // ACTION: directive", - filterOutIrrelevantActions(actualActions), - expectedActions) + UsefulTestCase.assertOrderedEquals( + "Some unexpected actions available at current position. Use // ACTION: directive", + filterOutIrrelevantActions(actualActions), + expectedActions + ) } //TODO: hack, implemented because irrelevant actions behave in different ways on build server and locally @@ -62,26 +64,26 @@ object DirectiveBasedActionUtils { private fun isIrrelevantAction(action: String) = action.isEmpty() || IRRELEVANT_ACTION_PREFIXES.any { action.startsWith(it) } private val IRRELEVANT_ACTION_PREFIXES = listOf( - "Disable ", - "Edit intention settings", - "Edit inspection profile setting", - "Inject language or reference", - "Suppress '", - "Run inspection on", - "Inspection '", - "Suppress for ", - "Suppress all ", - "Edit cleanup profile settings", - "Fix all '", - "Cleanup code", - "Go to ", - "Show local variable type hints", - "Show function return type hints", - "Show property type hints", - "Show parameter type hints", - "Show argument name hints", - "Show hints for suspending calls", - "Add 'JUnit", - "Add 'testng" + "Disable ", + "Edit intention settings", + "Edit inspection profile setting", + "Inject language or reference", + "Suppress '", + "Run inspection on", + "Inspection '", + "Suppress for ", + "Suppress all ", + "Edit cleanup profile settings", + "Fix all '", + "Cleanup code", + "Go to ", + "Show local variable type hints", + "Show function return type hints", + "Show property type hints", + "Show parameter type hints", + "Show argument name hints", + "Show hints for suspending calls", + "Add 'JUnit", + "Add 'testng" ) } diff --git a/idea/idea-test-framework/test/org/jetbrains/kotlin/idea/test/KotlinLightJava9ModulesCodeInsightFixtureTestCase.kt b/idea/idea-test-framework/test/org/jetbrains/kotlin/idea/test/KotlinLightJava9ModulesCodeInsightFixtureTestCase.kt index c0f1ecafa87..b835f065bee 100644 --- a/idea/idea-test-framework/test/org/jetbrains/kotlin/idea/test/KotlinLightJava9ModulesCodeInsightFixtureTestCase.kt +++ b/idea/idea-test-framework/test/org/jetbrains/kotlin/idea/test/KotlinLightJava9ModulesCodeInsightFixtureTestCase.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.test @@ -32,19 +21,21 @@ abstract class KotlinLightJava9ModulesCodeInsightFixtureTestCase : KotlinLightCo } protected fun addFile(path: String, text: String, module: ModuleDescriptor = ModuleDescriptor.MAIN): VirtualFile = - VfsTestUtil.createFile(module.root(), path, text) + VfsTestUtil.createFile(module.root(), path, text) - protected fun addKotlinFile(path: String, @Language("kotlin") text: String, module: ModuleDescriptor = ModuleDescriptor.MAIN): VirtualFile = - addFile(path, text.toTestData(), module) + protected fun addKotlinFile( + path: String, + @Language("kotlin") text: String, + module: ModuleDescriptor = ModuleDescriptor.MAIN + ): VirtualFile = addFile(path, text.toTestData(), module) protected fun addJavaFile(path: String, @Language("java") text: String, module: ModuleDescriptor = ModuleDescriptor.MAIN): VirtualFile = - addFile(path, text.toTestData(), module) + addFile(path, text.toTestData(), module) protected fun moduleInfo(@Language("JAVA") text: String, module: ModuleDescriptor = ModuleDescriptor.MAIN) = - addFile("module-info.java", text.toTestData(), module) + addFile("module-info.java", text.toTestData(), module) - protected fun checkModuleInfo(@Language("JAVA") text: String) = - myFixture.checkResult("module-info.java", text.toTestData(), false) + protected fun checkModuleInfo(@Language("JAVA") text: String) = myFixture.checkResult("module-info.java", text.toTestData(), false) } private const val IDENTIFIER_CARET = "CARET" @@ -53,4 +44,4 @@ private const val COMMENT_CARET = "/*CARET*/" private val ADDITIONAL_CARET_MARKERS = arrayOf(IDENTIFIER_CARET, COMMENT_CARET_CHAR, COMMENT_CARET) private fun String.toTestData(): String = - ADDITIONAL_CARET_MARKERS.fold(trimIndent()) { result, marker -> result.replace(marker, EditorTestUtil.CARET_TAG, ignoreCase = true) } \ No newline at end of file + ADDITIONAL_CARET_MARKERS.fold(trimIndent()) { result, marker -> result.replace(marker, EditorTestUtil.CARET_TAG, ignoreCase = true) } \ No newline at end of file diff --git a/idea/idea-test-framework/test/org/jetbrains/kotlin/idea/test/KotlinLightPlatformCodeInsightFixtureTestCase.kt b/idea/idea-test-framework/test/org/jetbrains/kotlin/idea/test/KotlinLightPlatformCodeInsightFixtureTestCase.kt index 8dd930cce32..cdecd53df5b 100644 --- a/idea/idea-test-framework/test/org/jetbrains/kotlin/idea/test/KotlinLightPlatformCodeInsightFixtureTestCase.kt +++ b/idea/idea-test-framework/test/org/jetbrains/kotlin/idea/test/KotlinLightPlatformCodeInsightFixtureTestCase.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.test @@ -25,7 +14,7 @@ import org.jetbrains.kotlin.test.TestMetadata import java.io.File import kotlin.reflect.full.findAnnotation -abstract class KotlinLightPlatformCodeInsightFixtureTestCase: LightPlatformCodeInsightFixtureTestCase() { +abstract class KotlinLightPlatformCodeInsightFixtureTestCase : LightPlatformCodeInsightFixtureTestCase() { override fun setUp() { super.setUp() (StartupManager.getInstance(project) as StartupManagerImpl).runPostStartupActivities() diff --git a/idea/idea-test-framework/test/org/jetbrains/kotlin/idea/test/KotlinMultiFileTestCase.kt b/idea/idea-test-framework/test/org/jetbrains/kotlin/idea/test/KotlinMultiFileTestCase.kt index 9131d186432..09dc47a222e 100644 --- a/idea/idea-test-framework/test/org/jetbrains/kotlin/idea/test/KotlinMultiFileTestCase.kt +++ b/idea/idea-test-framework/test/org/jetbrains/kotlin/idea/test/KotlinMultiFileTestCase.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.test @@ -43,20 +32,22 @@ abstract class KotlinMultiFileTestCase : MultiFileTestCase() { } } - protected fun getTestDirName(lowercaseFirstLetter : Boolean) : String { + protected fun getTestDirName(lowercaseFirstLetter: Boolean): String { val testName = getTestName(lowercaseFirstLetter) val endIndex = testName.lastIndexOf('_') if (endIndex < 0) return testName return testName.substring(0, endIndex).replace('_', '/') } - protected fun doTestCommittingDocuments(action : (VirtualFile, VirtualFile?) -> Unit) { - super.doTest({ rootDir, rootAfter -> - action(rootDir, rootAfter) + protected fun doTestCommittingDocuments(action: (VirtualFile, VirtualFile?) -> Unit) { + super.doTest( + { rootDir, rootAfter -> + action(rootDir, rootAfter) - PsiDocumentManager.getInstance(project!!).commitAllDocuments() - FileDocumentManager.getInstance().saveAllDocuments() - }, getTestDirName(true)) + PsiDocumentManager.getInstance(project!!).commitAllDocuments() + FileDocumentManager.getInstance().saveAllDocuments() + }, getTestDirName(true) + ) } override fun prepareProject(rootDir: VirtualFile) { @@ -64,22 +55,21 @@ abstract class KotlinMultiFileTestCase : MultiFileTestCase() { val model = ModuleManager.getInstance(project).modifiableModel VfsUtilCore.visitChildrenRecursively( - rootDir, - object : VirtualFileVisitor() { - override fun visitFile(file: VirtualFile): Boolean { - if (!file.isDirectory && file.name.endsWith(ModuleFileType.DOT_DEFAULT_EXTENSION)) { - model.loadModule(file.path) - return false - } - - return true + rootDir, + object : VirtualFileVisitor() { + override fun visitFile(file: VirtualFile): Boolean { + if (!file.isDirectory && file.name.endsWith(ModuleFileType.DOT_DEFAULT_EXTENSION)) { + model.loadModule(file.path) + return false } + + return true } + } ) runWriteAction { model.commit() } - } - else { + } else { PsiTestUtil.addSourceContentToRoots(myModule, rootDir) } } diff --git a/idea/idea-test-framework/test/org/jetbrains/kotlin/idea/test/KotlinMultiModuleJava9ProjectDescriptor.kt b/idea/idea-test-framework/test/org/jetbrains/kotlin/idea/test/KotlinMultiModuleJava9ProjectDescriptor.kt index 00249f3d6eb..93d5f280ee8 100644 --- a/idea/idea-test-framework/test/org/jetbrains/kotlin/idea/test/KotlinMultiModuleJava9ProjectDescriptor.kt +++ b/idea/idea-test-framework/test/org/jetbrains/kotlin/idea/test/KotlinMultiModuleJava9ProjectDescriptor.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.test @@ -58,10 +47,9 @@ object KotlinMultiModuleJava9ProjectDescriptor : DefaultLightProjectDescriptor() M7("${TEST_MODULE_NAME}_m7", "src_m7"); fun root(): VirtualFile = - if (this == MAIN) LightPlatformTestCase.getSourceRoot() else TempFileSystem.getInstance().findFileByPath("/$rootName")!! + if (this == MAIN) LightPlatformTestCase.getSourceRoot() else TempFileSystem.getInstance().findFileByPath("/$rootName")!! - fun testRoot(): VirtualFile? = - if (this == MAIN) TempFileSystem.getInstance().findFileByPath("/test_src")!! else null + fun testRoot(): VirtualFile? = if (this == MAIN) TempFileSystem.getInstance().findFileByPath("/test_src")!! else null } override fun getSdk(): Sdk = PluginTestCaseBase.jdk(TestJdkKind.FULL_JDK_9) @@ -110,9 +98,9 @@ object KotlinMultiModuleJava9ProjectDescriptor : DefaultLightProjectDescriptor() fun cleanupSourceRoots() = runWriteAction { ModuleDescriptor.values().asSequence() - .filter { it != ModuleDescriptor.MAIN } - .flatMap { it.root().children.asSequence() } - .plus(ModuleDescriptor.MAIN.testRoot()!!.children.asSequence()) - .forEach { it.delete(this) } + .filter { it != ModuleDescriptor.MAIN } + .flatMap { it.root().children.asSequence() } + .plus(ModuleDescriptor.MAIN.testRoot()!!.children.asSequence()) + .forEach { it.delete(this) } } } \ No newline at end of file diff --git a/idea/jvm-debugger/eval4j/src/org/jetbrains/eval4j/interpreter.kt b/idea/jvm-debugger/eval4j/src/org/jetbrains/eval4j/interpreter.kt index b21457d1179..a27c15204a9 100644 --- a/idea/jvm-debugger/eval4j/src/org/jetbrains/eval4j/interpreter.kt +++ b/idea/jvm-debugger/eval4j/src/org/jetbrains/eval4j/interpreter.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.eval4j @@ -182,7 +171,11 @@ class SingleInstructionInterpreter(private val eval: Eval) : Interpreter( when { value == NULL_VALUE -> NULL_VALUE eval.isInstanceOf(value, targetType) -> ObjectValue(value.obj(), targetType) - else -> throwInterpretingException(ClassCastException("${value.asmType.className} cannot be cast to ${targetType.className}")) + else -> throwInterpretingException( + ClassCastException( + "${value.asmType.className} cannot be cast to ${targetType.className}" + ) + ) } } diff --git a/idea/jvm-debugger/eval4j/src/org/jetbrains/eval4j/jdi/jdiEval.kt b/idea/jvm-debugger/eval4j/src/org/jetbrains/eval4j/jdi/jdiEval.kt index b17f3e559da..3a65deec9ec 100644 --- a/idea/jvm-debugger/eval4j/src/org/jetbrains/eval4j/jdi/jdiEval.kt +++ b/idea/jvm-debugger/eval4j/src/org/jetbrains/eval4j/jdi/jdiEval.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.eval4j.jdi @@ -444,10 +433,13 @@ open class JDIEval( listOf(instance, mirrorOfArgs(args)) ) - if (methodDesc.returnType.sort != Type.OBJECT && methodDesc.returnType.sort != Type.ARRAY && methodDesc.returnType.sort != Type.VOID) { - return unboxType(invocationResult, methodDesc.returnType) - } - return invocationResult + return if (methodDesc.returnType.sort != Type.OBJECT && + methodDesc.returnType.sort != Type.ARRAY && + methodDesc.returnType.sort != Type.VOID + ) + unboxType(invocationResult, methodDesc.returnType) + else + invocationResult } private fun mirrorOfArgs(args: List): Value { diff --git a/idea/jvm-debugger/eval4j/test/org/jetbrains/eval4j/jdi/test/jdiTest.kt b/idea/jvm-debugger/eval4j/test/org/jetbrains/eval4j/jdi/test/jdiTest.kt index 65d3242ea47..e1614761e7c 100644 --- a/idea/jvm-debugger/eval4j/test/org/jetbrains/eval4j/jdi/test/jdiTest.kt +++ b/idea/jvm-debugger/eval4j/test/org/jetbrains/eval4j/jdi/test/jdiTest.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.eval4j.jdi.test @@ -57,8 +46,8 @@ fun suite(): TestSuite { req.enable() val latch = CountDownLatch(1) - var classLoader : ClassLoaderReference? = null - var thread : ThreadReference? = null + var classLoader: ClassLoaderReference? = null + var thread: ThreadReference? = null Thread { val eventQueue = vm.eventQueue() @@ -89,7 +78,8 @@ fun suite(): TestSuite { break@mainLoop } - else -> {} + else -> { + } } } } @@ -101,8 +91,7 @@ fun suite(): TestSuite { var remainingTests = AtomicInteger(0) - val suite = buildTestSuite { - methodNode, ownerClass, expected -> + val suite = buildTestSuite { methodNode, ownerClass, expected -> remainingTests.incrementAndGet() object : TestCase(getTestName(methodNode.name)) { @@ -112,47 +101,45 @@ fun suite(): TestSuite { val args = if ((methodNode.access and Opcodes.ACC_STATIC) == 0) { // Instance method val newInstance = eval.newInstance(Type.getType(ownerClass)) - val thisValue = eval.invokeMethod(newInstance, MethodDescription(ownerClass.name, "", "()V", false), listOf(), true) + val thisValue = + eval.invokeMethod(newInstance, MethodDescription(ownerClass.name, "", "()V", false), listOf(), true) listOf(thisValue) - } - else { + } else { listOf() } val value = interpreterLoop( - methodNode, - makeInitialFrame(methodNode, args), - eval + methodNode, + makeInitialFrame(methodNode, args), + eval ) fun ObjectReference?.callToString(): String? { if (this == null) return "null" return (eval.invokeMethod( - this.asValue(), - MethodDescription( - "java/lang/Object", - "toString", - "()Ljava/lang/String;", - false - ), - listOf()).jdiObj as StringReference).value() + this.asValue(), + MethodDescription( + "java/lang/Object", + "toString", + "()Ljava/lang/String;", + false + ), + listOf() + ).jdiObj as StringReference).value() } try { if (expected is ValueReturned && value is ValueReturned && value.result is ObjectValue) { assertEquals(expected.result.obj().toString(), value.result.jdiObj.callToString()) - } - else if (expected is ExceptionThrown && value is ExceptionThrown) { + } else if (expected is ExceptionThrown && value is ExceptionThrown) { val valueObj = value.exception.obj() val actual = if (valueObj is ObjectReference) valueObj.callToString() else valueObj.toString() assertEquals(expected.exception.obj().toString(), actual) - } - else { + } else { assertEquals(expected, value) } - } - finally { + } finally { if (remainingTests.decrementAndGet() == 0) vm.resume() } diff --git a/idea/jvm-debugger/eval4j/test/org/jetbrains/eval4j/test/main.kt b/idea/jvm-debugger/eval4j/test/org/jetbrains/eval4j/test/main.kt index ce395031bfc..4d4eaabf3b0 100644 --- a/idea/jvm-debugger/eval4j/test/org/jetbrains/eval4j/test/main.kt +++ b/idea/jvm-debugger/eval4j/test/org/jetbrains/eval4j/test/main.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.eval4j.test @@ -28,45 +17,42 @@ import org.junit.Assert.assertTrue import java.lang.reflect.* import java.lang.reflect.Array as JArray -fun suite(): TestSuite = buildTestSuite { - methodNode, ownerClass, expected -> +fun suite(): TestSuite = buildTestSuite { methodNode, ownerClass, expected -> object : TestCase(getTestName(methodNode.name)) { - override fun runTest() { - if (!isIgnored(methodNode)) { - val value = interpreterLoop( - methodNode, - initFrame( - ownerClass.getInternalName(), - methodNode - ), - REFLECTION_EVAL - ) - - if (expected is ExceptionThrown && value is ExceptionThrown) { - assertEquals(expected.exception.toString(), value.exception.toString()) - } - else { - assertEquals(expected.toString(), value.toString()) - } + override fun runTest() { + if (!isIgnored(methodNode)) { + val value = interpreterLoop( + methodNode, + initFrame( + ownerClass.getInternalName(), + methodNode + ), + REFLECTION_EVAL + ) + + if (expected is ExceptionThrown && value is ExceptionThrown) { + assertEquals(expected.exception.toString(), value.exception.toString()) + } else { + assertEquals(expected.toString(), value.toString()) } } - - private fun isIgnored(methodNode: MethodNode): Boolean { - return methodNode.visibleAnnotations?.any { - val annotationDesc = it.desc - annotationDesc != null && - Type.getType(annotationDesc) == Type.getType(IgnoreInReflectionTests::class.java) - } ?: false - } } + + private fun isIgnored(methodNode: MethodNode): Boolean { + return methodNode.visibleAnnotations?.any { + val annotationDesc = it.desc + annotationDesc != null && Type.getType(annotationDesc) == Type.getType(IgnoreInReflectionTests::class.java) + } ?: false + } + } } fun Class<*>.getInternalName(): String = Type.getType(this).internalName fun initFrame( - owner: String, - m: MethodNode + owner: String, + m: MethodNode ): Frame { val current = Frame(m.maxLocals, m.maxStack) current.setReturn(makeNotInitializedValue(Type.getReturnType(m.desc))) @@ -80,7 +66,7 @@ fun initFrame( } val args = Type.getArgumentTypes(m.desc) - for (i in 0..args.size - 1) { + for (i in args.indices) { current.setLocal(local++, makeNotInitializedValue(args[i])) if (args[i].size == 2) { current.setLocal(local++, NOT_A_VALUE) @@ -198,12 +184,10 @@ object REFLECTION_EVAL : Eval { try { try { return f() + } catch (ite: InvocationTargetException) { + throw ite.cause ?: ite } - catch (ite: InvocationTargetException) { - throw ite.cause ?: ite - } - } - catch (e: Throwable) { + } catch (e: Throwable) { throw ThrownFromEvaluatedCodeException(ObjectValue(e, Type.getType(e::class.java))) } } @@ -211,14 +195,14 @@ object REFLECTION_EVAL : Eval { override fun getStaticField(fieldDesc: FieldDescription): Value { val field = findStaticField(fieldDesc) - val result = mayThrow {field.get(null)} + val result = mayThrow { field.get(null) } return objectToValue(result, fieldDesc.fieldType) } override fun setStaticField(fieldDesc: FieldDescription, newValue: Value) { val field = findStaticField(fieldDesc) val obj = newValue.obj(fieldDesc.fieldType) - mayThrow {field.set(null, obj)} + mayThrow { field.set(null, obj) } } fun findStaticField(fieldDesc: FieldDescription): Field { @@ -234,7 +218,7 @@ object REFLECTION_EVAL : Eval { val method = findClass(methodDesc).findMethod(methodDesc) assertNotNull("Method not found: $methodDesc", method) val args = mapArguments(arguments, methodDesc.parameterTypes).toTypedArray() - val result = mayThrow {method!!.invoke(null, *args)} + val result = mayThrow { method!!.invoke(null, *args) } return objectToValue(result, methodDesc.returnType) } @@ -250,7 +234,7 @@ object REFLECTION_EVAL : Eval { val obj = instance.obj().checkNull() val field = findInstanceField(obj, fieldDesc) - return objectToValue(mayThrow {field.get(obj)}, fieldDesc.fieldType) + return objectToValue(mayThrow { field.get(obj) }, fieldDesc.fieldType) } override fun setField(instance: Value, fieldDesc: FieldDescription, newValue: Value) { @@ -258,7 +242,7 @@ object REFLECTION_EVAL : Eval { val field = findInstanceField(obj, fieldDesc) val newObj = newValue.obj(fieldDesc.fieldType) - mayThrow {field.set(obj, newObj)} + mayThrow { field.set(obj, newObj) } } fun findInstanceField(obj: Any, fieldDesc: FieldDescription): Field { @@ -277,11 +261,10 @@ object REFLECTION_EVAL : Eval { val ctor = _class.findConstructor(methodDesc) assertNotNull("Constructor not found: $methodDesc", ctor) val args = mapArguments(arguments, methodDesc.parameterTypes).toTypedArray() - val result = mayThrow {ctor!!.newInstance(*args)} + val result = mayThrow { ctor!!.newInstance(*args) } instance.value = result return objectToValue(result, instance.asmType) - } - else { + } else { // TODO throw UnsupportedOperationException("invokespecial is not suported in reflection eval") } @@ -290,7 +273,7 @@ object REFLECTION_EVAL : Eval { val method = obj::class.java.findMethod(methodDesc) assertNotNull("Method not found: $methodDesc", method) val args = mapArguments(arguments, methodDesc.parameterTypes).toTypedArray() - val result = mayThrow {method!!.invoke(obj, *args)} + val result = mayThrow { method!!.invoke(obj, *args) } return objectToValue(result, methodDesc.returnType) } diff --git a/idea/jvm-debugger/eval4j/test/org/jetbrains/eval4j/test/suiteBuilder.kt b/idea/jvm-debugger/eval4j/test/org/jetbrains/eval4j/test/suiteBuilder.kt index dd5f7237e31..56aa208c718 100644 --- a/idea/jvm-debugger/eval4j/test/org/jetbrains/eval4j/test/suiteBuilder.kt +++ b/idea/jvm-debugger/eval4j/test/org/jetbrains/eval4j/test/suiteBuilder.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.eval4j.test @@ -29,23 +18,26 @@ import org.jetbrains.org.objectweb.asm.Opcodes.API_VERSION import org.jetbrains.org.objectweb.asm.Type import org.jetbrains.org.objectweb.asm.tree.MethodNode import java.lang.reflect.Modifier -import java.lang.reflect.Array as JArray fun buildTestSuite( - create: (MethodNode, Class<*>, InterpreterResult?) -> TestCase + create: (MethodNode, Class<*>, InterpreterResult?) -> TestCase ): TestSuite { val suite = TestSuite() val ownerClass = TestData::class.java ownerClass.classLoader!!.getResourceAsStream(ownerClass.getInternalName() + ".class")!!.use { inputStream -> ClassReader(inputStream).accept(object : ClassVisitor(API_VERSION) { - override fun visitMethod(access: Int, name: String, desc: String, signature: String?, exceptions: Array?): MethodVisitor? { - return object : MethodNode(API_VERSION, access, name, desc, signature, exceptions) { - override fun visitEnd() { - val testCase = buildTestCase(ownerClass, this, create) - if (testCase != null) { - suite.addTest(testCase) - } + override fun visitMethod( + access: Int, + name: String, + desc: String, + signature: String?, + exceptions: Array? + ): MethodVisitor? = object : MethodNode(API_VERSION, access, name, desc, signature, exceptions) { + override fun visitEnd() { + val testCase = buildTestCase(ownerClass, this, create) + if (testCase != null) { + suite.addTest(testCase) } } } @@ -55,32 +47,33 @@ fun buildTestSuite( return suite } -private fun buildTestCase(ownerClass: Class, - methodNode: MethodNode, - create: (MethodNode, Class, InterpreterResult?) -> TestCase): TestCase? { +private fun buildTestCase( + ownerClass: Class, + methodNode: MethodNode, + create: (MethodNode, Class, InterpreterResult?) -> TestCase +): TestCase? { var expected: InterpreterResult? = null for (method in ownerClass.declaredMethods) { if (method.name == methodNode.name) { val isStatic = (method.modifiers and Modifier.STATIC) != 0 - if (method.parameterTypes!!.size > 0) { + if (method.parameterTypes!!.isNotEmpty()) { println("Skipping method with parameters: $method") - } - else if (!isStatic && !method.name!!.startsWith("test")) { + } else if (!isStatic && !method.name!!.startsWith("test")) { println("Skipping instance method (should be started with 'test') : $method") - } - else { + } else { method.isAccessible = true try { val result = method.invoke(if (isStatic) null else ownerClass.newInstance()) val returnType = Type.getType(method.returnType!!) expected = ValueReturned(objectToValue(result, returnType)) - } - catch (e: UnsupportedOperationException) { + } catch (e: UnsupportedOperationException) { println("Skipping $method: $e") - } - catch (e: Throwable) { + } catch (e: Throwable) { val cause = e.cause ?: e - expected = ExceptionThrown(objectToValue(cause, Type.getType(cause::class.java)) as ObjectValue, ExceptionThrown.ExceptionKind.FROM_EVALUATOR) + expected = ExceptionThrown( + objectToValue(cause, Type.getType(cause::class.java)) as ObjectValue, + ExceptionThrown.ExceptionKind.FROM_EVALUATOR + ) } } } diff --git a/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/AsyncStackTraceContext.kt b/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/AsyncStackTraceContext.kt index d50a04091b5..85547008244 100644 --- a/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/AsyncStackTraceContext.kt +++ b/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/AsyncStackTraceContext.kt @@ -13,9 +13,9 @@ import com.intellij.debugger.jdi.GeneratedLocation import com.intellij.debugger.memory.utils.StackFrameItem import com.intellij.debugger.ui.impl.watch.ValueDescriptorImpl import com.intellij.xdebugger.frame.XNamedValue -import org.jetbrains.kotlin.idea.debugger.evaluate.ExecutionContext import com.sun.jdi.* import org.jetbrains.kotlin.codegen.coroutines.CONTINUATION_VARIABLE_NAME +import org.jetbrains.kotlin.idea.debugger.evaluate.ExecutionContext class AsyncStackTraceContext( val context: ExecutionContext, @@ -23,7 +23,7 @@ class AsyncStackTraceContext( private val debugMetadataKtType: ClassType ) { - fun getAsyncStackTraceForSuspendLambda() : List? { + fun getAsyncStackTraceForSuspendLambda(): List? { if (method.name() != "invokeSuspend" || method.signature() != "(Ljava/lang/Object;)Ljava/lang/Object;") { return null } diff --git a/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/InlineCallableUsagesSearcher.kt b/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/InlineCallableUsagesSearcher.kt index a2db47361bd..186d7ebaf60 100644 --- a/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/InlineCallableUsagesSearcher.kt +++ b/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/InlineCallableUsagesSearcher.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.debugger @@ -43,15 +32,14 @@ import org.jetbrains.kotlin.resolve.inline.InlineUtil class InlineCallableUsagesSearcher(private val myDebugProcess: DebugProcess) { fun findInlinedCalls( - declaration: KtDeclaration, - alreadyVisited: Set, - bindingContext: BindingContext = KotlinDebuggerCaches.getOrCreateTypeMapper(declaration).bindingContext, - transformer: (PsiElement, Set) -> ComputedClassNames + declaration: KtDeclaration, + alreadyVisited: Set, + bindingContext: BindingContext = KotlinDebuggerCaches.getOrCreateTypeMapper(declaration).bindingContext, + transformer: (PsiElement, Set) -> ComputedClassNames ): ComputedClassNames { if (!checkIfInline(declaration, bindingContext)) { return ComputedClassNames.EMPTY - } - else { + } else { val searchResult = hashSetOf() val declarationName = runReadAction { declaration.name } @@ -65,12 +53,12 @@ class InlineCallableUsagesSearcher(private val myDebugProcess: DebugProcess) { val applicationEx = ApplicationManagerEx.getApplicationEx() if (applicationEx.isDispatchThread) { isSuccess = ProgressManager.getInstance().runProcessWithProgressSynchronously( - task, - "Compute class names for declaration $declarationName", - true, - myDebugProcess.project) - } - else { + task, + "Compute class names for declaration $declarationName", + true, + myDebugProcess.project + ) + } else { try { ProgressManager.getInstance().runProcess(task, EmptyProgressIndicator()) } catch (e: InterruptedException) { @@ -80,8 +68,8 @@ class InlineCallableUsagesSearcher(private val myDebugProcess: DebugProcess) { if (!isSuccess) { XDebuggerManagerImpl.NOTIFICATION_GROUP.createNotification( - "Debugger can skip some executions of $declarationName because the computation of class names was interrupted", - MessageType.WARNING + "Debugger can skip some executions of $declarationName because the computation of class names was interrupted", + MessageType.WARNING ).notify(myDebugProcess.project) } @@ -119,9 +107,9 @@ class InlineCallableUsagesSearcher(private val myDebugProcess: DebugProcess) { val virtualFile = runReadAction { inlineDeclaration.containingFile.virtualFile } return if (virtualFile != null && ProjectRootsUtil.isLibraryFile(myDebugProcess.project, virtualFile)) { myDebugProcess.searchScope.uniteWith( - KotlinSourceFilterScope.librarySources(GlobalSearchScope.allScope(myDebugProcess.project), myDebugProcess.project)) - } - else { + KotlinSourceFilterScope.librarySources(GlobalSearchScope.allScope(myDebugProcess.project), myDebugProcess.project) + ) + } else { myDebugProcess.searchScope } } diff --git a/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/KotlinAlternativeSourceNotificationProvider.kt b/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/KotlinAlternativeSourceNotificationProvider.kt index 9db313d6183..16cdcd90574 100644 --- a/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/KotlinAlternativeSourceNotificationProvider.kt +++ b/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/KotlinAlternativeSourceNotificationProvider.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.debugger @@ -40,7 +29,8 @@ import com.intellij.xdebugger.impl.ui.DebuggerUIUtil import org.jetbrains.kotlin.idea.stubindex.PackageIndexUtil.findFilesWithExactPackage import org.jetbrains.kotlin.psi.KtFile -class KotlinAlternativeSourceNotificationProvider(private val myProject: Project) : EditorNotifications.Provider() { +class KotlinAlternativeSourceNotificationProvider(private val myProject: Project) : + EditorNotifications.Provider() { override fun getKey(): Key { return KEY } @@ -69,9 +59,11 @@ class KotlinAlternativeSourceNotificationProvider(private val myProject: Project val packageFqName = ktFile.packageFqName val fileName = ktFile.name - val alternativeKtFiles = findFilesWithExactPackage(packageFqName, GlobalSearchScope.allScope(myProject), myProject).filterTo(HashSet()) { - it.name == fileName - } + val alternativeKtFiles = findFilesWithExactPackage( + packageFqName, + GlobalSearchScope.allScope(myProject), + myProject + ).filterTo(HashSet()) { it.name == fileName } FILE_PROCESSED_KEY.set(file, true) @@ -81,8 +73,7 @@ class KotlinAlternativeSourceNotificationProvider(private val myProject: Project val currentFirstAlternatives: Collection = listOf(ktFile) + alternativeKtFiles.filter { it != ktFile } - val frame = session.currentStackFrame - val locationDeclName: String? = when (frame) { + val locationDeclName: String? = when (val frame = session.currentStackFrame) { is JavaStackFrame -> { val location = frame.descriptor.location location?.declaringType()?.name() @@ -94,10 +85,10 @@ class KotlinAlternativeSourceNotificationProvider(private val myProject: Project } private class AlternativeSourceNotificationPanel( - alternatives: Collection, - project: Project, - file: VirtualFile, - locationDeclName: String? + alternatives: Collection, + project: Project, + file: VirtualFile, + locationDeclName: String? ) : EditorNotificationPanel() { private class ComboBoxFileElement(val ktFile: KtFile) { private val label: String by lazy(LazyThreadSafetyMode.NONE) { @@ -119,34 +110,34 @@ class KotlinAlternativeSourceNotificationProvider(private val myProject: Project val items = alternatives.map { ComboBoxFileElement(it) } myLinksPanel.add( - ComboBox(items.toTypedArray()).apply { - addActionListener { - val context = DebuggerManagerEx.getInstanceEx(project).context - val session = context.debuggerSession - val ktFile = (selectedItem as ComboBoxFileElement).ktFile - val vFile = ktFile.containingFile.virtualFile + ComboBox(items.toTypedArray()).apply { + addActionListener { + val context = DebuggerManagerEx.getInstanceEx(project).context + val session = context.debuggerSession + val ktFile = (selectedItem as ComboBoxFileElement).ktFile + val vFile = ktFile.containingFile.virtualFile - when { - session != null && vFile != null -> - session.process.managerThread.schedule(object : DebuggerCommandImpl() { - override fun action() { - if (!StringUtil.isEmpty(locationDeclName)) { - DebuggerUtilsEx.setAlternativeSourceUrl(locationDeclName, vFile.url, project) - } - - DebuggerUIUtil.invokeLater { - FileEditorManager.getInstance(project).closeFile(file) - session.refresh(true) - } + when { + session != null && vFile != null -> + session.process.managerThread.schedule(object : DebuggerCommandImpl() { + override fun action() { + if (!StringUtil.isEmpty(locationDeclName)) { + DebuggerUtilsEx.setAlternativeSourceUrl(locationDeclName, vFile.url, project) } - }) - else -> { - FileEditorManager.getInstance(project).closeFile(file) - ktFile.navigate(true) - } + + DebuggerUIUtil.invokeLater { + FileEditorManager.getInstance(project).closeFile(file) + session.refresh(true) + } + } + }) + else -> { + FileEditorManager.getInstance(project).closeFile(file) + ktFile.navigate(true) } } - }) + } + }) createActionLabel("Disable") { DebuggerSettings.getInstance().SHOW_ALTERNATIVE_SOURCE = false diff --git a/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/KotlinDebuggerSettings.kt b/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/KotlinDebuggerSettings.kt index 47dac6d41cc..ff7c6c45034 100644 --- a/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/KotlinDebuggerSettings.kt +++ b/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/KotlinDebuggerSettings.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -29,22 +29,26 @@ class KotlinDebuggerSettings : XDebuggerSettings("kotlin } } - override fun createConfigurables(category: DebuggerSettingsCategory): Collection { - return when (category) { - DebuggerSettingsCategory.STEPPING -> - listOf(SimpleConfigurable.create( - "reference.idesettings.debugger.kotlin.stepping", - "Kotlin", - KotlinSteppingConfigurableUi::class.java, - this)) - DebuggerSettingsCategory.DATA_VIEWS -> - listOf(SimpleConfigurable.create( - "reference.idesettings.debugger.kotlin.data.view", - "Kotlin", - KotlinDelegatedPropertyRendererConfigurableUi::class.java, - this)) - else -> listOf() - } + override fun createConfigurables(category: DebuggerSettingsCategory): Collection = when (category) { + DebuggerSettingsCategory.STEPPING -> + listOf( + SimpleConfigurable.create( + "reference.idesettings.debugger.kotlin.stepping", + "Kotlin", + KotlinSteppingConfigurableUi::class.java, + this + ) + ) + DebuggerSettingsCategory.DATA_VIEWS -> + listOf( + SimpleConfigurable.create( + "reference.idesettings.debugger.kotlin.data.view", + "Kotlin", + KotlinDelegatedPropertyRendererConfigurableUi::class.java, + this + ) + ) + else -> listOf() } override fun getState() = this diff --git a/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/KotlinFrameExtraVariablesProvider.kt b/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/KotlinFrameExtraVariablesProvider.kt index 77235779ff8..ccf142c3197 100644 --- a/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/KotlinFrameExtraVariablesProvider.kt +++ b/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/KotlinFrameExtraVariablesProvider.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.debugger @@ -50,9 +39,8 @@ class KotlinFrameExtraVariablesProvider : FrameExtraVariablesProvider { } override fun collectVariables( - sourcePosition: SourcePosition, evalContext: EvaluationContext, alreadyCollected: MutableSet): Set { - return runReadAction { findAdditionalExpressions(sourcePosition) } - } + sourcePosition: SourcePosition, evalContext: EvaluationContext, alreadyCollected: MutableSet + ): Set = runReadAction { findAdditionalExpressions(sourcePosition) } } private fun findAdditionalExpressions(position: SourcePosition): Set { @@ -99,7 +87,8 @@ private fun findAdditionalExpressions(position: SourcePosition): Set + private val myLineRange: TextRange, + private val myExpressions: MutableSet ) : KtTreeVisitorVoid() { override fun visitKtElement(element: KtElement) { @@ -160,8 +149,7 @@ private class VariablesCollector( val descriptor = context[BindingContext.REFERENCE_TARGET, expression] if (descriptor is PropertyDescriptor) { val getter = descriptor.getter - return (getter == null || context[BindingContext.DELEGATED_PROPERTY_RESOLVED_CALL, getter] == null) && - descriptor.compileTimeInitializer == null + return (getter == null || context[BindingContext.DELEGATED_PROPERTY_RESOLVED_CALL, getter] == null) && descriptor.compileTimeInitializer == null } return false } diff --git a/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/KotlinPositionManager.kt b/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/KotlinPositionManager.kt index 6512771a0b6..e023efe3c5a 100644 --- a/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/KotlinPositionManager.kt +++ b/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/KotlinPositionManager.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.debugger @@ -62,41 +51,39 @@ import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.resolve.inline.InlineUtil import org.jetbrains.kotlin.resolve.jvm.JvmClassName -import com.intellij.debugger.engine.DebuggerUtils as JDebuggerUtils class KotlinPositionManager(private val myDebugProcess: DebugProcess) : MultiRequestPositionManager, PositionManagerEx() { - private val allKotlinFilesScope = - object : DelegatingGlobalSearchScope( - KotlinSourceFilterScope.projectAndLibrariesSources(GlobalSearchScope.allScope(myDebugProcess.project), myDebugProcess.project) - ) { - private val projectIndex = ProjectRootManager.getInstance(myDebugProcess.project).fileIndex - private val scopeComparator = - Comparator.comparing(projectIndex::isInSourceContent) - .thenComparing(projectIndex::isInLibrarySource) - .thenComparing { file1, file2 -> super.compare(file1, file2) } + private val allKotlinFilesScope = object : DelegatingGlobalSearchScope( + KotlinSourceFilterScope.projectAndLibrariesSources(GlobalSearchScope.allScope(myDebugProcess.project), myDebugProcess.project) + ) { + private val projectIndex = ProjectRootManager.getInstance(myDebugProcess.project).fileIndex + private val scopeComparator = Comparator.comparing(projectIndex::isInSourceContent).thenComparing(projectIndex::isInLibrarySource) + .thenComparing { file1, file2 -> super.compare(file1, file2) } - override fun compare(file1: VirtualFile, file2: VirtualFile): Int { - return scopeComparator.compare(file1, file2) - } - } + override fun compare(file1: VirtualFile, file2: VirtualFile): Int = scopeComparator.compare(file1, file2) + } private val sourceSearchScopes: List = listOf( - myDebugProcess.searchScope, - allKotlinFilesScope + myDebugProcess.searchScope, + allKotlinFilesScope ) override fun getAcceptedFileTypes(): Set = KotlinFileTypeFactory.KOTLIN_FILE_TYPES_SET - override fun evaluateCondition(context: EvaluationContext, frame: StackFrameProxyImpl, location: Location, expression: String): ThreeState? { + override fun evaluateCondition( + context: EvaluationContext, + frame: StackFrameProxyImpl, + location: Location, + expression: String + ): ThreeState? { return ThreeState.UNSURE } - override fun createStackFrame(frame: StackFrameProxyImpl, debugProcess: DebugProcessImpl, location: Location): XStackFrame? { - if (location.isInKotlinSources()) { - return KotlinStackFrame(frame) - } - return null - } + override fun createStackFrame(frame: StackFrameProxyImpl, debugProcess: DebugProcessImpl, location: Location): XStackFrame? = + if (location.isInKotlinSources()) + KotlinStackFrame(frame) + else + null override fun getSourcePosition(location: Location?): SourcePosition? { if (location == null) throw NoDataException.INSTANCE @@ -120,13 +107,13 @@ class KotlinPositionManager(private val myDebugProcess: DebugProcess) : MultiReq val project = myDebugProcess.project val defaultPsiFile = DebuggerUtils.findSourceFileForClass( - project, sourceSearchScopes, javaClassName, javaSourceFileName, location) + project, sourceSearchScopes, javaClassName, javaSourceFileName, location + ) if (defaultPsiFile != null) { return SourcePosition.createFromLine(defaultPsiFile, 0) } - } - catch (e: AbsentInformationException) { + } catch (e: AbsentInformationException) { // ignored } } @@ -225,8 +212,8 @@ class KotlinPositionManager(private val myDebugProcess: DebugProcess) : MultiReq val elementAt = file.findElementAt(start) ?: return null val typeMapper = KotlinDebuggerCaches.getOrCreateTypeMapper(elementAt) - val currentLocationClassName = JvmClassName.byFqNameWithoutInnerClasses(FqName(currentLocationFqName)) - .internalName.replace('/', '.') + val currentLocationClassName = + JvmClassName.byFqNameWithoutInnerClasses(FqName(currentLocationFqName)).internalName.replace('/', '.') for (literal in literalsOrFunctions) { if (InlineUtil.isInlinedArgument(literal, typeMapper.bindingContext, true)) { @@ -236,9 +223,10 @@ class KotlinPositionManager(private val myDebugProcess: DebugProcess) : MultiReq continue } - val internalClassNames = DebuggerClassNameProvider(myDebugProcess, alwaysReturnLambdaParentClass = false) - .getOuterClassNamesForElement(literal.firstChild, emptySet()) - .classNames + val internalClassNames = DebuggerClassNameProvider( + myDebugProcess, + alwaysReturnLambdaParentClass = false + ).getOuterClassNamesForElement(literal.firstChild, emptySet()).classNames if (internalClassNames.any { it == currentLocationClassName }) { return literal @@ -255,12 +243,10 @@ class KotlinPositionManager(private val myDebugProcess: DebugProcess) : MultiReq if (location.declaringType().containsKotlinStrata()) { //replace is required for windows location.sourcePath().replace('\\', '/') - } - else { + } else { defaultInternalName(location) } - } - catch (e: AbsentInformationException) { + } catch (e: AbsentInformationException) { defaultInternalName(location) } @@ -307,7 +293,7 @@ class KotlinPositionManager(private val myDebugProcess: DebugProcess) : MultiReq try { if (myDebugProcess.isDexDebug()) { val inlineLocations = runReadAction { getLocationsOfInlinedLine(type, position, myDebugProcess.searchScope) } - if (!inlineLocations.isEmpty()) { + if (inlineLocations.isNotEmpty()) { return inlineLocations } } @@ -320,8 +306,7 @@ class KotlinPositionManager(private val myDebugProcess: DebugProcess) : MultiReq } return locations.filter { it.sourceName(KOTLIN_STRATA_NAME) == position.file.name } - } - catch (e: AbsentInformationException) { + } catch (e: AbsentInformationException) { throw NoDataException.INSTANCE } } @@ -340,8 +325,8 @@ class KotlinPositionManager(private val myDebugProcess: DebugProcess) : MultiReq val classNames = DebuggerClassNameProvider(myDebugProcess).getOuterClassNamesForPosition(position) classNames.flatMap { name -> listOfNotNull( - myDebugProcess.requestsManager.createClassPrepareRequest(requestor, name), - myDebugProcess.requestsManager.createClassPrepareRequest(requestor, "$name$*") + myDebugProcess.requestsManager.createClassPrepareRequest(requestor, name), + myDebugProcess.requestsManager.createClassPrepareRequest(requestor, "$name$*") ) } }) diff --git a/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/KotlinSourcePositionHighlighter.kt b/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/KotlinSourcePositionHighlighter.kt index 492347f92f9..bb0a83c46fd 100644 --- a/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/KotlinSourcePositionHighlighter.kt +++ b/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/KotlinSourcePositionHighlighter.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.debugger @@ -21,7 +10,7 @@ import com.intellij.debugger.engine.SourcePositionHighlighter import com.intellij.openapi.util.TextRange import org.jetbrains.kotlin.psi.KtFunctionLiteral -class KotlinSourcePositionHighlighter: SourcePositionHighlighter() { +class KotlinSourcePositionHighlighter : SourcePositionHighlighter() { override fun getHighlightRange(sourcePosition: SourcePosition?): TextRange? { val lambda = sourcePosition?.elementAt?.parent if (lambda is KtFunctionLiteral) { diff --git a/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/KotlinSourcePositionProvider.kt b/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/KotlinSourcePositionProvider.kt index 33f59042c1a..16d5f6578df 100644 --- a/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/KotlinSourcePositionProvider.kt +++ b/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/KotlinSourcePositionProvider.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.debugger @@ -25,14 +14,18 @@ import com.intellij.debugger.ui.tree.FieldDescriptor import com.intellij.debugger.ui.tree.LocalVariableDescriptor import com.intellij.debugger.ui.tree.NodeDescriptor import com.intellij.openapi.project.Project -import com.intellij.psi.* +import com.intellij.psi.JavaPsiFacade +import com.intellij.psi.PsiElement import com.intellij.psi.search.GlobalSearchScope import com.sun.jdi.AbsentInformationException import com.sun.jdi.ClassNotPreparedException import com.sun.jdi.ReferenceType import org.jetbrains.kotlin.codegen.AsmUtil import org.jetbrains.kotlin.idea.caches.resolve.analyze -import org.jetbrains.kotlin.psi.* +import org.jetbrains.kotlin.psi.KtClassOrObject +import org.jetbrains.kotlin.psi.KtFile +import org.jetbrains.kotlin.psi.KtPsiFactory +import org.jetbrains.kotlin.psi.KtSimpleNameExpression import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.resolve.BindingContextUtils import org.jetbrains.kotlin.resolve.jvm.JvmClassName @@ -41,7 +34,12 @@ import org.jetbrains.kotlin.resolve.source.KotlinSourceElement import org.jetbrains.kotlin.resolve.source.getPsi class KotlinSourcePositionProvider : SourcePositionProvider() { - override fun computeSourcePosition(descriptor: NodeDescriptor, project: Project, context: DebuggerContextImpl, nearest: Boolean): SourcePosition? { + override fun computeSourcePosition( + descriptor: NodeDescriptor, + project: Project, + context: DebuggerContextImpl, + nearest: Boolean + ): SourcePosition? { if (context.frameProxy == null) return null if (descriptor is FieldDescriptor) { @@ -84,7 +82,12 @@ class KotlinSourcePositionProvider : SourcePositionProvider() { return null } - private fun computeSourcePosition(descriptor: FieldDescriptor, project: Project, context: DebuggerContextImpl, nearest: Boolean): SourcePosition? { + private fun computeSourcePosition( + descriptor: FieldDescriptor, + project: Project, + context: DebuggerContextImpl, + nearest: Boolean + ): SourcePosition? { val fieldName = descriptor.field.name() if (fieldName == AsmUtil.CAPTURED_THIS_FIELD @@ -128,14 +131,12 @@ class KotlinSourcePositionProvider : SourcePositionProvider() { if (debugProcess != null) { try { val locations = type.safeAllLineLocations() - if (!locations.isEmpty()) { - val lastLocation = locations.get(locations.size - 1) + if (locations.isNotEmpty()) { + val lastLocation = locations[locations.size - 1] return debugProcess.positionManager.getSourcePosition(lastLocation) } - } - catch (ignored: AbsentInformationException) { - } - catch (ignored: ClassNotPreparedException) { + } catch (ignored: AbsentInformationException) { + } catch (ignored: ClassNotPreparedException) { } } return null diff --git a/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/breakpoints/KotlinFieldBreakpoint.kt b/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/breakpoints/KotlinFieldBreakpoint.kt index 91796e383c2..3f547bb2fc5 100644 --- a/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/breakpoints/KotlinFieldBreakpoint.kt +++ b/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/breakpoints/KotlinFieldBreakpoint.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.debugger.breakpoints @@ -55,9 +44,9 @@ import org.jetbrains.kotlin.resolve.BindingContext import javax.swing.Icon class KotlinFieldBreakpoint( - project: Project, - breakpoint: XBreakpoint -): BreakpointWithHighlighter(project, breakpoint) { + project: Project, + breakpoint: XBreakpoint +) : BreakpointWithHighlighter(project, breakpoint) { companion object { private val LOG = Logger.getInstance("#org.jetbrains.kotlin.idea.debugger.breakpoints.KotlinFieldBreakpoint") private val CATEGORY: Key = BreakpointCategory.lookup("field_breakpoints") @@ -130,18 +119,18 @@ class KotlinFieldBreakpoint( val sourcePosition = sourcePosition if (sourcePosition != null) { debugProcess.positionManager - .locationsOfLine(refType, sourcePosition) - .filter { it.method().isConstructor || it.method().isStaticInitializer } - .forEach { - val request = debugProcess.requestsManager.createBreakpointRequest(this, it) - debugProcess.requestsManager.enableRequest(request) - if (LOG.isDebugEnabled) { - LOG.debug("Breakpoint request added") - } + .locationsOfLine(refType, sourcePosition) + .filter { it.method().isConstructor || it.method().isStaticInitializer } + .forEach { + val request = debugProcess.requestsManager.createBreakpointRequest(this, it) + debugProcess.requestsManager.enableRequest(request) + if (LOG.isDebugEnabled) { + LOG.debug("Breakpoint request added") } + } } } - + when (breakpointType) { BreakpointType.FIELD -> { val field = refType.fieldByName(getFieldName()) @@ -181,8 +170,7 @@ class KotlinFieldBreakpoint( } } } - } - catch (ex: Exception) { + } catch (ex: Exception) { LOG.debug(ex) } } @@ -198,12 +186,10 @@ class KotlinFieldBreakpoint( if (descriptor is PropertyDescriptor) { if (bindingContext.get(BindingContext.BACKING_FIELD_REQUIRED, descriptor)!!) { BreakpointType.FIELD - } - else { + } else { BreakpointType.METHOD } - } - else { + } else { null } } @@ -218,16 +204,14 @@ class KotlinFieldBreakpoint( if (LOG.isDebugEnabled) { LOG.debug("Breakpoint request added") } - } - else { + } else { var entryRequest: MethodEntryRequest? = findRequest(debugProcess, MethodEntryRequest::class.java, this) if (entryRequest == null) { entryRequest = manager.createMethodEntryRequest(this)!! if (LOG.isDebugEnabled) { LOG.debug("Method entry request added (method = ${accessor.name()}; refType = ${refType.name()})") } - } - else { + } else { entryRequest.disable() } entryRequest.addClassFilter(refType) @@ -235,7 +219,11 @@ class KotlinFieldBreakpoint( } } - inline private fun findRequest(debugProcess: DebugProcessImpl, requestClass: Class, requestor: Requestor): T? { + inline private fun findRequest( + debugProcess: DebugProcessImpl, + requestClass: Class, + requestor: Requestor + ): T? { val requests = debugProcess.requestsManager.findRequests(requestor) for (eventRequest in requests) { if (eventRequest::class.java == requestClass) { @@ -268,60 +256,63 @@ class KotlinFieldBreakpoint( val locationQName = location.declaringType().name() + "." + location.method().name() val locationFileName = try { location.sourceName() - } - catch (e: AbsentInformationException) { + } catch (e: AbsentInformationException) { fileName - } - catch (e: InternalError) { + } catch (e: InternalError) { fileName } val locationLine = location.lineNumber() when (event) { - is ModificationWatchpointEvent-> { + is ModificationWatchpointEvent -> { val field = event.field() return DebuggerBundle.message( - "status.static.field.watchpoint.reached.access", - field.declaringType().name(), - field.name(), - locationQName, - locationFileName, - locationLine) + "status.static.field.watchpoint.reached.access", + field.declaringType().name(), + field.name(), + locationQName, + locationFileName, + locationLine + ) } is AccessWatchpointEvent -> { val field = event.field() return DebuggerBundle.message( - "status.static.field.watchpoint.reached.access", - field.declaringType().name(), - field.name(), - locationQName, - locationFileName, - locationLine) + "status.static.field.watchpoint.reached.access", + field.declaringType().name(), + field.name(), + locationQName, + locationFileName, + locationLine + ) } is MethodEntryEvent -> { val method = event.method() return DebuggerBundle.message( - "status.method.entry.breakpoint.reached", - method.declaringType().name() + "." + method.name() + "()", - locationQName, - locationFileName, - locationLine) + "status.method.entry.breakpoint.reached", + method.declaringType().name() + "." + method.name() + "()", + locationQName, + locationFileName, + locationLine + ) } is MethodExitEvent -> { val method = event.method() return DebuggerBundle.message( - "status.method.exit.breakpoint.reached", - method.declaringType().name() + "." + method.name() + "()", - locationQName, - locationFileName, - locationLine) + "status.method.exit.breakpoint.reached", + method.declaringType().name() + "." + method.name() + "()", + locationQName, + locationFileName, + locationLine + ) } } return DebuggerBundle.message( - "status.line.breakpoint.reached", - locationQName, - locationFileName, - locationLine) + "status.line.breakpoint.reached", + locationQName, + locationFileName, + locationLine + ) } fun setFieldName(fieldName: String) { @@ -376,7 +367,7 @@ class KotlinFieldBreakpoint( return DebuggerBundle.message("status.breakpoint.invalid") } val className = className - return if (className != null && !className.isEmpty()) className + "." + getFieldName() else getFieldName() + return if (className != null && className.isNotEmpty()) className + "." + getFieldName() else getFieldName() } private fun getFieldName(): String { diff --git a/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/breakpoints/KotlinFieldBreakpointPropertiesPanel.kt b/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/breakpoints/KotlinFieldBreakpointPropertiesPanel.kt index 2b0d399dcd7..8c3d4e7d261 100644 --- a/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/breakpoints/KotlinFieldBreakpointPropertiesPanel.kt +++ b/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/breakpoints/KotlinFieldBreakpointPropertiesPanel.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.debugger.breakpoints @@ -30,15 +19,17 @@ import javax.swing.JComponent import javax.swing.JPanel import kotlin.properties.Delegates -class KotlinFieldBreakpointPropertiesPanel: XBreakpointCustomPropertiesPanel>() { +class KotlinFieldBreakpointPropertiesPanel : XBreakpointCustomPropertiesPanel>() { private var myWatchInitializationCheckBox: JCheckBox by Delegates.notNull() private var myWatchAccessCheckBox: JCheckBox by Delegates.notNull() private var myWatchModificationCheckBox: JCheckBox by Delegates.notNull() override fun getComponent(): JComponent { - myWatchInitializationCheckBox = JCheckBox(KotlinBundle.message("debugger.field.watchpoints.properties.panel.field.initialization.label")) + myWatchInitializationCheckBox = + JCheckBox(KotlinBundle.message("debugger.field.watchpoints.properties.panel.field.initialization.label")) myWatchAccessCheckBox = JCheckBox(KotlinBundle.message("debugger.field.watchpoints.properties.panel.field.access.label")) - myWatchModificationCheckBox = JCheckBox(KotlinBundle.message("debugger.field.watchpoints.properties.panel.field.modification.label")) + myWatchModificationCheckBox = + JCheckBox(KotlinBundle.message("debugger.field.watchpoints.properties.panel.field.modification.label")) DialogUtil.registerMnemonic(myWatchInitializationCheckBox) DialogUtil.registerMnemonic(myWatchAccessCheckBox) diff --git a/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/breakpoints/KotlinFieldBreakpointType.kt b/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/breakpoints/KotlinFieldBreakpointType.kt index 0ed00eafac8..eeb92386f22 100644 --- a/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/breakpoints/KotlinFieldBreakpointType.kt +++ b/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/breakpoints/KotlinFieldBreakpointType.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.debugger.breakpoints @@ -34,8 +23,8 @@ import com.intellij.xdebugger.breakpoints.XLineBreakpoint import com.intellij.xdebugger.breakpoints.XLineBreakpointType import com.intellij.xdebugger.breakpoints.ui.XBreakpointCustomPropertiesPanel import org.jetbrains.kotlin.asJava.classes.KtLightClass -import org.jetbrains.kotlin.asJava.classes.KtLightClassForSourceDeclaration import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacade +import org.jetbrains.kotlin.asJava.classes.KtLightClassForSourceDeclaration import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.debugger.breakpoints.dialog.AddFieldBreakpointDialog import org.jetbrains.kotlin.idea.util.application.runWriteAction @@ -48,9 +37,11 @@ import javax.swing.JComponent class KotlinFieldBreakpointType : JavaBreakpointType, XLineBreakpointType("kotlin-field", KotlinBundle.message("debugger.field.watchpoints.tab.title")), - KotlinBreakpointType -{ - override fun createJavaBreakpoint(project: Project, breakpoint: XBreakpoint): Breakpoint { + KotlinBreakpointType { + override fun createJavaBreakpoint( + project: Project, + breakpoint: XBreakpoint + ): Breakpoint { return KotlinFieldBreakpoint(project, breakpoint) } @@ -94,9 +85,10 @@ class KotlinFieldBreakpointType : } result = when (psiClass) { - is KtLightClassForFacade -> { - psiClass.files.asSequence().mapNotNull { createBreakpointIfPropertyExists(it, it, className, fieldName) }.firstOrNull() - } + is KtLightClassForFacade -> psiClass.files.asSequence().mapNotNull { + createBreakpointIfPropertyExists(it, it, className, fieldName) + }.firstOrNull() + is KtLightClassForSourceDeclaration -> { val jetClass = psiClass.kotlinOrigin createBreakpointIfPropertyExists(jetClass, jetClass.containingKtFile, className, fieldName) @@ -117,10 +109,10 @@ class KotlinFieldBreakpointType : } private fun createBreakpointIfPropertyExists( - declaration: KtDeclarationContainer, - file: KtFile, - className: String, - fieldName: String + declaration: KtDeclarationContainer, + file: KtFile, + className: String, + fieldName: String ): XLineBreakpoint? { val project = file.project val property = declaration.declarations.firstOrNull { it is KtProperty && it.name == fieldName } ?: return null @@ -129,10 +121,10 @@ class KotlinFieldBreakpointType : val line = document.getLineNumber(property.textOffset) return runWriteAction { XDebuggerManager.getInstance(project).breakpointManager.addLineBreakpoint( - this, - file.virtualFile.url, - line, - KotlinPropertyBreakpointProperties(fieldName, className) + this, + file.virtualFile.url, + line, + KotlinPropertyBreakpointProperties(fieldName, className) ) } } @@ -156,7 +148,7 @@ class KotlinFieldBreakpointType : override fun getShortText(breakpoint: XLineBreakpoint): String? { val properties = breakpoint.properties val className = properties.myClassName - return if (!className.isEmpty()) className + "." + properties.myFieldName else properties.myFieldName + return if (className.isNotEmpty()) className + "." + properties.myFieldName else properties.myFieldName } override fun createProperties(): KotlinPropertyBreakpointProperties? { @@ -169,12 +161,7 @@ class KotlinFieldBreakpointType : override fun getDisplayText(breakpoint: XLineBreakpoint): String? { val kotlinBreakpoint = BreakpointManager.getJavaBreakpoint(breakpoint) as? BreakpointWithHighlighter - return if (kotlinBreakpoint != null) { - kotlinBreakpoint.description - } - else { - super.getDisplayText(breakpoint) - } + return kotlinBreakpoint?.description ?: super.getDisplayText(breakpoint) } override fun getEditorsProvider() = null diff --git a/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/breakpoints/KotlinPropertyBreakpointProperties.kt b/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/breakpoints/KotlinPropertyBreakpointProperties.kt index c6004c8f410..c10ad4408f2 100644 --- a/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/breakpoints/KotlinPropertyBreakpointProperties.kt +++ b/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/breakpoints/KotlinPropertyBreakpointProperties.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.debugger.breakpoints @@ -20,9 +9,9 @@ import com.intellij.util.xmlb.annotations.Attribute import org.jetbrains.java.debugger.breakpoints.properties.JavaBreakpointProperties class KotlinPropertyBreakpointProperties( - @Attribute var myFieldName: String = "", - @Attribute var myClassName: String = "" -): JavaBreakpointProperties() { + @Attribute var myFieldName: String = "", + @Attribute var myClassName: String = "" +) : JavaBreakpointProperties() { var WATCH_MODIFICATION: Boolean = true var WATCH_ACCESS: Boolean = false var WATCH_INITIALIZATION: Boolean = false diff --git a/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/breakpoints/breakpointTypeUtils.kt b/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/breakpoints/breakpointTypeUtils.kt index 68a14624ea0..db976f21432 100644 --- a/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/breakpoints/breakpointTypeUtils.kt +++ b/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/breakpoints/breakpointTypeUtils.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.debugger.breakpoints @@ -31,13 +20,15 @@ import com.intellij.xdebugger.impl.XSourcePositionImpl import org.jetbrains.kotlin.idea.KotlinFileType import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.core.util.CodeInsightUtils -import org.jetbrains.kotlin.idea.core.util.attachmentByPsiFile import org.jetbrains.kotlin.idea.core.util.getLineNumber import org.jetbrains.kotlin.idea.debugger.findElementAtLine import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* -import org.jetbrains.kotlin.psi.psiUtil.* +import org.jetbrains.kotlin.psi.psiUtil.endOffset +import org.jetbrains.kotlin.psi.psiUtil.getParentOfType +import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf +import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.inline.INLINE_ONLY_ANNOTATION_FQ_NAME import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode @@ -179,12 +170,11 @@ fun getLambdasAtLineIfAny(file: KtFile, line: Int): List { val start = lineElement.startOffset val end = lineElement.endOffset - val allLiterals = CodeInsightUtils. - findElementsOfClassInRange(file, start, end, KtFunction::class.java) - .filterIsInstance() - // filter function literals and functional expressions - .filter { it is KtFunctionLiteral || it.name == null } - .toSet() + val allLiterals = CodeInsightUtils.findElementsOfClassInRange(file, start, end, KtFunction::class.java) + .filterIsInstance() + // filter function literals and functional expressions + .filter { it is KtFunctionLiteral || it.name == null } + .toSet() return allLiterals.filter { val statement = it.bodyBlockExpression?.statements?.firstOrNull() ?: it diff --git a/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/debuggerUtil.kt b/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/debuggerUtil.kt index 17955206251..fd25b97caec 100644 --- a/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/debuggerUtil.kt +++ b/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/debuggerUtil.kt @@ -1,5 +1,5 @@ /* - * Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -100,14 +100,11 @@ private fun Location.visibleVariables(debugProcess: DebugProcessImpl): List { createVisibleVariables() val mapAsList = ArrayList(visibleVariables!!.values) - Collections.sort(mapAsList) + mapAsList.sort() return mapAsList } @@ -235,14 +232,11 @@ fun findCallByEndToken(element: PsiElement): KtCallExpression? { return when (element.node.elementType) { KtTokens.RPAR -> (element.parent as? KtValueArgumentList)?.parent as? KtCallExpression - KtTokens.RBRACE -> { - val braceParent = CodeInsightUtils.getTopParentWithEndOffset(element, KtCallExpression::class.java) - when (braceParent) { - is KtCallExpression -> braceParent - is KtLambdaArgument -> braceParent.parent as? KtCallExpression - is KtValueArgument -> (braceParent.parent as? KtValueArgumentList)?.parent as? KtCallExpression - else -> null - } + KtTokens.RBRACE -> when (val braceParent = CodeInsightUtils.getTopParentWithEndOffset(element, KtCallExpression::class.java)) { + is KtCallExpression -> braceParent + is KtLambdaArgument -> braceParent.parent as? KtCallExpression + is KtValueArgument -> (braceParent.parent as? KtValueArgumentList)?.parent as? KtCallExpression + else -> null } else -> null } diff --git a/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/filter/KotlinDebuggerInternalClassesFilterProvider.kt b/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/filter/KotlinDebuggerInternalClassesFilterProvider.kt index 6c8423cb445..8ab392ccc13 100644 --- a/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/filter/KotlinDebuggerInternalClassesFilterProvider.kt +++ b/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/filter/KotlinDebuggerInternalClassesFilterProvider.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.debugger.filter @@ -21,11 +10,11 @@ import com.intellij.ui.classFilter.DebuggerClassFilterProvider import org.jetbrains.kotlin.idea.debugger.KotlinDebuggerSettings private val FILTERS = listOf( - ClassFilter("kotlin.jvm*"), - ClassFilter("kotlin.reflect*"), - ClassFilter("kotlin.NoWhenBranchMatchedException"), - ClassFilter("kotlin.TypeCastException"), - ClassFilter("kotlin.KotlinNullPointerException") + ClassFilter("kotlin.jvm*"), + ClassFilter("kotlin.reflect*"), + ClassFilter("kotlin.NoWhenBranchMatchedException"), + ClassFilter("kotlin.TypeCastException"), + ClassFilter("kotlin.KotlinNullPointerException") ) class KotlinDebuggerInternalClassesFilterProvider : DebuggerClassFilterProvider { diff --git a/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/filter/KotlinSyntheticTypeComponentProviderBase.kt b/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/filter/KotlinSyntheticTypeComponentProviderBase.kt index de16a6f7969..ceebadc2dfb 100644 --- a/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/filter/KotlinSyntheticTypeComponentProviderBase.kt +++ b/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/filter/KotlinSyntheticTypeComponentProviderBase.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.debugger.filter @@ -25,7 +14,7 @@ import org.jetbrains.org.objectweb.asm.Opcodes import kotlin.jvm.internal.FunctionReference import kotlin.jvm.internal.PropertyReference -abstract class KotlinSyntheticTypeComponentProviderBase: SyntheticTypeComponentProvider { +abstract class KotlinSyntheticTypeComponentProviderBase : SyntheticTypeComponentProvider { override fun isSynthetic(typeComponent: TypeComponent?): Boolean { if (typeComponent !is Method) return false @@ -48,11 +37,9 @@ abstract class KotlinSyntheticTypeComponentProviderBase: SyntheticTypeComponentP } return !typeComponent.declaringType().safeAllLineLocations().any { it.lineNumber() != 1 } - } - catch(e: AbsentInformationException) { + } catch (e: AbsentInformationException) { return false - } - catch(e: UnsupportedOperationException) { + } catch (e: UnsupportedOperationException) { return false } } @@ -126,6 +113,6 @@ abstract class KotlinSyntheticTypeComponentProviderBase: SyntheticTypeComponentP val interfaces = declaringType.allInterfaces() val vm = declaringType.virtualMachine() val traitImpls = interfaces.flatMap { vm.classesByName(it.name() + JvmAbi.DEFAULT_IMPLS_SUFFIX) } - return traitImpls.any { !it.methodsByName(method.name()).isEmpty() } + return traitImpls.any { it.methodsByName(method.name()).isNotEmpty() } } } \ No newline at end of file diff --git a/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/render/DelegatedPropertyFieldDescriptor.kt b/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/render/DelegatedPropertyFieldDescriptor.kt index 32ae48f1f80..ab45e9e79f8 100644 --- a/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/render/DelegatedPropertyFieldDescriptor.kt +++ b/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/render/DelegatedPropertyFieldDescriptor.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.debugger.render @@ -27,10 +16,10 @@ import org.jetbrains.kotlin.load.java.JvmAbi import org.jetbrains.kotlin.name.Name class DelegatedPropertyFieldDescriptor( - project: Project, - objectRef: ObjectReference, - val delegate: Field, - private val renderDelegatedProperty: Boolean + project: Project, + objectRef: ObjectReference, + val delegate: Field, + private val renderDelegatedProperty: Boolean ) : FieldDescriptorImpl(project, objectRef, delegate) { override fun calcValue(evaluationContext: EvaluationContextImpl?): Value? { @@ -43,17 +32,16 @@ class DelegatedPropertyFieldDescriptor( return super.calcValue(evaluationContext) } - try { - return evaluationContext.debugProcess.invokeInstanceMethod( - evaluationContext, - `object`, - method, - listOf(), - evaluationContext.suspendContext.suspendPolicy + return try { + evaluationContext.debugProcess.invokeInstanceMethod( + evaluationContext, + `object`, + method, + listOf(), + evaluationContext.suspendContext.suspendPolicy ) - } - catch(e: EvaluateException) { - return e.exceptionFromTargetVM + } catch (e: EvaluateException) { + e.exceptionFromTargetVM } } diff --git a/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/render/KotlinClassWithDelegatedPropertyRenderer.kt b/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/render/KotlinClassWithDelegatedPropertyRenderer.kt index 4b23f9e1bbc..77bcb035541 100644 --- a/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/render/KotlinClassWithDelegatedPropertyRenderer.kt +++ b/idea/jvm-debugger/jvm-debugger-core/src/org/jetbrains/kotlin/idea/debugger/render/KotlinClassWithDelegatedPropertyRenderer.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.debugger.render @@ -30,14 +19,11 @@ import com.intellij.debugger.ui.tree.render.DescriptorLabelListener import com.intellij.openapi.diagnostic.Logger import com.intellij.xdebugger.settings.XDebuggerSettingsManager import com.sun.jdi.* -import com.sun.jdi.Type import org.jetbrains.kotlin.idea.debugger.KotlinDebuggerSettings import org.jetbrains.kotlin.idea.debugger.ToggleKotlinVariablesState import org.jetbrains.kotlin.idea.debugger.canRunEvaluation import org.jetbrains.kotlin.load.java.JvmAbi import java.util.* -import com.sun.jdi.Type as JdiType -import org.jetbrains.org.objectweb.asm.Type as AsmType private val LOG = Logger.getInstance(KotlinClassWithDelegatedPropertyRenderer::class.java) private fun notPreparedClassMessage(referenceType: ReferenceType) = @@ -45,7 +31,7 @@ private fun notPreparedClassMessage(referenceType: ReferenceType) = class KotlinClassWithDelegatedPropertyRenderer : ClassRenderer() { private val rendererSettings = NodeRendererSettings.getInstance() - + override fun isApplicable(jdiType: Type?): Boolean { if (!super.isApplicable(jdiType)) return false diff --git a/idea/jvm-debugger/jvm-debugger-evaluation/src/org/jetbrains/kotlin/idea/debugger/evaluate/KotlinCodeFragmentFactory.kt b/idea/jvm-debugger/jvm-debugger-evaluation/src/org/jetbrains/kotlin/idea/debugger/evaluate/KotlinCodeFragmentFactory.kt index 7ef9559a0e7..e245d62a797 100644 --- a/idea/jvm-debugger/jvm-debugger-evaluation/src/org/jetbrains/kotlin/idea/debugger/evaluate/KotlinCodeFragmentFactory.kt +++ b/idea/jvm-debugger/jvm-debugger-evaluation/src/org/jetbrains/kotlin/idea/debugger/evaluate/KotlinCodeFragmentFactory.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.debugger.evaluate @@ -34,7 +23,8 @@ import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.PsiTypesUtil import com.intellij.util.IncorrectOperationException import com.intellij.util.concurrency.Semaphore -import com.sun.jdi.* +import com.sun.jdi.AbsentInformationException +import com.sun.jdi.InvalidStackFrameException import org.jetbrains.annotations.TestOnly import org.jetbrains.kotlin.idea.KotlinFileType import org.jetbrains.kotlin.idea.core.util.getKotlinJvmRuntimeMarkerClass @@ -94,7 +84,9 @@ class KotlinCodeFragmentFactory : CodeFragmentFactory() { val debuggerContext = DebuggerManagerEx.getInstanceEx(project).context val debuggerSession = debuggerContext.debuggerSession - if ((debuggerSession == null || debuggerContext.suspendContext == null) && !ApplicationManager.getApplication().isUnitTestMode) { + if ((debuggerSession == null || debuggerContext.suspendContext == null) && + !ApplicationManager.getApplication().isUnitTestMode + ) { LOG.warn("Couldn't create fake context element for java file, debugger isn't paused on breakpoint") return@putCopyableUserData emptyFile } diff --git a/idea/jvm-debugger/jvm-debugger-evaluation/src/org/jetbrains/kotlin/idea/debugger/evaluate/compilation/CodeFragmentParameterAnalyzer.kt b/idea/jvm-debugger/jvm-debugger-evaluation/src/org/jetbrains/kotlin/idea/debugger/evaluate/compilation/CodeFragmentParameterAnalyzer.kt index e7cd18c6456..55d37380524 100644 --- a/idea/jvm-debugger/jvm-debugger-evaluation/src/org/jetbrains/kotlin/idea/debugger/evaluate/compilation/CodeFragmentParameterAnalyzer.kt +++ b/idea/jvm-debugger/jvm-debugger-evaluation/src/org/jetbrains/kotlin/idea/debugger/evaluate/compilation/CodeFragmentParameterAnalyzer.kt @@ -18,13 +18,15 @@ import org.jetbrains.kotlin.idea.debugger.evaluate.DebuggerFieldPropertyDescript import org.jetbrains.kotlin.idea.debugger.evaluate.EvaluationError import org.jetbrains.kotlin.idea.debugger.evaluate.EvaluationStatus import org.jetbrains.kotlin.idea.debugger.evaluate.ExecutionContext -import org.jetbrains.kotlin.idea.debugger.evaluate.compilation.CodeFragmentParameter.* import org.jetbrains.kotlin.idea.debugger.evaluate.KotlinCodeFragmentFactory.Companion.FAKE_JAVA_CONTEXT_FUNCTION_NAME +import org.jetbrains.kotlin.idea.debugger.evaluate.compilation.CodeFragmentParameter.* import org.jetbrains.kotlin.idea.debugger.safeLocation import org.jetbrains.kotlin.idea.debugger.safeMethod import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.psi.* -import org.jetbrains.kotlin.psi.psiUtil.* +import org.jetbrains.kotlin.psi.psiUtil.getParentOfType +import org.jetbrains.kotlin.psi.psiUtil.isAncestor +import org.jetbrains.kotlin.psi.psiUtil.isDotSelector import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.calls.checkers.COROUTINE_CONTEXT_1_3_FQ_NAME @@ -310,6 +312,7 @@ class CodeFragmentParameterAnalyzer( parameters.getOrPut(target) { val type = target.type + @Suppress("DEPRECATION") val kind = if (target is LocalVariableDescriptor && target.isDelegated) Kind.DELEGATED else Kind.ORDINARY Smart(Dumb(kind, target.name.asString()), type, target, isLValue) diff --git a/idea/jvm-debugger/jvm-debugger-evaluation/src/org/jetbrains/kotlin/idea/debugger/evaluate/compilation/DebugLabelPropertyDescriptorProvider.kt b/idea/jvm-debugger/jvm-debugger-evaluation/src/org/jetbrains/kotlin/idea/debugger/evaluate/compilation/DebugLabelPropertyDescriptorProvider.kt index 72f40de403b..24a2ae7cfae 100644 --- a/idea/jvm-debugger/jvm-debugger-evaluation/src/org/jetbrains/kotlin/idea/debugger/evaluate/compilation/DebugLabelPropertyDescriptorProvider.kt +++ b/idea/jvm-debugger/jvm-debugger-evaluation/src/org/jetbrains/kotlin/idea/debugger/evaluate/compilation/DebugLabelPropertyDescriptorProvider.kt @@ -11,12 +11,11 @@ import com.intellij.openapi.application.ApplicationManager import com.intellij.psi.search.GlobalSearchScope import com.intellij.xdebugger.impl.XDebugSessionImpl import com.intellij.xdebugger.impl.ui.tree.ValueMarkup -import org.jetbrains.kotlin.builtins.PrimitiveType import com.sun.jdi.* import org.jetbrains.kotlin.backend.common.SimpleMemberScope -import com.sun.jdi.Type as JdiType import org.jetbrains.kotlin.builtins.DefaultBuiltIns import org.jetbrains.kotlin.builtins.KotlinBuiltIns +import org.jetbrains.kotlin.builtins.PrimitiveType import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.annotations.Annotations import org.jetbrains.kotlin.descriptors.impl.DeclarationDescriptorImpl @@ -26,13 +25,14 @@ import org.jetbrains.kotlin.descriptors.impl.PropertyGetterDescriptorImpl import org.jetbrains.kotlin.idea.debugger.getClassDescriptor import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name -import org.jetbrains.kotlin.psi.KtCodeFragment -import org.jetbrains.kotlin.psi.externalDescriptors import org.jetbrains.kotlin.platform.TargetPlatform import org.jetbrains.kotlin.platform.jvm.JvmPlatforms +import org.jetbrains.kotlin.psi.KtCodeFragment +import org.jetbrains.kotlin.psi.externalDescriptors import org.jetbrains.kotlin.resolve.scopes.MemberScope import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.Variance +import com.sun.jdi.Type as JdiType import org.jetbrains.org.objectweb.asm.Type as AsmType class DebugLabelPropertyDescriptorProvider(val codeFragment: KtCodeFragment, val debugProcess: DebugProcessImpl) { @@ -144,10 +144,8 @@ class DebugLabelPropertyDescriptorProvider(val codeFragment: KtCodeFragment, val } } -private object DebugLabelModuleDescriptor - : DeclarationDescriptorImpl(Annotations.EMPTY, Name.identifier("DebugLabelExtensions")), - ModuleDescriptor -{ +private object DebugLabelModuleDescriptor : DeclarationDescriptorImpl(Annotations.EMPTY, Name.identifier("DebugLabelExtensions")), + ModuleDescriptor { override val builtIns: KotlinBuiltIns get() = DefaultBuiltIns.Instance diff --git a/idea/jvm-debugger/jvm-debugger-evaluation/src/org/jetbrains/kotlin/idea/debugger/evaluate/surroundWith/KotlinRuntimeTypeCastSurrounder.kt b/idea/jvm-debugger/jvm-debugger-evaluation/src/org/jetbrains/kotlin/idea/debugger/evaluate/surroundWith/KotlinRuntimeTypeCastSurrounder.kt index db494e41776..7c0a870dc68 100644 --- a/idea/jvm-debugger/jvm-debugger-evaluation/src/org/jetbrains/kotlin/idea/debugger/evaluate/surroundWith/KotlinRuntimeTypeCastSurrounder.kt +++ b/idea/jvm-debugger/jvm-debugger-evaluation/src/org/jetbrains/kotlin/idea/debugger/evaluate/surroundWith/KotlinRuntimeTypeCastSurrounder.kt @@ -1,6 +1,6 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license - * that can be found in the license/LICENSE.txt file. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.debugger.surroundWith @@ -20,9 +20,9 @@ import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze -import org.jetbrains.kotlin.idea.debugger.evaluate.KotlinRuntimeTypeEvaluator import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.core.surroundWith.KotlinExpressionSurrounder +import org.jetbrains.kotlin.idea.debugger.evaluate.KotlinRuntimeTypeEvaluator import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode @@ -30,7 +30,7 @@ import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.TypeUtils import org.jetbrains.kotlin.types.checker.KotlinTypeChecker -class KotlinRuntimeTypeCastSurrounder: KotlinExpressionSurrounder() { +class KotlinRuntimeTypeCastSurrounder : KotlinExpressionSurrounder() { override fun isApplicable(expression: KtExpression): Boolean { if (!super.isApplicable(expression)) return false @@ -61,11 +61,11 @@ class KotlinRuntimeTypeCastSurrounder: KotlinExpressionSurrounder() { } private inner class SurroundWithCastWorker( - private val myEditor: Editor, - expression: KtExpression, - context: DebuggerContextImpl, - indicator: ProgressIndicator - ): KotlinRuntimeTypeEvaluator(myEditor, expression, context, indicator) { + private val myEditor: Editor, + expression: KtExpression, + context: DebuggerContextImpl, + indicator: ProgressIndicator + ) : KotlinRuntimeTypeEvaluator(myEditor, expression, context, indicator) { override fun typeCalculationFinished(type: KotlinType?) { if (type == null) return @@ -74,29 +74,28 @@ class KotlinRuntimeTypeCastSurrounder: KotlinExpressionSurrounder() { val project = myEditor.project DebuggerInvocationUtil.invokeLater(project, Runnable { - object : WriteCommandAction(project, CodeInsightBundle.message("command.name.surround.with.runtime.cast")) { - override fun run(result: Result) { - try { - val factory = KtPsiFactory(myElement.project) + object : WriteCommandAction(project, CodeInsightBundle.message("command.name.surround.with.runtime.cast")) { + override fun run(result: Result) { + try { + val factory = KtPsiFactory(myElement.project) - val fqName = DescriptorUtils.getFqName(type.constructor.declarationDescriptor!!) - val parentCast = factory.createExpression("(expr as " + fqName.asString() + ")") as KtParenthesizedExpression - val cast = parentCast.expression as KtBinaryExpressionWithTypeRHS - cast.left.replace(myElement) - val expr = myElement.replace(parentCast) as KtExpression + val fqName = DescriptorUtils.getFqName(type.constructor.declarationDescriptor!!) + val parentCast = factory.createExpression("(expr as " + fqName.asString() + ")") as KtParenthesizedExpression + val cast = parentCast.expression as KtBinaryExpressionWithTypeRHS + cast.left.replace(myElement) + val expr = myElement.replace(parentCast) as KtExpression - ShortenReferences.DEFAULT.process(expr) + ShortenReferences.DEFAULT.process(expr) - val range = expr.textRange - myEditor.selectionModel.setSelection(range.startOffset, range.endOffset) - myEditor.caretModel.moveToOffset(range.endOffset) - myEditor.scrollingModel.scrollToCaret(ScrollType.RELATIVE) - } - finally { - release() - } + val range = expr.textRange + myEditor.selectionModel.setSelection(range.startOffset, range.endOffset) + myEditor.caretModel.moveToOffset(range.endOffset) + myEditor.scrollingModel.scrollToCaret(ScrollType.RELATIVE) + } finally { + release() } - }.execute() + } + }.execute() }, myProgressIndicator.modalityState) } diff --git a/idea/jvm-debugger/jvm-debugger-sequence/src/org/jetbrains/kotlin/idea/debugger/sequence/psi/impl/KotlinChainTransformerImpl.kt b/idea/jvm-debugger/jvm-debugger-sequence/src/org/jetbrains/kotlin/idea/debugger/sequence/psi/impl/KotlinChainTransformerImpl.kt index 0a9dd3ffa19..90d63cf556f 100644 --- a/idea/jvm-debugger/jvm-debugger-sequence/src/org/jetbrains/kotlin/idea/debugger/sequence/psi/impl/KotlinChainTransformerImpl.kt +++ b/idea/jvm-debugger/jvm-debugger-sequence/src/org/jetbrains/kotlin/idea/debugger/sequence/psi/impl/KotlinChainTransformerImpl.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2017 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -66,8 +66,7 @@ class KotlinChainTransformerImpl(private val typeExtractor: CallTypeExtractor) : } private fun createQualifier(expression: PsiElement, typeAfter: GenericType): QualifierExpression { - val parent = expression.parent as? KtDotQualifiedExpression - ?: return QualifierExpressionImpl("", TextRange.EMPTY_RANGE, typeAfter) + val parent = expression.parent as? KtDotQualifiedExpression ?: return QualifierExpressionImpl("", TextRange.EMPTY_RANGE, typeAfter) val receiver = parent.receiverExpression return QualifierExpressionImpl(receiver.text, receiver.textRange, typeAfter) diff --git a/idea/jvm-debugger/jvm-debugger-sequence/src/org/jetbrains/kotlin/idea/debugger/sequence/psi/java/StreamExCallChecker.kt b/idea/jvm-debugger/jvm-debugger-sequence/src/org/jetbrains/kotlin/idea/debugger/sequence/psi/java/StreamExCallChecker.kt index 5e1e59bcc93..4764168094d 100644 --- a/idea/jvm-debugger/jvm-debugger-sequence/src/org/jetbrains/kotlin/idea/debugger/sequence/psi/java/StreamExCallChecker.kt +++ b/idea/jvm-debugger/jvm-debugger-sequence/src/org/jetbrains/kotlin/idea/debugger/sequence/psi/java/StreamExCallChecker.kt @@ -1,5 +1,5 @@ /* - * Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -8,7 +8,7 @@ package org.jetbrains.kotlin.idea.debugger.sequence.psi.java import org.jetbrains.kotlin.idea.debugger.sequence.psi.CallCheckerWithNameHeuristics import org.jetbrains.kotlin.idea.debugger.sequence.psi.StreamCallChecker -class StreamExCallChecker(nestedChecker: StreamCallChecker): CallCheckerWithNameHeuristics(nestedChecker) { +class StreamExCallChecker(nestedChecker: StreamCallChecker) : CallCheckerWithNameHeuristics(nestedChecker) { private companion object { val TERMINATION_CALLS: Set = setOf( "forEach", "toArray", "reduce", "collect", "min", "max", "count", "sum", "anyMatch", "allMatch", "noneMatch", "findFirst", diff --git a/idea/jvm-debugger/jvm-debugger-sequence/src/org/jetbrains/kotlin/idea/debugger/sequence/psi/sequence/SequenceTypeExtractor.kt b/idea/jvm-debugger/jvm-debugger-sequence/src/org/jetbrains/kotlin/idea/debugger/sequence/psi/sequence/SequenceTypeExtractor.kt index 2a4d0ed1a3b..a0fbbf4e912 100644 --- a/idea/jvm-debugger/jvm-debugger-sequence/src/org/jetbrains/kotlin/idea/debugger/sequence/psi/sequence/SequenceTypeExtractor.kt +++ b/idea/jvm-debugger/jvm-debugger-sequence/src/org/jetbrains/kotlin/idea/debugger/sequence/psi/sequence/SequenceTypeExtractor.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2017 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -28,8 +28,8 @@ class SequenceTypeExtractor : CallTypeExtractor.Base() { override fun getResultType(type: KotlinType): GenericType { val typeName = KotlinPsiUtil.getTypeWithoutTypeParameters(type) return KotlinSequenceTypes.primitiveTypeByName(typeName) - ?: KotlinSequenceTypes.primitiveArrayByName(typeName) - ?: ClassTypeImpl(KotlinPsiUtil.getTypeName(type)) + ?: KotlinSequenceTypes.primitiveArrayByName(typeName) + ?: ClassTypeImpl(KotlinPsiUtil.getTypeName(type)) } private fun tryToFindElementType(type: KotlinType): GenericType? { diff --git a/idea/jvm-debugger/jvm-debugger-sequence/src/org/jetbrains/kotlin/idea/debugger/sequence/trace/dsl/KotlinArrayVariable.kt b/idea/jvm-debugger/jvm-debugger-sequence/src/org/jetbrains/kotlin/idea/debugger/sequence/trace/dsl/KotlinArrayVariable.kt index 699cc2fa7d1..3cfda70723b 100644 --- a/idea/jvm-debugger/jvm-debugger-sequence/src/org/jetbrains/kotlin/idea/debugger/sequence/trace/dsl/KotlinArrayVariable.kt +++ b/idea/jvm-debugger/jvm-debugger-sequence/src/org/jetbrains/kotlin/idea/debugger/sequence/trace/dsl/KotlinArrayVariable.kt @@ -15,7 +15,8 @@ import com.intellij.debugger.streams.trace.impl.handler.type.ArrayType class KotlinArrayVariable(override val type: ArrayType, override val name: String) : VariableImpl(type, name), ArrayVariable { override fun get(index: Expression): Expression = TextExpression("$name[${index.toCode()}]!!") - override operator fun set(index: Expression, value: Expression): Expression = TextExpression("$name[${index.toCode()}] = ${value.toCode()}") + override operator fun set(index: Expression, value: Expression): Expression = + TextExpression("$name[${index.toCode()}] = ${value.toCode()}") override fun defaultDeclaration(size: Expression): VariableDeclaration = KotlinVariableDeclaration(this, false, type.sizedDeclaration(size.toCode())) diff --git a/idea/jvm-debugger/jvm-debugger-test/test/org/jetbrains/kotlin/idea/debugger/test/DebuggerTestUtils.kt b/idea/jvm-debugger/jvm-debugger-test/test/org/jetbrains/kotlin/idea/debugger/test/DebuggerTestUtils.kt index 815508a31a7..cb9f1a26199 100644 --- a/idea/jvm-debugger/jvm-debugger-test/test/org/jetbrains/kotlin/idea/debugger/test/DebuggerTestUtils.kt +++ b/idea/jvm-debugger/jvm-debugger-test/test/org/jetbrains/kotlin/idea/debugger/test/DebuggerTestUtils.kt @@ -4,6 +4,7 @@ */ @file:JvmName("DebuggerTestUtils") + package org.jetbrains.kotlin.idea.debugger.test import org.jetbrains.kotlin.test.KotlinTestUtils diff --git a/idea/jvm-debugger/jvm-debugger-test/test/org/jetbrains/kotlin/idea/debugger/test/mock/MockMethod.kt b/idea/jvm-debugger/jvm-debugger-test/test/org/jetbrains/kotlin/idea/debugger/test/mock/MockMethod.kt index d67a8368a36..adde875fff0 100644 --- a/idea/jvm-debugger/jvm-debugger-test/test/org/jetbrains/kotlin/idea/debugger/test/mock/MockMethod.kt +++ b/idea/jvm-debugger/jvm-debugger-test/test/org/jetbrains/kotlin/idea/debugger/test/mock/MockMethod.kt @@ -31,7 +31,7 @@ class MockMethod : Method { override fun isAbstract() = throw UnsupportedOperationException() override fun isVarArgs() = throw UnsupportedOperationException() override fun returnTypeName() = throw UnsupportedOperationException() - override fun argumentTypes( ) = throw UnsupportedOperationException() + override fun argumentTypes() = throw UnsupportedOperationException() override fun isConstructor() = throw UnsupportedOperationException() override fun locationsOfLine(lineNumber: Int) = throw UnsupportedOperationException() override fun locationsOfLine(stratum: String?, sourceName: String?, lineNumber: Int) = throw UnsupportedOperationException() diff --git a/idea/jvm-debugger/jvm-debugger-test/test/org/jetbrains/kotlin/idea/debugger/test/preference/SettingsMutators.kt b/idea/jvm-debugger/jvm-debugger-test/test/org/jetbrains/kotlin/idea/debugger/test/preference/SettingsMutators.kt index c4a7eda1751..319c09a1de1 100644 --- a/idea/jvm-debugger/jvm-debugger-test/test/org/jetbrains/kotlin/idea/debugger/test/preference/SettingsMutators.kt +++ b/idea/jvm-debugger/jvm-debugger-test/test/org/jetbrains/kotlin/idea/debugger/test/preference/SettingsMutators.kt @@ -13,14 +13,14 @@ import org.jetbrains.kotlin.idea.debugger.KotlinDebuggerSettings import org.jetbrains.kotlin.idea.debugger.ToggleKotlinVariablesState import org.jetbrains.kotlin.idea.debugger.emulateDexDebugInTests import org.jetbrains.kotlin.idea.debugger.test.preference.DebuggerPreferenceKeys.DISABLE_KOTLIN_INTERNAL_CLASSES +import org.jetbrains.kotlin.idea.debugger.test.preference.DebuggerPreferenceKeys.EMULATE_DEX import org.jetbrains.kotlin.idea.debugger.test.preference.DebuggerPreferenceKeys.IS_FILTER_FOR_STDLIB_ALREADY_ADDED import org.jetbrains.kotlin.idea.debugger.test.preference.DebuggerPreferenceKeys.RENDER_DELEGATED_PROPERTIES -import org.jetbrains.kotlin.idea.debugger.test.preference.DebuggerPreferenceKeys.SKIP_CONSTRUCTORS import org.jetbrains.kotlin.idea.debugger.test.preference.DebuggerPreferenceKeys.SKIP_CLASSLOADERS +import org.jetbrains.kotlin.idea.debugger.test.preference.DebuggerPreferenceKeys.SKIP_CONSTRUCTORS import org.jetbrains.kotlin.idea.debugger.test.preference.DebuggerPreferenceKeys.SKIP_GETTERS import org.jetbrains.kotlin.idea.debugger.test.preference.DebuggerPreferenceKeys.SKIP_SYNTHETIC_METHODS import org.jetbrains.kotlin.idea.debugger.test.preference.DebuggerPreferenceKeys.TRACING_FILTERS_ENABLED -import org.jetbrains.kotlin.idea.debugger.test.preference.DebuggerPreferenceKeys.EMULATE_DEX import kotlin.reflect.KMutableProperty1 internal val SettingsMutators: List> = listOf( @@ -38,7 +38,7 @@ internal val SettingsMutators: List> = listOf( ForceRankingSettingsMutator ) -private class DexSettingsMutator(key: DebuggerPreferenceKey): SettingsMutator(key) { +private class DexSettingsMutator(key: DebuggerPreferenceKey) : SettingsMutator(key) { override fun setValue(value: Boolean, project: Project): Boolean { val oldValue = emulateDexDebugInTests emulateDexDebugInTests = value diff --git a/idea/jvm-debugger/jvm-debugger-test/test/org/jetbrains/kotlin/idea/debugger/test/sequence/psi/collection/TypedCollectionChainTest.kt b/idea/jvm-debugger/jvm-debugger-test/test/org/jetbrains/kotlin/idea/debugger/test/sequence/psi/collection/TypedCollectionChainTest.kt index 336780e3b10..ec789461fbc 100644 --- a/idea/jvm-debugger/jvm-debugger-test/test/org/jetbrains/kotlin/idea/debugger/test/sequence/psi/collection/TypedCollectionChainTest.kt +++ b/idea/jvm-debugger/jvm-debugger-test/test/org/jetbrains/kotlin/idea/debugger/test/sequence/psi/collection/TypedCollectionChainTest.kt @@ -6,8 +6,8 @@ package org.jetbrains.kotlin.idea.debugger.test.sequence.psi.collection import com.intellij.debugger.streams.wrapper.StreamChainBuilder import org.jetbrains.kotlin.idea.debugger.sequence.lib.collections.KotlinCollectionSupportProvider -import org.jetbrains.kotlin.idea.debugger.test.sequence.psi.TypedChainTestCase import org.jetbrains.kotlin.idea.debugger.sequence.trace.dsl.KotlinSequenceTypes +import org.jetbrains.kotlin.idea.debugger.test.sequence.psi.TypedChainTestCase import org.jetbrains.kotlin.test.JUnit3WithIdeaConfigurationRunner import org.junit.runner.RunWith @@ -51,6 +51,9 @@ class TypedCollectionChainTest : TypedChainTestCase("collection/positive/types") fun testNullableToNotNull() = doTest(KotlinSequenceTypes.NULLABLE_ANY, KotlinSequenceTypes.INT) fun testNotNullToNullable() = doTest(KotlinSequenceTypes.DOUBLE, KotlinSequenceTypes.NULLABLE_ANY) - fun testFewTransitions1() = doTest(KotlinSequenceTypes.BYTE, KotlinSequenceTypes.ANY, KotlinSequenceTypes.NULLABLE_ANY, KotlinSequenceTypes.INT) - fun testFewTransitions2() = doTest(KotlinSequenceTypes.CHAR, KotlinSequenceTypes.BOOLEAN, KotlinSequenceTypes.DOUBLE, KotlinSequenceTypes.ANY) + fun testFewTransitions1() = + doTest(KotlinSequenceTypes.BYTE, KotlinSequenceTypes.ANY, KotlinSequenceTypes.NULLABLE_ANY, KotlinSequenceTypes.INT) + + fun testFewTransitions2() = + doTest(KotlinSequenceTypes.CHAR, KotlinSequenceTypes.BOOLEAN, KotlinSequenceTypes.DOUBLE, KotlinSequenceTypes.ANY) } \ No newline at end of file diff --git a/idea/jvm-debugger/jvm-debugger-test/test/org/jetbrains/kotlin/idea/debugger/test/util/KotlinOutputChecker.kt b/idea/jvm-debugger/jvm-debugger-test/test/org/jetbrains/kotlin/idea/debugger/test/util/KotlinOutputChecker.kt index cd1ec8aa2a4..a2842cc68ae 100644 --- a/idea/jvm-debugger/jvm-debugger-test/test/org/jetbrains/kotlin/idea/debugger/test/util/KotlinOutputChecker.kt +++ b/idea/jvm-debugger/jvm-debugger-test/test/org/jetbrains/kotlin/idea/debugger/test/util/KotlinOutputChecker.kt @@ -109,9 +109,9 @@ internal class KotlinOutputChecker( val disconnectedIndex = lines.indexOfFirst { it.startsWith(DISCONNECT_PREFIX) } lines[disconnectedIndex] = DISCONNECT_PREFIX - return lines.filter { !(it.matches(JDI_BUG_OUTPUT_PATTERN_1) || it.matches( - JDI_BUG_OUTPUT_PATTERN_2 - )) }.joinToString("\n") + return lines.filter { + !(it.matches(JDI_BUG_OUTPUT_PATTERN_1) || it.matches(JDI_BUG_OUTPUT_PATTERN_2)) + }.joinToString("\n") } private fun buildOutputString(): String { diff --git a/idea/jvm-debugger/jvm-debugger-util/src/org/jetbrains/kotlin/idea/debugger/FileRankingCalculator.kt b/idea/jvm-debugger/jvm-debugger-util/src/org/jetbrains/kotlin/idea/debugger/FileRankingCalculator.kt index 15317bb675c..e40ee6302fc 100644 --- a/idea/jvm-debugger/jvm-debugger-util/src/org/jetbrains/kotlin/idea/debugger/FileRankingCalculator.kt +++ b/idea/jvm-debugger/jvm-debugger-util/src/org/jetbrains/kotlin/idea/debugger/FileRankingCalculator.kt @@ -1,5 +1,5 @@ /* - * Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -239,7 +239,7 @@ abstract class FileRankingCalculator(private val checkClassFqName: Boolean = tru val containingClass = elementAt.getParentOfType(false) ?: return LOW val constructorOrInitializer = elementAt.getParentOfTypes2, KtClassInitializer>()?.takeIf { containingClass.isAncestor(it) } - ?: containingClass.primaryConstructor?.takeIf { it.getLine() == containingClass.getLine() } + ?: containingClass.primaryConstructor?.takeIf { it.getLine() == containingClass.getLine() } if (constructorOrInitializer == null && locationLineNumber < containingClass.getLine() diff --git a/idea/jvm-debugger/jvm-debugger-util/src/org/jetbrains/kotlin/idea/debugger/KotlinEditorTextProvider.kt b/idea/jvm-debugger/jvm-debugger-util/src/org/jetbrains/kotlin/idea/debugger/KotlinEditorTextProvider.kt index 0c9cdca28f2..a021558eb2c 100644 --- a/idea/jvm-debugger/jvm-debugger-util/src/org/jetbrains/kotlin/idea/debugger/KotlinEditorTextProvider.kt +++ b/idea/jvm-debugger/jvm-debugger-util/src/org/jetbrains/kotlin/idea/debugger/KotlinEditorTextProvider.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.debugger @@ -102,8 +91,7 @@ class KotlinEditorTextProvider : EditorTextProvider { val qualifier = context[BindingContext.QUALIFIER, ktElement] if (qualifier != null && !DescriptorUtils.isObject(qualifier.descriptor)) { null - } - else { + } else { ktElement } } @@ -113,11 +101,10 @@ class KotlinEditorTextProvider : EditorTextProvider { } private val NOT_ACCEPTED_AS_CONTEXT_TYPES = - arrayOf(KtUserType::class.java, KtImportDirective::class.java, KtPackageDirective::class.java, KtValueArgumentName::class.java) + arrayOf(KtUserType::class.java, KtImportDirective::class.java, KtPackageDirective::class.java, KtValueArgumentName::class.java) - fun isAcceptedAsCodeFragmentContext(element: PsiElement): Boolean { - return !NOT_ACCEPTED_AS_CONTEXT_TYPES.contains(element::class.java as Class<*>) && - PsiTreeUtil.getParentOfType(element, *NOT_ACCEPTED_AS_CONTEXT_TYPES) == null - } + fun isAcceptedAsCodeFragmentContext(element: PsiElement): Boolean = + !NOT_ACCEPTED_AS_CONTEXT_TYPES.contains(element::class.java as Class<*>) && + PsiTreeUtil.getParentOfType(element, *NOT_ACCEPTED_AS_CONTEXT_TYPES) == null } } \ No newline at end of file diff --git a/idea/jvm-debugger/jvm-debugger-util/src/org/jetbrains/kotlin/idea/debugger/NoStrataPositionManagerHelper.kt b/idea/jvm-debugger/jvm-debugger-util/src/org/jetbrains/kotlin/idea/debugger/NoStrataPositionManagerHelper.kt index 8df6e171f60..d42bcc41bf8 100644 --- a/idea/jvm-debugger/jvm-debugger-util/src/org/jetbrains/kotlin/idea/debugger/NoStrataPositionManagerHelper.kt +++ b/idea/jvm-debugger/jvm-debugger-util/src/org/jetbrains/kotlin/idea/debugger/NoStrataPositionManagerHelper.kt @@ -22,10 +22,10 @@ import com.sun.jdi.ReferenceType import com.sun.jdi.VirtualMachine import org.jetbrains.kotlin.idea.caches.project.implementingModules import org.jetbrains.kotlin.idea.caches.resolve.analyze -import org.jetbrains.kotlin.idea.debugger.evaluate.KotlinDebuggerCaches import org.jetbrains.kotlin.idea.core.util.getLineCount import org.jetbrains.kotlin.idea.core.util.getLineStartOffset import org.jetbrains.kotlin.idea.core.util.toPsiFile +import org.jetbrains.kotlin.idea.debugger.evaluate.KotlinDebuggerCaches import org.jetbrains.kotlin.idea.util.ProjectRootsUtil import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.lexer.KtTokens @@ -55,14 +55,18 @@ fun isInlineFunctionLineNumber(file: VirtualFile, lineNumber: Int, project: Proj return true } -fun readBytecodeInfo(project: Project, - jvmName: JvmClassName, - file: VirtualFile): BytecodeDebugInfo? { +fun readBytecodeInfo( + project: Project, + jvmName: JvmClassName, + file: VirtualFile +): BytecodeDebugInfo? { return KotlinDebuggerCaches.getOrReadDebugInfoFromBytecode(project, jvmName, file) } -fun ktLocationInfo(location: Location, isDexDebug: Boolean, project: Project, - preferInlined: Boolean = false, locationFile: KtFile? = null): Pair { +fun ktLocationInfo( + location: Location, isDexDebug: Boolean, project: Project, + preferInlined: Boolean = false, locationFile: KtFile? = null +): Pair { if (isDexDebug && (locationFile == null || location.lineNumber() > locationFile.getLineCount())) { if (!preferInlined) { val thisFunLine = runReadAction { getLastLineNumberForLocation(location, project) } @@ -85,7 +89,11 @@ fun ktLocationInfo(location: Location, isDexDebug: Boolean, project: Project, * Only the first line number is stored for instruction in dex. It can be obtained through location.lineNumber(). * This method allows to get last stored linenumber for instruction. */ -fun getLastLineNumberForLocation(location: Location, project: Project, searchScope: GlobalSearchScope = GlobalSearchScope.allScope(project)): Int? { +fun getLastLineNumberForLocation( + location: Location, + project: Project, + searchScope: GlobalSearchScope = GlobalSearchScope.allScope(project) +): Int? { val lineNumber = location.lineNumber() val fqName = FqName(location.declaringType().name()) val fileName = location.sourceName() @@ -94,7 +102,8 @@ fun getLastLineNumberForLocation(location: Location, project: Project, searchSco val name = method.name() ?: return null val signature = method.signature() ?: return null - val debugInfo = findAndReadClassFile(fqName, fileName, project, searchScope, { isInlineFunctionLineNumber(it, lineNumber, project) }) ?: return null + val debugInfo = + findAndReadClassFile(fqName, fileName, project, searchScope, { isInlineFunctionLineNumber(it, lineNumber, project) }) ?: return null val lineMapping = debugInfo.lineTableMapping[BytecodeMethodKey(name, signature)] ?: return null return lineMapping.values.firstOrNull { it.contains(lineNumber) }?.last() @@ -117,9 +126,11 @@ data class BytecodeMethodKey(val methodName: String, val signature: String) data class BinaryCacheKey(val project: Project, val jvmName: JvmClassName, val file: VirtualFile) -private fun readClassFileImpl(project: Project, - jvmName: JvmClassName, - file: VirtualFile): ByteArray? { +private fun readClassFileImpl( + project: Project, + jvmName: JvmClassName, + file: VirtualFile +): ByteArray? { val fqNameWithInners = jvmName.fqNameForClassNameWithoutDollars.tail(jvmName.packageFqName) fun readFromLibrary(): ByteArray? { @@ -175,13 +186,11 @@ private fun readClassFileImpl(project: Project, fun readFromTestOutput(): ByteArray? = readFromOutput(true) - return readFromLibrary() ?: - readFromSourceOutput() ?: - readFromTestOutput() + return readFromLibrary() ?: readFromSourceOutput() ?: readFromTestOutput() } private fun findClassFileByPaths(packageName: String, className: String, paths: List): File? = - paths.mapNotNull { path -> findClassFileByPath(packageName, className, path) }.maxBy { it.lastModified() } + paths.mapNotNull { path -> findClassFileByPath(packageName, className, path) }.maxBy { it.lastModified() } private fun findClassFileByPath(packageName: String, className: String, outputDirPath: String): File? { val outDirFile = File(outputDirPath).takeIf(File::exists) ?: return null @@ -208,7 +217,13 @@ private fun readLineNumberTableMapping(bytes: ByteArray): Map>>() ClassReader(bytes).accept(object : ClassVisitor(Opcodes.API_VERSION) { - override fun visitMethod(access: Int, name: String?, desc: String?, signature: String?, exceptions: Array?): MethodVisitor? { + override fun visitMethod( + access: Int, + name: String?, + desc: String?, + signature: String?, + exceptions: Array? + ): MethodVisitor? { if (name == null || desc == null) { return null } @@ -236,16 +251,17 @@ internal fun getOriginalPositionOfInlinedLine(location: Location, project: Proje val fileName = location.sourceName() val searchScope = GlobalSearchScope.allScope(project) - val debugInfo = findAndReadClassFile(fqName, fileName, project, searchScope, { isInlineFunctionLineNumber(it, lineNumber, project) }) ?: - return null + val debugInfo = + findAndReadClassFile(fqName, fileName, project, searchScope) { isInlineFunctionLineNumber(it, lineNumber, project) } ?: return null val smapData = debugInfo.smapData ?: return null return mapStacktraceLineToSource(smapData, lineNumber, project, SourceLineKind.EXECUTED_LINE, searchScope) } private fun findAndReadClassFile( - fqName: FqName, fileName: String, project: Project, searchScope: GlobalSearchScope, - fileFilter: (VirtualFile) -> Boolean): BytecodeDebugInfo? { + fqName: FqName, fileName: String, project: Project, searchScope: GlobalSearchScope, + fileFilter: (VirtualFile) -> Boolean +): BytecodeDebugInfo? { val internalName = fqName.asString().replace('.', '/') val jvmClassName = JvmClassName.byInternalName(internalName) @@ -285,7 +301,8 @@ fun isInCrossinlineArgument(ktElement: KtElement): Boolean { val argumentFunctions = runReadAction { ktElement.parents.filter { when (it) { - is KtFunctionLiteral -> it.parent is KtLambdaExpression && (it.parent.parent is KtValueArgument || it.parent.parent is KtLambdaArgument) + is KtFunctionLiteral -> it.parent is KtLambdaExpression && + (it.parent.parent is KtValueArgument || it.parent.parent is KtLambdaArgument) is KtFunction -> it.parent is KtValueArgument else -> false } @@ -301,14 +318,15 @@ fun isInCrossinlineArgument(ktElement: KtElement): Boolean { private fun inlinedLinesNumbers( - inlineLineNumber: Int, inlineFileName: String, - destinationTypeFqName: FqName, destinationFileName: String, - project: Project, sourceSearchScope: GlobalSearchScope): List { + inlineLineNumber: Int, inlineFileName: String, + destinationTypeFqName: FqName, destinationFileName: String, + project: Project, sourceSearchScope: GlobalSearchScope +): List { val internalName = destinationTypeFqName.asString().replace('.', '/') val jvmClassName = JvmClassName.byInternalName(internalName) - val file = DebuggerUtils.findSourceFileForClassIncludeLibrarySources(project, sourceSearchScope, jvmClassName, destinationFileName) ?: - return listOf() + val file = DebuggerUtils.findSourceFileForClassIncludeLibrarySources(project, sourceSearchScope, jvmClassName, destinationFileName) + ?: return listOf() val virtualFile = file.virtualFile ?: return listOf() @@ -320,14 +338,12 @@ private fun inlinedLinesNumbers( val mappingsToInlinedFile = smap.fileMappings.filter { it.name == inlineFileName } val mappingIntervals = mappingsToInlinedFile.flatMap { it.lineMappings } - return mappingIntervals.asSequence(). - filter { rangeMapping -> rangeMapping.hasMappingForSource(inlineLineNumber) }. - map { rangeMapping -> rangeMapping.mapSourceToDest(inlineLineNumber) }. - filter { line -> line != -1 }. - toList() + return mappingIntervals.asSequence().filter { rangeMapping -> rangeMapping.hasMappingForSource(inlineLineNumber) } + .map { rangeMapping -> rangeMapping.mapSourceToDest(inlineLineNumber) }.filter { line -> line != -1 }.toList() } -@Volatile var emulateDexDebugInTests: Boolean = false +@Volatile +var emulateDexDebugInTests: Boolean = false fun DebugProcess.isDexDebug(): Boolean { val virtualMachine = (this.virtualMachineProxy as? VirtualMachineProxyImpl)?.virtualMachine diff --git a/idea/jvm-debugger/jvm-debugger-util/src/org/jetbrains/kotlin/idea/debugger/hopelessExceptionUtil.kt b/idea/jvm-debugger/jvm-debugger-util/src/org/jetbrains/kotlin/idea/debugger/hopelessExceptionUtil.kt index 0835fb1776a..61b00d5a1c9 100644 --- a/idea/jvm-debugger/jvm-debugger-util/src/org/jetbrains/kotlin/idea/debugger/hopelessExceptionUtil.kt +++ b/idea/jvm-debugger/jvm-debugger-util/src/org/jetbrains/kotlin/idea/debugger/hopelessExceptionUtil.kt @@ -23,7 +23,8 @@ inline fun hopelessAware(block: () -> T?): T? { fun handleHopelessException(e: Exception) { when (if (e is EvaluateException) e.cause ?: e else e) { - is IncompatibleThreadStateException, is VMDisconnectedException -> {} + is IncompatibleThreadStateException, is VMDisconnectedException -> { + } else -> { if (e is EvaluateException) { LOG.debug("Cannot evaluate async stack trace", e) diff --git a/idea/jvm-debugger/jvm-debugger-util/src/org/jetbrains/kotlin/idea/debugger/smapUtil.kt b/idea/jvm-debugger/jvm-debugger-util/src/org/jetbrains/kotlin/idea/debugger/smapUtil.kt index 08385f8f581..2b480faa8e2 100644 --- a/idea/jvm-debugger/jvm-debugger-util/src/org/jetbrains/kotlin/idea/debugger/smapUtil.kt +++ b/idea/jvm-debugger/jvm-debugger-util/src/org/jetbrains/kotlin/idea/debugger/smapUtil.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.debugger @@ -32,15 +21,17 @@ enum class SourceLineKind { EXECUTED_LINE } -fun mapStacktraceLineToSource(smapData: SmapData, - line: Int, - project: Project, - lineKind: SourceLineKind, - searchScope: GlobalSearchScope): Pair? { +fun mapStacktraceLineToSource( + smapData: SmapData, + line: Int, + project: Project, + lineKind: SourceLineKind, + searchScope: GlobalSearchScope +): Pair? { val smap = when (lineKind) { - SourceLineKind.CALL_LINE -> smapData.kotlinDebugStrata - SourceLineKind.EXECUTED_LINE -> smapData.kotlinStrata - } ?: return null + SourceLineKind.CALL_LINE -> smapData.kotlinDebugStrata + SourceLineKind.EXECUTED_LINE -> smapData.kotlinStrata + } ?: return null val mappingInfo = smap.fileMappings.firstOrNull { it.getIntervalIfContains(line) != null @@ -48,7 +39,8 @@ fun mapStacktraceLineToSource(smapData: SmapData, val jvmName = JvmClassName.byInternalName(mappingInfo.path) val sourceFile = DebuggerUtils.findSourceFileForClassIncludeLibrarySources( - project, searchScope, jvmName, mappingInfo.name) ?: return null + project, searchScope, jvmName, mappingInfo.name + ) ?: return null val interval = mappingInfo.getIntervalIfContains(line)!! val sourceLine = when (lineKind) { diff --git a/idea/kotlin-gradle-tooling/src/KotlinGradleModelBuilder.kt b/idea/kotlin-gradle-tooling/src/KotlinGradleModelBuilder.kt index 9321919b57f..fa7c4b64801 100644 --- a/idea/kotlin-gradle-tooling/src/KotlinGradleModelBuilder.kt +++ b/idea/kotlin-gradle-tooling/src/KotlinGradleModelBuilder.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.gradle @@ -24,7 +13,6 @@ import org.jetbrains.plugins.gradle.tooling.ErrorMessageBuilder import org.jetbrains.plugins.gradle.tooling.ModelBuilderService import java.io.File import java.io.Serializable -import java.lang.Exception import java.lang.reflect.InvocationTargetException import java.util.* @@ -104,13 +92,11 @@ abstract class AbstractKotlinGradleModelBuilder : ModelBuilderService { val kotlinPluginWrapper = "org.jetbrains.kotlin.gradle.plugin.KotlinPluginWrapperKt" - fun Task.getSourceSetName(): String { - return try { - javaClass.methods.firstOrNull { it.name.startsWith("getSourceSetName") && it.parameterTypes.isEmpty() }?.invoke(this) as? String - } catch (e: InvocationTargetException) { - null // can be thrown if property is not initialized yet - } ?: "main" - } + fun Task.getSourceSetName(): String = try { + javaClass.methods.firstOrNull { it.name.startsWith("getSourceSetName") && it.parameterTypes.isEmpty() }?.invoke(this) as? String + } catch (e: InvocationTargetException) { + null // can be thrown if property is not initialized yet + } ?: "main" } } diff --git a/idea/kotlin-gradle-tooling/src/KotlinMPPGradleModel.kt b/idea/kotlin-gradle-tooling/src/KotlinMPPGradleModel.kt index 0bc865f0001..ab17d84aa42 100644 --- a/idea/kotlin-gradle-tooling/src/KotlinMPPGradleModel.kt +++ b/idea/kotlin-gradle-tooling/src/KotlinMPPGradleModel.kt @@ -1,5 +1,5 @@ /* - * Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -55,6 +55,7 @@ interface KotlinSourceSet : KotlinModule { val resourceDirs: Set val dependsOnSourceSets: Set val actualPlatforms: KotlinPlatformContainer + @Deprecated("Returns single target platform", ReplaceWith("actualPlatforms.actualPlatforms"), DeprecationLevel.ERROR) val platform: KotlinPlatform get() = actualPlatforms.getSinglePlatform() diff --git a/idea/kotlin-gradle-tooling/src/KotlinMPPGradleModelBuilder.kt b/idea/kotlin-gradle-tooling/src/KotlinMPPGradleModelBuilder.kt index de92719d8fa..2dd27f2920c 100644 --- a/idea/kotlin-gradle-tooling/src/KotlinMPPGradleModelBuilder.kt +++ b/idea/kotlin-gradle-tooling/src/KotlinMPPGradleModelBuilder.kt @@ -1,11 +1,14 @@ /* - * Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.gradle -import org.gradle.api.* +import org.gradle.api.Named +import org.gradle.api.NamedDomainObjectContainer +import org.gradle.api.Project +import org.gradle.api.Task import org.gradle.api.artifacts.Configuration import org.gradle.api.artifacts.Dependency import org.gradle.api.artifacts.component.ProjectComponentIdentifier @@ -73,7 +76,8 @@ class KotlinMPPGradleModelBuilder : ModelBuilderService { project: Project ): Map { if (project.properties["import_orphan_source_sets"]?.toString()?.toBoolean() ?: DEFAULT_IMPORT_ORPHAN_SOURCE_SETS) return sourceSets - val compiledSourceSets: Collection = targets.flatMap { it.compilations }.flatMap { it.sourceSets }.flatMap { it.dependsOnSourceSets.union(listOf(it.name)) }.distinct() + val compiledSourceSets: Collection = targets.flatMap { it.compilations } + .flatMap { it.sourceSets }.flatMap { it.dependsOnSourceSets.union(listOf(it.name)) }.distinct() sourceSets.filter { !compiledSourceSets.contains(it.key) }.forEach { logger.warn("[sync warning] Source set \"${it.key}\" is not compiled with any compilation. This source set is not imported in the IDE.") } @@ -90,8 +94,7 @@ class KotlinMPPGradleModelBuilder : ModelBuilderService { } private fun reportUnresolvedDependencies(targets: Collection) { - targets - .asSequence() + targets.asSequence() .flatMap { it.compilations.asSequence() } .flatMap { it.dependencies.asSequence() } .mapNotNull { (it as? UnresolvedExternalDependency)?.failureMessage } @@ -126,9 +129,14 @@ class KotlinMPPGradleModelBuilder : ModelBuilderService { } } - private fun buildSourceSets(dependencyResolver: DependencyResolver, project: Project, dependencyMapper: KotlinDependencyMapper): Collection? { + private fun buildSourceSets( + dependencyResolver: DependencyResolver, + project: Project, + dependencyMapper: KotlinDependencyMapper + ): Collection? { val kotlinExt = project.extensions.findByName("kotlin") ?: return null val getSourceSets = kotlinExt.javaClass.getMethodOrNull("getSourceSets") ?: return null + @Suppress("UNCHECKED_CAST") val sourceSets = (getSourceSets(kotlinExt) as? NamedDomainObjectContainer)?.asMap?.values ?: emptyList() @@ -139,10 +147,10 @@ class KotlinMPPGradleModelBuilder : ModelBuilderService { ?: DEFAULT_BUILD_METADATA_DEPENDENCIES_FOR_ACTUALISED_SOURCE_SETS val allSourceSetsProtos = sourceSets.mapNotNull { buildSourceSet(it, dependencyResolver, project, dependencyMapper) } val allSourceSets = if (doBuildMetadataDependencies) { - allSourceSetsProtos.map { proto -> proto.buildKotlinSourceSetImpl(true)} + allSourceSetsProtos.map { proto -> proto.buildKotlinSourceSetImpl(true) } } else { val unactualizedSourceSets = allSourceSetsProtos.flatMap { it.dependsOnSourceSets }.distinct() - allSourceSetsProtos.map { proto -> proto.buildKotlinSourceSetImpl(unactualizedSourceSets.contains(proto.name))} + allSourceSetsProtos.map { proto -> proto.buildKotlinSourceSetImpl(unactualizedSourceSets.contains(proto.name)) } } val map = allSourceSets.map { it.name to it }.toMap() @@ -361,7 +369,10 @@ class KotlinMPPGradleModelBuilder : ModelBuilderService { return target } - private fun KotlinCompilationImpl.addDependsOnSourceSetsToCompilation(sourceSetMap: Map, isHMPPEnabled: Boolean): KotlinCompilationImpl { + private fun KotlinCompilationImpl.addDependsOnSourceSetsToCompilation( + sourceSetMap: Map, + isHMPPEnabled: Boolean + ): KotlinCompilationImpl { val dependsOnSourceSets = this.sourceSets.flatMap { it.dependsOnSourceSets }.mapNotNull { sourceSetMap[it] } if (!isHMPPEnabled) { @@ -388,7 +399,8 @@ class KotlinMPPGradleModelBuilder : ModelBuilderService { if (getTestRunsMethod != null) { val testRuns = getTestRunsMethod?.invoke(gradleTarget) as? Iterable if (testRuns != null) { - val testReports = testRuns.mapNotNull { (it.javaClass.getMethodOrNull("getExecutionTask")?.invoke(it) as? TaskProvider)?.get() } + val testReports = + testRuns.mapNotNull { (it.javaClass.getMethodOrNull("getExecutionTask")?.invoke(it) as? TaskProvider)?.get() } val testTasks = testReports.flatMap { ((it.javaClass.getMethodOrNull("getTestTasks")?.invoke(it) as? Collection)?.mapNotNull { when { @@ -402,7 +414,8 @@ class KotlinMPPGradleModelBuilder : ModelBuilderService { return testTasks.mapNotNull { val name = it.name val compilation = it.javaClass.getMethodOrNull("getCompilation")?.invoke(it) - val compilationName = compilation?.javaClass?.getMethodOrNull("getCompilationName")?.invoke(compilation)?.toString() ?: KotlinCompilation.TEST_COMPILATION_NAME + val compilationName = compilation?.javaClass?.getMethodOrNull("getCompilationName")?.invoke(compilation)?.toString() + ?: KotlinCompilation.TEST_COMPILATION_NAME KotlinTestTaskImpl(name, compilationName) }.toList() } @@ -436,7 +449,7 @@ class KotlinMPPGradleModelBuilder : ModelBuilderService { val getJvmTargetName = jvmTestTaskClass.getDeclaredMethodOrNull("getTargetName") ?: return emptyList() - return project.tasks.filter { kotlinTestTaskClass.isInstance(it) || jvmTestTaskClass.isInstance(it)}.mapNotNull { task -> + return project.tasks.filter { kotlinTestTaskClass.isInstance(it) || jvmTestTaskClass.isInstance(it) }.mapNotNull { task -> val testTaskDisambiguationClassifier = (if (kotlinTestTaskClass.isInstance(task)) getTargetName(task) else getJvmTargetName(task)) as String? task.name.takeIf { @@ -469,6 +482,7 @@ class KotlinMPPGradleModelBuilder : ModelBuilderService { ): KotlinCompilationImpl? { val compilationClass = gradleCompilation.javaClass val getKotlinSourceSets = compilationClass.getMethodOrNull("getKotlinSourceSets") ?: return null + @Suppress("UNCHECKED_CAST") val kotlinGradleSourceSets = (getKotlinSourceSets(gradleCompilation) as? Collection) ?: return null val kotlinSourceSets = kotlinGradleSourceSets.mapNotNull { sourceSetMap[it.name] } @@ -834,6 +848,7 @@ class KotlinMPPGradleModelBuilder : ModelBuilderService { fun getCompileKotlinTaskName(project: Project, compilation: Named): Task? { val compilationClass = compilation.javaClass val getCompileKotlinTaskName = compilationClass.getMethodOrNull("getCompileKotlinTaskName") ?: return null + @Suppress("UNCHECKED_CAST") val compileKotlinTaskName = (getCompileKotlinTaskName(compilation) as? String) ?: return null return project.tasks.findByName(compileKotlinTaskName) ?: return null diff --git a/idea/kotlin-gradle-tooling/src/KotlinMPPGradleModelImpl.kt b/idea/kotlin-gradle-tooling/src/KotlinMPPGradleModelImpl.kt index 5c89900b365..fdfc5d0f953 100644 --- a/idea/kotlin-gradle-tooling/src/KotlinMPPGradleModelImpl.kt +++ b/idea/kotlin-gradle-tooling/src/KotlinMPPGradleModelImpl.kt @@ -1,5 +1,5 @@ /* - * Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -7,7 +7,6 @@ package org.jetbrains.kotlin.gradle import org.gradle.api.tasks.Exec import java.io.File -import kotlin.collections.HashSet class KotlinSourceSetProto( val name: String, @@ -28,6 +27,7 @@ class KotlinSourceSetProto( ) } + class KotlinSourceSetImpl( override val name: String, override val languageSettings: KotlinLanguageSettings, @@ -177,9 +177,10 @@ data class KotlinTargetImpl( } }.toList(), target.testTasks.map { initialTestTask -> - (cloningCache[initialTestTask] as? KotlinTestTask) ?: KotlinTestTaskImpl(initialTestTask.taskName, initialTestTask.compilationName).also { - cloningCache[initialTestTask] = it - } + (cloningCache[initialTestTask] as? KotlinTestTask) + ?: KotlinTestTaskImpl(initialTestTask.taskName, initialTestTask.compilationName).also { + cloningCache[initialTestTask] = it + } }, KotlinTargetJarImpl(target.jar?.archiveFile), target.konanArtifacts.map { KonanArtifactModelImpl(it) }.toList() diff --git a/idea/performanceTests/org/jetbrains/kotlin/idea/testFramework/Fixture.kt b/idea/performanceTests/org/jetbrains/kotlin/idea/testFramework/Fixture.kt index 564c428f765..5c575b7e994 100644 --- a/idea/performanceTests/org/jetbrains/kotlin/idea/testFramework/Fixture.kt +++ b/idea/performanceTests/org/jetbrains/kotlin/idea/testFramework/Fixture.kt @@ -167,10 +167,10 @@ class Fixture(val project: Project, val editor: Editor, val psiFile: PsiFile, va val projectBaseName = baseName(project.name) val virtualFiles = FilenameIndex.getVirtualFilesByName( - project, - baseFileName, true, - GlobalSearchScope.projectScope(project) - ) + project, + baseFileName, true, + GlobalSearchScope.projectScope(project) + ) .filter { it.canonicalPath?.contains("/$projectBaseName/$name") ?: false }.toList() assertEquals( diff --git a/idea/scripting-support/test/org/jetbrains/kotlin/idea/scratch/AbstractScratchRunActionTest.kt b/idea/scripting-support/test/org/jetbrains/kotlin/idea/scratch/AbstractScratchRunActionTest.kt index c449af9ac30..5d000a0bd78 100644 --- a/idea/scripting-support/test/org/jetbrains/kotlin/idea/scratch/AbstractScratchRunActionTest.kt +++ b/idea/scripting-support/test/org/jetbrains/kotlin/idea/scratch/AbstractScratchRunActionTest.kt @@ -87,8 +87,18 @@ abstract class AbstractScratchRunActionTest : FileEditorManagerTestCase() { } val testDataPathFile = File(myFixture.testDataPath) - javaFiles.forEach { myFixture.copyFileToProject(FileUtil.getRelativePath(testDataPathFile, it)!!, FileUtil.getRelativePath(baseDir, it)!!) } - kotlinFiles.forEach { myFixture.copyFileToProject(FileUtil.getRelativePath(testDataPathFile, it)!!, FileUtil.getRelativePath(baseDir, it)!!) } + javaFiles.forEach { + myFixture.copyFileToProject( + FileUtil.getRelativePath(testDataPathFile, it)!!, + FileUtil.getRelativePath(baseDir, it)!! + ) + } + kotlinFiles.forEach { + myFixture.copyFileToProject( + FileUtil.getRelativePath(testDataPathFile, it)!!, + FileUtil.getRelativePath(baseDir, it)!! + ) + } val outputDir = createTempDir(dirName) diff --git a/idea/src/org/jetbrains/kotlin/idea/KotlinFoldingBuilder.kt b/idea/src/org/jetbrains/kotlin/idea/KotlinFoldingBuilder.kt index 5d7f4b9e023..1b8e2809e58 100644 --- a/idea/src/org/jetbrains/kotlin/idea/KotlinFoldingBuilder.kt +++ b/idea/src/org/jetbrains/kotlin/idea/KotlinFoldingBuilder.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea @@ -105,7 +94,7 @@ class KotlinFoldingBuilder : CustomFoldingBuilder(), DumbAware { private fun needFolding(node: ASTNode, document: Document): Boolean { val type = node.elementType val parentType = node.treeParent?.elementType - + if (type is KtFunctionElementType) { val bodyExpression = (node.psi as? KtNamedFunction)?.bodyExpression if (bodyExpression != null && bodyExpression !is KtBlockExpression) return true @@ -144,7 +133,7 @@ class KotlinFoldingBuilder : CustomFoldingBuilder(), DumbAware { return bodyExpression.textRange } } - + if (node.elementType == KtNodeTypes.FUNCTION_LITERAL) { val psi = node.psi as? KtFunctionLiteral val lbrace = psi?.lBrace @@ -162,7 +151,7 @@ class KotlinFoldingBuilder : CustomFoldingBuilder(), DumbAware { return TextRange(leftParenthesis.startOffset, rightParenthesis.endOffset) } } - + if (node.elementType == KtNodeTypes.WHEN) { val whenExpression = node.psi as? KtWhenExpression val openBrace = whenExpression?.openBrace diff --git a/idea/src/org/jetbrains/kotlin/idea/KotlinPluginUpdater.kt b/idea/src/org/jetbrains/kotlin/idea/KotlinPluginUpdater.kt index ac6ef8e1589..6765dd38a72 100644 --- a/idea/src/org/jetbrains/kotlin/idea/KotlinPluginUpdater.kt +++ b/idea/src/org/jetbrains/kotlin/idea/KotlinPluginUpdater.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -22,7 +22,6 @@ import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task -import com.intellij.openapi.project.Project import com.intellij.openapi.updateSettings.impl.PluginDownloader import com.intellij.openapi.updateSettings.impl.UpdateSettings import com.intellij.openapi.util.JDOMUtil @@ -94,6 +93,7 @@ class KotlinPluginUpdater : Disposable { @Volatile private var checkQueued = false + @Volatile private var lastUpdateStatus: PluginUpdateStatus? = null @@ -332,9 +332,11 @@ class KotlinPluginUpdater : Disposable { private class PluginDTO { var cdate: String? = null var channel: String? = null + // `true` if the version is seen in plugin site and available for download. // Maybe be `false` if author requested version deletion. var listed: Boolean = true + // `true` if version is approved and verified var approve: Boolean = true } diff --git a/idea/src/org/jetbrains/kotlin/idea/KotlinQuickDocumentationProvider.kt b/idea/src/org/jetbrains/kotlin/idea/KotlinQuickDocumentationProvider.kt index fa8623406ab..59a3cb951f2 100644 --- a/idea/src/org/jetbrains/kotlin/idea/KotlinQuickDocumentationProvider.kt +++ b/idea/src/org/jetbrains/kotlin/idea/KotlinQuickDocumentationProvider.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea @@ -241,7 +230,7 @@ class KotlinQuickDocumentationProvider : AbstractDocumentationProvider() { // so reference extracted from originalElement val context = referenceExpression.analyze(BodyResolveMode.PARTIAL) (context[BindingContext.REFERENCE_TARGET, referenceExpression] - ?: context[BindingContext.REFERENCE_TARGET, referenceExpression.getChildOfType()])?.let { + ?: context[BindingContext.REFERENCE_TARGET, referenceExpression.getChildOfType()])?.let { if (it is FunctionDescriptor) // To protect from SomeEnum.values() return renderEnumSpecialFunction(element, it, quickNavigation) } @@ -255,7 +244,8 @@ class KotlinQuickDocumentationProvider : AbstractDocumentationProvider() { return try { getTextImpl(element, originalElement, quickNavigation) } catch (_: IndexNotReadyException) { - DumbService.getInstance(element.project).showDumbModeNotification("Element information is not available during index update") + DumbService.getInstance(element.project) + .showDumbModeNotification("Element information is not available during index update") null } } @@ -304,7 +294,7 @@ class KotlinQuickDocumentationProvider : AbstractDocumentationProvider() { val origin = element.kotlinOrigin ?: return null return renderKotlinDeclaration(origin, quickNavigation) } else if (element.isModifier()) { - when(element.text) { + when (element.text) { KtTokens.LATEINIT_KEYWORD.value -> { return "lateinit allows initializing a ${a( LATE_INITIALIZED_PROPERTIES_AND_VARIABLES_URL, @@ -515,7 +505,7 @@ class KotlinQuickDocumentationProvider : AbstractDocumentationProvider() { val originalInfo = JavaDocumentationProvider().getQuickNavigateInfo(element, originalElement) if (originalInfo != null) { val renderedDecl = constant { DESCRIPTOR_RENDERER.withOptions { withDefinedIn = false } }.render(declarationDescriptor) - return renderedDecl + "
    Java declaration:
    " + originalInfo + return "$renderedDecl
    Java declaration:
    $originalInfo" } return null @@ -530,9 +520,8 @@ class KotlinQuickDocumentationProvider : AbstractDocumentationProvider() { } } - private fun PsiElement?.isModifier() = this != null - && parent is KtModifierList - && KtTokens.MODIFIER_KEYWORDS_ARRAY.firstOrNull { it.value == text } != null + private fun PsiElement?.isModifier() = + this != null && parent is KtModifierList && KtTokens.MODIFIER_KEYWORDS_ARRAY.firstOrNull { it.value == text } != null } } diff --git a/idea/src/org/jetbrains/kotlin/idea/actions/DecompileKotlinToJavaAction.kt b/idea/src/org/jetbrains/kotlin/idea/actions/DecompileKotlinToJavaAction.kt index 6d17f7d8c6e..4f7123ea20e 100644 --- a/idea/src/org/jetbrains/kotlin/idea/actions/DecompileKotlinToJavaAction.kt +++ b/idea/src/org/jetbrains/kotlin/idea/actions/DecompileKotlinToJavaAction.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.actions @@ -56,7 +45,10 @@ fun KtFile.canBeDecompiledToJava() = isCompiled && virtualFile?.fileType == Java // Add action to "Attach sources" notification panel class DecompileKotlinToJavaActionProvider : AttachSourcesProvider { - override fun getActions(orderEntries: MutableList, psiFile: PsiFile): Collection { + override fun getActions( + orderEntries: MutableList, + psiFile: PsiFile + ): Collection { if (psiFile !is KtFile || !psiFile.canBeDecompiledToJava()) return emptyList() return listOf(object : AttachSourcesProvider.AttachSourcesAction { diff --git a/idea/src/org/jetbrains/kotlin/idea/actions/KotlinCreateFromTemplateHandler.kt b/idea/src/org/jetbrains/kotlin/idea/actions/KotlinCreateFromTemplateHandler.kt index 6a721bae904..213d1c67421 100644 --- a/idea/src/org/jetbrains/kotlin/idea/actions/KotlinCreateFromTemplateHandler.kt +++ b/idea/src/org/jetbrains/kotlin/idea/actions/KotlinCreateFromTemplateHandler.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.actions @@ -27,9 +16,7 @@ class KotlinCreateFromTemplateHandler : DefaultCreateFromTemplateHandler() { override fun prepareProperties(props: MutableMap) { val packageName = props[FileTemplate.ATTRIBUTE_PACKAGE_NAME] as? String if (!packageName.isNullOrEmpty()) { - props[FileTemplate.ATTRIBUTE_PACKAGE_NAME] = packageName - .split('.') - .joinToString(".", transform = String::quoteIfNeeded) + props[FileTemplate.ATTRIBUTE_PACKAGE_NAME] = packageName.split('.').joinToString(".", transform = String::quoteIfNeeded) } val name = props[FileTemplate.ATTRIBUTE_NAME] as? String diff --git a/idea/src/org/jetbrains/kotlin/idea/actions/KotlinQualifiedNameProvider.kt b/idea/src/org/jetbrains/kotlin/idea/actions/KotlinQualifiedNameProvider.kt index c9a46b15705..9ab928fc2ea 100644 --- a/idea/src/org/jetbrains/kotlin/idea/actions/KotlinQualifiedNameProvider.kt +++ b/idea/src/org/jetbrains/kotlin/idea/actions/KotlinQualifiedNameProvider.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.actions @@ -26,10 +15,10 @@ import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.KtProperty -class KotlinQualifiedNameProvider: QualifiedNameProvider { +class KotlinQualifiedNameProvider : QualifiedNameProvider { override fun adjustElementToCopy(element: PsiElement?) = null - override fun getQualifiedName(element: PsiElement?) = when(element) { + override fun getQualifiedName(element: PsiElement?) = when (element) { is KtClassOrObject -> element.fqName?.asString() is KtNamedFunction -> getJavaQualifiedName(LightClassUtil.getLightClassMethod(element)) diff --git a/idea/src/org/jetbrains/kotlin/idea/actions/generate/KotlinGenerateActionBase.kt b/idea/src/org/jetbrains/kotlin/idea/actions/generate/KotlinGenerateActionBase.kt index 6ce1944f760..87882370f2a 100644 --- a/idea/src/org/jetbrains/kotlin/idea/actions/generate/KotlinGenerateActionBase.kt +++ b/idea/src/org/jetbrains/kotlin/idea/actions/generate/KotlinGenerateActionBase.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.actions.generate @@ -31,12 +20,12 @@ import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType abstract class KotlinGenerateActionBase : CodeInsightAction(), CodeInsightActionHandler { override fun update( - presentation: Presentation, - project: Project, - editor: Editor, - file: PsiFile, - dataContext: DataContext, - actionPlace: String? + presentation: Presentation, + project: Project, + editor: Editor, + file: PsiFile, + dataContext: DataContext, + actionPlace: String? ) { super.update(presentation, project, editor, file, dataContext, actionPlace) val actionHandler = handler diff --git a/idea/src/org/jetbrains/kotlin/idea/actions/generate/KotlinGenerateSecondaryConstructorAction.kt b/idea/src/org/jetbrains/kotlin/idea/actions/generate/KotlinGenerateSecondaryConstructorAction.kt index 77dbc69032d..c82358ae0a3 100644 --- a/idea/src/org/jetbrains/kotlin/idea/actions/generate/KotlinGenerateSecondaryConstructorAction.kt +++ b/idea/src/org/jetbrains/kotlin/idea/actions/generate/KotlinGenerateSecondaryConstructorAction.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.actions.generate @@ -49,9 +38,9 @@ import java.util.* class KotlinGenerateSecondaryConstructorAction : KotlinGenerateMemberActionBase() { class Info( - val propertiesToInitialize: List, - val superConstructors: List, - val classDescriptor: ClassDescriptor + val propertiesToInitialize: List, + val superConstructors: List, + val classDescriptor: ClassDescriptor ) override fun isValidForClass(targetClass: KtClassOrObject): Boolean { @@ -68,8 +57,8 @@ class KotlinGenerateSecondaryConstructorAction : KotlinGenerateMemberActionBase< val project = klass.project val superClassDescriptor = classDescriptor.getSuperClassNotAny() ?: return emptyList() val candidates = superClassDescriptor.constructors - .filter { it.isVisible(classDescriptor) } - .map { DescriptorMemberChooserObject(DescriptorToSourceUtilsIde.getAnyDeclaration(project, it) ?: klass, it) } + .filter { it.isVisible(classDescriptor) } + .map { DescriptorMemberChooserObject(DescriptorToSourceUtilsIde.getAnyDeclaration(project, it) ?: klass, it) } if (ApplicationManager.getApplication().isUnitTestMode || candidates.size <= 1) return candidates return with(MemberChooser(candidates.toTypedArray(), false, true, klass.project)) { @@ -115,7 +104,8 @@ class KotlinGenerateSecondaryConstructorAction : KotlinGenerateMemberActionBase< fun Info.findAnchor(): PsiElement? { targetClass.declarations.lastIsInstanceOrNull()?.let { return it } val lastPropertyToInitialize = propertiesToInitialize.lastOrNull()?.source?.getPsi() - val declarationsAfter = lastPropertyToInitialize?.siblings()?.filterIsInstance() ?: targetClass.declarations.asSequence() + val declarationsAfter = + lastPropertyToInitialize?.siblings()?.filterIsInstance() ?: targetClass.declarations.asSequence() val firstNonProperty = declarationsAfter.firstOrNull { it !is KtProperty } ?: return null return firstNonProperty.siblings(forward = false).firstIsInstanceOrNull() ?: targetClass.getOrCreateBody().lBrace } @@ -137,9 +127,9 @@ class KotlinGenerateSecondaryConstructorAction : KotlinGenerateMemberActionBase< } private fun generateConstructor( - classDescriptor: ClassDescriptor, - propertiesToInitialize: List, - superConstructor: ConstructorDescriptor? + classDescriptor: ClassDescriptor, + propertiesToInitialize: List, + superConstructor: ConstructorDescriptor? ): KtSecondaryConstructor? { fun equalTypes(types1: Collection, types2: Collection): Boolean { return types1.size == types2.size && (types1.zip(types2)).all { KotlinTypeChecker.DEFAULT.equalTypes(it.first, it.second) } @@ -148,8 +138,11 @@ class KotlinGenerateSecondaryConstructorAction : KotlinGenerateMemberActionBase< val constructorParamTypes = propertiesToInitialize.map { it.type } + (superConstructor?.valueParameters?.map { it.varargElementType ?: it.type } ?: emptyList()) - if (classDescriptor.constructors.any { it.source.getPsi() is KtConstructor<*> - && equalTypes(it.valueParameters.map { it.varargElementType ?: it.type }, constructorParamTypes) }) return null + if (classDescriptor.constructors.any { descriptor -> + descriptor.source.getPsi() is KtConstructor<*> && + equalTypes(descriptor.valueParameters.map { it.varargElementType ?: it.type }, constructorParamTypes) + } + ) return null val targetClass = classDescriptor.source.getPsi() as KtClass val psiFactory = KtPsiFactory(targetClass) @@ -161,7 +154,7 @@ class KotlinGenerateSecondaryConstructorAction : KotlinGenerateMemberActionBase< if (superConstructor != null) { val substitutor = getTypeSubstitutor(superConstructor.containingDeclaration.defaultType, classDescriptor.defaultType) - ?: TypeSubstitutor.EMPTY + ?: TypeSubstitutor.EMPTY val delegationCallArguments = ArrayList() for (parameter in superConstructor.valueParameters) { val isVararg = parameter.varargElementType != null @@ -170,7 +163,7 @@ class KotlinGenerateSecondaryConstructorAction : KotlinGenerateMemberActionBase< val typeToUse = parameter.varargElementType ?: parameter.type val paramType = IdeDescriptorRenderers.SOURCE_CODE.renderType( - substitutor.substitute(typeToUse, Variance.INVARIANT) ?: classDescriptor.builtIns.anyType + substitutor.substitute(typeToUse, Variance.INVARIANT) ?: classDescriptor.builtIns.anyType ) val modifiers = if (isVararg) "vararg " else "" @@ -179,7 +172,8 @@ class KotlinGenerateSecondaryConstructorAction : KotlinGenerateMemberActionBase< delegationCallArguments.add(if (isVararg) "*$paramName" else paramName) } - val delegationCall = psiFactory.creareDelegatedSuperTypeEntry(delegationCallArguments.joinToString(prefix = "super(", postfix = ")")) + val delegationCall = + psiFactory.creareDelegatedSuperTypeEntry(delegationCallArguments.joinToString(prefix = "super(", postfix = ")")) constructor.replaceImplicitDelegationCallWithExplicit(false).replace(delegationCall) } diff --git a/idea/src/org/jetbrains/kotlin/idea/actions/generate/KotlinGenerateTestSupportActionBase.kt b/idea/src/org/jetbrains/kotlin/idea/actions/generate/KotlinGenerateTestSupportActionBase.kt index ff8df4d114e..e1b0f49dc75 100644 --- a/idea/src/org/jetbrains/kotlin/idea/actions/generate/KotlinGenerateTestSupportActionBase.kt +++ b/idea/src/org/jetbrains/kotlin/idea/actions/generate/KotlinGenerateTestSupportActionBase.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.actions.generate @@ -57,7 +46,7 @@ import org.jetbrains.kotlin.psi.psiUtil.quoteIfNeeded import org.jetbrains.kotlin.utils.ifEmpty abstract class KotlinGenerateTestSupportActionBase( - private val methodKind : MethodKind + private val methodKind: MethodKind ) : KotlinGenerateActionBase(), GenerateActionPopupTemplateInjector { companion object { private fun findTargetClass(editor: Editor, file: PsiFile): KtClassOrObject? { @@ -74,13 +63,12 @@ abstract class KotlinGenerateTestSupportActionBase( val list = JBList(*frameworks.toTypedArray()) list.cellRenderer = TestFrameworkListCellRenderer() - PopupChooserBuilder(list) - .setFilteringEnabled { (it as TestFramework).name } - .setTitle("Choose Framework") - .setItemChoosenCallback { consumer(list.selectedValue as TestFramework) } - .setMovable(true) - .createPopup() - .showInBestPositionFor(editor) + PopupChooserBuilder(list).setFilteringEnabled { (it as TestFramework).name } + .setTitle("Choose Framework") + .setItemChoosenCallback { consumer(list.selectedValue as TestFramework) } + .setMovable(true) + .createPopup() + .showInBestPositionFor(editor) } private val BODY_VAR = "\${BODY}" @@ -133,10 +121,10 @@ abstract class KotlinGenerateTestSupportActionBase( if (isApplicableTo(frameworkToUse, klass)) { doGenerate(editor, file, klass, frameworkToUse) } - } - else { - val frameworks = findSuitableFrameworks(klass) - .filter { methodKind.getFileTemplateDescriptor(it) != null && isApplicableTo(it, klass) } + } else { + val frameworks = findSuitableFrameworks(klass).filter { + methodKind.getFileTemplateDescriptor(it) != null && isApplicableTo(it, klass) + } chooseAndPerform(editor, frameworks) { doGenerate(editor, file, klass, it) } } @@ -158,7 +146,7 @@ abstract class KotlinGenerateTestSupportActionBase( name = if (templateText.contains("test$NAME_VAR")) "Name" else "name" if (!ApplicationManager.getApplication().isUnitTestMode) { name = Messages.showInputDialog("Choose test name: ", commandName, null, name, NAME_VALIDATOR) - ?: return + ?: return } templateText = fileTemplate.text.replace(NAME_VAR, DUMMY_NAME) @@ -198,8 +186,7 @@ abstract class KotlinGenerateTestSupportActionBase( setupEditorSelection(editor, functionInPlace) } errorHint?.let { HintManager.getInstance().showErrorHint(editor, it) } - } - catch (e: IncorrectOperationException) { + } catch (e: IncorrectOperationException) { HintManager.getInstance().showErrorHint(editor, "Cannot generate method: " + e.message) } } @@ -210,23 +197,23 @@ abstract class KotlinGenerateTestSupportActionBase( // First replace all DUMMY_NAME occurrences in names as they need special treatment due to quotation var function1 = function function1.accept( - object : KtTreeVisitorVoid() { - private fun getNewId(currentId: String): String? { - if (!currentId.contains(DUMMY_NAME)) return null - return currentId.replace(DUMMY_NAME, name).quoteIfNeeded() - } - - override fun visitNamedDeclaration(declaration: KtNamedDeclaration) { - val nameIdentifier = declaration.nameIdentifier ?: return - val newId = getNewId(nameIdentifier.text) ?: return - declaration.setName(newId) - } - - override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { - val newId = getNewId(expression.text) ?: return - expression.replace(psiFactory.createSimpleName(newId)) - } + object : KtTreeVisitorVoid() { + private fun getNewId(currentId: String): String? { + if (!currentId.contains(DUMMY_NAME)) return null + return currentId.replace(DUMMY_NAME, name).quoteIfNeeded() } + + override fun visitNamedDeclaration(declaration: KtNamedDeclaration) { + val nameIdentifier = declaration.nameIdentifier ?: return + val newId = getNewId(nameIdentifier.text) ?: return + declaration.setName(newId) + } + + override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { + val newId = getNewId(expression.text) ?: return + expression.replace(psiFactory.createSimpleName(newId)) + } + } ) // Then text-replace remaining occurrences (if any) val functionText = function1.text diff --git a/idea/src/org/jetbrains/kotlin/idea/actions/generate/utils.kt b/idea/src/org/jetbrains/kotlin/idea/actions/generate/utils.kt index 7bd580981e5..04e8e95ea39 100644 --- a/idea/src/org/jetbrains/kotlin/idea/actions/generate/utils.kt +++ b/idea/src/org/jetbrains/kotlin/idea/actions/generate/utils.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.actions.generate @@ -34,14 +23,13 @@ import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperClassOrAny import java.util.* tailrec fun ClassDescriptor.findDeclaredFunction( - name: String, - checkSuperClasses: Boolean, - filter: (FunctionDescriptor) -> Boolean + name: String, + checkSuperClasses: Boolean, + filter: (FunctionDescriptor) -> Boolean ): FunctionDescriptor? { - unsubstitutedMemberScope - .getContributedFunctions(Name.identifier(name), NoLookupLocation.FROM_IDE) - .firstOrNull { it.containingDeclaration == this && it.kind == CallableMemberDescriptor.Kind.DECLARATION && filter(it) } - ?.let { return it } + unsubstitutedMemberScope.getContributedFunctions(Name.identifier(name), NoLookupLocation.FROM_IDE) + .firstOrNull { it.containingDeclaration == this && it.kind == CallableMemberDescriptor.Kind.DECLARATION && filter(it) } + ?.let { return it } return if (checkSuperClasses) getSuperClassOrAny().findDeclaredFunction(name, checkSuperClasses, filter) else null } @@ -73,13 +61,15 @@ fun confirmMemberRewrite(targetClass: KtClass, vararg descriptors: FunctionDescr val functionsText = descriptors.joinToString(separator = " and ") { "'${MEMBER_RENDERER.render(it)}'" } val message = "Functions $functionsText are already defined\nfor class ${targetClass.name}. Do you want to delete them and proceed?" - return Messages.showYesNoDialog(targetClass.project, message, - CodeInsightBundle.message("generate.equals.and.hashcode.already.defined.title"), - Messages.getQuestionIcon()) == Messages.YES + return Messages.showYesNoDialog( + targetClass.project, message, + CodeInsightBundle.message("generate.equals.and.hashcode.already.defined.title"), + Messages.getQuestionIcon() + ) == Messages.YES } fun generateFunctionSkeleton(descriptor: FunctionDescriptor, targetClass: KtClassOrObject): KtNamedFunction { return OverrideMemberChooserObject - .create(targetClass.project, descriptor, descriptor, OverrideMemberChooserObject.BodyType.FROM_TEMPLATE) - .generateMember(targetClass, false) as KtNamedFunction + .create(targetClass.project, descriptor, descriptor, OverrideMemberChooserObject.BodyType.FROM_TEMPLATE) + .generateMember(targetClass, false) as KtNamedFunction } \ No newline at end of file diff --git a/idea/src/org/jetbrains/kotlin/idea/actions/internal/CheckComponentsUsageSearchAction.kt b/idea/src/org/jetbrains/kotlin/idea/actions/internal/CheckComponentsUsageSearchAction.kt index 03160c229cc..00c88aacf5b 100644 --- a/idea/src/org/jetbrains/kotlin/idea/actions/internal/CheckComponentsUsageSearchAction.kt +++ b/idea/src/org/jetbrains/kotlin/idea/actions/internal/CheckComponentsUsageSearchAction.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.actions.internal @@ -86,7 +75,8 @@ class CheckComponentsUsageSearchAction : AnAction() { SwingUtilities.invokeLater { Messages.showInfoMessage( project, - "Difference found for data class ${dataClass.fqName?.asString()}. Found $smartRefsCount usage(s) but $goldRefsCount expected", + "Difference found for data class ${dataClass.fqName + ?.asString()}. Found $smartRefsCount usage(s) but $goldRefsCount expected", "Error" ) } diff --git a/idea/src/org/jetbrains/kotlin/idea/actions/internal/refactoringTesting/cases/MoveKotlinDeclarationsHandlerTestActions.kt b/idea/src/org/jetbrains/kotlin/idea/actions/internal/refactoringTesting/cases/MoveKotlinDeclarationsHandlerTestActions.kt index 214ce46b01c..4a68973df4e 100644 --- a/idea/src/org/jetbrains/kotlin/idea/actions/internal/refactoringTesting/cases/MoveKotlinDeclarationsHandlerTestActions.kt +++ b/idea/src/org/jetbrains/kotlin/idea/actions/internal/refactoringTesting/cases/MoveKotlinDeclarationsHandlerTestActions.kt @@ -71,7 +71,9 @@ internal class MoveKotlinDeclarationsHandlerTestActions(private val caseDataKeep private fun KotlinAwareMoveFilesOrDirectoriesModel.testDataString(): String { return "KotlinAwareMoveFilesOrDirectoriesModel:\n" + - "elementsToMove = ${elementsToMove.joinToString { if (it is PsiFileSystemItem) it.virtualFile.path else it.javaClass.name }}\n" + + "elementsToMove = ${elementsToMove.joinToString { + if (it is PsiFileSystemItem) it.virtualFile.path else it.javaClass.name + }}\n" + "directoryName = $targetDirectoryName\n" + "updatePackageDirective = $updatePackageDirective\n" + "searchReferences = $searchReferences" diff --git a/idea/src/org/jetbrains/kotlin/idea/caches/FileAttributeServiceImpl.kt b/idea/src/org/jetbrains/kotlin/idea/caches/FileAttributeServiceImpl.kt index bf7aae5d7d8..4589d49990b 100644 --- a/idea/src/org/jetbrains/kotlin/idea/caches/FileAttributeServiceImpl.kt +++ b/idea/src/org/jetbrains/kotlin/idea/caches/FileAttributeServiceImpl.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.caches @@ -31,29 +20,24 @@ class FileAttributeServiceImpl : FileAttributeService { attributes[id] = FileAttribute(id, version, fixedSize) } - override fun > writeEnumAttribute(id: String, file: VirtualFile, value: T): CachedAttributeData { - return write(file, id, value) { output, v -> + override fun > writeEnumAttribute(id: String, file: VirtualFile, value: T): CachedAttributeData = + write(file, id, value) { output, v -> DataInputOutputUtil.writeINT(output, v.ordinal) } - } - override fun > readEnumAttribute(id: String, file: VirtualFile, klass: Class): CachedAttributeData? { - return read(file, id) { input -> + override fun > readEnumAttribute(id: String, file: VirtualFile, klass: Class): CachedAttributeData? = + read(file, id) { input -> deserializeEnumValue(DataInputOutputUtil.readINT(input), klass) } - } - override fun writeBooleanAttribute(id: String, file: VirtualFile, value: Boolean): CachedAttributeData { - return write(file, id, value) { output, v -> + override fun writeBooleanAttribute(id: String, file: VirtualFile, value: Boolean): CachedAttributeData = + write(file, id, value) { output, v -> DataInputOutputUtil.writeINT(output, if (v) 1 else 0) } - } - override fun readBooleanAttribute(id: String, file: VirtualFile): CachedAttributeData? { - return read(file, id) { input -> - DataInputOutputUtil.readINT(input) > 0 - } + override fun readBooleanAttribute(id: String, file: VirtualFile): CachedAttributeData? = read(file, id) { input -> + DataInputOutputUtil.readINT(input) > 0 } override fun write(file: VirtualFile, id: String, value: T, writeValueFun: (DataOutput, T) -> Unit): CachedAttributeData { @@ -81,14 +65,13 @@ class FileAttributeServiceImpl : FileAttributeService { if (file.timeStamp == timeStamp) { CachedAttributeData(value, timeStamp) - } - else { + } else { null } } } - private fun > deserializeEnumValue(i: Int, klass: Class): T { + private fun > deserializeEnumValue(i: Int, klass: Class): T { val method = klass.getMethod("values") @Suppress("UNCHECKED_CAST") diff --git a/idea/src/org/jetbrains/kotlin/idea/codeInliner/CodeInliner.kt b/idea/src/org/jetbrains/kotlin/idea/codeInliner/CodeInliner.kt index ac9eb4d2bb8..c1dd63c1e4c 100644 --- a/idea/src/org/jetbrains/kotlin/idea/codeInliner/CodeInliner.kt +++ b/idea/src/org/jetbrains/kotlin/idea/codeInliner/CodeInliner.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.codeInliner @@ -321,7 +310,9 @@ class CodeInliner( is KtUnaryExpression -> operationToken in setOf(KtTokens.PLUSPLUS, KtTokens.MINUSMINUS) || baseExpression.shouldKeepValue( usageCount ) - is KtStringTemplateExpression -> entries.any { if (sideEffectOnly) it.expression.shouldKeepValue(usageCount) else it is KtStringTemplateEntryWithExpression } + is KtStringTemplateExpression -> entries.any { + if (sideEffectOnly) it.expression.shouldKeepValue(usageCount) else it is KtStringTemplateEntryWithExpression + } is KtThisExpression, is KtSuperExpression, is KtConstantExpression -> false is KtParenthesizedExpression -> expression.shouldKeepValue(usageCount) is KtArrayAccessExpression -> if (sideEffectOnly) arrayExpression.shouldKeepValue(usageCount) || indexExpressions.any { diff --git a/idea/src/org/jetbrains/kotlin/idea/codeInsight/KotlinDeclarationRangeHandler.kt b/idea/src/org/jetbrains/kotlin/idea/codeInsight/KotlinDeclarationRangeHandler.kt index 448ab78c579..689054d1961 100644 --- a/idea/src/org/jetbrains/kotlin/idea/codeInsight/KotlinDeclarationRangeHandler.kt +++ b/idea/src/org/jetbrains/kotlin/idea/codeInsight/KotlinDeclarationRangeHandler.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -32,9 +32,9 @@ class KotlinFunDeclarationRangeHandler : DeclarationRangeHandler() { override fun getExpressionsAt(elementAt: PsiElement): List { val candidates = elementAt.parentsWithSelf.filterIsInstance().filter { it.shouldShowType() }.toList() - val fileEditor = elementAt.containingFile?.virtualFile?.let { FileEditorManager.getInstance(elementAt.project).getSelectedEditor(it) } + val fileEditor = + elementAt.containingFile?.virtualFile?.let { FileEditorManager.getInstance(elementAt.project).getSelectedEditor(it) } val selectionTextRange = if (fileEditor is TextEditor) { EditorUtil.getSelectionInAnyMode(fileEditor.editor) } else { TextRange.EMPTY_RANGE } - val anchor = candidates.firstOrNull { selectionTextRange.isEmpty || it.textRange.contains(selectionTextRange) } ?: return emptyList() + val anchor = + candidates.firstOrNull { selectionTextRange.isEmpty || it.textRange.contains(selectionTextRange) } ?: return emptyList() return candidates.filter { it.textRange.startOffset == anchor.textRange.startOffset } } @@ -122,11 +113,10 @@ class KotlinExpressionTypeProvider : ExpressionTypeProvider() { val result = expressionType?.let { typeRenderer.renderType(it) } ?: return "Type is unknown" val dataFlowValueFactory = element.getResolutionFacade().frontendService() - val dataFlowValue = dataFlowValueFactory.createDataFlowValue(element, expressionType, bindingContext, element.findModuleDescriptor()) + val dataFlowValue = + dataFlowValueFactory.createDataFlowValue(element, expressionType, bindingContext, element.findModuleDescriptor()) val types = expressionTypeInfo.dataFlowInfo.getStableTypes(dataFlowValue, element.languageVersionSettings) - if (!types.isEmpty()) { - return types.joinToString(separator = " & ") { typeRenderer.renderType(it) } + " (smart cast from " + result + ")" - } + if (types.isNotEmpty()) return types.joinToString(separator = " & ") { typeRenderer.renderType(it) } + " (smart cast from " + result + ")" val smartCast = bindingContext[BindingContext.SMARTCAST, element] if (smartCast != null && element is KtReferenceExpression) { diff --git a/idea/src/org/jetbrains/kotlin/idea/compiler/configuration/ClearBuildStateExtension.kt b/idea/src/org/jetbrains/kotlin/idea/compiler/configuration/ClearBuildStateExtension.kt index 751fbe4d201..687f6c61296 100644 --- a/idea/src/org/jetbrains/kotlin/idea/compiler/configuration/ClearBuildStateExtension.kt +++ b/idea/src/org/jetbrains/kotlin/idea/compiler/configuration/ClearBuildStateExtension.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.compiler.configuration @@ -27,7 +16,7 @@ abstract class ClearBuildStateExtension { } val EP_NAME: ExtensionPointName = - ExtensionPointName.create("org.jetbrains.kotlin.clearBuildState") + ExtensionPointName.create("org.jetbrains.kotlin.clearBuildState") } abstract fun clearState(project: Project) diff --git a/idea/src/org/jetbrains/kotlin/idea/configuration/KotlinLanguageConfiguration.kt b/idea/src/org/jetbrains/kotlin/idea/configuration/KotlinLanguageConfiguration.kt index 69ad0369c99..207411e4c31 100644 --- a/idea/src/org/jetbrains/kotlin/idea/configuration/KotlinLanguageConfiguration.kt +++ b/idea/src/org/jetbrains/kotlin/idea/configuration/KotlinLanguageConfiguration.kt @@ -1,5 +1,5 @@ /* - * Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -144,7 +144,7 @@ class KotlinLanguageConfiguration : SearchableConfigurable, Configurable.NoScrol saveChannelSettings() form.updateCheckProgressIcon.resume() form.resetUpdateStatus() - KotlinPluginUpdater.getInstance().runUpdateCheck{ pluginUpdateStatus -> + KotlinPluginUpdater.getInstance().runUpdateCheck { pluginUpdateStatus -> // Need this to show something is happening when check is very fast Thread.sleep(30) form.updateCheckProgressIcon.suspend() diff --git a/idea/src/org/jetbrains/kotlin/idea/configuration/ui/NotPropertyListPanel.kt b/idea/src/org/jetbrains/kotlin/idea/configuration/ui/NotPropertyListPanel.kt index 702f2e91214..8cec4e7e3cb 100644 --- a/idea/src/org/jetbrains/kotlin/idea/configuration/ui/NotPropertyListPanel.kt +++ b/idea/src/org/jetbrains/kotlin/idea/configuration/ui/NotPropertyListPanel.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.configuration.ui @@ -31,11 +20,12 @@ class NotPropertyListPanel(data: MutableList) : AddEditRemovePanel } override fun editItem(fqName: FqNameUnsafe): FqNameUnsafe? { - val result = Messages.showInputDialog(this, "Enter fully-qualified method name:", - "Edit exclusion", - Messages.getQuestionIcon(), - fqName.asString(), - NonEmptyInputValidator() + val result = Messages.showInputDialog( + this, "Enter fully-qualified method name:", + "Edit exclusion", + Messages.getQuestionIcon(), + fqName.asString(), + NonEmptyInputValidator() ) ?: return null val created = FqNameUnsafe(result) @@ -48,11 +38,12 @@ class NotPropertyListPanel(data: MutableList) : AddEditRemovePanel } override fun addItem(): FqNameUnsafe? { - val result = Messages.showInputDialog(this, "Enter fully-qualified method name:", - "Add exclusion", - Messages.getQuestionIcon(), - "", - NonEmptyInputValidator() + val result = Messages.showInputDialog( + this, "Enter fully-qualified method name:", + "Add exclusion", + Messages.getQuestionIcon(), + "", + NonEmptyInputValidator() ) ?: return null val created = FqNameUnsafe(result) diff --git a/idea/src/org/jetbrains/kotlin/idea/conversion/copy/KotlinFilePasteProvider.kt b/idea/src/org/jetbrains/kotlin/idea/conversion/copy/KotlinFilePasteProvider.kt index 4a7075cd45c..ebae12d68b5 100644 --- a/idea/src/org/jetbrains/kotlin/idea/conversion/copy/KotlinFilePasteProvider.kt +++ b/idea/src/org/jetbrains/kotlin/idea/conversion/copy/KotlinFilePasteProvider.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -34,6 +34,7 @@ class KotlinFilePasteProvider : PasteProvider { val ktFile = KtPsiFactory(project).createFile(text) val fileName = (ktFile.declarations.firstOrNull()?.name ?: return) + ".kt" + @Suppress("UsePropertyAccessSyntax") val directory = ideView.getOrChooseDirectory() ?: return project.executeWriteCommand("Create Kotlin file") { diff --git a/idea/src/org/jetbrains/kotlin/idea/editor/KotlinLiteralCopyPasteProcessor.kt b/idea/src/org/jetbrains/kotlin/idea/editor/KotlinLiteralCopyPasteProcessor.kt index 9da6ea1cdc1..64017b28e4c 100644 --- a/idea/src/org/jetbrains/kotlin/idea/editor/KotlinLiteralCopyPasteProcessor.kt +++ b/idea/src/org/jetbrains/kotlin/idea/editor/KotlinLiteralCopyPasteProcessor.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.editor @@ -45,7 +34,8 @@ private val PsiElement.templateContentRange: TextRange? private fun PsiFile.getTemplateIfAtLiteral(offset: Int, at: PsiElement? = findElementAt(offset)): KtStringTemplateExpression? { if (at == null) return null return when (at.node?.elementType) { - KtTokens.REGULAR_STRING_PART, KtTokens.ESCAPE_SEQUENCE, KtTokens.LONG_TEMPLATE_ENTRY_START, KtTokens.SHORT_TEMPLATE_ENTRY_START -> at.parent.parent as? KtStringTemplateExpression + KtTokens.REGULAR_STRING_PART, KtTokens.ESCAPE_SEQUENCE, KtTokens.LONG_TEMPLATE_ENTRY_START, KtTokens.SHORT_TEMPLATE_ENTRY_START -> at.parent + .parent as? KtStringTemplateExpression KtTokens.CLOSING_QUOTE -> if (offset == at.startOffset) at.parent as? KtStringTemplateExpression else null else -> null } @@ -110,7 +100,7 @@ class KotlinLiteralCopyPasteProcessor : CopyPastePreProcessor { } } val blockSelectionPadding = deducedBlockSelectionWidth - fileRange.length - for (j in 0..blockSelectionPadding - 1) { + for (j in 0 until blockSelectionPadding) { buffer.append(' ') } } @@ -235,11 +225,11 @@ private class TemplateTokenSequence(private val inputString: String) : Sequence< private suspend fun SequenceScope.yieldLiteral(chunk: String) { val splitLines = LineTokenizer.tokenize(chunk, false, false) - for (i in 0..splitLines.size - 1) { + for (i in splitLines.indices) { if (i != 0) { yield(NewLineChunk) } - splitLines[i].takeIf { !it.isEmpty() }?.let { yield(LiteralChunk(it)) } + splitLines[i].takeIf { it.isNotEmpty() }?.let { yield(LiteralChunk(it)) } } } diff --git a/idea/src/org/jetbrains/kotlin/idea/facet/DescriptionListCellRenderer.kt b/idea/src/org/jetbrains/kotlin/idea/facet/DescriptionListCellRenderer.kt index 60517f2bfbf..f896a07e181 100644 --- a/idea/src/org/jetbrains/kotlin/idea/facet/DescriptionListCellRenderer.kt +++ b/idea/src/org/jetbrains/kotlin/idea/facet/DescriptionListCellRenderer.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.facet @@ -22,9 +11,13 @@ import javax.swing.DefaultListCellRenderer import javax.swing.JList class DescriptionListCellRenderer : DefaultListCellRenderer() { - override fun getListCellRendererComponent(list: JList<*>?, value: Any?, index: Int, isSelected: Boolean, cellHasFocus: Boolean): Component { - return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus).apply { - text = (value as? DescriptionAware)?.description ?: "" - } + override fun getListCellRendererComponent( + list: JList<*>?, + value: Any?, + index: Int, + isSelected: Boolean, + cellHasFocus: Boolean + ): Component = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus).apply { + text = (value as? DescriptionAware)?.description ?: "" } } \ No newline at end of file diff --git a/idea/src/org/jetbrains/kotlin/idea/facet/KotlinFacetCompilerPluginsTab.kt b/idea/src/org/jetbrains/kotlin/idea/facet/KotlinFacetCompilerPluginsTab.kt index 85092e9018b..c9897755a04 100644 --- a/idea/src/org/jetbrains/kotlin/idea/facet/KotlinFacetCompilerPluginsTab.kt +++ b/idea/src/org/jetbrains/kotlin/idea/facet/KotlinFacetCompilerPluginsTab.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.facet @@ -33,12 +22,12 @@ import javax.swing.table.TableCellRenderer import kotlin.math.max class KotlinFacetCompilerPluginsTab( - private val configuration: KotlinFacetConfiguration, - private val validatorsManager: FacetValidatorsManager + private val configuration: KotlinFacetConfiguration, + private val validatorsManager: FacetValidatorsManager ) : FacetEditorTab() { companion object { fun parsePluginOptions(configuration: KotlinFacetConfiguration) = - configuration.settings.compilerArguments?.pluginOptions?.mapNotNull(::parsePluginOption) ?: emptyList() + configuration.settings.compilerArguments?.pluginOptions?.mapNotNull(::parsePluginOption) ?: emptyList() } class PluginInfo(val id: String, var options: List) @@ -65,8 +54,8 @@ class KotlinFacetCompilerPluginsTab( result } ) - .groupBy({ it.pluginId }) - .mapTo(this) { PluginInfo(it.key, it.value.map { "${it.optionName}=${it.value}" }) } + .groupBy { it.pluginId } + .mapTo(this) { entry -> PluginInfo(entry.key, entry.value.map { "${it.optionName}=${it.value}" }) } sortBy { it.id } } @@ -106,7 +95,14 @@ class KotlinFacetCompilerPluginsTab( } } - override fun getTableCellRendererComponent(table: JTable, value: Any?, isSelected: Boolean, hasFocus: Boolean, row: Int, column: Int): Component { + override fun getTableCellRendererComponent( + table: JTable, + value: Any?, + isSelected: Boolean, + hasFocus: Boolean, + row: Int, + column: Int + ): Component { return setupComponent(table, value) } diff --git a/idea/src/org/jetbrains/kotlin/idea/facet/KotlinFacetConfigurationExtension.kt b/idea/src/org/jetbrains/kotlin/idea/facet/KotlinFacetConfigurationExtension.kt index b45aa579407..b2837fe4868 100644 --- a/idea/src/org/jetbrains/kotlin/idea/facet/KotlinFacetConfigurationExtension.kt +++ b/idea/src/org/jetbrains/kotlin/idea/facet/KotlinFacetConfigurationExtension.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.facet @@ -23,7 +12,8 @@ import com.intellij.openapi.extensions.ExtensionPointName interface KotlinFacetConfigurationExtension { companion object { - val EP_NAME: ExtensionPointName = ExtensionPointName.create("org.jetbrains.kotlin.facetConfigurationExtension") + val EP_NAME: ExtensionPointName = + ExtensionPointName.create("org.jetbrains.kotlin.facetConfigurationExtension") } fun createEditorTabs(editorContext: FacetEditorContext, validatorsManager: FacetValidatorsManager): List diff --git a/idea/src/org/jetbrains/kotlin/idea/facet/KotlinFacetConfigurationImpl.kt b/idea/src/org/jetbrains/kotlin/idea/facet/KotlinFacetConfigurationImpl.kt index 55c17cd6b0f..fb6f51972cf 100644 --- a/idea/src/org/jetbrains/kotlin/idea/facet/KotlinFacetConfigurationImpl.kt +++ b/idea/src/org/jetbrains/kotlin/idea/facet/KotlinFacetConfigurationImpl.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.facet @@ -39,8 +28,8 @@ class KotlinFacetConfigurationImpl : KotlinFacetConfiguration { } override fun createEditorTabs( - editorContext: FacetEditorContext, - validatorsManager: FacetValidatorsManager + editorContext: FacetEditorContext, + validatorsManager: FacetValidatorsManager ): Array { settings.initializeIfNeeded(editorContext.module, editorContext.rootModel) diff --git a/idea/src/org/jetbrains/kotlin/idea/facet/KotlinFacetEditorGeneralTab.kt b/idea/src/org/jetbrains/kotlin/idea/facet/KotlinFacetEditorGeneralTab.kt index c2e7a416934..6c7ed00323e 100644 --- a/idea/src/org/jetbrains/kotlin/idea/facet/KotlinFacetEditorGeneralTab.kt +++ b/idea/src/org/jetbrains/kotlin/idea/facet/KotlinFacetEditorGeneralTab.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.facet @@ -31,14 +20,13 @@ import org.jetbrains.kotlin.idea.compiler.configuration.* import org.jetbrains.kotlin.idea.core.util.onTextChange import org.jetbrains.kotlin.platform.* import org.jetbrains.kotlin.platform.js.isJs +import org.jetbrains.kotlin.platform.jvm.JvmPlatforms import org.jetbrains.kotlin.platform.jvm.isJvm import java.awt.BorderLayout +import java.awt.Component import javax.swing.* import javax.swing.border.EmptyBorder import kotlin.reflect.full.findAnnotation -import org.jetbrains.kotlin.platform.jvm.JvmPlatforms -import java.awt.Component -import kotlin.math.min class KotlinFacetEditorGeneralTab( private val configuration: KotlinFacetConfiguration, @@ -146,8 +134,8 @@ class KotlinFacetEditorGeneralTab( useProjectSettingsCheckBox = ThreeStateCheckBox("Use project settings").apply { isThirdStateEnabled = isMultiEditor } dependsOnLabel = JLabel() - targetPlatformWrappers = - CommonPlatforms.allDefaultTargetPlatforms.sortedBy { unifyJvmVersion(it.oldFashionedDescription) }.map { TargetPlatformWrapper(it) } + targetPlatformWrappers = CommonPlatforms.allDefaultTargetPlatforms.sortedBy { unifyJvmVersion(it.oldFashionedDescription) } + .map { TargetPlatformWrapper(it) } targetPlatformLabel = JLabel() //JTextField()? targetPlatformLabel.isEditable = false targetPlatformSelectSingleCombobox = ComboBox(targetPlatformWrappers.toTypedArray()).apply { @@ -161,7 +149,8 @@ class KotlinFacetEditorGeneralTab( ): Component { return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus).apply { text = - (value as? TargetPlatformWrapper)?.targetPlatform?.componentPlatforms?.singleOrNull()?.oldFashionedDescription + (value as? TargetPlatformWrapper)?.targetPlatform?.componentPlatforms?.singleOrNull() + ?.oldFashionedDescription ?: "Multiplatform" } } @@ -369,7 +358,8 @@ class KotlinFacetEditorGeneralTab( // work-around for hacked equals in JvmPlatform if (!configuration?.settings?.isHmppEnabled) { - if (configuration.settings.targetPlatform?.let { TargetPlatformWrapper(it) } != editor.targetPlatformSelectSingleCombobox.selectedItemTyped) { + if (configuration.settings.targetPlatform?.let { TargetPlatformWrapper(it) } != editor.targetPlatformSelectSingleCombobox + .selectedItemTyped) { return true } } @@ -391,7 +381,7 @@ class KotlinFacetEditorGeneralTab( editor.targetPlatformsCurrentlySelected?.componentPlatforms?.map { it.oldFashionedDescription.trim() }?.joinToString(", ") ?: "" editor.dependsOnLabel.isVisible = configuration.settings.dependsOnModuleNames.isNotEmpty() - editor.dependsOnLabel.text = configuration.settings.dependsOnModuleNames.joinToString(", ","Depends on: ", ".") + editor.dependsOnLabel.text = configuration.settings.dependsOnModuleNames.joinToString(", ", "Depends on: ", ".") editor.targetPlatformSelectSingleCombobox.selectedItem = configuration.settings.targetPlatform?.let { val index = editor.targetPlatformWrappers.indexOf(TargetPlatformWrapper(it)) diff --git a/idea/src/org/jetbrains/kotlin/idea/facet/KotlinFacetSettingsProviderImpl.kt b/idea/src/org/jetbrains/kotlin/idea/facet/KotlinFacetSettingsProviderImpl.kt index 61ec449f325..0ffa7461191 100644 --- a/idea/src/org/jetbrains/kotlin/idea/facet/KotlinFacetSettingsProviderImpl.kt +++ b/idea/src/org/jetbrains/kotlin/idea/facet/KotlinFacetSettingsProviderImpl.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.facet @@ -29,17 +18,17 @@ import org.jetbrains.kotlin.psi.UserDataProperty class KotlinFacetSettingsProviderImpl(private val project: Project) : KotlinFacetSettingsProvider { companion object { - private var Module.facetSettingsCache : KotlinFacetSettings? by UserDataProperty(Key.create("FACET_SETTINGS_CACHE")) + private var Module.facetSettingsCache: KotlinFacetSettings? by UserDataProperty(Key.create("FACET_SETTINGS_CACHE")) } init { project.messageBus.connect(project).subscribe( - ProjectTopics.PROJECT_ROOTS, - object : ModuleRootListener { - override fun rootsChanged(event: ModuleRootEvent) { - ModuleManager.getInstance(project).modules.forEach { it.facetSettingsCache = null } - } + ProjectTopics.PROJECT_ROOTS, + object : ModuleRootListener { + override fun rootsChanged(event: ModuleRootEvent) { + ModuleManager.getInstance(project).modules.forEach { it.facetSettingsCache = null } } + } ) } diff --git a/idea/src/org/jetbrains/kotlin/idea/facet/KotlinFacetTypeImpl.kt b/idea/src/org/jetbrains/kotlin/idea/facet/KotlinFacetTypeImpl.kt index 639c8648104..c20e3c98870 100644 --- a/idea/src/org/jetbrains/kotlin/idea/facet/KotlinFacetTypeImpl.kt +++ b/idea/src/org/jetbrains/kotlin/idea/facet/KotlinFacetTypeImpl.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.facet @@ -26,12 +15,12 @@ class KotlinFacetTypeImpl : KotlinFacetType() { override fun createDefaultConfiguration() = KotlinFacetConfigurationImpl() override fun createFacet( - module: Module, - name: String, - configuration: KotlinFacetConfiguration, - underlyingFacet: Facet<*>? + module: Module, + name: String, + configuration: KotlinFacetConfiguration, + underlyingFacet: Facet<*>? ) = KotlinFacet(module, name, configuration) override fun createMultipleConfigurationsEditor(project: Project, editors: Array) = - MultipleKotlinFacetEditor(project, editors) + MultipleKotlinFacetEditor(project, editors) } \ No newline at end of file diff --git a/idea/src/org/jetbrains/kotlin/idea/facet/KotlinFacetValidatorCreator.kt b/idea/src/org/jetbrains/kotlin/idea/facet/KotlinFacetValidatorCreator.kt index 63e79d0632c..8f12853058e 100644 --- a/idea/src/org/jetbrains/kotlin/idea/facet/KotlinFacetValidatorCreator.kt +++ b/idea/src/org/jetbrains/kotlin/idea/facet/KotlinFacetValidatorCreator.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.facet @@ -25,8 +14,12 @@ import org.jetbrains.kotlin.idea.facet.KotlinFacetEditorGeneralTab.EditorCompone abstract class KotlinFacetValidatorCreator { companion object { val EP_NAME: ExtensionPointName = - ExtensionPointName.create("org.jetbrains.kotlin.facetValidatorCreator") + ExtensionPointName.create("org.jetbrains.kotlin.facetValidatorCreator") } - abstract fun create(editor: EditorComponent, validatorsManager: FacetValidatorsManager, editorContext: FacetEditorContext): FacetEditorValidator + abstract fun create( + editor: EditorComponent, + validatorsManager: FacetValidatorsManager, + editorContext: FacetEditorContext + ): FacetEditorValidator } \ No newline at end of file diff --git a/idea/src/org/jetbrains/kotlin/idea/facet/KotlinVersionInfoProviderByModuleDependencies.kt b/idea/src/org/jetbrains/kotlin/idea/facet/KotlinVersionInfoProviderByModuleDependencies.kt index 4ef40b7e1a6..ab3caa4a111 100644 --- a/idea/src/org/jetbrains/kotlin/idea/facet/KotlinVersionInfoProviderByModuleDependencies.kt +++ b/idea/src/org/jetbrains/kotlin/idea/facet/KotlinVersionInfoProviderByModuleDependencies.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.facet @@ -38,10 +27,10 @@ class KotlinVersionInfoProviderByModuleDependencies : KotlinVersionInfoProvider val versionProvider = platformKind.tooling.getLibraryVersionProvider(module.project) return (rootModel ?: ModuleRootManager.getInstance(module)) - .orderEntries - .asSequence() - .filterIsInstance() - .mapNotNull { libraryEntry -> libraryEntry.library?.let { versionProvider(it) } } - .toList() + .orderEntries + .asSequence() + .filterIsInstance() + .mapNotNull { libraryEntry -> libraryEntry.library?.let { versionProvider(it) } } + .toList() } } \ No newline at end of file diff --git a/idea/src/org/jetbrains/kotlin/idea/facet/MultipleKotlinFacetEditor.kt b/idea/src/org/jetbrains/kotlin/idea/facet/MultipleKotlinFacetEditor.kt index e75059c144c..684fe67693f 100644 --- a/idea/src/org/jetbrains/kotlin/idea/facet/MultipleKotlinFacetEditor.kt +++ b/idea/src/org/jetbrains/kotlin/idea/facet/MultipleKotlinFacetEditor.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.facet @@ -25,8 +14,8 @@ import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstance import javax.swing.JComponent class MultipleKotlinFacetEditor( - private val project: Project, - private val editors: Array + private val project: Project, + private val editors: Array ) : MultipleFacetSettingsEditor() { private val helper = FacetEditorsFactory.getInstance().createMultipleFacetEditorHelper() @@ -46,18 +35,18 @@ class MultipleKotlinFacetEditor( helper.bind(reportWarningsCheckBox, editors) { it.compilerConfigurable.reportWarningsCheckBox } helper.bind(enableNewInferenceInIDECheckBox, editors) { it.compilerConfigurable.enableNewInferenceInIDECheckBox } helper.bind(additionalArgsOptionsField.textField, editors) { it.compilerConfigurable.additionalArgsOptionsField.textField } - helper.bind(generateSourceMapsCheckBox, editors) { it.compilerConfigurable.generateSourceMapsCheckBox} + helper.bind(generateSourceMapsCheckBox, editors) { it.compilerConfigurable.generateSourceMapsCheckBox } helper.bind(outputPrefixFile.textField, editors) { it.compilerConfigurable.outputPrefixFile.textField } helper.bind(outputPostfixFile.textField, editors) { it.compilerConfigurable.outputPostfixFile.textField } helper.bind(outputDirectory.textField, editors) { it.compilerConfigurable.outputDirectory.textField } - helper.bind(copyRuntimeFilesCheckBox, editors) { it.compilerConfigurable.copyRuntimeFilesCheckBox} - helper.bind(keepAliveCheckBox, editors) { it.compilerConfigurable.keepAliveCheckBox} - helper.bind(moduleKindComboBox, editors) { it.compilerConfigurable.moduleKindComboBox} - helper.bind(scriptTemplatesField, editors) { it.compilerConfigurable.scriptTemplatesField} - helper.bind(scriptTemplatesClasspathField, editors) { it.compilerConfigurable.scriptTemplatesClasspathField} - helper.bind(languageVersionComboBox, editors) { it.compilerConfigurable.languageVersionComboBox} - helper.bind(apiVersionComboBox, editors) { it.compilerConfigurable.apiVersionComboBox} - helper.bind(coroutineSupportComboBox, editors) { it.compilerConfigurable.coroutineSupportComboBox} + helper.bind(copyRuntimeFilesCheckBox, editors) { it.compilerConfigurable.copyRuntimeFilesCheckBox } + helper.bind(keepAliveCheckBox, editors) { it.compilerConfigurable.keepAliveCheckBox } + helper.bind(moduleKindComboBox, editors) { it.compilerConfigurable.moduleKindComboBox } + helper.bind(scriptTemplatesField, editors) { it.compilerConfigurable.scriptTemplatesField } + helper.bind(scriptTemplatesClasspathField, editors) { it.compilerConfigurable.scriptTemplatesClasspathField } + helper.bind(languageVersionComboBox, editors) { it.compilerConfigurable.languageVersionComboBox } + helper.bind(apiVersionComboBox, editors) { it.compilerConfigurable.apiVersionComboBox } + helper.bind(coroutineSupportComboBox, editors) { it.compilerConfigurable.coroutineSupportComboBox } } } } diff --git a/idea/src/org/jetbrains/kotlin/idea/facet/facetUtils.kt b/idea/src/org/jetbrains/kotlin/idea/facet/facetUtils.kt index 64f41674c1f..66d7366e1b5 100644 --- a/idea/src/org/jetbrains/kotlin/idea/facet/facetUtils.kt +++ b/idea/src/org/jetbrains/kotlin/idea/facet/facetUtils.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.facet @@ -42,8 +31,8 @@ import org.jetbrains.kotlin.idea.util.getProjectJdkTableSafe import org.jetbrains.kotlin.platform.* import org.jetbrains.kotlin.platform.compat.toNewPlatform import org.jetbrains.kotlin.platform.impl.JvmIdePlatformKind -import org.jetbrains.kotlin.psi.NotNullableUserDataProperty import org.jetbrains.kotlin.platform.jvm.JvmPlatforms +import org.jetbrains.kotlin.psi.NotNullableUserDataProperty import kotlin.reflect.KProperty1 var Module.hasExternalSdkConfiguration: Boolean @@ -95,7 +84,7 @@ fun KotlinFacetSettings.initializeIfNeeded( if (shouldInferLanguageLevel) { languageLevel = (if (useProjectSettings) LanguageVersion.fromVersionString(commonArguments.languageVersion) else null) - ?: getDefaultLanguageLevel(module, compilerVersion, coerceRuntimeLibraryVersionToReleased = compilerVersion == null) + ?: getDefaultLanguageLevel(module, compilerVersion, coerceRuntimeLibraryVersionToReleased = compilerVersion == null) } if (shouldInferAPILevel) { @@ -130,11 +119,11 @@ fun Module.getOrCreateFacet( val facetModel = modelsProvider.getModifiableFacetModel(this) val facet = facetModel.findFacet(KotlinFacetType.TYPE_ID, KotlinFacetType.INSTANCE.defaultFacetName) - ?: with(KotlinFacetType.INSTANCE) { createFacet(this@getOrCreateFacet, defaultFacetName, createDefaultConfiguration(), null) } - .apply { - val externalSource = externalSystemId?.let { ExternalProjectSystemRegistry.getInstance().getSourceById(it) } - facetModel.addFacet(this, externalSource) - } + ?: with(KotlinFacetType.INSTANCE) { createFacet(this@getOrCreateFacet, defaultFacetName, createDefaultConfiguration(), null) } + .apply { + val externalSource = externalSystemId?.let { ExternalProjectSystemRegistry.getInstance().getSourceById(it) } + facetModel.addFacet(this, externalSource) + } facet.configuration.settings.useProjectSettings = useProjectSettings if (commitModel) { runWriteAction { @@ -369,7 +358,7 @@ fun applyCompilerArgumentsToFacet( } } compilerSettings?.additionalArguments = - if (additionalArgumentsString.isNotEmpty()) additionalArgumentsString else CompilerSettings.DEFAULT_ADDITIONAL_ARGUMENTS + if (additionalArgumentsString.isNotEmpty()) additionalArgumentsString else CompilerSettings.DEFAULT_ADDITIONAL_ARGUMENTS with(compilerArguments::class.java.newInstance()) { copyFieldsSatisfying(this, compilerArguments) { exposeAsAdditionalArgument(it) || it.name in ignoredFields } diff --git a/idea/src/org/jetbrains/kotlin/idea/filters/InlineFunctionHyperLinkInfo.kt b/idea/src/org/jetbrains/kotlin/idea/filters/InlineFunctionHyperLinkInfo.kt index 314b3bd872a..e4f8f5708fd 100644 --- a/idea/src/org/jetbrains/kotlin/idea/filters/InlineFunctionHyperLinkInfo.kt +++ b/idea/src/org/jetbrains/kotlin/idea/filters/InlineFunctionHyperLinkInfo.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.filters @@ -30,8 +19,8 @@ import javax.swing.JList import javax.swing.ListCellRenderer class InlineFunctionHyperLinkInfo( - private val project: Project, - private val inlineInfo: List + private val project: Project, + private val inlineInfo: List ) : HyperlinkInfoBase(), FileHyperlinkInfo { override fun navigate(project: Project, hyperlinkLocationPoint: RelativePoint?) { @@ -39,22 +28,20 @@ class InlineFunctionHyperLinkInfo( if (inlineInfo.size == 1) { OpenFileHyperlinkInfo(project, inlineInfo.first().file, inlineInfo.first().line).navigate(project) - } - else { + } else { val list = JBList(inlineInfo) list.cellRenderer = InlineInfoCellRenderer() val popup = JBPopupFactory.getInstance().createListPopupBuilder(list) - .setTitle("Navigate to") - .setItemChoosenCallback { - val fileInfo = list.selectedValue as InlineInfo - OpenFileHyperlinkInfo(project, fileInfo.file, fileInfo.line).navigate(project) - } - .createPopup() + .setTitle("Navigate to") + .setItemChoosenCallback { + val fileInfo = list.selectedValue as InlineInfo + OpenFileHyperlinkInfo(project, fileInfo.file, fileInfo.line).navigate(project) + } + .createPopup() if (hyperlinkLocationPoint != null) { popup.show(hyperlinkLocationPoint) - } - else { + } else { popup.showInFocusCenter() } } @@ -66,8 +53,8 @@ class InlineFunctionHyperLinkInfo( } sealed class InlineInfo(val prefix: String, val file: VirtualFile, val line: Int) { - class CallSiteInfo(file: VirtualFile, line: Int): InlineInfo("inline function call site", file, line) - class InlineFunctionBodyInfo(file: VirtualFile, line: Int): InlineInfo("inline function body", file, line) + class CallSiteInfo(file: VirtualFile, line: Int) : InlineInfo("inline function call site", file, line) + class InlineFunctionBodyInfo(file: VirtualFile, line: Int) : InlineInfo("inline function body", file, line) } private class InlineInfoCellRenderer : SimpleColoredComponent(), ListCellRenderer { @@ -76,11 +63,11 @@ class InlineFunctionHyperLinkInfo( } override fun getListCellRendererComponent( - list: JList?, - value: InlineInfo?, - index: Int, - isSelected: Boolean, - cellHasFocus: Boolean + list: JList?, + value: InlineInfo?, + index: Int, + isSelected: Boolean, + cellHasFocus: Boolean ): Component { clear() @@ -92,8 +79,7 @@ class InlineFunctionHyperLinkInfo( if (isSelected) { background = list?.selectionBackground foreground = list?.selectionForeground - } - else { + } else { background = list?.background foreground = list?.foreground } diff --git a/idea/src/org/jetbrains/kotlin/idea/formatter/CollectChangesWithoutApplyModel.kt b/idea/src/org/jetbrains/kotlin/idea/formatter/CollectChangesWithoutApplyModel.kt index 359a242b37c..5bd385cc55a 100644 --- a/idea/src/org/jetbrains/kotlin/idea/formatter/CollectChangesWithoutApplyModel.kt +++ b/idea/src/org/jetbrains/kotlin/idea/formatter/CollectChangesWithoutApplyModel.kt @@ -1,5 +1,5 @@ /* - * Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -20,7 +20,10 @@ import org.jetbrains.kotlin.idea.formatter.FormattingChange.ShiftIndentInsideRan import org.jetbrains.kotlin.psi.NotNullablePsiCopyableUserDataProperty import org.jetbrains.kotlin.psi.UserDataProperty -private var PsiFile.collectFormattingChanges: Boolean by NotNullablePsiCopyableUserDataProperty(Key.create("COLLECT_FORMATTING_CHANGES"), false) +private var PsiFile.collectFormattingChanges: Boolean by NotNullablePsiCopyableUserDataProperty( + Key.create("COLLECT_FORMATTING_CHANGES"), + false +) private var PsiFile.collectChangesFormattingModel: CollectChangesWithoutApplyModel? by UserDataProperty(Key.create("COLLECT_CHANGES_FORMATTING_MODEL")) fun createCollectFormattingChangesModel(file: PsiFile, block: Block): FormattingModel? { @@ -43,8 +46,7 @@ fun collectFormattingChanges(file: PsiFile): Set { file.collectFormattingChanges = true CodeStyleManager.getInstance(file.project).reformat(file, true) return file.collectChangesFormattingModel?.requestedChanges ?: emptySet() - } - finally { + } finally { file.collectFormattingChanges = false file.collectChangesFormattingModel = null } diff --git a/idea/src/org/jetbrains/kotlin/idea/formatter/ImportSettingsPanel.kt b/idea/src/org/jetbrains/kotlin/idea/formatter/ImportSettingsPanel.kt index 2ee055ec03a..62b329db9ca 100644 --- a/idea/src/org/jetbrains/kotlin/idea/formatter/ImportSettingsPanel.kt +++ b/idea/src/org/jetbrains/kotlin/idea/formatter/ImportSettingsPanel.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.formatter @@ -70,9 +59,12 @@ class ImportSettingsPanel(private val commonSettings: CodeStyleSettings) : JPane private val starImportPackageTable = ImportLayoutPanel.createTableForPackageEntries(starImportPackageEntryTable, dummyImportLayoutPanel) private val nameCountToUseStarImportSelector = NameCountToUseStarImportSelector( - "Top-level Symbols", KotlinCodeStyleSettings.defaultSettings().NAME_COUNT_TO_USE_STAR_IMPORT) + "Top-level Symbols", KotlinCodeStyleSettings.defaultSettings().NAME_COUNT_TO_USE_STAR_IMPORT + ) + private val nameCountToUseStarImportForMembersSelector = NameCountToUseStarImportSelector( - "Java Statics and Enum Members", KotlinCodeStyleSettings.defaultSettings().NAME_COUNT_TO_USE_STAR_IMPORT_FOR_MEMBERS) + "Java Statics and Enum Members", KotlinCodeStyleSettings.defaultSettings().NAME_COUNT_TO_USE_STAR_IMPORT_FOR_MEMBERS + ) init { layout = BorderLayout() diff --git a/idea/src/org/jetbrains/kotlin/idea/formatter/KotlinFormattingModelBuilder.kt b/idea/src/org/jetbrains/kotlin/idea/formatter/KotlinFormattingModelBuilder.kt index bede215ba98..3c31f6caddc 100644 --- a/idea/src/org/jetbrains/kotlin/idea/formatter/KotlinFormattingModelBuilder.kt +++ b/idea/src/org/jetbrains/kotlin/idea/formatter/KotlinFormattingModelBuilder.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.formatter @@ -34,13 +23,15 @@ class KotlinFormattingModelBuilder : FormattingModelBuilder { override fun createModel(element: PsiElement, settings: CodeStyleSettings): FormattingModel { val containingFile = element.containingFile.viewProvider.getPsi(KotlinLanguage.INSTANCE) val block = KotlinBlock( - containingFile.node, NodeAlignmentStrategy.getNullStrategy(), Indent.getNoneIndent(), null, settings, - createSpacingBuilder(settings, KotlinSpacingBuilderUtilImpl)) + containingFile.node, NodeAlignmentStrategy.getNullStrategy(), Indent.getNoneIndent(), null, settings, + createSpacingBuilder(settings, KotlinSpacingBuilderUtilImpl) + ) //TODO: this is temporary code to allow formatting non-physical files in non-UI thread (used by conversion from Java to Kotlin) // it's needed until IDEA's issue with this document being created with wrong threading policy is fixed if (!element.isPhysical) { - val formattingDocumentModel = FormattingDocumentModelImpl(DocumentImpl(containingFile.viewProvider.contents, true), containingFile) + val formattingDocumentModel = + FormattingDocumentModelImpl(DocumentImpl(containingFile.viewProvider.contents, true), containingFile) return PsiBasedFormattingModel(containingFile, block, formattingDocumentModel) } diff --git a/idea/src/org/jetbrains/kotlin/idea/framework/KotlinLibraryUtil.kt b/idea/src/org/jetbrains/kotlin/idea/framework/KotlinLibraryUtil.kt index d78a8e07082..414bf6cd856 100644 --- a/idea/src/org/jetbrains/kotlin/idea/framework/KotlinLibraryUtil.kt +++ b/idea/src/org/jetbrains/kotlin/idea/framework/KotlinLibraryUtil.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -14,12 +14,10 @@ val MAVEN_SYSTEM_ID = ProjectSystemId("Maven") val GRADLE_SYSTEM_ID = ProjectSystemId("GRADLE") val KOBALT_SYSTEM_ID = ProjectSystemId("KOBALT") -fun isExternalLibrary(library: Library): Boolean { - return ExternalSystemApiUtil.isExternalSystemLibrary(library, ProjectSystemId.IDE) || - ExternalSystemApiUtil.isExternalSystemLibrary(library, GRADLE_SYSTEM_ID) || - ExternalSystemApiUtil.isExternalSystemLibrary(library, KOBALT_SYSTEM_ID) || - ExternalSystemApiUtil.isExternalSystemLibrary(library, MAVEN_SYSTEM_ID) -} +fun isExternalLibrary(library: Library): Boolean = ExternalSystemApiUtil.isExternalSystemLibrary(library, ProjectSystemId.IDE) || + ExternalSystemApiUtil.isExternalSystemLibrary(library, GRADLE_SYSTEM_ID) || + ExternalSystemApiUtil.isExternalSystemLibrary(library, KOBALT_SYSTEM_ID) || + ExternalSystemApiUtil.isExternalSystemLibrary(library, MAVEN_SYSTEM_ID) fun Module.isGradleModule() = diff --git a/idea/src/org/jetbrains/kotlin/idea/framework/KotlinSdkType.kt b/idea/src/org/jetbrains/kotlin/idea/framework/KotlinSdkType.kt index e93179adbd4..b56e25013d6 100644 --- a/idea/src/org/jetbrains/kotlin/idea/framework/KotlinSdkType.kt +++ b/idea/src/org/jetbrains/kotlin/idea/framework/KotlinSdkType.kt @@ -1,10 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. - * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. - */ - -/* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -25,7 +20,8 @@ import javax.swing.JComponent class KotlinSdkType : SdkType("KotlinSDK") { companion object { - @JvmField val INSTANCE = KotlinSdkType() + @JvmField + val INSTANCE = KotlinSdkType() val defaultHomePath: String get() = PathUtil.kotlinPathsForIdeaPlugin.homePath.absolutePath diff --git a/idea/src/org/jetbrains/kotlin/idea/framework/LibraryEffectiveKindProviderImpl.kt b/idea/src/org/jetbrains/kotlin/idea/framework/LibraryEffectiveKindProviderImpl.kt index a0d79e22144..5d32ccb8db1 100644 --- a/idea/src/org/jetbrains/kotlin/idea/framework/LibraryEffectiveKindProviderImpl.kt +++ b/idea/src/org/jetbrains/kotlin/idea/framework/LibraryEffectiveKindProviderImpl.kt @@ -1,5 +1,5 @@ /* - * Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -21,24 +21,21 @@ class LibraryEffectiveKindProviderImpl(project: Project) : LibraryEffectiveKindP init { project.messageBus.connect(project).subscribe( - ProjectTopics.PROJECT_ROOTS, - object : ModuleRootListener { - override fun rootsChanged(event: ModuleRootEvent) { - synchronized(effectiveKindMap) { - effectiveKindMap.clear() - } + ProjectTopics.PROJECT_ROOTS, + object : ModuleRootListener { + override fun rootsChanged(event: ModuleRootEvent) { + synchronized(effectiveKindMap) { + effectiveKindMap.clear() } } + } ) } - override fun getEffectiveKind(library: LibraryEx): PersistentLibraryKind<*>? { - val kind = library.kind - return when (kind) { - is KotlinLibraryKind -> kind - else -> synchronized(effectiveKindMap) { - effectiveKindMap.get(library) - } + override fun getEffectiveKind(library: LibraryEx): PersistentLibraryKind<*>? = when (val kind = library.kind) { + is KotlinLibraryKind -> kind + else -> synchronized(effectiveKindMap) { + effectiveKindMap.get(library) } } } \ No newline at end of file diff --git a/idea/src/org/jetbrains/kotlin/idea/goto/KotlinExpectOrActualGotoRelatedProvider.kt b/idea/src/org/jetbrains/kotlin/idea/goto/KotlinExpectOrActualGotoRelatedProvider.kt index 83a74985257..be5ca005c63 100644 --- a/idea/src/org/jetbrains/kotlin/idea/goto/KotlinExpectOrActualGotoRelatedProvider.kt +++ b/idea/src/org/jetbrains/kotlin/idea/goto/KotlinExpectOrActualGotoRelatedProvider.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.goto @@ -24,7 +13,7 @@ import org.jetbrains.kotlin.psi.KtNamedDeclaration import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypeAndBranch class KotlinExpectOrActualGotoRelatedProvider : GotoRelatedProvider() { - private class ActualOrExpectGotoRelatedItem(element: PsiElement): GotoRelatedItem(element) { + private class ActualOrExpectGotoRelatedItem(element: PsiElement) : GotoRelatedItem(element) { override fun getCustomContainerName(): String? { val module = element?.module ?: return null return "(in module ${module.name})" diff --git a/idea/src/org/jetbrains/kotlin/idea/goto/KotlinSearchEverywhereClassifier.kt b/idea/src/org/jetbrains/kotlin/idea/goto/KotlinSearchEverywhereClassifier.kt index 95d37b91350..af9cdedacf4 100644 --- a/idea/src/org/jetbrains/kotlin/idea/goto/KotlinSearchEverywhereClassifier.kt +++ b/idea/src/org/jetbrains/kotlin/idea/goto/KotlinSearchEverywhereClassifier.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.goto @@ -31,7 +20,13 @@ class KotlinSearchEverywhereClassifier : SearchEverywhereClassifier { override fun getVirtualFile(o: Any) = (o as? PsiElement)?.containingFile?.virtualFile - override fun getListCellRendererComponent(list: JList<*>, value: Any?, index: Int, isSelected: Boolean, cellHasFocus: Boolean): Component? { + override fun getListCellRendererComponent( + list: JList<*>, + value: Any?, + index: Int, + isSelected: Boolean, + cellHasFocus: Boolean + ): Component? { val declaration = (value as? PsiElement)?.unwrapped as? KtNamedDeclaration ?: return null return KotlinSearchEverywherePsiRenderer(list).getListCellRendererComponent(list, declaration, index, isSelected, isSelected) } diff --git a/idea/src/org/jetbrains/kotlin/idea/goto/gotoContributors.kt b/idea/src/org/jetbrains/kotlin/idea/goto/gotoContributors.kt index 50edc916461..a54b9a09598 100644 --- a/idea/src/org/jetbrains/kotlin/idea/goto/gotoContributors.kt +++ b/idea/src/org/jetbrains/kotlin/idea/goto/gotoContributors.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -52,16 +52,14 @@ class KotlinGotoClassContributor : GotoClassContributor { * We have to process Kotlin builtIn classes separately since no light classes are built for them. * */ class KotlinGotoSymbolContributor : GotoClassContributor { - override fun getNames(project: Project, includeNonProjectItems: Boolean): Array { - return listOf( - KotlinFunctionShortNameIndex.getInstance(), - KotlinPropertyShortNameIndex.getInstance(), - KotlinClassShortNameIndex.getInstance(), - KotlinTypeAliasShortNameIndex.getInstance() - ).flatMap { - StubIndex.getInstance().getAllKeys(it.key, project) - }.toTypedArray() - } + override fun getNames(project: Project, includeNonProjectItems: Boolean): Array = listOf( + KotlinFunctionShortNameIndex.getInstance(), + KotlinPropertyShortNameIndex.getInstance(), + KotlinClassShortNameIndex.getInstance(), + KotlinTypeAliasShortNameIndex.getInstance() + ).flatMap { + StubIndex.getInstance().getAllKeys(it.key, project) + }.toTypedArray() override fun getItemsByName(name: String, pattern: String, project: Project, includeNonProjectItems: Boolean): Array { val baseScope = if (includeNonProjectItems) GlobalSearchScope.allScope(project) else GlobalSearchScope.projectScope(project) @@ -74,7 +72,7 @@ class KotlinGotoSymbolContributor : GotoClassContributor { } result += KotlinPropertyShortNameIndex.getInstance().get(name, project, noLibrarySourceScope).filter { LightClassUtil.getLightClassBackingField(it) == null || - it.containingClass()?.isInterface() ?: false + it.containingClass()?.isInterface() ?: false } result += KotlinClassShortNameIndex.getInstance().get(name, project, noLibrarySourceScope).filter { it is KtEnumEntry || it.containingFile.virtualFile?.fileType == KotlinBuiltInFileType diff --git a/idea/src/org/jetbrains/kotlin/idea/hierarchy/KotlinTypeHierarchyProvider.kt b/idea/src/org/jetbrains/kotlin/idea/hierarchy/KotlinTypeHierarchyProvider.kt index 0f2d7d1ff34..337d7b8dc34 100644 --- a/idea/src/org/jetbrains/kotlin/idea/hierarchy/KotlinTypeHierarchyProvider.kt +++ b/idea/src/org/jetbrains/kotlin/idea/hierarchy/KotlinTypeHierarchyProvider.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.hierarchy @@ -50,8 +39,8 @@ class KotlinTypeHierarchyProvider : JavaTypeHierarchyProvider() { val javaClassId = JavaToKotlinClassMap.mapKotlinToJava(fqName.toUnsafe()) if (javaClassId != null) { return JavaPsiFacade.getInstance(classOrObject.project).findClass( - javaClassId.asSingleFqName().asString(), - GlobalSearchScope.allScope(classOrObject.project) + javaClassId.asSingleFqName().asString(), + GlobalSearchScope.allScope(classOrObject.project) ) } } @@ -76,7 +65,7 @@ class KotlinTypeHierarchyProvider : JavaTypeHierarchyProvider() { val returnTypeText = DescriptorRenderer.FQ_NAMES_IN_TYPES.renderType(type) if (returnTypeText != functionName) return null val classOrObject = KotlinClassShortNameIndex.getInstance()[functionName, project, project.allScope()].singleOrNull() - ?: return null + ?: return null getOriginalPsiClassOrCreateLightClass(classOrObject, module) } else -> null diff --git a/idea/src/org/jetbrains/kotlin/idea/hierarchy/calls/KotlinCallReferenceProcessor.kt b/idea/src/org/jetbrains/kotlin/idea/hierarchy/calls/KotlinCallReferenceProcessor.kt index 0a09fcd17ab..d7d9d5f9878 100644 --- a/idea/src/org/jetbrains/kotlin/idea/hierarchy/calls/KotlinCallReferenceProcessor.kt +++ b/idea/src/org/jetbrains/kotlin/idea/hierarchy/calls/KotlinCallReferenceProcessor.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.hierarchy.calls @@ -27,7 +16,13 @@ class KotlinCallReferenceProcessor : CallReferenceProcessor { override fun process(reference: PsiReference, data: JavaCallHierarchyData): Boolean { val nodeDescriptor = data.nodeDescriptor as? HierarchyNodeDescriptor ?: return false @Suppress("UNCHECKED_CAST") - KotlinCallerTreeStructure.processReference(reference, reference.element, nodeDescriptor, data.resultMap as MutableMap>, true) + KotlinCallerTreeStructure.processReference( + reference, + reference.element, + nodeDescriptor, + data.resultMap as MutableMap>, + true + ) return true } } diff --git a/idea/src/org/jetbrains/kotlin/idea/hierarchy/calls/KotlinCalleeTreeStructure.kt b/idea/src/org/jetbrains/kotlin/idea/hierarchy/calls/KotlinCalleeTreeStructure.kt index e3bfb14d299..e139b59cab9 100644 --- a/idea/src/org/jetbrains/kotlin/idea/hierarchy/calls/KotlinCalleeTreeStructure.kt +++ b/idea/src/org/jetbrains/kotlin/idea/hierarchy/calls/KotlinCalleeTreeStructure.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.hierarchy.calls @@ -33,22 +22,22 @@ import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject class KotlinCalleeTreeStructure( - element: KtElement, - private val scopeType: String -) : HierarchyTreeStructure(element.project, - KotlinCallHierarchyNodeDescriptor(null, element, true, false)) { - private fun KtElement.getCalleeSearchScope(): List { - return when (this) { - is KtNamedFunction, is KtFunctionLiteral, is KtPropertyAccessor -> listOf((this as KtDeclarationWithBody).bodyExpression) - is KtProperty -> accessors.map { it.bodyExpression } - is KtClassOrObject -> { - superTypeListEntries.filterIsInstance() + - getAnonymousInitializers().map { it.body } + - declarations.asSequence().filterIsInstance().map { it.initializer }.toList() - } - else -> emptyList() - }.filterNotNull() - } + element: KtElement, + private val scopeType: String +) : HierarchyTreeStructure( + element.project, + KotlinCallHierarchyNodeDescriptor(null, element, true, false) +) { + private fun KtElement.getCalleeSearchScope(): List = when (this) { + is KtNamedFunction, is KtFunctionLiteral, is KtPropertyAccessor -> listOf((this as KtDeclarationWithBody).bodyExpression) + is KtProperty -> accessors.map { it.bodyExpression } + is KtClassOrObject -> { + superTypeListEntries.filterIsInstance() + + getAnonymousInitializers().map { it.body } + + declarations.asSequence().filterIsInstance().map { it.initializer }.toList() + } + else -> emptyList() + }.filterNotNull() override fun buildChildren(nodeDescriptor: HierarchyNodeDescriptor): Array { if (nodeDescriptor is CallHierarchyNodeDescriptor) { @@ -64,12 +53,13 @@ class KotlinCalleeTreeStructure( element.getCalleeSearchScope().forEach { it.accept( - object : CalleeReferenceVisitorBase(it.analyze(), false) { - override fun processDeclaration(reference: KtSimpleNameExpression, declaration: PsiElement) { - if (!isInScope(baseClass, declaration, scopeType)) return - result += (getOrCreateNodeDescriptor(nodeDescriptor, declaration, null, false, calleeToDescriptorMap, false) ?: return) - } + object : CalleeReferenceVisitorBase(it.analyze(), false) { + override fun processDeclaration(reference: KtSimpleNameExpression, declaration: PsiElement) { + if (!isInScope(baseClass, declaration, scopeType)) return + result += (getOrCreateNodeDescriptor(nodeDescriptor, declaration, null, false, calleeToDescriptorMap, false) + ?: return) } + } ) } diff --git a/idea/src/org/jetbrains/kotlin/idea/hierarchy/calls/KotlinCallerTreeStructure.kt b/idea/src/org/jetbrains/kotlin/idea/hierarchy/calls/KotlinCallerTreeStructure.kt index f89ceb81792..d4969d68851 100644 --- a/idea/src/org/jetbrains/kotlin/idea/hierarchy/calls/KotlinCallerTreeStructure.kt +++ b/idea/src/org/jetbrains/kotlin/idea/hierarchy/calls/KotlinCallerTreeStructure.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.hierarchy.calls @@ -41,17 +30,16 @@ import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType class KotlinCallerTreeStructure( - element: KtElement, - private val scopeType: String -) : HierarchyTreeStructure(element.project, - KotlinCallHierarchyNodeDescriptor(null, element, true, false)) { + element: KtElement, + private val scopeType: String +) : HierarchyTreeStructure(element.project, KotlinCallHierarchyNodeDescriptor(null, element, true, false)) { companion object { internal fun processReference( - reference: PsiReference?, - refElement: PsiElement, - nodeDescriptor: HierarchyNodeDescriptor, - callerToDescriptorMap: MutableMap>, - isJavaMap: Boolean + reference: PsiReference?, + refElement: PsiElement, + nodeDescriptor: HierarchyNodeDescriptor, + callerToDescriptorMap: MutableMap>, + isJavaMap: Boolean ) { var callerElement: PsiElement? = when (refElement) { is KtElement -> getCallHierarchyElement(refElement) @@ -72,9 +60,9 @@ class KotlinCallerTreeStructure( } private fun buildChildren( - element: PsiElement, - nodeDescriptor: HierarchyNodeDescriptor, - callerToDescriptorMap: MutableMap> + element: PsiElement, + nodeDescriptor: HierarchyNodeDescriptor, + callerToDescriptorMap: MutableMap> ): Collection { if (nodeDescriptor is CallHierarchyNodeDescriptor) { val psiMethod = nodeDescriptor.enclosingElement as? PsiMethod ?: return emptyList() @@ -122,22 +110,21 @@ class KotlinCallerTreeStructure( if (descriptor is CallableMemberDescriptor) { return descriptor.getDeepestSuperDeclarations().flatMap { rootDescriptor -> val rootElement = DescriptorToSourceUtilsIde.getAnyDeclaration(myProject, rootDescriptor) - ?: return@flatMap emptyList() + ?: return@flatMap emptyList() val rootNodeDescriptor = when (rootElement) { is KtElement -> nodeDescriptor is PsiMethod -> CallHierarchyNodeDescriptor( - myProject, - nodeDescriptor.parentDescriptor as HierarchyNodeDescriptor?, - rootElement, - nodeDescriptor.parentDescriptor == null, - false + myProject, + nodeDescriptor.parentDescriptor as HierarchyNodeDescriptor?, + rootElement, + nodeDescriptor.parentDescriptor == null, + false ) else -> return@flatMap emptyList() } buildChildren(rootElement, rootNodeDescriptor, callerToDescriptorMap) }.toTypedArray() - } - else { + } else { return buildChildren(element, nodeDescriptor, callerToDescriptorMap).toTypedArray() } } diff --git a/idea/src/org/jetbrains/kotlin/idea/hierarchy/calls/callHierarchyUtils.kt b/idea/src/org/jetbrains/kotlin/idea/hierarchy/calls/callHierarchyUtils.kt index d455e8ebd5d..25b87faf3ab 100644 --- a/idea/src/org/jetbrains/kotlin/idea/hierarchy/calls/callHierarchyUtils.kt +++ b/idea/src/org/jetbrains/kotlin/idea/hierarchy/calls/callHierarchyUtils.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.hierarchy.calls @@ -28,11 +17,11 @@ import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf fun isCallHierarchyElement(e: PsiElement): Boolean { return (e is KtNamedFunction && e.name != null) || - e is KtSecondaryConstructor || - (e is KtProperty && !e.isLocal) || - e is KtObjectDeclaration || - (e is KtClass && !e.isInterface()) || - e is KtFile + e is KtSecondaryConstructor || + (e is KtProperty && !e.isLocal) || + e is KtObjectDeclaration || + (e is KtClass && !e.isInterface()) || + e is KtFile } fun getCallHierarchyElement(element: PsiElement) = element.parentsWithSelf.firstOrNull(::isCallHierarchyElement) as? KtElement @@ -52,22 +41,21 @@ private fun NodeDescriptor<*>.addReference(reference: PsiReference) { } internal fun getOrCreateNodeDescriptor( - parent: HierarchyNodeDescriptor, - originalElement: PsiElement, - reference: PsiReference?, - navigateToReference: Boolean, - elementToDescriptorMap: MutableMap>, - isJavaMap: Boolean + parent: HierarchyNodeDescriptor, + originalElement: PsiElement, + reference: PsiReference?, + navigateToReference: Boolean, + elementToDescriptorMap: MutableMap>, + isJavaMap: Boolean ): HierarchyNodeDescriptor? { val element = (if (isJavaMap && originalElement is KtElement) originalElement.toLightElements().firstOrNull() else originalElement) - ?: return null + ?: return null val existingDescriptor = elementToDescriptorMap[element] as? HierarchyNodeDescriptor val result = if (existingDescriptor != null) { existingDescriptor.incrementUsageCount() existingDescriptor - } - else { + } else { val newDescriptor: HierarchyNodeDescriptor = when (element) { is KtElement -> KotlinCallHierarchyNodeDescriptor(parent, element, false, navigateToReference) is PsiMember -> CallHierarchyNodeDescriptor(element.project, parent, element, false, navigateToReference) diff --git a/idea/src/org/jetbrains/kotlin/idea/hierarchy/overrides/KotlinOverrideHierarchyProvider.kt b/idea/src/org/jetbrains/kotlin/idea/hierarchy/overrides/KotlinOverrideHierarchyProvider.kt index 2505e0705a9..d03e1949fbd 100644 --- a/idea/src/org/jetbrains/kotlin/idea/hierarchy/overrides/KotlinOverrideHierarchyProvider.kt +++ b/idea/src/org/jetbrains/kotlin/idea/hierarchy/overrides/KotlinOverrideHierarchyProvider.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.hierarchy.overrides @@ -28,7 +17,7 @@ import org.jetbrains.kotlin.psi.KtCallableDeclaration import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypesAndPredicate -class KotlinOverrideHierarchyProvider: HierarchyProvider { +class KotlinOverrideHierarchyProvider : HierarchyProvider { override fun getTarget(dataContext: DataContext): PsiElement? { return CommonDataKeys.PROJECT.getData(dataContext)?.let { project -> getOverrideHierarchyElement(getCurrentElement(dataContext, project)) @@ -36,14 +25,14 @@ class KotlinOverrideHierarchyProvider: HierarchyProvider { } override fun createHierarchyBrowser(target: PsiElement): HierarchyBrowser = - KotlinOverrideHierarchyBrowser(target.project, target) + KotlinOverrideHierarchyBrowser(target.project, target) override fun browserActivated(hierarchyBrowser: HierarchyBrowser) { (hierarchyBrowser as HierarchyBrowserBaseEx).changeView(MethodHierarchyBrowserBase.METHOD_TYPE) } - private fun getOverrideHierarchyElement(element: PsiElement?): PsiElement? - = element?.getParentOfTypesAndPredicate { it.isOverrideHierarchyElement() } + private fun getOverrideHierarchyElement(element: PsiElement?): PsiElement? = + element?.getParentOfTypesAndPredicate { it.isOverrideHierarchyElement() } } fun PsiElement.isOverrideHierarchyElement() = this is KtCallableDeclaration && containingClassOrObject != null diff --git a/idea/src/org/jetbrains/kotlin/idea/hierarchy/overrides/KotlinOverrideTreeStructure.kt b/idea/src/org/jetbrains/kotlin/idea/hierarchy/overrides/KotlinOverrideTreeStructure.kt index 62d0cb8f7b0..09a649311bb 100644 --- a/idea/src/org/jetbrains/kotlin/idea/hierarchy/overrides/KotlinOverrideTreeStructure.kt +++ b/idea/src/org/jetbrains/kotlin/idea/hierarchy/overrides/KotlinOverrideTreeStructure.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.hierarchy.overrides @@ -39,12 +28,11 @@ class KotlinOverrideTreeStructure(project: Project, declaration: KtCallableDecla val baseElement = baseElement.element ?: return ArrayUtil.EMPTY_OBJECT_ARRAY val psiElement = nodeDescriptor.psiElement ?: return ArrayUtil.EMPTY_OBJECT_ARRAY val subclasses = HierarchySearchRequest(psiElement, psiElement.useScope, false).searchInheritors().findAll() - return subclasses - .mapNotNull { - val subclass = it.unwrapped ?: return@mapNotNull null - KotlinOverrideHierarchyNodeDescriptor(nodeDescriptor, subclass, baseElement) - } - .filter { it.calculateState() != AllIcons.Hierarchy.MethodNotDefined } - .toTypedArray() + return subclasses.mapNotNull { + val subclass = it.unwrapped ?: return@mapNotNull null + KotlinOverrideHierarchyNodeDescriptor(nodeDescriptor, subclass, baseElement) + } + .filter { it.calculateState() != AllIcons.Hierarchy.MethodNotDefined } + .toTypedArray() } } diff --git a/idea/src/org/jetbrains/kotlin/idea/highlighter/KotlinRainbowVisitor.kt b/idea/src/org/jetbrains/kotlin/idea/highlighter/KotlinRainbowVisitor.kt index 660229b073d..f792d59f33f 100644 --- a/idea/src/org/jetbrains/kotlin/idea/highlighter/KotlinRainbowVisitor.kt +++ b/idea/src/org/jetbrains/kotlin/idea/highlighter/KotlinRainbowVisitor.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.highlighter @@ -96,8 +85,8 @@ class KotlinRainbowVisitor : RainbowVisitor() { } val context = target.getStrictParentOfType() - ?: target.getStrictParentOfType() - ?: return + ?: target.getStrictParentOfType() + ?: return addInfo(getInfo(context, rainbowElement, rainbowElement.text, attributesKeyToUse)) } diff --git a/idea/src/org/jetbrains/kotlin/idea/highlighter/markers/KotlinClassTooltipLinkHandler.kt b/idea/src/org/jetbrains/kotlin/idea/highlighter/markers/KotlinClassTooltipLinkHandler.kt index 4b8936f7e26..2e0481371a2 100644 --- a/idea/src/org/jetbrains/kotlin/idea/highlighter/markers/KotlinClassTooltipLinkHandler.kt +++ b/idea/src/org/jetbrains/kotlin/idea/highlighter/markers/KotlinClassTooltipLinkHandler.kt @@ -1,5 +1,5 @@ /* - * Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -26,10 +26,9 @@ class KotlinClassTooltipLinkHandler : TooltipLinkHandler() { module?.let { GlobalSearchScope.moduleScope(it) } ?: GlobalSearchScope.allScope(project) } // Non-JVM classes cannot be found with Java PSI Facade - val aClassElement = - KotlinFullClassNameIndex.getInstance().get(qualifiedName, project, scope).firstOrNull() - ?: javaPsiFacade.findClass(qualifiedName, scope) - ?: return false + val aClassElement = KotlinFullClassNameIndex.getInstance().get(qualifiedName, project, scope).firstOrNull() + ?: javaPsiFacade.findClass(qualifiedName, scope) + ?: return false NavigationUtil.activateFileWithPsiElement(aClassElement) return true } diff --git a/idea/src/org/jetbrains/kotlin/idea/imports/KotlinImportOptimizer.kt b/idea/src/org/jetbrains/kotlin/idea/imports/KotlinImportOptimizer.kt index 864e32d1268..534c3eee2ad 100644 --- a/idea/src/org/jetbrains/kotlin/idea/imports/KotlinImportOptimizer.kt +++ b/idea/src/org/jetbrains/kotlin/idea/imports/KotlinImportOptimizer.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.imports @@ -201,7 +190,10 @@ class KotlinImportOptimizer : ImportOptimizer { if (isInScope(noImportsScope)) return true if (target !is ClassDescriptor) { // classes not accessible through receivers, only their constructors - if (resolutionScope.getImplicitReceiversHierarchy().any { isInScope(it.type.memberScope.memberScopeAsImportingScope()) }) return true + if (resolutionScope.getImplicitReceiversHierarchy().any { + isInScope(it.type.memberScope.memberScopeAsImportingScope()) + } + ) return true } return false } diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/AddVarianceModifierInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/AddVarianceModifierInspection.kt index 1479b1ec58c..8cdd04e1e1d 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/AddVarianceModifierInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/AddVarianceModifierInspection.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -32,9 +32,9 @@ class AddVarianceModifierInspection : AbstractKotlinInspection() { } for (member in klass.declarations + klass.primaryConstructorParameters) { val descriptor = when (member) { - is KtParameter -> context.get(BindingContext.PRIMARY_CONSTRUCTOR_PARAMETER, member) - else -> context.get(BindingContext.DECLARATION_TO_DESCRIPTOR, member) - } as? MemberDescriptor ?: continue + is KtParameter -> context.get(BindingContext.PRIMARY_CONSTRUCTOR_PARAMETER, member) + else -> context.get(BindingContext.DECLARATION_TO_DESCRIPTOR, member) + } as? MemberDescriptor ?: continue when (member) { is KtClassOrObject -> { if (!checkClassOrObject(member)) return false @@ -55,7 +55,7 @@ class AddVarianceModifierInspection : AbstractKotlinInspection() { for (typeParameter in klass.typeParameters) { if (typeParameter.variance != Variance.INVARIANT) continue val parameterDescriptor = - context.get(BindingContext.DECLARATION_TO_DESCRIPTOR, typeParameter) as? TypeParameterDescriptor ?: continue + context.get(BindingContext.DECLARATION_TO_DESCRIPTOR, typeParameter) as? TypeParameterDescriptor ?: continue val variances = listOf(Variance.IN_VARIANCE, Variance.OUT_VARIANCE).filter { variancePossible(klass, parameterDescriptor, it, context) } @@ -63,10 +63,10 @@ class AddVarianceModifierInspection : AbstractKotlinInspection() { val suggested = variances.first() val fixes = variances.map(::AddVarianceFix) holder.registerProblem( - typeParameter, - "Type parameter can have $suggested variance", - ProblemHighlightType.GENERIC_ERROR_OR_WARNING, - *fixes.toTypedArray() + typeParameter, + "Type parameter can have $suggested variance", + ProblemHighlightType.GENERIC_ERROR_OR_WARNING, + *fixes.toTypedArray() ) } } @@ -93,7 +93,7 @@ class AddVarianceModifierInspection : AbstractKotlinInspection() { override fun applyFix(project: Project, descriptor: ProblemDescriptor) { if (!FileModificationService.getInstance().preparePsiElementForWrite(descriptor.psiElement)) return val typeParameter = descriptor.psiElement as? KtTypeParameter - ?: throw AssertionError("Add variance fix is used on ${descriptor.psiElement.text}") + ?: throw AssertionError("Add variance fix is used on ${descriptor.psiElement.text}") addModifier(typeParameter, if (variance == Variance.IN_VARIANCE) KtTokens.IN_KEYWORD else KtTokens.OUT_KEYWORD) } diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/ArrayInDataClassInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/ArrayInDataClassInspection.kt index 4adcfc4d0ff..61124f1d51b 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/ArrayInDataClassInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/ArrayInDataClassInspection.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -34,10 +34,12 @@ class ArrayInDataClassInspection : AbstractKotlinInspection() { if (!parameter.hasValOrVar()) continue val type = context.get(BindingContext.TYPE, parameter.typeReference) ?: continue if (KotlinBuiltIns.isArray(type) || KotlinBuiltIns.isPrimitiveArray(type)) { - holder.registerProblem(parameter, - "Array property in data class: it's recommended to override equals() / hashCode()", - ProblemHighlightType.GENERIC_ERROR_OR_WARNING, - GenerateEqualsAndHashcodeFix()) + holder.registerProblem( + parameter, + "Array property in data class: it's recommended to override equals() / hashCode()", + ProblemHighlightType.GENERIC_ERROR_OR_WARNING, + GenerateEqualsAndHashcodeFix() + ) } } } diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/CanBePrimaryConstructorPropertyInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/CanBePrimaryConstructorPropertyInspection.kt index 4ac9f4be10b..c1ea0cb4ef2 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/CanBePrimaryConstructorPropertyInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/CanBePrimaryConstructorPropertyInspection.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -44,16 +44,18 @@ class CanBePrimaryConstructorPropertyInspection : AbstractKotlinInspection() { val assignedParameter = DescriptorToSourceUtils.descriptorToDeclaration(assignedDescriptor) as? KtParameter ?: return if (property.containingClassOrObject !== assignedParameter.containingClassOrObject) return - if (property.containingClassOrObject?.isInterfaceClass() ?: false) return + if (property.containingClassOrObject?.isInterfaceClass() == true) return - holder.registerProblem(holder.manager.createProblemDescriptor( + holder.registerProblem( + holder.manager.createProblemDescriptor( nameIdentifier, nameIdentifier, "Property is explicitly assigned to parameter ${assignedDescriptor.name}, can be declared directly in constructor", ProblemHighlightType.GENERIC_ERROR_OR_WARNING, isOnTheFly, MovePropertyToConstructorIntention() - )) + ) + ) }) } } \ No newline at end of file diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/CascadeIfInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/CascadeIfInspection.kt index 6038916f34c..98e52e90536 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/CascadeIfInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/CascadeIfInspection.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -26,20 +26,20 @@ class CascadeIfInspection : AbstractKotlinInspection() { if (expression.isOneLiner()) return if (branches.any { - it == null || - it.lastBlockStatementOrThis() is KtIfExpression - }) return + it == null || it.lastBlockStatementOrThis() is KtIfExpression + } + ) return if (expression.isElseIf()) return if (expression.anyDescendantOfType { - it is KtBreakExpression || it is KtContinueExpression - }) return + it is KtBreakExpression || it is KtContinueExpression + } + ) return var current: KtIfExpression? = expression while (current != null) { - val condition = current.condition - when (condition) { + when (val condition = current.condition) { is KtBinaryExpression -> when (condition.operationToken) { KtTokens.ANDAND, KtTokens.OROR -> return } @@ -51,10 +51,10 @@ class CascadeIfInspection : AbstractKotlinInspection() { } holder.registerProblem( - expression.ifKeyword, - "Cascade if should be replaced with when", - ProblemHighlightType.GENERIC_ERROR_OR_WARNING, - IntentionWrapper(IfToWhenIntention(), expression.containingKtFile) + expression.ifKeyword, + "Cascade if should be replaced with when", + ProblemHighlightType.GENERIC_ERROR_OR_WARNING, + IntentionWrapper(IfToWhenIntention(), expression.containingKtFile) ) }) } diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/ConflictingExtensionPropertyInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/ConflictingExtensionPropertyInspection.kt index 8ba36eea7b5..b774b683ac4 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/ConflictingExtensionPropertyInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/ConflictingExtensionPropertyInspection.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -68,11 +68,11 @@ class ConflictingExtensionPropertyInspection : AbstractKotlinInspection() { val fixes = createFixes(property, conflictingExtension, isOnTheFly) val problemDescriptor = holder.manager.createProblemDescriptor( - nameElement, - "This property conflicts with synthetic extension and should be removed or renamed to avoid breaking code by future changes in the compiler", - true, - fixes, - ProblemHighlightType.GENERIC_ERROR_OR_WARNING + nameElement, + "This property conflicts with synthetic extension and should be removed or renamed to avoid breaking code by future changes in the compiler", + true, + fixes, + ProblemHighlightType.GENERIC_ERROR_OR_WARNING ) holder.registerProblem(problemDescriptor) } @@ -82,7 +82,7 @@ class ConflictingExtensionPropertyInspection : AbstractKotlinInspection() { private fun conflictingSyntheticExtension(descriptor: PropertyDescriptor, scopes: SyntheticScopes): SyntheticJavaPropertyDescriptor? { val extensionReceiverType = descriptor.extensionReceiverParameter?.type ?: return null return scopes.collectSyntheticExtensionProperties(listOf(extensionReceiverType), descriptor.name, NoLookupLocation.FROM_IDE) - .firstIsInstanceOrNull() + .firstIsInstanceOrNull() } private fun isSameAsSynthetic(declaration: KtProperty, syntheticProperty: SyntheticJavaPropertyDescriptor): Boolean { @@ -103,8 +103,7 @@ class ConflictingExtensionPropertyInspection : AbstractKotlinInspection() { return if (getter.hasBlockBody()) { val statement = getter.bodyBlockExpression?.statements?.singleOrNull() ?: return false (statement as? KtReturnExpression)?.returnedExpression.isGetMethodCall(getMethod) - } - else { + } else { getter.bodyExpression.isGetMethodCall(getMethod) } } @@ -114,8 +113,7 @@ class ConflictingExtensionPropertyInspection : AbstractKotlinInspection() { if (setter.hasBlockBody()) { val statement = setter.bodyBlockExpression?.statements?.singleOrNull() ?: return false return statement.isSetMethodCall(setMethod, valueParameterName) - } - else { + } else { return setter.bodyExpression.isSetMethodCall(setMethod, valueParameterName) } } @@ -137,21 +135,32 @@ class ConflictingExtensionPropertyInspection : AbstractKotlinInspection() { private fun KtExpression?.isSetMethodCall(setMethod: FunctionDescriptor, valueParameterName: Name): Boolean { when (this) { is KtCallExpression -> { - if ((valueArguments.singleOrNull()?.getArgumentExpression() as? KtSimpleNameExpression)?.getReferencedNameAsName() != valueParameterName) return false + if ((valueArguments.singleOrNull() + ?.getArgumentExpression() as? KtSimpleNameExpression)?.getReferencedNameAsName() != valueParameterName + ) return false val resolvedCall = resolveToCall() - return resolvedCall != null && resolvedCall.isReallySuccess() && resolvedCall.resultingDescriptor.original == setMethod.original + return resolvedCall != null && + resolvedCall.isReallySuccess() && + resolvedCall.resultingDescriptor.original == setMethod.original } is KtQualifiedExpression -> { val receiver = receiverExpression - return receiver is KtThisExpression && receiver.labelQualifier == null && selectorExpression.isSetMethodCall(setMethod, valueParameterName) + return receiver is KtThisExpression && receiver.labelQualifier == null && selectorExpression.isSetMethodCall( + setMethod, + valueParameterName + ) } else -> return false } } - private fun createFixes(property: KtProperty, conflictingExtension: SyntheticJavaPropertyDescriptor, isOnTheFly: Boolean): Array { + private fun createFixes( + property: KtProperty, + conflictingExtension: SyntheticJavaPropertyDescriptor, + isOnTheFly: Boolean + ): Array { return if (isSameAsSynthetic(property, conflictingExtension)) { val fix1 = IntentionWrapper(DeleteRedundantExtensionAction(property), property.containingFile) // don't add the second fix when on the fly to allow code cleanup @@ -160,8 +169,7 @@ class ConflictingExtensionPropertyInspection : AbstractKotlinInspection() { else null listOfNotNull(fix1, fix2).toTypedArray() - } - else { + } else { emptyArray() } } @@ -179,33 +187,33 @@ class ConflictingExtensionPropertyInspection : AbstractKotlinInspection() { val fqName = declaration.unsafeResolveToDescriptor(BodyResolveMode.PARTIAL).importableFqName if (fqName != null) { ProgressManager.getInstance().run( - object : Task.Modal(project, "Searching for imports to delete", true) { - override fun run(indicator: ProgressIndicator) { - val importsToDelete = runReadAction { - val searchScope = KotlinSourceFilterScope.projectSources(GlobalSearchScope.projectScope(project), project) - ReferencesSearch.search(declaration, searchScope) - .filterIsInstance() - .mapNotNull { ref -> ref.expression.getStrictParentOfType() } - .filter { import -> !import.isAllUnder && import.targetDescriptors().size == 1 } - } - GuiUtils.invokeLaterIfNeeded({ - project.executeWriteCommand(text) { - importsToDelete.forEach { import -> - if (!FileModificationService.getInstance().preparePsiElementForWrite(import)) return@forEach - try { - import.delete() - } - catch(e: Exception) { - LOG.error(e) - } - } - declaration.delete() - } - }, ModalityState.NON_MODAL) + object : Task.Modal(project, "Searching for imports to delete", true) { + override fun run(indicator: ProgressIndicator) { + val importsToDelete = runReadAction { + val searchScope = KotlinSourceFilterScope.projectSources(GlobalSearchScope.projectScope(project), project) + ReferencesSearch.search(declaration, searchScope) + .filterIsInstance() + .mapNotNull { ref -> ref.expression.getStrictParentOfType() } + .filter { import -> !import.isAllUnder && import.targetDescriptors().size == 1 } } - }) - } - else { + GuiUtils.invokeLaterIfNeeded({ + project.executeWriteCommand(text) { + importsToDelete.forEach { import -> + if (!FileModificationService.getInstance() + .preparePsiElementForWrite(import) + ) return@forEach + try { + import.delete() + } catch (e: Exception) { + LOG.error(e) + } + } + declaration.delete() + } + }, ModalityState.NON_MODAL) + } + }) + } else { project.executeWriteCommand(text) { declaration.delete() } } } @@ -229,8 +237,7 @@ class ConflictingExtensionPropertyInspection : AbstractKotlinInspection() { val result = addAnnotationEntry(annotationEntry) modifierList!!.addAfter(newLine, result) result - } - else { + } else { val result = addAnnotationEntry(annotationEntry) addAfter(newLine, modifierList) result diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/CopyWithoutNamedArgumentsInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/CopyWithoutNamedArgumentsInspection.kt index c436fe4ceed..517561e56ad 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/CopyWithoutNamedArgumentsInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/CopyWithoutNamedArgumentsInspection.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -36,10 +36,10 @@ class CopyWithoutNamedArgumentsInspection : AbstractKotlinInspection() { if (call.candidateDescriptor != context[BindingContext.DATA_CLASS_COPY_FUNCTION, receiver]) return holder.registerProblem( - expression.calleeExpression ?: return, - "'copy' method of data class is called without named arguments", - ProblemHighlightType.GENERIC_ERROR_OR_WARNING, - IntentionWrapper(AddNamesToCallArgumentsIntention(), expression.containingKtFile) + expression.calleeExpression ?: return, + "'copy' method of data class is called without named arguments", + ProblemHighlightType.GENERIC_ERROR_OR_WARNING, + IntentionWrapper(AddNamesToCallArgumentsIntention(), expression.containingKtFile) ) }) } diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/DataClassPrivateConstructorInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/DataClassPrivateConstructorInspection.kt index 4dab979f8a3..b47a0fdd651 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/DataClassPrivateConstructorInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/DataClassPrivateConstructorInspection.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -19,11 +19,11 @@ class DataClassPrivateConstructorInspection : AbstractKotlinInspection() { if (constructor.containingClass()?.isData() == true && constructor.isPrivate()) { val keyword = constructor.modifierList?.getModifier(KtTokens.PRIVATE_KEYWORD) ?: return@primaryConstructorVisitor val problemDescriptor = holder.manager.createProblemDescriptor( - keyword, - keyword, - "Private data class constructor is exposed via the generated 'copy' method.", - ProblemHighlightType.GENERIC_ERROR_OR_WARNING, - isOnTheFly + keyword, + keyword, + "Private data class constructor is exposed via the generated 'copy' method.", + ProblemHighlightType.GENERIC_ERROR_OR_WARNING, + isOnTheFly ) holder.registerProblem(problemDescriptor) diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/DestructuringWrongNameInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/DestructuringWrongNameInspection.kt index edf73916cbd..1c9def4860c 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/DestructuringWrongNameInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/DestructuringWrongNameInspection.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -21,9 +21,9 @@ class DestructuringWrongNameInspection : AbstractKotlinInspection() { val classDescriptor = type.constructor.declarationDescriptor as? ClassDescriptor ?: return val primaryParameterNames = classDescriptor.constructors - .firstOrNull { it.isPrimary } - ?.valueParameters - ?.map { it.name.asString() } ?: return + .firstOrNull { it.isPrimary } + ?.valueParameters + ?.map { it.name.asString() } ?: return destructuringDeclaration.entries.forEachIndexed { entryIndex, entry -> val variableName = entry.name @@ -33,9 +33,10 @@ class DestructuringWrongNameInspection : AbstractKotlinInspection() { if (variableName == parameterName) { val fix = primaryParameterNames.getOrNull(entryIndex)?.let { RenameElementFix(entry, it) } holder.registerProblem( - entry, - "Variable name '$variableName' matches the name of a different component", - *listOfNotNull(fix).toTypedArray()) + entry, + "Variable name '$variableName' matches the name of a different component", + *listOfNotNull(fix).toTypedArray() + ) break } } diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/EmptyRangeInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/EmptyRangeInspection.kt index e7178dd8ffb..399ea242c9e 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/EmptyRangeInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/EmptyRangeInspection.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.inspections @@ -40,10 +29,11 @@ class EmptyRangeInspection : AbstractPrimitiveRangeToInspection() { if (startValue <= endValue) return holder.registerProblem( - expression, - "This range is empty. Did you mean to use 'downTo'?", - ProblemHighlightType.GENERIC_ERROR_OR_WARNING, - ReplaceWithDownToFix()) + expression, + "This range is empty. Did you mean to use 'downTo'?", + ProblemHighlightType.GENERIC_ERROR_OR_WARNING, + ReplaceWithDownToFix() + ) } class ReplaceWithDownToFix : LocalQuickFix { diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/EqualsOrHashCodeInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/EqualsOrHashCodeInspection.kt index c0559137194..5405a1458a2 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/EqualsOrHashCodeInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/EqualsOrHashCodeInspection.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -73,14 +73,14 @@ class EqualsOrHashCodeInspection : AbstractKotlinInspection() { ClassKind.CLASS -> { if (hasEquals && hasHashCode) return val description = InspectionsBundle.message( - "inspection.equals.hashcode.only.one.defined.problem.descriptor", - if (hasEquals) "equals()" else "hashCode()", - if (hasEquals) "hashCode()" else "equals()" + "inspection.equals.hashcode.only.one.defined.problem.descriptor", + if (hasEquals) "equals()" else "hashCode()", + if (hasEquals) "hashCode()" else "equals()" ) holder.registerProblem( - nameIdentifier, - description, - if (hasEquals) GenerateEqualsOrHashCodeFix.HashCode else GenerateEqualsOrHashCodeFix.Equals + nameIdentifier, + description, + if (hasEquals) GenerateEqualsOrHashCodeFix.HashCode else GenerateEqualsOrHashCodeFix.Equals ) } else -> return diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/FoldInitializerAndIfToElvisInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/FoldInitializerAndIfToElvisInspection.kt index 1715081a69f..fb61aeb49b0 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/FoldInitializerAndIfToElvisInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/FoldInitializerAndIfToElvisInspection.kt @@ -74,7 +74,8 @@ class FoldInitializerAndIfToElvisInspection : AbstractApplicabilityBasedInspecti declaration.isVar && declaration.typeReference == null -> initializer.analyze(BodyResolveMode.PARTIAL).getType(initializer) // for val with explicit type, change it to non-nullable - !declaration.isVar && declaration.typeReference != null -> initializer.analyze(BodyResolveMode.PARTIAL).getType(initializer)?.makeNotNullable() + !declaration.isVar && declaration.typeReference != null -> initializer.analyze(BodyResolveMode.PARTIAL).getType(initializer) + ?.makeNotNullable() else -> null } diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/FunctionWithLambdaExpressionBodyInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/FunctionWithLambdaExpressionBodyInspection.kt index c9cce0dc39c..db527df073d 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/FunctionWithLambdaExpressionBodyInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/FunctionWithLambdaExpressionBodyInspection.kt @@ -1,5 +1,5 @@ /* - * Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -48,7 +48,13 @@ class FunctionWithLambdaExpressionBodyInspection : AbstractKotlinInspection() { val fixes = listOfNotNull( IntentionWrapper(SpecifyTypeExplicitlyFix(), file), IntentionWrapper(AddArrowIntention(), file), - if (!used && lambdaBody.statements.size == 1 && lambdaBody.allChildren.none { it is PsiComment }) RemoveBracesFix() else null, + if (!used && + lambdaBody.statements.size == 1 && + lambdaBody.allChildren.none { it is PsiComment } + ) + RemoveBracesFix() + else + null, if (!used) WrapRunFix() else null ) holder.registerProblem( diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/ImplicitThisInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/ImplicitThisInspection.kt index c9399083637..1cfe26be3e6 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/ImplicitThisInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/ImplicitThisInspection.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.inspections @@ -53,8 +42,8 @@ class ImplicitThisInspection : AbstractKotlinInspection() { val descriptor = reference.getCallableDescriptor() ?: return val receiverDescriptor = descriptor.extensionReceiverParameter - ?: descriptor.dispatchReceiverParameter - ?: return + ?: descriptor.dispatchReceiverParameter + ?: return val receiverType = receiverDescriptor.type val expressionFactory = scope.getFactoryForImplicitReceiverWithSubtypeOf(receiverType) ?: return diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/KotlinCleanupInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/KotlinCleanupInspection.kt index c23c64625eb..bbd694b4335 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/KotlinCleanupInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/KotlinCleanupInspection.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.inspections @@ -83,24 +72,24 @@ class KotlinCleanupInspection : LocalInspectionTool(), CleanupLocalInspectionToo private fun Diagnostic.isCleanup() = factory in cleanupDiagnosticsFactories || isObsoleteLabel() private val cleanupDiagnosticsFactories = setOf( - Errors.MISSING_CONSTRUCTOR_KEYWORD, - Errors.UNNECESSARY_NOT_NULL_ASSERTION, - Errors.UNNECESSARY_SAFE_CALL, - Errors.USELESS_CAST, - Errors.USELESS_ELVIS, - ErrorsJvm.POSITIONED_VALUE_ARGUMENT_FOR_JAVA_ANNOTATION, - Errors.DEPRECATION, - Errors.DEPRECATION_ERROR, - Errors.NON_CONST_VAL_USED_IN_CONSTANT_EXPRESSION, - Errors.OPERATOR_MODIFIER_REQUIRED, - Errors.INFIX_MODIFIER_REQUIRED, - Errors.DEPRECATED_TYPE_PARAMETER_SYNTAX, - Errors.MISPLACED_TYPE_PARAMETER_CONSTRAINTS, - Errors.COMMA_IN_WHEN_CONDITION_WITHOUT_ARGUMENT, - ErrorsJs.WRONG_EXTERNAL_DECLARATION, - Errors.YIELD_IS_RESERVED, - Errors.DEPRECATED_MODIFIER_FOR_TARGET, - Errors.DEPRECATED_MODIFIER + Errors.MISSING_CONSTRUCTOR_KEYWORD, + Errors.UNNECESSARY_NOT_NULL_ASSERTION, + Errors.UNNECESSARY_SAFE_CALL, + Errors.USELESS_CAST, + Errors.USELESS_ELVIS, + ErrorsJvm.POSITIONED_VALUE_ARGUMENT_FOR_JAVA_ANNOTATION, + Errors.DEPRECATION, + Errors.DEPRECATION_ERROR, + Errors.NON_CONST_VAL_USED_IN_CONSTANT_EXPRESSION, + Errors.OPERATOR_MODIFIER_REQUIRED, + Errors.INFIX_MODIFIER_REQUIRED, + Errors.DEPRECATED_TYPE_PARAMETER_SYNTAX, + Errors.MISPLACED_TYPE_PARAMETER_CONSTRAINTS, + Errors.COMMA_IN_WHEN_CONDITION_WITHOUT_ARGUMENT, + ErrorsJs.WRONG_EXTERNAL_DECLARATION, + Errors.YIELD_IS_RESERVED, + Errors.DEPRECATED_MODIFIER_FOR_TARGET, + Errors.DEPRECATED_MODIFIER ) private fun Diagnostic.isObsoleteLabel(): Boolean { @@ -114,22 +103,34 @@ class KotlinCleanupInspection : LocalInspectionTool(), CleanupLocalInspectionToo private class Wrapper(val intention: IntentionAction, file: KtFile) : IntentionWrapper(intention, file) { override fun invoke(project: Project, editor: Editor?, file: PsiFile?) { - if (intention.isAvailable(project, editor, file)) { // we should check isAvailable here because some elements may get invalidated (or other conditions may change) + if (intention.isAvailable( + project, + editor, + file + ) + ) { // we should check isAvailable here because some elements may get invalidated (or other conditions may change) super.invoke(project, editor, file) } } } - private fun Diagnostic.toProblemDescriptor(fixes: Collection, file: KtFile, manager: InspectionManager): ProblemDescriptor { - return createProblemDescriptor(psiElement, DefaultErrorMessages.render(this), fixes, file, manager) - } + private fun Diagnostic.toProblemDescriptor(fixes: Collection, file: KtFile, manager: InspectionManager): ProblemDescriptor = + createProblemDescriptor(psiElement, DefaultErrorMessages.render(this), fixes, file, manager) - private fun createProblemDescriptor(element: PsiElement, message: String, fixes: Collection, file: KtFile, manager: InspectionManager): ProblemDescriptor { - return manager.createProblemDescriptor(element, - message, - false, - fixes.map { Wrapper(it, file) }.toTypedArray(), - ProblemHighlightType.GENERIC_ERROR_OR_WARNING) + private fun createProblemDescriptor( + element: PsiElement, + message: String, + fixes: Collection, + file: KtFile, + manager: InspectionManager + ): ProblemDescriptor { + return manager.createProblemDescriptor( + element, + message, + false, + fixes.map { Wrapper(it, file) }.toTypedArray(), + ProblemHighlightType.GENERIC_ERROR_OR_WARNING + ) } private class RemoveImportFix(import: KtImportDirective) : KotlinQuickFixAction(import), CleanupFix { diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/KotlinDoubleNegationInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/KotlinDoubleNegationInspection.kt index f6c66cebad6..caca0a4a2cb 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/KotlinDoubleNegationInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/KotlinDoubleNegationInspection.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -18,22 +18,25 @@ import org.jetbrains.kotlin.types.typeUtil.isBoolean class KotlinDoubleNegationInspection : AbstractKotlinInspection(), CleanupLocalInspectionTool { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession) = - prefixExpressionVisitor(fun(expression) { - if (expression.operationToken != KtTokens.EXCL || - expression.baseExpression?.getType(expression.analyze())?.isBoolean() != true) { - return - } - var parent = expression.parent - while (parent is KtParenthesizedExpression) { - parent = parent.parent - } - if (parent is KtPrefixExpression && parent.operationToken == KtTokens.EXCL) { - holder.registerProblem(expression, - "Redundant double negation", - ProblemHighlightType.GENERIC_ERROR_OR_WARNING, - DoubleNegationFix()) - } - }) + prefixExpressionVisitor(fun(expression) { + if (expression.operationToken != KtTokens.EXCL || + expression.baseExpression?.getType(expression.analyze())?.isBoolean() != true + ) { + return + } + var parent = expression.parent + while (parent is KtParenthesizedExpression) { + parent = parent.parent + } + if (parent is KtPrefixExpression && parent.operationToken == KtTokens.EXCL) { + holder.registerProblem( + expression, + "Redundant double negation", + ProblemHighlightType.GENERIC_ERROR_OR_WARNING, + DoubleNegationFix() + ) + } + }) private class DoubleNegationFix : LocalQuickFix { override fun getName() = "Remove redundant negations" diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/KotlinJUnitStaticEntryPoint.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/KotlinJUnitStaticEntryPoint.kt index 6fad578c1fa..a1f4c05886e 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/KotlinJUnitStaticEntryPoint.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/KotlinJUnitStaticEntryPoint.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @file:Suppress("DEPRECATION") @@ -33,8 +22,11 @@ class KotlinJUnitStaticEntryPoint(@JvmField var wasSelected: Boolean = true) : E override fun isEntryPoint(refElement: RefElement, psiElement: PsiElement) = isEntryPoint(psiElement) - private val staticJUnitAnnotations = listOf("org.junit.BeforeClass", "org.junit.AfterClass", - "org.junit.runners.Parameterized.Parameters") + private val staticJUnitAnnotations = listOf( + "org.junit.BeforeClass", + "org.junit.AfterClass", + "org.junit.runners.Parameterized.Parameters" + ) override fun isEntryPoint(psiElement: PsiElement) = psiElement is PsiMethod && AnnotationUtil.isAnnotated(psiElement, staticJUnitAnnotations) && diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/LeakingThisInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/LeakingThisInspection.kt index 09b178e6749..f66bb303dbb 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/LeakingThisInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/LeakingThisInspection.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -56,7 +56,9 @@ class LeakingThisInspection : AbstractKotlinInspection() { val function = leakingThisDescriptor.function klass.createDescription("Calling non-final function ${function.name} in constructor") { it.hasOverriddenMember { owner -> - owner is KtNamedFunction && owner.name == function.name.asString() && owner.valueParameters.size == function.valueParameters.size + owner is KtNamedFunction && + owner.name == function.name.asString() && + owner.valueParameters.size == function.valueParameters.size } } ?: continue@these } diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/MigrateDiagnosticSuppressionInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/MigrateDiagnosticSuppressionInspection.kt index 5b3535589e9..7a057bf5a6b 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/MigrateDiagnosticSuppressionInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/MigrateDiagnosticSuppressionInspection.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -35,10 +35,10 @@ class MigrateDiagnosticSuppressionInspection : AbstractKotlinInspection(), Clean val newDiagnosticFactory = MIGRATION_MAP[StringUtil.unquoteString(text)] ?: continue holder.registerProblem( - expression, - "Diagnostic name should be replaced by the new one", - ProblemHighlightType.GENERIC_ERROR_OR_WARNING, - ReplaceDiagnosticNameFix(newDiagnosticFactory) + expression, + "Diagnostic name should be replaced by the new one", + ProblemHighlightType.GENERIC_ERROR_OR_WARNING, + ReplaceDiagnosticNameFix(newDiagnosticFactory) ) } }) @@ -62,23 +62,23 @@ class MigrateDiagnosticSuppressionInspection : AbstractKotlinInspection(), Clean companion object { private val MIGRATION_MAP = mapOf( - "HEADER_DECLARATION_WITH_BODY" to EXPECTED_DECLARATION_WITH_BODY, - "HEADER_CLASS_CONSTRUCTOR_DELEGATION_CALL" to EXPECTED_CLASS_CONSTRUCTOR_DELEGATION_CALL, - "HEADER_CLASS_CONSTRUCTOR_PROPERTY_PARAMETER" to EXPECTED_CLASS_CONSTRUCTOR_PROPERTY_PARAMETER, - "HEADER_ENUM_CONSTRUCTOR" to EXPECTED_ENUM_CONSTRUCTOR, - "HEADER_ENUM_ENTRY_WITH_BODY" to EXPECTED_ENUM_ENTRY_WITH_BODY, - "HEADER_PROPERTY_INITIALIZER" to EXPECTED_PROPERTY_INITIALIZER, + "HEADER_DECLARATION_WITH_BODY" to EXPECTED_DECLARATION_WITH_BODY, + "HEADER_CLASS_CONSTRUCTOR_DELEGATION_CALL" to EXPECTED_CLASS_CONSTRUCTOR_DELEGATION_CALL, + "HEADER_CLASS_CONSTRUCTOR_PROPERTY_PARAMETER" to EXPECTED_CLASS_CONSTRUCTOR_PROPERTY_PARAMETER, + "HEADER_ENUM_CONSTRUCTOR" to EXPECTED_ENUM_CONSTRUCTOR, + "HEADER_ENUM_ENTRY_WITH_BODY" to EXPECTED_ENUM_ENTRY_WITH_BODY, + "HEADER_PROPERTY_INITIALIZER" to EXPECTED_PROPERTY_INITIALIZER, - "IMPL_TYPE_ALIAS_NOT_TO_CLASS" to ACTUAL_TYPE_ALIAS_NOT_TO_CLASS, - "IMPL_TYPE_ALIAS_TO_CLASS_WITH_DECLARATION_SITE_VARIANCE" to ACTUAL_TYPE_ALIAS_TO_CLASS_WITH_DECLARATION_SITE_VARIANCE, - "IMPL_TYPE_ALIAS_WITH_USE_SITE_VARIANCE" to ACTUAL_TYPE_ALIAS_WITH_USE_SITE_VARIANCE, - "IMPL_TYPE_ALIAS_WITH_COMPLEX_SUBSTITUTION" to ACTUAL_TYPE_ALIAS_WITH_COMPLEX_SUBSTITUTION, + "IMPL_TYPE_ALIAS_NOT_TO_CLASS" to ACTUAL_TYPE_ALIAS_NOT_TO_CLASS, + "IMPL_TYPE_ALIAS_TO_CLASS_WITH_DECLARATION_SITE_VARIANCE" to ACTUAL_TYPE_ALIAS_TO_CLASS_WITH_DECLARATION_SITE_VARIANCE, + "IMPL_TYPE_ALIAS_WITH_USE_SITE_VARIANCE" to ACTUAL_TYPE_ALIAS_WITH_USE_SITE_VARIANCE, + "IMPL_TYPE_ALIAS_WITH_COMPLEX_SUBSTITUTION" to ACTUAL_TYPE_ALIAS_WITH_COMPLEX_SUBSTITUTION, - "HEADER_WITHOUT_IMPLEMENTATION" to NO_ACTUAL_FOR_EXPECT, - "IMPLEMENTATION_WITHOUT_HEADER" to ACTUAL_WITHOUT_EXPECT, + "HEADER_WITHOUT_IMPLEMENTATION" to NO_ACTUAL_FOR_EXPECT, + "IMPLEMENTATION_WITHOUT_HEADER" to ACTUAL_WITHOUT_EXPECT, - "HEADER_CLASS_MEMBERS_ARE_NOT_IMPLEMENTED" to NO_ACTUAL_CLASS_MEMBER_FOR_EXPECTED_CLASS, - "IMPL_MISSING" to ACTUAL_MISSING + "HEADER_CLASS_MEMBERS_ARE_NOT_IMPLEMENTED" to NO_ACTUAL_CLASS_MEMBER_FOR_EXPECTED_CLASS, + "IMPL_MISSING" to ACTUAL_MISSING ) } } diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/NullChecksToSafeCallInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/NullChecksToSafeCallInspection.kt index 1080c8e7384..c943ed5678f 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/NullChecksToSafeCallInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/NullChecksToSafeCallInspection.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -95,7 +95,9 @@ class NullChecksToSafeCallInspection : AbstractKotlinInspection() { private fun KtExpression.isChainStable(context: BindingContext): Boolean = when (this) { is KtReferenceExpression -> isStableSimpleExpression(context) - is KtQualifiedExpression -> selectorExpression?.isStableSimpleExpression(context) == true && receiverExpression.isChainStable(context) + is KtQualifiedExpression -> selectorExpression?.isStableSimpleExpression(context) == true && receiverExpression.isChainStable( + context + ) else -> false } } diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/NullableBooleanElvisInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/NullableBooleanElvisInspection.kt index 820640ab193..cfe4611e81a 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/NullableBooleanElvisInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/NullableBooleanElvisInspection.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -30,9 +30,8 @@ class NullableBooleanElvisInspection : AbstractKotlinInspection(), CleanupLocalI if (!KtPsiUtil.isBooleanConstant(rhs)) return val lhsType = lhs.analyze(BodyResolveMode.PARTIAL).getType(lhs) ?: return if (TypeUtils.isNullableType(lhsType) && lhsType.isBooleanOrNullableBoolean()) { - val parentIfOrWhile = PsiTreeUtil.getParentOfType( - expression, KtIfExpression::class.java, KtWhileExpressionBase::class.java) - val condition = when (parentIfOrWhile) { + val condition = when (val parentIfOrWhile = + PsiTreeUtil.getParentOfType(expression, KtIfExpression::class.java, KtWhileExpressionBase::class.java)) { is KtIfExpression -> parentIfOrWhile.condition is KtWhileExpressionBase -> parentIfOrWhile.condition else -> null @@ -43,11 +42,11 @@ class NullableBooleanElvisInspection : AbstractKotlinInspection(), CleanupLocalI INFORMATION to "can" holder.registerProblemWithoutOfflineInformation( - expression, - "Equality check $verb be used instead of elvis for nullable boolean check", - isOnTheFly, - highlightType, - ReplaceWithEqualityCheckFix() + expression, + "Equality check $verb be used instead of elvis for nullable boolean check", + isOnTheFly, + highlightType, + ReplaceWithEqualityCheckFix() ) } }) diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/OverridingDeprecatedMemberInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/OverridingDeprecatedMemberInspection.kt index 6f048b91533..4ebb9595dce 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/OverridingDeprecatedMemberInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/OverridingDeprecatedMemberInspection.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.inspections @@ -51,14 +40,14 @@ class OverridingDeprecatedMemberInspection : AbstractKotlinInspection() { val deprecationProvider = declaration.getResolutionFacade().frontendService() val message = deprecationProvider.getDeprecations(accessorDescriptor) - .firstOrNull() - ?.deprecatedByOverriddenMessage() ?: return + .firstOrNull() + ?.deprecatedByOverriddenMessage() ?: return val problem = holder.manager.createProblemDescriptor( - targetForProblem, - message, - /* showTooltip = */ true, - ProblemHighlightType.LIKE_DEPRECATED, - isOnTheFly + targetForProblem, + message, + /* showTooltip = */ true, + ProblemHighlightType.LIKE_DEPRECATED, + isOnTheFly ) holder.registerProblem(problem) } diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/PlatformUnresolvedProvider.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/PlatformUnresolvedProvider.kt index 3e927a427be..7e29004b88d 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/PlatformUnresolvedProvider.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/PlatformUnresolvedProvider.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.inspections @@ -33,14 +22,20 @@ import org.jetbrains.kotlin.psi.KtNameReferenceExpression import java.util.* object PlatformUnresolvedProvider : KotlinIntentionActionFactoryWithDelegate() { - override fun getElementOfInterest(diagnostic: Diagnostic) = QuickFixUtil.getParentElementOfType(diagnostic, KtNameReferenceExpression::class.java) + override fun getElementOfInterest(diagnostic: Diagnostic) = + QuickFixUtil.getParentElementOfType(diagnostic, KtNameReferenceExpression::class.java) + override fun extractFixData(element: KtNameReferenceExpression, diagnostic: Diagnostic) = element.getReferencedName() - override fun createFixes(originalElementPointer: SmartPsiElementPointer, diagnostic: Diagnostic, quickFixDataFactory: () -> String?): List { + override fun createFixes( + originalElementPointer: SmartPsiElementPointer, + diagnostic: Diagnostic, + quickFixDataFactory: () -> String? + ): List { val result = ArrayList() originalElementPointer.element?.references?.filterIsInstance()?.firstOrNull()?.let { reference -> - UnresolvedReferenceQuickFixProvider.registerReferenceFixes(reference, object: QuickFixActionRegistrar { + UnresolvedReferenceQuickFixProvider.registerReferenceFixes(reference, object : QuickFixActionRegistrar { override fun register(action: IntentionAction) { result.add(QuickFixWithDelegateFactory(action.detectPriority()) { action }) } diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/RecursiveEqualsCallInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/RecursiveEqualsCallInspection.kt index e18311c7ccf..caf1468f474 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/RecursiveEqualsCallInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/RecursiveEqualsCallInspection.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.inspections @@ -48,15 +37,17 @@ class RecursiveEqualsCallInspection : AbstractKotlinInspection() { val containingFunctionDescriptor = getNonStrictParentOfType()?.descriptor as? FunctionDescriptor return calledFunctionDescriptor == containingFunctionDescriptor && - dispatchReceiver.classDescriptor == containingFunctionDescriptor.containingDeclaration && - argumentDescriptor == containingFunctionDescriptor.valueParameters.singleOrNull() + dispatchReceiver.classDescriptor == containingFunctionDescriptor.containingDeclaration && + argumentDescriptor == containingFunctionDescriptor.valueParameters.singleOrNull() } private fun KtExpression.reportRecursiveEquals(invert: Boolean = false) { - holder.registerProblem(this, - "Recursive equals call", - ProblemHighlightType.GENERIC_ERROR_OR_WARNING, - ReplaceWithReferentialEqualityFix(invert)) + holder.registerProblem( + this, + "Recursive equals call", + ProblemHighlightType.GENERIC_ERROR_OR_WARNING, + ReplaceWithReferentialEqualityFix(invert) + ) } override fun visitBinaryExpression(expr: KtBinaryExpression) { @@ -92,7 +83,7 @@ private class ReplaceWithReferentialEqualityFix(invert: Boolean) : LocalQuickFix is KtBinaryExpression -> { element.right to element } - is KtCallExpression -> with (element ){ + is KtCallExpression -> with(element) { valueArguments.first().getArgumentExpression() to getQualifiedExpressionForSelectorOrThis() } else -> return diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantLambdaArrowInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantLambdaArrowInspection.kt index 655cb840fa6..1ef7915785c 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantLambdaArrowInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantLambdaArrowInspection.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -122,5 +122,6 @@ private fun KtFunctionLiteral.removeArrow() { private fun KtCallExpression.findLambdaExpressionByOffset(offset: Int): KtLambdaExpression? = lambdaArguments.asSequence().mapNotNull(KtLambdaArgument::getLambdaExpression).firstOrNull { it.textOffset == offset } - ?: valueArguments.asSequence().mapNotNull(KtValueArgument::getArgumentExpression).firstOrNull { it.textOffset == offset } as? KtLambdaExpression + ?: valueArguments.asSequence().mapNotNull(KtValueArgument::getArgumentExpression) + .firstOrNull { it.textOffset == offset } as? KtLambdaExpression diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantModalityModifierInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantModalityModifierInspection.kt index 1a1f070fe90..c220b9280de 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantModalityModifierInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantModalityModifierInspection.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -21,11 +21,15 @@ class RedundantModalityModifierInspection : AbstractKotlinInspection(), CleanupL if (modalityModifierType != implicitModality) return@declarationVisitor - holder.registerProblem(modalityModifier, - "Redundant modality modifier", - ProblemHighlightType.LIKE_UNUSED_SYMBOL, - IntentionWrapper(RemoveModifierFix(declaration, implicitModality, isRedundant = true), - declaration.containingFile)) + holder.registerProblem( + modalityModifier, + "Redundant modality modifier", + ProblemHighlightType.LIKE_UNUSED_SYMBOL, + IntentionWrapper( + RemoveModifierFix(declaration, implicitModality, isRedundant = true), + declaration.containingFile + ) + ) } } } diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantRequireNotNullCallInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantRequireNotNullCallInspection.kt index b217d062903..1b0429f934e 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantRequireNotNullCallInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantRequireNotNullCallInspection.kt @@ -72,7 +72,7 @@ private class RemoveRequireNotNullCallFix(private val functionName: String) : Lo val argument = callExpression.valueArguments.firstOrNull()?.getArgumentExpression() ?: return val target = callExpression.getQualifiedExpressionForSelector() ?: callExpression if (callExpression.isUsedAsExpression(callExpression.analyze(BodyResolveMode.PARTIAL_WITH_CFA))) { - target.replace(argument) + target.replace(argument) } else { target.delete() } diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantSamConstructorInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantSamConstructorInspection.kt index 42c442d5180..5974cff9828 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantSamConstructorInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantSamConstructorInspection.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -106,7 +106,7 @@ class RedundantSamConstructorInspection : AbstractKotlinInspection() { companion object { fun replaceSamConstructorCall(callExpression: KtCallExpression): KtLambdaExpression { val functionalArgument = callExpression.samConstructorValueArgument()?.getArgumentExpression() - ?: throw AssertionError("SAM-constructor should have a FunctionLiteralExpression as single argument: ${callExpression.getElementTextWithContext()}") + ?: throw AssertionError("SAM-constructor should have a FunctionLiteralExpression as single argument: ${callExpression.getElementTextWithContext()}") return callExpression.getQualifiedExpressionForSelectorOrThis().replace(functionalArgument) as KtLambdaExpression } @@ -190,7 +190,8 @@ class RedundantSamConstructorInspection : AbstractKotlinInspection() { val originalFunctionDescriptor = functionResolvedCall.resultingDescriptor.original as? FunctionDescriptor ?: return emptyList() val containingClass = originalFunctionDescriptor.containingDeclaration as? ClassDescriptor ?: return emptyList() - val syntheticScopes = functionCall.getResolutionFacade().getFrontendService(SyntheticScopes::class.java).forceEnableSamAdapters() + val syntheticScopes = + functionCall.getResolutionFacade().getFrontendService(SyntheticScopes::class.java).forceEnableSamAdapters() // SAM adapters for static functions val contributedFunctions = syntheticScopes.collectSyntheticStaticFunctions(containingClass.staticScope) diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantSemicolonInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantSemicolonInspection.kt index 3fc3e88e1ef..6c7f92fc0ba 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantSemicolonInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantSemicolonInspection.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.inspections @@ -65,10 +54,12 @@ class RedundantSemicolonInspection : AbstractKotlinInspection(), CleanupLocalIns if (semicolon.parent is KtEnumEntry) return false - (semicolon.parent.parent as? KtClass)?.let { - if (it.isEnum() && it.getChildrenOfType().isEmpty()) { - if (semicolon.prevLeaf { it !is PsiWhiteSpace && it !is PsiComment && !it.isLineBreak() }?.node?.elementType == KtTokens.LBRACE - && it.declarations.isNotEmpty() + (semicolon.parent.parent as? KtClass)?.let { clazz -> + if (clazz.isEnum() && clazz.getChildrenOfType().isEmpty()) { + if (semicolon.prevLeaf { + it !is PsiWhiteSpace && it !is PsiComment && !it.isLineBreak() + }?.node?.elementType == KtTokens.LBRACE && + clazz.declarations.isNotEmpty() ) { //first semicolon in enum with no entries, but with some declarations return false diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantSuspendModifierInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantSuspendModifierInspection.kt index 606adc6406d..0d720ddb4d9 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantSuspendModifierInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantSuspendModifierInspection.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -39,11 +39,15 @@ class RedundantSuspendModifierInspection : AbstractKotlinInspection() { return } - holder.registerProblem(suspendModifier, - "Redundant 'suspend' modifier", - ProblemHighlightType.LIKE_UNUSED_SYMBOL, - IntentionWrapper(RemoveModifierFix(function, KtTokens.SUSPEND_KEYWORD, isRedundant = true), - function.containingFile)) + holder.registerProblem( + suspendModifier, + "Redundant 'suspend' modifier", + ProblemHighlightType.LIKE_UNUSED_SYMBOL, + IntentionWrapper( + RemoveModifierFix(function, KtTokens.SUSPEND_KEYWORD, isRedundant = true), + function.containingFile + ) + ) }) } } diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/RemoveAnnotationFix.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/RemoveAnnotationFix.kt index 4e7189f888f..d3dc0ffee0f 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/RemoveAnnotationFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/RemoveAnnotationFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.inspections @@ -24,8 +13,8 @@ import org.jetbrains.kotlin.idea.quickfix.KotlinSingleIntentionActionFactory import org.jetbrains.kotlin.psi.KtAnnotationEntry import org.jetbrains.kotlin.psi.KtFile -class RemoveAnnotationFix(private val name: String, annotationEntry: KtAnnotationEntry) - : KotlinQuickFixAction(annotationEntry) { +class RemoveAnnotationFix(private val name: String, annotationEntry: KtAnnotationEntry) : + KotlinQuickFixAction(annotationEntry) { override fun getText() = name diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceArrayOfWithLiteralInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceArrayOfWithLiteralInspection.kt index 9d85329df59..caeb0afe5ef 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceArrayOfWithLiteralInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceArrayOfWithLiteralInspection.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -20,37 +20,35 @@ import org.jetbrains.kotlin.psi.psiUtil.getParentOfType class ReplaceArrayOfWithLiteralInspection : AbstractKotlinInspection() { - override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { - return callExpressionVisitor(fun(expression) { - if (!expression.languageVersionSettings.supportsFeature(ArrayLiteralsInAnnotations) && - !ApplicationManager.getApplication().isUnitTestMode) return + override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor = callExpressionVisitor(fun(expression) { + if (!expression.languageVersionSettings.supportsFeature(ArrayLiteralsInAnnotations) && + !ApplicationManager.getApplication().isUnitTestMode + ) return - val calleeExpression = expression.calleeExpression as? KtNameReferenceExpression ?: return - if (!expression.isArrayOfMethod()) return + val calleeExpression = expression.calleeExpression as? KtNameReferenceExpression ?: return + if (!expression.isArrayOfMethod()) return - val parent = expression.parent - when (parent) { - is KtValueArgument -> { - if (parent.parent.parent !is KtAnnotationEntry) return - if (parent.getSpreadElement() != null && !parent.isNamed()) return - } - is KtParameter -> { - val constructor = parent.parent.parent as? KtPrimaryConstructor ?: return - val containingClass = constructor.getContainingClassOrObject() - if (!containingClass.isAnnotation()) return - } - else -> return + when (val parent = expression.parent) { + is KtValueArgument -> { + if (parent.parent.parent !is KtAnnotationEntry) return + if (parent.getSpreadElement() != null && !parent.isNamed()) return } + is KtParameter -> { + val constructor = parent.parent.parent as? KtPrimaryConstructor ?: return + val containingClass = constructor.getContainingClassOrObject() + if (!containingClass.isAnnotation()) return + } + else -> return + } - val calleeName = calleeExpression.getReferencedName() - holder.registerProblem( - calleeExpression, - "'$calleeName' call should be replaced with array literal [...]", - ProblemHighlightType.GENERIC_ERROR_OR_WARNING, - ReplaceWithArrayLiteralFix() - ) - }) - } + val calleeName = calleeExpression.getReferencedName() + holder.registerProblem( + calleeExpression, + "'$calleeName' call should be replaced with array literal [...]", + ProblemHighlightType.GENERIC_ERROR_OR_WARNING, + ReplaceWithArrayLiteralFix() + ) + }) private class ReplaceWithArrayLiteralFix : LocalQuickFix { override fun getFamilyName() = "Replace with [...]" diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceGuardClauseWithFunctionCallInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceGuardClauseWithFunctionCallInspection.kt index c7754af935b..24bac07597d 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceGuardClauseWithFunctionCallInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceGuardClauseWithFunctionCallInspection.kt @@ -1,6 +1,6 @@ /* - * Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license - * that can be found in the license/LICENSE.txt file. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.inspections @@ -106,10 +106,10 @@ class ReplaceGuardClauseWithFunctionCallInspection : AbstractApplicabilityBasedI else -> return } commentSaver.restore(replaced) - editor?.caretModel?.moveToOffset(replaced.startOffset) + editor?.caretModel?.moveToOffset(replaced.startOffset) ShortenReferences.DEFAULT.process(replaced) } - + private fun KtIfExpression.replaceWith(newExpression: KtExpression, psiFactory: KtPsiFactory): KtExpression { val parent = parent val elseBranch = `else` diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceToWithInfixFormInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceToWithInfixFormInspection.kt index c3005c31040..49e9787c79a 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceToWithInfixFormInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceToWithInfixFormInspection.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -50,7 +50,11 @@ class ReplaceToWithInfixFormQuickfix : LocalQuickFix { override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val element = descriptor.psiElement as KtDotQualifiedExpression - element.replace(KtPsiFactory(element).createExpressionByPattern("$0 to $1", element.receiverExpression, - element.callExpression?.valueArguments?.get(0)?.getArgumentExpression() ?: return)) + element.replace( + KtPsiFactory(element).createExpressionByPattern( + "$0 to $1", element.receiverExpression, + element.callExpression?.valueArguments?.get(0)?.getArgumentExpression() ?: return + ) + ) } } \ No newline at end of file diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/ScopeFunctionConversionInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/ScopeFunctionConversionInspection.kt index 8280ec81b75..28a6b061561 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/ScopeFunctionConversionInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/ScopeFunctionConversionInspection.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -228,7 +228,8 @@ class ConvertScopeFunctionToParameter(counterpartName: String) : ConvertScopeFun override fun visitThisExpression(expression: KtThisExpression) { val resolvedCall = expression.getResolvedCall(bindingContext) ?: return if (resolvedCall.resultingDescriptor == lambdaDispatchReceiver || - resolvedCall.resultingDescriptor == lambdaExtensionReceiver) { + resolvedCall.resultingDescriptor == lambdaExtensionReceiver + ) { replacements.add(expression) { createExpression(parameterName) } } } diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/SelfAssignmentInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/SelfAssignmentInspection.kt index 9d77395e0e9..bf8c6a891c2 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/SelfAssignmentInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/SelfAssignmentInspection.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -42,15 +42,20 @@ class SelfAssignmentInspection : AbstractKotlinInspection(), CleanupLocalInspect if (rightCallee.accessors.any { !it.isDefault }) return } - if (left.receiverDeclarationDescriptor(leftResolvedCall, context) != - right.receiverDeclarationDescriptor(rightResolvedCall, context)) { + if (left.receiverDeclarationDescriptor(leftResolvedCall, context) != right.receiverDeclarationDescriptor( + rightResolvedCall, + context + ) + ) { return } - holder.registerProblem(right, - "Variable '${rightCallee.name}' is assigned to itself", - ProblemHighlightType.GENERIC_ERROR_OR_WARNING, - RemoveSelfAssignmentFix()) + holder.registerProblem( + right, + "Variable '${rightCallee.name}' is assigned to itself", + ProblemHighlightType.GENERIC_ERROR_OR_WARNING, + RemoveSelfAssignmentFix() + ) }) } @@ -71,7 +76,7 @@ class SelfAssignmentInspection : AbstractKotlinInspection(), CleanupLocalInspect if (thisExpression != null) { return thisExpression.getResolvedCall(context)?.resultingDescriptor?.containingDeclaration } - val implicitReceiver = with (resolvedCall) { dispatchReceiver ?: extensionReceiver } as? ImplicitReceiver + val implicitReceiver = with(resolvedCall) { dispatchReceiver ?: extensionReceiver } as? ImplicitReceiver return implicitReceiver?.declarationDescriptor } } diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/SimplifyWhenWithBooleanConstantConditionInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/SimplifyWhenWithBooleanConstantConditionInspection.kt index 934ae9b574d..0e567da6176 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/SimplifyWhenWithBooleanConstantConditionInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/SimplifyWhenWithBooleanConstantConditionInspection.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -24,10 +24,12 @@ class SimplifyWhenWithBooleanConstantConditionInspection : AbstractKotlinInspect if (expression.subjectExpression != null) return if (expression.entries.none { it.isTrueConstantCondition() || it.isFalseConstantCondition() }) return - holder.registerProblem(expression.whenKeyword, - "This 'when' is simplifiable", - ProblemHighlightType.GENERIC_ERROR_OR_WARNING, - SimplifyWhenFix()) + holder.registerProblem( + expression.whenKeyword, + "This 'when' is simplifiable", + ProblemHighlightType.GENERIC_ERROR_OR_WARNING, + SimplifyWhenFix() + ) }) } } @@ -57,8 +59,7 @@ private fun KtWhenExpression.deleteFalseEntries(usedAsExpression: Boolean) { val entries = entries if (entries.isEmpty() && !usedAsExpression) { delete() - } - else if (entries.singleOrNull()?.isElse == true) { + } else if (entries.singleOrNull()?.isElse == true) { elseExpression?.let { replaceWithBranch(it, usedAsExpression) } } } @@ -72,8 +73,7 @@ private fun KtWhenExpression.replaceTrueEntry(usedAsExpression: Boolean, closeBr if (trueIndex == 0) { replaceWithBranch(expression, usedAsExpression) - } - else { + } else { val elseEntry = factory.createWhenEntry("else -> ${expression.text}") for (entry in entries.subList(trueIndex, entries.size)) { entry.delete() @@ -83,7 +83,7 @@ private fun KtWhenExpression.replaceTrueEntry(usedAsExpression: Boolean, closeBr } private fun KtWhenEntry.isTrueConstantCondition(): Boolean = - (conditions.singleOrNull() as? KtWhenConditionWithExpression)?.expression.isTrueConstant() + (conditions.singleOrNull() as? KtWhenConditionWithExpression)?.expression.isTrueConstant() private fun KtWhenEntry.isFalseConstantCondition(): Boolean = - (conditions.singleOrNull() as? KtWhenConditionWithExpression)?.expression.isFalseConstant() \ No newline at end of file + (conditions.singleOrNull() as? KtWhenConditionWithExpression)?.expression.isFalseConstant() \ No newline at end of file diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/UnsafeCastFromDynamicInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/UnsafeCastFromDynamicInspection.kt index 9a8d9ed4216..e1168a9a02e 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/UnsafeCastFromDynamicInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/UnsafeCastFromDynamicInspection.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -21,8 +21,8 @@ import org.jetbrains.kotlin.types.TypeUtils import org.jetbrains.kotlin.types.isDynamic class UnsafeCastFromDynamicInspection : AbstractKotlinInspection() { - override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor { - return expressionVisitor(fun(expression) { + override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor = + expressionVisitor(fun(expression) { val context = expression.analyze(BodyResolveMode.PARTIAL) val expectedType = context[BindingContext.EXPECTED_EXPRESSION_TYPE, expression] ?: return val actualType = expression.getType(context) ?: return @@ -32,10 +32,10 @@ class UnsafeCastFromDynamicInspection : AbstractKotlinInspection() { expression, "Implicit (unsafe) cast from dynamic to $expectedType", ProblemHighlightType.GENERIC_ERROR_OR_WARNING, - CastExplicitlyFix(expectedType)) + CastExplicitlyFix(expectedType) + ) } }) - } } private class CastExplicitlyFix(private val type: KotlinType) : LocalQuickFix { diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/UnusedEqualsInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/UnusedEqualsInspection.kt index 0cee8460b2f..d56f7291cd8 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/UnusedEqualsInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/UnusedEqualsInspection.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.inspections @@ -34,9 +23,11 @@ class UnusedEqualsInspection : AbstractKotlinInspection() { private fun reportIfNotUsedAsExpression(expression: KtExpression, target: KtExpression) { val context = expression.analyze() if (!expression.isUsedAsExpression(context)) { - holder.registerProblem(target, - "Unused equals expression", - ProblemHighlightType.LIKE_UNUSED_SYMBOL) + holder.registerProblem( + target, + "Unused equals expression", + ProblemHighlightType.LIKE_UNUSED_SYMBOL + ) } } @@ -44,7 +35,8 @@ class UnusedEqualsInspection : AbstractKotlinInspection() { override fun visitBinaryExpression(expression: KtBinaryExpression) { super.visitBinaryExpression(expression) if (expression.operationToken == KtTokens.EQEQ && - (expression.parent is KtBlockExpression || expression.parent.parent is KtIfExpression)) { + (expression.parent is KtBlockExpression || expression.parent.parent is KtIfExpression) + ) { reportIfNotUsedAsExpression(expression, expression.operationReference) } } diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/UnusedLambdaExpressionBodyInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/UnusedLambdaExpressionBodyInspection.kt index 08edaa9a0b2..19330804e9e 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/UnusedLambdaExpressionBodyInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/UnusedLambdaExpressionBodyInspection.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -15,11 +15,9 @@ import com.intellij.psi.PsiFile import org.jetbrains.kotlin.builtins.isFunctionType import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.idea.caches.resolve.analyze -import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtFunction import org.jetbrains.kotlin.psi.KtLambdaExpression import org.jetbrains.kotlin.psi.callExpressionVisitor -import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.calls.tower.NewResolvedCallImpl @@ -49,9 +47,11 @@ class UnusedLambdaExpressionBodyInspection : AbstractKotlinInspection() { return } - holder.registerProblem(expression, - "Unused return value of a function with lambda expression body", - RemoveEqTokenFromFunctionDeclarationFix(function)) + holder.registerProblem( + expression, + "Unused return value of a function with lambda expression body", + RemoveEqTokenFromFunctionDeclarationFix(function) + ) }) } diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/UnusedSymbolInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/UnusedSymbolInspection.kt index 723e7a91cba..3bd952dfa79 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/UnusedSymbolInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/UnusedSymbolInspection.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -93,7 +93,7 @@ class UnusedSymbolInspection : AbstractKotlinInspection() { private val KOTLIN_ADDITIONAL_ANNOTATIONS = listOf("kotlin.test.*") private val KOTLIN_BUILTIN_ENUM_FUNCTIONS = listOf(FqName("kotlin.enumValues"), FqName("kotlin.enumValueOf")) - + private val ENUM_STATIC_METHODS = listOf("values", "valueOf") private fun KtDeclaration.hasKotlinAdditionalAnnotation() = @@ -210,7 +210,9 @@ class UnusedSymbolInspection : AbstractKotlinInspection() { if (declaration is KtSecondaryConstructor && declaration.containingClass()?.isEnum() == true) return if (declaration.hasModifier(KtTokens.OVERRIDE_KEYWORD)) return if (declaration is KtProperty && declaration.isLocal) return - if (declaration is KtParameter && (declaration.getParent().parent !is KtPrimaryConstructor || !declaration.hasValOrVar())) return + if (declaration is KtParameter && + (declaration.getParent().parent !is KtPrimaryConstructor || !declaration.hasValOrVar()) + ) return // More expensive, resolve-based checks val descriptor = declaration.resolveToDescriptorIfAny() ?: return @@ -405,7 +407,7 @@ class UnusedSymbolInspection : AbstractKotlinInspection() { return referenceUsed || checkPrivateDeclaration(declaration, descriptor) } - + private fun hasBuiltInEnumFunctionReference(reference: PsiReference): Boolean { return when (val parent = reference.element.getParentOfTypes( true, diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/UseExpressionBodyInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/UseExpressionBodyInspection.kt index 979029ca049..b825aec7040 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/UseExpressionBodyInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/UseExpressionBodyInspection.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -114,7 +114,7 @@ class UseExpressionBodyInspection(private val convertEmptyToUnit: Boolean) : Abs return statement } - //TODO: IMO this is not good code, there should be a way to detect that KtExpression does not have value + //TODO: IMO this is not good code, there should be a way to detect that KtExpression does not have value is KtDeclaration, is KtLoopExpression -> return null else -> { diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/WrapUnaryOperatorInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/WrapUnaryOperatorInspection.kt index 7205b405917..b59e8b31ec7 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/WrapUnaryOperatorInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/WrapUnaryOperatorInspection.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -29,11 +29,14 @@ class WrapUnaryOperatorInspection : AbstractKotlinInspection() { if (baseExpression is KtDotQualifiedExpression) { val receiverExpression = baseExpression.receiverExpression if (receiverExpression is KtConstantExpression && - receiverExpression.node.elementType in numberTypes) { - holder.registerProblem(expression, - "Wrap unary operator and value with ()", - ProblemHighlightType.GENERIC_ERROR_OR_WARNING, - WrapUnaryOperatorQuickfix()) + receiverExpression.node.elementType in numberTypes + ) { + holder.registerProblem( + expression, + "Wrap unary operator and value with ()", + ProblemHighlightType.GENERIC_ERROR_OR_WARNING, + WrapUnaryOperatorQuickfix() + ) } } } @@ -51,7 +54,11 @@ class WrapUnaryOperatorInspection : AbstractKotlinInspection() { val expression = descriptor.psiElement as? KtPrefixExpression ?: return val dotQualifiedExpression = expression.baseExpression as? KtDotQualifiedExpression ?: return val factory = KtPsiFactory(project) - val newReceiver = factory.createExpressionByPattern("($0$1)", expression.operationReference.text, dotQualifiedExpression.getLeftMostReceiverExpression()) + val newReceiver = factory.createExpressionByPattern( + "($0$1)", + expression.operationReference.text, + dotQualifiedExpression.getLeftMostReceiverExpression() + ) val newExpression = dotQualifiedExpression.replaceFirstReceiver(factory, newReceiver) expression.replace(newExpression) } diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/branchedTransformations/IfThenToElvisInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/branchedTransformations/IfThenToElvisInspection.kt index f6a9edc2978..3ccc35f362f 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/branchedTransformations/IfThenToElvisInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/branchedTransformations/IfThenToElvisInspection.kt @@ -87,7 +87,9 @@ class IfThenToElvisInspection( fun isApplicableTo(element: KtIfExpression, expressionShouldBeStable: Boolean): Boolean { val ifThenToSelectData = element.buildSelectTransformationData() ?: return false - if (expressionShouldBeStable && !ifThenToSelectData.receiverExpression.isStableSimpleExpression(ifThenToSelectData.context)) return false + if (expressionShouldBeStable && + !ifThenToSelectData.receiverExpression.isStableSimpleExpression(ifThenToSelectData.context) + ) return false val type = element.getType(ifThenToSelectData.context) ?: return false if (KotlinBuiltIns.isUnit(type)) return false diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/branchedTransformations/IfThenToSafeAccessInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/branchedTransformations/IfThenToSafeAccessInspection.kt index 02637e138d2..4d22ca691ae 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/branchedTransformations/IfThenToSafeAccessInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/branchedTransformations/IfThenToSafeAccessInspection.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.inspections.branchedTransformations @@ -87,7 +76,9 @@ class IfThenToSafeAccessInspection : AbstractApplicabilityBasedInspection(true) - ?: throw IllegalStateException("Can't find declaration") + ?: throw IllegalStateException("Can't find declaration") declaration.addBefore(KDocElementFactory(project).createKDocFromText("/**\n*\n*/\n"), declaration.firstChild) diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/AbstractProcessableUsageInfo.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/AbstractProcessableUsageInfo.kt index 3e2ff359302..a3d86ed742b 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/AbstractProcessableUsageInfo.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/AbstractProcessableUsageInfo.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions @@ -20,7 +9,7 @@ import com.intellij.psi.PsiElement import com.intellij.usageView.UsageInfo import org.jetbrains.kotlin.psi.KtElement -abstract class AbstractProcessableUsageInfo(element: T) : UsageInfo(element) { +abstract class AbstractProcessableUsageInfo(element: T) : UsageInfo(element) { @Suppress("UNCHECKED_CAST") override fun getElement() = super.getElement() as T? diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/AddJvmOverloadsIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/AddJvmOverloadsIntention.kt index 40292a9bf3f..80e02ef0bff 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/AddJvmOverloadsIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/AddJvmOverloadsIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions @@ -22,15 +11,15 @@ import org.jetbrains.kotlin.idea.project.TargetPlatformDetector import org.jetbrains.kotlin.idea.util.addAnnotation import org.jetbrains.kotlin.idea.util.findAnnotation import org.jetbrains.kotlin.name.FqName +import org.jetbrains.kotlin.platform.jvm.isJvm import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.startOffset -import org.jetbrains.kotlin.platform.jvm.isJvm private val annotationFqName = FqName("kotlin.jvm.JvmOverloads") class AddJvmOverloadsIntention : SelfTargetingIntention( - KtModifierListOwner::class.java, "Add '@JvmOverloads' annotation" + KtModifierListOwner::class.java, "Add '@JvmOverloads' annotation" ), LowPriorityAction { override fun isApplicableTo(element: KtModifierListOwner, caretOffset: Int): Boolean { @@ -70,8 +59,8 @@ class AddJvmOverloadsIntention : SelfTargetingIntention( text = "Add '@JvmOverloads' annotation to $targetName" return TargetPlatformDetector.getPlatform(element.containingKtFile).isJvm() - && parameters.any { it.hasDefaultValue() } - && element.findAnnotation(annotationFqName) == null + && parameters.any { it.hasDefaultValue() } + && element.findAnnotation(annotationFqName) == null } override fun applyTo(element: KtModifierListOwner, editor: Editor?) { @@ -80,8 +69,7 @@ class AddJvmOverloadsIntention : SelfTargetingIntention( element.addBefore(KtPsiFactory(element).createConstructorKeyword(), element.valueParameterList) } element.addAnnotation(annotationFqName, whiteSpaceText = " ") - } - else { + } else { element.addAnnotation(annotationFqName) } } diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/AddJvmStaticIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/AddJvmStaticIntention.kt index 011e20efae5..66137ba68ae 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/AddJvmStaticIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/AddJvmStaticIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions @@ -41,8 +30,8 @@ import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject class AddJvmStaticIntention : SelfTargetingRangeIntention( - KtNamedDeclaration::class.java, - "Add '@JvmStatic' annotation" + KtNamedDeclaration::class.java, + "Add '@JvmStatic' annotation" ), LowPriorityAction { private val JvmStaticFqName = FqName("kotlin.jvm.JvmStatic") private val JvmFieldFqName = FqName("kotlin.jvm.JvmField") @@ -74,23 +63,23 @@ class AddJvmStaticIntention : SelfTargetingRangeIntention( val project = element.project val expressionsToReplaceWithQualifier = - project.runSynchronouslyWithProgress("Looking for usages in Java files...", true) { - runReadAction { - val searchScope = element.useScope.restrictByFileType(JavaFileType.INSTANCE) - ReferencesSearch - .search(element, searchScope) - .mapNotNull { - val refExpr = it.element as? PsiReferenceExpression ?: return@mapNotNull null - if ((refExpr.resolve() as? KtLightElement<*, *>)?.kotlinOrigin != element) return@mapNotNull null - val qualifierExpr = refExpr.qualifierExpression as? PsiReferenceExpression ?: return@mapNotNull null - if (qualifierExpr.qualifierExpression == null) return@mapNotNull null - val instanceField = qualifierExpr.resolve() as? KtLightField ?: return@mapNotNull null - if (instanceField.name != instanceFieldName) return@mapNotNull null - if ((instanceField.containingClass as? KtLightClass)?.kotlinOrigin != instanceFieldContainingClass) return@mapNotNull null - qualifierExpr - } - } - } ?: return + project.runSynchronouslyWithProgress("Looking for usages in Java files...", true) { + runReadAction { + val searchScope = element.useScope.restrictByFileType(JavaFileType.INSTANCE) + ReferencesSearch + .search(element, searchScope) + .mapNotNull { + val refExpr = it.element as? PsiReferenceExpression ?: return@mapNotNull null + if ((refExpr.resolve() as? KtLightElement<*, *>)?.kotlinOrigin != element) return@mapNotNull null + val qualifierExpr = refExpr.qualifierExpression as? PsiReferenceExpression ?: return@mapNotNull null + if (qualifierExpr.qualifierExpression == null) return@mapNotNull null + val instanceField = qualifierExpr.resolve() as? KtLightField ?: return@mapNotNull null + if (instanceField.name != instanceFieldName) return@mapNotNull null + if ((instanceField.containingClass as? KtLightClass)?.kotlinOrigin != instanceFieldContainingClass) return@mapNotNull null + qualifierExpr + } + } + } ?: return runWriteAction { element.addAnnotation(JvmStaticFqName) diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/AddMissingDestructuringIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/AddMissingDestructuringIntention.kt index 01693b8cd0b..9a44704c2e9 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/AddMissingDestructuringIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/AddMissingDestructuringIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions @@ -26,7 +15,8 @@ import org.jetbrains.kotlin.psi.KtDestructuringDeclaration import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.createDestructuringDeclarationByPattern -class AddMissingDestructuringIntention : SelfTargetingIntention(KtDestructuringDeclaration::class.java, "Add missing component") { +class AddMissingDestructuringIntention : + SelfTargetingIntention(KtDestructuringDeclaration::class.java, "Add missing component") { override fun isApplicableTo(element: KtDestructuringDeclaration, caretOffset: Int): Boolean { val entriesCount = element.entries.size @@ -43,18 +33,19 @@ class AddMissingDestructuringIntention : SelfTargetingIntention( - KtCallableDeclaration::class.java, "Make open" + KtCallableDeclaration::class.java, "Make open" ), LowPriorityAction { override fun isApplicableTo(element: KtCallableDeclaration, caretOffset: Int): Boolean { @@ -35,16 +24,17 @@ class AddOpenModifierIntention : SelfTargetingIntention( } if (element.hasModifier(KtTokens.OPEN_KEYWORD) || element.hasModifier(KtTokens.ABSTRACT_KEYWORD) - || element.hasModifier(KtTokens.PRIVATE_KEYWORD)) { + || element.hasModifier(KtTokens.PRIVATE_KEYWORD) + ) { return false } val implicitModality = element.implicitModality() if (implicitModality == KtTokens.OPEN_KEYWORD || implicitModality == KtTokens.ABSTRACT_KEYWORD) return false val ktClassOrObject = element.containingClassOrObject ?: return false return ktClassOrObject.hasModifier(KtTokens.ENUM_KEYWORD) - || ktClassOrObject.hasModifier(KtTokens.OPEN_KEYWORD) - || ktClassOrObject.hasModifier(KtTokens.ABSTRACT_KEYWORD) - || ktClassOrObject.hasModifier(KtTokens.SEALED_KEYWORD) + || ktClassOrObject.hasModifier(KtTokens.OPEN_KEYWORD) + || ktClassOrObject.hasModifier(KtTokens.ABSTRACT_KEYWORD) + || ktClassOrObject.hasModifier(KtTokens.SEALED_KEYWORD) } override fun applyTo(element: KtCallableDeclaration, editor: Editor?) { diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/AnonymousFunctionToLambdaIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/AnonymousFunctionToLambdaIntention.kt index 4c98b54f2ce..b3b8d61f759 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/AnonymousFunctionToLambdaIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/AnonymousFunctionToLambdaIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions @@ -32,9 +21,9 @@ import org.jetbrains.kotlin.resolve.calls.callUtil.getCalleeExpressionIfAny import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstance class AnonymousFunctionToLambdaIntention : SelfTargetingRangeIntention( - KtNamedFunction::class.java, - "Convert to lambda expression", - "Convert anonymous function to lambda expression" + KtNamedFunction::class.java, + "Convert to lambda expression", + "Convert anonymous function to lambda expression" ) { override fun applicabilityRange(element: KtNamedFunction): TextRange? { if (element.name != null) return null @@ -60,7 +49,8 @@ class AnonymousFunctionToLambdaIntention : SelfTargetingRangeIntention 1 || parameters.any { parameter -> ReferencesSearch.search(parameter, LocalSearchScope(body)).any() } + val needParameters = + parameters.count() > 1 || parameters.any { parameter -> ReferencesSearch.search(parameter, LocalSearchScope(body)).any() } if (needParameters) { parameters.forEachIndexed { index, parameter -> if (index > 0) { @@ -74,8 +64,7 @@ class AnonymousFunctionToLambdaIntention : SelfTargetingRangeIntention( - lookupItems: Collection, - defaultItem: T, - private val advertisementText: String? = null + lookupItems: Collection, + defaultItem: T, + private val advertisementText: String? = null ) : Expression() { protected abstract fun getLookupString(element: T): String protected abstract fun getResult(element: T): String @@ -60,9 +49,9 @@ abstract class ChooseValueExpression( } class ChooseStringExpression( - suggestions: Collection, - default: String = suggestions.first(), - advertisementText: String? = null + suggestions: Collection, + default: String = suggestions.first(), + advertisementText: String? = null ) : ChooseValueExpression(suggestions, default, advertisementText) { override fun getLookupString(element: String) = element override fun getResult(element: String) = element diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertArrayParameterToVarargIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertArrayParameterToVarargIntention.kt index ad957bb8d30..8f1f2c7b0f3 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertArrayParameterToVarargIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertArrayParameterToVarargIntention.kt @@ -1,5 +1,5 @@ /* - * Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -53,8 +53,8 @@ class ConvertArrayParameterToVarargIntention : SelfTargetingIntention() ?: return val type = element.descriptor?.type ?: return val newType = KotlinBuiltIns.getPrimitiveArrayElementType(type)?.typeName?.asString() - ?: typeReference.typeElement?.typeArgumentsAsTypes?.firstOrNull()?.text - ?: return + ?: typeReference.typeElement?.typeArgumentsAsTypes?.firstOrNull()?.text + ?: return typeReference.replace(KtPsiFactory(element).createType(newType)) element.addModifier(KtTokens.VARARG_KEYWORD) } diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertBinaryExpressionWithDemorgansLawIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertBinaryExpressionWithDemorgansLawIntention.kt index 813601d682b..b90b296187b 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertBinaryExpressionWithDemorgansLawIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertBinaryExpressionWithDemorgansLawIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions @@ -22,7 +11,8 @@ import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf import java.util.* -class ConvertBinaryExpressionWithDemorgansLawIntention : SelfTargetingOffsetIndependentIntention(KtBinaryExpression::class.java, "DeMorgan Law") { +class ConvertBinaryExpressionWithDemorgansLawIntention : + SelfTargetingOffsetIndependentIntention(KtBinaryExpression::class.java, "DeMorgan Law") { override fun isApplicableTo(element: KtBinaryExpression): Boolean { val expr = element.parentsWithSelf.takeWhile { it is KtBinaryExpression }.last() as KtBinaryExpression @@ -56,7 +46,7 @@ class ConvertBinaryExpressionWithDemorgansLawIntention : SelfTargetingOffsetInde val grandParentPrefix = expr.parent.parent as? KtPrefixExpression val negated = expr.parent is KtParenthesizedExpression && - grandParentPrefix?.operationReference?.getReferencedNameElementType() == KtTokens.EXCL + grandParentPrefix?.operationReference?.getReferencedNameElementType() == KtTokens.EXCL if (negated) { grandParentPrefix?.replace(newExpression) } else { diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertFunctionTypeParameterToReceiverIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertFunctionTypeParameterToReceiverIntention.kt index fd1f39c2525..c3e3999eea2 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertFunctionTypeParameterToReceiverIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertFunctionTypeParameterToReceiverIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions @@ -55,8 +44,8 @@ import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.KotlinType class ConvertFunctionTypeParameterToReceiverIntention : SelfTargetingRangeIntention( - KtTypeReference::class.java, - "Convert function type parameter to receiver" + KtTypeReference::class.java, + "Convert function type parameter to receiver" ) { class FunctionDefinitionInfo(element: KtFunction) : AbstractProcessableUsageInfo(element) { override fun process(data: ConversionData, elementsToShorten: MutableList) { @@ -76,25 +65,27 @@ class ConvertFunctionTypeParameterToReceiverIntention : SelfTargetingRangeIntent val callExpression = element ?: return val argumentList = callExpression.valueArgumentList ?: return val expressionToMove = argumentList.arguments.getOrNull(data.typeParameterIndex)?.getArgumentExpression() ?: return - val callWithReceiver = KtPsiFactory(callExpression).createExpressionByPattern("$0.$1", expressionToMove, callExpression) as KtQualifiedExpression + val callWithReceiver = + KtPsiFactory(callExpression).createExpressionByPattern("$0.$1", expressionToMove, callExpression) as KtQualifiedExpression (callWithReceiver.selectorExpression as KtCallExpression).valueArgumentList!!.removeArgument(data.typeParameterIndex) callExpression.replace(callWithReceiver) } } - class InternalReferencePassInfo(element: KtSimpleNameExpression) : AbstractProcessableUsageInfo(element) { + class InternalReferencePassInfo(element: KtSimpleNameExpression) : + AbstractProcessableUsageInfo(element) { override fun process(data: ConversionData, elementsToShorten: MutableList) { val expression = element ?: return val lambdaType = data.lambdaType val validator = CollectingNameValidator() val parameterNames = lambdaType.arguments - .dropLast(1) - .map { KotlinNameSuggester.suggestNamesByType(it.type, validator, "p").first() } + .dropLast(1) + .map { KotlinNameSuggester.suggestNamesByType(it.type, validator, "p").first() } val receiver = parameterNames.getOrNull(data.typeParameterIndex) ?: return val arguments = parameterNames.filter { it != receiver } val adapterLambda = KtPsiFactory(expression).createLambdaExpression( - parameterNames.joinToString(), - "$receiver.${expression.text}(${arguments.joinToString()})" + parameterNames.joinToString(), + "$receiver.${expression.text}(${arguments.joinToString()})" ) expression.replaced(adapterLambda).let { it.moveFunctionLiteralOutsideParenthesesIfPossible() @@ -141,10 +132,11 @@ class ConvertFunctionTypeParameterToReceiverIntention : SelfTargetingRangeIntent } val parameterNameValidator = CollectingNameValidator( - if (expression !is KtCallableReferenceExpression) listOf(calleeText) else emptyList() + if (expression !is KtCallableReferenceExpression) listOf(calleeText) else emptyList() ) val parameterNamesWithReceiver = originalParameterTypes.mapIndexed { i, type -> - if (i != data.typeParameterIndex) KotlinNameSuggester.suggestNamesByType(type, parameterNameValidator, "p").first() else "this" + if (i != data.typeParameterIndex) KotlinNameSuggester.suggestNamesByType(type, parameterNameValidator, "p") + .first() else "this" } val parameterNames = parameterNamesWithReceiver.filter { it != "this" } @@ -173,7 +165,7 @@ class ConvertFunctionTypeParameterToReceiverIntention : SelfTargetingRangeIntent } private inner class Converter( - private val data: ConversionData + private val data: ConversionData ) : CallableRefactoring(data.function.project, data.functionDescriptor, text) { override fun performRefactoring(descriptorsForChange: Collection) { val callables = getAffectedCallables(project, descriptorsForChange) @@ -184,7 +176,7 @@ class ConvertFunctionTypeParameterToReceiverIntention : SelfTargetingRangeIntent project.runSynchronouslyWithProgress("Looking for usages and conflicts...", true) { runReadAction { - val progressStep = 1.0/callables.size + val progressStep = 1.0 / callables.size for ((i, callable) in callables.withIndex()) { ProgressManager.getInstance().progressIndicator!!.fraction = (i + 1) * progressStep @@ -203,8 +195,8 @@ class ConvertFunctionTypeParameterToReceiverIntention : SelfTargetingRangeIntent else -> { if (data.isFirstParameter) continue@usageLoop conflicts.putValue( - refElement, - "Can't replace non-Kotlin reference with call expression: " + StringUtil.htmlEmphasize(refElement.text) + refElement, + "Can't replace non-Kotlin reference with call expression: " + StringUtil.htmlEmphasize(refElement.text) ) } } @@ -228,9 +220,9 @@ class ConvertFunctionTypeParameterToReceiverIntention : SelfTargetingRangeIntent } private fun processExternalUsage( - conflicts: MultiMap, - refElement: PsiElement, - usages: ArrayList> + conflicts: MultiMap, + refElement: PsiElement, + usages: ArrayList> ) { val callElement = refElement.getParentOfTypeAndBranch { calleeExpression } if (callElement != null) { @@ -241,10 +233,11 @@ class ConvertFunctionTypeParameterToReceiverIntention : SelfTargetingRangeIntent && callElement is KtConstructorDelegationCall && expressionToProcess !is KtLambdaExpression && expressionToProcess !is KtSimpleNameExpression - && expressionToProcess !is KtCallableReferenceExpression) { + && expressionToProcess !is KtCallableReferenceExpression + ) { conflicts.putValue( - expressionToProcess, - "Following expression won't be processed since refactoring can't preserve its semantics: ${expressionToProcess.text}" + expressionToProcess, + "Following expression won't be processed since refactoring can't preserve its semantics: ${expressionToProcess.text}" ) return } @@ -262,8 +255,8 @@ class ConvertFunctionTypeParameterToReceiverIntention : SelfTargetingRangeIntent val callableReference = refElement.getParentOfTypeAndBranch { callableReference } if (callableReference != null) { conflicts.putValue( - refElement, - "Callable reference transformation is not supported: " + StringUtil.htmlEmphasize(callableReference.text) + refElement, + "Callable reference transformation is not supported: " + StringUtil.htmlEmphasize(callableReference.text) ) return } @@ -271,20 +264,24 @@ class ConvertFunctionTypeParameterToReceiverIntention : SelfTargetingRangeIntent private fun getArgumentExpressionToProcess(callElement: KtCallElement, context: BindingContext): KtExpression? { return callElement - .getArgumentByParameterIndex(data.functionParameterIndex, context) - .singleOrNull() - ?.getArgumentExpression() - ?.let { KtPsiUtil.safeDeparenthesize(it) } + .getArgumentByParameterIndex(data.functionParameterIndex, context) + .singleOrNull() + ?.getArgumentExpression() + ?.let { KtPsiUtil.safeDeparenthesize(it) } } - private fun checkThisExpressionsAreExplicatable(conflicts: MultiMap, context: BindingContext, expressionToProcess: KtExpression): Boolean { + private fun checkThisExpressionsAreExplicatable( + conflicts: MultiMap, + context: BindingContext, + expressionToProcess: KtExpression + ): Boolean { for (thisExpr in expressionToProcess.collectDescendantsOfType()) { if (thisExpr.getLabelName() != null) continue val descriptor = context[BindingContext.REFERENCE_TARGET, thisExpr.instanceReference] ?: continue if (explicateReceiverOf(descriptor) == "this") { conflicts.putValue( - thisExpr, - "Following expression won't be processed since refactoring can't preserve its semantics: ${thisExpr.text}" + thisExpr, + "Following expression won't be processed since refactoring can't preserve its semantics: ${thisExpr.text}" ) return false } @@ -304,8 +301,7 @@ class ConvertFunctionTypeParameterToReceiverIntention : SelfTargetingRangeIntent val callExpression = element.getParentOfTypeAndBranch { calleeExpression } if (callExpression != null) { usages += ParameterCallInfo(callExpression) - } - else if (!data.isFirstParameter) { + } else if (!data.isFirstParameter) { usages += InternalReferencePassInfo(element) } } @@ -314,10 +310,10 @@ class ConvertFunctionTypeParameterToReceiverIntention : SelfTargetingRangeIntent } class ConversionData( - val typeParameterIndex: Int, - val functionParameterIndex: Int, - val lambdaType: KotlinType, - val function: KtFunction + val typeParameterIndex: Int, + val functionParameterIndex: Int, + val lambdaType: KotlinType, + val function: KtFunction ) { val isFirstParameter: Boolean get() = typeParameterIndex == 0 val functionDescriptor by lazy { function.unsafeResolveToDescriptor() as FunctionDescriptor } diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertFunctionTypeReceiverToParameterIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertFunctionTypeReceiverToParameterIntention.kt index aef443b2561..2cac0a93937 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertFunctionTypeReceiverToParameterIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertFunctionTypeReceiverToParameterIntention.kt @@ -31,11 +31,11 @@ import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde import org.jetbrains.kotlin.idea.core.* +import org.jetbrains.kotlin.idea.core.util.runSynchronouslyWithProgress import org.jetbrains.kotlin.idea.refactoring.CallableRefactoring import org.jetbrains.kotlin.idea.refactoring.checkConflictsInteractively import org.jetbrains.kotlin.idea.refactoring.getAffectedCallables import org.jetbrains.kotlin.idea.references.KtSimpleReference -import org.jetbrains.kotlin.idea.core.util.runSynchronouslyWithProgress import org.jetbrains.kotlin.idea.search.usagesSearch.searchReferencesOrMethodReferences import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.idea.util.application.runReadAction @@ -49,13 +49,13 @@ import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.KotlinType class ConvertFunctionTypeReceiverToParameterIntention : SelfTargetingRangeIntention( - KtTypeReference::class.java, - "Convert function type receiver to parameter" + KtTypeReference::class.java, + "Convert function type receiver to parameter" ) { class ConversionData( - val functionParameterIndex: Int, - val lambdaReceiverType: KotlinType, - val function: KtFunction + val functionParameterIndex: Int, + val lambdaReceiverType: KotlinType, + val function: KtFunction ) { val functionDescriptor by lazy { function.unsafeResolveToDescriptor() as FunctionDescriptor } } @@ -92,8 +92,8 @@ class ConvertFunctionTypeReceiverToParameterIntention : SelfTargetingRangeIntent val psiFactory = KtPsiFactory(project) val validator = CollectingNameValidator( - lambda.valueParameters.mapNotNull { it.name }, - NewDeclarationNameValidator(lambda.bodyExpression!!, null, NewDeclarationNameValidator.Target.VARIABLES) + lambda.valueParameters.mapNotNull { it.name }, + NewDeclarationNameValidator(lambda.bodyExpression!!, null, NewDeclarationNameValidator.Target.VARIABLES) ) val newParameterName = KotlinNameSuggester.suggestNamesByType(data.lambdaReceiverType, validator, "p").first() val newParameterRefExpression = psiFactory.createExpression(newParameterName) @@ -112,7 +112,7 @@ class ConvertFunctionTypeReceiverToParameterIntention : SelfTargetingRangeIntent } private inner class Converter( - private val data: ConversionData + private val data: ConversionData ) : CallableRefactoring(data.function.project, data.functionDescriptor, text) { override fun performRefactoring(descriptorsForChange: Collection) { val callables = getAffectedCallables(project, descriptorsForChange) @@ -123,7 +123,7 @@ class ConvertFunctionTypeReceiverToParameterIntention : SelfTargetingRangeIntent project.runSynchronouslyWithProgress("Looking for usages and conflicts...", true) { runReadAction { - val progressStep = 1.0/callables.size + val progressStep = 1.0 / callables.size for ((i, callable) in callables.withIndex()) { ProgressManager.getInstance().progressIndicator!!.fraction = (i + 1) * progressStep @@ -155,21 +155,27 @@ class ConvertFunctionTypeReceiverToParameterIntention : SelfTargetingRangeIntent } } - private fun processExternalUsage(ref: KtSimpleReference<*>, usages: java.util.ArrayList>) { + private fun processExternalUsage( + ref: KtSimpleReference<*>, + usages: java.util.ArrayList> + ) { val callElement = ref.element.getParentOfTypeAndBranch { calleeExpression } ?: return val context = callElement.analyze(BodyResolveMode.PARTIAL) val expressionToProcess = callElement - .getArgumentByParameterIndex(data.functionParameterIndex, context) - .singleOrNull() - ?.getArgumentExpression() - ?.let { KtPsiUtil.safeDeparenthesize(it) } - ?: return + .getArgumentByParameterIndex(data.functionParameterIndex, context) + .singleOrNull() + ?.getArgumentExpression() + ?.let { KtPsiUtil.safeDeparenthesize(it) } + ?: return if (expressionToProcess is KtLambdaExpression) { usages += LambdaInfo(expressionToProcess) } } - private fun processInternalUsages(callable: KtFunction, usages: java.util.ArrayList>) { + private fun processInternalUsages( + callable: KtFunction, + usages: java.util.ArrayList> + ) { val body = when (callable) { is KtConstructor<*> -> callable.containingClassOrObject?.getBody() else -> callable.bodyExpression @@ -189,9 +195,9 @@ class ConvertFunctionTypeReceiverToParameterIntention : SelfTargetingRangeIntent val functionTypeReceiver = parent as? KtFunctionTypeReceiver ?: return null val functionType = functionTypeReceiver.parent as? KtFunctionType ?: return null val lambdaReceiverType = functionType - .getAbbreviatedTypeOrType(functionType.analyze(BodyResolveMode.PARTIAL)) - ?.getReceiverTypeFromFunctionType() - ?: return null + .getAbbreviatedTypeOrType(functionType.analyze(BodyResolveMode.PARTIAL)) + ?.getReceiverTypeFromFunctionType() + ?: return null val containingParameter = (functionType.parent as? KtTypeReference)?.parent as? KtParameter ?: return null val ownerFunction = containingParameter.ownerFunction as? KtFunction ?: return null val functionParameterIndex = ownerFunction.valueParameters.indexOf(containingParameter) @@ -206,8 +212,8 @@ class ConvertFunctionTypeReceiverToParameterIntention : SelfTargetingRangeIntent val elementBefore = data.function.valueParameters[data.functionParameterIndex].typeReference!!.typeElement as KtFunctionType val elementAfter = elementBefore.copied().apply { parameterList!!.addParameterBefore( - KtPsiFactory(element).createFunctionTypeParameter(element), - parameterList!!.parameters.firstOrNull() + KtPsiFactory(element).createFunctionTypeParameter(element), + parameterList!!.parameters.firstOrNull() ) setReceiverTypeReference(null) } diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertLambdaToReferenceIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertLambdaToReferenceIntention.kt index db26ac29fe1..d20ef968036 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertLambdaToReferenceIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertLambdaToReferenceIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions @@ -238,7 +227,8 @@ open class ConvertLambdaToReferenceIntention(text: String) : val descriptor by lazy { receiver?.type?.constructor?.declarationDescriptor } val receiverText = when { receiver == null || descriptor?.isCompanionObject() == true -> "" - receiver is ExtensionReceiver || lambdaExpression.getResolutionScope().getImplicitReceiversHierarchy().size == 1 -> "this" + receiver is ExtensionReceiver || + lambdaExpression.getResolutionScope().getImplicitReceiversHierarchy().size == 1 -> "this" else -> descriptor?.name?.let { "this@$it" } ?: return null } "$receiverText::${singleStatement.getCallReferencedName()}" @@ -259,7 +249,8 @@ open class ConvertLambdaToReferenceIntention(text: String) : val originalReceiverType = receiverDescriptor.type val receiverType = originalReceiverType.approximateFlexibleTypes(preferNotNull = true) if (shortTypes) { - "${IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderType(receiverType)}::$selectorReferenceName" + "${IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS + .renderType(receiverType)}::$selectorReferenceName" } else { "${IdeDescriptorRenderers.SOURCE_CODE.renderType(receiverType)}::$selectorReferenceName" } diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertObjectLiteralToClassIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertObjectLiteralToClassIntention.kt index 6f2ee45172f..44c1c3af736 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertObjectLiteralToClassIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertObjectLiteralToClassIntention.kt @@ -42,8 +42,8 @@ import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.scopes.utils.findClassifier class ConvertObjectLiteralToClassIntention : SelfTargetingRangeIntention( - KtObjectLiteralExpression::class.java, - "Convert object literal to class" + KtObjectLiteralExpression::class.java, + "Convert object literal to class" ) { override fun applicabilityRange(element: KtObjectLiteralExpression) = element.objectDeclaration.getObjectKeyword()?.textRange @@ -70,7 +70,7 @@ class ConvertObjectLiteralToClassIntention : SelfTargetingRangeIntention Unit - ) { - val descriptor = descriptorWithConflicts.descriptor.copy(suggestedNames = listOf(className)) - doRefactor( - ExtractionGeneratorConfiguration(descriptor, ExtractionGeneratorOptions.DEFAULT), - onFinish - ) - } + object : ExtractionEngineHelper(text) { + override fun configureAndRun( + project: Project, + editor: Editor, + descriptorWithConflicts: ExtractableCodeDescriptorWithConflicts, + onFinish: (ExtractionResult) -> Unit + ) { + val descriptor = descriptorWithConflicts.descriptor.copy(suggestedNames = listOf(className)) + doRefactor( + ExtractionGeneratorConfiguration(descriptor, ExtractionGeneratorOptions.DEFAULT), + onFinish + ) } + } ).run(editor, ExtractionData(element.containingKtFile, element.toRange(), targetSibling)) { extractionResult -> val functionDeclaration = extractionResult.declaration as KtFunction if (functionDeclaration.valueParameters.isNotEmpty()) { val valKeyword = psiFactory.createValKeyword() - newClass - .createPrimaryConstructorParameterListIfAbsent() - .replaced(functionDeclaration.valueParameterList!!) - .parameters - .forEach { - it.addAfter(valKeyword, null) - it.addModifier(KtTokens.PRIVATE_KEYWORD) - } + newClass.createPrimaryConstructorParameterListIfAbsent() + .replaced(functionDeclaration.valueParameterList!!) + .parameters + .forEach { + it.addAfter(valKeyword, null) + it.addModifier(KtTokens.PRIVATE_KEYWORD) + } } val introducedClass = functionDeclaration.replaced(newClass).apply { @@ -147,12 +146,12 @@ class ConvertObjectLiteralToClassIntention : SelfTargetingRangeIntention( - KtPrimaryConstructor::class.java, - "Convert to secondary constructor" + KtPrimaryConstructor::class.java, + "Convert to secondary constructor" ) { override fun isApplicableTo(element: KtPrimaryConstructor, caretOffset: Int): Boolean { val containingClass = element.containingClassOrObject as? KtClass ?: return false if (containingClass.isAnnotation() || containingClass.isData() - || containingClass.superTypeListEntries.any { it is KtDelegatedSuperTypeEntry }) return false + || containingClass.superTypeListEntries.any { it is KtDelegatedSuperTypeEntry } + ) return false return element.valueParameters.all { !it.hasValOrVar() || (it.name != null && it.annotationEntries.isEmpty()) } } @@ -73,7 +63,7 @@ class ConvertPrimaryConstructorToSecondaryIntention : SelfTargetingIntention" else typeText, - valueParameter.isMutable, null) + val property = factory.createProperty( + valueParameter.modifierList?.text, valueParameter.name!!, + if (isVararg && typeText != null) "Array" else typeText, + valueParameter.isMutable, null + ) if (anchorBefore == null) klass.addDeclarationBefore(property, null) else klass.addDeclarationAfter(property, anchorBefore) } } @@ -166,8 +159,7 @@ class ConvertPrimaryConstructorToSecondaryIntention : SelfTargetingIntention().none { it.elementType == KtTokens.SEMICOLON }) { + } else if (lastEnumEntry.getChildrenOfType().none { it.elementType == KtTokens.SEMICOLON }) { lastEnumEntry.add(factory.createSemicolon()) } } diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertRangeCheckToTwoComparisonsIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertRangeCheckToTwoComparisonsIntention.kt index 96b6a20b74a..9cb25bd8d06 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertRangeCheckToTwoComparisonsIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertRangeCheckToTwoComparisonsIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions @@ -21,8 +10,8 @@ import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* class ConvertRangeCheckToTwoComparisonsIntention : SelfTargetingOffsetIndependentIntention( - KtBinaryExpression::class.java, - "Convert to comparisons" + KtBinaryExpression::class.java, + "Convert to comparisons" ) { private fun KtExpression?.isSimple() = this is KtConstantExpression || this is KtNameReferenceExpression diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertReceiverToParameterIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertReceiverToParameterIntention.kt index d4cb1b9d659..d182c4311c7 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertReceiverToParameterIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertReceiverToParameterIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions @@ -37,7 +26,9 @@ import org.jetbrains.kotlin.psi.KtTypeReference import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.psi.typeRefHelpers.setReceiverTypeReference -class ConvertReceiverToParameterIntention : SelfTargetingOffsetIndependentIntention(KtTypeReference::class.java, "Convert receiver to parameter"), LowPriorityAction { +class ConvertReceiverToParameterIntention : + SelfTargetingOffsetIndependentIntention(KtTypeReference::class.java, "Convert receiver to parameter"), + LowPriorityAction { override fun isApplicableTo(element: KtTypeReference): Boolean { return (element.parent as? KtNamedFunction)?.receiverTypeReference == element } @@ -86,39 +77,38 @@ class ConvertReceiverToParameterIntention : SelfTargetingOffsetIndependentIntent val templateBuilder = TemplateBuilderImpl(function) templateBuilder.replaceElement(addedParameter.nameIdentifier!!, ChooseStringExpression(receiverNames)) TemplateManager.getInstance(project).startTemplate( - editor, - templateBuilder.buildInlineTemplate(), - object: TemplateEditingAdapter() { - private fun revertChanges() { - runWriteAction { - function.setReceiverTypeReference(addedParameter.typeReference) - function.valueParameterList!!.removeParameter(addedParameter) - PsiDocumentManager.getInstance(project).commitDocument(editor.document) - } - } - - override fun templateFinished(template: Template, brokenOff: Boolean) { - val newName = addedParameter.name - revertChanges() - if (!brokenOff) { - runChangeSignature( - element.project, - function.resolveToExpectedDescriptorIfPossible() as FunctionDescriptor, - configureChangeSignature(newName), - function.receiverTypeReference!!, - text - ) - } - } - - override fun templateCancelled(template: Template?) { - revertChanges() + editor, + templateBuilder.buildInlineTemplate(), + object : TemplateEditingAdapter() { + private fun revertChanges() { + runWriteAction { + function.setReceiverTypeReference(addedParameter.typeReference) + function.valueParameterList!!.removeParameter(addedParameter) + PsiDocumentManager.getInstance(project).commitDocument(editor.document) } } + + override fun templateFinished(template: Template, brokenOff: Boolean) { + val newName = addedParameter.name + revertChanges() + if (!brokenOff) { + runChangeSignature( + element.project, + function.resolveToExpectedDescriptorIfPossible() as FunctionDescriptor, + configureChangeSignature(newName), + function.receiverTypeReference!!, + text + ) + } + } + + override fun templateCancelled(template: Template?) { + revertChanges() + } + } ) } - } - else { + } else { runChangeSignature(element.project, descriptor, configureChangeSignature(), element, text) } } diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertReferenceToLambdaIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertReferenceToLambdaIntention.kt index dd9e9d34a46..3f406ae7ef3 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertReferenceToLambdaIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertReferenceToLambdaIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions @@ -55,7 +44,7 @@ class ConvertReferenceToLambdaIntention : SelfTargetingOffsetIndependentIntentio } val receiverNameAndType = receiverType?.let { KotlinNameSuggester.suggestNamesByType(it, validator = { name -> - name !in parameterNamesAndTypes.map { it.first } + name !in parameterNamesAndTypes.map { pair -> pair.first } }, defaultName = "receiver").first() to it } @@ -83,7 +72,8 @@ class ConvertReferenceToLambdaIntention : SelfTargetingOffsetIndependentIntentio val lambdaExpression = if (valueArgumentParent != null && lambdaParameterNamesAndTypes.size == 1 && - receiverExpression?.text != "it") { + receiverExpression?.text != "it" + ) { factory.createLambdaExpression( parameters = "", body = when { diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertSealedClassToEnumIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertSealedClassToEnumIntention.kt index cfb8b703c8f..8924c696401 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertSealedClassToEnumIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertSealedClassToEnumIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions @@ -71,10 +60,10 @@ class ConvertSealedClassToEnumIntention : SelfTargetingRangeIntention(K val inconvertibleSubclasses = subclassesByContainer[null] ?: emptyList() if (inconvertibleSubclasses.isNotEmpty()) { return showError( - "All inheritors must be nested objects of the class itself and may not inherit from other classes or interfaces.\n", - inconvertibleSubclasses, - project, - editor + "All inheritors must be nested objects of the class itself and may not inherit from other classes or interfaces.\n", + inconvertibleSubclasses, + project, + editor ) } @@ -86,8 +75,7 @@ class ConvertSealedClassToEnumIntention : SelfTargetingRangeIntention(K if (subclassesByContainer.isNotEmpty()) { subclassesByContainer.forEach { currentClass, currentSubclasses -> processClass(currentClass!!, currentSubclasses, project) } - } - else { + } else { processClass(klass, emptyList(), project) } } @@ -125,8 +113,7 @@ class ConvertSealedClassToEnumIntention : SelfTargetingRangeIntention(K if (i < subclasses.lastIndex) { entry.add(comma) - } - else if (needSemicolon) { + } else if (needSemicolon) { entry.add(semicolon) } @@ -143,11 +130,10 @@ class ConvertSealedClassToEnumIntention : SelfTargetingRangeIntention(K .reversed() .asSequence() .map { klass.addDeclarationBefore(it, null) } - .last() + .last() // TODO: Add formatter rule firstEntry.parent.addBefore(psiFactory.createNewLine(), firstEntry) - } - else if (needSemicolon) { + } else if (needSemicolon) { klass.declarations.firstOrNull()?.let { anchor -> val delimiter = anchor.parent.addBefore(semicolon, anchor) CodeStyleManager.getInstance(project).reformat(delimiter) diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertSecondaryConstructorToPrimaryIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertSecondaryConstructorToPrimaryIntention.kt index 627c726e551..740e0ac3d32 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertSecondaryConstructorToPrimaryIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertSecondaryConstructorToPrimaryIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions @@ -101,13 +90,13 @@ class ConvertSecondaryConstructorToPrimaryIntention : SelfTargetingRangeIntentio val initializer = factory.createAnonymousInitializer() as? KtClassInitializer for (statement in bodyExpression?.statements ?: emptyList()) { val (rightDescriptor, leftDescriptor) = - statement.tryConvertToPropertyByParameterInitialization(constructorDescriptor, context) ?: with(initializer) { - (initializer?.body as? KtBlockExpression)?.let { - it.addBefore(statement.copy(), it.rBrace) - it.addBefore(factory.createNewLine(), it.rBrace) - } - null to null + statement.tryConvertToPropertyByParameterInitialization(constructorDescriptor, context) ?: with(initializer) { + (initializer?.body as? KtBlockExpression)?.let { + it.addBefore(statement.copy(), it.rBrace) + it.addBefore(factory.createNewLine(), it.rBrace) } + null to null + } if (rightDescriptor == null || leftDescriptor == null) continue parameterToPropertyMap[rightDescriptor] = leftDescriptor } diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertToConcatenatedStringIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertToConcatenatedStringIntention.kt index ca5d9f99ce9..a8559eeb787 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertToConcatenatedStringIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertToConcatenatedStringIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions @@ -23,7 +12,10 @@ import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* -class ConvertToConcatenatedStringIntention : SelfTargetingOffsetIndependentIntention(KtStringTemplateExpression::class.java, "Convert template to concatenated string"), LowPriorityAction { +class ConvertToConcatenatedStringIntention : SelfTargetingOffsetIndependentIntention( + KtStringTemplateExpression::class.java, + "Convert template to concatenated string" +), LowPriorityAction { override fun isApplicableTo(element: KtStringTemplateExpression): Boolean { if (element.lastChild.node.elementType != KtTokens.CLOSING_QUOTE) return false // not available for unclosed literal return element.entries.any { it is KtStringTemplateEntryWithExpression } @@ -35,12 +27,12 @@ class ConvertToConcatenatedStringIntention : SelfTargetingOffsetIndependentInten val entries = element.entries val text = entries - .filterNot { it is KtStringTemplateEntryWithExpression && it.expression == null } - .mapIndexed { index, entry -> - entry.toSeparateString(quote, convertExplicitly = (index == 0), isFinalEntry = (index == entries.lastIndex)) - } - .joinToString(separator = "+") - .replace("""$quote+$quote""", "") + .filterNot { it is KtStringTemplateEntryWithExpression && it.expression == null } + .mapIndexed { index, entry -> + entry.toSeparateString(quote, convertExplicitly = (index == 0), isFinalEntry = (index == entries.lastIndex)) + } + .joinToString(separator = "+") + .replace("""$quote+$quote""", "") val replacement = KtPsiFactory(element).createExpression(text) element.replace(replacement) @@ -61,7 +53,7 @@ class ConvertToConcatenatedStringIntention : SelfTargetingOffsetIndependentInten expression.text return if (convertExplicitly && !expression.isStringExpression()) - text + ".toString()" + "$text.toString()" else text } diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertToRawStringTemplateIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertToRawStringTemplateIntention.kt index dff6fd6e2db..a0866bf5639 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertToRawStringTemplateIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertToRawStringTemplateIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions @@ -21,7 +10,7 @@ import org.jetbrains.kotlin.idea.core.replaced import org.jetbrains.kotlin.psi.KtBinaryExpression class ConvertToRawStringTemplateIntention : ConvertToStringTemplateIntention() { - init { + init { text = "Convert concatenation to raw string" } diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertTryFinallyToUseCallIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertTryFinallyToUseCallIntention.kt index f44ba54d26c..87770b4a2c6 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertTryFinallyToUseCallIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertTryFinallyToUseCallIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions @@ -38,7 +27,7 @@ class ConvertTryFinallyToUseCallInspection : IntentionBasedInspection( - KtTryExpression::class.java, "Convert try-finally to .use()" + KtTryExpression::class.java, "Convert try-finally to .use()" ) { override fun applyTo(element: KtTryExpression, editor: Editor?) { val finallySection = element.finallyBlock!! @@ -53,8 +42,7 @@ class ConvertTryFinallyToUseCallIntention : SelfTargetingRangeIntention result.selectorExpression as? KtCallExpression ?: return is KtCallExpression -> result else -> return @@ -93,10 +80,10 @@ class ConvertTryFinallyToUseCallIntention : SelfTargetingRangeIntention + s != "java.io.Closeable" && s != "java.lang.AutoCloseable" + } + }) return null when (receiver) { is ExpressionReceiver -> { @@ -104,11 +91,12 @@ class ConvertTryFinallyToUseCallIntention : SelfTargetingRangeIntention {} + is ImplicitReceiver -> { + } else -> return null } diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/CreateKotlinSubClassIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/CreateKotlinSubClassIntention.kt index 9854d5d2ba5..76134e82d77 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/CreateKotlinSubClassIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/CreateKotlinSubClassIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions @@ -55,9 +44,9 @@ class CreateKotlinSubClassIntention : SelfTargetingRangeIntention(KtCla if (!element.isInterface() && primaryConstructor != null) { val constructors = element.secondaryConstructors + primaryConstructor if (constructors.none() { - !it.isPrivate() && - it.getValueParameters().all { it.hasDefaultValue() } - }) { + !it.isPrivate() && + it.getValueParameters().all { it.hasDefaultValue() } + }) { // At this moment we require non-private default constructor // TODO: handle non-private constructors with parameters return null @@ -68,12 +57,12 @@ class CreateKotlinSubClassIntention : SelfTargetingRangeIntention(KtCla } private fun getImplementTitle(baseClass: KtClass) = - when { - baseClass.isInterface() -> "Implement interface" - baseClass.isAbstract() -> "Implement abstract class" - baseClass.isSealed() -> "Implement sealed class" - else /* open class */ -> "Create subclass" - } + when { + baseClass.isInterface() -> "Implement interface" + baseClass.isAbstract() -> "Implement abstract class" + baseClass.isSealed() -> "Implement sealed class" + else /* open class */ -> "Create subclass" + } override fun startInWriteAction() = false @@ -83,8 +72,7 @@ class CreateKotlinSubClassIntention : SelfTargetingRangeIntention(KtCla val name = element.name ?: throw IllegalStateException("This intention should not be applied to anonymous classes") if (element.isSealed()) { createSealedSubclass(element, name, editor) - } - else { + } else { createExternalSubclass(element, name, editor) } } @@ -94,7 +82,7 @@ class CreateKotlinSubClassIntention : SelfTargetingRangeIntention(KtCla private fun KtClassOrObject.hasSameDeclaration(name: String) = declarations.any { it is KtNamedDeclaration && it.name == name } private fun targetNameWithoutConflicts(baseName: String, container: KtClassOrObject?) = - KotlinNameSuggester.suggestNameByName(defaultTargetName(baseName)) { container?.hasSameDeclaration(it) != true } + KotlinNameSuggester.suggestNameByName(defaultTargetName(baseName)) { container?.hasSameDeclaration(it) != true } private fun createSealedSubclass(sealedClass: KtClass, sealedName: String, editor: Editor) { val project = sealedClass.project @@ -143,11 +131,12 @@ class CreateKotlinSubClassIntention : SelfTargetingRangeIntention(KtCla file to klass } chooseAndImplementMethods(project, klass, CodeInsightUtil.positionCursor(project, file, klass) ?: editor) - } - else { + } else { val klass = runWriteAction { - val builder = buildClassHeader(targetNameWithoutConflicts(baseName, baseClass.containingClassOrObject), - baseClass, name, visibility) + val builder = buildClassHeader( + targetNameWithoutConflicts(baseName, baseClass.containingClassOrObject), + baseClass, name, visibility + ) val classFromText = factory.createClass(builder.asString()) container.parent.addAfter(classFromText, container) as KtClass } @@ -166,11 +155,11 @@ class CreateKotlinSubClassIntention : SelfTargetingRangeIntention(KtCla val aPackage = JavaDirectoryService.getInstance().getPackage(sourceDir) val dialog = object : CreateKotlinClassDialog( - baseClass.project, text, - targetNameWithoutConflicts(baseName, baseClass.containingClassOrObject), - aPackage?.qualifiedName ?: "", - CreateClassKind.CLASS, true, - ModuleUtilCore.findModuleForPsiElement(baseClass) + baseClass.project, text, + targetNameWithoutConflicts(baseName, baseClass.containingClassOrObject), + aPackage?.qualifiedName ?: "", + CreateClassKind.CLASS, true, + ModuleUtilCore.findModuleForPsiElement(baseClass) ) { override fun getBaseDir(packageName: String) = sourceDir @@ -180,10 +169,10 @@ class CreateKotlinSubClassIntention : SelfTargetingRangeIntention(KtCla } private fun buildClassHeader( - targetName: String, - baseClass: KtClass, - baseName: String, - defaultVisibility: Visibility = ModifiersChecker.resolveVisibilityFromModifiers(baseClass, Visibilities.PUBLIC) + targetName: String, + baseClass: KtClass, + baseName: String, + defaultVisibility: Visibility = ModifiersChecker.resolveVisibilityFromModifiers(baseClass, Visibilities.PUBLIC) ): ClassHeaderBuilder { return ClassHeaderBuilder().apply { if (!baseClass.isInterface()) { diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/DestructureIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/DestructureIntention.kt index c5678dca84e..0682a83706a 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/DestructureIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/DestructureIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions @@ -49,31 +38,30 @@ import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns import java.util.* class DestructureInspection : IntentionBasedInspection( - DestructureIntention::class, - { element, _ -> - val usagesToRemove = DestructureIntention.collectUsagesToRemove(element)?.data - if (element is KtParameter) { - usagesToRemove != null && - (usagesToRemove.any { it.declarationToDrop is KtDestructuringDeclaration } || - usagesToRemove.filter { it.usagesToReplace.isNotEmpty() }.size > usagesToRemove.size / 2) - } - else { - usagesToRemove?.any { it.declarationToDrop is KtDestructuringDeclaration } ?: false - } + DestructureIntention::class, + { element, _ -> + val usagesToRemove = DestructureIntention.collectUsagesToRemove(element)?.data + if (element is KtParameter) { + usagesToRemove != null && + (usagesToRemove.any { it.declarationToDrop is KtDestructuringDeclaration } || + usagesToRemove.filter { it.usagesToReplace.isNotEmpty() }.size > usagesToRemove.size / 2) + } else { + usagesToRemove?.any { it.declarationToDrop is KtDestructuringDeclaration } ?: false } + } ) class DestructureIntention : SelfTargetingRangeIntention( - KtDeclaration::class.java, - "Use destructuring declaration" + KtDeclaration::class.java, + "Use destructuring declaration" ) { override fun applyTo(element: KtDeclaration, editor: Editor?) { val (usagesToRemove, removeSelectorInLoopRange) = collectUsagesToRemove(element)!! val factory = KtPsiFactory(element) val validator = NewDeclarationNameValidator( - container = element.parent, anchor = element, target = NewDeclarationNameValidator.Target.VARIABLES, - excludedDeclarations = usagesToRemove.map { listOfNotNull(it.declarationToDrop) }.flatten() + container = element.parent, anchor = element, target = NewDeclarationNameValidator.Target.VARIABLES, + excludedDeclarations = usagesToRemove.map { listOfNotNull(it.declarationToDrop) }.flatten() ) val names = ArrayList() val underscoreSupported = element.languageVersionSettings.supportsFeature(LanguageFeature.SingleUnderscoreForParameterName) @@ -84,12 +72,11 @@ class DestructureIntention : SelfTargetingRangeIntention( usagesToRemove.forEach { (descriptor, usagesToReplace, variableToDrop, name) -> val suggestedName = - if (usagesToReplace.isEmpty() && variableToDrop == null && underscoreSupported && !allUnused) { - "_" - } - else { - name ?: KotlinNameSuggester.suggestNameByName(descriptor.name.asString(), validator) - } + if (usagesToReplace.isEmpty() && variableToDrop == null && underscoreSupported && !allUnused) { + "_" + } else { + name ?: KotlinNameSuggester.suggestNameByName(descriptor.name.asString(), validator) + } runWriteAction { variableToDrop?.delete() @@ -184,13 +171,12 @@ class DestructureIntention : SelfTargetingRangeIntention( internal fun collectUsagesToRemove(declaration: KtDeclaration): UsagesToRemove? { val context = declaration.analyze() - val variableDescriptor = - when (declaration) { - is KtParameter -> context.get(BindingContext.VALUE_PARAMETER, declaration) - is KtFunctionLiteral -> context.get(BindingContext.FUNCTION, declaration)?.valueParameters?.singleOrNull() - is KtVariableDeclaration -> context.get(BindingContext.VARIABLE, declaration) - else -> null - } ?: return null + val variableDescriptor = when (declaration) { + is KtParameter -> context.get(BindingContext.VALUE_PARAMETER, declaration) + is KtFunctionLiteral -> context.get(BindingContext.FUNCTION, declaration)?.valueParameters?.singleOrNull() + is KtVariableDeclaration -> context.get(BindingContext.VARIABLE, declaration) + else -> null + } ?: return null val variableType = variableDescriptor.type if (variableType.isMarkedNullable) return null @@ -209,23 +195,26 @@ class DestructureIntention : SelfTargetingRangeIntention( val loopRangeDescriptorOwner = loopRangeDescriptor.containingDeclaration val mapClassDescriptor = classDescriptor.builtIns.map if (loopRangeDescriptorOwner is ClassDescriptor && - DescriptorUtils.isSubclass(loopRangeDescriptorOwner, mapClassDescriptor)) { + DescriptorUtils.isSubclass(loopRangeDescriptorOwner, mapClassDescriptor) + ) { removeSelectorInLoopRange = loopRangeDescriptor.name.asString().let { it == "entries" || it == "entrySet" } } } listOf("key", "value").mapTo(usagesToRemove) { - UsageData(descriptor = mapEntryClassDescriptor.unsubstitutedMemberScope.getContributedVariables( - Name.identifier(it), NoLookupLocation.FROM_BUILTINS).single()) + UsageData( + descriptor = mapEntryClassDescriptor.unsubstitutedMemberScope.getContributedVariables( + Name.identifier(it), NoLookupLocation.FROM_BUILTINS + ).single() + ) } ReferencesSearchScopeHelper.search(declaration).iterateOverMapEntryPropertiesUsages( - context, - { index, usageData -> noBadUsages = usagesToRemove[index].add(usageData, index) && noBadUsages }, - { noBadUsages = false } + context, + { index, usageData -> noBadUsages = usagesToRemove[index].add(usageData, index) && noBadUsages }, + { noBadUsages = false } ) - } - else if (classDescriptor.isData) { + } else if (classDescriptor.isData) { val valueParameters = classDescriptor.unsubstitutedPrimaryConstructor?.valueParameters ?: return null valueParameters.mapTo(usagesToRemove) { UsageData(descriptor = it) } @@ -233,23 +222,22 @@ class DestructureIntention : SelfTargetingRangeIntention( val usageScopeElement = declaration.getUsageScopeElement() ?: return null val nameToSearch = when (declaration) { - is KtParameter -> declaration.nameAsName - is KtVariableDeclaration -> declaration.nameAsName - else -> Name.identifier("it") - } ?: return null + is KtParameter -> declaration.nameAsName + is KtVariableDeclaration -> declaration.nameAsName + else -> Name.identifier("it") + } ?: return null val constructorParameterNameMap = mutableMapOf() valueParameters.forEach { constructorParameterNameMap[it.name] = it } usageScopeElement.iterateOverDataClassPropertiesUsagesWithIndex( - context, - nameToSearch, - constructorParameterNameMap, - { index, usageData -> noBadUsages = usagesToRemove[index].add(usageData, index) && noBadUsages }, - { noBadUsages = false } + context, + nameToSearch, + constructorParameterNameMap, + { index, usageData -> noBadUsages = usagesToRemove[index].add(usageData, index) && noBadUsages }, + { noBadUsages = false } ) - } - else { + } else { return null } if (!noBadUsages) return null @@ -257,16 +245,15 @@ class DestructureIntention : SelfTargetingRangeIntention( val droppedLastUnused = usagesToRemove.dropLastWhile { it.usagesToReplace.isEmpty() && it.declarationToDrop == null } return if (droppedLastUnused.isEmpty()) { UsagesToRemove(usagesToRemove, removeSelectorInLoopRange) - } - else { + } else { UsagesToRemove(droppedLastUnused, removeSelectorInLoopRange) } } private fun Query.iterateOverMapEntryPropertiesUsages( - context: BindingContext, - process: (Int, SingleUsageData) -> Unit, - cancel: () -> Unit + context: BindingContext, + process: (Int, SingleUsageData) -> Unit, + cancel: () -> Unit ) { // TODO: Remove SAM-constructor when KT-11265 will be fixed forEach(Processor forEach@{ @@ -296,11 +283,11 @@ class DestructureIntention : SelfTargetingRangeIntention( } private fun PsiElement.iterateOverDataClassPropertiesUsagesWithIndex( - context: BindingContext, - parameterName: Name, - constructorParameterNameMap: Map, - process: (Int, SingleUsageData) -> Unit, - cancel: () -> Unit + context: BindingContext, + parameterName: Name, + constructorParameterNameMap: Map, + process: (Int, SingleUsageData) -> Unit, + cancel: () -> Unit ) { anyDescendantOfType { if (it.getReferencedNameAsName() != parameterName) false @@ -328,7 +315,7 @@ class DestructureIntention : SelfTargetingRangeIntention( } private fun getDataIfUsageIsApplicable(dataClassUsage: PsiReference, context: BindingContext) = - (dataClassUsage.element as? KtReferenceExpression)?.let { getDataIfUsageIsApplicable(it, context) } + (dataClassUsage.element as? KtReferenceExpression)?.let { getDataIfUsageIsApplicable(it, context) } private fun getDataIfUsageIsApplicable(dataClassUsage: KtReferenceExpression, context: BindingContext): SingleUsageData? { val destructuringDecl = dataClassUsage.parent as? KtDestructuringDeclaration @@ -350,24 +337,27 @@ class DestructureIntention : SelfTargetingRangeIntention( if (property != null && property.isVar) return null val descriptor = qualifiedExpression.getResolvedCall(context)?.resultingDescriptor ?: return null - if (!descriptor.isVisible(dataClassUsage, qualifiedExpression.receiverExpression, - context, dataClassUsage.containingKtFile.getResolutionFacade())) { + if (!descriptor.isVisible( + dataClassUsage, qualifiedExpression.receiverExpression, + context, dataClassUsage.containingKtFile.getResolutionFacade() + ) + ) { return null } return SingleUsageData(descriptor = descriptor, usageToReplace = qualifiedExpression, declarationToDrop = property) } internal data class SingleUsageData( - val descriptor: CallableDescriptor?, - val usageToReplace: KtExpression?, - val declarationToDrop: KtDeclaration? + val descriptor: CallableDescriptor?, + val usageToReplace: KtExpression?, + val declarationToDrop: KtDeclaration? ) internal data class UsageData( - val descriptor: CallableDescriptor, - val usagesToReplace: MutableList = mutableListOf(), - var declarationToDrop: KtDeclaration? = null, - var name: String? = null + val descriptor: CallableDescriptor, + val usagesToReplace: MutableList = mutableListOf(), + var declarationToDrop: KtDeclaration? = null, + var name: String? = null ) { // Returns true if data is successfully added, false otherwise fun add(newData: SingleUsageData, componentIndex: Int): Boolean { @@ -378,8 +368,7 @@ class DestructureIntention : SelfTargetingRangeIntention( name = destructuringEntries[componentIndex].name ?: return false declarationToDrop = newData.declarationToDrop } - } - else { + } else { name = name ?: newData.declarationToDrop?.name declarationToDrop = declarationToDrop ?: newData.declarationToDrop } diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/ImplementAbstractMemberIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/ImplementAbstractMemberIntention.kt index 7147903c110..6e37206ccaf 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/ImplementAbstractMemberIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/ImplementAbstractMemberIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions @@ -42,8 +31,8 @@ import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaClassDescriptor import org.jetbrains.kotlin.idea.core.overrideImplement.OverrideImplementMembersHandler import org.jetbrains.kotlin.idea.core.overrideImplement.OverrideMemberChooserObject -import org.jetbrains.kotlin.idea.refactoring.isAbstract import org.jetbrains.kotlin.idea.core.util.runSynchronouslyWithProgress +import org.jetbrains.kotlin.idea.refactoring.isAbstract import org.jetbrains.kotlin.idea.search.declarationsSearch.HierarchySearchRequest import org.jetbrains.kotlin.idea.search.declarationsSearch.searchInheritors import org.jetbrains.kotlin.idea.util.application.executeCommand @@ -58,14 +47,14 @@ import java.util.* import javax.swing.ListSelectionModel abstract class ImplementAbstractMemberIntentionBase : - SelfTargetingRangeIntention(KtNamedDeclaration::class.java, "", "Implement abstract member") { + SelfTargetingRangeIntention(KtNamedDeclaration::class.java, "", "Implement abstract member") { companion object { private val LOG = Logger.getInstance("#${ImplementAbstractMemberIntentionBase::class.java.canonicalName}") } protected fun findExistingImplementation( - subClass: ClassDescriptor, - superMember: CallableMemberDescriptor + subClass: ClassDescriptor, + superMember: CallableMemberDescriptor ): CallableMemberDescriptor? { val superClass = superMember.containingDeclaration as? ClassDescriptor ?: return null val substitutor = getTypeSubstitutor(superClass.defaultType, subClass.defaultType) ?: TypeSubstitutor.EMPTY @@ -92,15 +81,15 @@ abstract class ImplementAbstractMemberIntentionBase : if (baseClass.isEnum()) { return baseClass.declarations - .asSequence() - .filterIsInstance() - .filter(::acceptSubClass) + .asSequence() + .filterIsInstance() + .filter(::acceptSubClass) } return HierarchySearchRequest(baseClass, baseClass.useScope, false) - .searchInheritors() - .asSequence() - .filter(::acceptSubClass) + .searchInheritors() + .asSequence() + .filter(::acceptSubClass) } protected abstract fun computeText(element: KtNamedDeclaration): String? @@ -122,13 +111,15 @@ abstract class ImplementAbstractMemberIntentionBase : val superMemberDescriptor = member.resolveToDescriptorIfAny() as? CallableMemberDescriptor ?: return val superClassDescriptor = superMemberDescriptor.containingDeclaration as? ClassDescriptor ?: return val substitutor = getTypeSubstitutor(superClassDescriptor.defaultType, subClassDescriptor.defaultType) - ?: TypeSubstitutor.EMPTY + ?: TypeSubstitutor.EMPTY val descriptorToImplement = superMemberDescriptor.substitute(substitutor) as CallableMemberDescriptor - val chooserObject = OverrideMemberChooserObject.create(member.project, - descriptorToImplement, - descriptorToImplement, - OverrideMemberChooserObject.BodyType.FROM_TEMPLATE, - preferConstructorParameters) + val chooserObject = OverrideMemberChooserObject.create( + member.project, + descriptorToImplement, + descriptorToImplement, + OverrideMemberChooserObject.BodyType.FROM_TEMPLATE, + preferConstructorParameters + ) OverrideImplementMembersHandler.generateMembers(editor, targetClass, listOf(chooserObject), false) } @@ -150,8 +141,7 @@ abstract class ImplementAbstractMemberIntentionBase : is KtEnumEntry -> implementInKotlinClass(targetEditor, member, targetClass) is PsiClass -> implementInJavaClass(member, targetClass) } - } - catch(e: IncorrectOperationException) { + } catch (e: IncorrectOperationException) { LOG.error(e) } } @@ -199,8 +189,8 @@ abstract class ImplementAbstractMemberIntentionBase : val project = element.project val classesToProcess = project.runSynchronouslyWithProgress( - CodeInsightBundle.message("intention.implement.abstract.method.searching.for.descendants.progress"), - true + CodeInsightBundle.message("intention.implement.abstract.method.searching.for.descendants.progress"), + true ) { findClassesToProcess(element).toList() } ?: return if (classesToProcess.isEmpty()) return @@ -230,12 +220,10 @@ abstract class ImplementAbstractMemberIntentionBase : } class ImplementAbstractMemberIntention : ImplementAbstractMemberIntentionBase() { - override fun computeText(element: KtNamedDeclaration): String? { - return when(element) { - is KtProperty -> "Implement abstract property" - is KtNamedFunction -> "Implement abstract function" - else -> null - } + override fun computeText(element: KtNamedDeclaration): String? = when (element) { + is KtProperty -> "Implement abstract property" + is KtNamedFunction -> "Implement abstract function" + else -> null } override fun acceptSubClass(subClassDescriptor: ClassDescriptor, memberDescriptor: CallableMemberDescriptor): Boolean { @@ -255,8 +243,8 @@ class ImplementAbstractMemberAsConstructorParameterIntention : ImplementAbstract override fun acceptSubClass(subClassDescriptor: ClassDescriptor, memberDescriptor: CallableMemberDescriptor): Boolean { val kind = subClassDescriptor.kind return (kind == ClassKind.CLASS || kind == ClassKind.ENUM_CLASS) - && subClassDescriptor !is JavaClassDescriptor - && findExistingImplementation(subClassDescriptor, memberDescriptor) == null + && subClassDescriptor !is JavaClassDescriptor + && findExistingImplementation(subClassDescriptor, memberDescriptor) == null } override val preferConstructorParameters: Boolean diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/ImportAllMembersIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/ImportAllMembersIntention.kt index 85d5845440f..6dfdd5b5b34 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/ImportAllMembersIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/ImportAllMembersIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions @@ -20,8 +9,8 @@ import com.intellij.codeInsight.intention.HighPriorityAction import com.intellij.openapi.editor.Editor import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.idea.caches.resolve.analyze -import org.jetbrains.kotlin.idea.core.util.range import org.jetbrains.kotlin.idea.core.ShortenReferences +import org.jetbrains.kotlin.idea.core.util.range import org.jetbrains.kotlin.idea.imports.importableFqName import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.util.ImportDescriptorResult @@ -68,11 +57,13 @@ class ImportAllMembersIntention : SelfTargetingIntention(KtElement::c val qualifiedExpressions = containingKtFile.collectDescendantsOfType { qualifiedExpression -> val qualifierName = qualifiedExpression.receiverExpression.getQualifiedElementSelector() as? KtNameReferenceExpression - qualifierName?.getReferencedNameAsName() == classFqName.shortName() && target(qualifiedExpression)?.importableFqName?.parent() == classFqName + qualifierName?.getReferencedNameAsName() == classFqName.shortName() && target(qualifiedExpression)?.importableFqName + ?.parent() == classFqName } val userTypes = containingKtFile.collectDescendantsOfType { userType -> val receiver = userType.receiverExpression()?.getQualifiedElementSelector() as? KtNameReferenceExpression - receiver?.getReferencedNameAsName() == classFqName.shortName() && target(userType)?.importableFqName?.parent() == classFqName + receiver?.getReferencedNameAsName() == classFqName.shortName() && target(userType)?.importableFqName + ?.parent() == classFqName } //TODO: not deep @@ -93,12 +84,10 @@ class ImportAllMembersIntention : SelfTargetingIntention(KtElement::c return target(qualifiedElement, receiverExpression) } - private fun KtElement.receiverExpression(): KtExpression? { - return when (this) { - is KtDotQualifiedExpression -> receiverExpression - is KtUserType -> qualifier?.referenceExpression - else -> null - } + private fun KtElement.receiverExpression(): KtExpression? = when (this) { + is KtDotQualifiedExpression -> receiverExpression + is KtUserType -> qualifier?.referenceExpression + else -> null } } diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/IndentRawStringIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/IndentRawStringIntention.kt index 842c6639d73..546304a8fb2 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/IndentRawStringIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/IndentRawStringIntention.kt @@ -1,5 +1,5 @@ /* - * Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -23,7 +23,9 @@ class IndentRawStringIntention : SelfTargetingOffsetIndependentIntention(KtBinaryExpression::class.java, "Replace infix call with ordinary call") { +class InfixCallToOrdinaryIntention : + SelfTargetingIntention(KtBinaryExpression::class.java, "Replace infix call with ordinary call") { override fun isApplicableTo(element: KtBinaryExpression, caretOffset: Int): Boolean { if (element.operationToken != KtTokens.IDENTIFIER || element.left == null || element.right == null) return false return element.operationReference.textRange.containsOffset(caretOffset) @@ -37,7 +27,8 @@ class InfixCallToOrdinaryIntention : SelfTargetingIntention( is KtLambdaExpression -> " $2:'{}'" else -> "($2)" } - val replacement = KtPsiFactory(element).createExpressionByPattern(pattern, element.left!!, element.operationReference.text, argument) + val replacement = + KtPsiFactory(element).createExpressionByPattern(pattern, element.left!!, element.operationReference.text, argument) return element.replace(replacement) as KtExpression } } diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/InsertExplicitTypeArgumentsIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/InsertExplicitTypeArgumentsIntention.kt index 1594a071bdb..710ed56680d 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/InsertExplicitTypeArgumentsIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/InsertExplicitTypeArgumentsIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions @@ -56,7 +45,8 @@ class InsertExplicitTypeArgumentsIntention : } } - return typeArgs.isNotEmpty() && typeArgs.values.none { ErrorUtils.containsErrorType(it) || it is CapturedType || it is NewCapturedType } + return typeArgs.isNotEmpty() && typeArgs.values + .none { ErrorUtils.containsErrorType(it) || it is CapturedType || it is NewCapturedType } } fun applyTo(element: KtCallElement, shortenReferences: Boolean = true) { diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/InvertIfConditionIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/InvertIfConditionIntention.kt index f69b33a56e5..c612bfe5e27 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/InvertIfConditionIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/InvertIfConditionIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions @@ -49,7 +38,7 @@ class InvertIfConditionIntention : SelfTargetingIntention(KtIfEx if (rBrace != null) { element.nextEolCommentOnSameLine()?.delete() } - + val newCondition = element.condition!!.negate() val newIf = handleSpecialCases(element, newCondition) ?: handleStandardCase(element, newCondition) @@ -209,14 +198,14 @@ class InvertIfConditionIntention : SelfTargetingIntention(KtIfEx val parent = expression.parent if (parent is KtBlockExpression) { val lastStatement = parent.statements.last() - if (expression == lastStatement) { - return exitStatementExecutedAfter(parent) - } else { - if (lastStatement.isExitStatement() && expression.siblings(withItself = false).firstIsInstance() == lastStatement) { - return lastStatement - } - return null - } + return if (expression == lastStatement) { + exitStatementExecutedAfter(parent) + } else if (lastStatement.isExitStatement() && expression.siblings(withItself = false) + .firstIsInstance() == lastStatement + ) { + lastStatement + } else + null } when (parent) { @@ -230,8 +219,7 @@ class InvertIfConditionIntention : SelfTargetingIntention(KtIfEx } is KtContainerNode -> { - val pparent = parent.parent - when (pparent) { + when (val pparent = parent.parent) { is KtLoopExpression -> { if (expression == pparent.body) { return KtPsiFactory(expression).createExpression("continue") diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/IterateExpressionIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/IterateExpressionIntention.kt index bc8faf583c4..b979c38db61 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/IterateExpressionIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/IterateExpressionIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions @@ -36,7 +25,8 @@ import org.jetbrains.kotlin.psi.psiUtil.siblings import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.KotlinType -class IterateExpressionIntention : SelfTargetingIntention(KtExpression::class.java, "Iterate over collection"), HighPriorityAction { +class IterateExpressionIntention : SelfTargetingIntention(KtExpression::class.java, "Iterate over collection"), + HighPriorityAction { override fun isApplicableTo(element: KtExpression, caretOffset: Int): Boolean { if (element.parent !is KtBlockExpression) return false val range = element.textRange @@ -76,13 +66,12 @@ class IterateExpressionIntention : SelfTargetingIntention(KtExpres val names = if (componentFunctions.isNotEmpty()) { val collectingValidator = CollectingNameValidator(filter = nameValidator) componentFunctions.map { suggestNamesForComponent(it, project, collectingValidator) } - } - else { + } else { listOf(KotlinNameSuggester.suggestIterationVariableNames(element, elementType, bindingContext, nameValidator, "e")) } val paramPattern = (names.asSequence().singleOrNull()?.first() - ?: psiFactory.createDestructuringParameter(names.indices.joinToString(prefix = "(", postfix = ")") { "p$it" })) + ?: psiFactory.createDestructuringParameter(names.indices.joinToString(prefix = "(", postfix = ")") { "p$it" })) var forExpression = psiFactory.createExpressionByPattern("for($0 in $1) {\nx\n}", paramPattern, element) as KtForExpression forExpression = element.replaced(forExpression) diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/MovePropertyToClassBodyIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/MovePropertyToClassBodyIntention.kt index 09f30d1b17d..55d75067dc2 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/MovePropertyToClassBodyIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/MovePropertyToClassBodyIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions @@ -38,7 +27,7 @@ class MovePropertyToClassBodyIntention : SelfTargetingIntention(KtP val parentClass = PsiTreeUtil.getParentOfType(element, KtClass::class.java) ?: return val propertyDeclaration = KtPsiFactory(element) - .createProperty("${element.valOrVarKeyword?.text} ${element.name} = ${element.name}") + .createProperty("${element.valOrVarKeyword?.text} ${element.name} = ${element.name}") val firstProperty = parentClass.getProperties().firstOrNull() parentClass.addDeclarationBefore(propertyDeclaration, firstProperty).apply { @@ -48,8 +37,7 @@ class MovePropertyToClassBodyIntention : SelfTargetingIntention(KtP modifierList?.annotationEntries?.forEach { if (!it.isAppliedToProperty()) { it.delete() - } - else if (it.useSiteTarget?.getAnnotationUseSiteTarget() == AnnotationUseSiteTarget.PROPERTY) { + } else if (it.useSiteTarget?.getAnnotationUseSiteTarget() == AnnotationUseSiteTarget.PROPERTY) { it.useSiteTarget?.removeWithColon() } } @@ -57,15 +45,14 @@ class MovePropertyToClassBodyIntention : SelfTargetingIntention(KtP element.valOrVarKeyword?.delete() val parameterAnnotationsText = element.modifierList?.annotationEntries - ?.filter { it.isAppliedToConstructorParameter() } - ?.takeIf { it.isNotEmpty() } - ?.joinToString(separator = " ") { it.textWithoutUseSite() } + ?.filter { it.isAppliedToConstructorParameter() } + ?.takeIf { it.isNotEmpty() } + ?.joinToString(separator = " ") { it.textWithoutUseSite() } val hasVararg = element.hasModifier(KtTokens.VARARG_KEYWORD) if (parameterAnnotationsText != null) { element.modifierList?.replace(KtPsiFactory(element).createModifierList(parameterAnnotationsText)) - } - else { + } else { element.modifierList?.delete() } if (hasVararg) element.addModifier(KtTokens.VARARG_KEYWORD) @@ -74,10 +61,10 @@ class MovePropertyToClassBodyIntention : SelfTargetingIntention(KtP private fun KtAnnotationEntry.isAppliedToProperty(): Boolean { useSiteTarget?.getAnnotationUseSiteTarget()?.let { return it == AnnotationUseSiteTarget.FIELD - || it == AnnotationUseSiteTarget.PROPERTY - || it == AnnotationUseSiteTarget.PROPERTY_GETTER - || it == AnnotationUseSiteTarget.PROPERTY_SETTER - || it == AnnotationUseSiteTarget.SETTER_PARAMETER + || it == AnnotationUseSiteTarget.PROPERTY + || it == AnnotationUseSiteTarget.PROPERTY_GETTER + || it == AnnotationUseSiteTarget.PROPERTY_SETTER + || it == AnnotationUseSiteTarget.SETTER_PARAMETER } return !isApplicableToConstructorParameter() diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/NullableBooleanEqualityCheckToElvisIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/NullableBooleanEqualityCheckToElvisIntention.kt index 348380ed5fd..491e07749a2 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/NullableBooleanEqualityCheckToElvisIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/NullableBooleanEqualityCheckToElvisIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions @@ -26,7 +15,7 @@ import org.jetbrains.kotlin.types.TypeUtils import org.jetbrains.kotlin.types.typeUtil.isBooleanOrNullableBoolean class NullableBooleanEqualityCheckToElvisIntention : SelfTargetingIntention( - KtBinaryExpression::class.java, "Convert Boolean? == const to elvis" + KtBinaryExpression::class.java, "Convert Boolean? == const to elvis" ) { override fun isApplicableTo(element: KtBinaryExpression, caretOffset: Int): Boolean { if (element.operationToken != KtTokens.EQEQ && element.operationToken != KtTokens.EXCLEQ) return false @@ -44,8 +33,7 @@ class NullableBooleanEqualityCheckToElvisIntention : SelfTargetingIntention true diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/ObjectLiteralToLambdaIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/ObjectLiteralToLambdaIntention.kt index c994d545051..64f4e18124b 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/ObjectLiteralToLambdaIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/ObjectLiteralToLambdaIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions @@ -69,9 +58,9 @@ class ObjectLiteralToLambdaInspection : IntentionBasedInspection( - KtObjectLiteralExpression::class.java, - "Convert to lambda", - "Convert object literal to lambda" + KtObjectLiteralExpression::class.java, + "Convert to lambda", + "Convert object literal to lambda" ) { override fun applicabilityRange(element: KtObjectLiteralExpression): TextRange? { val (baseTypeRef, baseType, singleFunction) = extractData(element) ?: return null @@ -91,8 +80,9 @@ class ObjectLiteralToLambdaIntention : SelfTargetingRangeIntention { thisReference -> - context[BindingContext.REFERENCE_TARGET, thisReference.instanceReference] == containingDeclaration - }) return null + context[BindingContext.REFERENCE_TARGET, thisReference.instanceReference] == containingDeclaration + } + ) return null // Recursive call, skip labels if (ReferencesSearch.search(singleFunction, LocalSearchScope(bodyExpression)).any { it.element !is KtLabelReferenceExpression }) { @@ -100,15 +90,16 @@ class ObjectLiteralToLambdaIntention : SelfTargetingRangeIntention { expression -> - val resolvedCall = expression.getResolvedCall(context) - resolvedCall?.let { - it.dispatchReceiver.isImplicitClassFor(containingDeclaration) || - it.extensionReceiver.isImplicitClassFor(containingDeclaration) - } ?: false - }) return null + val resolvedCall = expression.getResolvedCall(context) + resolvedCall?.let { + it.dispatchReceiver.isImplicitClassFor(containingDeclaration) || it.extensionReceiver + .isImplicitClassFor(containingDeclaration) + } == true + } + ) return null return TextRange(element.objectDeclaration.getObjectKeyword()!!.startOffset, baseTypeRef.endOffset) } @@ -130,7 +121,8 @@ class ObjectLiteralToLambdaIntention : SelfTargetingRangeIntention 1 || parameters.any { parameter -> ReferencesSearch.search(parameter, LocalSearchScope(body)).any() } + val needParameters = + parameters.count() > 1 || parameters.any { parameter -> ReferencesSearch.search(parameter, LocalSearchScope(body)).any() } if (needParameters) { parameters.forEachIndexed { index, parameter -> if (index > 0) { @@ -146,13 +138,12 @@ class ObjectLiteralToLambdaIntention : SelfTargetingRangeIntention { it.tokenType == KtTokens.EOL_COMMENT } ?: false) { + if (lastCommentOwner?.anyDescendantOfType { it.tokenType == KtTokens.EOL_COMMENT } == true) { appendFixedText("\n") } appendFixedText("}") @@ -169,15 +160,16 @@ class ObjectLiteralToLambdaIntention : SelfTargetingRangeIntention(KtTypeReference::class.java, "Replace by reconstructed type"), LowPriorityAction { +class ReconstructTypeInCastOrIsIntention : + SelfTargetingOffsetIndependentIntention(KtTypeReference::class.java, "Replace by reconstructed type"), + LowPriorityAction { override fun isApplicableTo(element: KtTypeReference): Boolean { // Only user types (like Foo) are interesting val typeElement = element.typeElement as? KtUserType ?: return false diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveEmptyClassBodyIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveEmptyClassBodyIntention.kt index 0b1ce8e8a89..435d397b556 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveEmptyClassBodyIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveEmptyClassBodyIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions @@ -34,7 +23,8 @@ class RemoveEmptyClassBodyInspection : ProblemHighlightType.LIKE_UNUSED_SYMBOL } -class RemoveEmptyClassBodyIntention : SelfTargetingOffsetIndependentIntention(KtClassBody::class.java, "Redundant empty class body") { +class RemoveEmptyClassBodyIntention : + SelfTargetingOffsetIndependentIntention(KtClassBody::class.java, "Redundant empty class body") { override fun applyTo(element: KtClassBody, editor: Editor?) { val parent = element.parent diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveEmptySecondaryConstructorBodyIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveEmptySecondaryConstructorBodyIntention.kt index af046744038..1839eaa3d5e 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveEmptySecondaryConstructorBodyIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveEmptySecondaryConstructorBodyIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions @@ -25,19 +14,20 @@ import org.jetbrains.kotlin.psi.KtSecondaryConstructor @Suppress("DEPRECATION") class RemoveEmptySecondaryConstructorBodyInspection : IntentionBasedInspection( - RemoveEmptySecondaryConstructorBodyIntention::class + RemoveEmptySecondaryConstructorBodyIntention::class ), CleanupLocalInspectionTool { override fun problemHighlightType(element: KtBlockExpression): ProblemHighlightType = - ProblemHighlightType.LIKE_UNUSED_SYMBOL + ProblemHighlightType.LIKE_UNUSED_SYMBOL } -class RemoveEmptySecondaryConstructorBodyIntention : SelfTargetingOffsetIndependentIntention(KtBlockExpression::class.java, "Remove empty constructor body") { +class RemoveEmptySecondaryConstructorBodyIntention : + SelfTargetingOffsetIndependentIntention(KtBlockExpression::class.java, "Remove empty constructor body") { override fun applyTo(element: KtBlockExpression, editor: Editor?) = element.delete() override fun isApplicableTo(element: KtBlockExpression): Boolean { - if(element.parent !is KtSecondaryConstructor) return false - if(element.statements.isNotEmpty()) return false + if (element.parent !is KtSecondaryConstructor) return false + if (element.statements.isNotEmpty()) return false return element.text.replace("{", "").replace("}", "").isBlank() } diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveExplicitLambdaParameterTypesIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveExplicitLambdaParameterTypesIntention.kt index 3a369688882..1df9e55ddaf 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveExplicitLambdaParameterTypesIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveExplicitLambdaParameterTypesIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions @@ -21,7 +10,8 @@ import org.jetbrains.kotlin.psi.KtLambdaExpression import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.psiUtil.endOffset -class RemoveExplicitLambdaParameterTypesIntention : SelfTargetingIntention(KtLambdaExpression::class.java, "Remove explicit lambda parameter types (may break code)") { +class RemoveExplicitLambdaParameterTypesIntention : + SelfTargetingIntention(KtLambdaExpression::class.java, "Remove explicit lambda parameter types (may break code)") { override fun isApplicableTo(element: KtLambdaExpression, caretOffset: Int): Boolean { if (element.valueParameters.none { it.typeReference != null }) return false val arrow = element.functionLiteral.arrow ?: return false diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveExplicitSuperQualifierIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveExplicitSuperQualifierIntention.kt index 0b9aa9c93d4..f403dafe3e0 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveExplicitSuperQualifierIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveExplicitSuperQualifierIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions @@ -42,7 +31,8 @@ class RemoveExplicitSuperQualifierInspection : IntentionBasedInspection(KtSuperExpression::class.java, "Remove explicit supertype qualification") { +class RemoveExplicitSuperQualifierIntention : + SelfTargetingRangeIntention(KtSuperExpression::class.java, "Remove explicit supertype qualification") { override fun applicabilityRange(element: KtSuperExpression): TextRange? { if (element.superTypeQualifier == null) return null @@ -53,8 +43,8 @@ class RemoveExplicitSuperQualifierIntention : SelfTargetingRangeIntention(KtTypeArgumentList::class.java, "Remove explicit type arguments") { +class RemoveExplicitTypeArgumentsIntention : + SelfTargetingOffsetIndependentIntention(KtTypeArgumentList::class.java, "Remove explicit type arguments") { companion object { fun isApplicableTo(element: KtTypeArgumentList, approximateFlexible: Boolean): Boolean { @@ -71,12 +61,12 @@ class RemoveExplicitTypeArgumentsIntention : SelfTargetingOffsetIndependentInten newCallExpression.typeArgumentList!!.delete() val newBindingContext = expressionToAnalyze.analyzeInContext( - resolutionScope, - contextExpression, - trace = DelegatingBindingTrace(bindingContext, "Temporary trace"), - dataFlowInfo = bindingContext.getDataFlowInfoBefore(contextExpression), - expectedType = expectedType ?: TypeUtils.NO_EXPECTED_TYPE, - isStatement = contextExpression.isUsedAsStatement(bindingContext) + resolutionScope, + contextExpression, + trace = DelegatingBindingTrace(bindingContext, "Temporary trace"), + dataFlowInfo = bindingContext.getDataFlowInfoBefore(contextExpression), + expectedType = expectedType ?: TypeUtils.NO_EXPECTED_TYPE, + isStatement = contextExpression.isUsedAsStatement(bindingContext) ) val newCall = newCallExpression.getResolvedCall(newBindingContext) ?: return false @@ -87,8 +77,7 @@ class RemoveExplicitTypeArgumentsIntention : SelfTargetingOffsetIndependentInten fun equalTypes(type1: KotlinType, type2: KotlinType): Boolean { return if (approximateFlexible) { KotlinTypeChecker.DEFAULT.equalTypes(type1, type2) - } - else { + } else { type1 == type2 } } @@ -106,8 +95,7 @@ class RemoveExplicitTypeArgumentsIntention : SelfTargetingOffsetIndependentInten if (element is KtFunctionLiteral) continue if (!element.isUsedAsExpression(bindingContext)) return element to null - val parent = element.parent - when (parent) { + when (val parent = element.parent) { is KtNamedFunction -> { val expectedType = if (element == parent.bodyExpression && !parent.hasBlockBody() && parent.hasDeclaredReturnType()) (bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, parent] as? FunctionDescriptor)?.returnType diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveForLoopIndicesIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveForLoopIndicesIntention.kt index a32f43f28f8..d7560b6d74a 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveForLoopIndicesIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveForLoopIndicesIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2014 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions @@ -37,7 +26,8 @@ class RemoveForLoopIndicesInspection : IntentionBasedInspection override fun problemHighlightType(element: KtForExpression): ProblemHighlightType = ProblemHighlightType.LIKE_UNUSED_SYMBOL } -class RemoveForLoopIndicesIntention : SelfTargetingRangeIntention(KtForExpression::class.java, "Remove indices in 'for' loop") { +class RemoveForLoopIndicesIntention : + SelfTargetingRangeIntention(KtForExpression::class.java, "Remove indices in 'for' loop") { private val WITH_INDEX_NAME = "withIndex" private val WITH_INDEX_FQ_NAMES: Set by lazy { sequenceOf("collections", "sequences", "text", "ranges").map { "kotlin.$it.$WITH_INDEX_NAME" }.toSet() diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveSingleExpressionStringTemplateIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveSingleExpressionStringTemplateIntention.kt index 25942a04c28..b77436c2266 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveSingleExpressionStringTemplateIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveSingleExpressionStringTemplateIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions @@ -27,33 +16,33 @@ import org.jetbrains.kotlin.psi.createExpressionByPattern import org.jetbrains.kotlin.resolve.calls.callUtil.getType private fun KtStringTemplateExpression.singleExpressionOrNull() = - children.singleOrNull()?.children?.firstOrNull() as? KtExpression + children.singleOrNull()?.children?.firstOrNull() as? KtExpression class RemoveSingleExpressionStringTemplateInspection : IntentionBasedInspection( - RemoveSingleExpressionStringTemplateIntention::class, - additionalChecker = { - templateExpression -> - templateExpression.singleExpressionOrNull()?.let { - KotlinBuiltIns.isString(it.getType(it.analyze())) - } ?: false - } + RemoveSingleExpressionStringTemplateIntention::class, + additionalChecker = { templateExpression -> + templateExpression.singleExpressionOrNull()?.let { + KotlinBuiltIns.isString(it.getType(it.analyze())) + } ?: false + } ) { override val problemText = "Redundant string template" } class RemoveSingleExpressionStringTemplateIntention : SelfTargetingOffsetIndependentIntention( - KtStringTemplateExpression::class.java, - "Remove single-expression string template" + KtStringTemplateExpression::class.java, + "Remove single-expression string template" ) { override fun isApplicableTo(element: KtStringTemplateExpression) = - element.singleExpressionOrNull() != null + element.singleExpressionOrNull() != null override fun applyTo(element: KtStringTemplateExpression, editor: Editor?) { val expression = element.singleExpressionOrNull() ?: return val type = expression.getType(expression.analyze()) - val newElement = - if (KotlinBuiltIns.isString(type)) expression - else KtPsiFactory(element).createExpressionByPattern("$0.$1()", expression, "toString") + val newElement = if (KotlinBuiltIns.isString(type)) + expression + else + KtPsiFactory(element).createExpressionByPattern("$0.$1()", expression, "toString") element.replace(newElement) } } \ No newline at end of file diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/RenameFileToMatchClassIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/RenameFileToMatchClassIntention.kt index 1edbbfa0c59..54d84bf113c 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/RenameFileToMatchClassIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/RenameFileToMatchClassIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions @@ -24,7 +13,8 @@ import com.intellij.refactoring.RefactoringSettings import com.intellij.refactoring.rename.RenameProcessor import org.jetbrains.kotlin.psi.KtClassOrObject -class RenameFileToMatchClassIntention : SelfTargetingRangeIntention(KtClassOrObject::class.java, "", "Rename file to match top-level class name") { +class RenameFileToMatchClassIntention : + SelfTargetingRangeIntention(KtClassOrObject::class.java, "", "Rename file to match top-level class name") { override fun applicabilityRange(element: KtClassOrObject): TextRange? { if (!element.isTopLevel()) return null val fileName = element.containingKtFile.name @@ -39,10 +29,11 @@ class RenameFileToMatchClassIntention : SelfTargetingRangeIntention( - KtDotQualifiedExpression::class.java, - "Replace with '+='" + KtDotQualifiedExpression::class.java, + "Replace with '+='" ) { private val compatibleNames: Set by lazy { setOf("add", "addAll") } @@ -53,7 +42,11 @@ class ReplaceAddWithPlusAssignIntention : SelfTargetingOffsetIndependentIntentio } override fun applyTo(element: KtDotQualifiedExpression, editor: Editor?) { - element.replace(KtPsiFactory(element).createExpressionByPattern("$0 += $1", element.receiverExpression, - element.callExpression?.valueArguments?.get(0)?.getArgumentExpression() ?: return)) + element.replace( + KtPsiFactory(element).createExpressionByPattern( + "$0 += $1", element.receiverExpression, + element.callExpression?.valueArguments?.get(0)?.getArgumentExpression() ?: return + ) + ) } } \ No newline at end of file diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/ReplaceSizeCheckIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/ReplaceSizeCheckIntention.kt index 250ec8d750f..180f1cf2e29 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/ReplaceSizeCheckIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/ReplaceSizeCheckIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions @@ -24,7 +13,8 @@ import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtPsiFactory abstract class ReplaceSizeCheckIntention(text: String) : SelfTargetingOffsetIndependentIntention( - KtBinaryExpression::class.java, text) { + KtBinaryExpression::class.java, text +) { override fun applyTo(element: KtBinaryExpression, editor: Editor?) { val target = getTargetExpression(element) diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/ReplaceUnderscoreWithParameterNameIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/ReplaceUnderscoreWithParameterNameIntention.kt index a02877f6a26..8057dc71f4c 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/ReplaceUnderscoreWithParameterNameIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/ReplaceUnderscoreWithParameterNameIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions @@ -36,16 +25,16 @@ import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class ReplaceUnderscoreWithParameterNameIntention : SelfTargetingOffsetIndependentIntention( - KtCallableDeclaration::class.java, - "Replace '_' with parameter name" + KtCallableDeclaration::class.java, + "Replace '_' with parameter name" ) { override fun isApplicableTo(element: KtCallableDeclaration) = - element.name == "_" && (element is KtDestructuringDeclarationEntry || element is KtParameter) + element.name == "_" && (element is KtDestructuringDeclarationEntry || element is KtParameter) override fun applyTo(element: KtCallableDeclaration, editor: Editor?) { val suggestedParameterName = suggestedParameterName(element) val validator = CollectingNameValidator( - filter = NewDeclarationNameValidator(element.parent.parent, null, NewDeclarationNameValidator.Target.VARIABLES) + filter = NewDeclarationNameValidator(element.parent.parent, null, NewDeclarationNameValidator.Target.VARIABLES) ) val name = suggestedParameterName?.let { KotlinNameSuggester.suggestNameByName(it, validator) @@ -56,12 +45,11 @@ class ReplaceUnderscoreWithParameterNameIntention : SelfTargetingOffsetIndepende element.setName(name) } - private fun suggestedParameterName(element: KtCallableDeclaration) = - when (element) { - is KtDestructuringDeclarationEntry -> dataClassParameterName(element) - is KtParameter -> lambdaParameterName(element) - else -> null - } + private fun suggestedParameterName(element: KtCallableDeclaration) = when (element) { + is KtDestructuringDeclarationEntry -> dataClassParameterName(element) + is KtParameter -> lambdaParameterName(element) + else -> null + } private fun lambdaParameterName(element: KtParameter): String? { val functionLiteral = element.getParentOfType(strict = true) ?: return null @@ -91,6 +79,5 @@ class ReplaceUnderscoreWithParameterNameIntention : SelfTargetingOffsetIndepende } } - private fun KtDestructuringDeclarationEntry.entryIndex() = - parent.getChildrenOfType().indexOf(this) + private fun KtDestructuringDeclarationEntry.entryIndex() = parent.getChildrenOfType().indexOf(this) } \ No newline at end of file diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/ReplaceWithOrdinaryAssignmentIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/ReplaceWithOrdinaryAssignmentIntention.kt index 1a934a349c7..644dc828f76 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/ReplaceWithOrdinaryAssignmentIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/ReplaceWithOrdinaryAssignmentIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions @@ -24,7 +13,8 @@ import org.jetbrains.kotlin.psi.KtNameReferenceExpression import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.createExpressionByPattern -class ReplaceWithOrdinaryAssignmentIntention : SelfTargetingIntention(KtBinaryExpression::class.java, "Replace with ordinary assignment"), LowPriorityAction { +class ReplaceWithOrdinaryAssignmentIntention : + SelfTargetingIntention(KtBinaryExpression::class.java, "Replace with ordinary assignment"), LowPriorityAction { override fun isApplicableTo(element: KtBinaryExpression, caretOffset: Int): Boolean { if (element.operationToken !in KtTokens.AUGMENTED_ASSIGNMENTS) return false if (element.left !is KtNameReferenceExpression) return false diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/ReturnSaver.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/ReturnSaver.kt index 90e69112172..d590de24da6 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/ReturnSaver.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/ReturnSaver.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions @@ -59,11 +48,9 @@ class ReturnSaver(val function: KtNamedFunction) { val value = returnExpression.returnedExpression val replaceWith = if (value != null && returnExpression.isValueOfBlock(lambdaBody)) { value - } - else if (value != null) { + } else if (value != null) { factory.createExpressionByPattern("return@$0 $1", label, value) - } - else { + } else { factory.createExpressionByPattern("return@$0", label) } @@ -72,30 +59,26 @@ class ReturnSaver(val function: KtNamedFunction) { } } - private fun KtExpression.isValueOfBlock(inBlock: KtBlockExpression): Boolean { - val parent = parent - when (parent) { - inBlock -> { - return this == inBlock.statements.last() - } - - is KtBlockExpression -> { - return isValueOfBlock(parent) && parent.isValueOfBlock(inBlock) - } - - is KtContainerNode -> { - val owner = parent.parent - if (owner is KtIfExpression) { - return (this == owner.then || this == owner.`else`) && owner.isValueOfBlock(inBlock) - } - } - - is KtWhenEntry -> { - return this == parent.expression && (parent.parent as KtWhenExpression).isValueOfBlock(inBlock) - } + private fun KtExpression.isValueOfBlock(inBlock: KtBlockExpression): Boolean = when (val parent = parent) { + inBlock -> { + this == inBlock.statements.last() } - return false - } + is KtBlockExpression -> { + isValueOfBlock(parent) && parent.isValueOfBlock(inBlock) + } + is KtContainerNode -> { + val owner = parent.parent + if (owner is KtIfExpression) { + (this == owner.then || this == owner.`else`) && owner.isValueOfBlock(inBlock) + } else + false + } + + is KtWhenEntry -> { + this == parent.expression && (parent.parent as KtWhenExpression).isValueOfBlock(inBlock) + } + else -> false + } } \ No newline at end of file diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/SpecifyTypeExplicitlyInDestructuringAssignmentIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/SpecifyTypeExplicitlyInDestructuringAssignmentIntention.kt index 479c330e9fc..c012d5554df 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/SpecifyTypeExplicitlyInDestructuringAssignmentIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/SpecifyTypeExplicitlyInDestructuringAssignmentIntention.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -18,7 +18,7 @@ import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.types.isError class SpecifyTypeExplicitlyInDestructuringAssignmentIntention : SelfTargetingRangeIntention( - KtDestructuringDeclaration::class.java, "Specify all types explicitly in destructuring declaration" + KtDestructuringDeclaration::class.java, "Specify all types explicitly in destructuring declaration" ), LowPriorityAction { override fun applicabilityRange(element: KtDestructuringDeclaration): TextRange? { diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/SplitIfIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/SplitIfIntention.kt index cf9bb40b38a..40e50f90120 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/SplitIfIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/SplitIfIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions @@ -64,14 +53,14 @@ class SplitIfIntention : SelfTargetingIntention(KtExpression::clas KtTokens.OROR -> { val container = ifExpression.parent - if (container is KtBlockExpression && elseBranch == null && thenBranch.lastBlockStatementOrThis().isExitStatement()) { // special case + // special case + if (container is KtBlockExpression && elseBranch == null && thenBranch.lastBlockStatementOrThis().isExitStatement()) { val secondIf = container.addAfter(innerIf, ifExpression) container.addAfter(psiFactory.createNewLine(), ifExpression) val firstIf = ifExpression.replace(psiFactory.createIf(leftExpression, thenBranch)) commentSaver.restore(PsiChildRange(firstIf, secondIf)) return - } - else { + } else { psiFactory.createIf(leftExpression, thenBranch, innerIf) } } @@ -98,7 +87,7 @@ class SplitIfIntention : SelfTargetingIntention(KtExpression::clas private fun getFirstValidOperator(element: KtIfExpression): KtOperationReferenceExpression? { val condition = element.condition ?: return null return PsiTreeUtil.findChildrenOfType(condition, KtOperationReferenceExpression::class.java) - .firstOrNull { isOperatorValid(it) } + .firstOrNull { isOperatorValid(it) } } private fun isOperatorValid(element: KtOperationReferenceExpression): Boolean { diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/SwapBinaryExpressionIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/SwapBinaryExpressionIntention.kt index b323c61c9f1..93de2120ea3 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/SwapBinaryExpressionIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/SwapBinaryExpressionIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions @@ -28,7 +17,8 @@ import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.createExpressionByPattern import org.jetbrains.kotlin.types.expressions.OperatorConventions -class SwapBinaryExpressionIntention : SelfTargetingIntention(KtBinaryExpression::class.java, "Flip binary expression"), LowPriorityAction { +class SwapBinaryExpressionIntention : SelfTargetingIntention(KtBinaryExpression::class.java, "Flip binary expression"), + LowPriorityAction { companion object { private val SUPPORTED_OPERATIONS: Set by lazy { setOf(PLUS, MUL, OROR, ANDAND, EQEQ, EXCLEQ, EQEQEQ, EXCLEQEQEQ, GT, LT, GTEQ, LTEQ) @@ -51,7 +41,8 @@ class SwapBinaryExpressionIntention : SelfTargetingIntention val operationToken = element.operationToken val operationTokenText = opRef.text if (operationToken in SUPPORTED_OPERATIONS - || operationToken == IDENTIFIER && operationTokenText in SUPPORTED_OPERATION_NAMES) { + || operationToken == IDENTIFIER && operationTokenText in SUPPORTED_OPERATION_NAMES + ) { text = "Flip '$operationTokenText'" return true } @@ -85,7 +76,11 @@ class SwapBinaryExpressionIntention : SelfTargetingIntention return firstDescendantOfTighterPrecedence(element.right, PsiPrecedences.getPrecedence(element), KtBinaryExpression::getLeft) } - private fun firstDescendantOfTighterPrecedence(expression: KtExpression?, precedence: Int, getChild: KtBinaryExpression.() -> KtExpression?): KtExpression? { + private fun firstDescendantOfTighterPrecedence( + expression: KtExpression?, + precedence: Int, + getChild: KtBinaryExpression.() -> KtExpression? + ): KtExpression? { if (expression is KtBinaryExpression) { val expressionPrecedence = PsiPrecedences.getPrecedence(expression) if (!PsiPrecedences.isTighter(expressionPrecedence, precedence)) { diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/SwapStringEqualsIgnoreCaseIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/SwapStringEqualsIgnoreCaseIntention.kt index 37a93e74fcc..f4aa5c61f62 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/SwapStringEqualsIgnoreCaseIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/SwapStringEqualsIgnoreCaseIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions @@ -29,7 +18,8 @@ import org.jetbrains.kotlin.psi.createExpressionByPattern import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull -class SwapStringEqualsIgnoreCaseIntention : SelfTargetingRangeIntention(KtDotQualifiedExpression::class.java, "Flip 'equals'"), LowPriorityAction { +class SwapStringEqualsIgnoreCaseIntention : + SelfTargetingRangeIntention(KtDotQualifiedExpression::class.java, "Flip 'equals'"), LowPriorityAction { override fun applicabilityRange(element: KtDotQualifiedExpression): TextRange? { val descriptor = element.getCallableDescriptor() ?: return null @@ -50,10 +40,10 @@ class SwapStringEqualsIgnoreCaseIntention : SelfTargetingRangeIntention(KtWhenExpression::class.java, "Eliminate argument of 'when'"), LowPriorityAction { +class EliminateWhenSubjectIntention : + SelfTargetingIntention(KtWhenExpression::class.java, "Eliminate argument of 'when'"), LowPriorityAction { override fun isApplicableTo(element: KtWhenExpression, caretOffset: Int): Boolean { if (element.subjectExpression !is KtNameReferenceExpression) return false val lBrace = element.openBrace ?: return false @@ -47,8 +37,7 @@ class EliminateWhenSubjectIntention : SelfTargetingIntention(K if (entry.isElse) { appendFixedText("else") - } - else { + } else { appendExpressions(entry.conditions.map { it.toExpression(subject) }, separator = "||") } appendFixedText("->") diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/ElvisToIfThenIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/ElvisToIfThenIntention.kt index f8897b6b44f..680d1eb9304 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/ElvisToIfThenIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/ElvisToIfThenIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions @@ -32,7 +21,9 @@ import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.TypeUtils -class ElvisToIfThenIntention : SelfTargetingRangeIntention(KtBinaryExpression::class.java, "Replace elvis expression with 'if' expression"), LowPriorityAction { +class ElvisToIfThenIntention : + SelfTargetingRangeIntention(KtBinaryExpression::class.java, "Replace elvis expression with 'if' expression"), + LowPriorityAction { override fun applicabilityRange(element: KtBinaryExpression): TextRange? { return if (element.operationToken == KtTokens.ELVIS && element.left != null && element.right != null) element.operationReference.textRange @@ -53,14 +44,14 @@ class ElvisToIfThenIntention : SelfTargetingRangeIntention(K current = KtPsiUtil.safeDeparenthesize(current) return (current as? KtBinaryExpressionWithTypeRHS)?.takeIf { it.operationReference.getReferencedNameElementType() === KtTokens.AS_SAFE && - it.right != null + it.right != null } } private fun KtExpression.buildExpressionWithReplacedReceiver( - factory: KtPsiFactory, - newReceiver: KtExpression, - topLevel: Boolean = true + factory: KtPsiFactory, + newReceiver: KtExpression, + topLevel: Boolean = true ): KtExpression { if (this !is KtQualifiedExpression) { return newReceiver @@ -99,12 +90,11 @@ class ElvisToIfThenIntention : SelfTargetingRangeIntention(K val typeReference = leftSafeCastReceiver.right!! val factory = KtPsiFactory(element) newReceiver.isStableSimpleExpression(context) to element.convertToIfStatement( - factory.createExpressionByPattern("$0 is $1", newReceiver, typeReference), - left.buildExpressionWithReplacedReceiver(factory, newReceiver), - right + factory.createExpressionByPattern("$0 is $1", newReceiver, typeReference), + left.buildExpressionWithReplacedReceiver(factory, newReceiver), + right ) - } - else { + } else { left.isStableSimpleExpression(context) to element.convertToIfNotNullExpression(left, left, right) } diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/FoldIfToReturnAsymmetricallyIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/FoldIfToReturnAsymmetricallyIntention.kt index daaf5226bb8..6bbe4a0dea1 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/FoldIfToReturnAsymmetricallyIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/FoldIfToReturnAsymmetricallyIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions @@ -22,7 +11,8 @@ import org.jetbrains.kotlin.idea.intentions.SelfTargetingRangeIntention import org.jetbrains.kotlin.idea.intentions.branchedTransformations.BranchedFoldingUtils import org.jetbrains.kotlin.psi.* -class FoldIfToReturnAsymmetricallyIntention : SelfTargetingRangeIntention(KtIfExpression::class.java, "Replace 'if' expression with return") { +class FoldIfToReturnAsymmetricallyIntention : + SelfTargetingRangeIntention(KtIfExpression::class.java, "Replace 'if' expression with return") { override fun applicabilityRange(element: KtIfExpression): TextRange? { if (BranchedFoldingUtils.getFoldableBranchedReturn(element.then) == null || element.`else` != null) { return null diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/FoldIfToReturnIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/FoldIfToReturnIntention.kt index 992745c2447..16c62de0888 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/FoldIfToReturnIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/FoldIfToReturnIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions @@ -23,8 +12,8 @@ import org.jetbrains.kotlin.idea.intentions.branchedTransformations.BranchedFold import org.jetbrains.kotlin.psi.KtIfExpression class FoldIfToReturnIntention : SelfTargetingRangeIntention( - KtIfExpression::class.java, - "Lift return out of 'if' expression" + KtIfExpression::class.java, + "Lift return out of 'if' expression" ) { override fun applicabilityRange(element: KtIfExpression): TextRange? { diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/UnfoldAssignmentToIfIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/UnfoldAssignmentToIfIntention.kt index 0ede6b657b5..75631d8376c 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/UnfoldAssignmentToIfIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/UnfoldAssignmentToIfIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions @@ -27,7 +16,9 @@ import org.jetbrains.kotlin.psi.KtIfExpression import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.startOffset -class UnfoldAssignmentToIfIntention : SelfTargetingRangeIntention(KtBinaryExpression::class.java, "Replace assignment with 'if' expression"), LowPriorityAction { +class UnfoldAssignmentToIfIntention : + SelfTargetingRangeIntention(KtBinaryExpression::class.java, "Replace assignment with 'if' expression"), + LowPriorityAction { override fun applicabilityRange(element: KtBinaryExpression): TextRange? { if (element.operationToken !in KtTokens.ALL_ASSIGNMENTS) return null if (element.left == null) return null diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/UnfoldAssignmentToWhenIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/UnfoldAssignmentToWhenIntention.kt index 9e02849aebe..9c2995da22c 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/UnfoldAssignmentToWhenIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/UnfoldAssignmentToWhenIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions @@ -28,7 +17,9 @@ import org.jetbrains.kotlin.psi.KtWhenExpression import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.startOffset -class UnfoldAssignmentToWhenIntention : SelfTargetingRangeIntention(KtBinaryExpression::class.java, "Replace assignment with 'when' expression" ), LowPriorityAction { +class UnfoldAssignmentToWhenIntention : + SelfTargetingRangeIntention(KtBinaryExpression::class.java, "Replace assignment with 'when' expression"), + LowPriorityAction { override fun applicabilityRange(element: KtBinaryExpression): TextRange? { if (element.operationToken !in KtTokens.ALL_ASSIGNMENTS) return null if (element.left == null) return null diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/UnfoldPropertyToIfIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/UnfoldPropertyToIfIntention.kt index f7bfbc8bbc2..53c4d3c79aa 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/UnfoldPropertyToIfIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/UnfoldPropertyToIfIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions @@ -27,7 +16,9 @@ import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.startOffset -class UnfoldPropertyToIfIntention : SelfTargetingRangeIntention(KtProperty::class.java, "Replace property initializer with 'if' expression"), LowPriorityAction { +class UnfoldPropertyToIfIntention : + SelfTargetingRangeIntention(KtProperty::class.java, "Replace property initializer with 'if' expression"), + LowPriorityAction { override fun applicabilityRange(element: KtProperty): TextRange? { if (!element.isLocal) return null val initializer = element.initializer as? KtIfExpression ?: return null diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/UnfoldPropertyToWhenIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/UnfoldPropertyToWhenIntention.kt index 1c5b90a422d..bb82a621fcc 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/UnfoldPropertyToWhenIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/UnfoldPropertyToWhenIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions @@ -28,7 +17,9 @@ import org.jetbrains.kotlin.psi.KtWhenExpression import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.startOffset -class UnfoldPropertyToWhenIntention : SelfTargetingRangeIntention(KtProperty::class.java, "Replace property initializer with 'when' expression"), LowPriorityAction { +class UnfoldPropertyToWhenIntention : + SelfTargetingRangeIntention(KtProperty::class.java, "Replace property initializer with 'when' expression"), + LowPriorityAction { override fun applicabilityRange(element: KtProperty): TextRange? { if (!element.isLocal) return null val initializer = element.initializer as? KtWhenExpression ?: return null diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/WhenToIfIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/WhenToIfIntention.kt index fa41b425532..82119e6f5b6 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/WhenToIfIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/WhenToIfIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions @@ -27,7 +16,8 @@ import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.KtWhenExpression import org.jetbrains.kotlin.psi.buildExpression -class WhenToIfIntention : SelfTargetingRangeIntention(KtWhenExpression::class.java, "Replace 'when' with 'if'"), LowPriorityAction { +class WhenToIfIntention : SelfTargetingRangeIntention(KtWhenExpression::class.java, "Replace 'when' with 'if'"), + LowPriorityAction { override fun applicabilityRange(element: KtWhenExpression): TextRange? { val entries = element.entries if (entries.isEmpty()) return null @@ -50,8 +40,7 @@ class WhenToIfIntention : SelfTargetingRangeIntention(KtWhenEx val branch = entry.expression if (entry.isElse) { appendExpression(branch) - } - else { + } else { val condition = factory.combineWhenConditions(entry.conditions, element.subjectExpression) appendFixedText("if (") appendExpression(condition) diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/conventionNameCalls/ReplaceContainsIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/conventionNameCalls/ReplaceContainsIntention.kt index df03ac8aaee..f06534b62b8 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/conventionNameCalls/ReplaceContainsIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/conventionNameCalls/ReplaceContainsIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions.conventionNameCalls @@ -73,7 +62,7 @@ class ReplaceContainsIntention : SelfTargetingRangeIntention(KtDotQualifiedExpression::class.java, "Replace 'invoke' with direct call"), HighPriorityAction { +class ReplaceInvokeIntention : + SelfTargetingRangeIntention(KtDotQualifiedExpression::class.java, "Replace 'invoke' with direct call"), + HighPriorityAction { override fun applicabilityRange(element: KtDotQualifiedExpression): TextRange? { if (element.calleeName != OperatorNameConventions.INVOKE.asString() || element.callExpression?.typeArgumentList != null) return null return element.callExpression!!.calleeExpression!!.textRange diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/copyConcatenatedStringToClipboard/ConcatenatedStringGenerator.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/copyConcatenatedStringToClipboard/ConcatenatedStringGenerator.kt index 1d00844d7ad..b8f4f0dee23 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/copyConcatenatedStringToClipboard/ConcatenatedStringGenerator.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/copyConcatenatedStringToClipboard/ConcatenatedStringGenerator.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions.copyConcatenatedStringToClipboard @@ -25,7 +14,7 @@ import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class ConcatenatedStringGenerator { fun create(element: KtBinaryExpression): String { - val binaryExpression = element.getTopmostParentOfType () ?: element + val binaryExpression = element.getTopmostParentOfType() ?: element val stringBuilder = StringBuilder() binaryExpression.appendTo(stringBuilder) return stringBuilder.toString() @@ -46,8 +35,7 @@ class ConcatenatedStringGenerator { } private fun KtStringTemplateExpression.appendTo(sb: StringBuilder) { - collectDescendantsOfType().forEach { - stringTemplate -> + collectDescendantsOfType().forEach { stringTemplate -> when (stringTemplate) { is KtLiteralStringTemplateEntry -> sb.append(stringTemplate.text) is KtEscapeStringTemplateEntry -> sb.append(stringTemplate.unescapedValue) diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/copyConcatenatedStringToClipboard/CopyConcatenatedStringToClipboardIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/copyConcatenatedStringToClipboard/CopyConcatenatedStringToClipboardIntention.kt index 131ceba786e..e055a452ac0 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/copyConcatenatedStringToClipboard/CopyConcatenatedStringToClipboardIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/copyConcatenatedStringToClipboard/CopyConcatenatedStringToClipboardIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions.copyConcatenatedStringToClipboard @@ -26,7 +15,8 @@ import org.jetbrains.kotlin.psi.KtBinaryExpression import java.awt.datatransfer.StringSelection class CopyConcatenatedStringToClipboardIntention : SelfTargetingOffsetIndependentIntention( - KtBinaryExpression::class.java, "Copy concatenation text to clipboard") { + KtBinaryExpression::class.java, "Copy concatenation text to clipboard" +) { override fun applyTo(element: KtBinaryExpression, editor: Editor?) { val text = ConcatenatedStringGenerator().create(element) CopyPasteManager.getInstance().setContents(StringSelection(text)) diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/declarations/SplitPropertyDeclarationIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/declarations/SplitPropertyDeclarationIntention.kt index d4e0765dbf0..7ebe2b9f434 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/declarations/SplitPropertyDeclarationIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/declarations/SplitPropertyDeclarationIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions.declarations @@ -24,7 +13,8 @@ import org.jetbrains.kotlin.idea.intentions.splitPropertyDeclaration import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.kotlin.psi.psiUtil.startOffset -class SplitPropertyDeclarationIntention : SelfTargetingRangeIntention(KtProperty::class.java, "Split property declaration"), LowPriorityAction { +class SplitPropertyDeclarationIntention : SelfTargetingRangeIntention(KtProperty::class.java, "Split property declaration"), + LowPriorityAction { override fun applicabilityRange(element: KtProperty): TextRange? { if (!element.isLocal) return null val initializer = element.initializer ?: return null diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/LoopToCallChainInspection.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/LoopToCallChainInspection.kt index d6966ac43cb..0be095ca6fa 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/LoopToCallChainInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/LoopToCallChainInspection.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions.loopToCallChain @@ -33,41 +22,40 @@ import org.jetbrains.kotlin.psi.psiUtil.startOffset class LoopToCallChainInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession) = - object : KtVisitorVoid() { - val nonLazyIntention = LoopToCallChainIntention() - val lazyIntention = LoopToLazyCallChainIntention() + object : KtVisitorVoid() { + val nonLazyIntention = LoopToCallChainIntention() + val lazyIntention = LoopToLazyCallChainIntention() - override fun visitForExpression(expression: KtForExpression) { - super.visitForExpression(expression) + override fun visitForExpression(expression: KtForExpression) { + super.visitForExpression(expression) - val nonLazyApplicable = nonLazyIntention.applicabilityRange(expression) != null - val lazyApplicable = lazyIntention.applicabilityRange(expression) != null + val nonLazyApplicable = nonLazyIntention.applicabilityRange(expression) != null + val lazyApplicable = lazyIntention.applicabilityRange(expression) != null - if (!nonLazyApplicable && !lazyApplicable) return + if (!nonLazyApplicable && !lazyApplicable) return - val fixes = mutableListOf() - if (nonLazyApplicable) { - fixes += Fix(lazy = false, text = nonLazyIntention.text) - } - if (lazyApplicable) { - fixes += Fix(lazy = true, text = lazyIntention.text) - } - - holder.registerProblem( - expression.forKeyword, - "Loop can be replaced with stdlib operations", - ProblemHighlightType.GENERIC_ERROR_OR_WARNING, - *fixes.toTypedArray() - ) + val fixes = mutableListOf() + if (nonLazyApplicable) { + fixes += Fix(lazy = false, text = nonLazyIntention.text) } + if (lazyApplicable) { + fixes += Fix(lazy = true, text = lazyIntention.text) + } + + holder.registerProblem( + expression.forKeyword, + "Loop can be replaced with stdlib operations", + ProblemHighlightType.GENERIC_ERROR_OR_WARNING, + *fixes.toTypedArray() + ) } + } class Fix(val lazy: Boolean, val text: String = "") : LocalQuickFix { override fun getFamilyName(): String { return if (lazy) { "Replace with stdlib operations with use of 'asSequence()'" - } - else { + } else { "Replace with stdlib operations" } } @@ -81,9 +69,7 @@ class LoopToCallChainInspection : AbstractKotlinInspection() { fun applyFix(expression: KtForExpression, editor: Editor? = expression.findExistingEditor()) { val match = match(expression, lazy, true) ?: return - val result = convertLoop(expression, match) - - val offset = when (result) { + val offset = when (val result = convertLoop(expression, match)) { // if result is variable declaration, put the caret onto its name to allow quick inline is KtProperty -> result.nameIdentifier?.startOffset ?: result.startOffset else -> result.startOffset @@ -95,21 +81,21 @@ class LoopToCallChainInspection : AbstractKotlinInspection() { } class LoopToCallChainIntention : AbstractLoopToCallChainIntention( - lazy = false, - text = "Replace with stdlib operations" + lazy = false, + text = "Replace with stdlib operations" ) class LoopToLazyCallChainIntention : AbstractLoopToCallChainIntention( - lazy = true, - text = "Replace with stdlib operations with use of 'asSequence()'" + lazy = true, + text = "Replace with stdlib operations with use of 'asSequence()'" ) abstract class AbstractLoopToCallChainIntention( - private val lazy: Boolean, - text: String + private val lazy: Boolean, + text: String ) : SelfTargetingRangeIntention( - KtForExpression::class.java, - text + KtForExpression::class.java, + text ) { override fun applicabilityRange(element: KtForExpression): TextRange? { val match = match(element, lazy, false) diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/UseWithIndexIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/UseWithIndexIntention.kt index d20e0b295b3..62d4edad770 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/UseWithIndexIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/UseWithIndexIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions.loopToCallChain @@ -29,8 +18,8 @@ import org.jetbrains.kotlin.psi.createExpressionByPattern class UseWithIndexInspection : IntentionBasedInspection(UseWithIndexIntention::class) class UseWithIndexIntention : SelfTargetingRangeIntention( - KtForExpression::class.java, - "Use withIndex() instead of manual index increment" + KtForExpression::class.java, + "Use withIndex() instead of manual index increment" ) { override fun applicabilityRange(element: KtForExpression): TextRange? { return if (matchIndexToIntroduce(element, reformat = false) != null) element.forKeyword.textRange else null @@ -46,14 +35,17 @@ class UseWithIndexIntention : SelfTargetingRangeIntention( val newLoopRange = factory.createExpressionByPattern("$0.withIndex()", loopRange) loopRange.replace(newLoopRange) - val multiParameter = (factory.createExpressionByPattern("for(($0, $1) in x){}", indexVariable.nameAsSafeName, loopParameter.text) as KtForExpression).loopParameter!! + val multiParameter = (factory.createExpressionByPattern( + "for(($0, $1) in x){}", + indexVariable.nameAsSafeName, + loopParameter.text + ) as KtForExpression).loopParameter!! loopParameter.replace(multiParameter) initializationStatement.delete() if (incrementExpression.parent is KtBlockExpression) { incrementExpression.delete() - } - else { + } else { removePlusPlus(incrementExpression, true) } } diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/baseTransformations.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/baseTransformations.kt index 7d94b0321a8..dc1fca2d937 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/baseTransformations.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/baseTransformations.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions.loopToCallChain @@ -49,8 +38,8 @@ abstract class ReplaceLoopResultTransformation(final override val loop: KtForExp * Base class for [ResultTransformation]'s that replaces initialization of a variable with the result call chain */ abstract class AssignToVariableResultTransformation( - final override val loop: KtForExpression, - protected val initialization: VariableInitialization + final override val loop: KtForExpression, + protected val initialization: VariableInitialization ) : ResultTransformation { override val commentSavingRange = PsiChildRange(initialization.initializationStatement, loop.unwrapIfLabeled()) @@ -64,18 +53,18 @@ abstract class AssignToVariableResultTransformation( fun isUniqueName(name: String): Boolean { val identifier = Name.identifier(name) return resolutionScope.findVariable(identifier, NoLookupLocation.FROM_IDE) == null - && resolutionScope.findFunction(identifier, NoLookupLocation.FROM_IDE) == null - && resolutionScope.findClassifier(identifier, NoLookupLocation.FROM_IDE) == null - && resolutionScope.findPackage(identifier) == null + && resolutionScope.findFunction(identifier, NoLookupLocation.FROM_IDE) == null + && resolutionScope.findClassifier(identifier, NoLookupLocation.FROM_IDE) == null + && resolutionScope.findPackage(identifier) == null } + val uniqueName = KotlinNameSuggester.suggestNameByName("test", ::isUniqueName) val copy = initializationStatement.copied() copy.initializer!!.replace(resultCallChain) copy.setName(uniqueName) copy - } - else { + } else { psiFactory.createExpressionByPattern("$0 = $1", initialization.variable.nameAsSafeName, resultCallChain, reformat = false) } } @@ -111,7 +100,7 @@ abstract class AssignToVariableResultTransformation( companion object { fun createDelegated(delegate: ResultTransformation, initialization: VariableInitialization): AssignToVariableResultTransformation { - return object: AssignToVariableResultTransformation(delegate.loop, initialization) { + return object : AssignToVariableResultTransformation(delegate.loop, initialization) { override val presentation: String get() = delegate.presentation @@ -130,8 +119,8 @@ abstract class AssignToVariableResultTransformation( * [ResultTransformation] that replaces initialization of a variable with the call chain produced by the given [SequenceTransformation] */ class AssignSequenceResultTransformation( - private val sequenceTransformation: SequenceTransformation, - initialization: VariableInitialization + private val sequenceTransformation: SequenceTransformation, + initialization: VariableInitialization ) : AssignToVariableResultTransformation(sequenceTransformation.loop, initialization) { override val presentation: String diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/commonUtils.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/commonUtils.kt index ddc2b2b4047..12ea9b78547 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/commonUtils.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/commonUtils.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions.loopToCallChain @@ -45,11 +34,9 @@ fun KtExpression.isConstant(): Boolean { return ConstantExpressionEvaluator.getConstant(this, bindingContext) != null } -fun KtExpression?.isTrueConstant() - = this != null && node?.elementType == KtNodeTypes.BOOLEAN_CONSTANT && text == "true" +fun KtExpression?.isTrueConstant() = this != null && node?.elementType == KtNodeTypes.BOOLEAN_CONSTANT && text == "true" -fun KtExpression?.isFalseConstant() - = this != null && node?.elementType == KtNodeTypes.BOOLEAN_CONSTANT && text == "false" +fun KtExpression?.isFalseConstant() = this != null && node?.elementType == KtNodeTypes.BOOLEAN_CONSTANT && text == "false" private val ZERO_VALUES = setOf(0, 0L, 0f, 0.0) @@ -137,8 +124,7 @@ fun KtExpressionWithLabel.targetLoop(): KtLoopExpression? { val label = getTargetLabel() return if (label == null) { parents.firstIsInstance() - } - else { + } else { //TODO: does PARTIAL always work here? analyze(BodyResolveMode.PARTIAL)[BindingContext.LABEL_TARGET, label] as? KtLoopExpression } diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/interfaces.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/interfaces.kt index 97604d34fc9..9a68ad69d7e 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/interfaces.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/interfaces.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions.loopToCallChain @@ -96,20 +85,20 @@ interface ResultTransformation : Transformation { * Represents a state when matching a part of the loop against known transformations */ data class MatchingState( - val outerLoop: KtForExpression, - val innerLoop: KtForExpression, - val statements: List, - val inputVariable: KtCallableDeclaration, - /** - * Matchers can assume that indexVariable is null if it's not used in the rest of the loop - */ - val indexVariable: KtCallableDeclaration?, - val lazySequence: Boolean, - val pseudocodeProvider: () -> Pseudocode, - val reformat: Boolean, - val initializationStatementsToDelete: Collection = emptyList(), - val previousTransformations: MutableList = arrayListOf(), - val incrementExpressions: Collection = emptyList() + val outerLoop: KtForExpression, + val innerLoop: KtForExpression, + val statements: List, + val inputVariable: KtCallableDeclaration, + /** + * Matchers can assume that indexVariable is null if it's not used in the rest of the loop + */ + val indexVariable: KtCallableDeclaration?, + val lazySequence: Boolean, + val pseudocodeProvider: () -> Pseudocode, + val reformat: Boolean, + val initializationStatementsToDelete: Collection = emptyList(), + val previousTransformations: MutableList = arrayListOf(), + val incrementExpressions: Collection = emptyList() ) interface TransformationMatcher { @@ -151,9 +140,12 @@ sealed class TransformationMatch(val sequenceTransformations: List) : TransformationMatch(sequenceTransformations) { - constructor(resultTransformation: ResultTransformation, vararg sequenceTransformations: SequenceTransformation) - : this(resultTransformation, sequenceTransformations.asList()) + class Result(val resultTransformation: ResultTransformation, sequenceTransformations: List) : + TransformationMatch(sequenceTransformations) { + constructor(resultTransformation: ResultTransformation, vararg sequenceTransformations: SequenceTransformation) : this( + resultTransformation, + sequenceTransformations.asList() + ) override val allTransformations = sequenceTransformations + resultTransformation } @@ -195,32 +187,31 @@ class CommentSavingRangeHolder(range: PsiChildRange) { element == range.first -> { val newFirst = element - .siblings(forward = true, withItself = false) - .takeWhile { it != range.last!!.nextSibling } - .firstOrNull { it !is PsiWhiteSpace } + .siblings(forward = true, withItself = false) + .takeWhile { it != range.last!!.nextSibling } + .firstOrNull { it !is PsiWhiteSpace } range = if (newFirst != null) { PsiChildRange(newFirst, range.last) - } - else { + } else { PsiChildRange.EMPTY } } element == range.last -> { val newLast = element - .siblings(forward = false, withItself = false) - .takeWhile { it != range.first!!.prevSibling } - .firstOrNull { it !is PsiWhiteSpace } + .siblings(forward = false, withItself = false) + .takeWhile { it != range.first!!.prevSibling } + .firstOrNull { it !is PsiWhiteSpace } range = if (newLast != null) { PsiChildRange(range.first, newLast) - } - else { + } else { PsiChildRange.EMPTY } } } } - private fun PsiElement.siblingsBefore() = if (prevSibling != null) PsiChildRange(parent.firstChild, prevSibling) else PsiChildRange.EMPTY + private fun PsiElement.siblingsBefore() = + if (prevSibling != null) PsiChildRange(parent.firstChild, prevSibling) else PsiChildRange.EMPTY } diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/matchAndConvert.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/matchAndConvert.kt index 82dc02c12d3..e8c28241e11 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/matchAndConvert.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/matchAndConvert.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions.loopToCallChain @@ -39,23 +28,23 @@ import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode object MatcherRegistrar { val matchers: Collection = listOf( - FindTransformationMatcher, - AddToCollectionTransformation.Matcher, - CountTransformation.Matcher, - SumTransformationBase.Matcher, - MaxOrMinTransformation.Matcher, - IntroduceIndexMatcher, - FilterTransformationBase.Matcher, - MapTransformation.Matcher, - FlatMapTransformation.Matcher, - ForEachTransformation.Matcher + FindTransformationMatcher, + AddToCollectionTransformation.Matcher, + CountTransformation.Matcher, + SumTransformationBase.Matcher, + MaxOrMinTransformation.Matcher, + IntroduceIndexMatcher, + FilterTransformationBase.Matcher, + MapTransformation.Matcher, + FlatMapTransformation.Matcher, + ForEachTransformation.Matcher ) } data class MatchResult( - val sequenceExpression: KtExpression, - val transformationMatch: TransformationMatch.Result, - val initializationStatementsToDelete: Collection + val sequenceExpression: KtExpression, + val transformationMatch: TransformationMatch.Result, + val initializationStatementsToDelete: Collection ) //TODO: loop which is already over Sequence @@ -78,7 +67,8 @@ fun match(loop: KtForExpression, useLazySequence: Boolean, reformat: Boolean): M state = state.copy(indexVariable = null) } - val restContainsEmbeddedBreakOrContinue = loopContainsEmbeddedBreakOrContinue && state.statements.any { it.containsEmbeddedBreakOrContinue() } + val restContainsEmbeddedBreakOrContinue = + loopContainsEmbeddedBreakOrContinue && state.statements.any { it.containsEmbeddedBreakOrContinue() } MatchersLoop@ for (matcher in MatcherRegistrar.matchers) { @@ -95,7 +85,8 @@ fun match(loop: KtForExpression, useLazySequence: Boolean, reformat: Boolean): M if (matcher.shouldUseInputVariables && !state.inputVariable.hasDifferentSetsOfUsages(state.statements, newState.statements) - && !(state.indexVariable?.hasDifferentSetsOfUsages(state.statements, newState.statements) ?: false)) { + && !(state.indexVariable?.hasDifferentSetsOfUsages(state.statements, newState.statements) ?: false) + ) { // matched part of the loop uses neither input variable nor index variable continue@MatchersLoop } @@ -129,7 +120,8 @@ fun match(loop: KtForExpression, useLazySequence: Boolean, reformat: Boolean): M val sequenceTransformations = result.sequenceTransformations val resultTransformation = result.resultTransformation if (sequenceTransformations.isEmpty() && !resultTransformation.lazyMakesSense - || sequenceTransformations.size == 1 && resultTransformation is AssignToListTransformation) { + || sequenceTransformations.size == 1 && resultTransformation is AssignToListTransformation + ) { return null // it makes no sense to use lazy sequence if no intermediate sequences produced } val asSequence = AsSequenceTransformation(loop) @@ -138,7 +130,7 @@ fun match(loop: KtForExpression, useLazySequence: Boolean, reformat: Boolean): M return MatchResult(sequenceExpression, result, state.initializationStatementsToDelete) - .takeIf { checkSmartCastsPreserved(loop, it) } + .takeIf { checkSmartCastsPreserved(loop, it) } } } } @@ -175,9 +167,10 @@ fun convertLoop(loop: KtForExpression, matchResult: MatchResult): KtExpression { } data class LoopData( - val inputVariable: KtCallableDeclaration, - val indexVariable: KtCallableDeclaration?, - val sequenceExpression: KtExpression) + val inputVariable: KtCallableDeclaration, + val indexVariable: KtCallableDeclaration?, + val sequenceExpression: KtExpression +) private fun extractLoopData(loop: KtForExpression): LoopData? { val loopRange = loop.loopRange ?: return null @@ -201,11 +194,11 @@ private fun extractLoopData(loop: KtForExpression): LoopData? { } private fun createInitialMatchingState( - loop: KtForExpression, - inputVariable: KtCallableDeclaration, - indexVariable: KtCallableDeclaration?, - useLazySequence: Boolean, - reformat: Boolean + loop: KtForExpression, + inputVariable: KtCallableDeclaration, + indexVariable: KtCallableDeclaration?, + useLazySequence: Boolean, + reformat: Boolean ): MatchingState? { val pseudocodeProvider: () -> Pseudocode = object : () -> Pseudocode { @@ -219,14 +212,14 @@ private fun createInitialMatchingState( } return MatchingState( - outerLoop = loop, - innerLoop = loop, - statements = listOf(loop.body ?: return null), - inputVariable = inputVariable, - indexVariable = indexVariable, - lazySequence = useLazySequence, - pseudocodeProvider = pseudocodeProvider, - reformat = reformat + outerLoop = loop, + innerLoop = loop, + statements = listOf(loop.body ?: return null), + inputVariable = inputVariable, + indexVariable = indexVariable, + lazySequence = useLazySequence, + pseudocodeProvider = pseudocodeProvider, + reformat = reformat ) } @@ -302,8 +295,7 @@ private fun checkSmartCastsPreserved(loop: KtForExpression, matchResult: MatchRe if (!tryChangeAndCheckErrors(loop) { it.replace(expression) }) return false return true - } - finally { + } finally { storedUserData.forEach { it.set(null) } if (smartCastCount > 0) { loop.forEachDescendantOfType { @@ -317,7 +309,7 @@ private fun checkSmartCastsPreserved(loop: KtForExpression, matchResult: MatchRe private fun MatchResult.generateCallChain(loop: KtForExpression, reformat: Boolean): KtExpression { var sequenceTransformations = transformationMatch.sequenceTransformations var resultTransformation = transformationMatch.resultTransformation - while(true) { + while (true) { val last = sequenceTransformations.lastOrNull() ?: break resultTransformation = resultTransformation.mergeWithPrevious(last, reformat) ?: break sequenceTransformations = sequenceTransformations.dropLast(1) @@ -357,7 +349,7 @@ private fun mergeTransformations(match: TransformationMatch.Result, reformat: Bo var anyChange: Boolean do { anyChange = false - for (index in 0..transformations.lastIndex - 1) { + for (index in 0 until transformations.lastIndex) { val transformation = transformations[index] as SequenceTransformation val next = transformations[index + 1] val merged = next.mergeWithPrevious(transformation, reformat) ?: continue @@ -366,16 +358,19 @@ private fun mergeTransformations(match: TransformationMatch.Result, reformat: Bo anyChange = true break } - } while(anyChange) + } while (anyChange) @Suppress("UNCHECKED_CAST") - return TransformationMatch.Result(transformations.last() as ResultTransformation, transformations.dropLast(1) as List) + return TransformationMatch.Result( + transformations.last() as ResultTransformation, + transformations.dropLast(1) as List + ) } data class IntroduceIndexData( - val indexVariable: KtCallableDeclaration, - val initializationStatement: KtExpression, - val incrementExpression: KtUnaryExpression + val indexVariable: KtCallableDeclaration, + val initializationStatement: KtExpression, + val incrementExpression: KtUnaryExpression ) fun matchIndexToIntroduce(loop: KtForExpression, reformat: Boolean): IntroduceIndexData? { @@ -383,7 +378,8 @@ fun matchIndexToIntroduce(loop: KtForExpression, reformat: Boolean): IntroduceIn val (inputVariable, indexVariable) = extractLoopData(loop) ?: return null if (indexVariable != null) return null // loop is already with "withIndex" - val state = createInitialMatchingState(loop, inputVariable, indexVariable, useLazySequence = false, reformat = reformat)?.unwrapBlock() ?: return null + val state = createInitialMatchingState(loop, inputVariable, indexVariable, useLazySequence = false, reformat = reformat)?.unwrapBlock() + ?: return null val match = IntroduceIndexMatcher.match(state) ?: return null assert(match.sequenceTransformations.isEmpty()) diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/result/AddToCollectionTransformation.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/result/AddToCollectionTransformation.kt index c47015f59ed..f59a6587d5f 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/result/AddToCollectionTransformation.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/result/AddToCollectionTransformation.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions.loopToCallChain.result @@ -36,33 +25,37 @@ import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.descriptorUtil.overriddenTreeUniqueAsSequence class AddToCollectionTransformation( - loop: KtForExpression, - private val targetCollection: KtExpression + loop: KtForExpression, + private val targetCollection: KtExpression ) : ReplaceLoopResultTransformation(loop) { - override fun mergeWithPrevious(previousTransformation: SequenceTransformation, reformat: Boolean): ResultTransformation? { - return when (previousTransformation) { - is FilterTransformation -> { - FilterToTransformation.create( - loop, previousTransformation.inputVariable, previousTransformation.indexVariable, - targetCollection, previousTransformation.effectiveCondition, previousTransformation.isFilterNot) - } + override fun mergeWithPrevious(previousTransformation: SequenceTransformation, reformat: Boolean): ResultTransformation? = + when (previousTransformation) { + is FilterTransformation -> FilterToTransformation.create( + loop, previousTransformation.inputVariable, previousTransformation.indexVariable, + targetCollection, previousTransformation.effectiveCondition, previousTransformation.isFilterNot + ) - is FilterNotNullTransformation -> { - FilterNotNullToTransformation.create(loop, targetCollection) - } + is FilterNotNullTransformation -> FilterNotNullToTransformation.create(loop, targetCollection) - is MapTransformation -> { - MapToTransformation.create(loop, previousTransformation.inputVariable, previousTransformation.indexVariable, targetCollection, previousTransformation.mapping, previousTransformation.mapNotNull) - } + is MapTransformation -> MapToTransformation.create( + loop, + previousTransformation.inputVariable, + previousTransformation.indexVariable, + targetCollection, + previousTransformation.mapping, + previousTransformation.mapNotNull + ) - is FlatMapTransformation -> { - FlatMapToTransformation.create(loop, previousTransformation.inputVariable, targetCollection, previousTransformation.transform) - } + is FlatMapTransformation -> FlatMapToTransformation.create( + loop, + previousTransformation.inputVariable, + targetCollection, + previousTransformation.transform + ) else -> null } - } override val presentation: String get() = "+=" @@ -79,8 +72,8 @@ class AddToCollectionTransformation( override fun generateCode(chainedCallGenerator: ChainedCallGenerator): KtExpression { return KtPsiFactory(loop).createExpressionByPattern( - "$0 += $1", targetCollection, chainedCallGenerator.receiver, - reformat = chainedCallGenerator.reformat + "$0 += $1", targetCollection, chainedCallGenerator.receiver, + reformat = chainedCallGenerator.reformat ) } @@ -114,29 +107,32 @@ class AddToCollectionTransformation( if (state.indexVariable == null) { matchWithCollectionInitializationReplacement(state, targetCollection, argumentValue) - ?.let { return it } + ?.let { return it } } return if (state.indexVariable == null && argumentValue.isVariableReference(state.inputVariable)) { TransformationMatch.Result(AddToCollectionTransformation(state.outerLoop, targetCollection)) - } - else { + } else { if (state.outerLoop.loopRange.isRangeLiteral()) null else { //TODO: recognize "?: continue" in the argument - TransformationMatch.Result(MapToTransformation.create( - state.outerLoop, state.inputVariable, state.indexVariable, targetCollection, argumentValue, mapNotNull = false)) + TransformationMatch.Result( + MapToTransformation.create( + state.outerLoop, state.inputVariable, state.indexVariable, targetCollection, argumentValue, mapNotNull = false + ) + ) } } } private fun matchWithCollectionInitializationReplacement( - state: MatchingState, - targetCollection: KtExpression, - addOperationArgument: KtExpression + state: MatchingState, + targetCollection: KtExpression, + addOperationArgument: KtExpression ): TransformationMatch.Result? { - val collectionInitialization = targetCollection.findVariableInitializationBeforeLoop(state.outerLoop, checkNoOtherUsagesInLoop = true) ?: return null + val collectionInitialization = + targetCollection.findVariableInitializationBeforeLoop(state.outerLoop, checkNoOtherUsagesInLoop = true) ?: return null val collectionKind = collectionInitialization.initializer.isSimpleCollectionInstantiation() ?: return null val argumentIsInputVariable = addOperationArgument.isVariableReference(state.inputVariable) when (collectionKind) { @@ -146,14 +142,14 @@ class AddToCollectionTransformation( return if (argumentIsInputVariable) { val assignToList = AssignToListTransformation(state.outerLoop, collectionInitialization, state.lazySequence) TransformationMatch.Result(assignToList) - } - else { - val mapTransformation = MapTransformation(state.outerLoop, state.inputVariable, null, addOperationArgument, mapNotNull = false) + } else { + val mapTransformation = + MapTransformation(state.outerLoop, state.inputVariable, null, addOperationArgument, mapNotNull = false) if (state.lazySequence) { - val assignToList = AssignToListTransformation(state.outerLoop, collectionInitialization, lazySequence = true) + val assignToList = + AssignToListTransformation(state.outerLoop, collectionInitialization, lazySequence = true) TransformationMatch.Result(assignToList, mapTransformation) - } - else { + } else { val assignSequence = AssignSequenceResultTransformation(mapTransformation, collectionInitialization) TransformationMatch.Result(assignSequence) } @@ -184,9 +180,9 @@ class AddToCollectionTransformation( return if (argumentIsInputVariable) { TransformationMatch.Result(assignToSetTransformation) - } - else { - val mapTransformation = MapTransformation(state.outerLoop, state.inputVariable, null, addOperationArgument, mapNotNull = false) + } else { + val mapTransformation = + MapTransformation(state.outerLoop, state.inputVariable, null, addOperationArgument, mapNotNull = false) TransformationMatch.Result(assignToSetTransformation, mapTransformation) } } @@ -195,9 +191,14 @@ class AddToCollectionTransformation( return null } - private fun canChangeInitializerType(initialization: VariableInitialization, newTypeFqName: FqName, loop: KtForExpression): Boolean { + private fun canChangeInitializerType( + initialization: VariableInitialization, + newTypeFqName: FqName, + loop: KtForExpression + ): Boolean { val currentType = (initialization.variable.unsafeResolveToDescriptor() as VariableDescriptor).type - if ((currentType.constructor.declarationDescriptor as? ClassDescriptor)?.importableFqName == newTypeFqName) return true // already of the required type + // already of the required type + if ((currentType.constructor.declarationDescriptor as? ClassDescriptor)?.importableFqName == newTypeFqName) return true // we do not change explicit type if (initialization.variable.typeReference != null) return false @@ -224,12 +225,12 @@ private fun DeclarationDescriptor.isCollectionAdd(): Boolean { } class FilterToTransformation private constructor( - loop: KtForExpression, - private val inputVariable: KtCallableDeclaration, - private val indexVariable: KtCallableDeclaration?, - private val targetCollection: KtExpression, - private val effectiveCondition: Condition, - private val isFilterNot: Boolean + loop: KtForExpression, + private val inputVariable: KtCallableDeclaration, + private val indexVariable: KtCallableDeclaration?, + private val targetCollection: KtExpression, + private val effectiveCondition: Condition, + private val isFilterNot: Boolean ) : ReplaceLoopResultTransformation(loop) { init { @@ -252,25 +253,29 @@ class FilterToTransformation private constructor( val lambda = if (indexVariable != null) generateLambda(inputVariable, indexVariable, effectiveCondition.asExpression(reformat), reformat) else - generateLambda(inputVariable, if (isFilterNot) effectiveCondition.asNegatedExpression(reformat) else effectiveCondition.asExpression(reformat), reformat) + generateLambda( + inputVariable, + if (isFilterNot) effectiveCondition.asNegatedExpression(reformat) else effectiveCondition.asExpression(reformat), + reformat + ) return chainedCallGenerator.generate("$functionName($0) $1:'{}'", targetCollection, lambda) } companion object { fun create( - loop: KtForExpression, - inputVariable: KtCallableDeclaration, - indexVariable: KtCallableDeclaration?, - targetCollection: KtExpression, - condition: Condition, - isFilterNot: Boolean + loop: KtForExpression, + inputVariable: KtCallableDeclaration, + indexVariable: KtCallableDeclaration?, + targetCollection: KtExpression, + condition: Condition, + isFilterNot: Boolean ): ResultTransformation { val initialization = targetCollection.findVariableInitializationBeforeLoop(loop, checkNoOtherUsagesInLoop = true) return if (initialization != null && initialization.initializer.hasNoSideEffect()) { - val transformation = FilterToTransformation(loop, inputVariable, indexVariable, initialization.initializer, condition, isFilterNot) + val transformation = + FilterToTransformation(loop, inputVariable, indexVariable, initialization.initializer, condition, isFilterNot) AssignToVariableResultTransformation.createDelegated(transformation, initialization) - } - else { + } else { FilterToTransformation(loop, inputVariable, indexVariable, targetCollection, condition, isFilterNot) } } @@ -278,8 +283,8 @@ class FilterToTransformation private constructor( } class FilterNotNullToTransformation private constructor( - loop: KtForExpression, - private val targetCollection: KtExpression + loop: KtForExpression, + private val targetCollection: KtExpression ) : ReplaceLoopResultTransformation(loop) { override val presentation: String @@ -291,15 +296,14 @@ class FilterNotNullToTransformation private constructor( companion object { fun create( - loop: KtForExpression, - targetCollection: KtExpression + loop: KtForExpression, + targetCollection: KtExpression ): ResultTransformation { val initialization = targetCollection.findVariableInitializationBeforeLoop(loop, checkNoOtherUsagesInLoop = true) return if (initialization != null && initialization.initializer.hasNoSideEffect()) { val transformation = FilterNotNullToTransformation(loop, initialization.initializer) AssignToVariableResultTransformation.createDelegated(transformation, initialization) - } - else { + } else { FilterNotNullToTransformation(loop, targetCollection) } } @@ -307,12 +311,12 @@ class FilterNotNullToTransformation private constructor( } class MapToTransformation private constructor( - loop: KtForExpression, - private val inputVariable: KtCallableDeclaration, - private val indexVariable: KtCallableDeclaration?, - private val targetCollection: KtExpression, - private val mapping: KtExpression, - mapNotNull: Boolean + loop: KtForExpression, + private val inputVariable: KtCallableDeclaration, + private val indexVariable: KtCallableDeclaration?, + private val targetCollection: KtExpression, + private val mapping: KtExpression, + mapNotNull: Boolean ) : ReplaceLoopResultTransformation(loop) { private val functionName = if (indexVariable != null) @@ -330,19 +334,19 @@ class MapToTransformation private constructor( companion object { fun create( - loop: KtForExpression, - inputVariable: KtCallableDeclaration, - indexVariable: KtCallableDeclaration?, - targetCollection: KtExpression, - mapping: KtExpression, - mapNotNull: Boolean + loop: KtForExpression, + inputVariable: KtCallableDeclaration, + indexVariable: KtCallableDeclaration?, + targetCollection: KtExpression, + mapping: KtExpression, + mapNotNull: Boolean ): ResultTransformation { val initialization = targetCollection.findVariableInitializationBeforeLoop(loop, checkNoOtherUsagesInLoop = true) return if (initialization != null && initialization.initializer.hasNoSideEffect()) { - val transformation = MapToTransformation(loop, inputVariable, indexVariable, initialization.initializer, mapping, mapNotNull) + val transformation = + MapToTransformation(loop, inputVariable, indexVariable, initialization.initializer, mapping, mapNotNull) AssignToVariableResultTransformation.createDelegated(transformation, initialization) - } - else { + } else { MapToTransformation(loop, inputVariable, indexVariable, targetCollection, mapping, mapNotNull) } } @@ -350,10 +354,10 @@ class MapToTransformation private constructor( } class FlatMapToTransformation private constructor( - loop: KtForExpression, - private val inputVariable: KtCallableDeclaration, - private val targetCollection: KtExpression, - private val transform: KtExpression + loop: KtForExpression, + private val inputVariable: KtCallableDeclaration, + private val targetCollection: KtExpression, + private val transform: KtExpression ) : ReplaceLoopResultTransformation(loop) { override val presentation: String @@ -371,17 +375,16 @@ class FlatMapToTransformation private constructor( companion object { fun create( - loop: KtForExpression, - inputVariable: KtCallableDeclaration, - targetCollection: KtExpression, - transform: KtExpression + loop: KtForExpression, + inputVariable: KtCallableDeclaration, + targetCollection: KtExpression, + transform: KtExpression ): ResultTransformation { val initialization = targetCollection.findVariableInitializationBeforeLoop(loop, checkNoOtherUsagesInLoop = true) return if (initialization != null && initialization.initializer.hasNoSideEffect()) { val transformation = FlatMapToTransformation(loop, inputVariable, initialization.initializer, transform) AssignToVariableResultTransformation.createDelegated(transformation, initialization) - } - else { + } else { FlatMapToTransformation(loop, inputVariable, targetCollection, transform) } } @@ -389,9 +392,9 @@ class FlatMapToTransformation private constructor( } class AssignToListTransformation( - loop: KtForExpression, - initialization: VariableInitialization, - private val lazySequence: Boolean + loop: KtForExpression, + initialization: VariableInitialization, + private val lazySequence: Boolean ) : AssignToVariableResultTransformation(loop, initialization) { override val presentation: String @@ -409,8 +412,8 @@ class AssignToListTransformation( } class AssignToMutableListTransformation( - loop: KtForExpression, - initialization: VariableInitialization + loop: KtForExpression, + initialization: VariableInitialization ) : AssignToVariableResultTransformation(loop, initialization) { override val presentation: String @@ -422,8 +425,8 @@ class AssignToMutableListTransformation( } class AssignToSetTransformation( - loop: KtForExpression, - initialization: VariableInitialization + loop: KtForExpression, + initialization: VariableInitialization ) : AssignToVariableResultTransformation(loop, initialization) { override val presentation: String @@ -435,8 +438,8 @@ class AssignToSetTransformation( } class AssignToMutableSetTransformation( - loop: KtForExpression, - initialization: VariableInitialization + loop: KtForExpression, + initialization: VariableInitialization ) : AssignToVariableResultTransformation(loop, initialization) { override val presentation: String diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/result/CountTransformation.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/result/CountTransformation.kt index c47c7f3ca70..e9de0d29b9d 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/result/CountTransformation.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/result/CountTransformation.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions.loopToCallChain.result @@ -23,10 +12,10 @@ import org.jetbrains.kotlin.idea.intentions.loopToCallChain.sequence.FilterTrans import org.jetbrains.kotlin.psi.* class CountTransformation( - loop: KtForExpression, - private val inputVariable: KtCallableDeclaration, - initialization: VariableInitialization, - private val filter: KtExpression? + loop: KtForExpression, + private val inputVariable: KtCallableDeclaration, + initialization: VariableInitialization, + private val filter: KtExpression? ) : AssignToVariableResultTransformation(loop, initialization) { override fun mergeWithPrevious(previousTransformation: SequenceTransformation, reformat: Boolean): ResultTransformation? { @@ -35,8 +24,10 @@ class CountTransformation( val newFilter = if (filter == null) previousTransformation.effectiveCondition.asExpression(reformat) else - KtPsiFactory(filter).createExpressionByPattern("$0 && $1", previousTransformation.effectiveCondition.asExpression(reformat), filter, - reformat = reformat) + KtPsiFactory(filter).createExpressionByPattern( + "$0 && $1", previousTransformation.effectiveCondition.asExpression(reformat), filter, + reformat = reformat + ) return CountTransformation(loop, previousTransformation.inputVariable, initialization, newFilter) } @@ -48,15 +39,13 @@ class CountTransformation( val call = if (filter != null) { val lambda = generateLambda(inputVariable, filter, reformat) chainedCallGenerator.generate("count $0:'{}'", lambda) - } - else { + } else { chainedCallGenerator.generate("count()") } return if (initialization.initializer.isZeroConstant()) { call - } - else { + } else { KtPsiFactory(call).createExpressionByPattern("$0 + $1", initialization.initializer, call, reformat = reformat) } } @@ -78,9 +67,11 @@ class CountTransformation( override fun match(state: MatchingState): TransformationMatch.Result? { val operand = state.statements.singleOrNull()?.isPlusPlusOf() ?: return null - val initialization = operand.findVariableInitializationBeforeLoop(state.outerLoop, checkNoOtherUsagesInLoop = true) ?: return null + val initialization = + operand.findVariableInitializationBeforeLoop(state.outerLoop, checkNoOtherUsagesInLoop = true) ?: return null - if (initialization.variable.countUsages(state.outerLoop) != 1) return null // this should be the only usage of this variable inside the loop + // this should be the only usage of this variable inside the loop + if (initialization.variable.countUsages(state.outerLoop) != 1) return null val variableType = initialization.variable.resolveToDescriptorIfAny()?.type ?: return null if (!KotlinBuiltIns.isInt(variableType)) return null diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/result/FindTransformationMatcher.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/result/FindTransformationMatcher.kt index 99f54980004..823afadd65b 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/result/FindTransformationMatcher.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/result/FindTransformationMatcher.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions.loopToCallChain.result @@ -65,7 +54,8 @@ object FindTransformationMatcher : TransformationMatcher { matchReturn(state, filterTransformation)?.let { return it } when (state.statements.size) { - 1 -> { } + 1 -> { + } 2 -> { val breakExpression = state.statements.last() as? KtBreakExpression ?: return null @@ -83,17 +73,19 @@ object FindTransformationMatcher : TransformationMatcher { val initialization = left.findVariableInitializationBeforeLoop(state.outerLoop, checkNoOtherUsagesInLoop = true) ?: return null - if (initialization.variable.countUsages(state.outerLoop) != 1) return null // this should be the only usage of this variable inside the loop + // this should be the only usage of this variable inside the loop + if (initialization.variable.countUsages(state.outerLoop) != 1) return null // we do not try to convert anything if the initializer is not compile-time constant because of possible side-effects if (!initialization.initializer.isConstant()) return null - val generator = buildFindOperationGenerator(state.outerLoop, state.inputVariable, state.indexVariable, filterTransformation, - valueIfFound = right, - valueIfNotFound = initialization.initializer, - findFirst = findFirst, - reformat = state.reformat) - ?: return null + val generator = buildFindOperationGenerator( + state.outerLoop, state.inputVariable, state.indexVariable, filterTransformation, + valueIfFound = right, + valueIfNotFound = initialization.initializer, + findFirst = findFirst, + reformat = state.reformat + ) ?: return null val transformation = FindAndAssignTransformation(state.outerLoop, generator, initialization) return TransformationMatch.Result(transformation) @@ -107,22 +99,23 @@ object FindTransformationMatcher : TransformationMatcher { val returnValueInLoop = returnInLoop.returnedExpression ?: return null val returnValueAfterLoop = returnAfterLoop.returnedExpression ?: return null - val generator = buildFindOperationGenerator(state.outerLoop, state.inputVariable, state.indexVariable, - filterTransformation, - valueIfFound = returnValueInLoop, - valueIfNotFound = returnValueAfterLoop, - findFirst = true, - reformat = state.reformat) - ?: return null + val generator = buildFindOperationGenerator( + state.outerLoop, state.inputVariable, state.indexVariable, + filterTransformation, + valueIfFound = returnValueInLoop, + valueIfNotFound = returnValueAfterLoop, + findFirst = true, + reformat = state.reformat + ) ?: return null val transformation = FindAndReturnTransformation(state.outerLoop, generator, returnAfterLoop) return TransformationMatch.Result(transformation) } private class FindAndReturnTransformation( - override val loop: KtForExpression, - private val generator: FindOperationGenerator, - private val endReturn: KtReturnExpression + override val loop: KtForExpression, + private val generator: FindOperationGenerator, + private val endReturn: KtReturnExpression ) : ResultTransformation { override val commentSavingRange = PsiChildRange(loop.unwrapIfLabeled(), endReturn) @@ -149,9 +142,9 @@ object FindTransformationMatcher : TransformationMatcher { } private class FindAndAssignTransformation( - loop: KtForExpression, - private val generator: FindOperationGenerator, - initialization: VariableInitialization + loop: KtForExpression, + private val generator: FindOperationGenerator, + initialization: VariableInitialization ) : AssignToVariableResultTransformation(loop, initialization) { override val presentation: String @@ -166,9 +159,9 @@ object FindTransformationMatcher : TransformationMatcher { } private abstract class FindOperationGenerator( - val functionName: String, - val hasFilter: Boolean, - val chainCallCount: Int = 1 + val functionName: String, + val hasFilter: Boolean, + val chainCallCount: Int = 1 ) { constructor(other: FindOperationGenerator) : this(other.functionName, other.hasFilter, other.chainCallCount) @@ -179,10 +172,10 @@ object FindTransformationMatcher : TransformationMatcher { } private class SimpleGenerator( - functionName: String, - private val inputVariable: KtCallableDeclaration, - private val filter: KtExpression?, - private val argument: KtExpression? = null + functionName: String, + private val inputVariable: KtCallableDeclaration, + private val filter: KtExpression?, + private val argument: KtExpression? = null ) : FindOperationGenerator(functionName, filter != null) { override fun generate(chainedCallGenerator: ChainedCallGenerator): KtExpression { return generateChainedCall(functionName, chainedCallGenerator, inputVariable, filter, argument) @@ -191,45 +184,42 @@ object FindTransformationMatcher : TransformationMatcher { private class NegatingFindOpetationGenerator(val generator: FindOperationGenerator) : FindOperationGenerator(generator) { override fun generate(chainedCallGenerator: ChainedCallGenerator): KtExpression = - generator.generate(chainedCallGenerator).negate() + generator.generate(chainedCallGenerator).negate() } private fun generateChainedCall( - stdlibFunName: String, - chainedCallGenerator: ChainedCallGenerator, - inputVariable: KtCallableDeclaration, - filter: KtExpression?, - argument: KtExpression? = null + stdlibFunName: String, + chainedCallGenerator: ChainedCallGenerator, + inputVariable: KtCallableDeclaration, + filter: KtExpression?, + argument: KtExpression? = null ): KtExpression { return if (filter == null) { if (argument != null) { chainedCallGenerator.generate("$stdlibFunName($0)", argument) - } - else { + } else { chainedCallGenerator.generate("$stdlibFunName()") } - } - else { + } else { val lambda = generateLambda(inputVariable, filter, chainedCallGenerator.reformat) if (argument != null) { chainedCallGenerator.generate("$stdlibFunName($0) $1:'{}'", argument, lambda) - } - else { + } else { chainedCallGenerator.generate("$stdlibFunName $0:'{}'", lambda) } } } private fun buildFindOperationGenerator( - loop: KtForExpression, - inputVariable: KtCallableDeclaration, - indexVariable: KtCallableDeclaration?, - filterTransformation: FilterTransformationBase?, - valueIfFound: KtExpression, - valueIfNotFound: KtExpression, - findFirst: Boolean, - reformat: Boolean - ): FindOperationGenerator? { + loop: KtForExpression, + inputVariable: KtCallableDeclaration, + indexVariable: KtCallableDeclaration?, + filterTransformation: FilterTransformationBase?, + valueIfFound: KtExpression, + valueIfNotFound: KtExpression, + findFirst: Boolean, + reformat: Boolean + ): FindOperationGenerator? { assert(valueIfFound.isPhysical) assert(valueIfNotFound.isPhysical) @@ -246,8 +236,7 @@ object FindTransformationMatcher : TransformationMatcher { return if (containsArgument != null) { val functionName = if (findFirst) "indexOf" else "lastIndexOf" SimpleGenerator(functionName, inputVariable, null, containsArgument) - } - else { + } else { val functionName = if (findFirst) "indexOfFirst" else "indexOfLast" SimpleGenerator(functionName, inputVariable, filterExpression) } @@ -255,9 +244,9 @@ object FindTransformationMatcher : TransformationMatcher { return null - } - else { - val inputVariableCanHoldNull = (inputVariable.unsafeResolveToDescriptor() as VariableDescriptor).type.nullability() != TypeNullability.NOT_NULL + } else { + val inputVariableCanHoldNull = + (inputVariable.unsafeResolveToDescriptor() as VariableDescriptor).type.nullability() != TypeNullability.NOT_NULL fun FindOperationGenerator.useElvisOperatorIfNeeded(): FindOperationGenerator? { if (valueIfNotFound.isNullExpression()) return this @@ -269,8 +258,8 @@ object FindTransformationMatcher : TransformationMatcher { override fun generate(chainedCallGenerator: ChainedCallGenerator): KtExpression { val generated = this@useElvisOperatorIfNeeded.generate(chainedCallGenerator) return KtPsiFactory(generated).createExpressionByPattern( - "$0\n ?: $1", generated, valueIfNotFound, - reformat = chainedCallGenerator.reformat + "$0\n ?: $1", generated, valueIfNotFound, + reformat = chainedCallGenerator.reformat ) } } @@ -300,9 +289,14 @@ object FindTransformationMatcher : TransformationMatcher { val receiver = qualifiedExpression.receiverExpression val selector = qualifiedExpression.selectorExpression if (receiver.isVariableReference(inputVariable) && selector != null && !inputVariable.hasUsages(selector)) { - return object: FindOperationGenerator("firstOrNull", filterCondition != null, chainCallCount = 2) { + return object : FindOperationGenerator("firstOrNull", filterCondition != null, chainCallCount = 2) { override fun generate(chainedCallGenerator: ChainedCallGenerator): KtExpression { - val findFirstCall = generateChainedCall(functionName, chainedCallGenerator, inputVariable, filterCondition?.asExpression(reformat)) + val findFirstCall = generateChainedCall( + functionName, + chainedCallGenerator, + inputVariable, + filterCondition?.asExpression(reformat) + ) return chainedCallGenerator.generate("$0", selector, receiver = findFirstCall, safeCall = true) } }.useElvisOperatorIfNeeded() @@ -312,9 +306,15 @@ object FindTransformationMatcher : TransformationMatcher { // in case of nullable input variable we cannot distinguish by the result of "firstOrNull" whether nothing was found or 'null' was found if (inputVariableCanHoldNull) return null - return object : FindOperationGenerator("firstOrNull", filterCondition != null, chainCallCount = 2 /* also includes "let" */) { + return object : + FindOperationGenerator("firstOrNull", filterCondition != null, chainCallCount = 2 /* also includes "let" */) { override fun generate(chainedCallGenerator: ChainedCallGenerator): KtExpression { - val findFirstCall = generateChainedCall(functionName, chainedCallGenerator, inputVariable, filterCondition?.asExpression(reformat)) + val findFirstCall = generateChainedCall( + functionName, + chainedCallGenerator, + inputVariable, + filterCondition?.asExpression(reformat) + ) val letBody = generateLambda(inputVariable, valueIfFound, chainedCallGenerator.reformat) return chainedCallGenerator.generate("let $0:'{}'", letBody, receiver = findFirstCall, safeCall = true) } @@ -327,8 +327,8 @@ object FindTransformationMatcher : TransformationMatcher { override fun generate(chainedCallGenerator: ChainedCallGenerator): KtExpression { val chainedCall = generator.generate(chainedCallGenerator) return KtPsiFactory(chainedCall).createExpressionByPattern( - "if ($0) $1 else $2", chainedCall, valueIfFound, valueIfNotFound, - reformat = chainedCallGenerator.reformat + "if ($0) $1 else $2", chainedCall, valueIfFound, valueIfNotFound, + reformat = chainedCallGenerator.reformat ) } } @@ -338,11 +338,11 @@ object FindTransformationMatcher : TransformationMatcher { } private fun buildFoundFlagGenerator( - loop: KtForExpression, - inputVariable: KtCallableDeclaration, - filter: Condition?, - negated: Boolean, - reformat: Boolean + loop: KtForExpression, + inputVariable: KtCallableDeclaration, + filter: Condition?, + negated: Boolean, + reformat: Boolean ): FindOperationGenerator { if (filter == null) { return SimpleGenerator(if (negated) "none" else "any", inputVariable, null) diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/result/ForEachTransformation.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/result/ForEachTransformation.kt index 62d49a16e71..f584bbddf6d 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/result/ForEachTransformation.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/result/ForEachTransformation.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions.loopToCallChain.result @@ -25,16 +14,16 @@ import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector class ForEachTransformation( - loop: KtForExpression, - private val inputVariable: KtCallableDeclaration, - private val indexVariable: KtCallableDeclaration?, - private val statement: KtExpression + loop: KtForExpression, + private val inputVariable: KtCallableDeclaration, + private val indexVariable: KtCallableDeclaration?, + private val statement: KtExpression ) : ReplaceLoopResultTransformation(loop) { private val functionName = if (indexVariable != null) "forEachIndexed" else "forEach" override val presentation: String - get() = functionName + "{}" + get() = "$functionName{}" override fun generateCode(chainedCallGenerator: ChainedCallGenerator): KtExpression { val lambda = generateLambda(inputVariable, indexVariable, statement, chainedCallGenerator.reformat) @@ -56,7 +45,8 @@ class ForEachTransformation( get() = false override fun match(state: MatchingState): TransformationMatch.Result? { - if (state.previousTransformations.isEmpty()) return null // do not suggest conversion to just ".forEach{}" or ".forEachIndexed{}" + // do not suggest conversion to just ".forEach{}" or ".forEachIndexed{}" + if (state.previousTransformations.isEmpty()) return null val statement = state.statements.singleOrNull() ?: return null if (statement is KtReturnExpression) return null diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/result/MaxOrMinTransformation.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/result/MaxOrMinTransformation.kt index ca96b600e3b..0d79aa1ab52 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/result/MaxOrMinTransformation.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/result/MaxOrMinTransformation.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions.loopToCallChain.result @@ -23,9 +12,9 @@ import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.blockExpressionsOrSingle class MaxOrMinTransformation( - loop: KtForExpression, - initialization: VariableInitialization, - private val isMax: Boolean + loop: KtForExpression, + initialization: VariableInitialization, + private val isMax: Boolean ) : AssignToVariableResultTransformation(loop, initialization) { override val presentation: String @@ -34,8 +23,8 @@ class MaxOrMinTransformation( override fun generateCode(chainedCallGenerator: ChainedCallGenerator): KtExpression { val call = chainedCallGenerator.generate(presentation) return KtPsiFactory(call).createExpressionByPattern( - "$0\n ?: $1", call, initialization.initializer, - reformat = chainedCallGenerator.reformat + "$0\n ?: $1", call, initialization.initializer, + reformat = chainedCallGenerator.reformat ) } @@ -75,8 +64,8 @@ class MaxOrMinTransformation( override fun match(state: MatchingState): TransformationMatch.Result? { return matchIfAssign(state) - ?: matchAssignIf(state) - ?: matchMathMaxOrMin(state) + ?: matchAssignIf(state) + ?: matchMathMaxOrMin(state) } private fun matchIfAssign(state: MatchingState): TransformationMatch.Result? { @@ -96,25 +85,33 @@ class MaxOrMinTransformation( val ifExpression = assignment.right as? KtIfExpression ?: return null - return match(ifExpression.condition, assignment.left, ifExpression.then, ifExpression.`else`, state.inputVariable, state.outerLoop) + return match( + ifExpression.condition, + assignment.left, + ifExpression.then, + ifExpression.`else`, + state.inputVariable, + state.outerLoop + ) } private fun matchMathMaxOrMin(state: MatchingState): TransformationMatch.Result? { val assignment = state.statements.singleOrNull() as? KtBinaryExpression ?: return null if (assignment.operationToken != KtTokens.EQ) return null - val variableInitialization = assignment.left.findVariableInitializationBeforeLoop(state.outerLoop, checkNoOtherUsagesInLoop = false) - ?: return null + val variableInitialization = + assignment.left.findVariableInitializationBeforeLoop(state.outerLoop, checkNoOtherUsagesInLoop = false) + ?: return null return matchMathMaxOrMin(variableInitialization, assignment, state, isMax = true) - ?: matchMathMaxOrMin(variableInitialization, assignment, state, isMax = false) + ?: matchMathMaxOrMin(variableInitialization, assignment, state, isMax = false) } private fun matchMathMaxOrMin( - variableInitialization: VariableInitialization, - assignment: KtBinaryExpression, - state: MatchingState, - isMax: Boolean + variableInitialization: VariableInitialization, + assignment: KtBinaryExpression, + state: MatchingState, + isMax: Boolean ): TransformationMatch.Result? { val functionName = if (isMax) "max" else "min" val arguments = assignment.right.extractStaticFunctionCallArguments("java.lang.Math." + functionName) ?: return null @@ -135,12 +132,12 @@ class MaxOrMinTransformation( } private fun match( - condition: KtExpression?, - assignmentTarget: KtExpression?, - valueAssignedIfTrue: KtExpression?, - valueAssignedIfFalse: KtExpression?, - inputVariable: KtCallableDeclaration, - loop: KtForExpression + condition: KtExpression?, + assignmentTarget: KtExpression?, + valueAssignedIfTrue: KtExpression?, + valueAssignedIfFalse: KtExpression?, + inputVariable: KtCallableDeclaration, + loop: KtForExpression ): TransformationMatch.Result? { if (condition !is KtBinaryExpression) return null val comparison = condition.operationToken @@ -154,7 +151,7 @@ class MaxOrMinTransformation( } val variableInitialization = otherHand.findVariableInitializationBeforeLoop(loop, checkNoOtherUsagesInLoop = false) - ?: return null + ?: return null if (!assignmentTarget.isVariableReference(variableInitialization.variable)) return null diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/result/SumTransformation.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/result/SumTransformation.kt index 0142685ade7..ebf498a9ba7 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/result/SumTransformation.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/result/SumTransformation.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions.loopToCallChain.result @@ -28,8 +17,8 @@ import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.KotlinType abstract class SumTransformationBase( - loop: KtForExpression, - initialization: VariableInitialization + loop: KtForExpression, + initialization: VariableInitialization ) : AssignToVariableResultTransformation(loop, initialization) { override fun generateCode(chainedCallGenerator: ChainedCallGenerator): KtExpression { @@ -37,11 +26,10 @@ abstract class SumTransformationBase( return if (initialization.initializer.isZeroConstant()) { call - } - else { + } else { KtPsiFactory(call).createExpressionByPattern( - "$0 + $1", initialization.initializer, call, - reformat = chainedCallGenerator.reformat + "$0 + $1", initialization.initializer, call, + reformat = chainedCallGenerator.reformat ) } } @@ -64,8 +52,9 @@ abstract class SumTransformationBase( val statement = state.statements.singleOrNull() as? KtBinaryExpression ?: return null if (statement.operationToken != KtTokens.PLUSEQ) return null - val variableInitialization = statement.left.findVariableInitializationBeforeLoop(state.outerLoop, checkNoOtherUsagesInLoop = true) - ?: return null + val variableInitialization = + statement.left.findVariableInitializationBeforeLoop(state.outerLoop, checkNoOtherUsagesInLoop = true) + ?: return null val value = statement.right ?: return null @@ -107,7 +96,8 @@ abstract class SumTransformationBase( } if (state.indexVariable != null) { - val mapTransformation = MapTransformation(state.outerLoop, state.inputVariable, state.indexVariable, byExpression, mapNotNull = false) + val mapTransformation = + MapTransformation(state.outerLoop, state.inputVariable, state.indexVariable, byExpression, mapNotNull = false) val sumTransformation = SumTransformation(state.outerLoop, variableInitialization) return TransformationMatch.Result(sumTransformation, mapTransformation) } @@ -124,7 +114,8 @@ abstract class SumTransformationBase( } } - val transformation = SumByTransformation(state.outerLoop, variableInitialization, state.inputVariable, byExpression, sumByFunctionName) + val transformation = + SumByTransformation(state.outerLoop, variableInitialization, state.inputVariable, byExpression, sumByFunctionName) return TransformationMatch.Result(transformation) } @@ -147,7 +138,7 @@ abstract class SumTransformationBase( private fun KtExpression.typeWithSmartCast(): KotlinType? { val bindingContext = analyze(BodyResolveMode.PARTIAL) return bindingContext[BindingContext.SMARTCAST, this]?.defaultType - ?: bindingContext.getType(this) + ?: bindingContext.getType(this) } } } @@ -162,11 +153,11 @@ class SumTransformation(loop: KtForExpression, initialization: VariableInitializ } class SumByTransformation( - loop: KtForExpression, - initialization: VariableInitialization, - private val inputVariable: KtCallableDeclaration, - private val byExpression: KtExpression, - private val functionName: String + loop: KtForExpression, + initialization: VariableInitialization, + private val inputVariable: KtCallableDeclaration, + private val byExpression: KtExpression, + private val functionName: String ) : SumTransformationBase(loop, initialization) { override val presentation: String diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/sequence/Condition.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/sequence/Condition.kt index a88c79383f4..77c00938797 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/sequence/Condition.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/sequence/Condition.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions.loopToCallChain.sequence @@ -39,8 +28,7 @@ interface Condition { return CompositeCondition.create(leftCondition.toAtomicConditions() + rightCondition.toAtomicConditions()) } } - } - else { + } else { if (expression is KtBinaryExpression && expression.operationToken == KtTokens.ANDAND) { //TODO: check Boolean type for operands val left = expression.left diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/sequence/FilterTransformation.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/sequence/FilterTransformation.kt index bace16a6de9..295dfc8517c 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/sequence/FilterTransformation.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/sequence/FilterTransformation.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions.loopToCallChain.sequence @@ -81,7 +70,8 @@ abstract class FilterTransformationBase : SequenceTransformation { while (true) { currentState = currentState.unwrapBlock() - if (MaxOrMinTransformation.Matcher.match(currentState) != null) break // do not take 'if' which is required for min/max matcher + // do not take 'if' which is required for min/max matcher + if (MaxOrMinTransformation.Matcher.match(currentState) != null) break val (nextTransformation, nextState) = matchOneTransformation(currentState) ?: break if (nextTransformation !is FilterTransformationBase) break @@ -93,31 +83,33 @@ abstract class FilterTransformationBase : SequenceTransformation { } val transformations = createTransformationsByAtomicConditions( - currentState.outerLoop, - currentState.inputVariable, - currentState.indexVariable, - atomicConditions, - currentState.statements, - currentState.reformat) + currentState.outerLoop, + currentState.inputVariable, + currentState.indexVariable, + atomicConditions, + currentState.statements, + currentState.reformat + ) assert(transformations.isNotEmpty()) val findTransformationMatch = FindTransformationMatcher.matchWithFilterBefore(currentState, transformations.last()) return if (findTransformationMatch != null) { - TransformationMatch.Result(findTransformationMatch.resultTransformation, - transformations.dropLast(1) + findTransformationMatch.sequenceTransformations) - } - else { + TransformationMatch.Result( + findTransformationMatch.resultTransformation, + transformations.dropLast(1) + findTransformationMatch.sequenceTransformations + ) + } else { TransformationMatch.Sequence(transformations, currentState) } } private fun createTransformationsByAtomicConditions( - loop: KtForExpression, - inputVariable: KtCallableDeclaration, - indexVariable: KtCallableDeclaration?, - conditions: List, - restStatements: List, - reformat: Boolean + loop: KtForExpression, + inputVariable: KtCallableDeclaration, + indexVariable: KtCallableDeclaration?, + conditions: List, + restStatements: List, + reformat: Boolean ): List { if (conditions.size == 1) { return listOf(createFilterTransformation(loop, inputVariable, indexVariable, conditions.single(), reformat = reformat)) @@ -136,18 +128,38 @@ abstract class FilterTransformationBase : SequenceTransformation { } for ((transformation, condition) in transformations.zip(conditions)) { - if (transformation !is FilterTransformation && isSmartCastUsed(inputVariable, restStatements)) { // filterIsInstance of filterNotNull + if (transformation !is FilterTransformation && isSmartCastUsed( + inputVariable, + restStatements + ) + ) { // filterIsInstance of filterNotNull resultTransformations.add(transformation) - } - else { + } else { val prevFilter = resultTransformations.lastOrNull() as? FilterTransformation if (prevFilter != null) { - val mergedCondition = CompositeCondition.create(prevFilter.effectiveCondition.toAtomicConditions() + transformation.effectiveCondition.toAtomicConditions()) - val mergedTransformation = createFilterTransformation(loop, inputVariable, indexVariable, mergedCondition, onlyFilterOrFilterNot = true, reformat = reformat) + val mergedCondition = CompositeCondition.create( + prevFilter.effectiveCondition.toAtomicConditions() + transformation.effectiveCondition.toAtomicConditions() + ) + val mergedTransformation = createFilterTransformation( + loop, + inputVariable, + indexVariable, + mergedCondition, + onlyFilterOrFilterNot = true, + reformat = reformat + ) resultTransformations[resultTransformations.lastIndex] = mergedTransformation - } - else { - resultTransformations.add(createFilterTransformation(loop, inputVariable, indexVariable, condition, onlyFilterOrFilterNot = true, reformat = reformat)) + } else { + resultTransformations.add( + createFilterTransformation( + loop, + inputVariable, + indexVariable, + condition, + onlyFilterOrFilterNot = true, + reformat = reformat + ) + ) } } } @@ -162,8 +174,7 @@ abstract class FilterTransformationBase : SequenceTransformation { if (elseBranch == null) { return matchOneTransformation(state, condition, false, thenBranch, state.statements.drop(1)) - } - else if (state.statements.size == 1) { + } else if (state.statements.size == 1) { val thenStatement = thenBranch.blockExpressionsOrSingle().singleOrNull() if (thenStatement is KtBreakExpression || thenStatement is KtContinueExpression) { return matchOneTransformation(state, condition, false, thenBranch, listOf(elseBranch)) @@ -179,32 +190,33 @@ abstract class FilterTransformationBase : SequenceTransformation { } private fun matchOneTransformation( - state: MatchingState, - condition: KtExpression, - negateCondition: Boolean, - then: KtExpression, - restStatements: List + state: MatchingState, + condition: KtExpression, + negateCondition: Boolean, + then: KtExpression, + restStatements: List ): Pair? { // we do not allow filter() which uses neither input variable nor index variable (though is technically possible but looks confusing) // shouldUseInputVariables = false does not work for us because we sometimes return Result match in this matcher - if (!state.inputVariable.hasUsages(condition) && (state.indexVariable == null || !state.indexVariable.hasUsages(condition))) return null + if (!state.inputVariable.hasUsages(condition) && + (state.indexVariable == null || !state.indexVariable.hasUsages(condition)) + ) return null if (restStatements.isEmpty()) { val transformation = createFilterTransformation( - state.outerLoop, state.inputVariable, state.indexVariable, Condition.create(condition, negateCondition), - reformat = state.reformat + state.outerLoop, state.inputVariable, state.indexVariable, Condition.create(condition, negateCondition), + reformat = state.reformat ) val newState = state.copy(statements = listOf(then)) return transformation to newState - } - else { + } else { val statement = then.blockExpressionsOrSingle().singleOrNull() ?: return null when (statement) { is KtContinueExpression -> { if (statement.targetLoop() != state.innerLoop) return null val transformation = createFilterTransformation( - state.outerLoop, state.inputVariable, state.indexVariable, Condition.create(condition, !negateCondition), - reformat = state.reformat + state.outerLoop, state.inputVariable, state.indexVariable, Condition.create(condition, !negateCondition), + reformat = state.reformat ) val newState = state.copy(statements = restStatements) return transformation to newState @@ -213,8 +225,8 @@ abstract class FilterTransformationBase : SequenceTransformation { is KtBreakExpression -> { if (statement.targetLoop() != state.outerLoop) return null val transformation = TakeWhileTransformation( - state.outerLoop, state.inputVariable, - if (negateCondition) condition else condition.negate(reformat = state.reformat) + state.outerLoop, state.inputVariable, + if (negateCondition) condition else condition.negate(reformat = state.reformat) ) val newState = state.copy(statements = restStatements) return transformation to newState @@ -226,12 +238,12 @@ abstract class FilterTransformationBase : SequenceTransformation { } private fun createFilterTransformation( - loop: KtForExpression, - inputVariable: KtCallableDeclaration, - indexVariable: KtCallableDeclaration?, - condition: Condition, - onlyFilterOrFilterNot: Boolean = false, - reformat: Boolean + loop: KtForExpression, + inputVariable: KtCallableDeclaration, + indexVariable: KtCallableDeclaration?, + condition: Condition, + onlyFilterOrFilterNot: Boolean = false, + reformat: Boolean ): FilterTransformationBase { if (indexVariable != null && condition.hasUsagesOf(indexVariable)) { @@ -242,7 +254,8 @@ abstract class FilterTransformationBase : SequenceTransformation { if (!onlyFilterOrFilterNot) { if (conditionAsExpression is KtIsExpression && !conditionAsExpression.isNegated - && conditionAsExpression.leftHandSide.isSimpleName(inputVariable.nameAsSafeName) // we cannot use isVariableReference here because expression can be non-physical + // we cannot use isVariableReference here because expression can be non-physical + && conditionAsExpression.leftHandSide.isSimpleName(inputVariable.nameAsSafeName) ) { val typeRef = conditionAsExpression.typeReference if (typeRef != null) { @@ -277,11 +290,11 @@ abstract class FilterTransformationBase : SequenceTransformation { } class FilterTransformation( - override val loop: KtForExpression, - override val inputVariable: KtCallableDeclaration, - override val indexVariable: KtCallableDeclaration?, - override val effectiveCondition: Condition, - val isFilterNot: Boolean + override val loop: KtForExpression, + override val inputVariable: KtCallableDeclaration, + override val indexVariable: KtCallableDeclaration?, + override val effectiveCondition: Condition, + val isFilterNot: Boolean ) : FilterTransformationBase() { init { @@ -304,16 +317,20 @@ class FilterTransformation( val lambda = if (indexVariable != null) generateLambda(inputVariable, indexVariable, effectiveCondition.asExpression(reformat), reformat) else - generateLambda(inputVariable, if (isFilterNot) effectiveCondition.asNegatedExpression(reformat) else effectiveCondition.asExpression(reformat), reformat) + generateLambda( + inputVariable, + if (isFilterNot) effectiveCondition.asNegatedExpression(reformat) else effectiveCondition.asExpression(reformat), + reformat + ) return chainedCallGenerator.generate("$0$1:'{}'", functionName, lambda) } } class FilterIsInstanceTransformation( - override val loop: KtForExpression, - override val inputVariable: KtCallableDeclaration, - private val type: KtTypeReference, - override val effectiveCondition: Condition + override val loop: KtForExpression, + override val inputVariable: KtCallableDeclaration, + private val type: KtTypeReference, + override val effectiveCondition: Condition ) : FilterTransformationBase() { override val indexVariable: KtCallableDeclaration? get() = null @@ -327,16 +344,22 @@ class FilterIsInstanceTransformation( } class FilterNotNullTransformation( - override val loop: KtForExpression, - override val inputVariable: KtCallableDeclaration, - override val effectiveCondition: Condition + override val loop: KtForExpression, + override val inputVariable: KtCallableDeclaration, + override val effectiveCondition: Condition ) : FilterTransformationBase() { override val indexVariable: KtCallableDeclaration? get() = null override fun mergeWithPrevious(previousTransformation: SequenceTransformation, reformat: Boolean): SequenceTransformation? { if (previousTransformation is MapTransformation) { - return MapTransformation(loop, previousTransformation.inputVariable, previousTransformation.indexVariable, previousTransformation.mapping, mapNotNull = true) + return MapTransformation( + loop, + previousTransformation.inputVariable, + previousTransformation.indexVariable, + previousTransformation.mapping, + mapNotNull = true + ) } return null } @@ -350,9 +373,9 @@ class FilterNotNullTransformation( } class TakeWhileTransformation( - override val loop: KtForExpression, - val inputVariable: KtCallableDeclaration, - val condition: KtExpression + override val loop: KtForExpression, + val inputVariable: KtCallableDeclaration, + val condition: KtExpression ) : SequenceTransformation { //TODO: merge multiple diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/sequence/FlatMapTransformation.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/sequence/FlatMapTransformation.kt index 8cae280f54c..6b4f4794431 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/sequence/FlatMapTransformation.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/sequence/FlatMapTransformation.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions.loopToCallChain.sequence @@ -24,9 +13,9 @@ import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class FlatMapTransformation( - override val loop: KtForExpression, - val inputVariable: KtCallableDeclaration, - val transform: KtExpression + override val loop: KtForExpression, + val inputVariable: KtCallableDeclaration, + val transform: KtExpression ) : SequenceTransformation { override val affectsIndex: Boolean @@ -68,17 +57,18 @@ class FlatMapTransformation( if (state.indexVariable != null && state.indexVariable.hasUsages(transform)) { // if nested loop range uses index, convert to "mapIndexed {...}.flatMap { it }" - val mapIndexedTransformation = MapTransformation(state.outerLoop, state.inputVariable, state.indexVariable, transform, mapNotNull = false) + val mapIndexedTransformation = + MapTransformation(state.outerLoop, state.inputVariable, state.indexVariable, transform, mapNotNull = false) val inputVarExpression = KtPsiFactory(nestedLoop).createExpressionByPattern( - "$0", state.inputVariable.nameAsSafeName, - reformat = state.reformat + "$0", state.inputVariable.nameAsSafeName, + reformat = state.reformat ) val transformToUse = if (state.lazySequence) inputVarExpression.asSequence(state.reformat) else inputVarExpression val flatMapTransformation = FlatMapTransformation(state.outerLoop, state.inputVariable, transformToUse) val newState = state.copy( - innerLoop = nestedLoop, - statements = listOf(nestedLoopBody), - inputVariable = newInputVariable + innerLoop = nestedLoop, + statements = listOf(nestedLoopBody), + inputVariable = newInputVariable ) return TransformationMatch.Sequence(listOf(mapIndexedTransformation, flatMapTransformation), newState) } @@ -86,18 +76,16 @@ class FlatMapTransformation( val transformToUse = if (state.lazySequence) transform.asSequence(state.reformat) else transform val transformation = FlatMapTransformation(state.outerLoop, state.inputVariable, transformToUse) val newState = state.copy( - innerLoop = nestedLoop, - statements = listOf(nestedLoopBody), - inputVariable = newInputVariable + innerLoop = nestedLoop, + statements = listOf(nestedLoopBody), + inputVariable = newInputVariable ) return TransformationMatch.Sequence(transformation, newState) } - private fun KtExpression.asSequence(reformat: Boolean): KtExpression { - return KtPsiFactory(this).createExpressionByPattern( - "$0.asSequence()", this, - reformat = reformat - ) - } + private fun KtExpression.asSequence(reformat: Boolean): KtExpression = KtPsiFactory(this).createExpressionByPattern( + "$0.asSequence()", this, + reformat = reformat + ) } } \ No newline at end of file diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/sequence/IntroduceIndexMatcher.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/sequence/IntroduceIndexMatcher.kt index 24a5caf62f0..0b461eb7772 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/sequence/IntroduceIndexMatcher.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/sequence/IntroduceIndexMatcher.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions.loopToCallChain.sequence @@ -43,7 +32,7 @@ object IntroduceIndexMatcher : TransformationMatcher { override fun match(state: MatchingState): TransformationMatch.Sequence? { for (statement in state.statements) { val unaryExpressions = statement.collectDescendantsOfType( - canGoInside = { it !is KtBlockExpression && it !is KtFunction } + canGoInside = { it !is KtBlockExpression && it !is KtFunction } ) for (unaryExpression in unaryExpressions) { checkIndexCandidate(unaryExpression, state)?.let { return it } @@ -56,7 +45,7 @@ object IntroduceIndexMatcher : TransformationMatcher { val operand = incrementExpression.isPlusPlusOf() ?: return null val variableInitialization = operand.findVariableInitializationBeforeLoop(state.outerLoop, checkNoOtherUsagesInLoop = false) - ?: return null + ?: return null if ((variableInitialization.initializer as? KtConstantExpression)?.text != "0") return null val variable = variableInitialization.variable @@ -74,21 +63,25 @@ object IntroduceIndexMatcher : TransformationMatcher { if (!isAlwaysReachedOrExitedLoop(firstInstruction, incrementInstruction, state.outerLoop, state.innerLoop)) return null val variableDescriptor = variable.unsafeResolveToDescriptor() as VariableDescriptor - if (isAccessedAfter(variableDescriptor, incrementInstruction, state.innerLoop)) return null // index accessed inside loop after increment + // index accessed inside loop after increment + if (isAccessedAfter(variableDescriptor, incrementInstruction, state.innerLoop)) return null - val restStatements = state.statements - incrementExpression // if it is among statements then drop it, otherwise "index++" will be replaced with "index" by generateLambda() - val newState = state.copy(statements = restStatements, - indexVariable = variable, - initializationStatementsToDelete = state.initializationStatementsToDelete + variableInitialization.initializationStatement, - incrementExpressions = state.incrementExpressions + incrementExpression) + // if it is among statements then drop it, otherwise "index++" will be replaced with "index" by generateLambda() + val restStatements = state.statements - incrementExpression + val newState = state.copy( + statements = restStatements, + indexVariable = variable, + initializationStatementsToDelete = state.initializationStatementsToDelete + variableInitialization.initializationStatement, + incrementExpressions = state.incrementExpressions + incrementExpression + ) return TransformationMatch.Sequence(emptyList(), newState) } private fun isAlwaysReachedOrExitedLoop( - from: Instruction, - to: Instruction, - outerLoop: KtForExpression, - innerLoop: KtForExpression + from: Instruction, + to: Instruction, + outerLoop: KtForExpression, + innerLoop: KtForExpression ): Boolean { val visited = HashSet() return traverseFollowingInstructions(from, visited) { instruction -> @@ -97,8 +90,10 @@ object IntroduceIndexMatcher : TransformationMatcher { // (if we won't do this on some branch we will finally exit the inner loop and return false from traverseFollowingInstructions) when { instruction == to -> TraverseInstructionResult.SKIP - !outerLoop.isAncestor(nextInstructionScope, strict = false) -> TraverseInstructionResult.SKIP // we are out of the outer loop - it's ok - !innerLoop.isAncestor(nextInstructionScope, strict = true) -> TraverseInstructionResult.HALT // we exited or continued inner loop + // we are out of the outer loop - it's ok + !outerLoop.isAncestor(nextInstructionScope, strict = false) -> TraverseInstructionResult.SKIP + // we exited or continued inner loop + !innerLoop.isAncestor(nextInstructionScope, strict = true) -> TraverseInstructionResult.HALT else -> TraverseInstructionResult.CONTINUE } } && visited.contains(to) diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/sequence/MapTransformation.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/sequence/MapTransformation.kt index 34a75386ad7..2f4358310ed 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/sequence/MapTransformation.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/sequence/MapTransformation.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions.loopToCallChain.sequence @@ -21,11 +10,11 @@ import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* class MapTransformation( - override val loop: KtForExpression, - val inputVariable: KtCallableDeclaration, - val indexVariable: KtCallableDeclaration?, - val mapping: KtExpression, - val mapNotNull: Boolean + override val loop: KtForExpression, + val inputVariable: KtCallableDeclaration, + val indexVariable: KtCallableDeclaration?, + val mapping: KtExpression, + val mapNotNull: Boolean ) : SequenceTransformation { private val functionName = if (indexVariable != null) diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/utils.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/utils.kt index 8b8ce352107..e2c7f807e62 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/utils.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/utils.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.intentions.loopToCallChain @@ -49,8 +38,8 @@ fun generateLambda(inputVariable: KtCallableDeclaration, expression: KtExpressio val psiFactory = KtPsiFactory(expression) val lambdaExpression = psiFactory.createExpressionByPattern( - "{ $0 -> $1 }", inputVariable.nameAsSafeName, expression, - reformat = reformat + "{ $0 -> $1 }", inputVariable.nameAsSafeName, expression, + reformat = reformat ) as KtLambdaExpression val isItUsedInside = expression.anyDescendantOfType { @@ -74,10 +63,10 @@ fun generateLambda(inputVariable: KtCallableDeclaration, expression: KtExpressio } fun generateLambda( - inputVariable: KtCallableDeclaration, - indexVariable: KtCallableDeclaration?, - expression: KtExpression, - reformat: Boolean + inputVariable: KtCallableDeclaration, + indexVariable: KtCallableDeclaration?, + expression: KtExpression, + reformat: Boolean ): KtLambdaExpression { if (indexVariable == null) { return generateLambda(inputVariable, expression, reformat) @@ -93,8 +82,7 @@ fun generateLambda( val parameter = lambdaExpression.valueParameters[0] val parameterDescriptor = bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, parameter] operand.mainReference.resolveToDescriptors(bindingContext).singleOrNull() == parameterDescriptor - } - else { + } else { false } } @@ -147,14 +135,15 @@ private fun KtLambdaExpression.analyzeInContext(context: KtExpression): BindingC } data class VariableInitialization( - val variable: KtProperty, - val initializationStatement: KtExpression, - val initializer: KtExpression) + val variable: KtProperty, + val initializationStatement: KtExpression, + val initializer: KtExpression +) //TODO: we need more correctness checks (if variable is non-local or is local but can be changed by some local functions) fun KtExpression?.findVariableInitializationBeforeLoop( - loop: KtForExpression, - checkNoOtherUsagesInLoop: Boolean + loop: KtForExpression, + checkNoOtherUsagesInLoop: Boolean ): VariableInitialization? { if (this !is KtNameReferenceExpression) return null if (getQualifiedExpressionForSelector() != null) return null @@ -166,8 +155,8 @@ fun KtExpression?.findVariableInitializationBeforeLoop( val unwrapped = loop.unwrapIfLabeled() if (unwrapped.parent !is KtBlockExpression) return null val prevStatements = unwrapped - .siblings(forward = false, withItself = false) - .filterIsInstance() + .siblings(forward = false, withItself = false) + .filterIsInstance() val statementsBetween = ArrayList() for (statement in prevStatements) { @@ -206,13 +195,11 @@ fun KtExpression.isSimpleCollectionInstantiation(): CollectionKind? { if (callExpression.valueArguments.isNotEmpty()) return null val resolvedCall = callExpression.resolveToCall() ?: return null - val descriptor = resolvedCall.resultingDescriptor - when (descriptor) { + return when (val descriptor = resolvedCall.resultingDescriptor) { is ConstructorDescriptor -> { val classDescriptor = descriptor.containingDeclaration - val classFqName = classDescriptor.importableFqName?.asString() - return when (classFqName) { + when (classDescriptor.importableFqName?.asString()) { "java.util.ArrayList" -> CollectionKind.LIST "java.util.HashSet", "java.util.LinkedHashSet" -> CollectionKind.SET else -> null @@ -220,15 +207,14 @@ fun KtExpression.isSimpleCollectionInstantiation(): CollectionKind? { } is FunctionDescriptor -> { - val fqName = descriptor.importableFqName?.asString() - return when (fqName) { + when (descriptor.importableFqName?.asString()) { "kotlin.collections.arrayListOf", "kotlin.collections.mutableListOf" -> CollectionKind.LIST "kotlin.collections.hashSetOf", "kotlin.collections.mutableSetOf" -> CollectionKind.SET else -> null } } - else -> return null + else -> null } } @@ -239,17 +225,17 @@ fun canChangeLocalVariableType(variable: KtProperty, newTypeText: String, loop: } fun tryChangeAndCheckErrors( - expressionToChange: TExpression, - scopeToExclude: KtElement? = null, - performChange: (TExpression) -> Unit + expressionToChange: TExpression, + scopeToExclude: KtElement? = null, + performChange: (TExpression) -> Unit ): Boolean { val bindingContext = expressionToChange.analyze(BodyResolveMode.FULL) // analyze the closest block whose value is not used val block = expressionToChange.parents - .filterIsInstance() - .firstOrNull { !it.isUsedAsExpression(bindingContext) } - ?: return true + .filterIsInstance() + .firstOrNull { !it.isUsedAsExpression(bindingContext) } + ?: return true // we declare these keys locally to avoid possible race-condition problems if this code is executed in 2 threads simultaneously val EXPRESSION = Key("EXPRESSION") @@ -261,7 +247,7 @@ fun tryChangeAndCheckErrors( block.forEachDescendantOfType { element -> val errors = bindingContext.diagnostics.forElement(element) - .filter { it.severity == Severity.ERROR } + .filter { it.severity == Severity.ERROR } if (errors.isNotEmpty()) { element.putCopyableUserData(ERRORS_BEFORE, errors.map { it.factory }) } @@ -274,8 +260,7 @@ fun tryChangeAndCheckErrors( try { expressionCopy = blockCopy.findDescendantOfType { it.getCopyableUserData(EXPRESSION) != null } as TExpression scopeToExcludeCopy = blockCopy.findDescendantOfType { it.getCopyableUserData(SCOPE_TO_EXCLUDE) != null } - } - finally { + } finally { expressionToChange.putCopyableUserData(EXPRESSION, null) scopeToExclude?.putCopyableUserData(SCOPE_TO_EXCLUDE, null) } @@ -285,18 +270,18 @@ fun tryChangeAndCheckErrors( val newBindingContext = blockCopy.analyzeAsReplacement(block, bindingContext) return newBindingContext.diagnostics.none { it.severity == Severity.ERROR - && !scopeToExcludeCopy.isAncestor(it.psiElement) - && it.factory !in (it.psiElement.getCopyableUserData(ERRORS_BEFORE) ?: emptyList()) + && !scopeToExcludeCopy.isAncestor(it.psiElement) + && it.factory !in (it.psiElement.getCopyableUserData(ERRORS_BEFORE) ?: emptyList()) } } private val NO_SIDE_EFFECT_STANDARD_CLASSES = setOf( - "java.util.ArrayList", - "java.util.LinkedList", - "java.util.HashSet", - "java.util.LinkedHashSet", - "java.util.HashMap", - "java.util.LinkedHashMap" + "java.util.ArrayList", + "java.util.LinkedList", + "java.util.HashSet", + "java.util.LinkedHashSet", + "java.util.HashMap", + "java.util.LinkedHashMap" ) fun KtExpression.hasNoSideEffect(): Boolean { @@ -384,8 +369,7 @@ fun KtExpression.countEmbeddedBreaksAndContinues(): Int { private fun isEmbeddedBreakOrContinue(expression: KtExpressionWithLabel): Boolean { if (expression !is KtBreakExpression && expression !is KtContinueExpression) return false - val parent = expression.parent - return when (parent) { + return when (val parent = expression.parent) { is KtBlockExpression -> false is KtContainerNode -> { diff --git a/idea/src/org/jetbrains/kotlin/idea/internal/KotlinDecompilerAdapter.kt b/idea/src/org/jetbrains/kotlin/idea/internal/KotlinDecompilerAdapter.kt index f6ddb601393..a1b7e439d6b 100644 --- a/idea/src/org/jetbrains/kotlin/idea/internal/KotlinDecompilerAdapter.kt +++ b/idea/src/org/jetbrains/kotlin/idea/internal/KotlinDecompilerAdapter.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2017 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -67,6 +67,6 @@ val KOTLIN_DECOMPILED_ROOT = "dummy://$KOTLIN_DECOMPILED_FOLDER" var VirtualFile.isKotlinDecompiledFile: Boolean by NotNullableUserDataProperty(Key.create("IS_KOTLIN_DECOMPILED_FILE"), false) fun getOrCreateDummyRoot(): VirtualFile = - VirtualFileManager.getInstance().refreshAndFindFileByUrl(KOTLIN_DECOMPILED_ROOT) ?: - DummyFileSystem.getInstance().createRoot(KOTLIN_DECOMPILED_FOLDER) + VirtualFileManager.getInstance().refreshAndFindFileByUrl(KOTLIN_DECOMPILED_ROOT) + ?: DummyFileSystem.getInstance().createRoot(KOTLIN_DECOMPILED_FOLDER) diff --git a/idea/src/org/jetbrains/kotlin/idea/j2k/J2KPostProcessingRegistrarImpl.kt b/idea/src/org/jetbrains/kotlin/idea/j2k/J2KPostProcessingRegistrarImpl.kt index 6c5f32e6571..20183edfdbd 100644 --- a/idea/src/org/jetbrains/kotlin/idea/j2k/J2KPostProcessingRegistrarImpl.kt +++ b/idea/src/org/jetbrains/kotlin/idea/j2k/J2KPostProcessingRegistrarImpl.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.j2k @@ -37,7 +26,6 @@ import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isTrivialSta import org.jetbrains.kotlin.idea.quickfix.RemoveModifierFix import org.jetbrains.kotlin.idea.quickfix.RemoveUselessCastFix import org.jetbrains.kotlin.idea.references.mainReference -import org.jetbrains.kotlin.j2k.ConverterSettings import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getChildOfType @@ -78,7 +66,9 @@ object J2KPostProcessingRegistrarImpl : J2KPostProcessingRegistrar { registerInspectionBasedProcessing(FoldInitializerAndIfToElvisInspection()) - registerIntentionBasedProcessing(FoldIfToReturnIntention()) { it.then.isTrivialStatementBody() && it.`else`.isTrivialStatementBody() } + registerIntentionBasedProcessing(FoldIfToReturnIntention()) { + it.then.isTrivialStatementBody() && it.`else`.isTrivialStatementBody() + } registerIntentionBasedProcessing(FoldIfToReturnAsymmetricallyIntention()) { it.then.isTrivialStatementBody() && (KtPsiUtil.skipTrailingWhitespacesAndComments( it @@ -371,7 +361,9 @@ object J2KPostProcessingRegistrarImpl : J2KPostProcessingRegistrar { override val writeActionNeeded = true override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? { - if (element !is KtSimpleNameExpression || diagnostics.forElement(element).none { it.factory == Errors.UNINITIALIZED_VARIABLE }) return null + if (element !is KtSimpleNameExpression || diagnostics.forElement(element) + .none { it.factory == Errors.UNINITIALIZED_VARIABLE } + ) return null val resolved = element.mainReference.resolve() ?: return null if (resolved.isAncestor(element, strict = true)) { @@ -391,7 +383,9 @@ object J2KPostProcessingRegistrarImpl : J2KPostProcessingRegistrar { override val writeActionNeeded = true override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? { - if (element !is KtSimpleNameExpression || diagnostics.forElement(element).none { it.factory == Errors.UNRESOLVED_REFERENCE }) return null + if (element !is KtSimpleNameExpression || diagnostics.forElement(element) + .none { it.factory == Errors.UNRESOLVED_REFERENCE } + ) return null val anonymousObject = element.getParentOfType(true) ?: return null diff --git a/idea/src/org/jetbrains/kotlin/idea/joinLines/JoinBlockIntoSingleStatementHandler.kt b/idea/src/org/jetbrains/kotlin/idea/joinLines/JoinBlockIntoSingleStatementHandler.kt index 7ac894cf4ee..ff530b416bf 100644 --- a/idea/src/org/jetbrains/kotlin/idea/joinLines/JoinBlockIntoSingleStatementHandler.kt +++ b/idea/src/org/jetbrains/kotlin/idea/joinLines/JoinBlockIntoSingleStatementHandler.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.joinLines @@ -58,10 +47,10 @@ class JoinBlockIntoSingleStatementHandler : JoinRawLinesHandlerDelegate { if (block == pparent.`else`) { val ifParent = pparent.parent - if (!( - ifParent is KtBlockExpression || - ifParent is KtDeclaration || - KtPsiUtil.isAssignment(ifParent))) { + if (!(ifParent is KtBlockExpression || + ifParent is KtDeclaration || + KtPsiUtil.isAssignment(ifParent)) + ) { return -1 } } @@ -70,8 +59,7 @@ class JoinBlockIntoSingleStatementHandler : JoinRawLinesHandlerDelegate { return if (oneLineReturnFunction != null) { useExpressionBodyInspection.simplify(oneLineReturnFunction, false) oneLineReturnFunction.bodyExpression!!.startOffset - } - else { + } else { val newStatement = block.replace(statement) newStatement.textRange!!.startOffset } diff --git a/idea/src/org/jetbrains/kotlin/idea/joinLines/JoinDeclarationAndAssignmentHandler.kt b/idea/src/org/jetbrains/kotlin/idea/joinLines/JoinDeclarationAndAssignmentHandler.kt index eef6d409886..c943e441af3 100644 --- a/idea/src/org/jetbrains/kotlin/idea/joinLines/JoinDeclarationAndAssignmentHandler.kt +++ b/idea/src/org/jetbrains/kotlin/idea/joinLines/JoinDeclarationAndAssignmentHandler.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.joinLines @@ -36,27 +25,26 @@ class JoinDeclarationAndAssignmentHandler : JoinRawLinesHandlerDelegate { if (file !is KtFile) return -1 val element = file.findElementAt(start) - ?.siblings(forward = false, withItself = false) - ?.firstOrNull { !isToSkip(it) } ?: return -1 + ?.siblings(forward = false, withItself = false) + ?.firstOrNull { !isToSkip(it) } ?: return -1 val pair = element.parentsWithSelf - .mapNotNull { getPropertyAndAssignment(it) } - .firstOrNull() ?: return -1 + .mapNotNull { getPropertyAndAssignment(it) } + .firstOrNull() ?: return -1 val (property, assignment) = pair doJoin(property, assignment) return property.textRange!!.startOffset } - override fun tryJoinLines(document: Document, file: PsiFile, start: Int, end: Int) - = -1 + override fun tryJoinLines(document: Document, file: PsiFile, start: Int, end: Int) = -1 private fun getPropertyAndAssignment(element: PsiElement): Pair? { val property = element as? KtProperty ?: return null if (property.hasInitializer()) return null val assignment = element.siblings(forward = true, withItself = false) - .firstOrNull { !isToSkip(it) } as? KtBinaryExpression ?: return null + .firstOrNull { !isToSkip(it) } as? KtBinaryExpression ?: return null if (assignment.operationToken != KtTokens.EQ) return null val left = assignment.left as? KtSimpleNameExpression ?: return null diff --git a/idea/src/org/jetbrains/kotlin/idea/joinLines/JoinStatementsAddSemicolonHandler.kt b/idea/src/org/jetbrains/kotlin/idea/joinLines/JoinStatementsAddSemicolonHandler.kt index 4857b54c3b8..67f0fcb5550 100644 --- a/idea/src/org/jetbrains/kotlin/idea/joinLines/JoinStatementsAddSemicolonHandler.kt +++ b/idea/src/org/jetbrains/kotlin/idea/joinLines/JoinStatementsAddSemicolonHandler.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.joinLines @@ -34,9 +23,9 @@ class JoinStatementsAddSemicolonHandler : JoinRawLinesHandlerDelegate { if (file !is KtFile) return CANNOT_JOIN val linebreak = file.findElementAt(start) - ?.siblings(forward = true, withItself = true) - ?.firstOrNull { it.textContains('\n') } - ?: return CANNOT_JOIN + ?.siblings(forward = true, withItself = true) + ?.firstOrNull { it.textContains('\n') } + ?: return CANNOT_JOIN val parent = linebreak.parent ?: return CANNOT_JOIN val element1 = linebreak.firstMaterialSiblingSameLine { prevSibling } ?: return CANNOT_JOIN @@ -61,8 +50,7 @@ class JoinStatementsAddSemicolonHandler : JoinRawLinesHandlerDelegate { element = element.getNext() ?: return null if (element.node.elementType !in WHITE_SPACE_OR_COMMENT_BIT_SET) return element - } - while (!element.textContains('\n')) + } while (!element.textContains('\n')) return null } diff --git a/idea/src/org/jetbrains/kotlin/idea/kdoc/kdocBoringClassifiers.kt b/idea/src/org/jetbrains/kotlin/idea/kdoc/kdocBoringClassifiers.kt index e57aa8c131a..092cd8c4667 100644 --- a/idea/src/org/jetbrains/kotlin/idea/kdoc/kdocBoringClassifiers.kt +++ b/idea/src/org/jetbrains/kotlin/idea/kdoc/kdocBoringClassifiers.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.kdoc @@ -21,19 +10,18 @@ import org.jetbrains.kotlin.descriptors.ClassifierDescriptor import org.jetbrains.kotlin.resolve.DescriptorUtils private val boringBuiltinClasses = setOf( - FQ_NAMES.unit, - FQ_NAMES._byte, - FQ_NAMES._short, - FQ_NAMES._int, - FQ_NAMES._long, - FQ_NAMES._char, - FQ_NAMES._boolean, - FQ_NAMES._float, - FQ_NAMES._double, - FQ_NAMES.string, - FQ_NAMES.array, - FQ_NAMES.any + FQ_NAMES.unit, + FQ_NAMES._byte, + FQ_NAMES._short, + FQ_NAMES._int, + FQ_NAMES._long, + FQ_NAMES._char, + FQ_NAMES._boolean, + FQ_NAMES._float, + FQ_NAMES._double, + FQ_NAMES.string, + FQ_NAMES.array, + FQ_NAMES.any ) -fun ClassifierDescriptor.isBoringBuiltinClass(): Boolean = - DescriptorUtils.getFqName(this) in boringBuiltinClasses \ No newline at end of file +fun ClassifierDescriptor.isBoringBuiltinClass(): Boolean = DescriptorUtils.getFqName(this) in boringBuiltinClasses \ No newline at end of file diff --git a/idea/src/org/jetbrains/kotlin/idea/parameterInfo/TypeHints.kt b/idea/src/org/jetbrains/kotlin/idea/parameterInfo/TypeHints.kt index d015069f68d..4ca81154cc5 100644 --- a/idea/src/org/jetbrains/kotlin/idea/parameterInfo/TypeHints.kt +++ b/idea/src/org/jetbrains/kotlin/idea/parameterInfo/TypeHints.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -103,7 +103,7 @@ fun provideTypeHint(element: KtCallableDeclaration, offset: Int): List 1) { val propertyLine = element.getLineNumber() val equalsTokenLine = element.equalsToken?.getLineNumber() ?: -1 @@ -116,7 +116,7 @@ fun provideTypeHint(element: KtCallableDeclaration, offset: Int): List this.resolveMainReferenceToDescriptors().singleOrNull().let { it is ClassDescriptor || it is PackageViewDescriptor } + is KtNameReferenceExpression -> this.resolveMainReferenceToDescriptors().singleOrNull() + .let { it is ClassDescriptor || it is PackageViewDescriptor } is KtDotQualifiedExpression -> this.selectorExpression?.isClassOrPackageReference() ?: false else -> false } diff --git a/idea/src/org/jetbrains/kotlin/idea/patterns/KotlinPatterns.kt b/idea/src/org/jetbrains/kotlin/idea/patterns/KotlinPatterns.kt index a018cd52a77..b3e4dec7a25 100644 --- a/idea/src/org/jetbrains/kotlin/idea/patterns/KotlinPatterns.kt +++ b/idea/src/org/jetbrains/kotlin/idea/patterns/KotlinPatterns.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.patterns @@ -33,10 +22,15 @@ import org.jetbrains.kotlin.renderer.DescriptorRenderer // Methods in this class are used through reflection @Suppress("unused") -object KotlinPatterns: StandardPatterns() { - @JvmStatic fun kotlinParameter() = KtParameterPattern() - @JvmStatic fun kotlinFunction() = KotlinFunctionPattern() - @JvmStatic fun receiver() = KotlinReceiverPattern() +object KotlinPatterns : StandardPatterns() { + @JvmStatic + fun kotlinParameter() = KtParameterPattern() + + @JvmStatic + fun kotlinFunction() = KotlinFunctionPattern() + + @JvmStatic + fun receiver() = KotlinReceiverPattern() } // Methods in this class are used through reflection during pattern construction @@ -98,9 +92,11 @@ open class KotlinFunctionPattern : PsiElementPattern(KtParameter::class.java) { fun ofFunction(index: Int, pattern: ElementPattern): KtParameterPattern { return with(object : PatternConditionPlus("KtParameterPattern-ofMethod", pattern) { - override fun processValues(ktParameter: KtParameter, - context: ProcessingContext, - processor: PairProcessor): Boolean { + override fun processValues( + ktParameter: KtParameter, + context: ProcessingContext, + processor: PairProcessor + ): Boolean { val function = ktParameter.ownerFunction as? KtFunction ?: return true return processor.process(function, context) } @@ -132,9 +128,11 @@ class KtParameterPattern : PsiElementPattern(Kt class KotlinReceiverPattern : PsiElementPattern(KtTypeReference::class.java) { fun ofFunction(pattern: ElementPattern): KotlinReceiverPattern { return with(object : PatternConditionPlus("KtReceiverPattern-ofMethod", pattern) { - override fun processValues(typeReference: KtTypeReference, context: ProcessingContext?, processor: PairProcessor): Boolean { - return processor.process(typeReference.parent as? KtFunction, context) - } + override fun processValues( + typeReference: KtTypeReference, + context: ProcessingContext?, + processor: PairProcessor + ): Boolean = processor.process(typeReference.parent as? KtFunction, context) override fun accepts(typeReference: KtTypeReference, context: ProcessingContext?): Boolean { val ktFunction = typeReference.parent as? KtFunction ?: return false @@ -146,12 +144,11 @@ class KotlinReceiverPattern : PsiElementPattern> PsiElementPattern.withPatternCondition( - debugName: String, condition: (T, ProcessingContext?) -> Boolean): Self { - return with(object: PatternCondition(debugName) { - override fun accepts(element: T, context: ProcessingContext?): Boolean { - return condition(element, context) - } - }) -} +private fun > PsiElementPattern.withPatternCondition( + debugName: String, condition: (T, ProcessingContext?) -> Boolean +): Self = with(object : PatternCondition(debugName) { + override fun accepts(element: T, context: ProcessingContext?): Boolean { + return condition(element, context) + } +}) diff --git a/idea/src/org/jetbrains/kotlin/idea/projectView/KotlinProblemFileHighlightFilter.kt b/idea/src/org/jetbrains/kotlin/idea/projectView/KotlinProblemFileHighlightFilter.kt index cc99e742695..04f8c429d7a 100644 --- a/idea/src/org/jetbrains/kotlin/idea/projectView/KotlinProblemFileHighlightFilter.kt +++ b/idea/src/org/jetbrains/kotlin/idea/projectView/KotlinProblemFileHighlightFilter.kt @@ -1,18 +1,6 @@ - /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.projectView diff --git a/idea/src/org/jetbrains/kotlin/idea/projectView/KtClassOrObjectTreeNode.kt b/idea/src/org/jetbrains/kotlin/idea/projectView/KtClassOrObjectTreeNode.kt index 891df55c475..5382515f728 100644 --- a/idea/src/org/jetbrains/kotlin/idea/projectView/KtClassOrObjectTreeNode.kt +++ b/idea/src/org/jetbrains/kotlin/idea/projectView/KtClassOrObjectTreeNode.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.projectView @@ -28,8 +17,8 @@ import org.jetbrains.kotlin.idea.structureView.getStructureDeclarations import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtPsiUtil -class KtClassOrObjectTreeNode(project: Project?, ktClassOrObject: KtClassOrObject, viewSettings: ViewSettings) - : AbstractPsiBasedNode(project, ktClassOrObject, viewSettings) { +class KtClassOrObjectTreeNode(project: Project?, ktClassOrObject: KtClassOrObject, viewSettings: ViewSettings) : + AbstractPsiBasedNode(project, ktClassOrObject, viewSettings) { override fun extractPsiFromValue(): PsiElement? = value @@ -41,8 +30,7 @@ class KtClassOrObjectTreeNode(project: Project?, ktClassOrObject: KtClassOrObjec else KtDeclarationTreeNode(project, declaration, settings) } - } - else { + } else { emptyList() } } @@ -64,8 +52,7 @@ class KtClassOrObjectTreeNode(project: Project?, ktClassOrObject: KtClassOrObjec if (parent is KtFileTreeNode) { update(parent.getParent()) } - } - else { + } else { if (parent !is KtClassOrObjectTreeNode && parent !is KtFileTreeNode) { update(parent) } diff --git a/idea/src/org/jetbrains/kotlin/idea/projectView/projectViewProviders.kt b/idea/src/org/jetbrains/kotlin/idea/projectView/projectViewProviders.kt index 1da62801edb..adf303d8a68 100644 --- a/idea/src/org/jetbrains/kotlin/idea/projectView/projectViewProviders.kt +++ b/idea/src/org/jetbrains/kotlin/idea/projectView/projectViewProviders.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.projectView @@ -39,9 +28,9 @@ class KotlinExpandNodeProjectViewProvider : TreeStructureProvider, DumbAware { // should be called after ClassesTreeStructureProvider override fun modify( - parent: AbstractTreeNode, - children: Collection>, - settings: ViewSettings + parent: AbstractTreeNode, + children: Collection>, + settings: ViewSettings ): Collection> { val result = ArrayList>() @@ -52,12 +41,10 @@ class KotlinExpandNodeProjectViewProvider : TreeStructureProvider, DumbAware { val mainClass = KotlinIconProvider.getSingleClass(childValue) if (mainClass != null) { result.add(KtClassOrObjectTreeNode(childValue.project, mainClass, settings)) - } - else { + } else { result.add(KtFileTreeNode(childValue.project, childValue, settings)) } - } - else { + } else { result.add(child) } @@ -81,9 +68,9 @@ class KotlinSelectInProjectViewProvider(private val project: Project) : Selectab override fun getData(selected: Collection>, dataName: String): Any? = null override fun modify( - parent: AbstractTreeNode, - children: Collection>, - settings: ViewSettings + parent: AbstractTreeNode, + children: Collection>, + settings: ViewSettings ): Collection> { return ArrayList(children) } @@ -112,9 +99,7 @@ class KotlinSelectInProjectViewProvider(private val project: Project) : Selectab private fun PsiElement.isSelectable(): Boolean = when (this) { is KtFile -> true - is KtDeclaration -> - parent is KtFile || - ((parent as? KtClassBody)?.parent as? KtClassOrObject)?.isSelectable() ?: false + is KtDeclaration -> parent is KtFile || ((parent as? KtClassBody)?.parent as? KtClassOrObject)?.isSelectable() ?: false else -> false } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/AbstractImportFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/AbstractImportFix.kt index 33160c36e43..8663091a8ff 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/AbstractImportFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/AbstractImportFix.kt @@ -91,7 +91,9 @@ internal abstract class ImportFixBase protected constructor( if (!element.isValid || isOutdated()) return false - if (ApplicationManager.getApplication().isUnitTestMode && HintManager.getInstance().hasShownHintsThatWillHideByOtherHint(true)) return false + if (ApplicationManager.getApplication().isUnitTestMode && HintManager.getInstance() + .hasShownHintsThatWillHideByOtherHint(true) + ) return false if (suggestions.isEmpty()) return false @@ -262,7 +264,8 @@ internal abstract class OrdinaryImportFixBase(expression: T, f } // This is required to be abstract to reduce bunch file size -internal abstract class AbstractImportFix(expression: KtSimpleNameExpression, factory: Factory) : OrdinaryImportFixBase(expression, factory) { +internal abstract class AbstractImportFix(expression: KtSimpleNameExpression, factory: Factory) : + OrdinaryImportFixBase(expression, factory) { override fun getCallTypeAndReceiver() = element?.let { CallTypeAndReceiver.detect(it) } private fun importNamesForMembers(): Collection { diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/ActualImportFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/ActualImportFix.kt index 7e378b0dde0..af7d6d1f6ca 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/ActualImportFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/ActualImportFix.kt @@ -10,7 +10,7 @@ import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.codeInsight.KotlinCodeInsightWorkspaceSettings import org.jetbrains.kotlin.psi.KtSimpleNameExpression -internal class ImportFix(expression: KtSimpleNameExpression): AbstractImportFix(expression, MyFactory) { +internal class ImportFix(expression: KtSimpleNameExpression) : AbstractImportFix(expression, MyFactory) { override fun fixSilently(editor: Editor): Boolean { if (isOutdated()) return false val element = element ?: return false diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/AddArrayOfTypeFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/AddArrayOfTypeFix.kt index fd6fddfab92..224e8bb3c94 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/AddArrayOfTypeFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/AddArrayOfTypeFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -30,8 +19,7 @@ class AddArrayOfTypeFix(expression: KtExpression, expectedType: KotlinType) : Ko private val prefix = if (KotlinBuiltIns.isArray(expectedType)) { "arrayOf" - } - else { + } else { val typeName = DescriptorRenderer.SHORT_NAMES_IN_TYPES.renderType(expectedType) "${typeName.decapitalize()}Of" diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/AddDataModifierFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/AddDataModifierFix.kt index a81715ae59d..0a478ea5f15 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/AddDataModifierFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/AddDataModifierFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -46,13 +35,12 @@ class AddDataModifierFix(element: KtClass, private val fqName: String) : AddModi val callableDescriptor = if (element is KtDestructuringDeclarationEntry) { context[BindingContext.DECLARATION_TO_DESCRIPTOR, element.parent.parent] as? CallableDescriptor - } - else { + } else { element.getResolvedCall(context)?.resultingDescriptor } val constructor = callableDescriptor?.returnType?.arguments?.firstOrNull()?.type?.constructor - ?: callableDescriptor?.returnType?.constructor + ?: callableDescriptor?.returnType?.constructor val classDescriptor = constructor?.declarationDescriptor as? ClassDescriptor ?: return null @@ -62,12 +50,13 @@ class AddDataModifierFix(element: KtClass, private val fqName: String) : AddModi if (ctorParams.isEmpty()) return null if (!ctorParams.all { - if (it.varargElementType != null) return@all false - val property = context[BindingContext.VALUE_PARAMETER_AS_PROPERTY, it] ?: return@all false - // NB: we use element as receiver because element is a constructor call - // which is effectively used as receiver by destructuring declaration - property.isVisible(element, element, context, element.getResolutionFacade()) - }) return null + if (it.varargElementType != null) return@all false + val property = context[BindingContext.VALUE_PARAMETER_AS_PROPERTY, it] ?: return@all false + // NB: we use element as receiver because element is a constructor call + // which is effectively used as receiver by destructuring declaration + property.isVisible(element, element, context, element.getResolutionFacade()) + } + ) return null val klass = DescriptorToSourceUtils.descriptorToDeclaration(classDescriptor) as? KtClass ?: return null val fqName = DescriptorUtils.getFqName(classDescriptor).asString() diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/AddExplicitImportForDeprecatedVisibilityFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/AddExplicitImportForDeprecatedVisibilityFix.kt index 49cd19f3eab..1c2563409ef 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/AddExplicitImportForDeprecatedVisibilityFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/AddExplicitImportForDeprecatedVisibilityFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -28,7 +17,8 @@ import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtFile -internal class AddExplicitImportForDeprecatedVisibilityFix(expression: KtElement, private val targetFqName: FqName) : KotlinQuickFixAction(expression) { +internal class AddExplicitImportForDeprecatedVisibilityFix(expression: KtElement, private val targetFqName: FqName) : + KotlinQuickFixAction(expression) { override fun invoke(project: Project, editor: Editor?, file: KtFile) { val targetDescriptor = file.resolveImportReference(targetFqName).singleOrNull() ?: return ImportInsertHelper.getInstance(project).importDescriptor(file, targetDescriptor) diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/AddGenericUpperBoundFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/AddGenericUpperBoundFix.kt index 636feb91e33..60738071c6d 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/AddGenericUpperBoundFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/AddGenericUpperBoundFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -36,8 +25,8 @@ import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.Variance class AddGenericUpperBoundFix( - typeParameter: KtTypeParameter, - upperBound: KotlinType + typeParameter: KtTypeParameter, + upperBound: KotlinType ) : KotlinQuickFixAction(typeParameter) { private val renderedUpperBound: String = IdeDescriptorRenderers.SOURCE_CODE.renderType(upperBound) @@ -82,17 +71,17 @@ class AddGenericUpperBoundFix( val resultingSubstitutor = successfulConstraintSystem.resultingSubstitutor - return inferenceData.descriptor.typeParameters.mapNotNull factory@{ - typeParameterDescriptor -> + return inferenceData.descriptor.typeParameters.mapNotNull factory@{ typeParameterDescriptor -> if (ConstraintsUtil.checkUpperBoundIsSatisfied( successfulConstraintSystem, typeParameterDescriptor, inferenceData.call, /* substituteOtherTypeParametersInBound */ true - )) return@factory null + ) + ) return@factory null val upperBound = typeParameterDescriptor.upperBounds.singleOrNull() ?: return@factory null val argument = resultingSubstitutor.substitute(typeParameterDescriptor.defaultType, Variance.INVARIANT) - ?: return@factory null + ?: return@factory null createAction(argument, upperBound) } @@ -103,7 +92,7 @@ class AddGenericUpperBoundFix( val typeParameterDescriptor = (argument.constructor.declarationDescriptor as? TypeParameterDescriptor) ?: return null val typeParameterDeclaration = - (DescriptorToSourceUtils.getSourceFromDescriptor(typeParameterDescriptor) as? KtTypeParameter) ?: return null + (DescriptorToSourceUtils.getSourceFromDescriptor(typeParameterDescriptor) as? KtTypeParameter) ?: return null return AddGenericUpperBoundFix(typeParameterDeclaration, upperBound) } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/AddInlineModifierFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/AddInlineModifierFix.kt index ef3b4b4fb53..1716229fbd9 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/AddInlineModifierFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/AddInlineModifierFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -28,8 +17,8 @@ import org.jetbrains.kotlin.psi.KtParameter import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType class AddInlineModifierFix( - parameter: KtParameter, - modifier: KtModifierKeywordToken + parameter: KtParameter, + modifier: KtModifierKeywordToken ) : AddModifierFix(parameter, modifier) { override fun getText() = element?.let { "Add '${modifier.value}' to parameter '${it.name}'" } ?: "" diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/AddInlineToFunctionFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/AddInlineToFunctionFix.kt index bd1fe556c86..47bb82ca1f7 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/AddInlineToFunctionFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/AddInlineToFunctionFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -26,8 +15,8 @@ import org.jetbrains.kotlin.psi.KtFunction import org.jetbrains.kotlin.psi.psiUtil.getParentOfType -class AddInlineToFunctionFix(function: KtFunction): - KotlinQuickFixAction(function) { +class AddInlineToFunctionFix(function: KtFunction) : + KotlinQuickFixAction(function) { override fun getFamilyName(): String = "Add 'inline' to function" override fun getText(): String = "Add 'inline' to function '${element?.name}'" diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/AddNewLineAfterAnnotationsFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/AddNewLineAfterAnnotationsFix.kt index f23b9f9bf86..3f3bf623e29 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/AddNewLineAfterAnnotationsFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/AddNewLineAfterAnnotationsFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -37,7 +26,6 @@ class AddNewLineAfterAnnotationsFix(element: KtAnnotatedExpression) : KotlinQuic } companion object Factory : KotlinSingleIntentionActionFactory() { - override fun createAction(diagnostic: Diagnostic) = - diagnostic.createIntentionForFirstParentOfType(::AddNewLineAfterAnnotationsFix) + override fun createAction(diagnostic: Diagnostic) = diagnostic.createIntentionForFirstParentOfType(::AddNewLineAfterAnnotationsFix) } } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/AddStarProjectionsFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/AddStarProjectionsFix.kt index 00261f0c117..df7de04999c 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/AddStarProjectionsFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/AddStarProjectionsFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -42,7 +31,8 @@ object AddStarProjectionsFixFactory : KotlinSingleIntentionActionFactory() { return AddStartProjectionsForInnerClass(typeReference) else { val typeElement = typeReference.typeElement ?: return null - val unwrappedType = generateSequence(typeElement) { (it as? KtNullableType)?.innerType }.lastOrNull() as? KtUserType ?: return null + val unwrappedType = + generateSequence(typeElement) { (it as? KtNullableType)?.innerType }.lastOrNull() as? KtUserType ?: return null return AddStarProjectionsFix(unwrappedType, diagnosticWithParameters.a) } } @@ -92,8 +82,7 @@ class AddStartProjectionsForInnerClass(element: KtTypeReference) : KotlinQuickFi return if (last.isInner && next.declaredTypeParameters.isNotEmpty() || !last.inScope(scope)) { targets + next - } - else { + } else { targets } } @@ -109,7 +98,6 @@ class AddStartProjectionsForInnerClass(element: KtTypeReference) : KotlinQuickFi } private fun KtTypeReference.classDescriptor(): ClassDescriptor? = - this.analyze()[BindingContext.TYPE, this]?.constructor?.declarationDescriptor as? ClassDescriptor + this.analyze()[BindingContext.TYPE, this]?.constructor?.declarationDescriptor as? ClassDescriptor -private fun ClassDescriptor.inScope(scope: LexicalScope): Boolean = - scope.findClassifier(this.name, NoLookupLocation.FROM_IDE) != null +private fun ClassDescriptor.inScope(scope: LexicalScope): Boolean = scope.findClassifier(this.name, NoLookupLocation.FROM_IDE) != null diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/AddSuspendModifierFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/AddSuspendModifierFix.kt index b135121c45c..13130f55d45 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/AddSuspendModifierFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/AddSuspendModifierFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -27,16 +16,15 @@ import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils class AddSuspendModifierFix( - element: KtModifierListOwner, - private val declarationName: String? -): AddModifierFix(element, KtTokens.SUSPEND_KEYWORD) { + element: KtModifierListOwner, + private val declarationName: String? +) : AddModifierFix(element, KtTokens.SUSPEND_KEYWORD) { - override fun getText() = - when (element) { - is KtNamedFunction -> "Make ${declarationName ?: "containing function"} suspend" - is KtTypeReference -> "Make ${declarationName ?: "receiver"} type suspend" - else -> super.getText() - } + override fun getText() = when (element) { + is KtNamedFunction -> "Make ${declarationName ?: "containing function"} suspend" + is KtTypeReference -> "Make ${declarationName ?: "receiver"} type suspend" + else -> super.getText() + } companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { @@ -63,7 +51,7 @@ class AddSuspendModifierFix( val receiverDescriptor = receiver.resolveToCall()?.resultingDescriptor as? ValueDescriptor ?: return null if (!receiverDescriptor.type.isFunctionType) return null val declaration = DescriptorToSourceUtils.descriptorToDeclaration(receiverDescriptor) as? KtCallableDeclaration - ?: return null + ?: return null if (declaration is KtFunction) return null val variableTypeReference = declaration.typeReference ?: return null diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/AddToStringFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/AddToStringFix.kt index d96e7b6afe6..76820520bfe 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/AddToStringFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/AddToStringFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -26,7 +15,8 @@ import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.createExpressionByPattern import org.jetbrains.kotlin.psi.psiUtil.endOffset -class AddToStringFix(element: KtExpression, private val nullable: Boolean) : KotlinQuickFixAction(element), LowPriorityAction { +class AddToStringFix(element: KtExpression, private val nullable: Boolean) : KotlinQuickFixAction(element), + LowPriorityAction { override fun getFamilyName() = "Add 'toString()' call" override fun getText() = if (nullable) "Add safe '?.toString()' call" else "Add 'toString()' call" diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/AddTypeAnnotationToValueParameterFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/AddTypeAnnotationToValueParameterFix.kt index 1b77ad06a0a..989d10beb86 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/AddTypeAnnotationToValueParameterFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/AddTypeAnnotationToValueParameterFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -34,7 +23,7 @@ import org.jetbrains.kotlin.resolve.calls.callUtil.getType import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class AddTypeAnnotationToValueParameterFix(element: KtParameter) : KotlinQuickFixAction(element) { - private val typeNameShort : String? + private val typeNameShort: String? val typeName: String? init { @@ -46,8 +35,7 @@ class AddTypeAnnotationToValueParameterFix(element: KtParameter) : KotlinQuickFi element.builtIns.getArrayElementType(type) else type.arguments.singleOrNull()?.type - } - else if (defaultValue is KtCollectionLiteralExpression) { + } else if (defaultValue is KtCollectionLiteralExpression) { val builtIns = element.builtIns val elementType = builtIns.getArrayElementType(type) if (KotlinBuiltIns.isPrimitiveType(elementType)) { diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/AssignToPropertyFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/AssignToPropertyFix.kt index 9ab1d56937b..b218b90276c 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/AssignToPropertyFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/AssignToPropertyFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -42,8 +31,7 @@ class AssignToPropertyFix(element: KtNameReferenceExpression) : KotlinQuickFixAc val psiFactory = KtPsiFactory(element) if (element.getResolutionScope().getImplicitReceiversHierarchy().size == 1) { element.replace(psiFactory.createExpressionByPattern("this.$0", element)) - } - else { + } else { element.containingClass()?.name?.let { element.replace(psiFactory.createExpressionByPattern("this@$0.$1", it, element)) } @@ -52,7 +40,7 @@ class AssignToPropertyFix(element: KtNameReferenceExpression) : KotlinQuickFixAc companion object : KotlinSingleIntentionActionFactory() { private fun KtCallableDeclaration.hasNameAndTypeOf(name: Name, type: KotlinType) = - nameAsName == name && (resolveToDescriptorIfAny() as? CallableDescriptor)?.returnType == type + nameAsName == name && (resolveToDescriptorIfAny() as? CallableDescriptor)?.returnType == type override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction? { val expression = diagnostic.psiElement as? KtNameReferenceExpression ?: return null @@ -64,12 +52,11 @@ class AssignToPropertyFix(element: KtNameReferenceExpression) : KotlinQuickFixAc val inSecondaryConstructor = expression.getStrictParentOfType() != null val hasAssignableProperty = containingClass.getProperties().any { - (inSecondaryConstructor || it.isVar) && - it.hasNameAndTypeOf(name, type) + (inSecondaryConstructor || it.isVar) && it.hasNameAndTypeOf(name, type) } val hasAssignablePropertyInPrimaryConstructor = containingClass.primaryConstructor?.valueParameters?.any { it.valOrVarKeyword?.node?.elementType == KtTokens.VAR_KEYWORD && - it.hasNameAndTypeOf(name, type) + it.hasNameAndTypeOf(name, type) } ?: false if (!hasAssignableProperty && !hasAssignablePropertyInPrimaryConstructor) return null diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/CastExpressionFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/CastExpressionFix.kt index b62566e02f0..902b173e383 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/CastExpressionFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/CastExpressionFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -39,14 +28,13 @@ class CastExpressionFix(element: KtExpression, type: KotlinType) : KotlinQuickFi private val upOrDownCast: Boolean = run { val expressionType = element.analyze(BodyResolveMode.PARTIAL).getType(element) expressionType != null && (type.isSubtypeOf(expressionType) || expressionType.isSubtypeOf(type)) - && expressionType != type.makeNullable() //covered by AddExclExclCallFix + && expressionType != type.makeNullable() //covered by AddExclExclCallFix } override fun getFamilyName() = "Cast expression" override fun getText() = element?.let { "Cast expression '${it.text}' to '$typePresentation'" } ?: "" - override fun isAvailable(project: Project, editor: Editor?, file: KtFile) - = upOrDownCast + override fun isAvailable(project: Project, editor: Editor?, file: KtFile) = upOrDownCast public override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = element ?: return @@ -61,7 +49,7 @@ class CastExpressionFix(element: KtExpression, type: KotlinType) : KotlinQuickFi override fun createFix(originalElement: KtExpression, data: KotlinType) = CastExpressionFix(originalElement, data) } - object SmartCastImpossibleFactory: Factory() { + object SmartCastImpossibleFactory : Factory() { override fun extractFixData(element: KtExpression, diagnostic: Diagnostic) = Errors.SMARTCAST_IMPOSSIBLE.cast(diagnostic).a } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeAccessorTypeFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeAccessorTypeFix.kt index e9716094c22..abf31d2b013 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeAccessorTypeFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeAccessorTypeFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -31,8 +20,7 @@ import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.isError class ChangeAccessorTypeFix(element: KtPropertyAccessor) : KotlinQuickFixAction(element) { - private fun getType(): KotlinType? = - element!!.property.resolveToDescriptorIfAny()?.type?.takeUnless(KotlinType::isError) + private fun getType(): KotlinType? = element!!.property.resolveToDescriptorIfAny()?.type?.takeUnless(KotlinType::isError) override fun isAvailable(project: Project, editor: Editor?, file: KtFile) = getType() != null diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeFunctionLiteralReturnTypeFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeFunctionLiteralReturnTypeFix.kt index 52ae55f4b72..264c5ef56b2 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeFunctionLiteralReturnTypeFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeFunctionLiteralReturnTypeFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -37,8 +26,8 @@ import org.jetbrains.kotlin.types.checker.KotlinTypeChecker import java.util.* class ChangeFunctionLiteralReturnTypeFix( - functionLiteralExpression: KtLambdaExpression, - type: KotlinType + functionLiteralExpression: KtLambdaExpression, + type: KotlinType ) : KotlinQuickFixAction(functionLiteralExpression) { private val typePresentation = IdeDescriptorRenderers.SOURCE_CODE_TYPES_WITH_SHORT_NAMES.renderType(type) @@ -90,25 +79,29 @@ class ChangeFunctionLiteralReturnTypeFix( val parentFunction = PsiTreeUtil.getParentOfType(functionLiteralExpression, KtFunction::class.java, true) - if (parentFunction != null && QuickFixUtil.canFunctionOrGetterReturnExpression(parentFunction, functionLiteralExpression)) { + return if (parentFunction != null && QuickFixUtil.canFunctionOrGetterReturnExpression(parentFunction, functionLiteralExpression)) { val parentFunctionReturnTypeRef = parentFunction.typeReference val parentFunctionReturnType = context.get(BindingContext.TYPE, parentFunctionReturnTypeRef) - return if (parentFunctionReturnType != null && !KotlinTypeChecker.DEFAULT.isSubtypeOf(eventualFunctionLiteralType, parentFunctionReturnType)) + if (parentFunctionReturnType != null && !KotlinTypeChecker.DEFAULT + .isSubtypeOf(eventualFunctionLiteralType, parentFunctionReturnType) + ) ChangeCallableReturnTypeFix.ForEnclosing(parentFunction, eventualFunctionLiteralType) else null - } - - return null + } else + null } override fun getText() = appropriateQuickFix?.text ?: "Change lambda expression return type to '$typePresentation'" override fun getFamilyName() = KotlinBundle.message("change.type.family") - override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean { - return functionLiteralReturnTypeRef != null || appropriateQuickFix != null && appropriateQuickFix.isAvailable(project, editor!!, file) - } + override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean = + functionLiteralReturnTypeRef != null || appropriateQuickFix != null && appropriateQuickFix.isAvailable( + project, + editor!!, + file + ) override fun invoke(project: Project, editor: Editor?, file: KtFile) { functionLiteralReturnTypeRef?.let { diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeParameterTypeFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeParameterTypeFix.kt index 9d6a5d60c0d..035ac9568c2 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeParameterTypeFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeParameterTypeFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -35,7 +24,8 @@ import org.jetbrains.kotlin.types.KotlinType class ChangeParameterTypeFix(element: KtParameter, type: KotlinType) : KotlinQuickFixAction(element) { private val typePresentation = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderType(type) - private val typeInfo = KotlinTypeInfo(isCovariant = false, text = IdeDescriptorRenderers.SOURCE_CODE_NOT_NULL_TYPE_APPROXIMATION.renderType(type)) + private val typeInfo = + KotlinTypeInfo(isCovariant = false, text = IdeDescriptorRenderers.SOURCE_CODE_NOT_NULL_TYPE_APPROXIMATION.renderType(type)) private val containingDeclarationName: String? private val isPrimaryConstructorParameter: Boolean diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeSuperTypeListEntryTypeArgumentFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeSuperTypeListEntryTypeArgumentFix.kt index 1d64df1813e..f96bc15860f 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeSuperTypeListEntryTypeArgumentFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeSuperTypeListEntryTypeArgumentFix.kt @@ -1,5 +1,5 @@ /* - * Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -81,7 +81,8 @@ class ChangeSuperTypeListEntryTypeArgumentFix( (it.typeAsUserType?.referenceExpression?.mainReference?.resolve() as? KtClass)?.descriptor == superClassDescriptor } is KtSuperTypeCallEntry -> { - it.calleeExpression.resolveToCall()?.resultingDescriptor?.returnType?.constructor?.declarationDescriptor == superClassDescriptor + it.calleeExpression.resolveToCall()?.resultingDescriptor?.returnType?.constructor + ?.declarationDescriptor == superClassDescriptor } else -> false } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeSuspendInHierarchyFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeSuspendInHierarchyFix.kt index 743d0fe05ef..93030a423a3 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeSuspendInHierarchyFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeSuspendInHierarchyFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -52,8 +41,8 @@ import java.util.* import kotlin.collections.filter class ChangeSuspendInHierarchyFix( - element: KtNamedFunction, - private val addModifier: Boolean + element: KtNamedFunction, + private val addModifier: Boolean ) : KotlinQuickFixAction(element) { override fun getFamilyName(): String { return if (addModifier) { @@ -87,10 +76,10 @@ class ChangeSuspendInHierarchyFix( val subClass = it.unwrapped as? KtClassOrObject ?: return@mapNotNullTo null val classDescriptor = subClass.unsafeResolveToDescriptor() as ClassDescriptor val substitutor = getTypeSubstitutor(baseClassDescriptor.defaultType, classDescriptor.defaultType) - ?: return@mapNotNullTo null + ?: return@mapNotNullTo null val signatureInSubClass = baseFunctionDescriptor.substitute(substitutor) as FunctionDescriptor val subFunctionDescriptor = classDescriptor.findCallableMemberBySignature(signatureInSubClass, true) - ?: return@mapNotNullTo null + ?: return@mapNotNullTo null subFunctionDescriptor.source.getPsi() as? KtNamedFunction } } @@ -107,8 +96,7 @@ class ChangeSuspendInHierarchyFix( functions.forEach { if (addModifier) { it.addModifier(KtTokens.SUSPEND_KEYWORD) - } - else { + } else { it.removeModifier(KtTokens.SUSPEND_KEYWORD) } } @@ -124,9 +112,10 @@ class ChangeSuspendInHierarchyFix( val classDescriptor = containingDeclaration as? ClassDescriptorWithResolutionScopes ?: return emptyList() DescriptorUtils.getSuperclassDescriptors(classDescriptor).flatMap { superClassDescriptor -> if (superClassDescriptor !is ClassDescriptorWithResolutionScopes) return@flatMap emptyList() - val candidates = superClassDescriptor.unsubstitutedMemberScope.getContributedFunctions(name, NoLookupLocation.FROM_IDE) + val candidates = + superClassDescriptor.unsubstitutedMemberScope.getContributedFunctions(name, NoLookupLocation.FROM_IDE) val substitutor = getTypeSubstitutor(superClassDescriptor.defaultType, classDescriptor.defaultType) - ?: return@flatMap emptyList() + ?: return@flatMap emptyList() candidates.filter { val signature = it.substitute(substitutor) as FunctionDescriptor classDescriptor.findCallableMemberBySignature(signature, true) == this @@ -136,19 +125,19 @@ class ChangeSuspendInHierarchyFix( } return DFS.dfs( - listOf(this), - { it?.getOverridables() ?: emptyList() }, - object : DFS.CollectingNodeHandler>(ArrayList()) { - override fun afterChildren(current: FunctionDescriptor) { - if (current.getOverridables().isEmpty()) { - result.add(current) - } + listOf(this), + { it?.getOverridables() ?: emptyList() }, + object : DFS.CollectingNodeHandler>(ArrayList()) { + override fun afterChildren(current: FunctionDescriptor) { + if (current.getOverridables().isEmpty()) { + result.add(current) } - }) + } + }) } private fun Collection.getOverridables( - currentDescriptor: FunctionDescriptor + currentDescriptor: FunctionDescriptor ): List { val currentClassDescriptor = currentDescriptor.containingDeclaration as? ClassDescriptor ?: return emptyList() return filter { @@ -157,8 +146,8 @@ class ChangeSuspendInHierarchyFix( val containingClassDescriptor = it.containingDeclaration as? ClassDescriptor ?: return@filter false if (!currentClassDescriptor.isSubclassOf(containingClassDescriptor)) return@filter false val substitutor = getTypeSubstitutor( - containingClassDescriptor.defaultType, - currentClassDescriptor.defaultType + containingClassDescriptor.defaultType, + currentClassDescriptor.defaultType ) ?: return@filter false val signatureInCurrentClass = it.substitute(substitutor) ?: return@filter false OverridingUtil.DEFAULT.isOverridableBy(signatureInCurrentClass, currentDescriptor, null).result == @@ -172,8 +161,8 @@ class ChangeSuspendInHierarchyFix( Errors.CONFLICTING_OVERLOADS.cast(diagnostic).a.getOverridables(currentDescriptor).ifEmpty { return emptyList() } return listOf( - ChangeSuspendInHierarchyFix(currentFunction, true), - ChangeSuspendInHierarchyFix(currentFunction, false) + ChangeSuspendInHierarchyFix(currentFunction, true), + ChangeSuspendInHierarchyFix(currentFunction, false) ) } } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeToLabeledReturnFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeToLabeledReturnFix.kt index 71c2b5ac70b..2e082e09643 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeToLabeledReturnFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeToLabeledReturnFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -30,7 +19,7 @@ import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.inline.InlineUtil class ChangeToLabeledReturnFix( - element: KtReturnExpression, val labeledReturn: String + element: KtReturnExpression, val labeledReturn: String ) : KotlinQuickFixAction(element) { override fun getFamilyName() = "Change to return with label" diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeToPropertyAccessFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeToPropertyAccessFix.kt index 1e504320bfa..75f6ffa90f4 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeToPropertyAccessFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeToPropertyAccessFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -26,8 +15,9 @@ import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.resolve.calls.util.FakeCallableDescriptorForObject class ChangeToPropertyAccessFix( - element: KtCallExpression, - private val isObjectCall: Boolean) : KotlinQuickFixAction(element) { + element: KtCallExpression, + private val isObjectCall: Boolean +) : KotlinQuickFixAction(element) { override fun getFamilyName() = if (isObjectCall) "Remove invocation" else "Change to property access" diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeToStarProjectionFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeToStarProjectionFix.kt index 32e209eb399..862e4827469 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeToStarProjectionFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeToStarProjectionFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -88,7 +77,7 @@ class ChangeToStarProjectionFix(element: KtTypeElement) : KotlinQuickFixAction { return (this?.typeElement as? KtUserType)?.typeArguments.orEmpty() } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeTypeFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeTypeFix.kt index 2b8a75f33f8..e084cf3b1fc 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeTypeFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeTypeFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -45,12 +34,12 @@ class ChangeTypeFix(element: KtTypeReference, private val type: KotlinType) : Ko companion object : KotlinSingleIntentionActionFactoryWithDelegate() { override fun getElementOfInterest(diagnostic: Diagnostic) = - Errors.EXPECTED_PARAMETER_TYPE_MISMATCH.cast(diagnostic).psiElement.typeReference + Errors.EXPECTED_PARAMETER_TYPE_MISMATCH.cast(diagnostic).psiElement.typeReference override fun extractFixData(element: KtTypeReference, diagnostic: Diagnostic) = - Errors.EXPECTED_PARAMETER_TYPE_MISMATCH.cast(diagnostic).a + Errors.EXPECTED_PARAMETER_TYPE_MISMATCH.cast(diagnostic).a override fun createFix(originalElement: KtTypeReference, data: KotlinType) = - ChangeTypeFix(originalElement, data) + ChangeTypeFix(originalElement, data) } } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeVisibilityFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeVisibilityFix.kt index 412807c710f..f086f7b8704 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeVisibilityFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeVisibilityFix.kt @@ -45,7 +45,9 @@ open class ChangeVisibilityFix( val pointer = element?.createSmartPointer() val originalElement = pointer?.element if (originalElement is KtDeclaration) { - originalElement.runOnExpectAndAllActuals(useOnSelf = true) { it.setVisibility(visibilityModifier, addImplicitVisibilityModifier) } + originalElement.runOnExpectAndAllActuals(useOnSelf = true) { + it.setVisibility(visibilityModifier, addImplicitVisibilityModifier) + } } else { originalElement?.setVisibility(visibilityModifier, addImplicitVisibilityModifier) } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/CommaInWhenConditionWithoutArgumentFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/CommaInWhenConditionWithoutArgumentFix.kt index d6bcebfad4f..d54bce2964a 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/CommaInWhenConditionWithoutArgumentFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/CommaInWhenConditionWithoutArgumentFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -38,13 +27,13 @@ class CommaInWhenConditionWithoutArgumentFix(element: PsiElement) : KotlinQuickF companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? = - diagnostic.psiElement.parent?.parent?.let(::CommaInWhenConditionWithoutArgumentFix) + diagnostic.psiElement.parent?.parent?.let(::CommaInWhenConditionWithoutArgumentFix) private class WhenEntryConditionsData( - val conditions: Array, - val first: PsiElement, - val last: PsiElement, - val arrow: PsiElement + val conditions: Array, + val first: PsiElement, + val last: PsiElement, + val arrow: PsiElement ) private fun replaceCommasWithOrsInWhenExpression(whenExpression: KtWhenExpression) { diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/ConvertClassToKClassFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/ConvertClassToKClassFix.kt index 080c188017b..54245a50724 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/ConvertClassToKClassFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/ConvertClassToKClassFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -40,7 +29,8 @@ private fun KotlinType.isJClass(): Boolean { return expressionTypeFqName == JAVA_LANG_CLASS_FQ_NAME } -class ConvertClassToKClassFix(element: KtDotQualifiedExpression, type: KotlinType) : KotlinQuickFixAction(element) { +class ConvertClassToKClassFix(element: KtDotQualifiedExpression, type: KotlinType) : + KotlinQuickFixAction(element) { private val isApplicable: Boolean = run { val bindingContext = element.analyze(BodyResolveMode.PARTIAL) val expressionType = bindingContext.getType(element) ?: return@run false diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/DelegatingIntentionAction.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/DelegatingIntentionAction.kt index 19b95f51f30..a87ffc2c28b 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/DelegatingIntentionAction.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/DelegatingIntentionAction.kt @@ -1,21 +1,10 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.intention.IntentionAction -open class DelegatingIntentionAction(val delegate: IntentionAction): IntentionAction by delegate +open class DelegatingIntentionAction(val delegate: IntentionAction) : IntentionAction by delegate diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/InitializePropertyQuickFixFactory.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/InitializePropertyQuickFixFactory.kt index f74390ff65e..f81bc4a4b4c 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/InitializePropertyQuickFixFactory.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/InitializePropertyQuickFixFactory.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -74,18 +63,21 @@ object InitializePropertyQuickFixFactory : KotlinIntentionActionsFactory() { override fun startInWriteAction(): Boolean = false - private fun configureChangeSignature(property: KtProperty, propertyDescriptor: PropertyDescriptor): KotlinChangeSignatureConfiguration { + private fun configureChangeSignature( + property: KtProperty, + propertyDescriptor: PropertyDescriptor + ): KotlinChangeSignatureConfiguration { return object : KotlinChangeSignatureConfiguration { override fun configure(originalDescriptor: KotlinMethodDescriptor): KotlinMethodDescriptor { return originalDescriptor.modify { val initializerText = CodeInsightUtils.defaultInitializer(propertyDescriptor.type) ?: "null" val newParam = KotlinParameterInfo( - callableDescriptor = originalDescriptor.baseDescriptor, - name = propertyDescriptor.name.asString(), - originalTypeInfo = KotlinTypeInfo(false, propertyDescriptor.type), - valOrVar = property.valOrVarKeyword.toValVar(), - modifierList = property.modifierList, - defaultValueForCall = KtPsiFactory(property.project).createExpression(initializerText) + callableDescriptor = originalDescriptor.baseDescriptor, + name = propertyDescriptor.name.asString(), + originalTypeInfo = KotlinTypeInfo(false, propertyDescriptor.type), + valOrVar = property.valOrVarKeyword.toValVar(), + modifierList = property.modifierList, + defaultValueForCall = KtPsiFactory(property.project).createExpression(initializerText) ) it.addParameter(newParam) } @@ -123,8 +115,7 @@ object InitializePropertyQuickFixFactory : KotlinIntentionActionsFactory() { constructor?.getValueParameters()?.lastOrNull()?.replace(parameterToInsert) } }.run() - } - finally { + } finally { FinishMarkAction.finish(project, editor, startMarkAction) } } @@ -149,10 +140,10 @@ object InitializePropertyQuickFixFactory : KotlinIntentionActionsFactory() { } val initializerText = CodeInsightUtils.defaultInitializer(propertyDescriptor.type) ?: "null" val newParam = KotlinParameterInfo( - callableDescriptor = originalDescriptor.baseDescriptor, - name = KotlinNameSuggester.suggestNameByName(propertyDescriptor.name.asString(), validator), - originalTypeInfo = KotlinTypeInfo(false, propertyDescriptor.type), - defaultValueForCall = KtPsiFactory(element!!.project).createExpression(initializerText) + callableDescriptor = originalDescriptor.baseDescriptor, + name = KotlinNameSuggester.suggestNameByName(propertyDescriptor.name.asString(), validator), + originalTypeInfo = KotlinTypeInfo(false, propertyDescriptor.type), + defaultValueForCall = KtPsiFactory(element!!.project).createExpression(initializerText) ) it.addParameter(newParam) } @@ -164,10 +155,10 @@ object InitializePropertyQuickFixFactory : KotlinIntentionActionsFactory() { // TODO: Allow processing of multiple functions in Change Signature so that Start/Finish Mark can be used here private fun processConstructors( - project: Project, - propertyDescriptor: PropertyDescriptor, - descriptorsToProcess: Iterator, - visitedElements: MutableSet = HashSet() + project: Project, + propertyDescriptor: PropertyDescriptor, + descriptorsToProcess: Iterator, + visitedElements: MutableSet = HashSet() ) { val element = element!! @@ -188,7 +179,7 @@ object InitializePropertyQuickFixFactory : KotlinIntentionActionsFactory() { constructor.getValueParameters().lastOrNull()?.let { newParam -> val psiFactory = KtPsiFactory(project) (constructor as? KtSecondaryConstructor)?.getOrCreateBody()?.appendElement( - psiFactory.createExpression("this.${element.name} = ${newParam.name!!}") + psiFactory.createExpression("this.${element.name} = ${newParam.name!!}") ) ?: element.setInitializer(psiFactory.createExpression(newParam.name!!)) } processConstructors(project, propertyDescriptor, descriptorsToProcess) @@ -203,8 +194,7 @@ object InitializePropertyQuickFixFactory : KotlinIntentionActionsFactory() { val klass = element.containingClassOrObject ?: return val constructorDescriptors = if (klass.hasExplicitPrimaryConstructor() || klass.secondaryConstructors.isEmpty()) { listOf(classDescriptor.unsubstitutedPrimaryConstructor!!) - } - else { + } else { classDescriptor.secondaryConstructors.filter { val constructor = it.source.getPsi() as? KtSecondaryConstructor constructor != null && !constructor.getDelegationCall().isCallToThis @@ -234,8 +224,7 @@ object InitializePropertyQuickFixFactory : KotlinIntentionActionsFactory() { if (property.accessors.isNotEmpty() || klass.secondaryConstructors.any { !it.getDelegationCall().isCallToThis }) { actions.add(InitializeWithConstructorParameter(property)) - } - else { + } else { actions.add(MoveToConstructorParameters(property)) } } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/InsertDelegationCallQuickfix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/InsertDelegationCallQuickfix.kt index dcd05ac1507..6f025fc0390 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/InsertDelegationCallQuickfix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/InsertDelegationCallQuickfix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -36,7 +25,8 @@ import org.jetbrains.kotlin.resolve.calls.model.isReallySuccess import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode -class InsertDelegationCallQuickfix(val isThis: Boolean, element: KtSecondaryConstructor) : KotlinQuickFixAction(element) { +class InsertDelegationCallQuickfix(val isThis: Boolean, element: KtSecondaryConstructor) : + KotlinQuickFixAction(element) { override fun getText() = KotlinBundle.message("insert.delegation.call", keywordToUse) override fun getFamilyName() = "Insert explicit delegation call" @@ -50,7 +40,7 @@ class InsertDelegationCallQuickfix(val isThis: Boolean, element: KtSecondaryCons val descriptor = element.unsafeResolveToDescriptor() // if empty call is ok and it's resolved to another constructor, do not move caret - if (resolvedCall?.isReallySuccess() ?: false && resolvedCall!!.candidateDescriptor.original != descriptor) return + if (resolvedCall?.isReallySuccess() == true && resolvedCall.candidateDescriptor.original != descriptor) return val leftParOffset = newDelegationCall.valueArgumentList!!.leftParenthesis!!.textOffset @@ -63,13 +53,14 @@ class InsertDelegationCallQuickfix(val isThis: Boolean, element: KtSecondaryCons } object InsertThisDelegationCallFactory : KotlinSingleIntentionActionFactory() { - override fun createAction(diagnostic: Diagnostic) = diagnostic.createIntentionForFirstParentOfType { - secondaryConstructor -> - if (secondaryConstructor.getContainingClassOrObject().getConstructorsCount() <= 1 || - !secondaryConstructor.hasImplicitDelegationCall()) return null - - return InsertDelegationCallQuickfix(isThis = true, element = secondaryConstructor) - } + override fun createAction(diagnostic: Diagnostic) = + diagnostic.createIntentionForFirstParentOfType { secondaryConstructor -> + return if (secondaryConstructor.getContainingClassOrObject().getConstructorsCount() <= 1 || + !secondaryConstructor.hasImplicitDelegationCall() + ) null + else + InsertDelegationCallQuickfix(isThis = true, element = secondaryConstructor) + } private fun KtClassOrObject.getConstructorsCount() = (descriptor as ClassDescriptor).constructors.size } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/KotlinAddOrderEntryActionFactory.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/KotlinAddOrderEntryActionFactory.kt index 80b9cf171b0..3ad1ef87d36 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/KotlinAddOrderEntryActionFactory.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/KotlinAddOrderEntryActionFactory.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -41,7 +30,7 @@ object KotlinAddOrderEntryActionFactory : KotlinIntentionActionsFactory() { val refElement = simpleExpression.getQualifiedElement() - val reference = object: PsiReferenceBase(refElement) { + val reference = object : PsiReferenceBase(refElement) { override fun resolve() = null override fun getVariants() = PsiReference.EMPTY_ARRAY diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/KotlinAddRequiredModuleFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/KotlinAddRequiredModuleFix.kt index 12690c11f83..5f74140b2d1 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/KotlinAddRequiredModuleFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/KotlinAddRequiredModuleFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -30,9 +19,11 @@ import org.jetbrains.kotlin.idea.util.findRequireDirective import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.resolve.jvm.diagnostics.ErrorsJvm -class KotlinAddRequiredModuleFix(module: PsiJavaModule, private val requiredName: String) : LocalQuickFixAndIntentionActionOnPsiElement(module) { +class KotlinAddRequiredModuleFix(module: PsiJavaModule, private val requiredName: String) : + LocalQuickFixAndIntentionActionOnPsiElement(module) { @Suppress("InvalidBundleOrProperty") override fun getFamilyName(): String = "Add 'requires' directive to module-info.java" + @Suppress("InvalidBundleOrProperty") override fun getText(): String = QuickFixBundle.message("module.info.add.requires.name", requiredName) @@ -40,9 +31,9 @@ class KotlinAddRequiredModuleFix(module: PsiJavaModule, private val requiredName override fun isAvailable(project: Project, file: PsiFile, startElement: PsiElement, endElement: PsiElement): Boolean { return PsiUtil.isLanguageLevel9OrHigher(file) && - startElement is PsiJavaModule && - startElement.getManager().isInProject(startElement) && - getLBrace(startElement) != null + startElement is PsiJavaModule && + startElement.getManager().isInProject(startElement) && + getLBrace(startElement) != null } override fun invoke(project: Project, file: PsiFile, editor: Editor?, startElement: PsiElement, endElement: PsiElement) { diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/KotlinIntentionActionFactoryWithDelegate.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/KotlinIntentionActionFactoryWithDelegate.kt index fe343f25d9d..63fe6b6ca0b 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/KotlinIntentionActionFactoryWithDelegate.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/KotlinIntentionActionFactoryWithDelegate.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -27,36 +16,34 @@ import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode abstract class KotlinSingleIntentionActionFactoryWithDelegate( - private val actionPriority: IntentionActionPriority = IntentionActionPriority.NORMAL + private val actionPriority: IntentionActionPriority = IntentionActionPriority.NORMAL ) : KotlinIntentionActionFactoryWithDelegate() { protected abstract fun createFix(originalElement: E, data: D): IntentionAction? - override final fun createFixes( - originalElementPointer: SmartPsiElementPointer, - diagnostic: Diagnostic, - quickFixDataFactory: () -> D? - ): List { - return QuickFixWithDelegateFactory(actionPriority) factory@ { - val originalElement = originalElementPointer.element ?: return@factory null - val data = quickFixDataFactory() ?: return@factory null - createFix(originalElement, data) - }.let(::listOf) - } + final override fun createFixes( + originalElementPointer: SmartPsiElementPointer, + diagnostic: Diagnostic, + quickFixDataFactory: () -> D? + ): List = QuickFixWithDelegateFactory(actionPriority) factory@{ + val originalElement = originalElementPointer.element ?: return@factory null + val data = quickFixDataFactory() ?: return@factory null + createFix(originalElement, data) + }.let(::listOf) } abstract class KotlinIntentionActionFactoryWithDelegate : KotlinIntentionActionsFactory() { abstract fun getElementOfInterest(diagnostic: Diagnostic): E? protected abstract fun createFixes( - originalElementPointer: SmartPsiElementPointer, - diagnostic: Diagnostic, - quickFixDataFactory: () -> D? + originalElementPointer: SmartPsiElementPointer, + diagnostic: Diagnostic, + quickFixDataFactory: () -> D? ): List abstract fun extractFixData(element: E, diagnostic: Diagnostic): D? - override final fun doCreateActions(diagnostic: Diagnostic): List { + final override fun doCreateActions(diagnostic: Diagnostic): List { val diagnosticMessage = DefaultErrorMessages.render(diagnostic) val diagnosticElementPointer = diagnostic.psiElement.createSmartPointer() val originalElement = getElementOfInterest(diagnostic) ?: return emptyList() @@ -70,21 +57,19 @@ abstract class KotlinIntentionActionFactoryWithDelegate val cachedData: Ref = Ref.create(extractFixData(originalElement, diagnostic)) return try { - createFixes(originalElementPointer, diagnostic) factory@ { + createFixes(originalElementPointer, diagnostic) factory@{ val element = originalElementPointer.element ?: return@factory null val diagnosticElement = diagnosticElementPointer.element ?: return@factory null if (!diagnosticElement.isValid || !element.isValid) return@factory null - val currentDiagnostic = - element.analyze(BodyResolveMode.PARTIAL_WITH_DIAGNOSTICS) - .diagnostics - .forElement(diagnosticElement) - .firstOrNull { DefaultErrorMessages.render(it) == diagnosticMessage } ?: return@factory null + val currentDiagnostic = element.analyze(BodyResolveMode.PARTIAL_WITH_DIAGNOSTICS) + .diagnostics + .forElement(diagnosticElement) + .firstOrNull { DefaultErrorMessages.render(it) == diagnosticMessage } ?: return@factory null cachedData.get() ?: extractFixData(element, currentDiagnostic) }.filter { it.isAvailable(project, null, file) } - } - finally { + } finally { cachedData.set(null) // Do not keep cache after all actions are initialized } } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/LiftAssignmentOutOfTryFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/LiftAssignmentOutOfTryFix.kt index 175f359ec04..5ee90cd96e8 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/LiftAssignmentOutOfTryFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/LiftAssignmentOutOfTryFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -26,7 +15,7 @@ import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtTryExpression -class LiftAssignmentOutOfTryFix(element: KtTryExpression): KotlinQuickFixAction(element) { +class LiftAssignmentOutOfTryFix(element: KtTryExpression) : KotlinQuickFixAction(element) { override fun getFamilyName() = text override fun getText() = "Lift assignment out of 'try' expression" diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/MakeTypeParameterReifiedAndFunctionInlineFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/MakeTypeParameterReifiedAndFunctionInlineFix.kt index a7d1883eb75..d34aeab0702 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/MakeTypeParameterReifiedAndFunctionInlineFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/MakeTypeParameterReifiedAndFunctionInlineFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -29,9 +18,9 @@ import org.jetbrains.kotlin.psi.KtTypeReference import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType class MakeTypeParameterReifiedAndFunctionInlineFix( - typeReference: KtTypeReference, - function: KtNamedFunction, - private val typeParameter: KtTypeParameter + typeReference: KtTypeReference, + function: KtNamedFunction, + private val typeParameter: KtTypeParameter ) : KotlinQuickFixAction(typeReference) { private val inlineFix = AddInlineToFunctionWithReifiedFix(function) diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/MapPlatformClassToKotlinFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/MapPlatformClassToKotlinFix.kt index fecb35accdb..00908a3be1a 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/MapPlatformClassToKotlinFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/MapPlatformClassToKotlinFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -41,19 +30,19 @@ import org.jetbrains.kotlin.renderer.DescriptorRenderer import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull -import java.util.* class MapPlatformClassToKotlinFix( - element: KtReferenceExpression, - private val platformClass: ClassDescriptor, - private val possibleClasses: Collection + element: KtReferenceExpression, + private val platformClass: ClassDescriptor, + private val possibleClasses: Collection ) : KotlinQuickFixAction(element) { override fun getText(): String { val platformClassQualifiedName = DescriptorRenderer.FQ_NAMES_IN_TYPES.renderType(platformClass.defaultType) val singleClass = possibleClasses.singleOrNull() return if (singleClass != null) - "Change all usages of '$platformClassQualifiedName' in this file to '${DescriptorRenderer.FQ_NAMES_IN_TYPES.renderType(singleClass.defaultType)}'" + "Change all usages of '$platformClassQualifiedName' in this file to '${DescriptorRenderer.FQ_NAMES_IN_TYPES + .renderType(singleClass.defaultType)}'" else "Change all usages of '$platformClassQualifiedName' in this file to a Kotlin class" } @@ -75,8 +64,7 @@ class MapPlatformClassToKotlinFix( val import = refExpr.getStrictParentOfType() if (import != null) { imports.add(import) - } - else { + } else { usages.add(refExpr.getStrictParentOfType() ?: continue) } } @@ -120,8 +108,8 @@ class MapPlatformClassToKotlinFix( private val OTHER_USAGE = "OtherUsage" private fun buildAndShowTemplate( - project: Project, editor: Editor, file: PsiFile, - replacedElements: Collection, options: LinkedHashSet + project: Project, editor: Editor, file: PsiFile, + replacedElements: Collection, options: LinkedHashSet ) { PsiDocumentManager.getInstance(project).commitAllDocuments() PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.document) @@ -133,7 +121,8 @@ class MapPlatformClassToKotlinFix( caretModel.moveToOffset(file.node.startOffset) val builder = TemplateBuilderImpl(file) - val expression = MyLookupExpression(primaryReplacedExpression.text, options, null, null, false, "Choose an appropriate Kotlin class") + val expression = + MyLookupExpression(primaryReplacedExpression.text, options, null, null, false, "Choose an appropriate Kotlin class") builder.replaceElement(primaryReplacedExpression, PRIMARY_USAGE, expression, true) for (replacedExpression in replacedElements) { @@ -149,11 +138,12 @@ class MapPlatformClassToKotlinFix( } companion object : KotlinSingleIntentionActionFactoryWithDelegate() { - data class Data(val platformClass: ClassDescriptor, - val possibleClasses: Collection) + data class Data( + val platformClass: ClassDescriptor, + val possibleClasses: Collection + ) - override fun getElementOfInterest(diagnostic: Diagnostic): KtReferenceExpression? - = getImportOrUsageFromDiagnostic(diagnostic) + override fun getElementOfInterest(diagnostic: Diagnostic): KtReferenceExpression? = getImportOrUsageFromDiagnostic(diagnostic) override fun extractFixData(element: KtReferenceExpression, diagnostic: Diagnostic): Data? { val context = element.analyze(BodyResolveMode.PARTIAL) @@ -174,8 +164,7 @@ class MapPlatformClassToKotlinFix( val import = diagnostic.psiElement.getNonStrictParentOfType() return if (import != null) { import.importedReference?.getQualifiedElementSelector() as? KtReferenceExpression - } - else { + } else { (diagnostic.psiElement.getNonStrictParentOfType() ?: return null).referenceExpression } } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/MissingConstructorBracketsFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/MissingConstructorBracketsFix.kt index 55f5b16d12f..88ac103a910 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/MissingConstructorBracketsFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/MissingConstructorBracketsFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -45,6 +34,6 @@ class MissingConstructorBracketsFix(element: KtPrimaryConstructor) : KotlinQuick companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? = - diagnostic.createIntentionForFirstParentOfType(::MissingConstructorBracketsFix) + diagnostic.createIntentionForFirstParentOfType(::MissingConstructorBracketsFix) } } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/MissingConstructorKeywordFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/MissingConstructorKeywordFix.kt index 4b243bc28ca..561c6d8207b 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/MissingConstructorKeywordFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/MissingConstructorKeywordFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -35,6 +24,6 @@ class MissingConstructorKeywordFix(element: KtPrimaryConstructor) : KotlinQuickF companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? = - diagnostic.createIntentionForFirstParentOfType(::MissingConstructorKeywordFix) + diagnostic.createIntentionForFirstParentOfType(::MissingConstructorKeywordFix) } } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/QuickFixActionBase.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/QuickFixActionBase.kt index 8539c7c04af..24b01dd8499 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/QuickFixActionBase.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/QuickFixActionBase.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -44,12 +33,11 @@ abstract class QuickFixActionBase(element: T) : IntentionAct try { val element = element ?: return false return element.isValid && - !element.project.isDisposed && - (file.manager.isInProject(file) || file is KtCodeFragment || (file is KtFile && file.isScript())) && - (file is KtFile || isCrossLanguageFix) && - isAvailableImpl(project, editor, file) - } - finally { + !element.project.isDisposed && + (file.manager.isInProject(file) || file is KtCodeFragment || (file is KtFile && file.isScript())) && + (file is KtFile || isCrossLanguageFix) && + isAvailableImpl(project, editor, file) + } finally { CREATE_BY_PATTERN_MAY_NOT_REFORMAT = false } } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/QuickFixWithDelegateFactory.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/QuickFixWithDelegateFactory.kt index 7dc3a5b7320..4c895e3faf2 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/QuickFixWithDelegateFactory.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/QuickFixWithDelegateFactory.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -25,7 +14,7 @@ import com.intellij.openapi.project.Project import com.intellij.psi.PsiFile open class QuickFixWithDelegateFactory( - private val delegateFactory: () -> IntentionAction? + private val delegateFactory: () -> IntentionAction? ) : IntentionAction { private val familyName: String private val text: String @@ -65,12 +54,12 @@ open class QuickFixWithDelegateFactory( } class LowPriorityQuickFixWithDelegateFactory( - delegateFactory: () -> IntentionAction? -): QuickFixWithDelegateFactory(delegateFactory), LowPriorityAction + delegateFactory: () -> IntentionAction? +) : QuickFixWithDelegateFactory(delegateFactory), LowPriorityAction class HighPriorityQuickFixWithDelegateFactory( - delegateFactory: () -> IntentionAction? -): QuickFixWithDelegateFactory(delegateFactory), HighPriorityAction + delegateFactory: () -> IntentionAction? +) : QuickFixWithDelegateFactory(delegateFactory), HighPriorityAction enum class IntentionActionPriority { LOW, NORMAL, HIGH diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/RemoveFunctionBodyFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/RemoveFunctionBodyFix.kt index b1e3d219f4b..791634409c0 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/RemoveFunctionBodyFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/RemoveFunctionBodyFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -43,8 +32,7 @@ class RemoveFunctionBodyFix(element: KtFunction) : KotlinQuickFixAction? = - (diagnostic.psiElement as? KtValueArgumentList)?.let { RemoveNoConstructorFix(it) } + (diagnostic.psiElement as? KtValueArgumentList)?.let { RemoveNoConstructorFix(it) } } } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/RemovePartsFromPropertyFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/RemovePartsFromPropertyFix.kt index a484b144c4b..06d77c5264a 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/RemovePartsFromPropertyFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/RemovePartsFromPropertyFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -33,21 +22,21 @@ import org.jetbrains.kotlin.types.isError import org.jetbrains.kotlin.types.refinement.TypeRefinement open class RemovePartsFromPropertyFix( - element: KtProperty, - private val removeInitializer: Boolean, - private val removeGetter: Boolean, - private val removeSetter: Boolean + element: KtProperty, + private val removeInitializer: Boolean, + private val removeGetter: Boolean, + private val removeSetter: Boolean ) : KotlinQuickFixAction(element) { private constructor(element: KtProperty) : this( - element, - element.hasInitializer(), - element.getter?.bodyExpression != null, - element.setter?.bodyExpression != null + element, + element.hasInitializer(), + element.getter?.bodyExpression != null, + element.setter?.bodyExpression != null ) override fun getText(): String = - "Remove ${partsToRemove(removeGetter, removeSetter, removeInitializer)} from property" + "Remove ${partsToRemove(removeGetter, removeSetter, removeInitializer)} from property" override fun getFamilyName(): String = "Remove parts from property" diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/RemoveValVarFromParameterFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/RemoveValVarFromParameterFix.kt index 10a98469b55..9b9da4f7c28 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/RemoveValVarFromParameterFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/RemoveValVarFromParameterFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -27,8 +16,8 @@ class RemoveValVarFromParameterFix(element: KtValVarKeywordOwner) : KotlinQuickF private val varOrVal: String init { - val valOrVarNode = element.valOrVarKeyword - ?: throw AssertionError("Val or var node not found for " + element.getElementTextWithContext()) + val valOrVarNode = + element.valOrVarKeyword ?: throw AssertionError("Val or var node not found for " + element.getElementTextWithContext()) varOrVal = valOrVarNode.text } @@ -46,6 +35,6 @@ class RemoveValVarFromParameterFix(element: KtValVarKeywordOwner) : KotlinQuickF companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic) = - RemoveValVarFromParameterFix(diagnostic.psiElement.parent as KtValVarKeywordOwner) + RemoveValVarFromParameterFix(diagnostic.psiElement.parent as KtValVarKeywordOwner) } } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/RenameIdentifierFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/RenameIdentifierFix.kt index 18c39d7331a..2f006980d95 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/RenameIdentifierFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/RenameIdentifierFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -44,8 +33,7 @@ open class RenameIdentifierFix : LocalQuickFix { val editor = editorManager.selectedTextEditor if (editor != null) { renameHandler?.invoke(project, editor, file, dataContext) - } - else { + } else { val elementToRename = getElementToRename(element) ?: return renameHandler?.invoke(project, arrayOf(elementToRename), dataContext) } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/RenameParameterToMatchOverriddenMethodFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/RenameParameterToMatchOverriddenMethodFix.kt index bb7b0f5b4c1..8ae2d07e315 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/RenameParameterToMatchOverriddenMethodFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/RenameParameterToMatchOverriddenMethodFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -28,8 +17,8 @@ import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class RenameParameterToMatchOverriddenMethodFix( - parameter: KtParameter, - private val newName: String + parameter: KtParameter, + private val newName: String ) : KotlinQuickFixAction(parameter) { override fun getFamilyName() = "Rename" @@ -45,11 +34,10 @@ class RenameParameterToMatchOverriddenMethodFix( override fun createAction(diagnostic: Diagnostic): IntentionAction? { val parameter = diagnostic.psiElement.getNonStrictParentOfType() ?: return null val parameterDescriptor = parameter.resolveToParameterDescriptorIfAny(BodyResolveMode.FULL) ?: return null - val parameterFromSuperclassName = parameterDescriptor - .overriddenDescriptors - .map { it.name.asString() } - .distinct() - .singleOrNull() ?: return null + val parameterFromSuperclassName = parameterDescriptor.overriddenDescriptors + .map { it.name.asString() } + .distinct() + .singleOrNull() ?: return null return RenameParameterToMatchOverriddenMethodFix(parameter, parameterFromSuperclassName) } } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/RenameToUnderscoreFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/RenameToUnderscoreFix.kt index 38cc6fdd91a..36bd5c718d9 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/RenameToUnderscoreFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/RenameToUnderscoreFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -50,8 +39,9 @@ class RenameToUnderscoreFix(element: KtCallableDeclaration) : KotlinQuickFixActi else -> null } - if (declaration?.nameIdentifier == null || - !declaration.languageVersionSettings.supportsFeature(LanguageFeature.SingleUnderscoreForParameterName)) { + if (declaration?.nameIdentifier == null || !declaration.languageVersionSettings + .supportsFeature(LanguageFeature.SingleUnderscoreForParameterName) + ) { return null } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/RenameUnresolvedReferenceFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/RenameUnresolvedReferenceFix.kt index c239a643f46..fbcf2ecbeb5 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/RenameUnresolvedReferenceFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/RenameUnresolvedReferenceFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -50,15 +39,15 @@ object RenameUnresolvedReferenceActionFactory : KotlinSingleIntentionActionFacto } } -class RenameUnresolvedReferenceFix(element: KtNameReferenceExpression): KotlinQuickFixAction(element) { +class RenameUnresolvedReferenceFix(element: KtNameReferenceExpression) : KotlinQuickFixAction(element) { companion object { private val INPUT_VARIABLE_NAME = "INPUT_VAR" private val OTHER_VARIABLE_NAME = "OTHER_VAR" } private class ReferenceNameExpression( - private val items: Array, - private val originalReferenceName: String + private val items: Array, + private val originalReferenceName: String ) : Expression() { init { Arrays.sort(items, HammingComparator(originalReferenceName, { lookupString })) @@ -89,11 +78,11 @@ class RenameUnresolvedReferenceFix(element: KtNameReferenceExpression): KotlinQu val container = element.parents.firstOrNull { it is KtDeclarationWithBody || it is KtClassOrObject || it is KtFile } ?: return val isCallee = element.isCallee() val occurrences = patternExpression.toRange() - .match(container, KotlinPsiUnifier.DEFAULT) - .mapNotNull { - val candidate = (it.range.elements.first() as? KtExpression)?.getQualifiedElementSelector() as? KtNameReferenceExpression - if (candidate != null && candidate.isCallee() == isCallee) candidate else null - } + .match(container, KotlinPsiUnifier.DEFAULT) + .mapNotNull { + val candidate = (it.range.elements.first() as? KtExpression)?.getQualifiedElementSelector() as? KtNameReferenceExpression + if (candidate != null && candidate.isCallee() == isCallee) candidate else null + } val resolutionFacade = element.getResolutionFacade() val context = resolutionFacade.analyze(element, BodyResolveMode.PARTIAL_WITH_CFA) @@ -101,28 +90,25 @@ class RenameUnresolvedReferenceFix(element: KtNameReferenceExpression): KotlinQu val variantsHelper = ReferenceVariantsHelper(context, resolutionFacade, moduleDescriptor, { it !is DeclarationDescriptorWithVisibility || it.isVisible(element, null, context, resolutionFacade) }, NotPropertiesService.getNotProperties(element)) - val expectedTypes = patternExpression - .guessTypes(context, moduleDescriptor) - .ifEmpty { arrayOf(moduleDescriptor.builtIns.nullableAnyType) } + val expectedTypes = patternExpression.guessTypes(context, moduleDescriptor) + .ifEmpty { arrayOf(moduleDescriptor.builtIns.nullableAnyType) } val descriptorKindFilter = if (isCallee) DescriptorKindFilter.FUNCTIONS else DescriptorKindFilter.VARIABLES - val lookupItems = variantsHelper - .getReferenceVariants(element, descriptorKindFilter, { true }) - .filter { candidate -> - candidate is CallableDescriptor && (expectedTypes.any { candidate.returnType?.isSubtypeOf(it) ?: false }) - } - .mapTo(if (ApplicationManager.getApplication().isUnitTestMode) linkedSetOf() else linkedSetOf(originalName)) { - it.name.asString() - } - .map { LookupElementBuilder.create(it) } - .toTypedArray() + val lookupItems = variantsHelper.getReferenceVariants(element, descriptorKindFilter, { true }) + .filter { candidate -> + candidate is CallableDescriptor && (expectedTypes.any { candidate.returnType?.isSubtypeOf(it) ?: false }) + } + .mapTo(if (ApplicationManager.getApplication().isUnitTestMode) linkedSetOf() else linkedSetOf(originalName)) { + it.name.asString() + } + .map { LookupElementBuilder.create(it) } + .toTypedArray() val nameExpression = ReferenceNameExpression(lookupItems, originalName) val builder = TemplateBuilderImpl(container) occurrences.forEach { if (it != element) { builder.replaceElement(it.getReferencedNameElement(), OTHER_VARIABLE_NAME, INPUT_VARIABLE_NAME, false) - } - else { + } else { builder.replaceElement(it.getReferencedNameElement(), INPUT_VARIABLE_NAME, nameExpression, true) } } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/ReplaceCallFixUtils.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/ReplaceCallFixUtils.kt index 1ebc8dc91e0..98bfbc85b51 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/ReplaceCallFixUtils.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/ReplaceCallFixUtils.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -37,12 +26,11 @@ fun KtExpression.elvisOrEmpty(notNullNeeded: Boolean): String { } fun KtExpression.shouldHaveNotNullType(): Boolean { - val parent = parent - val type = when (parent) { - is KtBinaryExpression -> parent.left?.let { it.getType(it.analyze()) } - is KtProperty -> parent.typeReference?.let { it.analyze()[BindingContext.TYPE, it] } - else -> null - } ?: return false + val type = when (val parent = parent) { + is KtBinaryExpression -> parent.left?.let { it.getType(it.analyze()) } + is KtProperty -> parent.typeReference?.let { it.analyze()[BindingContext.TYPE, it] } + else -> null + } ?: return false return !type.isMarkedNullable } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/ReplaceInfixOrOperatorCallFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/ReplaceInfixOrOperatorCallFix.kt index e6673265ea8..ba9cf2d7ffc 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/ReplaceInfixOrOperatorCallFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/ReplaceInfixOrOperatorCallFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -32,8 +21,8 @@ import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.expressions.OperatorConventions class ReplaceInfixOrOperatorCallFix( - element: KtExpression, - private val notNullNeeded: Boolean + element: KtExpression, + private val notNullNeeded: Boolean ) : KotlinQuickFixAction(element) { override fun getText() = "Replace with safe (?.) call" @@ -53,32 +42,33 @@ class ReplaceInfixOrOperatorCallFix( if (assignment != null) { if (right == null) return val newExpression = psiFactory.createExpressionByPattern( - "$0?.set($1, $2)", arrayExpression, element.indexExpressions.joinToString(", ") { it.text }, right) + "$0?.set($1, $2)", arrayExpression, element.indexExpressions.joinToString(", ") { it.text }, right + ) assignment.replace(newExpression) - } - else { + } else { val newExpression = psiFactory.createExpressionByPattern( - "$0?.get($1)$elvis", arrayExpression, element.indexExpressions.joinToString(", ") { it.text }) + "$0?.get($1)$elvis", arrayExpression, element.indexExpressions.joinToString(", ") { it.text }) replacement = element.replace(newExpression) } } is KtCallExpression -> { val newExpression = psiFactory.createExpressionByPattern( - "$0?.invoke($1)$elvis", element.calleeExpression ?: return, element.valueArguments.joinToString(", ") { it.text }) + "$0?.invoke($1)$elvis", element.calleeExpression ?: return, element.valueArguments.joinToString(", ") { it.text }) replacement = element.replace(newExpression) } is KtBinaryExpression -> { replacement = if (element.operationToken == KtTokens.IDENTIFIER) { val newExpression = psiFactory.createExpressionByPattern( - "$0?.$1($2)$elvis", element.left ?: return, element.operationReference.text, element.right ?: return) + "$0?.$1($2)$elvis", element.left ?: return, element.operationReference.text, element.right ?: return + ) element.replace(newExpression) - } - else { + } else { val nameExpression = OperatorToFunctionIntention.convert(element).second val callExpression = nameExpression.parent as KtCallExpression val qualifiedExpression = callExpression.parent as KtDotQualifiedExpression val safeExpression = psiFactory.createExpressionByPattern( - "$0?.$1$elvis", qualifiedExpression.receiverExpression, callExpression) + "$0?.$1$elvis", qualifiedExpression.receiverExpression, callExpression + ) qualifiedExpression.replace(safeExpression) } } @@ -97,8 +87,8 @@ class ReplaceInfixOrOperatorCallFix( if (expression.arrayExpression == null) return null return ReplaceInfixOrOperatorCallFix(expression, expression.shouldHaveNotNullType()) } - val parent = expression.parent - return when (parent) { + + return when (val parent = expression.parent) { is KtBinaryExpression -> { when { parent.left == null || parent.right == null -> null diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/ReplaceJavaAnnotationPositionedArgumentsFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/ReplaceJavaAnnotationPositionedArgumentsFix.kt index 7e9822dc45c..918bd3342e4 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/ReplaceJavaAnnotationPositionedArgumentsFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/ReplaceJavaAnnotationPositionedArgumentsFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -27,9 +16,9 @@ import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.resolve.calls.model.ExpressionValueArgument import org.jetbrains.kotlin.resolve.jvm.checkers.JavaAnnotationCallChecker -class ReplaceJavaAnnotationPositionedArgumentsFix(element: KtAnnotationEntry) -: KotlinQuickFixAction(element), CleanupFix { - override fun getText(): String = "Replace invalid positioned arguments for annotation" +class ReplaceJavaAnnotationPositionedArgumentsFix(element: KtAnnotationEntry) : KotlinQuickFixAction(element), + CleanupFix { + override fun getText(): String = "Replace invalid positioned arguments for annotation" override fun getFamilyName(): String = text override fun invoke(project: Project, editor: Editor?, file: KtFile) { @@ -47,6 +36,6 @@ class ReplaceJavaAnnotationPositionedArgumentsFix(element: KtAnnotationEntry) companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic) = - diagnostic.createIntentionForFirstParentOfType(::ReplaceJavaAnnotationPositionedArgumentsFix) + diagnostic.createIntentionForFirstParentOfType(::ReplaceJavaAnnotationPositionedArgumentsFix) } } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/ReplaceJvmFieldWithConstFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/ReplaceJvmFieldWithConstFix.kt index b9533b34cdc..7998aa4f836 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/ReplaceJvmFieldWithConstFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/ReplaceJvmFieldWithConstFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -63,8 +52,6 @@ class ReplaceJvmFieldWithConstFix(annotation: KtAnnotationEntry) : KotlinQuickFi } private fun KtExpression.isConstantExpression() = - ConstantExpressionEvaluator.getConstant(this, analyze(BodyResolveMode.PARTIAL))?.let { - !it.usesNonConstValAsConstant - } ?: false + ConstantExpressionEvaluator.getConstant(this, analyze(BodyResolveMode.PARTIAL))?.let { !it.usesNonConstValAsConstant } ?: false } } \ No newline at end of file diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/ReplaceModifierFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/ReplaceModifierFix.kt index d9b77698eda..ce9eec91846 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/ReplaceModifierFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/ReplaceModifierFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -28,8 +17,8 @@ import org.jetbrains.kotlin.psi.KtModifierListOwner import org.jetbrains.kotlin.psi.psiUtil.getParentOfType class ReplaceModifierFix( - element: KtModifierListOwner, - private val replacement: KtModifierKeywordToken + element: KtModifierListOwner, + private val replacement: KtModifierKeywordToken ) : KotlinQuickFixAction(element), CleanupFix { private val text = "Replace with '${replacement.value}'" diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/ReplaceObsoleteLabelSyntaxFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/ReplaceObsoleteLabelSyntaxFix.kt index 678d44c8860..08d04185549 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/ReplaceObsoleteLabelSyntaxFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/ReplaceObsoleteLabelSyntaxFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -41,8 +30,7 @@ class ReplaceObsoleteLabelSyntaxFix(element: KtAnnotationEntry) : KotlinQuickFix return ReplaceObsoleteLabelSyntaxFix(annotationEntry) } - fun looksLikeObsoleteLabel(entry: KtAnnotationEntry): Boolean = - entry.atSymbol != null && + fun looksLikeObsoleteLabel(entry: KtAnnotationEntry): Boolean = entry.atSymbol != null && entry.parent is KtAnnotatedExpression && (entry.parent as KtAnnotatedExpression).annotationEntries.size == 1 && entry.valueArgumentList == null && diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/ReplacePrimitiveCastWithNumberConversionFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/ReplacePrimitiveCastWithNumberConversionFix.kt index e2d214d26ac..2d446fb2a5d 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/ReplacePrimitiveCastWithNumberConversionFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/ReplacePrimitiveCastWithNumberConversionFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -31,8 +20,8 @@ import org.jetbrains.kotlin.resolve.typeBinding.createTypeBinding import org.jetbrains.kotlin.types.typeUtil.isPrimitiveNumberType class ReplacePrimitiveCastWithNumberConversionFix( - element: KtBinaryExpressionWithTypeRHS, - private val targetShortType: String + element: KtBinaryExpressionWithTypeRHS, + private val targetShortType: String ) : KotlinQuickFixAction(element) { override fun getText() = "Replace cast with call to 'to$targetShortType()'" @@ -59,7 +48,10 @@ class ReplacePrimitiveCastWithNumberConversionFix( val castType = binaryExpression.right?.createTypeBinding(context)?.type ?: return null if (!castType.isPrimitiveNumberType()) return null - return ReplacePrimitiveCastWithNumberConversionFix(binaryExpression, SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderType(castType)) + return ReplacePrimitiveCastWithNumberConversionFix( + binaryExpression, + SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderType(castType) + ) } } } \ No newline at end of file diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/SpecifyOverrideExplicitlyFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/SpecifyOverrideExplicitlyFix.kt index 429697a928f..4f35c363050 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/SpecifyOverrideExplicitlyFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/SpecifyOverrideExplicitlyFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -35,7 +24,7 @@ import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils class SpecifyOverrideExplicitlyFix( - element: KtClassOrObject, private val signature: String + element: KtClassOrObject, private val signature: String ) : KotlinQuickFixAction(element) { override fun getText() = "Specify override for '$signature' explicitly" @@ -66,11 +55,13 @@ class SpecifyOverrideExplicitlyFix( if (delegateTargetDescriptor is ValueParameterDescriptor && delegateTargetDescriptor.containingDeclaration.let { it is ConstructorDescriptor && - it.isPrimary && - it.containingDeclaration == delegatedDescriptor.containingDeclaration - }) { + it.isPrimary && + it.containingDeclaration == delegatedDescriptor.containingDeclaration + } + ) { val delegateParameter = DescriptorToSourceUtils.descriptorToDeclaration( - delegateTargetDescriptor) as? KtParameter + delegateTargetDescriptor + ) as? KtParameter if (delegateParameter != null && !delegateParameter.hasValOrVar()) { val factory = KtPsiFactory(project) delegateParameter.addModifier(KtTokens.PRIVATE_KEYWORD) @@ -79,8 +70,8 @@ class SpecifyOverrideExplicitlyFix( } val overrideMemberChooserObject = OverrideMemberChooserObject.create( - project, delegatedDescriptor, overriddenDescriptor, - OverrideMemberChooserObject.BodyType.Delegate(delegateTargetDescriptor.name.asString()) + project, delegatedDescriptor, overriddenDescriptor, + OverrideMemberChooserObject.BodyType.Delegate(delegateTargetDescriptor.name.asString()) ) val member = overrideMemberChooserObject.generateMember(element, copyDoc = false) val insertedMember = element.addDeclaration(member) @@ -96,8 +87,8 @@ class SpecifyOverrideExplicitlyFix( val hidesOverrideError = Errors.DELEGATED_MEMBER_HIDES_SUPERTYPE_OVERRIDE.cast(diagnostic) val klass = hidesOverrideError.psiElement if (klass.superTypeListEntries.any { - it is KtDelegatedSuperTypeEntry && it.delegateExpression !is KtNameReferenceExpression - }) { + it is KtDelegatedSuperTypeEntry && it.delegateExpression !is KtNameReferenceExpression + }) { return null } val properOverride = hidesOverrideError.a diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/SuperClassNotInitialized.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/SuperClassNotInitialized.kt index 4fb10ae7fc0..95c7109858e 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/SuperClassNotInitialized.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/SuperClassNotInitialized.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -189,7 +178,7 @@ object SuperClassNotInitialized : KotlinIntentionActionsFactory() { val existingParameter = oldParameters.firstOrNull { it.name == nameString } if (existingParameter != null) { val type = (existingParameter.resolveToParameterDescriptorIfAny() as? VariableDescriptor)?.type - ?: return null + ?: return null if (type.isSubtypeOf(parameter.type)) continue // use existing parameter } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/SurroundWithArrayOfWithSpreadOperatorInFunctionFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/SurroundWithArrayOfWithSpreadOperatorInFunctionFix.kt index 6514e684066..e23cbf7697b 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/SurroundWithArrayOfWithSpreadOperatorInFunctionFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/SurroundWithArrayOfWithSpreadOperatorInFunctionFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -28,8 +17,8 @@ import org.jetbrains.kotlin.resolve.CollectionLiteralResolver.Companion.ARRAY_OF import org.jetbrains.kotlin.resolve.CollectionLiteralResolver.Companion.PRIMITIVE_TYPE_TO_ARRAY class SurroundWithArrayOfWithSpreadOperatorInFunctionFix( - val wrapper: Name, - argument: KtExpression + val wrapper: Name, + argument: KtExpression ) : KotlinQuickFixAction(argument) { override fun getText() = "Surround with *$wrapper(...)" diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/TypeOfAnnotationMemberFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/TypeOfAnnotationMemberFix.kt index bbb0edd7580..4c5561b0047 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/TypeOfAnnotationMemberFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/TypeOfAnnotationMemberFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -30,10 +19,10 @@ import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.KotlinType class TypeOfAnnotationMemberFix( - typeReference: KtTypeReference, - private val fixedType: String -): KotlinQuickFixAction(typeReference), CleanupFix { - override fun getText(): String = "Replace array of boxed with array of primitive" + typeReference: KtTypeReference, + private val fixedType: String +) : KotlinQuickFixAction(typeReference), CleanupFix { + override fun getText(): String = "Replace array of boxed with array of primitive" override fun getFamilyName(): String = text @@ -51,8 +40,7 @@ class TypeOfAnnotationMemberFix( val itemTypeName = itemType.constructor.declarationDescriptor?.name?.asString() ?: return null val fixedArrayTypeText = if (itemType.isItemTypeToFix()) { "${itemTypeName}Array" - } - else { + } else { return null } @@ -72,8 +60,7 @@ class TypeOfAnnotationMemberFix( return boxedType.type } - private fun KotlinType.isItemTypeToFix() = - KotlinBuiltIns.isByte(this) + private fun KotlinType.isItemTypeToFix() = KotlinBuiltIns.isByte(this) || KotlinBuiltIns.isChar(this) || KotlinBuiltIns.isShort(this) || KotlinBuiltIns.isInt(this) diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/UnsupportedYieldFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/UnsupportedYieldFix.kt index b95c509ab4a..27fd0e758ad 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/UnsupportedYieldFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/UnsupportedYieldFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix @@ -26,9 +15,9 @@ import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.MESSAGE_FOR_YIELD_BEFORE_LAMBDA -class UnsupportedYieldFix(psiElement: PsiElement): KotlinQuickFixAction(psiElement), CleanupFix { +class UnsupportedYieldFix(psiElement: PsiElement) : KotlinQuickFixAction(psiElement), CleanupFix { override fun getFamilyName(): String = "Migrate unsupported yield syntax" - override fun getText(): String = familyName + override fun getText(): String = familyName override fun invoke(project: Project, editor: Editor?, file: KtFile) { val psiElement = element ?: return @@ -56,8 +45,7 @@ class UnsupportedYieldFix(psiElement: PsiElement): KotlinQuickFixAction(element) { diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/CreateFromUsageFixBase.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/CreateFromUsageFixBase.kt index 7f18729cf1d..36bc676db6e 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/CreateFromUsageFixBase.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/CreateFromUsageFixBase.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix.createFromUsage @@ -20,6 +9,6 @@ import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.quickfix.KotlinQuickFixAction import org.jetbrains.kotlin.psi.KtElement -abstract class CreateFromUsageFixBase(element: T) : KotlinQuickFixAction(element) { +abstract class CreateFromUsageFixBase(element: T) : KotlinQuickFixAction(element) { override fun getFamilyName(): String = KotlinBundle.message("create.from.usage.family") } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/callableBuilder/CallableBuilder.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/callableBuilder/CallableBuilder.kt index ddce6903416..d19ea846744 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/callableBuilder/CallableBuilder.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/callableBuilder/CallableBuilder.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder @@ -594,7 +583,9 @@ class CallableBuilder(val config: CallableBuilderConfiguration) { val containingClass = declarationInPlace.containingClassOrObject!! if (containingClass.primaryConstructorParameters.isNotEmpty()) { declarationInPlace.replaceImplicitDelegationCallWithExplicit(true) - } else if ((receiverClassDescriptor as ClassDescriptor).getSuperClassOrAny().constructors.all { it.valueParameters.isNotEmpty() }) { + } else if ((receiverClassDescriptor as ClassDescriptor).getSuperClassOrAny().constructors + .all { it.valueParameters.isNotEmpty() } + ) { declarationInPlace.replaceImplicitDelegationCallWithExplicit(false) } } 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 1995d32de6e..0aac74417ac 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 @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder @@ -39,53 +28,54 @@ import java.util.* * Represents a concrete type or a set of types yet to be inferred from an expression. */ abstract class TypeInfo(val variance: Variance) { - object Empty: TypeInfo(Variance.INVARIANT) { + object Empty : TypeInfo(Variance.INVARIANT) { override fun getPossibleTypes(builder: CallableBuilder): List = Collections.emptyList() } - class ByExpression(val expression: KtExpression, variance: Variance): TypeInfo(variance) { + class ByExpression(val expression: KtExpression, variance: Variance) : TypeInfo(variance) { override fun getPossibleNamesFromExpression(bindingContext: BindingContext): Array { return KotlinNameSuggester.suggestNamesByExpressionOnly(expression, bindingContext, { true }).toTypedArray() } - override fun getPossibleTypes(builder: CallableBuilder): List = - expression.guessTypes( - context = builder.currentFileContext, - module = builder.currentFileModule, - pseudocode = builder.pseudocode - ).flatMap { it.getPossibleSupertypes(variance, builder) } + override fun getPossibleTypes(builder: CallableBuilder): List = expression.guessTypes( + context = builder.currentFileContext, + module = builder.currentFileModule, + pseudocode = builder.pseudocode + ).flatMap { it.getPossibleSupertypes(variance, builder) } } - class ByTypeReference(val typeReference: KtTypeReference, variance: Variance): TypeInfo(variance) { + class ByTypeReference(val typeReference: KtTypeReference, variance: Variance) : TypeInfo(variance) { override fun getPossibleTypes(builder: CallableBuilder): List = - builder.currentFileContext[BindingContext.TYPE, typeReference].getPossibleSupertypes(variance, builder) + builder.currentFileContext[BindingContext.TYPE, typeReference].getPossibleSupertypes(variance, builder) } - class ByType(val theType: KotlinType, variance: Variance): TypeInfo(variance) { + class ByType(val theType: KotlinType, variance: Variance) : TypeInfo(variance) { override fun getPossibleTypes(builder: CallableBuilder): List = - theType.getPossibleSupertypes(variance, builder) + theType.getPossibleSupertypes(variance, builder) } - class ByReceiverType(variance: Variance): TypeInfo(variance) { + class ByReceiverType(variance: Variance) : TypeInfo(variance) { override fun getPossibleTypes(builder: CallableBuilder): List = - (builder.placement as CallablePlacement.WithReceiver).receiverTypeCandidate.theType.getPossibleSupertypes(variance, builder) + (builder.placement as CallablePlacement.WithReceiver).receiverTypeCandidate.theType.getPossibleSupertypes(variance, builder) } class ByExplicitCandidateTypes(val types: List) : TypeInfo(Variance.INVARIANT) { override fun getPossibleTypes(builder: CallableBuilder) = types } - abstract class DelegatingTypeInfo(val delegate: TypeInfo): TypeInfo(delegate.variance) { + abstract class DelegatingTypeInfo(val delegate: TypeInfo) : TypeInfo(delegate.variance) { override val substitutionsAllowed: Boolean = delegate.substitutionsAllowed - override fun getPossibleNamesFromExpression(bindingContext: BindingContext) = delegate.getPossibleNamesFromExpression(bindingContext) + override fun getPossibleNamesFromExpression(bindingContext: BindingContext) = + delegate.getPossibleNamesFromExpression(bindingContext) + override fun getPossibleTypes(builder: CallableBuilder): List = delegate.getPossibleTypes(builder) } - class NoSubstitutions(delegate: TypeInfo): DelegatingTypeInfo(delegate) { + class NoSubstitutions(delegate: TypeInfo) : DelegatingTypeInfo(delegate) { override val substitutionsAllowed: Boolean = false } - class StaticContextRequired(delegate: TypeInfo): DelegatingTypeInfo(delegate) { + class StaticContextRequired(delegate: TypeInfo) : DelegatingTypeInfo(delegate) { override val staticContextRequired: Boolean = true } @@ -112,7 +102,7 @@ abstract class TypeInfo(val variance: Variance) { } is CallablePlacement.WithReceiver -> { val receiverClassDescriptor = - placement.receiverTypeCandidate.theType.constructor.declarationDescriptor + placement.receiverTypeCandidate.theType.constructor.declarationDescriptor val classDeclaration = receiverClassDescriptor?.let { DescriptorToSourceUtils.getSourceFromDescriptor(it) } if (!config.isExtension && classDeclaration != null) classDeclaration else config.currentFile } @@ -145,9 +135,9 @@ fun TypeInfo(theType: KotlinType, variance: Variance): TypeInfo = TypeInfo.ByTyp fun TypeInfo.noSubstitutions(): TypeInfo = (this as? TypeInfo.NoSubstitutions) ?: TypeInfo.NoSubstitutions(this) fun TypeInfo.forceNotNull(): TypeInfo { - class ForcedNotNull(delegate: TypeInfo): TypeInfo.DelegatingTypeInfo(delegate) { + class ForcedNotNull(delegate: TypeInfo) : TypeInfo.DelegatingTypeInfo(delegate) { override fun getPossibleTypes(builder: CallableBuilder): List = - super.getPossibleTypes(builder).map { it.makeNotNullable() } + super.getPossibleTypes(builder).map { it.makeNotNullable() } } return (this as? ForcedNotNull) ?: ForcedNotNull(this) @@ -159,10 +149,10 @@ fun TypeInfo.ofThis() = TypeInfo.OfThis(this) * Encapsulates information about a function parameter that is going to be created. */ class ParameterInfo( - val typeInfo: TypeInfo, - val nameSuggestions: List + val typeInfo: TypeInfo, + val nameSuggestions: List ) { - constructor(typeInfo: TypeInfo, preferredName: String? = null): this(typeInfo, listOfNotNull(preferredName)) + constructor(typeInfo: TypeInfo, preferredName: String? = null) : this(typeInfo, listOfNotNull(preferredName)) } enum class CallableKind { @@ -172,121 +162,131 @@ enum class CallableKind { PROPERTY } -abstract class CallableInfo ( - val name: String, - val receiverTypeInfo: TypeInfo, - val returnTypeInfo: TypeInfo, - val possibleContainers: List, - val typeParameterInfos: List, - val isForCompanion: Boolean = false, - val modifierList: KtModifierList? = null +abstract class CallableInfo( + val name: String, + val receiverTypeInfo: TypeInfo, + val returnTypeInfo: TypeInfo, + val possibleContainers: List, + val typeParameterInfos: List, + val isForCompanion: Boolean = false, + val modifierList: KtModifierList? = null ) { abstract val kind: CallableKind abstract val parameterInfos: List val isAbstract get() = modifierList?.hasModifier(KtTokens.ABSTRACT_KEYWORD) == true - abstract fun copy(receiverTypeInfo: TypeInfo = this.receiverTypeInfo, - possibleContainers: List = this.possibleContainers, - modifierList: KtModifierList? = this.modifierList): CallableInfo + abstract fun copy( + receiverTypeInfo: TypeInfo = this.receiverTypeInfo, + possibleContainers: List = this.possibleContainers, + modifierList: KtModifierList? = this.modifierList + ): CallableInfo } -class FunctionInfo(name: String, - receiverTypeInfo: TypeInfo, - returnTypeInfo: TypeInfo, - possibleContainers: List = Collections.emptyList(), - override val parameterInfos: List = Collections.emptyList(), - typeParameterInfos: List = Collections.emptyList(), - isForCompanion: Boolean = false, - modifierList: KtModifierList? = null, - val preferEmptyBody: Boolean = false +class FunctionInfo( + name: String, + receiverTypeInfo: TypeInfo, + returnTypeInfo: TypeInfo, + possibleContainers: List = Collections.emptyList(), + override val parameterInfos: List = Collections.emptyList(), + typeParameterInfos: List = Collections.emptyList(), + isForCompanion: Boolean = false, + modifierList: KtModifierList? = null, + val preferEmptyBody: Boolean = false ) : CallableInfo(name, receiverTypeInfo, returnTypeInfo, possibleContainers, typeParameterInfos, isForCompanion, modifierList) { override val kind: CallableKind get() = CallableKind.FUNCTION override fun copy( - receiverTypeInfo: TypeInfo, - possibleContainers: List, - modifierList: KtModifierList? + receiverTypeInfo: TypeInfo, + possibleContainers: List, + modifierList: KtModifierList? ) = FunctionInfo( - name, - receiverTypeInfo, - returnTypeInfo, - possibleContainers, - parameterInfos, - typeParameterInfos, - isForCompanion, - modifierList + name, + receiverTypeInfo, + returnTypeInfo, + possibleContainers, + parameterInfos, + typeParameterInfos, + isForCompanion, + modifierList ) } class ClassWithPrimaryConstructorInfo( - val classInfo: ClassInfo, - expectedTypeInfo: TypeInfo, - modifierList: KtModifierList? = null -): CallableInfo( - classInfo.name, TypeInfo.Empty, expectedTypeInfo.forceNotNull(), Collections.emptyList(), classInfo.typeArguments, false, modifierList = modifierList + val classInfo: ClassInfo, + expectedTypeInfo: TypeInfo, + modifierList: KtModifierList? = null +) : CallableInfo( + classInfo.name, + TypeInfo.Empty, + expectedTypeInfo.forceNotNull(), + Collections.emptyList(), + classInfo.typeArguments, + false, + modifierList = modifierList ) { override val kind: CallableKind get() = CallableKind.CLASS_WITH_PRIMARY_CONSTRUCTOR override val parameterInfos: List get() = classInfo.parameterInfos override fun copy( - receiverTypeInfo: TypeInfo, - possibleContainers: List, - modifierList: KtModifierList? + receiverTypeInfo: TypeInfo, + possibleContainers: List, + modifierList: KtModifierList? ) = throw UnsupportedOperationException() } class ConstructorInfo( - override val parameterInfos: List, - val targetClass: PsiElement, - val isPrimary: Boolean = false, - modifierList: KtModifierList? = null, - val withBody: Boolean = false -): CallableInfo("", TypeInfo.Empty, TypeInfo.Empty, Collections.emptyList(), Collections.emptyList(), false, modifierList = modifierList) { + override val parameterInfos: List, + val targetClass: PsiElement, + val isPrimary: Boolean = false, + modifierList: KtModifierList? = null, + val withBody: Boolean = false +) : CallableInfo("", TypeInfo.Empty, TypeInfo.Empty, Collections.emptyList(), Collections.emptyList(), false, modifierList = modifierList) { override val kind: CallableKind get() = CallableKind.CONSTRUCTOR override fun copy( - receiverTypeInfo: TypeInfo, - possibleContainers: List, - modifierList: KtModifierList? + receiverTypeInfo: TypeInfo, + possibleContainers: List, + modifierList: KtModifierList? ) = throw UnsupportedOperationException() } -class PropertyInfo(name: String, - receiverTypeInfo: TypeInfo, - returnTypeInfo: TypeInfo, - val writable: Boolean, - possibleContainers: List = Collections.emptyList(), - typeParameterInfos: List = Collections.emptyList(), - val isLateinitPreferred: Boolean = false, - isForCompanion: Boolean = false, - modifierList: KtModifierList? = null, - val withInitializer: Boolean = false +class PropertyInfo( + name: String, + receiverTypeInfo: TypeInfo, + returnTypeInfo: TypeInfo, + val writable: Boolean, + possibleContainers: List = Collections.emptyList(), + typeParameterInfos: List = Collections.emptyList(), + val isLateinitPreferred: Boolean = false, + isForCompanion: Boolean = false, + modifierList: KtModifierList? = null, + val withInitializer: Boolean = false ) : CallableInfo(name, receiverTypeInfo, returnTypeInfo, possibleContainers, typeParameterInfos, isForCompanion, modifierList) { override val kind: CallableKind get() = CallableKind.PROPERTY override val parameterInfos: List get() = Collections.emptyList() override fun copy( - receiverTypeInfo: TypeInfo, - possibleContainers: List, - modifierList: KtModifierList? + receiverTypeInfo: TypeInfo, + possibleContainers: List, + modifierList: KtModifierList? ) = copyProperty(receiverTypeInfo, possibleContainers, modifierList) fun copyProperty( - receiverTypeInfo: TypeInfo = this.receiverTypeInfo, - possibleContainers: List = this.possibleContainers, - modifierList: KtModifierList? = this.modifierList, - isLateinitPreferred: Boolean = this.isLateinitPreferred + receiverTypeInfo: TypeInfo = this.receiverTypeInfo, + possibleContainers: List = this.possibleContainers, + modifierList: KtModifierList? = this.modifierList, + isLateinitPreferred: Boolean = this.isLateinitPreferred ) = PropertyInfo( - name, - receiverTypeInfo, - returnTypeInfo, - writable, - possibleContainers, - typeParameterInfos, - isLateinitPreferred, - isForCompanion, - modifierList, - withInitializer + name, + receiverTypeInfo, + returnTypeInfo, + writable, + possibleContainers, + typeParameterInfos, + isLateinitPreferred, + isForCompanion, + modifierList, + withInitializer ) } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/callableBuilder/templateExpressions.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/callableBuilder/templateExpressions.kt index 51e5755856c..efeea0ea837 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/callableBuilder/templateExpressions.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/callableBuilder/templateExpressions.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder @@ -38,8 +27,9 @@ import java.util.* * Special Expression for parameter names based on its type. */ internal class ParameterNameExpression( - private val names: Array, - private val parameterTypeToNamesMap: Map>) : Expression() { + private val names: Array, + private val parameterTypeToNamesMap: Map> +) : Expression() { init { assert(names.all(String::isNotEmpty)) } @@ -103,19 +93,18 @@ internal class ParameterNameExpression( internal abstract class TypeExpression(val typeCandidates: List) : Expression() { class ForTypeReference(typeCandidates: List) : TypeExpression(typeCandidates) { override val cachedLookupElements: Array = - typeCandidates.map { LookupElementBuilder.create(it, it.renderedTypes.first()) }.toTypedArray() + typeCandidates.map { LookupElementBuilder.create(it, it.renderedTypes.first()) }.toTypedArray() } class ForDelegationSpecifier(typeCandidates: List) : TypeExpression(typeCandidates) { - override val cachedLookupElements: Array = - typeCandidates.map { - val types = it.theType.decomposeIntersection() - val text = (types zip it.renderedTypes).joinToString { (type, renderedType) -> - val descriptor = type.constructor.declarationDescriptor as ClassDescriptor - renderedType + if (descriptor.kind == ClassKind.INTERFACE) "" else "()" - } - LookupElementBuilder.create(it, text) - }.toTypedArray() + override val cachedLookupElements: Array = typeCandidates.map { + val types = it.theType.decomposeIntersection() + val text = (types zip it.renderedTypes).joinToString { (type, renderedType) -> + val descriptor = type.constructor.declarationDescriptor as ClassDescriptor + renderedType + if (descriptor.kind == ClassKind.INTERFACE) "" else "()" + } + LookupElementBuilder.create(it, text) + }.toTypedArray() } protected abstract val cachedLookupElements: Array @@ -133,9 +122,11 @@ internal abstract class TypeExpression(val typeCandidates: List) /** * A sort-of dummy Expression for parameter lists, to allow us to update the parameter list as the user makes selections. */ -internal class TypeParameterListExpression(private val mandatoryTypeParameters: List, - private val parameterTypeToTypeParameterNamesMap: Map>, - insertLeadingSpace: Boolean) : Expression() { +internal class TypeParameterListExpression( + private val mandatoryTypeParameters: List, + private val parameterTypeToTypeParameterNamesMap: Map>, + insertLeadingSpace: Boolean +) : Expression() { private val prefix = if (insertLeadingSpace) " <" else "<" var currentTypeParameters: List = Collections.emptyList() @@ -176,7 +167,7 @@ internal class TypeParameterListExpression(private val mandatoryTypeParameters: currentTypeParameters = sortedRenderedTypeParameters.map { it.typeParameter } return TextResult( - if (sortedRenderedTypeParameters.isEmpty()) "" else sortedRenderedTypeParameters.joinToString(", ", prefix, ">") { it.text } + if (sortedRenderedTypeParameters.isEmpty()) "" else sortedRenderedTypeParameters.joinToString(", ", prefix, ">") { it.text } ) } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/callableBuilder/typeUtils.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/callableBuilder/typeUtils.kt index ee7c9873100..64721ec0129 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/callableBuilder/typeUtils.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/callableBuilder/typeUtils.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder @@ -59,40 +48,39 @@ internal operator fun KotlinType.contains(descriptor: ClassifierDescriptor): Boo internal fun KotlinType.decomposeIntersection(): List { (constructor as? IntersectionTypeConstructor)?.let { - return it.supertypes.flatMap { it.decomposeIntersection() } + return it.supertypes.flatMap { type -> type.decomposeIntersection() } } return listOf(this) } private fun KotlinType.renderSingle(typeParameterNameMap: Map, fq: Boolean): String { - val substitution = typeParameterNameMap - .mapValues { - val name = Name.identifier(it.value) + val substitution = typeParameterNameMap.mapValues { + val name = Name.identifier(it.value) - val typeParameter = it.key + val typeParameter = it.key - var wrappingTypeParameter: TypeParameterDescriptor? = null - val wrappingTypeConstructor = object : TypeConstructor by typeParameter.typeConstructor { - override fun getDeclarationDescriptor() = wrappingTypeParameter - } + var wrappingTypeParameter: TypeParameterDescriptor? = null + val wrappingTypeConstructor = object : TypeConstructor by typeParameter.typeConstructor { + override fun getDeclarationDescriptor() = wrappingTypeParameter + } - wrappingTypeParameter = object : TypeParameterDescriptor by typeParameter { - override fun getName() = name - override fun getTypeConstructor() = wrappingTypeConstructor - } + wrappingTypeParameter = object : TypeParameterDescriptor by typeParameter { + override fun getName() = name + override fun getTypeConstructor() = wrappingTypeConstructor + } - val defaultType = typeParameter.defaultType - val wrappingType = KotlinTypeFactory.simpleTypeWithNonTrivialMemberScope( - defaultType.annotations, - wrappingTypeConstructor, - defaultType.arguments, - defaultType.isMarkedNullable, - defaultType.memberScope - ) - TypeProjectionImpl(wrappingType) - } - .mapKeys { it.key.typeConstructor } + val defaultType = typeParameter.defaultType + val wrappingType = KotlinTypeFactory.simpleTypeWithNonTrivialMemberScope( + defaultType.annotations, + wrappingTypeConstructor, + defaultType.arguments, + defaultType.isMarkedNullable, + defaultType.memberScope + ) + TypeProjectionImpl(wrappingType) + } + .mapKeys { it.key.typeConstructor } val typeToRender = TypeSubstitutor.create(substitution).substitute(this, Variance.INVARIANT)!! val renderer = if (fq) IdeDescriptorRenderers.SOURCE_CODE else IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS @@ -106,7 +94,10 @@ private fun KotlinType.render(typeParameterNameMap: Map) = render(typeParameterNameMap, false) internal fun KotlinType.renderLong(typeParameterNameMap: Map) = render(typeParameterNameMap, true) -internal fun getTypeParameterNamesNotInScope(typeParameters: Collection, scope: HierarchicalScope): List { +internal fun getTypeParameterNamesNotInScope( + typeParameters: Collection, + scope: HierarchicalScope +): List { return typeParameters.filter { typeParameter -> val classifier = scope.findClassifier(typeParameter.name, NoLookupLocation.FROM_IDE) classifier == null || classifier != typeParameter @@ -139,18 +130,19 @@ fun KotlinType.getTypeParameters(): Set { } fun KtExpression.guessTypes( - context: BindingContext, - module: ModuleDescriptor, - pseudocode: Pseudocode? = null, - coerceUnusedToUnit: Boolean = true, - allowErrorTypes: Boolean = false + context: BindingContext, + module: ModuleDescriptor, + pseudocode: Pseudocode? = null, + coerceUnusedToUnit: Boolean = true, + allowErrorTypes: Boolean = false ): Array { fun isAcceptable(type: KotlinType) = allowErrorTypes || !ErrorUtils.containsErrorType(type) if (coerceUnusedToUnit && this !is KtDeclaration && isUsedAsStatement(context) - && getNonStrictParentOfType() == null) return arrayOf(module.builtIns.unitType) + && getNonStrictParentOfType() == null + ) return arrayOf(module.builtIns.unitType) val parent = parent @@ -196,8 +188,7 @@ fun KtExpression.guessTypes( if (typeRef != null) { // and has a specified type arrayOf(context[BindingContext.TYPE, typeRef]!!) - } - else { + } else { // otherwise guess guessType(context) } @@ -208,8 +199,7 @@ fun KtExpression.guessTypes( if (typeRef != null) { // and has a specified type arrayOf(context[BindingContext.TYPE, typeRef]!!) - } - else { + } else { // otherwise guess guessType(context) } @@ -220,8 +210,7 @@ fun KtExpression.guessTypes( if (typeRef != null) { // and has a specified type arrayOf(context[BindingContext.TYPE, typeRef]!!) - } - else { + } else { // otherwise guess, based on LHS parent.guessType(context) } @@ -230,9 +219,9 @@ fun KtExpression.guessTypes( val variableDescriptor = context[BindingContext.DECLARATION_TO_DESCRIPTOR, parent.parent as KtProperty] as VariableDescriptor val delegateClassName = if (variableDescriptor.isVar) "ReadWriteProperty" else "ReadOnlyProperty" val delegateClass = module.resolveTopLevelClass(FqName("kotlin.properties.$delegateClassName"), NoLookupLocation.FROM_IDE) - ?: return arrayOf(module.builtIns.anyType) + ?: return arrayOf(module.builtIns.anyType) val receiverType = (variableDescriptor.extensionReceiverParameter ?: variableDescriptor.dispatchReceiverParameter)?.type - ?: module.builtIns.nullableNothingType + ?: module.builtIns.nullableNothingType val typeArguments = listOf(TypeProjectionImpl(receiverType), TypeProjectionImpl(variableDescriptor.type)) arrayOf(TypeUtils.substituteProjectionsForParameters(delegateClass, typeArguments)) } @@ -253,9 +242,9 @@ fun KtExpression.guessTypes( } if (functionalExpression == null) { functionDescriptor.overriddenDescriptors - .mapNotNull { it.returnType } - .firstOrNull { isAcceptable(it) } - ?.let { return arrayOf(it) } + .mapNotNull { it.returnType } + .firstOrNull { isAcceptable(it) } + ?.let { return arrayOf(it) } return arrayOf() } val lambdaTypes = functionalExpression.guessTypes(context, module, pseudocode?.parent, coerceUnusedToUnit) @@ -275,8 +264,7 @@ private fun KtNamedDeclaration.guessType(context: BindingContext): Array()) { ref -> if (ref is KtSimpleNameReference) { context[BindingContext.EXPECTED_EXPRESSION_TYPE, ref.expression] - } - else { + } else { null } } @@ -287,8 +275,7 @@ private fun KtNamedDeclaration.guessType(context: BindingContext): Array KotlinTypeChecker.DEFAULT.equalTypes(currentType, substitution.forType) - Variance.IN_VARIANCE -> KotlinTypeChecker.DEFAULT.isSubtypeOf(currentType, substitution.forType) - Variance.OUT_VARIANCE -> KotlinTypeChecker.DEFAULT.isSubtypeOf(substitution.forType, currentType) - }) { + Variance.INVARIANT -> KotlinTypeChecker.DEFAULT.equalTypes(currentType, substitution.forType) + Variance.IN_VARIANCE -> KotlinTypeChecker.DEFAULT.isSubtypeOf(currentType, substitution.forType) + Variance.OUT_VARIANCE -> KotlinTypeChecker.DEFAULT.isSubtypeOf(substitution.forType, currentType) + } + ) { TypeUtils.makeNullableAsSpecified(substitution.byType, nullable) - } - else { + } else { val newArguments = arguments.zip(constructor.parameters).map { pair -> val (projection, typeParameter) = pair TypeProjectionImpl(Variance.INVARIANT, projection.type.substitute(substitution, typeParameter.variance)) @@ -329,8 +316,8 @@ fun KtCallExpression.getParameterInfos(): List { val anyType = this.builtIns.nullableAnyType return valueArguments.map { ParameterInfo( - it.getArgumentExpression()?.let { TypeInfo(it, Variance.IN_VARIANCE) } ?: TypeInfo(anyType, Variance.IN_VARIANCE), - it.getArgumentName()?.referenceExpression?.getReferencedName() + it.getArgumentExpression()?.let { TypeInfo(it, Variance.IN_VARIANCE) } ?: TypeInfo(anyType, Variance.IN_VARIANCE), + it.getArgumentName()?.referenceExpression?.getReferencedName() ) } } @@ -345,7 +332,7 @@ private fun TypePredicate.getRepresentativeTypes(): Set { } is ForSomeType -> typeSets.flatMapTo(LinkedHashSet()) { it.getRepresentativeTypes() } is AllTypes -> emptySet() - else -> throw AssertionError("Invalid type predicate: ${this}") + else -> throw AssertionError("Invalid type predicate: $this") } } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateBinaryOperationActionFactory.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateBinaryOperationActionFactory.kt index cb30d823001..f7d2bf1194a 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateBinaryOperationActionFactory.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateBinaryOperationActionFactory.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createCallable @@ -35,9 +24,9 @@ object CreateBinaryOperationActionFactory : CreateCallableMemberFromUsageFactory override fun createCallableInfo(element: KtBinaryExpression, diagnostic: Diagnostic): CallableInfo? { val token = element.operationToken as KtToken val operationName = when (token) { - KtTokens.IDENTIFIER -> element.operationReference.getReferencedName() - else -> OperatorConventions.getNameForOperationSymbol(token, false, true)?.asString() - } ?: return null + KtTokens.IDENTIFIER -> element.operationReference.getReferencedName() + else -> OperatorConventions.getNameForOperationSymbol(token, false, true)?.asString() + } ?: return null val inOperation = token in OperatorConventions.IN_OPERATIONS val comparisonOperation = token in OperatorConventions.COMPARISON_OPERATIONS @@ -57,11 +46,11 @@ object CreateBinaryOperationActionFactory : CreateCallableMemberFromUsageFactory val parameters = Collections.singletonList(ParameterInfo(TypeInfo(argumentExpr, Variance.IN_VARIANCE))) val isOperator = token != KtTokens.IDENTIFIER return FunctionInfo( - operationName, - receiverType, - returnType, - parameterInfos = parameters, - modifierList = KtPsiFactory(element).createModifierList(if (isOperator) KtTokens.OPERATOR_KEYWORD else KtTokens.INFIX_KEYWORD) + operationName, + receiverType, + returnType, + parameterInfos = parameters, + modifierList = KtPsiFactory(element).createModifierList(if (isOperator) KtTokens.OPERATOR_KEYWORD else KtTokens.INFIX_KEYWORD) ) } } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateCallableFromCallActionFactory.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateCallableFromCallActionFactory.kt index f9f03d7fed4..164f13b909c 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateCallableFromCallActionFactory.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateCallableFromCallActionFactory.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createCallable @@ -202,7 +191,8 @@ sealed class CreateCallableFromCallActionFactory( val canBeLateinit = varExpected && returnTypes.any { !it.isMarkedNullable && !KotlinBuiltIns.isPrimitiveType(it) } - && fullCallExpr.parents.firstOrNull { it is KtDeclarationWithBody || it is KtClassInitializer } is KtDeclarationWithBody + && fullCallExpr.parents + .firstOrNull { it is KtDeclarationWithBody || it is KtClassInitializer } is KtDeclarationWithBody return PropertyInfo(name, receiverType, returnTypeInfo, varExpected, possibleContainers, isLateinitPreferred = canBeLateinit) } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateCallableMemberFromUsageFactory.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateCallableMemberFromUsageFactory.kt index b6ec7d94bbc..5aced0481f5 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateCallableMemberFromUsageFactory.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateCallableMemberFromUsageFactory.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createCallable @@ -29,30 +18,28 @@ import org.jetbrains.kotlin.psi.KtElement import java.util.* abstract class CreateCallableMemberFromUsageFactory( - private val extensionsSupported: Boolean = true + private val extensionsSupported: Boolean = true ) : KotlinIntentionActionFactoryWithDelegate>() { private fun newCallableQuickFix( - originalElementPointer: SmartPsiElementPointer, - priority: IntentionActionPriority, - quickFixDataFactory: () -> List?, - quickFixFactory: (E, List) -> IntentionAction? - ): QuickFixWithDelegateFactory { - return QuickFixWithDelegateFactory(priority) { - val data = quickFixDataFactory().orEmpty() - val originalElement = originalElementPointer.element - if (data.isNotEmpty() && originalElement != null) quickFixFactory(originalElement, data) else null - } + originalElementPointer: SmartPsiElementPointer, + priority: IntentionActionPriority, + quickFixDataFactory: () -> List?, + quickFixFactory: (E, List) -> IntentionAction? + ): QuickFixWithDelegateFactory = QuickFixWithDelegateFactory(priority) { + val data = quickFixDataFactory().orEmpty() + val originalElement = originalElementPointer.element + if (data.isNotEmpty() && originalElement != null) quickFixFactory(originalElement, data) else null } protected open fun createCallableInfo(element: E, diagnostic: Diagnostic): CallableInfo? = null - override fun extractFixData(element: E, diagnostic: Diagnostic): List - = listOfNotNull(createCallableInfo(element, diagnostic)) + override fun extractFixData(element: E, diagnostic: Diagnostic): List = + listOfNotNull(createCallableInfo(element, diagnostic)) override fun createFixes( - originalElementPointer: SmartPsiElementPointer, - diagnostic: Diagnostic, - quickFixDataFactory: () -> List? + originalElementPointer: SmartPsiElementPointer, + diagnostic: Diagnostic, + quickFixDataFactory: () -> List? ): List { val fixes = ArrayList(3) @@ -60,7 +47,7 @@ abstract class CreateCallableMemberFromUsageFactory( CreateCallableFromUsageFix(element, data) }.let { fixes.add(it) } - newCallableQuickFix(originalElementPointer, IntentionActionPriority.NORMAL, quickFixDataFactory) f@ { element, data -> + newCallableQuickFix(originalElementPointer, IntentionActionPriority.NORMAL, quickFixDataFactory) f@{ element, data -> (data.singleOrNull() as? PropertyInfo)?.let { CreateParameterFromUsageFix.createFixForPrimaryConstructorPropertyParameter(element, it) } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateComponentFunctionActionFactory.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateComponentFunctionActionFactory.kt index 9565af92b22..86c0f4696ae 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateComponentFunctionActionFactory.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateComponentFunctionActionFactory.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createCallable @@ -55,10 +44,10 @@ object CreateComponentFunctionActionFactory : CreateCallableMemberFromUsageFacto val returnTypeInfo = TypeInfo(entry, Variance.OUT_VARIANCE) return FunctionInfo( - name.identifier, - ownerTypeInfo, - returnTypeInfo, - modifierList = KtPsiFactory(element).createModifierList(KtTokens.OPERATOR_KEYWORD) + name.identifier, + ownerTypeInfo, + returnTypeInfo, + modifierList = KtPsiFactory(element).createModifierList(KtTokens.OPERATOR_KEYWORD) ) } } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateConstructorFromDelegationCallActionFactory.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateConstructorFromDelegationCallActionFactory.kt index 061f1ae154d..cc779890714 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateConstructorFromDelegationCallActionFactory.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateConstructorFromDelegationCallActionFactory.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createCallable @@ -48,10 +37,9 @@ object CreateConstructorFromDelegationCallActionFactory : CreateCallableMemberFr val targetClass = if (calleeExpression.isThis) { currentClass - } - else { + } else { val superClassDescriptor = - DescriptorUtils.getSuperclassDescriptors(classDescriptor).singleOrNull { it.kind == ClassKind.CLASS } ?: return null + DescriptorUtils.getSuperclassDescriptors(classDescriptor).singleOrNull { it.kind == ClassKind.CLASS } ?: return null DescriptorToSourceUtilsIde.getAnyDeclaration(project, superClassDescriptor) ?: return null } if (!(targetClass.canRefactor() && (targetClass is KtClass || targetClass is PsiClass))) return null @@ -59,8 +47,11 @@ object CreateConstructorFromDelegationCallActionFactory : CreateCallableMemberFr val anyType = classDescriptor.builtIns.nullableAnyType val parameters = element.valueArguments.map { ParameterInfo( - it.getArgumentExpression()?.let { TypeInfo(it, Variance.IN_VARIANCE) } ?: TypeInfo(anyType, Variance.IN_VARIANCE), - it.getArgumentName()?.asName?.asString() + it.getArgumentExpression()?.let { expression -> TypeInfo(expression, Variance.IN_VARIANCE) } ?: TypeInfo( + anyType, + Variance.IN_VARIANCE + ), + it.getArgumentName()?.asName?.asString() ) } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateConstructorFromSuperTypeCallActionFactory.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateConstructorFromSuperTypeCallActionFactory.kt index c5d207df1cf..4bf9c43dd89 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateConstructorFromSuperTypeCallActionFactory.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateConstructorFromSuperTypeCallActionFactory.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createCallable @@ -53,8 +42,11 @@ object CreateConstructorFromSuperTypeCallActionFactory : CreateCallableMemberFro val anyType = superClassDescriptor.builtIns.nullableAnyType val parameters = element.valueArguments.map { ParameterInfo( - it.getArgumentExpression()?.let { TypeInfo(it, Variance.IN_VARIANCE) } ?: TypeInfo(anyType, Variance.IN_VARIANCE), - it.getArgumentName()?.asName?.asString() + it.getArgumentExpression()?.let { expression -> TypeInfo(expression, Variance.IN_VARIANCE) } ?: TypeInfo( + anyType, + Variance.IN_VARIANCE + ), + it.getArgumentName()?.asName?.asString() ) } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateDataClassPropertyFromDestructuringActionFactory.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateDataClassPropertyFromDestructuringActionFactory.kt index 0ed3466f2c4..900bf7b7e21 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateDataClassPropertyFromDestructuringActionFactory.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateDataClassPropertyFromDestructuringActionFactory.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createCallable @@ -38,7 +27,10 @@ import org.jetbrains.kotlin.resolve.source.getPsi object CreateDataClassPropertyFromDestructuringActionFactory : CreateParameterFromUsageFactory() { override fun getElementOfInterest(diagnostic: Diagnostic) = CreateComponentFunctionActionFactory.getElementOfInterest(diagnostic) - override fun extractFixData(element: KtDestructuringDeclaration, diagnostic: Diagnostic): CreateParameterData? { + override fun extractFixData( + element: KtDestructuringDeclaration, + diagnostic: Diagnostic + ): CreateParameterData? { val diagnosticWithParameters = Errors.COMPONENT_FUNCTION_MISSING.cast(diagnostic) val functionName = diagnosticWithParameters.a @@ -57,10 +49,10 @@ object CreateDataClassPropertyFromDestructuringActionFactory : CreateParameterFr val paramType = entry.typeReference?.getAbbreviatedTypeOrType(entry.analyze()) ?: targetClassDescriptor.builtIns.anyType val parameterInfo = KotlinParameterInfo( - callableDescriptor = constructorDescriptor, - name = paramName, - originalTypeInfo = KotlinTypeInfo(false, paramType), - valOrVar = KotlinValVar.Val + callableDescriptor = constructorDescriptor, + name = paramName, + originalTypeInfo = KotlinTypeInfo(false, paramType), + valOrVar = KotlinValVar.Val ) return CreateParameterData(parameterInfo, element, createSilently = true) { editor -> diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateFunctionFromCallableReferenceActionFactory.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateFunctionFromCallableReferenceActionFactory.kt index d07e0dd1598..dc0ae6312f8 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateFunctionFromCallableReferenceActionFactory.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateFunctionFromCallableReferenceActionFactory.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createCallable @@ -43,34 +32,33 @@ object CreateFunctionFromCallableReferenceActionFactory : CreateCallableMemberFr val name = element.callableReference.getReferencedName() val resolutionFacade = element.getResolutionFacade() val context = resolutionFacade.analyze(element, BodyResolveMode.PARTIAL_WITH_CFA) - return element - .guessTypes(context, resolutionFacade.moduleDescriptor) - .ifEmpty { element.guessTypes(context, resolutionFacade.moduleDescriptor, allowErrorTypes = true) } // approximate with Any - .filter(KotlinType::isFunctionType) - .mapNotNull { - val expectedReceiverType = it.getReceiverTypeFromFunctionType() - val receiverExpression = element.receiverExpression - val qualifierType = (context.get(BindingContext.DOUBLE_COLON_LHS, receiverExpression) as? DoubleColonLHS.Type)?.type - val receiverTypeInfo = qualifierType?.let { TypeInfo(it, Variance.IN_VARIANCE) } ?: TypeInfo.Empty - val returnTypeInfo = TypeInfo(it.getReturnTypeFromFunctionType(), Variance.OUT_VARIANCE) - val containers = element.getExtractionContainers(includeAll = true).ifEmpty { return@mapNotNull null } - val parameterInfos = SmartList().apply { - if (receiverExpression == null && expectedReceiverType != null) { - add(ParameterInfo(TypeInfo(expectedReceiverType, Variance.IN_VARIANCE))) - } - - it.getValueParameterTypesFromFunctionType() - .let { - if (receiverExpression != null && expectedReceiverType == null && it.isNotEmpty()) - it.subList(1, it.size) - else it - } - .mapTo(this) { - ParameterInfo(TypeInfo(it.type, it.projectionKind)) - } + return element.guessTypes(context, resolutionFacade.moduleDescriptor) + .ifEmpty { element.guessTypes(context, resolutionFacade.moduleDescriptor, allowErrorTypes = true) } // approximate with Any + .filter(KotlinType::isFunctionType) + .mapNotNull { type -> + val expectedReceiverType = type.getReceiverTypeFromFunctionType() + val receiverExpression = element.receiverExpression + val qualifierType = (context.get(BindingContext.DOUBLE_COLON_LHS, receiverExpression) as? DoubleColonLHS.Type)?.type + val receiverTypeInfo = qualifierType?.let { TypeInfo(it, Variance.IN_VARIANCE) } ?: TypeInfo.Empty + val returnTypeInfo = TypeInfo(type.getReturnTypeFromFunctionType(), Variance.OUT_VARIANCE) + val containers = element.getExtractionContainers(includeAll = true).ifEmpty { return@mapNotNull null } + val parameterInfos = SmartList().apply { + if (receiverExpression == null && expectedReceiverType != null) { + add(ParameterInfo(TypeInfo(expectedReceiverType, Variance.IN_VARIANCE))) } - FunctionInfo(name, receiverTypeInfo, returnTypeInfo, containers, parameterInfos) + type.getValueParameterTypesFromFunctionType() + .let { + if (receiverExpression != null && expectedReceiverType == null && it.isNotEmpty()) + it.subList(1, it.size) + else it + } + .mapTo(this) { + ParameterInfo(TypeInfo(it.type, it.projectionKind)) + } } + + FunctionInfo(name, receiverTypeInfo, returnTypeInfo, containers, parameterInfos) + } } } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateGetFunctionActionFactory.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateGetFunctionActionFactory.kt index ed5e1df47e9..dfc51af8c3f 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateGetFunctionActionFactory.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateGetFunctionActionFactory.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createCallable @@ -26,7 +15,6 @@ import org.jetbrains.kotlin.psi.KtArrayAccessExpression import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.types.Variance import org.jetbrains.kotlin.util.OperatorNameConventions -import java.util.* object CreateGetFunctionActionFactory : CreateGetSetFunctionActionFactory(isGet = true) { override fun createCallableInfo(element: KtArrayAccessExpression, diagnostic: Diagnostic): CallableInfo? { @@ -36,12 +24,12 @@ object CreateGetFunctionActionFactory : CreateGetSetFunctionActionFactory(isGet val parameters = element.indexExpressions.map { ParameterInfo(TypeInfo(it, Variance.IN_VARIANCE)) } val returnType = TypeInfo(element, Variance.OUT_VARIANCE) return FunctionInfo( - OperatorNameConventions.GET.asString(), - arrayType, - returnType, - Collections.emptyList(), - parameters, - modifierList = KtPsiFactory(element).createModifierList(KtTokens.OPERATOR_KEYWORD) + OperatorNameConventions.GET.asString(), + arrayType, + returnType, + emptyList(), + parameters, + modifierList = KtPsiFactory(element).createModifierList(KtTokens.OPERATOR_KEYWORD) ) } } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateGetSetFunctionActionFactory.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateGetSetFunctionActionFactory.kt index 6b1a8f3d0a6..9f966a63c8e 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateGetSetFunctionActionFactory.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateGetSetFunctionActionFactory.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createCallable @@ -24,7 +13,8 @@ import org.jetbrains.kotlin.psi.KtBinaryExpression import org.jetbrains.kotlin.psi.KtContainerNode import org.jetbrains.kotlin.psi.KtPsiUtil -abstract class CreateGetSetFunctionActionFactory(private val isGet: Boolean) : CreateCallableMemberFromUsageFactory() { +abstract class CreateGetSetFunctionActionFactory(private val isGet: Boolean) : + CreateCallableMemberFromUsageFactory() { override fun getElementOfInterest(diagnostic: Diagnostic): KtArrayAccessExpression? { return when (diagnostic.factory) { Errors.NO_GET_METHOD -> if (isGet) Errors.NO_GET_METHOD.cast(diagnostic).psiElement else null diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateHasNextFunctionActionFactory.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateHasNextFunctionActionFactory.kt index 43062f7b8b1..58f3a3112a1 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateHasNextFunctionActionFactory.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateHasNextFunctionActionFactory.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createCallable @@ -37,14 +26,14 @@ object CreateHasNextFunctionActionFactory : CreateCallableMemberFromUsageFactory override fun createCallableInfo(element: KtForExpression, diagnostic: Diagnostic): CallableInfo? { val diagnosticWithParameters = - DiagnosticFactory.cast(diagnostic, Errors.HAS_NEXT_MISSING, Errors.HAS_NEXT_FUNCTION_NONE_APPLICABLE) + DiagnosticFactory.cast(diagnostic, Errors.HAS_NEXT_MISSING, Errors.HAS_NEXT_FUNCTION_NONE_APPLICABLE) val ownerType = TypeInfo(diagnosticWithParameters.a, Variance.IN_VARIANCE) val returnType = TypeInfo(element.builtIns.booleanType, Variance.OUT_VARIANCE) return FunctionInfo( - OperatorNameConventions.HAS_NEXT.asString(), - ownerType, - returnType, - modifierList = KtPsiFactory(element).createModifierList(KtTokens.OPERATOR_KEYWORD) + OperatorNameConventions.HAS_NEXT.asString(), + ownerType, + returnType, + modifierList = KtPsiFactory(element).createModifierList(KtTokens.OPERATOR_KEYWORD) ) } } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateInvokeFunctionActionFactory.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateInvokeFunctionActionFactory.kt index fb5915eb1a2..029ea81741b 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateInvokeFunctionActionFactory.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateInvokeFunctionActionFactory.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createCallable @@ -44,18 +33,21 @@ object CreateInvokeFunctionActionFactory : CreateCallableMemberFromUsageFactory< val anyType = element.builtIns.nullableAnyType val parameters = element.valueArguments.map { ParameterInfo( - it.getArgumentExpression()?.let { TypeInfo(it, Variance.IN_VARIANCE) } ?: TypeInfo(anyType, Variance.IN_VARIANCE), - it.getArgumentName()?.referenceExpression?.getReferencedName() + it.getArgumentExpression()?.let { expression -> TypeInfo(expression, Variance.IN_VARIANCE) } ?: TypeInfo( + anyType, + Variance.IN_VARIANCE + ), + it.getArgumentName()?.referenceExpression?.getReferencedName() ) } val returnType = TypeInfo(element, Variance.OUT_VARIANCE) return FunctionInfo( - OperatorNameConventions.INVOKE.asString(), - receiverType, - returnType, - parameterInfos = parameters, - modifierList = KtPsiFactory(element).createModifierList(KtTokens.OPERATOR_KEYWORD) + OperatorNameConventions.INVOKE.asString(), + receiverType, + returnType, + parameterInfos = parameters, + modifierList = KtPsiFactory(element).createModifierList(KtTokens.OPERATOR_KEYWORD) ) } } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateIteratorFunctionActionFactory.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateIteratorFunctionActionFactory.kt index 78236fecfb8..af03ee49d93 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateIteratorFunctionActionFactory.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateIteratorFunctionActionFactory.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createCallable @@ -53,17 +42,19 @@ object CreateIteratorFunctionActionFactory : CreateCallableMemberFromUsageFactor val returnJetTypeParameterType = TypeProjectionImpl(returnJetTypeParameterTypes[0]) val returnJetTypeArguments = Collections.singletonList(returnJetTypeParameterType) - val newReturnJetType = KotlinTypeFactory.simpleTypeWithNonTrivialMemberScope(returnJetType.annotations, - returnJetType.constructor, - returnJetTypeArguments, - returnJetType.isMarkedNullable, - returnJetType.memberScope) + val newReturnJetType = KotlinTypeFactory.simpleTypeWithNonTrivialMemberScope( + returnJetType.annotations, + returnJetType.constructor, + returnJetTypeArguments, + returnJetType.isMarkedNullable, + returnJetType.memberScope + ) val returnType = TypeInfo(newReturnJetType, Variance.OUT_VARIANCE) return FunctionInfo( - OperatorNameConventions.ITERATOR.asString(), - iterableType, - returnType, - modifierList = KtPsiFactory(element).createModifierList(KtTokens.OPERATOR_KEYWORD) + OperatorNameConventions.ITERATOR.asString(), + iterableType, + returnType, + modifierList = KtPsiFactory(element).createModifierList(KtTokens.OPERATOR_KEYWORD) ) } } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateNextFunctionActionFactory.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateNextFunctionActionFactory.kt index 15721dab37c..9da9da2d32d 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateNextFunctionActionFactory.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateNextFunctionActionFactory.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createCallable @@ -42,10 +31,10 @@ object CreateNextFunctionActionFactory : CreateCallableMemberFromUsageFactory() ?: return emptyList() val propertyDescriptor = context[BindingContext.DECLARATION_TO_DESCRIPTOR, property] as? VariableDescriptorWithAccessors - ?: return emptyList() + ?: return emptyList() if (propertyDescriptor is LocalVariableDescriptor - && !element.languageVersionSettings.supportsFeature(LanguageFeature.LocalDelegatedProperties)) { + && !element.languageVersionSettings.supportsFeature(LanguageFeature.LocalDelegatedProperties) + ) { return emptyList() } @@ -75,11 +65,11 @@ object CreatePropertyDelegateAccessorsActionFactory : CreateCallableMemberFromUs if (isApplicableForAccessor(propertyDescriptor.getter)) { val getterInfo = FunctionInfo( - name = OperatorNameConventions.GET_VALUE.asString(), - receiverTypeInfo = accessorReceiverType, - returnTypeInfo = TypeInfo(propertyType, Variance.OUT_VARIANCE), - parameterInfos = listOf(thisRefParam, metadataParam), - modifierList = psiFactory.createModifierList(KtTokens.OPERATOR_KEYWORD) + name = OperatorNameConventions.GET_VALUE.asString(), + receiverTypeInfo = accessorReceiverType, + returnTypeInfo = TypeInfo(propertyType, Variance.OUT_VARIANCE), + parameterInfos = listOf(thisRefParam, metadataParam), + modifierList = psiFactory.createModifierList(KtTokens.OPERATOR_KEYWORD) ) callableInfos.add(getterInfo) } @@ -87,11 +77,11 @@ object CreatePropertyDelegateAccessorsActionFactory : CreateCallableMemberFromUs if (propertyDescriptor.isVar && isApplicableForAccessor(propertyDescriptor.setter)) { val newValueParam = ParameterInfo(TypeInfo(propertyType, Variance.IN_VARIANCE)) val setterInfo = FunctionInfo( - name = OperatorNameConventions.SET_VALUE.asString(), - receiverTypeInfo = accessorReceiverType, - returnTypeInfo = TypeInfo(builtIns.unitType, Variance.OUT_VARIANCE), - parameterInfos = listOf(thisRefParam, metadataParam, newValueParam), - modifierList = psiFactory.createModifierList(KtTokens.OPERATOR_KEYWORD) + name = OperatorNameConventions.SET_VALUE.asString(), + receiverTypeInfo = accessorReceiverType, + returnTypeInfo = TypeInfo(builtIns.unitType, Variance.OUT_VARIANCE), + parameterInfos = listOf(thisRefParam, metadataParam, newValueParam), + modifierList = psiFactory.createModifierList(KtTokens.OPERATOR_KEYWORD) ) callableInfos.add(setterInfo) } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateSetFunctionActionFactory.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateSetFunctionActionFactory.kt index 750e0dbcb45..852ad8b2757 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateSetFunctionActionFactory.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateSetFunctionActionFactory.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createCallable @@ -64,12 +53,12 @@ object CreateSetFunctionActionFactory : CreateGetSetFunctionActionFactory(isGet val returnType = TypeInfo(builtIns.unitType, Variance.OUT_VARIANCE) return FunctionInfo( - OperatorNameConventions.SET.asString(), - arrayType, - returnType, - Collections.emptyList(), - parameters, - modifierList = KtPsiFactory(element).createModifierList(KtTokens.OPERATOR_KEYWORD) + OperatorNameConventions.SET.asString(), + arrayType, + returnType, + Collections.emptyList(), + parameters, + modifierList = KtPsiFactory(element).createModifierList(KtTokens.OPERATOR_KEYWORD) ) } } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateUnaryOperationActionFactory.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateUnaryOperationActionFactory.kt index 22383cb82e5..11926f7fe99 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateUnaryOperationActionFactory.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateUnaryOperationActionFactory.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createCallable @@ -27,7 +16,7 @@ import org.jetbrains.kotlin.psi.KtUnaryExpression import org.jetbrains.kotlin.types.Variance import org.jetbrains.kotlin.types.expressions.OperatorConventions -object CreateUnaryOperationActionFactory: CreateCallableMemberFromUsageFactory() { +object CreateUnaryOperationActionFactory : CreateCallableMemberFromUsageFactory() { override fun getElementOfInterest(diagnostic: Diagnostic): KtUnaryExpression? { return diagnostic.psiElement.parent as? KtUnaryExpression } @@ -42,10 +31,10 @@ object CreateUnaryOperationActionFactory: CreateCallableMemberFromUsageFactory() { +object CreateClassFromConstructorCallActionFactory : CreateClassFromUsageFactory() { override fun getElementOfInterest(diagnostic: Diagnostic): KtCallExpression? { val diagElement = diagnostic.psiElement if (diagElement.getNonStrictParentOfType() != null) return null @@ -68,8 +57,7 @@ object CreateClassFromConstructorCallActionFactory: CreateClassFromUsageFactory< if (!inAnnotationEntry && !name.checkClassName()) return null val callParent = callExpr.parent - val fullCallExpr = - if (callParent is KtQualifiedExpression && callParent.selectorExpression == callExpr) callParent else callExpr + val fullCallExpr = if (callParent is KtQualifiedExpression && callParent.selectorExpression == callExpr) callParent else callExpr val (context, moduleDescriptor) = callExpr.analyzeAndGetResult() @@ -82,8 +70,11 @@ object CreateClassFromConstructorCallActionFactory: CreateClassFromUsageFactory< val anyType = moduleDescriptor.builtIns.nullableAnyType val parameterInfos = valueArguments.map { ParameterInfo( - it.getArgumentExpression()?.let { TypeInfo(it, Variance.IN_VARIANCE) } ?: TypeInfo(anyType, Variance.IN_VARIANCE), - it.getArgumentName()?.referenceExpression?.getReferencedName() ?: defaultParamName + it.getArgumentExpression()?.let { expression -> TypeInfo(expression, Variance.IN_VARIANCE) } ?: TypeInfo( + anyType, + Variance.IN_VARIANCE + ), + it.getArgumentName()?.referenceExpression?.getReferencedName() ?: defaultParamName ) } @@ -98,12 +89,12 @@ object CreateClassFromConstructorCallActionFactory: CreateClassFromUsageFactory< val typeArgumentInfos = if (inAnnotationEntry) Collections.emptyList() else callExpr.getTypeInfoForTypeArguments() return ClassInfo( - name = name, - targetParents = filteredParents, - expectedTypeInfo = expectedTypeInfo, - inner = inner, - typeArguments = typeArgumentInfos, - parameterInfos = parameterInfos + name = name, + targetParents = filteredParents, + expectedTypeInfo = expectedTypeInfo, + inner = inner, + typeArguments = typeArgumentInfos, + parameterInfos = parameterInfos ) } } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createClass/CreateClassFromReferenceExpressionActionFactory.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createClass/CreateClassFromReferenceExpressionActionFactory.kt index 26b5bac98d1..80d7b2c4bbc 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createClass/CreateClassFromReferenceExpressionActionFactory.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createClass/CreateClassFromReferenceExpressionActionFactory.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createClass @@ -45,7 +34,8 @@ object CreateClassFromReferenceExpressionActionFactory : CreateClassFromUsageFac } } - private fun isQualifierExpected(element: KtSimpleNameExpression) = element.isDotReceiver() || ((element.parent as? KtDotQualifiedExpression)?.isDotReceiver() ?: false) + private fun isQualifierExpected(element: KtSimpleNameExpression) = + element.isDotReceiver() || ((element.parent as? KtDotQualifiedExpression)?.isDotReceiver() ?: false) override fun getPossibleClassKinds(element: KtSimpleNameExpression, diagnostic: Diagnostic): List { fun isEnum(element: PsiElement): Boolean { @@ -64,11 +54,12 @@ object CreateClassFromReferenceExpressionActionFactory : CreateClassFromUsageFac val inImport = element.getNonStrictParentOfType() != null if (inImport || isQualifierExpected(element)) { - val receiverSelector = (fullCallExpr as? KtQualifiedExpression)?.receiverExpression?.getQualifiedElementSelector() as? KtReferenceExpression + val receiverSelector = + (fullCallExpr as? KtQualifiedExpression)?.receiverExpression?.getQualifiedElementSelector() as? KtReferenceExpression val qualifierDescriptor = receiverSelector?.let { context[BindingContext.REFERENCE_TARGET, it] } val targetParents = getTargetParentsByQualifier(element, receiverSelector != null, qualifierDescriptor) - .ifEmpty { return emptyList() } + .ifEmpty { return emptyList() } targetParents.forEach { if (element.getCreatePackageFixIfApplicable(it) != null) return emptyList() @@ -76,15 +67,13 @@ object CreateClassFromReferenceExpressionActionFactory : CreateClassFromUsageFac if (!name.checkClassName()) return emptyList() - return ClassKind - .values() - .filter { - when (it) { - ClassKind.ANNOTATION_CLASS -> inImport - ClassKind.ENUM_ENTRY -> inImport && targetParents.any { isEnum(it) } - else -> true - } - } + return ClassKind.values().filter { + when (it) { + ClassKind.ANNOTATION_CLASS -> inImport + ClassKind.ENUM_ENTRY -> inImport && targetParents.any { isEnum(it) } + else -> true + } + } } val parent = element.parent if (parent is KtClassLiteralExpression && parent.receiverExpression == element) { @@ -120,16 +109,17 @@ object CreateClassFromReferenceExpressionActionFactory : CreateClassFromUsageFac val fullCallExpr = getFullCallExpression(element) ?: return null if (element.isInImportDirective() || isQualifierExpected(element)) { - val receiverSelector = (fullCallExpr as? KtQualifiedExpression)?.receiverExpression?.getQualifiedElementSelector() as? KtReferenceExpression + val receiverSelector = + (fullCallExpr as? KtQualifiedExpression)?.receiverExpression?.getQualifiedElementSelector() as? KtReferenceExpression val qualifierDescriptor = receiverSelector?.let { context[BindingContext.REFERENCE_TARGET, it] } val targetParents = getTargetParentsByQualifier(element, receiverSelector != null, qualifierDescriptor) - .ifEmpty { return null } + .ifEmpty { return null } return ClassInfo( - name = name, - targetParents = targetParents, - expectedTypeInfo = TypeInfo.Empty + name = name, + targetParents = targetParents, + expectedTypeInfo = TypeInfo.Empty ) } @@ -139,9 +129,9 @@ object CreateClassFromReferenceExpressionActionFactory : CreateClassFromUsageFac val expectedTypeInfo = fullCallExpr.guessTypeForClass(context, moduleDescriptor)?.toClassTypeInfo() ?: TypeInfo.Empty return ClassInfo( - name = name, - targetParents = targetParents, - expectedTypeInfo = expectedTypeInfo + name = name, + targetParents = targetParents, + expectedTypeInfo = expectedTypeInfo ) } } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createClass/CreateClassFromTypeReferenceActionFactory.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createClass/CreateClassFromTypeReferenceActionFactory.kt index 9002b4e0632..4d185b5ab73 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createClass/CreateClassFromTypeReferenceActionFactory.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createClass/CreateClassFromTypeReferenceActionFactory.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createClass @@ -44,8 +33,8 @@ object CreateClassFromTypeReferenceActionFactory : CreateClassFromUsageFactory { extendsBound } != null - || typeReference?.getParentOfTypeAndBranch { boundTypeReference } != null + val isUpperBound = + typeReference?.getParentOfTypeAndBranch { extendsBound } != null || typeReference?.getParentOfTypeAndBranch { boundTypeReference } != null return when { interfaceExpected -> Collections.singletonList(ClassKind.INTERFACE) @@ -87,12 +76,12 @@ object CreateClassFromTypeReferenceActionFactory : CreateClassFromUsageFactory : KotlinIntentionActio protected abstract fun getPossibleClassKinds(element: E, diagnostic: Diagnostic): List override fun createFixes( - originalElementPointer: SmartPsiElementPointer, - diagnostic: Diagnostic, - quickFixDataFactory: () -> ClassInfo? + originalElementPointer: SmartPsiElementPointer, + diagnostic: Diagnostic, + quickFixDataFactory: () -> ClassInfo? ): List { val possibleClassKinds = getPossibleClassKinds(originalElementPointer.element ?: return emptyList(), diagnostic) diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createClass/CreateClassFromUsageFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createClass/CreateClassFromUsageFix.kt index c43147b40d6..4164cba66f0 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createClass/CreateClassFromUsageFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createClass/CreateClassFromUsageFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createClass @@ -279,4 +268,5 @@ open class CreateClassFromUsageFix protected constructor( } } -private val TypeInfo.isUnit: Boolean get() = ((this as? TypeInfo.DelegatingTypeInfo)?.delegate as? TypeInfo.ByType)?.theType?.isUnit() == true +private val TypeInfo.isUnit: Boolean + get() = ((this as? TypeInfo.DelegatingTypeInfo)?.delegate as? TypeInfo.ByType)?.theType?.isUnit() == true diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createTypeParameter/CreateTypeParameterFromUsageFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createTypeParameter/CreateTypeParameterFromUsageFix.kt index d1c9dfa8abc..eda6dfc470d 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createTypeParameter/CreateTypeParameterFromUsageFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createTypeParameter/CreateTypeParameterFromUsageFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createTypeParameter @@ -24,14 +13,12 @@ import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.usageView.UsageViewTypeLocation import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.caches.resolve.analyze -import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.core.addTypeParameter import org.jetbrains.kotlin.idea.core.replaced import org.jetbrains.kotlin.idea.core.util.runSynchronouslyWithProgress import org.jetbrains.kotlin.idea.intentions.InsertExplicitTypeArgumentsIntention import org.jetbrains.kotlin.idea.quickfix.createFromUsage.CreateFromUsageFixBase -import org.jetbrains.kotlin.idea.resolve.frontendService import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.idea.util.application.runWriteAction @@ -39,7 +26,6 @@ import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypeAndBranch import org.jetbrains.kotlin.psi.psiUtil.quoteIfNeeded import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode -import org.jetbrains.kotlin.storage.StorageManager import org.jetbrains.kotlin.types.TypeProjectionImpl import org.jetbrains.kotlin.types.TypeSubstitutor import org.jetbrains.kotlin.types.Variance @@ -111,8 +97,13 @@ class CreateTypeParameterFromUsageFix( typeParameter.fakeTypeParameter.containingDeclaration, "_", typeParameter.fakeTypeParameter.storageManager ) val anonymizedUpperBoundText = upperBoundType?.let { - TypeSubstitutor - .create(mapOf(typeParameter.fakeTypeParameter.typeConstructor to TypeProjectionImpl(anonymizedTypeParameter.defaultType))) + TypeSubstitutor.create( + mapOf( + typeParameter.fakeTypeParameter.typeConstructor to TypeProjectionImpl( + anonymizedTypeParameter.defaultType + ) + ) + ) .substitute(upperBoundType, Variance.INVARIANT) }?.let { IdeDescriptorRenderers.SOURCE_CODE.renderType(it) @@ -131,9 +122,9 @@ class CreateTypeParameterFromUsageFix( ) as KtTypeArgumentList } is KtCallElement -> { - if (it.analyze(BodyResolveMode.PARTIAL_WITH_DIAGNOSTICS).diagnostics.forElement(it.calleeExpression!!).any { diagnostic -> - diagnostic.factory in Errors.TYPE_INFERENCE_ERRORS - }) { + if (it.analyze(BodyResolveMode.PARTIAL_WITH_DIAGNOSTICS).diagnostics.forElement(it.calleeExpression!!) + .any { diagnostic -> diagnostic.factory in Errors.TYPE_INFERENCE_ERRORS } + ) { callsToExplicateArguments += it } } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createVariable/CreateLocalVariableActionFactory.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createVariable/CreateLocalVariableActionFactory.kt index 6f8010bcab4..a3861957c63 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createVariable/CreateLocalVariableActionFactory.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createVariable/CreateLocalVariableActionFactory.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createVariable @@ -69,7 +58,8 @@ object CreateLocalVariableActionFactory : KotlinSingleIntentionActionFactory() { originalElement.getExpressionForTypeGuess(), if (varExpected) Variance.INVARIANT else Variance.OUT_VARIANCE ) - val propertyInfo = PropertyInfo(propertyName, TypeInfo.Empty, typeInfo, varExpected, Collections.singletonList(actualContainer)) + val propertyInfo = + PropertyInfo(propertyName, TypeInfo.Empty, typeInfo, varExpected, Collections.singletonList(actualContainer)) with(CallableBuilderConfiguration(listOfNotNull(propertyInfo), originalElement, file, editor).createBuilder()) { placement = CallablePlacement.NoReceiver(actualContainer) diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createVariable/CreateParameterByNamedArgumentActionFactory.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createVariable/CreateParameterByNamedArgumentActionFactory.kt index 25db9b23885..8ef53991563 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createVariable/CreateParameterByNamedArgumentActionFactory.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createVariable/CreateParameterByNamedArgumentActionFactory.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createVariable @@ -31,7 +20,7 @@ import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns -object CreateParameterByNamedArgumentActionFactory: CreateParameterFromUsageFactory() { +object CreateParameterByNamedArgumentActionFactory : CreateParameterFromUsageFactory() { override fun getElementOfInterest(diagnostic: Diagnostic): KtValueArgument? { val argument = QuickFixUtil.getParentElementOfType(diagnostic, KtValueArgument::class.java) ?: return null return if (argument.isNamed()) argument else null @@ -62,11 +51,11 @@ object CreateParameterByNamedArgumentActionFactory: CreateParameterFromUsageFact val needVal = callable is KtPrimaryConstructor && ((callable.getContainingClassOrObject() as? KtClass)?.isData() ?: false) val parameterInfo = KotlinParameterInfo( - callableDescriptor = functionDescriptor, - name = name, - originalTypeInfo = KotlinTypeInfo(false, paramType), - defaultValueForCall = argumentExpression, - valOrVar = if (needVal) KotlinValVar.Val else KotlinValVar.None + callableDescriptor = functionDescriptor, + name = name, + originalTypeInfo = KotlinTypeInfo(false, paramType), + defaultValueForCall = argumentExpression, + valOrVar = if (needVal) KotlinValVar.Val else KotlinValVar.None ) return CreateParameterData(parameterInfo, element) diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createVariable/CreateParameterByRefActionFactory.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createVariable/CreateParameterByRefActionFactory.kt index 1dbd0421307..d6887441e9b 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createVariable/CreateParameterByRefActionFactory.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createVariable/CreateParameterByRefActionFactory.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createVariable @@ -78,31 +67,30 @@ object CreateParameterByRefActionFactory : CreateParameterFromUsageFactory chooseContainingClass(it) - it is KtAnonymousInitializer -> it.parent.parent as? KtClass - it is KtSuperTypeListEntry -> { - val klass = it.getStrictParentOfType() - if (klass is KtClass && !klass.isInterface() && klass !is KtEnumEntry) klass else null - } - it is KtClassBody -> { - val klass = it.parent as? KtClass - when { - klass is KtEnumEntry -> chooseContainingClass(klass) - klass != null && klass.isInterface() -> null - else -> klass - } - } - else -> it + .filter { + it is KtNamedFunction || it is KtSecondaryConstructor || it is KtPropertyAccessor || it is KtClassBody || it is KtAnonymousInitializer || it is KtSuperTypeListEntry + } + .firstOrNull() + ?.let { + when { + (it is KtNamedFunction || it is KtSecondaryConstructor) && varExpected || + it is KtPropertyAccessor -> chooseContainingClass(it) + it is KtAnonymousInitializer -> it.parent.parent as? KtClass + it is KtSuperTypeListEntry -> { + val klass = it.getStrictParentOfType() + if (klass is KtClass && !klass.isInterface() && klass !is KtEnumEntry) klass else null } + it is KtClassBody -> { + val klass = it.parent as? KtClass + when { + klass is KtEnumEntry -> chooseContainingClass(klass) + klass != null && klass.isInterface() -> null + else -> klass + } + } + else -> it } + } } val container = chooseContainerPreferringClass() ?: chooseFunction() @@ -114,11 +102,13 @@ object CreateParameterByRefActionFactory : CreateParameterFromUsageFactory { - (functionDescriptor.containingDeclaration as? ClassDescriptorWithResolutionScopes)?.scopeForClassHeaderResolution - } + val scope = when (functionDescriptor) { + is ConstructorDescriptor -> { + (functionDescriptor.containingDeclaration as? ClassDescriptorWithResolutionScopes)?.scopeForClassHeaderResolution + } - else -> { - val function = functionDescriptor.source.getPsi() as? KtFunction - function?.bodyExpression?.getResolutionScope(context, function.getResolutionFacade()) - } - } ?: return true + else -> { + val function = functionDescriptor.source.getPsi() as? KtFunction + function?.bodyExpression?.getResolutionScope(context, function.getResolutionFacade()) + } + } ?: return true return typeParametersToAdd.any { scope.findClassifier(it.name, NoLookupLocation.FROM_IDE) != it } } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createVariable/CreateParameterFromUsageFactory.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createVariable/CreateParameterFromUsageFactory.kt index a5916998eaa..d7fd831e604 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createVariable/CreateParameterFromUsageFactory.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createVariable/CreateParameterFromUsageFactory.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createVariable @@ -22,12 +11,13 @@ import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinParameterInfo import org.jetbrains.kotlin.psi.KtElement data class CreateParameterData( - val parameterInfo: KotlinParameterInfo, - val originalExpression: E, - val createSilently: Boolean = false, - val onComplete: ((Editor?) -> Unit)? = null + val parameterInfo: KotlinParameterInfo, + val originalExpression: E, + val createSilently: Boolean = false, + val onComplete: ((Editor?) -> Unit)? = null ) -abstract class CreateParameterFromUsageFactory: KotlinSingleIntentionActionFactoryWithDelegate>() { +abstract class CreateParameterFromUsageFactory : + KotlinSingleIntentionActionFactoryWithDelegate>() { override fun createFix(originalElement: E, data: CreateParameterData) = CreateParameterFromUsageFix(data) } \ No newline at end of file diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createVariable/CreateParameterFromUsageFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createVariable/CreateParameterFromUsageFix.kt index 962f8b19b9b..1d780601cc0 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createVariable/CreateParameterFromUsageFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createVariable/CreateParameterFromUsageFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createVariable @@ -35,7 +24,7 @@ import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.resolve.source.getPsi open class CreateParameterFromUsageFix( - val data: CreateParameterData + val data: CreateParameterData ) : CreateFromUsageFixBase(data.originalExpression) { override fun getText(): String { return with(data.parameterInfo) { @@ -76,9 +65,9 @@ open class CreateParameterFromUsageFix( companion object { fun createFixForPrimaryConstructorPropertyParameter( - element: E, - info: PropertyInfo - ) : CreateParameterFromUsageFix? { + element: E, + info: PropertyInfo + ): CreateParameterFromUsageFix? { val receiverClassDescriptor: ClassDescriptor val builder = CallableBuilderConfiguration(listOf(info), element).createBuilder() @@ -86,8 +75,7 @@ open class CreateParameterFromUsageFix( if (receiverTypeCandidate != null) { builder.placement = CallablePlacement.WithReceiver(receiverTypeCandidate) receiverClassDescriptor = receiverTypeCandidate.theType.constructor.declarationDescriptor as? ClassDescriptor ?: return null - } - else { + } else { if (element !is KtSimpleNameExpression) return null val classOrObject = element.getStrictParentOfType() ?: return null @@ -106,10 +94,10 @@ open class CreateParameterFromUsageFix( if (paramType != null && paramType.hasTypeParametersToAdd(constructorDescriptor, builder.currentFileContext)) return null val paramInfo = KotlinParameterInfo( - callableDescriptor = constructorDescriptor, - name = info.name, - originalTypeInfo = KotlinTypeInfo(false, paramType), - valOrVar = if (info.writable) KotlinValVar.Var else KotlinValVar.Val + callableDescriptor = constructorDescriptor, + name = info.name, + originalTypeInfo = KotlinTypeInfo(false, paramType), + valOrVar = if (info.writable) KotlinValVar.Var else KotlinValVar.Val ) return CreateParameterFromUsageFix(CreateParameterData(paramInfo, element)) diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/crossLanguage/KotlinElementActionsFactory.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/crossLanguage/KotlinElementActionsFactory.kt index fcb46593d56..c99dd7b254d 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/crossLanguage/KotlinElementActionsFactory.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/crossLanguage/KotlinElementActionsFactory.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix.crossLanguage @@ -83,10 +72,10 @@ import org.jetbrains.kotlin.types.typeUtil.supertypes class KotlinElementActionsFactory : JvmElementActionsFactory() { companion object { val javaPsiModifiersMapping = mapOf( - JvmModifier.PRIVATE to KtTokens.PRIVATE_KEYWORD, - JvmModifier.PUBLIC to KtTokens.PUBLIC_KEYWORD, - JvmModifier.PROTECTED to KtTokens.PUBLIC_KEYWORD, - JvmModifier.ABSTRACT to KtTokens.ABSTRACT_KEYWORD + JvmModifier.PRIVATE to KtTokens.PRIVATE_KEYWORD, + JvmModifier.PUBLIC to KtTokens.PUBLIC_KEYWORD, + JvmModifier.PROTECTED to KtTokens.PUBLIC_KEYWORD, + JvmModifier.ABSTRACT to KtTokens.ABSTRACT_KEYWORD ) } @@ -102,8 +91,8 @@ class KotlinElementActionsFactory : JvmElementActionsFactory() { } private class ModifierBuilder( - private val targetContainer: KtElement, - private val allowJvmStatic: Boolean = true + private val targetContainer: KtElement, + private val allowJvmStatic: Boolean = true ) { private val psiFactory = KtPsiFactory(targetContainer.project) @@ -147,7 +136,7 @@ class KotlinElementActionsFactory : JvmElementActionsFactory() { } class CreatePropertyFix( - contextElement: KtElement, + contextElement: KtElement, propertyInfo: PropertyInfo, private val classOrFileName: String? ) : CreateCallableFromUsageFix(contextElement, listOf(propertyInfo)) { @@ -177,22 +166,21 @@ class KotlinElementActionsFactory : JvmElementActionsFactory() { private inline fun JvmElement.toKtElement() = sourceElement?.unwrapped as? T - private fun fakeParametersExpressions(parameters: List, project: Project): Array? = - when { - parameters.isEmpty() -> emptyArray() - else -> JavaPsiFacade - .getElementFactory(project) - .createParameterList( - parameters.map { it.semanticNames.firstOrNull() }.toTypedArray(), - parameters.map { - it.expectedTypes.firstOrNull()?.theType - ?.let { JvmPsiConversionHelper.getInstance(project).convertType(it) } ?: return null - }.toTypedArray() - ) - .parameters - .map(::FakeExpressionFromParameter) - .toTypedArray() - } + private fun fakeParametersExpressions(parameters: List, project: Project): Array? = when { + parameters.isEmpty() -> emptyArray() + else -> JavaPsiFacade + .getElementFactory(project) + .createParameterList( + parameters.map { it.semanticNames.firstOrNull() }.toTypedArray(), + parameters.map { + it.expectedTypes.firstOrNull()?.theType + ?.let { JvmPsiConversionHelper.getInstance(project).convertType(it) } ?: return null + }.toTypedArray() + ) + .parameters + .map(::FakeExpressionFromParameter) + .toTypedArray() + } private fun ExpectedTypes.toKotlinTypeInfo(resolutionFacade: ResolutionFacade): TypeInfo { @@ -250,11 +238,11 @@ class KotlinElementActionsFactory : JvmElementActionsFactory() { } val needPrimary = !targetKtClass.hasExplicitPrimaryConstructor() val constructorInfo = ConstructorInfo( - parameterInfos, - targetKtClass, - isPrimary = needPrimary, - modifierList = modifierBuilder.modifierList, - withBody = true + parameterInfos, + targetKtClass, + isPrimary = needPrimary, + modifierList = modifierBuilder.modifierList, + withBody = true ) val targetClassName = targetClass.name val addConstructorAction = object : CreateCallableFromUsageFix(targetKtClass, listOf(constructorInfo)) { @@ -267,15 +255,14 @@ class KotlinElementActionsFactory : JvmElementActionsFactory() { val lightMethod = primaryConstructor.toLightMethods().firstOrNull() ?: return@run null val project = targetKtClass.project val fakeParametersExpressions = fakeParametersExpressions(parameters, project) ?: return@run null - QuickFixFactory.getInstance() - .createChangeMethodSignatureFromUsageFix( - lightMethod, - fakeParametersExpressions, - PsiSubstitutor.EMPTY, - targetKtClass, - false, - 2 - ).takeIf { it.isAvailable(project, null, targetKtClass.containingFile) } + QuickFixFactory.getInstance().createChangeMethodSignatureFromUsageFix( + lightMethod, + fakeParametersExpressions, + PsiSubstitutor.EMPTY, + targetKtClass, + false, + 2 + ).takeIf { it.isAvailable(project, null, targetKtClass.containingFile) } } return listOfNotNull(changePrimaryConstructorAction, addConstructorAction) @@ -298,17 +285,16 @@ class KotlinElementActionsFactory : JvmElementActionsFactory() { val ktType = (propertyType as? PsiType)?.resolveToKotlinType(resolutionFacade) ?: nullableAnyType val propertyInfo = PropertyInfo( propertyName, - TypeInfo.Empty, - TypeInfo(ktType, Variance.INVARIANT), + TypeInfo.Empty, + TypeInfo(ktType, Variance.INVARIANT), setterRequired, - listOf(targetContainer), - modifierList = modifierBuilder.modifierList, - withInitializer = true + listOf(targetContainer), + modifierList = modifierBuilder.modifierList, + withInitializer = true ) val propertyInfos = if (setterRequired) { listOf(propertyInfo, propertyInfo.copyProperty(isLateinitPreferred = true)) - } - else { + } else { listOf(propertyInfo) } return propertyInfos.map { CreatePropertyFix(targetContainer, it, classOrFileName) } @@ -343,8 +329,7 @@ class KotlinElementActionsFactory : JvmElementActionsFactory() { val propertyInfos = if (writable) { listOf(propertyInfo(false), propertyInfo(true)) - } - else { + } else { listOf(propertyInfo(false)) } return propertyInfos.map { CreatePropertyFix(targetContainer, it, targetClass.name) } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/migration/MigrateExternalExtensionFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/migration/MigrateExternalExtensionFix.kt index c260d8e3a2b..708bbf3cbe2 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/migration/MigrateExternalExtensionFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/migration/MigrateExternalExtensionFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix.migration @@ -42,8 +31,7 @@ import org.jetbrains.kotlin.psi.psiUtil.getParentOfType import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode -class MigrateExternalExtensionFix(declaration: KtNamedDeclaration) - : KotlinQuickFixAction(declaration), CleanupFix { +class MigrateExternalExtensionFix(declaration: KtNamedDeclaration) : KotlinQuickFixAction(declaration), CleanupFix { override fun getText() = "Fix with 'asDynamic'" override fun getFamilyName() = text @@ -66,11 +54,11 @@ class MigrateExternalExtensionFix(declaration: KtNamedDeclaration) private fun fixNativeClass(containingClass: KtClassOrObject) { val membersToFix = containingClass.declarations.asSequence().filterIsInstance() - .filter { isMemberDeclaration(it) && !isMemberExtensionDeclaration(it) }. map { - it to fetchJsNativeAnnotations(it) - }.filter { - it.second.annotations.isNotEmpty() - }.toList() + .filter { isMemberDeclaration(it) && !isMemberExtensionDeclaration(it) }.map { + it to fetchJsNativeAnnotations(it) + }.filter { + it.second.annotations.isNotEmpty() + }.toList() membersToFix.asReversed().forEach { (memberDeclaration, annotations) -> if (annotations.nativeAnnotation != null && !annotations.isGetter && !annotations.isSetter && !annotations.isInvoke) { @@ -87,9 +75,15 @@ class MigrateExternalExtensionFix(declaration: KtNamedDeclaration) fixAnnotations(containingClass, classAnnotations, null) } - private data class JsNativeAnnotations(val annotations: List, val nativeAnnotation: KtAnnotationEntry?, val isGetter: Boolean, val isSetter: Boolean, val isInvoke: Boolean) + private data class JsNativeAnnotations( + val annotations: List, + val nativeAnnotation: KtAnnotationEntry?, + val isGetter: Boolean, + val isSetter: Boolean, + val isInvoke: Boolean + ) - private fun fetchJsNativeAnnotations(declaration: KtNamedDeclaration) : JsNativeAnnotations { + private fun fetchJsNativeAnnotations(declaration: KtNamedDeclaration): JsNativeAnnotations { var isGetter = false var isSetter = false var isInvoke = false @@ -171,8 +165,7 @@ class MigrateExternalExtensionFix(declaration: KtNamedDeclaration) declaration.add(ktPsiFactory.createEQ()) declaration.add(body) } - } - else if (declaration is KtProperty) { + } else if (declaration is KtProperty) { declaration.setter?.delete() declaration.getter?.delete() val getter = ktPsiFactory.createPropertyGetter(body) @@ -223,9 +216,14 @@ class MigrateExternalExtensionFix(declaration: KtNamedDeclaration) } } - private fun BuilderByPattern.appendParameters(declaration: KtNamedFunction, lParenth: String, rParenth: String, skipLast: Boolean = false) { + private fun BuilderByPattern.appendParameters( + declaration: KtNamedFunction, + lParenth: String, + rParenth: String, + skipLast: Boolean = false + ) { appendFixedText(lParenth) - for ((index, param) in declaration.valueParameters.let { if (skipLast) it.take(it.size-1) else it }.withIndex()) { + for ((index, param) in declaration.valueParameters.let { if (skipLast) it.take(it.size - 1) else it }.withIndex()) { param.nameAsName?.let { paramName -> if (index > 0) { appendFixedText(",") @@ -243,19 +241,20 @@ class MigrateExternalExtensionFix(declaration: KtNamedDeclaration) return annotationDescriptor != null && predefinedAnnotations.any { annotationDescriptor.fqName == it.fqName } } - private fun KtAnnotationEntry.isJsNativeAnnotation(): Boolean { - return isJsAnnotation(PredefinedAnnotation.NATIVE, PredefinedAnnotation.NATIVE_GETTER, PredefinedAnnotation.NATIVE_SETTER, PredefinedAnnotation.NATIVE_INVOKE ) - } + private fun KtAnnotationEntry.isJsNativeAnnotation(): Boolean = isJsAnnotation( + PredefinedAnnotation.NATIVE, + PredefinedAnnotation.NATIVE_GETTER, + PredefinedAnnotation.NATIVE_SETTER, + PredefinedAnnotation.NATIVE_INVOKE + ) private fun isMemberExtensionDeclaration(psiElement: PsiElement): Boolean { return (psiElement is KtNamedFunction && psiElement.receiverTypeReference != null) || - (psiElement is KtProperty && psiElement.receiverTypeReference != null) + (psiElement is KtProperty && psiElement.receiverTypeReference != null) } - private fun isMemberDeclaration(psiElement: PsiElement): Boolean { - return (psiElement is KtNamedFunction && psiElement.receiverTypeReference == null) || - (psiElement is KtProperty && psiElement.receiverTypeReference == null) - } + private fun isMemberDeclaration(psiElement: PsiElement): Boolean = + (psiElement is KtNamedFunction && psiElement.receiverTypeReference == null) || (psiElement is KtProperty && psiElement.receiverTypeReference == null) override fun createAction(diagnostic: Diagnostic): IntentionAction? { val e = diagnostic.psiElement diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/migration/MigrateTypeParameterListFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/migration/MigrateTypeParameterListFix.kt index bd785cc9d4a..593e099e9eb 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/migration/MigrateTypeParameterListFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/migration/MigrateTypeParameterListFix.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix.migration @@ -28,11 +17,11 @@ import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.KtTypeParameterList import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType -class MigrateTypeParameterListFix(typeParameterList: KtTypeParameterList) - : KotlinQuickFixAction(typeParameterList), CleanupFix { +class MigrateTypeParameterListFix(typeParameterList: KtTypeParameterList) : KotlinQuickFixAction(typeParameterList), + CleanupFix { override fun getFamilyName(): String = "Migrate type parameter list syntax" - override fun getText(): String = familyName + override fun getText(): String = familyName override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = element ?: return diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/replaceWith/DeprecatedSymbolUsageFixBase.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/replaceWith/DeprecatedSymbolUsageFixBase.kt index 29fd348cd5d..64cdc7b3d71 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/replaceWith/DeprecatedSymbolUsageFixBase.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/replaceWith/DeprecatedSymbolUsageFixBase.kt @@ -125,7 +125,7 @@ abstract class DeprecatedSymbolUsageFixBase( } return expressionFromPattern.text } - + if (expressionFromPattern !is KtCallExpression) return this val methodFromPattern = expressionFromPattern.referenceExpression()?.let { name -> KotlinShortNamesCache(element.project).getMethodsByName( diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/replaceWith/ReplaceWithAnnotationAnalyzer.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/replaceWith/ReplaceWithAnnotationAnalyzer.kt index 182bcb593fa..b6144e7d88b 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/replaceWith/ReplaceWithAnnotationAnalyzer.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/replaceWith/ReplaceWithAnnotationAnalyzer.kt @@ -1,22 +1,10 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix.replaceWith -import org.jetbrains.kotlin.platform.TargetPlatform import org.jetbrains.kotlin.config.LanguageVersionSettings import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.analysis.analyzeInContext @@ -30,6 +18,7 @@ import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.idea.resolve.frontendService import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.FqNameUnsafe +import org.jetbrains.kotlin.platform.TargetPlatform import org.jetbrains.kotlin.psi.KtNameReferenceExpression import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.KtUserType @@ -144,7 +133,8 @@ object ReplaceWithAnnotationAnalyzer { languageVersionSettings: LanguageVersionSettings ): List { val allDefaultImports = - resolutionFacade.frontendService().findAnalyzerServices.getDefaultImports(languageVersionSettings, includeLowPriorityImports = true) + resolutionFacade.frontendService().findAnalyzerServices + .getDefaultImports(languageVersionSettings, includeLowPriorityImports = true) val (allUnderImports, aliasImports) = allDefaultImports.partition { it.isAllUnder } // this solution doesn't support aliased default imports with a different alias // TODO: Create import directives from ImportPath, create ImportResolver, create LazyResolverScope, see FileScopeProviderImpl diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/KotlinRefactoringSettings.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/KotlinRefactoringSettings.kt index fe525821f0c..afdbe5437ad 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/KotlinRefactoringSettings.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/KotlinRefactoringSettings.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring @@ -20,37 +9,75 @@ import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage -import com.intellij.refactoring.JavaRefactoringSettings import com.intellij.util.xmlb.XmlSerializerUtil @State(name = "KotlinRefactoringSettings", storages = arrayOf(Storage("kotlinRefactoring.xml"))) class KotlinRefactoringSettings : PersistentStateComponent { - @JvmField var MOVE_TO_UPPER_LEVEL_SEARCH_IN_COMMENTS = false - @JvmField var MOVE_TO_UPPER_LEVEL_SEARCH_FOR_TEXT = false + @JvmField + var MOVE_TO_UPPER_LEVEL_SEARCH_IN_COMMENTS = false - @JvmField var RENAME_SEARCH_IN_COMMENTS_FOR_PACKAGE = false - @JvmField var RENAME_SEARCH_IN_COMMENTS_FOR_CLASS = false - @JvmField var RENAME_SEARCH_IN_COMMENTS_FOR_METHOD = false - @JvmField var RENAME_SEARCH_IN_COMMENTS_FOR_FIELD = false - @JvmField var RENAME_SEARCH_IN_COMMENTS_FOR_VARIABLE = false + @JvmField + var MOVE_TO_UPPER_LEVEL_SEARCH_FOR_TEXT = false - @JvmField var RENAME_SEARCH_FOR_TEXT_FOR_PACKAGE = false - @JvmField var RENAME_SEARCH_FOR_TEXT_FOR_CLASS = false - @JvmField var RENAME_SEARCH_FOR_TEXT_FOR_METHOD = false - @JvmField var RENAME_SEARCH_FOR_TEXT_FOR_FIELD = false - @JvmField var RENAME_SEARCH_FOR_TEXT_FOR_VARIABLE = false + @JvmField + var RENAME_SEARCH_IN_COMMENTS_FOR_PACKAGE = false - @JvmField var MOVE_PREVIEW_USAGES = true - @JvmField var MOVE_SEARCH_IN_COMMENTS = true - @JvmField var MOVE_SEARCH_FOR_TEXT = true - @JvmField var MOVE_DELETE_EMPTY_SOURCE_FILES = true + @JvmField + var RENAME_SEARCH_IN_COMMENTS_FOR_CLASS = false - @JvmField var EXTRACT_INTERFACE_JAVADOC: Int = 0 - @JvmField var EXTRACT_SUPERCLASS_JAVADOC: Int = 0 - @JvmField var PULL_UP_MEMBERS_JAVADOC: Int = 0 - @JvmField var PUSH_DOWN_PREVIEW_USAGES: Boolean = false - @JvmField var INLINE_METHOD_THIS: Boolean = false - @JvmField var INLINE_LOCAL_THIS: Boolean = false + @JvmField + var RENAME_SEARCH_IN_COMMENTS_FOR_METHOD = false + + @JvmField + var RENAME_SEARCH_IN_COMMENTS_FOR_FIELD = false + + @JvmField + var RENAME_SEARCH_IN_COMMENTS_FOR_VARIABLE = false + + @JvmField + var RENAME_SEARCH_FOR_TEXT_FOR_PACKAGE = false + + @JvmField + var RENAME_SEARCH_FOR_TEXT_FOR_CLASS = false + + @JvmField + var RENAME_SEARCH_FOR_TEXT_FOR_METHOD = false + + @JvmField + var RENAME_SEARCH_FOR_TEXT_FOR_FIELD = false + + @JvmField + var RENAME_SEARCH_FOR_TEXT_FOR_VARIABLE = false + + @JvmField + var MOVE_PREVIEW_USAGES = true + + @JvmField + var MOVE_SEARCH_IN_COMMENTS = true + + @JvmField + var MOVE_SEARCH_FOR_TEXT = true + + @JvmField + var MOVE_DELETE_EMPTY_SOURCE_FILES = true + + @JvmField + var EXTRACT_INTERFACE_JAVADOC: Int = 0 + + @JvmField + var EXTRACT_SUPERCLASS_JAVADOC: Int = 0 + + @JvmField + var PULL_UP_MEMBERS_JAVADOC: Int = 0 + + @JvmField + var PUSH_DOWN_PREVIEW_USAGES: Boolean = false + + @JvmField + var INLINE_METHOD_THIS: Boolean = false + + @JvmField + var INLINE_LOCAL_THIS: Boolean = false var renameInheritors = true diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/KotlinRefactoringSupportProvider.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/KotlinRefactoringSupportProvider.kt index 34aac8e9d1f..b3424678695 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/KotlinRefactoringSupportProvider.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/KotlinRefactoringSupportProvider.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring @@ -47,10 +36,10 @@ class KotlinRefactoringSupportProvider : RefactoringSupportProvider() { fun getIntroducePropertyHandler(): RefactoringActionHandler = KotlinIntroducePropertyHandler() fun getExtractFunctionHandler(): RefactoringActionHandler = - ExtractKotlinFunctionHandler() + ExtractKotlinFunctionHandler() fun getExtractFunctionToScopeHandler(): RefactoringActionHandler = - ExtractKotlinFunctionHandler(true, ExtractKotlinFunctionHandler.InteractiveExtractionHelper) + ExtractKotlinFunctionHandler(true, ExtractKotlinFunctionHandler.InteractiveExtractionHelper) override fun getChangeSignatureHandler() = KotlinChangeSignatureHandler() @@ -63,7 +52,7 @@ class KotlinRefactoringSupportProvider : RefactoringSupportProvider() { override fun getExtractInterfaceHandler() = KotlinExtractInterfaceHandler } -class KotlinVetoRenameCondition: Condition { +class KotlinVetoRenameCondition : Condition { override fun value(t: PsiElement?): Boolean = - t is KtElement && t is PsiNameIdentifierOwner && t.nameIdentifier == null && t !is KtConstructor<*> + t is KtElement && t is PsiNameIdentifierOwner && t.nameIdentifier == null && t !is KtConstructor<*> } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/ValVarExpression.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/ValVarExpression.kt index c75bc92512b..6b28dbd4db8 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/ValVarExpression.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/ValVarExpression.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring @@ -23,7 +12,7 @@ import com.intellij.codeInsight.template.ExpressionContext import com.intellij.codeInsight.template.Result import com.intellij.codeInsight.template.TextResult -object ValVarExpression: Expression() { +object ValVarExpression : Expression() { private val cachedLookupElements = listOf("val", "var").map { LookupElementBuilder.create(it) }.toTypedArray() override fun calculateResult(context: ExpressionContext?): Result? = TextResult("val") diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinAwareJavaParameterInfoImpl.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinAwareJavaParameterInfoImpl.kt index ac7ee4b3240..9ddab993cf4 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinAwareJavaParameterInfoImpl.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinAwareJavaParameterInfoImpl.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.changeSignature @@ -21,8 +10,8 @@ import com.intellij.refactoring.changeSignature.ParameterInfoImpl import org.jetbrains.kotlin.psi.KtExpression class KotlinAwareJavaParameterInfoImpl( - oldParameterIndex: Int, - name: String, - type: PsiType, - val kotlinDefaultValue: KtExpression? -): ParameterInfoImpl(oldParameterIndex, name, type, kotlinDefaultValue?.text ?: "") \ No newline at end of file + oldParameterIndex: Int, + name: String, + type: PsiType, + val kotlinDefaultValue: KtExpression? +) : ParameterInfoImpl(oldParameterIndex, name, type, kotlinDefaultValue?.text ?: "") \ No newline at end of file diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinChangeSignature.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinChangeSignature.kt index 5e91f0c9926..6461d908cea 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinChangeSignature.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinChangeSignature.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.changeSignature @@ -50,7 +39,7 @@ interface KotlinChangeSignatureConfiguration { fun performSilently(affectedFunctions: Collection): Boolean = false fun forcePerformForSelectedFunctionOnly(): Boolean = false - object Empty: KotlinChangeSignatureConfiguration + object Empty : KotlinChangeSignatureConfiguration } fun KotlinMethodDescriptor.modify(action: (KotlinMutableMethodDescriptor) -> Unit): KotlinMethodDescriptor { @@ -59,11 +48,13 @@ fun KotlinMethodDescriptor.modify(action: (KotlinMutableMethodDescriptor) -> Uni return newDescriptor } -fun runChangeSignature(project: Project, - callableDescriptor: CallableDescriptor, - configuration: KotlinChangeSignatureConfiguration, - defaultValueContext: PsiElement, - commandName: String? = null): Boolean { +fun runChangeSignature( + project: Project, + callableDescriptor: CallableDescriptor, + configuration: KotlinChangeSignatureConfiguration, + defaultValueContext: PsiElement, + commandName: String? = null +): Boolean { val result = KotlinChangeSignature(project, callableDescriptor, configuration, defaultValueContext, commandName).run() if (!result) { broadcastRefactoringExit(project, "refactoring.changeSignature") @@ -72,12 +63,12 @@ fun runChangeSignature(project: Project, } class KotlinChangeSignature( - project: Project, - callableDescriptor: CallableDescriptor, - val configuration: KotlinChangeSignatureConfiguration, - val defaultValueContext: PsiElement, - commandName: String? -): CallableRefactoring(project, callableDescriptor, commandName ?: ChangeSignatureHandler.REFACTORING_NAME) { + project: Project, + callableDescriptor: CallableDescriptor, + val configuration: KotlinChangeSignatureConfiguration, + val defaultValueContext: PsiElement, + commandName: String? +) : CallableRefactoring(project, callableDescriptor, commandName ?: ChangeSignatureHandler.REFACTORING_NAME) { private val LOG = Logger.getInstance(KotlinChangeSignature::class.java) @@ -86,12 +77,17 @@ class KotlinChangeSignature( private fun runSilentRefactoring(descriptor: KotlinMethodDescriptor) { val baseDeclaration = descriptor.baseDeclaration val processor = when (baseDeclaration) { - is KtFunction, is KtClass -> { - KotlinChangeSignatureDialog.createRefactoringProcessorForSilentChangeSignature(project, commandName, descriptor, defaultValueContext) - } - is KtProperty, is KtParameter -> { - KotlinChangePropertySignatureDialog.createProcessorForSilentRefactoring(project, commandName, descriptor) - } + is KtFunction, is KtClass -> KotlinChangeSignatureDialog.createRefactoringProcessorForSilentChangeSignature( + project, + commandName, + descriptor, + defaultValueContext + ) + is KtProperty, is KtParameter -> KotlinChangePropertySignatureDialog.createProcessorForSilentRefactoring( + project, + commandName, + descriptor + ) is PsiMethod -> { if (baseDeclaration.language != JavaLanguage.INSTANCE) { Messages.showErrorDialog("Can't change signature of ${baseDeclaration.language.displayName} method", commandName) @@ -106,8 +102,7 @@ class KotlinChangeSignature( } private fun runInteractiveRefactoring(descriptor: KotlinMethodDescriptor) { - val baseDeclaration = descriptor.baseDeclaration - val dialog = when (baseDeclaration) { + val dialog = when (val baseDeclaration = descriptor.baseDeclaration) { is KtFunction, is KtClass -> KotlinChangeSignatureDialog(project, descriptor, defaultValueContext, commandName) is KtProperty, is KtParameter -> KotlinChangePropertySignatureDialog(project, descriptor, commandName) is PsiMethod -> { @@ -127,20 +122,20 @@ class KotlinChangeSignature( @Suppress("UNCHECKED_CAST") override fun getParameters() = javaChangeInfo.newParameters.toMutableList() as MutableList } - object: JavaChangeSignatureDialog(project, javaDescriptor, false, null) { + object : JavaChangeSignatureDialog(project, javaDescriptor, false, null) { override fun createRefactoringProcessor(): BaseRefactoringProcessor? { val parameters = parameters LOG.assertTrue(myMethod.method.isValid) val newJavaChangeInfo = JavaChangeInfoImpl( - visibility ?: VisibilityUtil.getVisibilityModifier(myMethod.method.modifierList), - javaChangeInfo.method, - methodName, - returnType ?: CanonicalTypes.createTypeWrapper(PsiType.VOID), - parameters.toTypedArray(), - exceptions, - isGenerateDelegate, - myMethodsToPropagateParameters ?: HashSet(), - myMethodsToPropagateExceptions ?: HashSet() + visibility ?: VisibilityUtil.getVisibilityModifier(myMethod.method.modifierList), + javaChangeInfo.method, + methodName, + returnType ?: CanonicalTypes.createTypeWrapper(PsiType.VOID), + parameters.toTypedArray(), + exceptions, + isGenerateDelegate, + myMethodsToPropagateParameters ?: HashSet(), + myMethodsToPropagateExceptions ?: HashSet() ).also { it.setCheckUnusedParameter() } @@ -184,15 +179,17 @@ class KotlinChangeSignature( KotlinAwareJavaParameterInfoImpl(paramInfo.oldIndex, param.name!!, param.type, paramInfo.defaultValueForCall) }.toTypedArray() - return preview to JavaChangeInfoImpl(visibility, - originalMethod, - preview.name, - returnType, - params, - arrayOf(), - false, - emptySet(), - emptySet()) + return preview to JavaChangeInfoImpl( + visibility, + originalMethod, + preview.name, + returnType, + params, + arrayOf(), + false, + emptySet(), + emptySet() + ) } override fun performRefactoring(descriptorsForChange: Collection) { @@ -203,8 +200,7 @@ class KotlinChangeSignature( if (configuration.performSilently(affectedFunctions) || ApplicationManager.getApplication()!!.isUnitTestMode) { runSilentRefactoring(adjustedDescriptor) - } - else { + } else { runInteractiveRefactoring(adjustedDescriptor) } } @@ -237,23 +233,24 @@ class KotlinChangeSignature( } } -@TestOnly fun createChangeInfo( - project: Project, - callableDescriptor: CallableDescriptor, - configuration: KotlinChangeSignatureConfiguration, - defaultValueContext: PsiElement +@TestOnly +fun createChangeInfo( + project: Project, + callableDescriptor: CallableDescriptor, + configuration: KotlinChangeSignatureConfiguration, + defaultValueContext: PsiElement ): KotlinChangeInfo? { val jetChangeSignature = KotlinChangeSignature(project, callableDescriptor, configuration, defaultValueContext, null) val declarations = - (callableDescriptor as? CallableMemberDescriptor)?.getDeepestSuperDeclarations() ?: listOf(callableDescriptor) + (callableDescriptor as? CallableMemberDescriptor)?.getDeepestSuperDeclarations() ?: listOf(callableDescriptor) val adjustedDescriptor = jetChangeSignature.adjustDescriptor(declarations) ?: return null val processor = KotlinChangeSignatureDialog.createRefactoringProcessorForSilentChangeSignature( - project, - ChangeSignatureHandler.REFACTORING_NAME, - adjustedDescriptor, - defaultValueContext + project, + ChangeSignatureHandler.REFACTORING_NAME, + adjustedDescriptor, + defaultValueContext ) as KotlinChangeSignatureProcessor return processor.ktChangeInfo } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinChangeSignatureData.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinChangeSignatureData.kt index 674aa709b5e..729b533e7ca 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinChangeSignatureData.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinChangeSignatureData.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.changeSignature @@ -117,7 +106,11 @@ class KotlinChangeSignatureData( declaration.liftToExpected()?.let { collectExpectActualMembers(it, primaryFunction, results) } } - if (declaration.isExpectDeclaration()) for (it in declaration.actualsForExpected()) collectExpectActualMembers(it, primaryFunction, results) + if (declaration.isExpectDeclaration()) for (it in declaration.actualsForExpected()) collectExpectActualMembers( + it, + primaryFunction, + results + ) if (declaration !is KtCallableDeclaration) return diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinChangeSignatureHandler.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinChangeSignatureHandler.kt index eafbb4668a1..495495d1d43 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinChangeSignatureHandler.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinChangeSignatureHandler.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.changeSignature @@ -49,10 +38,9 @@ import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class KotlinChangeSignatureHandler : ChangeSignatureHandler { override fun findTargetMember(file: PsiFile, editor: Editor) = - file.findElementAt(editor.caretModel.offset)?.let { findTargetMember(it) } + file.findElementAt(editor.caretModel.offset)?.let { findTargetMember(it) } - override fun findTargetMember(element: PsiElement) = - findTargetForRefactoring(element) + override fun findTargetMember(element: PsiElement) = findTargetForRefactoring(element) override fun invoke(project: Project, editor: Editor, file: PsiFile, dataContext: DataContext) { editor.scrollingModel.scrollToCaret(ScrollType.MAKE_VISIBLE) @@ -72,22 +60,23 @@ class KotlinChangeSignatureHandler : ChangeSignatureHandler { invokeChangeSignature(element, element, project, editor) } - override fun getTargetNotFoundMessage() = - KotlinRefactoringBundle.message("error.wrong.caret.position.function.or.constructor.name") + override fun getTargetNotFoundMessage() = KotlinRefactoringBundle.message("error.wrong.caret.position.function.or.constructor.name") companion object { fun findTargetForRefactoring(element: PsiElement): PsiElement? { val elementParent = element.parent if ((elementParent is KtNamedFunction || elementParent is KtClass || elementParent is KtProperty) - && (elementParent as KtNamedDeclaration).nameIdentifier === element) return elementParent + && (elementParent as KtNamedDeclaration).nameIdentifier === element + ) return elementParent if (elementParent is KtParameter) { val primaryConstructor = PsiTreeUtil.getParentOfType(elementParent, KtPrimaryConstructor::class.java) if (elementParent.hasValOrVar() && (elementParent.nameIdentifier === element || elementParent.valOrVarKeyword === element) && primaryConstructor != null - && primaryConstructor.valueParameterList === elementParent.parent) return elementParent + && primaryConstructor.valueParameterList === elementParent.parent + ) return elementParent } if (elementParent is KtSecondaryConstructor && elementParent.getConstructorKeyword() === element) return elementParent @@ -100,10 +89,12 @@ class KotlinChangeSignatureHandler : ChangeSignatureHandler { return PsiTreeUtil.getParentOfType(typeParameterList, KtFunction::class.java, KtProperty::class.java, KtClass::class.java) } - val call: KtCallElement? = PsiTreeUtil.getParentOfType(element, - KtCallExpression::class.java, - KtSuperTypeCallEntry::class.java, - KtConstructorDelegationCall::class.java) + val call: KtCallElement? = PsiTreeUtil.getParentOfType( + element, + KtCallExpression::class.java, + KtSuperTypeCallEntry::class.java, + KtConstructorDelegationCall::class.java + ) val calleeExpr = call?.let { val callee = it.calleeExpression (callee as? KtConstructorCalleeExpression)?.constructorReferenceExpression ?: callee @@ -130,12 +121,14 @@ class KotlinChangeSignatureHandler : ChangeSignatureHandler { val declaration = DescriptorToSourceUtilsIde.getAnyDeclaration(project, callableDescriptor) if (declaration is PsiClass) { val message = RefactoringBundle.getCannotRefactorMessage( - RefactoringBundle.message("error.wrong.caret.position.method.or.class.name") + RefactoringBundle.message("error.wrong.caret.position.method.or.class.name") + ) + CommonRefactoringUtil.showErrorHint( + project, + editor, + message, + ChangeSignatureHandler.REFACTORING_NAME, "refactoring.changeSignature" ) - CommonRefactoringUtil.showErrorHint(project, - editor, - message, - ChangeSignatureHandler.REFACTORING_NAME, "refactoring.changeSignature") return } assert(declaration is PsiMethod) { "PsiMethod expected: $callableDescriptor" } @@ -145,7 +138,13 @@ class KotlinChangeSignatureHandler : ChangeSignatureHandler { if (callableDescriptor.isDynamic()) { if (editor != null) { - CodeInsightUtils.showErrorHint(project, editor, "Change signature is not applicable to dynamically invoked functions", "Change Signature", null) + CodeInsightUtils.showErrorHint( + project, + editor, + "Change signature is not applicable to dynamically invoked functions", + "Change Signature", + null + ) } return } @@ -173,13 +172,25 @@ class KotlinChangeSignatureHandler : ChangeSignatureHandler { is FunctionDescriptor -> { if (descriptor.valueParameters.any { it.varargElementType != null }) { val message = KotlinRefactoringBundle.message("error.cant.refactor.vararg.functions") - CommonRefactoringUtil.showErrorHint(project, editor, message, ChangeSignatureHandler.REFACTORING_NAME, HelpID.CHANGE_SIGNATURE) + CommonRefactoringUtil.showErrorHint( + project, + editor, + message, + ChangeSignatureHandler.REFACTORING_NAME, + HelpID.CHANGE_SIGNATURE + ) return null } if (descriptor.kind === SYNTHESIZED) { val message = KotlinRefactoringBundle.message("cannot.refactor.synthesized.function", descriptor.name) - CommonRefactoringUtil.showErrorHint(project, editor, message, ChangeSignatureHandler.REFACTORING_NAME, HelpID.CHANGE_SIGNATURE) + CommonRefactoringUtil.showErrorHint( + project, + editor, + message, + ChangeSignatureHandler.REFACTORING_NAME, + HelpID.CHANGE_SIGNATURE + ) return null } @@ -189,8 +200,15 @@ class KotlinChangeSignatureHandler : ChangeSignatureHandler { is PropertyDescriptor, is ValueParameterDescriptor -> descriptor as CallableDescriptor else -> { - val message = RefactoringBundle.getCannotRefactorMessage(KotlinRefactoringBundle.message("error.wrong.caret.position.function.or.constructor.name")) - CommonRefactoringUtil.showErrorHint(project, editor, message, ChangeSignatureHandler.REFACTORING_NAME, HelpID.CHANGE_SIGNATURE) + val message = + RefactoringBundle.getCannotRefactorMessage(KotlinRefactoringBundle.message("error.wrong.caret.position.function.or.constructor.name")) + CommonRefactoringUtil.showErrorHint( + project, + editor, + message, + ChangeSignatureHandler.REFACTORING_NAME, + HelpID.CHANGE_SIGNATURE + ) null } } 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 9f277fef59e..cfd96594ff7 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinChangeSignatureUsageProcessor.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinChangeSignatureUsageProcessor.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.changeSignature @@ -88,15 +77,17 @@ class KotlinChangeSignatureUsageProcessor : ChangeSignatureUsageProcessor { } private class DummyKotlinChangeInfo( - method: PsiElement, - methodDescriptor: KotlinMethodDescriptor - ) : KotlinChangeInfo(methodDescriptor = methodDescriptor, - name = "", - newReturnTypeInfo = KotlinTypeInfo(true), - newVisibility = Visibilities.DEFAULT_VISIBILITY, - parameterInfos = emptyList(), - receiver = null, - context = method) + method: PsiElement, + methodDescriptor: KotlinMethodDescriptor + ) : KotlinChangeInfo( + methodDescriptor = methodDescriptor, + name = "", + newReturnTypeInfo = KotlinTypeInfo(true), + newVisibility = Visibilities.DEFAULT_VISIBILITY, + parameterInfos = emptyList(), + receiver = null, + context = method + ) // It's here to prevent O(usage_count^2) performance private var initializedOriginalDescriptor: Boolean = false @@ -110,8 +101,7 @@ class KotlinChangeSignatureUsageProcessor : ChangeSignatureUsageProcessor { if (info is KotlinChangeInfoWrapper) { findAllMethodUsages(info.delegate!!, result) - } - else { + } else { findSAMUsages(info, result) //findConstructorDelegationUsages(info, result) findKotlinOverrides(info, result) @@ -133,16 +123,15 @@ class KotlinChangeSignatureUsageProcessor : ChangeSignatureUsageProcessor { val callee = functionUsageInfo.element ?: continue@loop - val propagationTarget = functionUsageInfo is CallerUsageInfo - || (functionUsageInfo is OverriderUsageInfo && !functionUsageInfo.isOriginalOverrider) + val propagationTarget = + functionUsageInfo is CallerUsageInfo || (functionUsageInfo is OverriderUsageInfo && !functionUsageInfo.isOriginalOverrider) for (reference in ReferencesSearch.search(callee, callee.useScope.restrictToKotlinSources())) { val callElement = reference.element.getParentOfTypeAndBranch { calleeExpression } ?: continue val usage = if (propagationTarget) { KotlinCallerCallUsage(callElement) - } - else { + } else { KotlinFunctionCallUsage(callElement, changeInfo.methodDescriptor.originalPrimaryCallable) } result.add(usage) @@ -167,44 +156,42 @@ class KotlinChangeSignatureUsageProcessor : ChangeSignatureUsageProcessor { val context = body.analyze() val newParameterNames = changeInfo.getNonReceiverParameters().mapTo(HashSet()) { it.name } body.accept( - object : KtTreeVisitorVoid() { - override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { - val currentName = expression.getReferencedName() - if (currentName !in newParameterNames) return + object : KtTreeVisitorVoid() { + override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { + val currentName = expression.getReferencedName() + if (currentName !in newParameterNames) return - val resolvedCall = expression.getResolvedCall(context) ?: return + val resolvedCall = expression.getResolvedCall(context) ?: return - if (resolvedCall.explicitReceiverKind != ExplicitReceiverKind.NO_EXPLICIT_RECEIVER) return + if (resolvedCall.explicitReceiverKind != ExplicitReceiverKind.NO_EXPLICIT_RECEIVER) return - val resultingDescriptor = resolvedCall.resultingDescriptor - if (resultingDescriptor !is VariableDescriptor) return + val resultingDescriptor = resolvedCall.resultingDescriptor + if (resultingDescriptor !is VariableDescriptor) return - // Do not report usages of duplicated parameter - if (resultingDescriptor is ValueParameterDescriptor - && resultingDescriptor.containingDeclaration === callerDescriptor) return + // Do not report usages of duplicated parameter + if (resultingDescriptor is ValueParameterDescriptor && resultingDescriptor.containingDeclaration === callerDescriptor) return - val callElement = resolvedCall.call.callElement + val callElement = resolvedCall.call.callElement - var receiver = resolvedCall.extensionReceiver - if (receiver !is ImplicitReceiver) { - receiver = resolvedCall.dispatchReceiver - } - - if (receiver is ImplicitReceiver) { - result.add(KotlinImplicitThisUsage(callElement, receiver.declarationDescriptor)) - } - else if (receiver == null) { - result.add( - object : UnresolvableCollisionUsageInfo(callElement, null) { - override fun getDescription(): String { - val signature = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.render(callerDescriptor) - return "There is already a variable '$currentName' in $signature. It will conflict with the new parameter." - } - } - ) - } + var receiver = resolvedCall.extensionReceiver + if (receiver !is ImplicitReceiver) { + receiver = resolvedCall.dispatchReceiver } - }) + + if (receiver is ImplicitReceiver) { + result.add(KotlinImplicitThisUsage(callElement, receiver.declarationDescriptor)) + } else if (receiver == null) { + result.add( + object : UnresolvableCollisionUsageInfo(callElement, null) { + override fun getDescription(): String { + val signature = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.render(callerDescriptor) + return "There is already a variable '$currentName' in $signature. It will conflict with the new parameter." + } + } + ) + } + } + }) } private fun findReferences(functionPsi: PsiElement): Set { @@ -227,9 +214,9 @@ class KotlinChangeSignatureUsageProcessor : ChangeSignatureUsageProcessor { } private fun findOneMethodUsages( - functionUsageInfo: KotlinCallableDefinitionUsage<*>, - changeInfo: KotlinChangeInfo, - result: MutableSet + functionUsageInfo: KotlinCallableDefinitionUsage<*>, + changeInfo: KotlinChangeInfo, + result: MutableSet ) { val isInherited = functionUsageInfo.isInherited @@ -285,9 +272,7 @@ class KotlinChangeSignatureUsageProcessor : ChangeSignatureUsageProcessor { val oldParam = oldParameters[parameterInfo.oldIndex] val oldParamName = oldParam.name - if (parameterInfo == newReceiverInfo || - (oldParamName != null && oldParamName != parameterInfo.name) || - isDataClass && i != parameterInfo.oldIndex) { + if (parameterInfo == newReceiverInfo || (oldParamName != null && oldParamName != parameterInfo.name) || isDataClass && i != parameterInfo.oldIndex) { for (reference in ReferencesSearch.search(oldParam, oldParam.useScope)) { val element = reference.element @@ -295,7 +280,8 @@ class KotlinChangeSignatureUsageProcessor : ChangeSignatureUsageProcessor { element is KtSimpleNameExpression && (element.parent as? KtCallExpression)?.calleeExpression == element && element.getReferencedName() != parameterInfo.name && - OperatorNameConventions.COMPONENT_REGEX.matches(element.getReferencedName())) { + OperatorNameConventions.COMPONENT_REGEX.matches(element.getReferencedName()) + ) { result.add(KotlinDataClassComponentUsage(element, "component${i + 1}")) } // Usages in named arguments of the calls usage will be changed when the function call is changed @@ -309,8 +295,8 @@ class KotlinChangeSignatureUsageProcessor : ChangeSignatureUsageProcessor { if (isDataClass && !changeInfo.hasAppendedParametersOnly()) { (functionPsi as KtPrimaryConstructor).valueParameters.firstOrNull()?.let { - ReferencesSearch.search(it).mapNotNullTo(result) { - val destructuringEntry = it.element as? KtDestructuringDeclarationEntry ?: return@mapNotNullTo null + ReferencesSearch.search(it).mapNotNullTo(result) { reference -> + val destructuringEntry = reference.element as? KtDestructuringDeclarationEntry ?: return@mapNotNullTo null KotlinComponentUsageInDestructuring(destructuringEntry) } } @@ -350,64 +336,64 @@ class KotlinChangeSignatureUsageProcessor : ChangeSignatureUsageProcessor { } private fun findOriginalReceiversUsages( - functionUsageInfo: KotlinCallableDefinitionUsage<*>, - result: MutableSet, - changeInfo: KotlinChangeInfo + functionUsageInfo: KotlinCallableDefinitionUsage<*>, + result: MutableSet, + changeInfo: KotlinChangeInfo ) { val originalReceiverInfo = changeInfo.methodDescriptor.receiver val callableDescriptor = functionUsageInfo.originalCallableDescriptor processInternalReferences( - functionUsageInfo, - object : KtTreeVisitor() { - private fun processExplicitThis( - expression: KtSimpleNameExpression, - receiverDescriptor: ReceiverParameterDescriptor) { - if (originalReceiverInfo != null && !changeInfo.hasParameter(originalReceiverInfo)) return - if (expression.parent !is KtThisExpression) return + functionUsageInfo, + object : KtTreeVisitor() { + private fun processExplicitThis( + expression: KtSimpleNameExpression, + receiverDescriptor: ReceiverParameterDescriptor + ) { + if (originalReceiverInfo != null && !changeInfo.hasParameter(originalReceiverInfo)) return + if (expression.parent !is KtThisExpression) return - if (receiverDescriptor === callableDescriptor.extensionReceiverParameter) { - assert(originalReceiverInfo != null) { "No original receiver info provided: " + functionUsageInfo.declaration.text } - result.add(KotlinParameterUsage(expression, originalReceiverInfo!!, functionUsageInfo)) - } - else { - val targetDescriptor = receiverDescriptor.type.constructor.declarationDescriptor - assert(targetDescriptor != null) { "Receiver type has no descriptor: " + functionUsageInfo.declaration.text } - result.add(KotlinNonQualifiedOuterThisUsage(expression.parent as KtThisExpression, targetDescriptor!!)) - } + if (receiverDescriptor === callableDescriptor.extensionReceiverParameter) { + assert(originalReceiverInfo != null) { "No original receiver info provided: " + functionUsageInfo.declaration.text } + result.add(KotlinParameterUsage(expression, originalReceiverInfo!!, functionUsageInfo)) + } else { + val targetDescriptor = receiverDescriptor.type.constructor.declarationDescriptor + assert(targetDescriptor != null) { "Receiver type has no descriptor: " + functionUsageInfo.declaration.text } + result.add(KotlinNonQualifiedOuterThisUsage(expression.parent as KtThisExpression, targetDescriptor!!)) } + } - private fun processImplicitThis( - callElement: KtElement, - implicitReceiver: ImplicitReceiver) { - val targetDescriptor = implicitReceiver.declarationDescriptor - if (compareDescriptors(callElement.project, targetDescriptor, callableDescriptor)) { - assert(originalReceiverInfo != null) { "No original receiver info provided: " + functionUsageInfo.declaration.text } - if (originalReceiverInfo in changeInfo.getNonReceiverParameters()) { - result.add(KotlinImplicitThisToParameterUsage(callElement, originalReceiverInfo!!, functionUsageInfo)) - } - } - else { - result.add(KotlinImplicitThisUsage(callElement, targetDescriptor)) + private fun processImplicitThis( + callElement: KtElement, + implicitReceiver: ImplicitReceiver + ) { + val targetDescriptor = implicitReceiver.declarationDescriptor + if (compareDescriptors(callElement.project, targetDescriptor, callableDescriptor)) { + assert(originalReceiverInfo != null) { "No original receiver info provided: " + functionUsageInfo.declaration.text } + if (originalReceiverInfo in changeInfo.getNonReceiverParameters()) { + result.add(KotlinImplicitThisToParameterUsage(callElement, originalReceiverInfo!!, functionUsageInfo)) } + } else { + result.add(KotlinImplicitThisUsage(callElement, targetDescriptor)) } + } - override fun visitSimpleNameExpression(expression: KtSimpleNameExpression, context: BindingContext): Void? { - val resolvedCall = expression.getResolvedCall(context) ?: return null - - val resultingDescriptor = resolvedCall.resultingDescriptor - if (resultingDescriptor is ReceiverParameterDescriptor) { - processExplicitThis(expression, resultingDescriptor) - return null - } - - val receiverValue = resolvedCall.extensionReceiver ?: resolvedCall.dispatchReceiver - if (receiverValue is ImplicitReceiver) { - processImplicitThis(resolvedCall.call.callElement, receiverValue) - } + override fun visitSimpleNameExpression(expression: KtSimpleNameExpression, context: BindingContext): Void? { + val resolvedCall = expression.getResolvedCall(context) ?: return null + val resultingDescriptor = resolvedCall.resultingDescriptor + if (resultingDescriptor is ReceiverParameterDescriptor) { + processExplicitThis(expression, resultingDescriptor) return null } - }) + + val receiverValue = resolvedCall.extensionReceiver ?: resolvedCall.dispatchReceiver + if (receiverValue is ImplicitReceiver) { + processImplicitThis(resolvedCall.call.callElement, receiverValue) + } + + return null + } + }) } private fun findSAMUsages(changeInfo: ChangeInfo, result: MutableSet) { @@ -480,11 +466,12 @@ class KotlinChangeSignatureUsageProcessor : ChangeSignatureUsageProcessor { } private fun findDeferredUsagesOfParameters( - changeInfo: ChangeInfo, - result: MutableSet, - function: KtNamedFunction, - functionDescriptor: FunctionDescriptor, - baseFunctionInfo: KotlinCallableDefinitionUsage) { + changeInfo: ChangeInfo, + result: MutableSet, + function: KtNamedFunction, + functionDescriptor: FunctionDescriptor, + baseFunctionInfo: KotlinCallableDefinitionUsage + ) { val functionInfoForParameters = KotlinCallableDefinitionUsage(function, functionDescriptor, baseFunctionInfo, null) val oldParameters = function.valueParameters val parameters = changeInfo.newParameters @@ -502,16 +489,18 @@ class KotlinChangeSignatureUsageProcessor : ChangeSignatureUsageProcessor { if (!((element is KtSimpleNameExpression || element is KDocName) && element.parent !is KtValueArgumentName)) continue result.add( - object : JavaMethodDeferredKotlinUsage(element as KtElement) { - override fun resolve(javaMethodChangeInfo: KotlinChangeInfo): JavaMethodKotlinUsageWithDelegate { - return object : JavaMethodKotlinUsageWithDelegate(element as KtElement, javaMethodChangeInfo) { - override val delegateUsage: KotlinUsageInfo - get() = KotlinParameterUsage(element as KtElement, - this.javaMethodChangeInfo.newParameters[paramIndex], - functionInfoForParameters) - } + object : JavaMethodDeferredKotlinUsage(element as KtElement) { + override fun resolve(javaMethodChangeInfo: KotlinChangeInfo): JavaMethodKotlinUsageWithDelegate { + return object : JavaMethodKotlinUsageWithDelegate(element as KtElement, javaMethodChangeInfo) { + override val delegateUsage: KotlinUsageInfo + get() = KotlinParameterUsage( + element as KtElement, + this.javaMethodChangeInfo.newParameters[paramIndex], + functionInfoForParameters + ) } } + } ) } } @@ -571,7 +560,10 @@ class KotlinChangeSignatureUsageProcessor : ChangeSignatureUsageProcessor { val candidateTypes = listOfNotNull(conflict.extensionReceiverParameter?.type) + conflict.valueParameters.map { it.type } if (candidateTypes == newTypes) { - result.putValue(conflictElement, "Function already exists: '" + DescriptorRenderer.SHORT_NAMES_IN_TYPES.render(conflict) + "'") + result.putValue( + conflictElement, + "Function already exists: '" + DescriptorRenderer.SHORT_NAMES_IN_TYPES.render(conflict) + "'" + ) break } } @@ -594,8 +586,7 @@ class KotlinChangeSignatureUsageProcessor : ChangeSignatureUsageProcessor { break } } - } - else if (function is KtFunction) { + } else if (function is KtFunction) { for (variable in parametersScope.getContributedVariables(Name.identifier(parameterName), NoLookupLocation.FROM_IDE)) { if (variable is ValueParameterDescriptor) continue val conflictElement = DescriptorToSourceUtils.descriptorToDeclaration(variable) @@ -624,10 +615,11 @@ class KotlinChangeSignatureUsageProcessor : ChangeSignatureUsageProcessor { } private fun findParameterDuplicationInCaller( - result: MultiMap, - changeInfo: KotlinChangeInfo, - caller: KtNamedDeclaration, - callerDescriptor: DeclarationDescriptor) { + result: MultiMap, + changeInfo: KotlinChangeInfo, + caller: KtNamedDeclaration, + callerDescriptor: DeclarationDescriptor + ) { val valueParameters = caller.getValueParameters() val existingParameters = valueParameters.associateBy { it.name } val signature = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.render(callerDescriptor) @@ -642,10 +634,11 @@ class KotlinChangeSignatureUsageProcessor : ChangeSignatureUsageProcessor { } private fun findThisLabelConflicts( - refUsages: Ref>, - result: MultiMap, - changeInfo: KotlinChangeInfo, - callable: KtCallableDeclaration) { + refUsages: Ref>, + result: MultiMap, + changeInfo: KotlinChangeInfo, + callable: KtCallableDeclaration + ) { val psiFactory = KtPsiFactory(callable.project) for (usageInfo in refUsages.get()) { if (usageInfo !is KotlinParameterUsage) continue @@ -666,8 +659,9 @@ class KotlinChangeSignatureUsageProcessor : ChangeSignatureUsageProcessor { val labelExpr = newExpr.getTargetLabel() if (labelExpr != null && newContext.get(BindingContext.AMBIGUOUS_LABEL_TARGET, labelExpr) != null) { result.putValue( - originalExpr, - "Parameter reference can't be safely replaced with " + newExprText + " since " + labelExpr.text + " is ambiguous in this context") + originalExpr, + "Parameter reference can't be safely replaced with " + newExprText + " since " + labelExpr.text + " is ambiguous in this context" + ) continue } @@ -675,16 +669,17 @@ class KotlinChangeSignatureUsageProcessor : ChangeSignatureUsageProcessor { val thisTargetPsi = (thisTarget as? DeclarationDescriptorWithSource)?.source?.getPsi() if (thisTargetPsi != null && callable.isAncestor(thisTargetPsi, true)) { result.putValue( - originalExpr, - "Parameter reference can't be safely replaced with $newExprText since target function can't be referenced in this context") + originalExpr, + "Parameter reference can't be safely replaced with $newExprText since target function can't be referenced in this context" + ) } } } private fun findInternalExplicitReceiverConflicts( - usages: Array, - result: MultiMap, - originalReceiverInfo: KotlinParameterInfo? + usages: Array, + result: MultiMap, + originalReceiverInfo: KotlinParameterInfo? ) { if (originalReceiverInfo != null) return @@ -700,15 +695,16 @@ class KotlinChangeSignatureUsageProcessor : ChangeSignatureUsageProcessor { else -> continue@loop } - val message = "Explicit receiver is already present in call element: " + CommonRefactoringUtil.htmlEmphasize(elementToReport.text) + val message = + "Explicit receiver is already present in call element: " + CommonRefactoringUtil.htmlEmphasize(elementToReport.text) result.putValue(callElement, message) } } private fun findReceiverToParameterInSafeCallsConflicts( - usages: Array, - result: MultiMap, - changeInfo: KotlinChangeInfo + usages: Array, + result: MultiMap, + changeInfo: KotlinChangeInfo ) { val originalReceiverInfo = changeInfo.methodDescriptor.receiver if (originalReceiverInfo == null || originalReceiverInfo !in changeInfo.getNonReceiverParameters()) return @@ -720,17 +716,18 @@ class KotlinChangeSignatureUsageProcessor : ChangeSignatureUsageProcessor { val qualifiedExpression = callElement.getQualifiedExpressionForSelector() if (qualifiedExpression is KtSafeQualifiedExpression) { result.putValue( - callElement, - "Receiver can't be safely transformed to value argument: ${CommonRefactoringUtil.htmlEmphasize(qualifiedExpression.text)}" + callElement, + "Receiver can't be safely transformed to value argument: ${CommonRefactoringUtil.htmlEmphasize(qualifiedExpression.text)}" ) } } } private fun findReceiverIntroducingConflicts( - result: MultiMap, - callable: PsiElement, - newReceiverInfo: KotlinParameterInfo?) { + result: MultiMap, + callable: PsiElement, + newReceiverInfo: KotlinParameterInfo? + ) { if (newReceiverInfo != null && (callable is KtNamedFunction) && callable.bodyExpression != null) { val originalContext = callable.analyzeWithContent() @@ -752,9 +749,8 @@ class KotlinChangeSignatureUsageProcessor : ChangeSignatureUsageProcessor { val originalOffset = callable.bodyExpression!!.textOffset val newBody = functionWithReceiver.bodyExpression ?: return for (originalRef in noReceiverRefs) { - val newRef = newBody - .findElementAt(originalRef.textOffset - originalOffset) - ?.getNonStrictParentOfType() + val newRef = + newBody.findElementAt(originalRef.textOffset - originalOffset)?.getNonStrictParentOfType() val newResolvedCall = newRef.getResolvedCall(newContext) if (newResolvedCall == null || newResolvedCall.extensionReceiver != null || newResolvedCall.dispatchReceiver != null) { val descriptor = originalRef.getResolvedCall(originalContext)!!.candidateDescriptor @@ -772,9 +768,9 @@ class KotlinChangeSignatureUsageProcessor : ChangeSignatureUsageProcessor { } private fun createReplacementUsage( - originalUsageInfo: UsageInfo, - javaMethodChangeInfo: KotlinChangeInfo, - allUsages: Array + originalUsageInfo: UsageInfo, + javaMethodChangeInfo: KotlinChangeInfo, + allUsages: Array ): UsageInfo? { if (originalUsageInfo is JavaMethodDeferredKotlinUsage<*>) return originalUsageInfo.resolve(javaMethodChangeInfo) @@ -814,8 +810,7 @@ class KotlinChangeSignatureUsageProcessor : ChangeSignatureUsageProcessor { if (notNullAnnotation != null && nullableAnnotation == null && element is PsiMethod) return val annotationQualifiedName = annotation?.qualifiedName - if (annotationQualifiedName != null - && javaPsiFacade.findClass(annotationQualifiedName, element.resolveScope) == null) return + if (annotationQualifiedName != null && javaPsiFacade.findClass(annotationQualifiedName, element.resolveScope) == null) return notNullAnnotation?.delete() nullableAnnotation?.delete() @@ -849,7 +844,12 @@ class KotlinChangeSignatureUsageProcessor : ChangeSignatureUsageProcessor { return null } - override fun processUsage(changeInfo: ChangeInfo, usageInfo: UsageInfo, beforeMethodChange: Boolean, usages: Array): Boolean { + override fun processUsage( + changeInfo: ChangeInfo, + usageInfo: UsageInfo, + beforeMethodChange: Boolean, + usages: Array + ): Boolean { val method = changeInfo.method val isJavaMethodUsage = isJavaMethodUsage(usageInfo) @@ -894,10 +894,12 @@ class KotlinChangeSignatureUsageProcessor : ChangeSignatureUsageProcessor { val baseDeclaration = method.unwrapped ?: return false val baseDeclarationDescriptor = method.getJavaOrKotlinMemberDescriptor()?.createDeepCopy() as CallableDescriptor? - ?: return false - descriptorWrapper.originalJavaMethodDescriptor = KotlinChangeSignatureData(baseDeclarationDescriptor, - baseDeclaration, - listOf(baseDeclarationDescriptor)) + ?: return false + descriptorWrapper.originalJavaMethodDescriptor = KotlinChangeSignatureData( + baseDeclarationDescriptor, + baseDeclaration, + listOf(baseDeclarationDescriptor) + ) // This change info is used as a placeholder before primary method update // It gets replaced with real change info afterwards @@ -947,7 +949,11 @@ class KotlinChangeSignatureUsageProcessor : ChangeSignatureUsageProcessor { } @Suppress("UNCHECKED_CAST") - return (usageInfo as? KotlinUsageInfo)?.processUsage((changeInfo as KotlinChangeInfoWrapper).delegate!!, element, usages) ?: false + return (usageInfo as? KotlinUsageInfo)?.processUsage( + (changeInfo as KotlinChangeInfoWrapper).delegate!!, + element, + usages + ) ?: false } override fun processPrimaryMethod(changeInfo: ChangeInfo): Boolean { @@ -970,8 +976,7 @@ class KotlinChangeSignatureUsageProcessor : ChangeSignatureUsageProcessor { changeInfo.updateMethod(dummyMethod) JavaChangeSignatureUsageProcessor().processPrimaryMethod(changeInfo) changeInfo.toJetChangeInfo(methodDescriptor, resolutionFacade) - } - finally { + } finally { changeInfo.updateMethod(method) } } @@ -990,8 +995,9 @@ class KotlinChangeSignatureUsageProcessor : ChangeSignatureUsageProcessor { override fun setupDefaultValues(changeInfo: ChangeInfo, refUsages: Ref>, project: Project) = true override fun registerConflictResolvers( - snapshots: List, - resolveSnapshotProvider: ResolveSnapshotProvider, - usages: Array, changeInfo: ChangeInfo) { + snapshots: List, + resolveSnapshotProvider: ResolveSnapshotProvider, + usages: Array, changeInfo: ChangeInfo + ) { } } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinMethodDescriptor.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinMethodDescriptor.kt index 034df5657df..33c39eac192 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinMethodDescriptor.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinMethodDescriptor.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2014 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.changeSignature @@ -33,14 +22,15 @@ interface KotlinMethodDescriptor : MethodDescriptor Kind.FUNCTION - descriptor.isPrimary -> Kind.PRIMARY_CONSTRUCTOR - else -> Kind.SECONDARY_CONSTRUCTOR + val kind: Kind + get() { + val descriptor = baseDescriptor + return when { + descriptor !is ConstructorDescriptor -> Kind.FUNCTION + descriptor.isPrimary -> Kind.PRIMARY_CONSTRUCTOR + else -> Kind.SECONDARY_CONSTRUCTOR + } } - } val original: KotlinMethodDescriptor @@ -58,8 +48,8 @@ val KotlinMethodDescriptor.returnTypeInfo: KotlinTypeInfo get() { val type = baseDescriptor.returnType val text = (baseDeclaration as? KtCallableDeclaration)?.typeReference?.text - ?: type?.let { IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderType(type) } - ?: "Unit" + ?: type?.let { IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderType(type) } + ?: "Unit" return KotlinTypeInfo(true, type, text) } @@ -67,6 +57,6 @@ val KotlinMethodDescriptor.receiverTypeInfo: KotlinTypeInfo get() { val type = baseDescriptor.extensionReceiverParameter?.type val text = (baseDeclaration as? KtCallableDeclaration)?.receiverTypeReference?.text - ?: type?.let { IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderType(type) } + ?: type?.let { IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderType(type) } return KotlinTypeInfo(false, type, text) } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinMutableMethodDescriptor.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinMutableMethodDescriptor.kt index b7faf7d6442..1d3bb5d8eb0 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinMutableMethodDescriptor.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinMutableMethodDescriptor.kt @@ -1,24 +1,13 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.changeSignature import org.jetbrains.kotlin.descriptors.Visibility -class KotlinMutableMethodDescriptor(override val original: KotlinMethodDescriptor): KotlinMethodDescriptor by original { +class KotlinMutableMethodDescriptor(override val original: KotlinMethodDescriptor) : KotlinMethodDescriptor by original { private val parameters: MutableList = original.parameters override var receiver: KotlinParameterInfo? = original.receiver @@ -32,7 +21,7 @@ class KotlinMutableMethodDescriptor(override val original: KotlinMethodDescripto fun addParameter(parameter: KotlinParameterInfo) { parameters.add(parameter) } - + fun addParameter(index: Int, parameter: KotlinParameterInfo) { parameters.add(index, parameter) } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinParameterInfo.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinParameterInfo.kt index ffc3570949c..c392a3f5ba5 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinParameterInfo.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinParameterInfo.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.changeSignature @@ -39,16 +28,16 @@ import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver import org.jetbrains.kotlin.types.isError import java.util.* -class KotlinParameterInfo @JvmOverloads constructor ( - val callableDescriptor: CallableDescriptor, - val originalIndex: Int = -1, - private var name: String, - val originalTypeInfo: KotlinTypeInfo = KotlinTypeInfo(false), - var defaultValueForParameter: KtExpression? = null, - var defaultValueForCall: KtExpression? = null, - var valOrVar: KotlinValVar = KotlinValVar.None, - val modifierList: KtModifierList? = null -): ParameterInfo { +class KotlinParameterInfo @JvmOverloads constructor( + val callableDescriptor: CallableDescriptor, + val originalIndex: Int = -1, + private var name: String, + val originalTypeInfo: KotlinTypeInfo = KotlinTypeInfo(false), + var defaultValueForParameter: KtExpression? = null, + var defaultValueForCall: KtExpression? = null, + var valOrVar: KotlinValVar = KotlinValVar.None, + val modifierList: KtModifierList? = null +) : ParameterInfo { var currentTypeInfo: KotlinTypeInfo = originalTypeInfo val defaultValueParameterReferences: Map @@ -56,75 +45,81 @@ class KotlinParameterInfo @JvmOverloads constructor ( init { val file = defaultValueForCall?.containingFile as? KtFile defaultValueParameterReferences = - if (defaultValueForCall != null && file != null && (file.isPhysical || file.analysisContext != null)) { - val project = file.project - val map = LinkedHashMap() + if (defaultValueForCall != null && file != null && (file.isPhysical || file.analysisContext != null)) { + val project = file.project + val map = LinkedHashMap() - defaultValueForCall!!.accept( - object : KtTreeVisitorVoid() { - private fun selfParameterOrNull(parameter: DeclarationDescriptor?): ValueParameterDescriptor? { - return if (parameter is ValueParameterDescriptor && - compareDescriptors(project, parameter.containingDeclaration, callableDescriptor)) { - parameter - } else null - } + defaultValueForCall!!.accept( + object : KtTreeVisitorVoid() { + private fun selfParameterOrNull(parameter: DeclarationDescriptor?): ValueParameterDescriptor? { + return if (parameter is ValueParameterDescriptor && + compareDescriptors(project, parameter.containingDeclaration, callableDescriptor) + ) { + parameter + } else null + } - private fun selfReceiverOrNull(receiverDescriptor: DeclarationDescriptor?): DeclarationDescriptor? { - if (compareDescriptors(project, - receiverDescriptor, - callableDescriptor.extensionReceiverParameter?.containingDeclaration)) { - return receiverDescriptor - } - if (compareDescriptors(project, - receiverDescriptor, - callableDescriptor.dispatchReceiverParameter?.containingDeclaration)) { - return receiverDescriptor - } - return null - } - - private fun selfReceiverOrNull(receiver: ImplicitReceiver?): DeclarationDescriptor? { - return selfReceiverOrNull(receiver?.declarationDescriptor) - } - - private fun getRelevantDescriptor( - expression: KtSimpleNameExpression, - ref: KtReference - ): DeclarationDescriptor? { - val context = expression.analyze(BodyResolveMode.PARTIAL) - - val descriptor = ref.resolveToDescriptors(context).singleOrNull() - if (descriptor is ValueParameterDescriptor) return selfParameterOrNull(descriptor) - - if (descriptor is PropertyDescriptor && callableDescriptor is ConstructorDescriptor) { - val parameter = DescriptorToSourceUtils.getSourceFromDescriptor(descriptor) as? KtParameter - return parameter?.let { selfParameterOrNull(context[BindingContext.VALUE_PARAMETER, it]) } - } - - val resolvedCall = expression.getResolvedCall(context) ?: return null - (resolvedCall.resultingDescriptor as? ReceiverParameterDescriptor)?.let { - return if (selfReceiverOrNull(it.containingDeclaration) != null) it else null - } - - selfReceiverOrNull(resolvedCall.extensionReceiver as? ImplicitReceiver)?.let { return it } - selfReceiverOrNull(resolvedCall.dispatchReceiver as? ImplicitReceiver)?.let { return it } - - return null - } - - override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { - val ref = expression.mainReference - val descriptor = getRelevantDescriptor(expression, ref) ?: return - map[ref] = descriptor - } + private fun selfReceiverOrNull(receiverDescriptor: DeclarationDescriptor?): DeclarationDescriptor? { + if (compareDescriptors( + project, + receiverDescriptor, + callableDescriptor.extensionReceiverParameter?.containingDeclaration + ) + ) { + return receiverDescriptor } - ) + if (compareDescriptors( + project, + receiverDescriptor, + callableDescriptor.dispatchReceiverParameter?.containingDeclaration + ) + ) { + return receiverDescriptor + } + return null + } - map - } - else { - emptyMap() - } + private fun selfReceiverOrNull(receiver: ImplicitReceiver?): DeclarationDescriptor? { + return selfReceiverOrNull(receiver?.declarationDescriptor) + } + + private fun getRelevantDescriptor( + expression: KtSimpleNameExpression, + ref: KtReference + ): DeclarationDescriptor? { + val context = expression.analyze(BodyResolveMode.PARTIAL) + + val descriptor = ref.resolveToDescriptors(context).singleOrNull() + if (descriptor is ValueParameterDescriptor) return selfParameterOrNull(descriptor) + + if (descriptor is PropertyDescriptor && callableDescriptor is ConstructorDescriptor) { + val parameter = DescriptorToSourceUtils.getSourceFromDescriptor(descriptor) as? KtParameter + return parameter?.let { selfParameterOrNull(context[BindingContext.VALUE_PARAMETER, it]) } + } + + val resolvedCall = expression.getResolvedCall(context) ?: return null + (resolvedCall.resultingDescriptor as? ReceiverParameterDescriptor)?.let { + return if (selfReceiverOrNull(it.containingDeclaration) != null) it else null + } + + selfReceiverOrNull(resolvedCall.extensionReceiver as? ImplicitReceiver)?.let { return it } + selfReceiverOrNull(resolvedCall.dispatchReceiver as? ImplicitReceiver)?.let { return it } + + return null + } + + override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { + val ref = expression.mainReference + val descriptor = getRelevantDescriptor(expression, ref) ?: return + map[ref] = descriptor + } + } + ) + + map + } else { + emptyMap() + } } override fun getOldIndex(): Int = originalIndex @@ -171,7 +166,8 @@ class KotlinParameterInfo @JvmOverloads constructor ( val inheritedParameterDescriptors = inheritedFunctionDescriptor.valueParameters if (originalIndex < 0 || originalIndex >= baseFunctionDescriptor.valueParameters.size - || originalIndex >= inheritedParameterDescriptors.size) return name + || originalIndex >= inheritedParameterDescriptors.size + ) return name val inheritedParamName = inheritedParameterDescriptors[originalIndex].name.asString() val oldParamName = baseFunctionDescriptor.valueParameters[originalIndex].name.asString() @@ -225,7 +221,7 @@ class KotlinParameterInfo @JvmOverloads constructor ( fun getDeclarationSignature(parameterIndex: Int, inheritedCallable: KotlinCallableDefinitionUsage<*>): KtParameter { val originalParameter = getOriginalParameter(inheritedCallable) - ?: return buildNewParameter(inheritedCallable, parameterIndex) + ?: return buildNewParameter(inheritedCallable, parameterIndex) val psiFactory = KtPsiFactory(originalParameter) val newParameter = originalParameter.copied() diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinUsagesViewDescriptor.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinUsagesViewDescriptor.kt index ce935cea77f..fdc9cfed674 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinUsagesViewDescriptor.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinUsagesViewDescriptor.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.changeSignature @@ -27,8 +16,8 @@ class KotlinUsagesViewDescriptor(private val element: PsiElement, private val el override fun getProcessedElementsHeader(): String = elementsHeader override fun getCodeReferencesText(usagesCount: Int, filesCount: Int): String = - RefactoringBundle.message("references.to.be.changed", UsageViewBundle.getReferencesString(usagesCount, filesCount)) + RefactoringBundle.message("references.to.be.changed", UsageViewBundle.getReferencesString(usagesCount, filesCount)) override fun getCommentReferencesText(usagesCount: Int, filesCount: Int): String? = - RefactoringBundle.message("comments.elements.header", UsageViewBundle.getOccurencesString(usagesCount, filesCount)) + RefactoringBundle.message("comments.elements.header", UsageViewBundle.getOccurencesString(usagesCount, filesCount)) } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinValVar.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinValVar.kt index 183d8e62ae3..c62b30049fc 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinValVar.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinValVar.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.changeSignature @@ -28,7 +17,7 @@ enum class KotlinValVar(val keywordName: String) { Val("val") { override fun createKeyword(factory: KtPsiFactory) = factory.createValKeyword() }, - Var("var"){ + Var("var") { override fun createKeyword(factory: KtPsiFactory) = factory.createVarKeyword() }; @@ -54,8 +43,7 @@ fun KtParameter.setValOrVar(valOrVar: KotlinValVar): PsiElement? { return if (newKeyword == null) { currentKeyword.delete() null - } - else { + } else { currentKeyword.replace(newKeyword) } } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/changeSignatureUtils.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/changeSignatureUtils.kt index 9f4efdcbcf2..1e3b87c888f 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/changeSignatureUtils.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/changeSignatureUtils.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.changeSignature @@ -44,29 +33,24 @@ import org.jetbrains.kotlin.types.* import org.jetbrains.kotlin.types.substitutions.getCallableSubstitutor import org.jetbrains.kotlin.types.typeUtil.asTypeProjection -fun KtNamedDeclaration.getDeclarationBody(): KtElement? { - return when { - this is KtClassOrObject -> getSuperTypeList() - this is KtPrimaryConstructor -> getContainingClassOrObject().getSuperTypeList() - this is KtSecondaryConstructor -> getDelegationCall() - this is KtNamedFunction -> bodyExpression - else -> null - } +fun KtNamedDeclaration.getDeclarationBody(): KtElement? = when (this) { + is KtClassOrObject -> getSuperTypeList() + is KtPrimaryConstructor -> getContainingClassOrObject().getSuperTypeList() + is KtSecondaryConstructor -> getDelegationCall() + is KtNamedFunction -> bodyExpression + else -> null } fun PsiElement.isCaller(allUsages: Array): Boolean { val primaryConstructor = (this as? KtClass)?.primaryConstructor val elementsToSearch = if (primaryConstructor != null) listOf(primaryConstructor, this) else listOf(this) return allUsages - .asSequence() - .filter { - val usage = (it as? JavaMethodKotlinUsageWithDelegate<*>)?.delegateUsage ?: it - usage is KotlinCallerUsage - || usage is DeferredJavaMethodKotlinCallerUsage - || usage is CallerUsageInfo - || (usage is OverriderUsageInfo && !usage.isOriginalOverrider) - } - .any { it.element in elementsToSearch } + .asSequence() + .filter { + val usage = (it as? JavaMethodKotlinUsageWithDelegate<*>)?.delegateUsage ?: it + usage is KotlinCallerUsage || usage is DeferredJavaMethodKotlinCallerUsage || usage is CallerUsageInfo || (usage is OverriderUsageInfo && !usage.isOriginalOverrider) + } + .any { it.element in elementsToSearch } } fun KtElement.isInsideOfCallerBody(allUsages: Array): Boolean { @@ -78,8 +62,8 @@ fun KtElement.isInsideOfCallerBody(allUsages: Array): Boolean { } fun getCallableSubstitutor( - baseFunction: KotlinCallableDefinitionUsage<*>, - derivedCallable: KotlinCallableDefinitionUsage<*> + baseFunction: KotlinCallableDefinitionUsage<*>, + derivedCallable: KotlinCallableDefinitionUsage<*> ): TypeSubstitutor? { val currentBaseFunction = baseFunction.currentCallableDescriptor ?: return null val currentDerivedFunction = derivedCallable.currentCallableDescriptor ?: return null @@ -88,21 +72,24 @@ fun getCallableSubstitutor( fun KotlinType.renderTypeWithSubstitution(substitutor: TypeSubstitutor?, defaultText: String, inArgumentPosition: Boolean): String { val newType = substitutor?.substitute(this, Variance.INVARIANT) ?: return defaultText - val renderer = if (inArgumentPosition) IdeDescriptorRenderers.SOURCE_CODE_NOT_NULL_TYPE_APPROXIMATION else IdeDescriptorRenderers.SOURCE_CODE + val renderer = + if (inArgumentPosition) IdeDescriptorRenderers.SOURCE_CODE_NOT_NULL_TYPE_APPROXIMATION else IdeDescriptorRenderers.SOURCE_CODE return renderer.renderType(newType) } // This method is used to create full copies of functions (including copies of all types) // It's needed to prevent accesses to PSI (e.g. using LazyJavaClassifierType properties) when Change signature invalidates it // See KotlinChangeSignatureTest.testSAMChangeMethodReturnType -fun DeclarationDescriptor.createDeepCopy() = (this as? JavaMethodDescriptor)?.substitute(TypeSubstitutor.create(ForceTypeCopySubstitution)) ?: this +fun DeclarationDescriptor.createDeepCopy() = + (this as? JavaMethodDescriptor)?.substitute(TypeSubstitutor.create(ForceTypeCopySubstitution)) ?: this private object ForceTypeCopySubstitution : TypeSubstitution() { override fun get(key: KotlinType) = - with(key) { - if (isError) return@with asTypeProjection() - KotlinTypeFactory.simpleTypeWithNonTrivialMemberScope(annotations, constructor, arguments, isMarkedNullable, memberScope).asTypeProjection() - } + with(key) { + if (isError) return@with asTypeProjection() + KotlinTypeFactory.simpleTypeWithNonTrivialMemberScope(annotations, constructor, arguments, isMarkedNullable, memberScope) + .asTypeProjection() + } override fun isEmpty() = false } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/ui/KotlinCallerChooser.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/ui/KotlinCallerChooser.kt index 12a6893ea0e..a13ed20661a 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/ui/KotlinCallerChooser.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/ui/KotlinCallerChooser.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.changeSignature.ui @@ -48,33 +37,29 @@ import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext import java.util.* class KotlinCallerChooser( - declaration: PsiElement, - project: Project, - title: String, - previousTree: Tree?, - callback: Consumer> -): CallerChooserBase(declaration, project, title, previousTree, "dummy." + KotlinFileType.EXTENSION, callback) { + declaration: PsiElement, + project: Project, + title: String, + previousTree: Tree?, + callback: Consumer> +) : CallerChooserBase(declaration, project, title, previousTree, "dummy." + KotlinFileType.EXTENSION, callback) { override fun createTreeNodeFor(method: PsiElement?, called: HashSet?, cancelCallback: Runnable?) = KotlinMethodNode(method, called ?: HashSet(), myProject, cancelCallback ?: Runnable {}) - override fun findDeepestSuperMethods(method: PsiElement) = - method.toLightMethods().singleOrNull()?.findDeepestSuperMethods() + override fun findDeepestSuperMethods(method: PsiElement) = method.toLightMethods().singleOrNull()?.findDeepestSuperMethods() - override fun getEmptyCallerText() = - "Caller text \nwith highlighted callee call would be shown here" + override fun getEmptyCallerText() = "Caller text \nwith highlighted callee call would be shown here" - override fun getEmptyCalleeText() = - "Callee text would be shown here" + override fun getEmptyCalleeText() = "Callee text would be shown here" } class KotlinMethodNode( - method: PsiElement?, - called: HashSet, - project: Project, - cancelCallback: Runnable -): MethodNodeBase(method?.namedUnwrappedElement ?: method, called, project, cancelCallback) { - override fun createNode(caller: PsiElement, called: HashSet) = - KotlinMethodNode(caller, called, myProject, myCancelCallback) + method: PsiElement?, + called: HashSet, + project: Project, + cancelCallback: Runnable +) : MethodNodeBase(method?.namedUnwrappedElement ?: method, called, project, cancelCallback) { + override fun createNode(caller: PsiElement, called: HashSet) = KotlinMethodNode(caller, called, myProject, myCancelCallback) override fun customizeRendererText(renderer: ColoredTreeCellRenderer) { val descriptor = when (myMethod) { @@ -84,14 +69,13 @@ class KotlinMethodNode( else -> throw AssertionError("Invalid declaration: ${myMethod.getElementTextWithContext()}") } val containerName = generateSequence(descriptor) { it.containingDeclaration } - .firstOrNull { it is ClassDescriptor } - ?.name + .firstOrNull { it is ClassDescriptor } + ?.name val renderedFunction = KotlinCallHierarchyNodeDescriptor.renderNamedFunction(descriptor) - val renderedFunctionWithContainer = - containerName?.let { - "${if (it.isSpecial) "[Anonymous]" else it.asString()}.$renderedFunction" - } ?: renderedFunction + val renderedFunctionWithContainer = containerName?.let { + "${if (it.isSpecial) "[Anonymous]" else it.asString()}.$renderedFunction" + } ?: renderedFunction val attributes = if (isEnabled) SimpleTextAttributes(SimpleTextAttributes.STYLE_PLAIN, UIUtil.getTreeForeground()) @@ -108,7 +92,7 @@ class KotlinMethodNode( val callers = LinkedHashSet() - val processor = object: CalleeReferenceProcessor(false) { + val processor = object : CalleeReferenceProcessor(false) { override fun onAccept(ref: PsiReference, element: PsiElement) { if ((element is KtFunction || element is KtClass || element is PsiMethod) && element !in myCalled) { callers.add(element) @@ -116,7 +100,7 @@ class KotlinMethodNode( } } val query = myMethod.getRepresentativeLightMethod()?.let { MethodReferencesSearch.search(it, it.useScope, true) } - ?: ReferencesSearch.search(myMethod, myMethod.useScope) + ?: ReferencesSearch.search(myMethod, myMethod.useScope) query.forEach { processor.process(it) } return callers.toList() } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/ui/KotlinChangePropertySignatureDialog.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/ui/KotlinChangePropertySignatureDialog.kt index 7b7535fbd62..f33d216433a 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/ui/KotlinChangePropertySignatureDialog.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/ui/KotlinChangePropertySignatureDialog.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.changeSignature.ui @@ -37,12 +26,12 @@ import javax.swing.JLabel import kotlin.properties.Delegates class KotlinChangePropertySignatureDialog( - project: Project, - private val methodDescriptor: KotlinMethodDescriptor, - private val commandName: String? -): RefactoringDialog(project, true) { + project: Project, + private val methodDescriptor: KotlinMethodDescriptor, + private val commandName: String? +) : RefactoringDialog(project, true) { private val visibilityCombo = JComboBox( - arrayOf(Visibilities.INTERNAL, Visibilities.PRIVATE, Visibilities.PROTECTED, Visibilities.PUBLIC) + arrayOf(Visibilities.INTERNAL, Visibilities.PRIVATE, Visibilities.PROTECTED, Visibilities.PUBLIC) ) private val nameField = EditorTextField(methodDescriptor.name) private var returnTypeField: EditorTextField by Delegates.notNull() @@ -80,8 +69,10 @@ class KotlinChangePropertySignatureDialog( addLabeledComponent("&Name: ", nameField) - val returnTypeCodeFragment = psiFactory.createTypeCodeFragment(methodDescriptor.returnTypeInfo.render(), - baseDeclaration) + val returnTypeCodeFragment = psiFactory.createTypeCodeFragment( + methodDescriptor.returnTypeInfo.render(), + baseDeclaration + ) returnTypeField = EditorTextField(documentManager.getDocument(returnTypeCodeFragment), myProject, KotlinFileType.INSTANCE) addLabeledComponent("&Type: ", returnTypeField) @@ -95,18 +86,23 @@ class KotlinChangePropertySignatureDialog( addComponent(receiverTypeCheckBox) this@KotlinChangePropertySignatureDialog.receiverTypeCheckBox = receiverTypeCheckBox - val receiverTypeCodeFragment = psiFactory.createTypeCodeFragment(methodDescriptor.receiverTypeInfo.render(), - methodDescriptor.baseDeclaration) - receiverTypeField = EditorTextField(documentManager.getDocument(receiverTypeCodeFragment), myProject, KotlinFileType.INSTANCE) + val receiverTypeCodeFragment = psiFactory.createTypeCodeFragment( + methodDescriptor.receiverTypeInfo.render(), + methodDescriptor.baseDeclaration + ) + receiverTypeField = + EditorTextField(documentManager.getDocument(receiverTypeCodeFragment), myProject, KotlinFileType.INSTANCE) receiverTypeLabel = JLabel("Receiver type: ") receiverTypeLabel.setDisplayedMnemonic('t') addLabeledComponent(receiverTypeLabel, receiverTypeField) if (methodDescriptor.receiver == null) { val receiverDefaultValueCodeFragment = psiFactory.createExpressionCodeFragment("", methodDescriptor.baseDeclaration) - receiverDefaultValueField = EditorTextField(documentManager.getDocument(receiverDefaultValueCodeFragment), - myProject, - KotlinFileType.INSTANCE) + receiverDefaultValueField = EditorTextField( + documentManager.getDocument(receiverDefaultValueCodeFragment), + myProject, + KotlinFileType.INSTANCE + ) receiverDefaultValueLabel = JLabel("Default receiver value: ") receiverDefaultValueLabel!!.setDisplayedMnemonic('D') addLabeledComponent(receiverDefaultValueLabel, receiverDefaultValueField!!) @@ -129,7 +125,7 @@ class KotlinChangePropertySignatureDialog( psiFactory.createSimpleName(nameField.text).validateElement("Invalid name") psiFactory.createType(returnTypeField.text).validateElement("Invalid return type") - if (receiverTypeCheckBox?.isSelected ?: false) { + if (receiverTypeCheckBox?.isSelected == true) { psiFactory.createType(receiverTypeField.text).validateElement("Invalid receiver type") } getDefaultReceiverValue()?.validateElement("Invalid default receiver value") @@ -138,28 +134,32 @@ class KotlinChangePropertySignatureDialog( override fun doAction() { val originalDescriptor = methodDescriptor.original - val receiver = if (receiverTypeCheckBox?.isSelected ?: false) { - originalDescriptor.receiver ?: KotlinParameterInfo(callableDescriptor = originalDescriptor.baseDescriptor, - name = "receiver", - defaultValueForCall = getDefaultReceiverValue()) + val receiver = if (receiverTypeCheckBox?.isSelected == true) { + originalDescriptor.receiver ?: KotlinParameterInfo( + callableDescriptor = originalDescriptor.baseDescriptor, + name = "receiver", + defaultValueForCall = getDefaultReceiverValue() + ) } else null receiver?.currentTypeInfo = KotlinTypeInfo(false, null, receiverTypeField.text) - val changeInfo = KotlinChangeInfo(originalDescriptor, - nameField.text, - KotlinTypeInfo(true, null, returnTypeField.text), - visibilityCombo.selectedItem as Visibility, - emptyList(), - receiver, - originalDescriptor.method) + val changeInfo = KotlinChangeInfo( + originalDescriptor, + nameField.text, + KotlinTypeInfo(true, null, returnTypeField.text), + visibilityCombo.selectedItem as Visibility, + emptyList(), + receiver, + originalDescriptor.method + ) invokeRefactoring(KotlinChangeSignatureProcessor(myProject, changeInfo, commandName ?: title)) } companion object { fun createProcessorForSilentRefactoring( - project: Project, - commandName: String, - descriptor: KotlinMethodDescriptor + project: Project, + commandName: String, + descriptor: KotlinMethodDescriptor ): BaseRefactoringProcessor { val originalDescriptor = descriptor.original val changeInfo = KotlinChangeInfo(methodDescriptor = originalDescriptor, context = originalDescriptor.method) diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/JavaMethodDeferredKotlinUsage.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/JavaMethodDeferredKotlinUsage.kt index 90d9bf55e4e..2d8566d91f8 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/JavaMethodDeferredKotlinUsage.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/JavaMethodDeferredKotlinUsage.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.changeSignature.usages @@ -29,19 +18,23 @@ abstract class JavaMethodDeferredKotlinUsage(element: T) : Usage } class DeferredJavaMethodOverrideOrSAMUsage( - val function: KtFunction, - val functionDescriptor: FunctionDescriptor, - val samCallType: KotlinType? + val function: KtFunction, + val functionDescriptor: FunctionDescriptor, + val samCallType: KotlinType? ) : JavaMethodDeferredKotlinUsage(function) { - override fun resolve(javaMethodChangeInfo: KotlinChangeInfo): JavaMethodKotlinUsageWithDelegate { - return object : JavaMethodKotlinUsageWithDelegate(function, javaMethodChangeInfo) { - override val delegateUsage = KotlinCallableDefinitionUsage(function, functionDescriptor, javaMethodChangeInfo.methodDescriptor.originalPrimaryCallable, samCallType) + override fun resolve(javaMethodChangeInfo: KotlinChangeInfo): JavaMethodKotlinUsageWithDelegate = + object : JavaMethodKotlinUsageWithDelegate(function, javaMethodChangeInfo) { + override val delegateUsage = KotlinCallableDefinitionUsage( + function, + functionDescriptor, + javaMethodChangeInfo.methodDescriptor.originalPrimaryCallable, + samCallType + ) } - } } class DeferredJavaMethodKotlinCallerUsage( - val declaration: KtNamedDeclaration + val declaration: KtNamedDeclaration ) : JavaMethodDeferredKotlinUsage(declaration) { override fun resolve(javaMethodChangeInfo: KotlinChangeInfo): JavaMethodKotlinUsageWithDelegate { return object : JavaMethodKotlinUsageWithDelegate(declaration, javaMethodChangeInfo) { diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/JavaMethodKotlinUsageWithDelegate.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/JavaMethodKotlinUsageWithDelegate.kt index 314126d0375..9bac45f87e6 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/JavaMethodKotlinUsageWithDelegate.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/JavaMethodKotlinUsageWithDelegate.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.changeSignature.usages @@ -22,19 +11,20 @@ import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinChangeInfo import org.jetbrains.kotlin.psi.KtCallElement import org.jetbrains.kotlin.psi.KtConstructorDelegationCall -abstract class JavaMethodKotlinUsageWithDelegate( - val psiElement: T, - var javaMethodChangeInfo: KotlinChangeInfo): UsageInfo(psiElement) { +abstract class JavaMethodKotlinUsageWithDelegate( + val psiElement: T, + var javaMethodChangeInfo: KotlinChangeInfo +) : UsageInfo(psiElement) { abstract val delegateUsage: KotlinUsageInfo fun processUsage(allUsages: Array): Boolean = delegateUsage.processUsage(javaMethodChangeInfo, psiElement, allUsages) } class JavaMethodKotlinCallUsage( - callElement: KtCallElement, - javaMethodChangeInfo: KotlinChangeInfo, - propagationCall: Boolean -): JavaMethodKotlinUsageWithDelegate(callElement, javaMethodChangeInfo) { + callElement: KtCallElement, + javaMethodChangeInfo: KotlinChangeInfo, + propagationCall: Boolean +) : JavaMethodKotlinUsageWithDelegate(callElement, javaMethodChangeInfo) { @Suppress("UNCHECKED_CAST") override val delegateUsage = when { propagationCall -> KotlinCallerCallUsage(psiElement) diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinCallableDefinitionUsage.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinCallableDefinitionUsage.kt index 7405c1befcf..62b104d7662 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinCallableDefinitionUsage.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinCallableDefinitionUsage.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2013 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.changeSignature.usages @@ -51,11 +40,11 @@ import org.jetbrains.kotlin.types.typeUtil.isUnit import org.jetbrains.kotlin.utils.sure class KotlinCallableDefinitionUsage( - function: T, - val originalCallableDescriptor: CallableDescriptor, - baseFunction: KotlinCallableDefinitionUsage?, - private val samCallType: KotlinType?, - private val canDropOverride: Boolean = true + function: T, + val originalCallableDescriptor: CallableDescriptor, + baseFunction: KotlinCallableDefinitionUsage?, + private val samCallType: KotlinType?, + private val canDropOverride: Boolean = true ) : KotlinUsageInfo(function) { val baseFunction: KotlinCallableDefinitionUsage<*> = baseFunction ?: this @@ -76,8 +65,7 @@ class KotlinCallableDefinitionUsage( if (samCallType == null) { getCallableSubstitutor(this.baseFunction, this) - } - else { + } else { val currentBaseDescriptor = this.baseFunction.currentCallableDescriptor val classDescriptor = currentBaseDescriptor?.containingDeclaration as? ClassDescriptor ?: return@lazy null getTypeSubstitutor(classDescriptor.defaultType, samCallType) @@ -118,8 +106,7 @@ class KotlinCallableDefinitionUsage( if (changeInfo.isParameterSetOrOrderChanged) { processParameterListWithStructuralChanges(changeInfo, element, parameterList, psiFactory) - } - else if (parameterList != null) { + } else if (parameterList != null) { val offset = if (originalCallableDescriptor.extensionReceiverParameter != null) 1 else 0 for ((paramIndex, parameter) in parameterList.parameters.withIndex()) { val parameterInfo = changeInfo.newParameters[paramIndex + offset] @@ -165,10 +152,11 @@ class KotlinCallableDefinitionUsage( } private fun processParameterListWithStructuralChanges( - changeInfo: KotlinChangeInfo, - element: PsiElement, - originalParameterList: KtParameterList?, - psiFactory: KtPsiFactory) { + changeInfo: KotlinChangeInfo, + element: PsiElement, + originalParameterList: KtParameterList?, + psiFactory: KtPsiFactory + ) { var parameterList = originalParameterList val parametersCount = changeInfo.getNonReceiverParametersCount() val isLambda = element is KtFunctionLiteral @@ -183,13 +171,11 @@ class KotlinCallableDefinitionUsage( arrow?.delete() parameterList = null } - } - else { + } else { newParameterList = psiFactory.createLambdaParameterList(changeInfo.getNewParametersSignatureWithoutParentheses(this)) canReplaceEntireList = true } - } - else if (!(element is KtProperty || element is KtParameter)) { + } else if (!(element is KtProperty || element is KtParameter)) { newParameterList = psiFactory.createParameterList(changeInfo.getNewParametersSignature(this)) } @@ -198,18 +184,15 @@ class KotlinCallableDefinitionUsage( if (parameterList != null) { newParameterList = if (canReplaceEntireList) { parameterList.replace(newParameterList) as KtParameterList - } - else { + } else { replaceListPsiAndKeepDelimiters(parameterList, newParameterList) { parameters } } - } - else { + } else { if (element is KtClass) { val constructor = element.createPrimaryConstructorIfAbsent() val oldParameterList = constructor.valueParameterList.sure { "primary constructor from factory has parameter list" } newParameterList = oldParameterList.replace(newParameterList) as KtParameterList - } - else if (isLambda) { + } else if (isLambda) { val functionLiteral = element as KtFunctionLiteral val anchor = functionLiteral.lBrace newParameterList = element.addAfter(newParameterList, anchor) as KtParameterList diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinCallerUsages.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinCallerUsages.kt index 241fa5f15ec..8b23a716606 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinCallerUsages.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinCallerUsages.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.changeSignature.usages @@ -24,7 +13,7 @@ import org.jetbrains.kotlin.idea.refactoring.changeSignature.isInsideOfCallerBod import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* -class KotlinCallerUsage(element: KtNamedDeclaration): KotlinUsageInfo(element) { +class KotlinCallerUsage(element: KtNamedDeclaration) : KotlinUsageInfo(element) { override fun processUsage(changeInfo: KotlinChangeInfo, element: KtNamedDeclaration, allUsages: Array): Boolean { // Do not process function twice if (changeInfo.getAffectedCallables().any { it is KotlinCallableDefinitionUsage<*> && it.element == element }) return true @@ -39,36 +28,35 @@ class KotlinCallerUsage(element: KtNamedDeclaration): KotlinUsageInfo(element) { +class KotlinCallerCallUsage(element: KtCallElement) : KotlinUsageInfo(element) { override fun processUsage(changeInfo: KotlinChangeInfo, element: KtCallElement, allUsages: Array): Boolean { val argumentList = element.valueArgumentList ?: return true val psiFactory = KtPsiFactory(project) val isNamedCall = argumentList.arguments.any { it.isNamed() } changeInfo.getNonReceiverParameters() - .filter { it.isNewParameter } - .forEach { - val parameterName = it.name - val argumentExpression = if (element.isInsideOfCallerBody(allUsages)) { - psiFactory.createExpression(parameterName) - } - else { - it.defaultValueForCall ?: psiFactory.createExpression("_") - } - val argument = psiFactory.createArgument( - expression = argumentExpression, - name = if (isNamedCall) Name.identifier(parameterName) else null - ) - argumentList.addArgument(argument) + .filter { it.isNewParameter } + .forEach { + val parameterName = it.name + val argumentExpression = if (element.isInsideOfCallerBody(allUsages)) { + psiFactory.createExpression(parameterName) + } else { + it.defaultValueForCall ?: psiFactory.createExpression("_") } + val argument = psiFactory.createArgument( + expression = argumentExpression, + name = if (isNamedCall) Name.identifier(parameterName) else null + ) + argumentList.addArgument(argument) + } return true } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinComponentUsageInDestructuring.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinComponentUsageInDestructuring.kt index 5253ec9624b..8f5e2a6a6fc 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinComponentUsageInDestructuring.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinComponentUsageInDestructuring.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.changeSignature.usages @@ -30,8 +19,13 @@ import org.jetbrains.kotlin.psi.buildDestructuringDeclaration import org.jetbrains.kotlin.psi.psiUtil.PsiChildRange import org.jetbrains.kotlin.utils.ifEmpty -class KotlinComponentUsageInDestructuring(element: KtDestructuringDeclarationEntry) : KotlinUsageInfo(element) { - override fun processUsage(changeInfo: KotlinChangeInfo, element: KtDestructuringDeclarationEntry, allUsages: Array): Boolean { +class KotlinComponentUsageInDestructuring(element: KtDestructuringDeclarationEntry) : + KotlinUsageInfo(element) { + override fun processUsage( + changeInfo: KotlinChangeInfo, + element: KtDestructuringDeclarationEntry, + allUsages: Array + ): Boolean { if (!changeInfo.isParameterSetOrOrderChanged) return true val declaration = element.parent as KtDestructuringDeclaration @@ -41,7 +35,8 @@ class KotlinComponentUsageInDestructuring(element: KtDestructuringDeclarationEnt val newDestructuring = KtPsiFactory(element).buildDestructuringDeclaration { val lastIndex = newParameterInfos.indexOfLast { it.oldIndex in currentEntries.indices } val nameValidator = CollectingNameValidator( - filter = NewDeclarationNameValidator(declaration.parent.parent, null, Target.VARIABLES)) + filter = NewDeclarationNameValidator(declaration.parent.parent, null, Target.VARIABLES) + ) appendFixedText("val (") for (i in 0..lastIndex) { @@ -53,29 +48,28 @@ class KotlinComponentUsageInDestructuring(element: KtDestructuringDeclarationEnt val oldIndex = paramInfo.oldIndex if (oldIndex >= 0 && oldIndex < currentEntries.size) { appendChildRange(PsiChildRange.singleElement(currentEntries[oldIndex])) - } - else { + } else { appendFixedText(KotlinNameSuggester.suggestNameByName(paramInfo.name, nameValidator)) } } appendFixedText(")") } replaceListPsiAndKeepDelimiters( - declaration, - newDestructuring, - { - apply { - val oldEntries = entries.ifEmpty { return@apply } - val firstOldEntry = oldEntries.first() - val lastOldEntry = oldEntries.last() - val newEntries = it.entries - if (newEntries.isNotEmpty()) { - addRangeBefore(newEntries.first(), newEntries.last(), firstOldEntry) - } - deleteChildRange(firstOldEntry, lastOldEntry) + declaration, + newDestructuring, + { + apply { + val oldEntries = entries.ifEmpty { return@apply } + val firstOldEntry = oldEntries.first() + val lastOldEntry = oldEntries.last() + val newEntries = it.entries + if (newEntries.isNotEmpty()) { + addRangeBefore(newEntries.first(), newEntries.last(), firstOldEntry) } - }, - { entries } + deleteChildRange(firstOldEntry, lastOldEntry) + } + }, + { entries } ) return true diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinConstructorDelegationCallUsage.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinConstructorDelegationCallUsage.kt index 0fc52f1b04f..f960036a6d8 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinConstructorDelegationCallUsage.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinConstructorDelegationCallUsage.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.changeSignature.usages @@ -23,12 +12,16 @@ import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.KtSecondaryConstructor class KotlinConstructorDelegationCallUsage( - call: KtConstructorDelegationCall, - changeInfo: KotlinChangeInfo + call: KtConstructorDelegationCall, + changeInfo: KotlinChangeInfo ) : KotlinUsageInfo(call) { val delegate = KotlinFunctionCallUsage(call, changeInfo.methodDescriptor.originalPrimaryCallable) - override fun processUsage(changeInfo: KotlinChangeInfo, element: KtConstructorDelegationCall, allUsages: Array): Boolean { + override fun processUsage( + changeInfo: KotlinChangeInfo, + element: KtConstructorDelegationCall, + allUsages: Array + ): Boolean { val isThisCall = element.isCallToThis var elementToWorkWith = element diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinDataClassComponentUsage.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinDataClassComponentUsage.kt index e3d39d45292..d2e8e75104c 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinDataClassComponentUsage.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinDataClassComponentUsage.kt @@ -22,8 +22,8 @@ import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.KtSimpleNameExpression class KotlinDataClassComponentUsage( - calleeExpression: KtSimpleNameExpression, - private val newName: String + calleeExpression: KtSimpleNameExpression, + private val newName: String ) : KotlinUsageInfo(calleeExpression) { override fun processUsage(changeInfo: KotlinChangeInfo, element: KtSimpleNameExpression, allUsages: Array): Boolean { element.replace(KtPsiFactory(element).createExpression(newName)) diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinEnumEntryWithoutSuperCallUsage.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinEnumEntryWithoutSuperCallUsage.kt index d97c979eb8d..b87feea3052 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinEnumEntryWithoutSuperCallUsage.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinEnumEntryWithoutSuperCallUsage.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.changeSignature.usages @@ -25,16 +14,19 @@ import org.jetbrains.kotlin.psi.KtSuperTypeCallEntry class KotlinEnumEntryWithoutSuperCallUsage(enumEntry: KtEnumEntry) : KotlinUsageInfo(enumEntry) { override fun processUsage(changeInfo: KotlinChangeInfo, element: KtEnumEntry, allUsages: Array): Boolean { - if (changeInfo.newParameters.size > 0) { + if (changeInfo.newParameters.isNotEmpty()) { val psiFactory = KtPsiFactory(element) val delegatorToSuperCall = (element.addAfter( - psiFactory.createEnumEntryInitializerList(), - element.nameIdentifier + psiFactory.createEnumEntryInitializerList(), + element.nameIdentifier ) as KtInitializerList).initializers[0] as KtSuperTypeCallEntry - return KotlinFunctionCallUsage(delegatorToSuperCall, changeInfo.methodDescriptor.originalPrimaryCallable) - .processUsage(changeInfo, delegatorToSuperCall, allUsages) + return KotlinFunctionCallUsage(delegatorToSuperCall, changeInfo.methodDescriptor.originalPrimaryCallable).processUsage( + changeInfo, + delegatorToSuperCall, + allUsages + ) } return true diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinImplicitThisToParameterUsage.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinImplicitThisToParameterUsage.kt index bea66f5f74a..a4cfc47d253 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinImplicitThisToParameterUsage.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinImplicitThisToParameterUsage.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2014 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.changeSignature.usages @@ -29,7 +18,7 @@ import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.KtQualifiedExpression import org.jetbrains.kotlin.resolve.DescriptorUtils -abstract class KotlinImplicitReceiverUsage(callElement: KtElement): KotlinUsageInfo(callElement) { +abstract class KotlinImplicitReceiverUsage(callElement: KtElement) : KotlinUsageInfo(callElement) { protected abstract fun getNewReceiverText(): String protected open fun processReplacedElement(element: KtElement) { @@ -38,7 +27,7 @@ abstract class KotlinImplicitReceiverUsage(callElement: KtElement): KotlinUsageI override fun processUsage(changeInfo: KotlinChangeInfo, element: KtElement, allUsages: Array): Boolean { val newQualifiedCall = KtPsiFactory(element.project).createExpression( - "${getNewReceiverText()}.${element.text}" + "${getNewReceiverText()}.${element.text}" ) as KtQualifiedExpression processReplacedElement(element.replace(newQualifiedCall) as KtElement) return false @@ -46,10 +35,10 @@ abstract class KotlinImplicitReceiverUsage(callElement: KtElement): KotlinUsageI } class KotlinImplicitThisToParameterUsage( - callElement: KtElement, - val parameterInfo: KotlinParameterInfo, - val containingCallable: KotlinCallableDefinitionUsage<*> -): KotlinImplicitReceiverUsage(callElement) { + callElement: KtElement, + val parameterInfo: KotlinParameterInfo, + val containingCallable: KotlinCallableDefinitionUsage<*> +) : KotlinImplicitReceiverUsage(callElement) { override fun getNewReceiverText(): String = parameterInfo.getInheritedName(containingCallable) override fun processReplacedElement(element: KtElement) { @@ -58,9 +47,9 @@ class KotlinImplicitThisToParameterUsage( } class KotlinImplicitThisUsage( - callElement: KtElement, - val targetDescriptor: DeclarationDescriptor -): KotlinImplicitReceiverUsage(callElement) { + callElement: KtElement, + val targetDescriptor: DeclarationDescriptor +) : KotlinImplicitReceiverUsage(callElement) { override fun getNewReceiverText() = explicateReceiverOf(targetDescriptor) override fun processReplacedElement(element: KtElement) { @@ -72,7 +61,8 @@ fun explicateReceiverOf(descriptor: DeclarationDescriptor): String { val name = descriptor.name return when { name.isSpecial -> "this" - DescriptorUtils.isCompanionObject(descriptor) -> IdeDescriptorRenderers.SOURCE_CODE.renderClassifierName(descriptor as ClassifierDescriptor) + DescriptorUtils.isCompanionObject(descriptor) -> IdeDescriptorRenderers.SOURCE_CODE + .renderClassifierName(descriptor as ClassifierDescriptor) else -> "this@${name.asString()}" } } \ No newline at end of file diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinParameterUsage.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinParameterUsage.kt index 5a4206246d6..856dd44d588 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinParameterUsage.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinParameterUsage.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2014 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.changeSignature.usages @@ -45,9 +34,9 @@ abstract class KotlinExplicitReferenceUsage(element: T) : KotlinU } class KotlinParameterUsage( - element: KtElement, - private val parameterInfo: KotlinParameterInfo, - val containingCallable: KotlinCallableDefinitionUsage<*> + element: KtElement, + private val parameterInfo: KotlinParameterInfo, + val containingCallable: KotlinCallableDefinitionUsage<*> ) : KotlinExplicitReferenceUsage(element) { override fun processReplacedElement(element: KtElement) { val qualifiedExpression = element.parent as? KtQualifiedExpression @@ -66,8 +55,8 @@ class KotlinParameterUsage( } class KotlinNonQualifiedOuterThisUsage( - element: KtThisExpression, - val targetDescriptor: DeclarationDescriptor + element: KtThisExpression, + val targetDescriptor: DeclarationDescriptor ) : KotlinExplicitReferenceUsage(element) { override fun processReplacedElement(element: KtElement) { element.addToShorteningWaitSet(Options(removeThisLabels = true)) diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinPropertyCallUsage.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinPropertyCallUsage.kt index 8b5b2d8ad94..79f5cb8763d 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinPropertyCallUsage.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinPropertyCallUsage.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.changeSignature.usages @@ -28,7 +17,7 @@ import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelectorOrThis import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver -class KotlinPropertyCallUsage(element: KtSimpleNameExpression): KotlinUsageInfo(element) { +class KotlinPropertyCallUsage(element: KtSimpleNameExpression) : KotlinUsageInfo(element) { private val resolvedCall = element.resolveToCall(BodyResolveMode.FULL) override fun processUsage(changeInfo: KotlinChangeInfo, element: KtSimpleNameExpression, allUsages: Array): Boolean { @@ -53,7 +42,8 @@ class KotlinPropertyCallUsage(element: KtSimpleNameExpression): KotlinUsageInfo< // Do not add extension receiver to calls with explicit dispatch receiver if (newReceiver != null && elementToReplace is KtQualifiedExpression - && resolvedCall?.dispatchReceiver is ExpressionReceiver) return + && resolvedCall?.dispatchReceiver is ExpressionReceiver + ) return val replacingElement = newReceiver?.let { val psiFactory = KtPsiFactory(project) diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinWrapperForJavaUsageInfos.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinWrapperForJavaUsageInfos.kt index d73bf071bbe..bb66941713f 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinWrapperForJavaUsageInfos.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinWrapperForJavaUsageInfos.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.changeSignature.usages @@ -21,10 +10,10 @@ import com.intellij.refactoring.changeSignature.JavaChangeInfo import com.intellij.usageView.UsageInfo class KotlinWrapperForJavaUsageInfos( - val javaChangeInfo: JavaChangeInfo, - val javaUsageInfos: Array, - primaryMethod: PsiElement -): UsageInfo(primaryMethod) { + val javaChangeInfo: JavaChangeInfo, + val javaUsageInfos: Array, + primaryMethod: PsiElement +) : UsageInfo(primaryMethod) { override fun hashCode() = javaChangeInfo.method.hashCode() override fun equals(other: Any?): Boolean { diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/cutPaste/MoveDeclarationsCopyPasteProcessor.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/cutPaste/MoveDeclarationsCopyPasteProcessor.kt index 320e0d02b0e..2fd8dc042a0 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/cutPaste/MoveDeclarationsCopyPasteProcessor.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/cutPaste/MoveDeclarationsCopyPasteProcessor.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.cutPaste @@ -51,10 +40,10 @@ class MoveDeclarationsCopyPasteProcessor : CopyPastePostProcessor { if (DumbService.isDumb(file.project)) return emptyList() @@ -90,34 +79,33 @@ class MoveDeclarationsCopyPasteProcessor : CopyPastePostProcessor, - values: List + project: Project, + editor: Editor, + bounds: RangeMarker, + caretOffset: Int, + indented: Ref, + values: List ) { val data = values.single() fun putCookie() { if (bounds.isValid) { - val cookie = MoveDeclarationsEditorCookie(data, bounds, PsiModificationTracker.SERVICE.getInstance(project).modificationCount) + val cookie = + MoveDeclarationsEditorCookie(data, bounds, PsiModificationTracker.SERVICE.getInstance(project).modificationCount) editor.putUserData(MoveDeclarationsEditorCookie.KEY, cookie) } } if (ApplicationManager.getApplication().isUnitTestMode) { putCookie() - } - else { + } else { // in real application we put cookie later to allow all other paste handlers do their work (because modificationCount will change) ApplicationManager.getApplication().invokeLater(::putCookie) } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/cutPaste/MoveDeclarationsEditorCookie.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/cutPaste/MoveDeclarationsEditorCookie.kt index db96b838416..d8be3187b00 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/cutPaste/MoveDeclarationsEditorCookie.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/cutPaste/MoveDeclarationsEditorCookie.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.cutPaste @@ -20,9 +9,9 @@ import com.intellij.openapi.editor.RangeMarker import com.intellij.openapi.util.Key class MoveDeclarationsEditorCookie( - val data: MoveDeclarationsTransferableData, - val bounds: RangeMarker, - val modificationCount: Long + val data: MoveDeclarationsTransferableData, + val bounds: RangeMarker, + val modificationCount: Long ) { companion object { val KEY = Key("MoveDeclarationsEditorCookie") diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/cutPaste/MoveDeclarationsIntentionAction.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/cutPaste/MoveDeclarationsIntentionAction.kt index c9be1b72079..e27e3a61e06 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/cutPaste/MoveDeclarationsIntentionAction.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/cutPaste/MoveDeclarationsIntentionAction.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.cutPaste @@ -30,9 +19,9 @@ import com.intellij.refactoring.BaseRefactoringIntentionAction import org.jetbrains.kotlin.idea.core.util.range class MoveDeclarationsIntentionAction( - private val processor: MoveDeclarationsProcessor, - private val bounds: RangeMarker, - private val modificationCount: Long + private val processor: MoveDeclarationsProcessor, + private val bounds: RangeMarker, + private val modificationCount: Long ) : BaseRefactoringIntentionAction(), HintAction { private val isSingleDeclaration = processor.pastedDeclarations.size == 1 @@ -56,7 +45,9 @@ class MoveDeclarationsIntentionAction( if (PsiModificationTracker.SERVICE.getInstance(processor.project).modificationCount != modificationCount) return false - val hintText = "$text? ${KeymapUtil.getFirstKeyboardShortcutText(ActionManager.getInstance().getAction(IdeActions.ACTION_SHOW_INTENTION_ACTIONS))}" + val hintText = "$text? ${KeymapUtil.getFirstKeyboardShortcutText( + ActionManager.getInstance().getAction(IdeActions.ACTION_SHOW_INTENTION_ACTIONS) + )}" HintManager.getInstance().showQuestionHint(editor, hintText, range.endOffset, range.endOffset) { processor.performRefactoring() true diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/cutPaste/MoveDeclarationsPassFactory.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/cutPaste/MoveDeclarationsPassFactory.kt index 17835333796..8a12a75343c 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/cutPaste/MoveDeclarationsPassFactory.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/cutPaste/MoveDeclarationsPassFactory.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.cutPaste @@ -32,11 +21,17 @@ import com.intellij.psi.PsiFile import com.intellij.psi.util.PsiModificationTracker import org.jetbrains.kotlin.idea.core.util.range -class MoveDeclarationsPassFactory(highlightingPassRegistrar: TextEditorHighlightingPassRegistrar) - : ProjectComponent, TextEditorHighlightingPassFactory { - +class MoveDeclarationsPassFactory(highlightingPassRegistrar: TextEditorHighlightingPassRegistrar) : ProjectComponent, + TextEditorHighlightingPassFactory { + init { - highlightingPassRegistrar.registerTextEditorHighlightingPass(this, TextEditorHighlightingPassRegistrar.Anchor.BEFORE, Pass.POPUP_HINTS, true, true) + highlightingPassRegistrar.registerTextEditorHighlightingPass( + this, + TextEditorHighlightingPassRegistrar.Anchor.BEFORE, + Pass.POPUP_HINTS, + true, + true + ) } override fun createHighlightingPass(file: PsiFile, editor: Editor): TextEditorHighlightingPass? { @@ -44,9 +39,9 @@ class MoveDeclarationsPassFactory(highlightingPassRegistrar: TextEditorHighlight } private class MyPass( - private val project: Project, - private val file: PsiFile, - private val editor: Editor + private val project: Project, + private val file: PsiFile, + private val editor: Editor ) : TextEditorHighlightingPass(project, editor.document, true) { override fun doCollectInformation(progress: ProgressIndicator) {} @@ -69,8 +64,8 @@ class MoveDeclarationsPassFactory(highlightingPassRegistrar: TextEditorHighlight } val info = HighlightInfo.newHighlightInfo(HighlightInfoType.INFORMATION) - .range(cookie.bounds.range!!) - .createUnconditionally() + .range(cookie.bounds.range!!) + .createUnconditionally() QuickFixAction.registerQuickFixAction(info, MoveDeclarationsIntentionAction(processor, cookie.bounds, cookie.modificationCount)) return info diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/cutPaste/MoveDeclarationsProcessor.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/cutPaste/MoveDeclarationsProcessor.kt index 7f053e37b0f..3e7bfe69fcc 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/cutPaste/MoveDeclarationsProcessor.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/cutPaste/MoveDeclarationsProcessor.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.cutPaste @@ -39,12 +28,12 @@ import org.jetbrains.kotlin.psi.psiUtil.findDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.startOffset class MoveDeclarationsProcessor( - val project: Project, - private val sourceContainer: KtDeclarationContainer, - private val targetPsiFile: KtFile, - val pastedDeclarations: List, - private val imports: List, - private val sourceDeclarationsText: List + val project: Project, + private val sourceContainer: KtDeclarationContainer, + private val targetPsiFile: KtFile, + val pastedDeclarations: List, + private val imports: List, + private val sourceDeclarationsText: List ) { companion object { fun build(editor: Editor, cookie: MoveDeclarationsEditorCookie): MoveDeclarationsProcessor? { diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/dataContextUtils.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/dataContextUtils.kt index aed384af123..6e91b914cf1 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/dataContextUtils.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/dataContextUtils.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring @@ -28,5 +17,5 @@ val DataContext.project: Project val DataContext.hostEditor: Editor? get() = CommonDataKeys.HOST_EDITOR.getData(this) -val DataContext.psiElement : PsiElement? +val DataContext.psiElement: PsiElement? get() = CommonDataKeys.PSI_ELEMENT.getData(this) \ No newline at end of file diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/inline/AbstractKotlinInlineDialog.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/inline/AbstractKotlinInlineDialog.kt index c0b3908bf3f..834882a2ecd 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/inline/AbstractKotlinInlineDialog.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/inline/AbstractKotlinInlineDialog.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.inline @@ -25,17 +14,18 @@ import org.jetbrains.kotlin.idea.references.KtSimpleNameReference import org.jetbrains.kotlin.psi.KtCallableDeclaration abstract class AbstractKotlinInlineDialog( - protected val callable: KtCallableDeclaration, - protected val reference: KtSimpleNameReference?, - project: Project = callable.project -) : InlineOptionsDialog(project, true, callable) { + protected val callable: KtCallableDeclaration, + protected val reference: KtSimpleNameReference?, + project: Project = callable.project +) : InlineOptionsDialog(project, true, callable) { // NB: can be -1 in case of too expensive search! protected val occurrencesNumber = initOccurrencesNumber(callable) - private val occurrencesString get() = if (occurrencesNumber >= 0) { - "" + occurrencesNumber + " " + StringUtil.pluralize("occurrence", occurrencesNumber) - } else null + private val occurrencesString + get() = if (occurrencesNumber >= 0) { + "" + occurrencesNumber + " " + StringUtil.pluralize("occurrence", occurrencesNumber) + } else null private val kind: String = ElementDescriptionUtil.getElementDescription(callable, UsageViewTypeLocation.INSTANCE) @@ -64,20 +54,17 @@ abstract class AbstractKotlinInlineDialog( return "${kind.capitalize()} ${callable.nameAsSafeName} $occurrencesString" } - private fun getInlineText(verb: String) = - "Inline all references and $verb the $kind " + (occurrencesString?.let { "($it)" } ?: "") + private fun getInlineText(verb: String) = "Inline all references and $verb the $kind " + (occurrencesString?.let { "($it)" } ?: "") - override fun getInlineAllText() = - getInlineText("remove") + override fun getInlineAllText() = getInlineText("remove") override fun getKeepTheDeclarationText(): String? = - // With non-writable callable refactoring does not work anyway (for both property or function) - if (callable.isWritable && (occurrencesNumber > 1 || !myInvokedOnReference)) { - getInlineText("keep") - } - else { - null - } + // With non-writable callable refactoring does not work anyway (for both property or function) + if (callable.isWritable && (occurrencesNumber > 1 || !myInvokedOnReference)) { + getInlineText("keep") + } else { + null + } override fun getInlineThisText() = "Inline this reference and keep the $kind" } \ No newline at end of file diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/inline/KotlinInlineFunctionDialog.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/inline/KotlinInlineFunctionDialog.kt index ce17b7c815e..3c7101cca27 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/inline/KotlinInlineFunctionDialog.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/inline/KotlinInlineFunctionDialog.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.inline @@ -19,18 +8,18 @@ package org.jetbrains.kotlin.idea.refactoring.inline import com.intellij.openapi.help.HelpManager import com.intellij.openapi.project.Project import com.intellij.refactoring.HelpID -import org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringSettings import org.jetbrains.kotlin.idea.codeInliner.UsageReplacementStrategy +import org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringSettings import org.jetbrains.kotlin.idea.references.KtSimpleNameReference import org.jetbrains.kotlin.psi.KtConstructor import org.jetbrains.kotlin.psi.KtNamedFunction class KotlinInlineFunctionDialog( - project: Project, - function: KtNamedFunction, - reference: KtSimpleNameReference?, - private val replacementStrategy: UsageReplacementStrategy, - private val allowInlineThisOnly: Boolean + project: Project, + function: KtNamedFunction, + reference: KtSimpleNameReference?, + private val replacementStrategy: UsageReplacementStrategy, + private val allowInlineThisOnly: Boolean ) : AbstractKotlinInlineDialog(function, reference, project) { init { @@ -41,9 +30,11 @@ class KotlinInlineFunctionDialog( public override fun doAction() { invokeRefactoring( - KotlinInlineCallableProcessor(project, replacementStrategy, callable, reference, - inlineThisOnly = isInlineThisOnly || allowInlineThisOnly, - deleteAfter = !isInlineThisOnly && !isKeepTheDeclaration && !allowInlineThisOnly) + KotlinInlineCallableProcessor( + project, replacementStrategy, callable, reference, + inlineThisOnly = isInlineThisOnly || allowInlineThisOnly, + deleteAfter = !isInlineThisOnly && !isKeepTheDeclaration && !allowInlineThisOnly + ) ) val settings = KotlinRefactoringSettings.instance @@ -53,7 +44,7 @@ class KotlinInlineFunctionDialog( } override fun doHelpAction() = - HelpManager.getInstance().invokeHelp(if (callable is KtConstructor<*>) HelpID.INLINE_CONSTRUCTOR else HelpID.INLINE_METHOD) + HelpManager.getInstance().invokeHelp(if (callable is KtConstructor<*>) HelpID.INLINE_CONSTRUCTOR else HelpID.INLINE_METHOD) override fun canInlineThisOnly() = allowInlineThisOnly } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/inline/KotlinInlineFunctionHandler.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/inline/KotlinInlineFunctionHandler.kt index 95f0fd92e9d..3caee35819f 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/inline/KotlinInlineFunctionHandler.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/inline/KotlinInlineFunctionHandler.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.inline @@ -36,7 +25,7 @@ import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall -class KotlinInlineFunctionHandler: InlineActionHandler() { +class KotlinInlineFunctionHandler : InlineActionHandler() { override fun isEnabledForLanguage(language: Language) = language == KotlinLanguage.INSTANCE //TODO: overrides etc @@ -55,22 +44,23 @@ class KotlinInlineFunctionHandler: InlineActionHandler() { val descriptor = element.unsafeResolveToDescriptor() as SimpleFunctionDescriptor val codeToInline = buildCodeToInline( - element, - descriptor.returnType, - element.hasDeclaredReturnType(), - element.bodyExpression!!, - element.hasBlockBody(), - editor + element, + descriptor.returnType, + element.hasDeclaredReturnType(), + element.bodyExpression!!, + element.hasBlockBody(), + editor ) ?: return val replacementStrategy = CallableUsageReplacementStrategy(codeToInline, inlineSetter = false) - val dialog = KotlinInlineFunctionDialog(project, element, nameReference, replacementStrategy, - allowInlineThisOnly = recursive) + val dialog = KotlinInlineFunctionDialog( + project, element, nameReference, replacementStrategy, + allowInlineThisOnly = recursive + ) if (!ApplicationManager.getApplication().isUnitTestMode) { dialog.show() - } - else { + } else { dialog.doAction() } } @@ -83,8 +73,8 @@ class KotlinInlineFunctionHandler: InlineActionHandler() { private fun KtExpression.includesCallOf(descriptor: FunctionDescriptor, context: BindingContext): Boolean { val refDescriptor = getResolvedCall(context)?.resultingDescriptor return descriptor == refDescriptor || anyDescendantOfType { - it !== this && descriptor == it.getResolvedCall(context)?.resultingDescriptor - } + it !== this && descriptor == it.getResolvedCall(context)?.resultingDescriptor + } } } \ No newline at end of file diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/inline/KotlinInlineTypeAliasHandler.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/inline/KotlinInlineTypeAliasHandler.kt index c16006cd26c..49388f85347 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/inline/KotlinInlineTypeAliasHandler.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/inline/KotlinInlineTypeAliasHandler.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.inline @@ -87,12 +76,15 @@ class KotlinInlineTypeAliasHandler : InlineActionHandler() { preProcessInternalUsages(aliasBody, usages) } - if (!showDialog(project, - name, - REFACTORING_NAME, - typeAlias, - usages, - HelpID.INLINE_VARIABLE)) { + if (!showDialog( + project, + name, + REFACTORING_NAME, + typeAlias, + usages, + HelpID.INLINE_VARIABLE + ) + ) { if (isHighlighting) { val statusBar = WindowManager.getInstance().getStatusBar(project) statusBar?.info = RefactoringBundle.message("press.escape.to.remove.the.highlighting") @@ -120,8 +112,7 @@ class KotlinInlineTypeAliasHandler : InlineActionHandler() { val expandedType = substitutor.substitute(typeToInline, Variance.INVARIANT) ?: return null val expandedTypeText = IdeDescriptorRenderers.SOURCE_CODE.renderType(expandedType) val needParentheses = - (expandedType.isFunctionType && usage.parent is KtNullableType) || - (expandedType.isExtensionFunctionType && usage.getParentOfTypeAndBranch { receiverTypeReference } != null) + (expandedType.isFunctionType && usage.parent is KtNullableType) || (expandedType.isExtensionFunctionType && usage.getParentOfTypeAndBranch { receiverTypeReference } != null) val expandedTypeReference = psiFactory.createType(expandedTypeText) return usage.replaced(expandedTypeReference.typeElement!!).apply { if (needParentheses) { @@ -147,8 +138,8 @@ class KotlinInlineTypeAliasHandler : InlineActionHandler() { val resolvedCall = usage.resolveToCall() ?: return null val callElement = resolvedCall.call.callElement as? KtCallElement ?: return null val substitution = resolvedCall.typeArguments - .mapKeys { it.key.typeConstructor } - .mapValues { TypeProjectionImpl(it.value) } + .mapKeys { it.key.typeConstructor } + .mapValues { TypeProjectionImpl(it.value) } if (substitution.size != typeConstructorsToInline.size) return null val substitutor = TypeSubstitutor.create(substitution) val expandedType = substitutor.substitute(typeToInline, Variance.INVARIANT) ?: return null @@ -156,22 +147,23 @@ class KotlinInlineTypeAliasHandler : InlineActionHandler() { if (expandedType.arguments.isNotEmpty()) { val expandedTypeArgumentList = psiFactory.createTypeArguments( - expandedType.arguments.joinToString(prefix = "<", - postfix = ">") { IdeDescriptorRenderers.SOURCE_CODE.renderType(it.type) } + expandedType.arguments.joinToString( + prefix = "<", + postfix = ">" + ) { IdeDescriptorRenderers.SOURCE_CODE.renderType(it.type) } ) val originalTypeArgumentList = callElement.typeArgumentList if (originalTypeArgumentList != null) { originalTypeArgumentList.replaced(expandedTypeArgumentList) - } - else { + } else { callElement.addAfter(expandedTypeArgumentList, callElement.calleeExpression) } } val newCallElement = ((usage.mainReference as KtSimpleNameReference).bindToFqName( - expandedTypeFqName, - KtSimpleNameReference.ShorteningMode.NO_SHORTENING + expandedTypeFqName, + KtSimpleNameReference.ShorteningMode.NO_SHORTENING ) as KtExpression).getNonStrictParentOfType() return newCallElement?.getQualifiedExpressionForSelector() ?: newCallElement } @@ -179,10 +171,10 @@ class KotlinInlineTypeAliasHandler : InlineActionHandler() { project.executeWriteCommand(RefactoringBundle.message("inline.command", name)) { val inlinedElements = usages.mapNotNull { val inlinedElement = when (it) { - is KtUserType -> inlineIntoType(it) - is KtReferenceExpression -> inlineIntoCall(it) - else -> null - } ?: return@mapNotNull null + is KtUserType -> inlineIntoType(it) + is KtReferenceExpression -> inlineIntoCall(it) + else -> null + } ?: return@mapNotNull null postProcessInternalReferences(inlinedElement) } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/inline/inlineUtils.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/inline/inlineUtils.kt index 4b90c4c8ccd..452bfbf0dc3 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/inline/inlineUtils.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/inline/inlineUtils.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.inline @@ -63,12 +52,12 @@ fun highlightElements(project: Project, editor: Editor?, elements: List, - helpTopic: String? = null + project: Project, + name: String, + title: String, + declaration: KtNamedDeclaration, + usages: List, + helpTopic: String? = null ): Boolean { if (ApplicationManager.getApplication().isUnitTestMode) return true @@ -78,12 +67,12 @@ fun showDialog( else -> return false } val dialog = RefactoringMessageDialog( - title, - "Inline " + kind + " '" + name + "'? " + RefactoringBundle.message("occurences.string", usages.size), - helpTopic, - "OptionPane.questionIcon", - true, - project + title, + "Inline " + kind + " '" + name + "'? " + RefactoringBundle.message("occurences.string", usages.size), + helpTopic, + "OptionPane.questionIcon", + true, + project ) dialog.show() return dialog.isOK @@ -99,9 +88,9 @@ internal fun preProcessInternalUsages(element: KtElement, usages: Collection - val infos = - expr.internalUsageInfos - ?: LinkedHashMap UsageInfo?>().apply { expr.internalUsageInfos = this } + val infos = expr.internalUsageInfos ?: LinkedHashMap UsageInfo?>().apply { + expr.internalUsageInfos = this + } infos[targetPackage] = factory } } @@ -118,12 +107,12 @@ internal fun postProcessInternalReferences(inlinedElement: E): E } internal fun buildCodeToInline( - declaration: KtDeclaration, - returnType: KotlinType?, - isReturnTypeExplicit: Boolean, - bodyOrInitializer: KtExpression, - isBlockBody: Boolean, - editor: Editor? + declaration: KtDeclaration, + returnType: KotlinType?, + isReturnTypeExplicit: Boolean, + bodyOrInitializer: KtExpression, + isBlockBody: Boolean, + editor: Editor? ): CodeToInline? { val bodyCopy = bodyOrInitializer.copied() @@ -132,11 +121,11 @@ internal fun buildCodeToInline( else TypeUtils.NO_EXPECTED_TYPE - fun analyzeBodyCopy(): BindingContext { - return bodyCopy.analyzeInContext(bodyOrInitializer.getResolutionScope(), - contextExpression = bodyOrInitializer, - expectedType = expectedType) - } + fun analyzeBodyCopy(): BindingContext = bodyCopy.analyzeInContext( + bodyOrInitializer.getResolutionScope(), + contextExpression = bodyOrInitializer, + expectedType = expectedType + ) val descriptor = declaration.unsafeResolveToDescriptor() val builder = CodeToInlineBuilder(descriptor as CallableDescriptor, declaration.getResolutionFacade()) @@ -151,28 +140,27 @@ internal fun buildCodeToInline( val lastReturn = statements.lastOrNull() as? KtReturnExpression if (returnStatements.any { it != lastReturn }) { val message = RefactoringBundle.getCannotRefactorMessage( - if (returnStatements.size > 1) - "Inline Function is not supported for functions with multiple return statements." - else - "Inline Function is not supported for functions with return statements not at the end of the body." + if (returnStatements.size > 1) + "Inline Function is not supported for functions with multiple return statements." + else + "Inline Function is not supported for functions with return statements not at the end of the body." ) CommonRefactoringUtil.showErrorHint(declaration.project, editor, message, "Inline Function", null) return null } - return builder.prepareCodeToInline(lastReturn?.returnedExpression, - statements.dropLast(returnStatements.size), ::analyzeBodyCopy, reformat = true) - } - else { + return builder.prepareCodeToInline( + lastReturn?.returnedExpression, + statements.dropLast(returnStatements.size), ::analyzeBodyCopy, reformat = true + ) + } else { return builder.prepareCodeToInline(bodyCopy, emptyList(), ::analyzeBodyCopy, reformat = true) } } -internal fun Editor.findSimpleNameReference(): KtSimpleNameReference? { - val reference = TargetElementUtil.findReference(this, caretModel.offset) - return when (reference) { +internal fun Editor.findSimpleNameReference(): KtSimpleNameReference? = + when (val reference = TargetElementUtil.findReference(this, caretModel.offset)) { is KtSimpleNameReference -> reference is PsiMultiReference -> reference.references.firstIsInstanceOrNull() else -> null } -} diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/extractFunction/ExtractFunctionAction.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/extractFunction/ExtractFunctionAction.kt index b7fb2249027..3218f8bc402 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/extractFunction/ExtractFunctionAction.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/extractFunction/ExtractFunctionAction.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.introduce.extractFunction @@ -21,12 +10,12 @@ import com.intellij.refactoring.RefactoringActionHandler import org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringSupportProvider import org.jetbrains.kotlin.idea.refactoring.introduce.AbstractIntroduceAction -class ExtractFunctionAction: AbstractIntroduceAction() { +class ExtractFunctionAction : AbstractIntroduceAction() { override fun getRefactoringHandler(provider: RefactoringSupportProvider): RefactoringActionHandler? = - (provider as? KotlinRefactoringSupportProvider)?.getExtractFunctionHandler() + (provider as? KotlinRefactoringSupportProvider)?.getExtractFunctionHandler() } -class ExtractFunctionToScopeAction: AbstractIntroduceAction() { +class ExtractFunctionToScopeAction : AbstractIntroduceAction() { override fun getRefactoringHandler(provider: RefactoringSupportProvider): RefactoringActionHandler? = - (provider as? KotlinRefactoringSupportProvider)?.getExtractFunctionToScopeHandler() + (provider as? KotlinRefactoringSupportProvider)?.getExtractFunctionToScopeHandler() } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/extractFunction/ui/ExtractFunctionParameterTablePanel.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/extractFunction/ui/ExtractFunctionParameterTablePanel.kt index c2c69dd4e68..d54e5e09a39 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/extractFunction/ui/ExtractFunctionParameterTablePanel.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/extractFunction/ui/ExtractFunctionParameterTablePanel.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.introduce.extractFunction.ui @@ -80,7 +69,9 @@ open class ExtractFunctionParameterTablePanel : AbstractParameterTablePanel @@ -308,7 +301,9 @@ private fun makeCall( val psiFactory = KtPsiFactory(anchor.project) val newLine = psiFactory.createNewLine() - if (controlFlow.outputValueBoxer is AsTuple && controlFlow.outputValues.size > 1 && controlFlow.outputValues.all { it is Initializer }) { + if (controlFlow.outputValueBoxer is AsTuple && controlFlow.outputValues.size > 1 && controlFlow.outputValues + .all { it is Initializer } + ) { val declarationsToMerge = controlFlow.outputValues.map { (it as Initializer).initializedDeclaration } val isVar = declarationsToMerge.first().isVar if (declarationsToMerge.all { it.isVar == isVar }) { @@ -556,7 +551,9 @@ fun ExtractionGeneratorConfiguration.generateDeclaration( if (lastExpression is KtReturnExpression) return val defaultExpression = - if (!generatorOptions.inTempFile && defaultValue != null && descriptor.controlFlow.outputValueBoxer.boxingRequired && lastExpression!!.isMultiLine()) { + if (!generatorOptions.inTempFile && defaultValue != null && descriptor.controlFlow.outputValueBoxer + .boxingRequired && lastExpression!!.isMultiLine() + ) { val varNameValidator = NewDeclarationNameValidator(body, lastExpression, NewDeclarationNameValidator.Target.VARIABLES) val resultVal = KotlinNameSuggester.suggestNamesByType(defaultValue.valueType, varNameValidator, null).first() body.addBefore(psiFactory.createDeclaration("val $resultVal = ${lastExpression.text}"), lastExpression) diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceParameter/KotlinInplaceParameterIntroducer.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceParameter/KotlinInplaceParameterIntroducer.kt index 6cf811f1af3..0d8086ffba3 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceParameter/KotlinInplaceParameterIntroducer.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceParameter/KotlinInplaceParameterIntroducer.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.introduce.introduceParameter @@ -47,20 +36,18 @@ import java.util.* import javax.swing.JCheckBox class KotlinInplaceParameterIntroducer( - val originalDescriptor: IntroduceParameterDescriptor, - val parameterType: KotlinType, - val suggestedNames: Array, - project: Project, - editor: Editor -): AbstractKotlinInplaceIntroducer( - null, - originalDescriptor.originalRange.elements.single() as KtExpression, - originalDescriptor.occurrencesToReplace - .map { it.elements.single() as KtExpression } - .toTypedArray(), - INTRODUCE_PARAMETER, - project, - editor + val originalDescriptor: IntroduceParameterDescriptor, + val parameterType: KotlinType, + val suggestedNames: Array, + project: Project, + editor: Editor +) : AbstractKotlinInplaceIntroducer( + null, + originalDescriptor.originalRange.elements.single() as KtExpression, + originalDescriptor.occurrencesToReplace.map { it.elements.single() as KtExpression }.toTypedArray(), + INTRODUCE_PARAMETER, + project, + editor ) { companion object { private val LOG = Logger.getInstance(KotlinInplaceParameterIntroducer::class.java) @@ -86,11 +73,12 @@ class KotlinInplaceParameterIntroducer( protected abstract val textAttributes: TextAttributes fun applyToRange(range: TextRange, markupModel: MarkupModel) { - markupModel.addRangeHighlighter(range.startOffset, - range.endOffset, - 0, - textAttributes, - HighlighterTargetArea.EXACT_RANGE + markupModel.addRangeHighlighter( + range.startOffset, + range.endOffset, + 0, + textAttributes, + HighlighterTargetArea.EXACT_RANGE ) } } @@ -109,9 +97,7 @@ class KotlinInplaceParameterIntroducer( init { val templateState = TemplateManagerImpl.getTemplateState(myEditor) val currentType = if (templateState?.template != null) { - templateState - .getVariableValue(KotlinInplaceVariableIntroducer.TYPE_REFERENCE_VARIABLE_NAME) - ?.text + templateState.getVariableValue(KotlinInplaceVariableIntroducer.TYPE_REFERENCE_VARIABLE_NAME)?.text } else null val builder = StringBuilder() @@ -131,7 +117,7 @@ class KotlinInplaceParameterIntroducer( for (i in parameters.indices) { val parameter = parameters[i] - val parameterText = if (parameter == addedParameter){ + val parameterText = if (parameter == addedParameter) { val parameterName = currentName ?: parameter.name val parameterType = currentType ?: parameter.typeReference!!.text descriptor = descriptor.copy(newParameterName = parameterName!!, newParameterTypeText = parameterType) @@ -141,16 +127,14 @@ class KotlinInplaceParameterIntroducer( } else "" "$modifier$parameterName: $parameterType$defaultValue" - } - else parameter.text + } else parameter.text builder.append(parameterText) val range = TextRange(builder.length - parameterText.length, builder.length) if (parameter == addedParameter) { addedRange = range - } - else if (!descriptor.withDefaultValue && parameter in parametersToRemove) { + } else if (!descriptor.withDefaultValue && parameter in parametersToRemove) { _rangesToRemove.add(range) } @@ -208,7 +192,7 @@ class KotlinInplaceParameterIntroducer( return runWriteAction { with(descriptor) { val parameterList = callable.getValueParameterList() - ?: (callable as KtClass).createPrimaryConstructorParameterListIfAbsent() + ?: (callable as KtClass).createPrimaryConstructorParameterListIfAbsent() val parameter = KtPsiFactory(myProject).createParameter("$newParameterName: $newParameterTypeText") parameterList.addParameter(parameter) } @@ -259,19 +243,21 @@ class KotlinInplaceParameterIntroducer( private fun getDescriptorToRefactor(replaceAll: Boolean): IntroduceParameterDescriptor { val originalRange = expr.toRange() return descriptor.copy( - originalRange = originalRange, - occurrencesToReplace = if (replaceAll) occurrences.map { it.toRange() } else listOf(originalRange), - argumentValue = expr!! + originalRange = originalRange, + occurrencesToReplace = if (replaceAll) occurrences.map { it.toRange() } else listOf(originalRange), + argumentValue = expr!! ) } fun switchToDialogUI() { stopIntroduce(myEditor) - KotlinIntroduceParameterDialog(myProject, - myEditor, - getDescriptorToRefactor(true), - myNameSuggestions.toTypedArray(), - listOf(parameterType) + parameterType.supertypes(), - KotlinIntroduceParameterHelper.Default).show() + KotlinIntroduceParameterDialog( + myProject, + myEditor, + getDescriptorToRefactor(true), + myNameSuggestions.toTypedArray(), + listOf(parameterType) + parameterType.supertypes(), + KotlinIntroduceParameterHelper.Default + ).show() } } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceParameter/KotlinIntroduceParameterDialog.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceParameter/KotlinIntroduceParameterDialog.kt index 9778f2bcb95..1110c1cc556 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceParameter/KotlinIntroduceParameterDialog.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceParameter/KotlinIntroduceParameterDialog.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.introduce.introduceParameter @@ -47,41 +36,41 @@ import javax.swing.JLabel import javax.swing.JPanel class KotlinIntroduceParameterDialog private constructor( + project: Project, + val editor: Editor, + val descriptor: IntroduceParameterDescriptor, + val lambdaExtractionDescriptor: ExtractableCodeDescriptor?, + nameSuggestions: Array, + typeSuggestions: List, + val helper: KotlinIntroduceParameterHelper +) : RefactoringDialog(project, true) { + constructor( project: Project, - val editor: Editor, - val descriptor: IntroduceParameterDescriptor, - val lambdaExtractionDescriptor: ExtractableCodeDescriptor?, + editor: Editor, + descriptor: IntroduceParameterDescriptor, nameSuggestions: Array, typeSuggestions: List, - val helper: KotlinIntroduceParameterHelper -): RefactoringDialog(project, true) { - constructor( - project: Project, - editor: Editor, - descriptor: IntroduceParameterDescriptor, - nameSuggestions: Array, - typeSuggestions: List, - helper: KotlinIntroduceParameterHelper - ): this(project, editor, descriptor, null, nameSuggestions, typeSuggestions, helper) + helper: KotlinIntroduceParameterHelper + ) : this(project, editor, descriptor, null, nameSuggestions, typeSuggestions, helper) - constructor(project: Project, - editor: Editor, - introduceParameterDescriptor: IntroduceParameterDescriptor, - lambdaExtractionDescriptor: ExtractableCodeDescriptor, - helper: KotlinIntroduceParameterHelper + constructor( + project: Project, + editor: Editor, + introduceParameterDescriptor: IntroduceParameterDescriptor, + lambdaExtractionDescriptor: ExtractableCodeDescriptor, + helper: KotlinIntroduceParameterHelper ) : this( - project, - editor, - introduceParameterDescriptor, - lambdaExtractionDescriptor, - lambdaExtractionDescriptor.suggestedNames.toTypedArray(), - listOf(lambdaExtractionDescriptor.returnType), - helper + project, + editor, + introduceParameterDescriptor, + lambdaExtractionDescriptor, + lambdaExtractionDescriptor.suggestedNames.toTypedArray(), + listOf(lambdaExtractionDescriptor.returnType), + helper ) - private val typeNameSuggestions = typeSuggestions - .map { IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderType(it) } - .toTypedArray() + private val typeNameSuggestions = + typeSuggestions.map { IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderType(it) }.toTypedArray() private val nameField = NameSuggestionsField(nameSuggestions, project, KotlinFileType.INSTANCE) private val typeField = NameSuggestionsField(typeNameSuggestions, project, KotlinFileType.INSTANCE) @@ -151,8 +140,9 @@ class KotlinIntroduceParameterDialog private constructor( gbConstraints.fill = GridBagConstraints.BOTH panel.add(typeField, gbConstraints) - if (lambdaExtractionDescriptor != null - && (lambdaExtractionDescriptor.parameters.isNotEmpty() || lambdaExtractionDescriptor.receiverParameter != null)) { + if (lambdaExtractionDescriptor != null && (lambdaExtractionDescriptor.parameters + .isNotEmpty() || lambdaExtractionDescriptor.receiverParameter != null) + ) { val parameterTablePanel = object : ExtractFunctionParameterTablePanel() { override fun onEnterAction() { doOKAction() @@ -264,19 +254,19 @@ class KotlinIntroduceParameterDialog private constructor( lambdaExtractionDescriptor?.let { oldDescriptor -> val newDescriptor = KotlinExtractFunctionDialog.createNewDescriptor( - oldDescriptor, - chosenName, - null, - parameterTablePanel?.selectedReceiverInfo, - parameterTablePanel?.selectedParameterInfos ?: listOf(), - null + oldDescriptor, + chosenName, + null, + parameterTablePanel?.selectedReceiverInfo, + parameterTablePanel?.selectedParameterInfos ?: listOf(), + null ) val options = ExtractionGeneratorOptions.DEFAULT.copy( - target = ExtractionTarget.FAKE_LAMBDALIKE_FUNCTION, - allowExpressionBody = false + target = ExtractionTarget.FAKE_LAMBDALIKE_FUNCTION, + allowExpressionBody = false ) runWriteAction { - with (ExtractionGeneratorConfiguration(newDescriptor, options).generateDeclaration()) { + with(ExtractionGeneratorConfiguration(newDescriptor, options).generateDeclaration()) { val function = declaration as KtFunction val receiverType = function.receiverTypeReference?.text val parameterTypes = function @@ -296,24 +286,23 @@ class KotlinIntroduceParameterDialog private constructor( } val descriptorToRefactor = descriptor.copy( - newParameterName = chosenName, - newParameterTypeText = chosenType, - argumentValue = newArgumentValue, - withDefaultValue = defaultValueCheckBox!!.isSelected, - occurrencesToReplace = with(descriptor) { - if (replaceAllCheckBox?.isSelected ?: true) { - occurrencesToReplace - } - else { - Collections.singletonList(originalOccurrence) - } - }, - parametersToRemove = removeParamsCheckBoxes.filter { it.key.isEnabled && it.key.isSelected }.map { it.value }, - occurrenceReplacer = newReplacer + newParameterName = chosenName, + newParameterTypeText = chosenType, + argumentValue = newArgumentValue, + withDefaultValue = defaultValueCheckBox!!.isSelected, + occurrencesToReplace = with(descriptor) { + if (replaceAllCheckBox?.isSelected != false) { + occurrencesToReplace + } else { + Collections.singletonList(originalOccurrence) + } + }, + parametersToRemove = removeParamsCheckBoxes.filter { it.key.isEnabled && it.key.isSelected }.map { it.value }, + occurrenceReplacer = newReplacer ) helper.configure(descriptorToRefactor).performRefactoring( - onExit = { FinishMarkAction.finish(myProject, editor, startMarkAction) } + onExit = { FinishMarkAction.finish(myProject, editor, startMarkAction) } ) } } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceParameter/KotlinIntroduceParameterHandler.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceParameter/KotlinIntroduceParameterHandler.kt index 48d486532ac..bbf915ee41f 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceParameter/KotlinIntroduceParameterHandler.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceParameter/KotlinIntroduceParameterHandler.kt @@ -310,7 +310,8 @@ open class KotlinIntroduceParameterHandler( callable = targetParent, callableDescriptor = functionDescriptor, newParameterName = suggestedNames.first().quoteIfNeeded(), - newParameterTypeText = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderType(replacementType), + newParameterTypeText = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS + .renderType(replacementType), argumentValue = originalExpression, withDefaultValue = false, parametersUsages = parametersUsages, diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceParameter/KotlinIntroduceParameterMethodUsageProcessor.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceParameter/KotlinIntroduceParameterMethodUsageProcessor.kt index a12b217f1c9..94aa45dc9b8 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceParameter/KotlinIntroduceParameterMethodUsageProcessor.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceParameter/KotlinIntroduceParameterMethodUsageProcessor.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.introduce.introduceParameter @@ -30,12 +19,12 @@ import org.jetbrains.kotlin.idea.KotlinFileType import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaMethodDescriptor import org.jetbrains.kotlin.idea.j2k.j2k -import org.jetbrains.kotlin.idea.refactoring.dropOverrideKeywordIfNecessary import org.jetbrains.kotlin.idea.refactoring.changeSignature.* import org.jetbrains.kotlin.idea.refactoring.changeSignature.usages.KotlinCallableDefinitionUsage import org.jetbrains.kotlin.idea.refactoring.changeSignature.usages.KotlinConstructorDelegationCallUsage import org.jetbrains.kotlin.idea.refactoring.changeSignature.usages.KotlinFunctionCallUsage import org.jetbrains.kotlin.idea.refactoring.changeSignature.usages.KotlinUsageInfo +import org.jetbrains.kotlin.idea.refactoring.dropOverrideKeywordIfNecessary import org.jetbrains.kotlin.idea.search.declarationsSearch.HierarchySearchRequest import org.jetbrains.kotlin.idea.search.declarationsSearch.searchOverriders import org.jetbrains.kotlin.psi.* @@ -65,10 +54,14 @@ class KotlinIntroduceParameterMethodUsageProcessor : IntroduceParameterMethodUsa // Temporarily assume that the new parameter is of Any type. Actual type is substituted during the signature update phase val defaultValueForCall = (data.parameterInitializer.expression as? PsiExpression)?.j2k() - changeInfo.addParameter(KotlinParameterInfo(callableDescriptor = psiMethodDescriptor, - name = data.parameterName, - originalTypeInfo = KotlinTypeInfo(false, psiMethodDescriptor.builtIns.anyType), - defaultValueForCall = defaultValueForCall)) + changeInfo.addParameter( + KotlinParameterInfo( + callableDescriptor = psiMethodDescriptor, + name = data.parameterName, + originalTypeInfo = KotlinTypeInfo(false, psiMethodDescriptor.builtIns.anyType), + defaultValueForCall = defaultValueForCall + ) + ) return changeInfo } @@ -83,12 +76,13 @@ class KotlinIntroduceParameterMethodUsageProcessor : IntroduceParameterMethodUsa val scope = element.useScope.let { if (it is GlobalSearchScope) GlobalSearchScope.getScopeRestrictedByFileTypes(it, KotlinFileType.INSTANCE) else it } - val kotlinFunctions = HierarchySearchRequest(element, scope) - .searchOverriders() - .map { it.unwrapped } - .filterIsInstance() + val kotlinFunctions = HierarchySearchRequest(element, scope).searchOverriders().map { it.unwrapped }.filterIsInstance() return (kotlinFunctions + element).all { - KotlinCallableDefinitionUsage(it, changeInfo.originalBaseFunctionDescriptor, null, null, false).processUsage(changeInfo, it, usages) + KotlinCallableDefinitionUsage(it, changeInfo.originalBaseFunctionDescriptor, null, null, false).processUsage( + changeInfo, + it, + usages + ) }.apply { dropOverrideKeywordIfNecessary(element) } @@ -102,8 +96,7 @@ class KotlinIntroduceParameterMethodUsageProcessor : IntroduceParameterMethodUsa val delegateUsage = if (callElement is KtConstructorDelegationCall) { @Suppress("UNCHECKED_CAST") (KotlinConstructorDelegationCallUsage(callElement, changeInfo) as KotlinUsageInfo) - } - else { + } else { KotlinFunctionCallUsage(callElement, changeInfo.methodDescriptor.originalPrimaryCallable) } return delegateUsage.processUsage(changeInfo, callElement, usages) diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceProperty/IntroducePropertyAction.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceProperty/IntroducePropertyAction.kt index 4ba2b727675..2d10bdc4894 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceProperty/IntroducePropertyAction.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceProperty/IntroducePropertyAction.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.introduce.introduceProperty @@ -23,5 +12,5 @@ import org.jetbrains.kotlin.idea.refactoring.introduce.AbstractIntroduceAction class IntroducePropertyAction : AbstractIntroduceAction() { override fun getRefactoringHandler(provider: RefactoringSupportProvider): RefactoringActionHandler? = - (provider as? KotlinRefactoringSupportProvider)?.getIntroducePropertyHandler() + (provider as? KotlinRefactoringSupportProvider)?.getIntroducePropertyHandler() } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceProperty/KotlinInplacePropertyIntroducer.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceProperty/KotlinInplacePropertyIntroducer.kt index 317eeb9ae81..2e8f60c2159 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceProperty/KotlinInplacePropertyIntroducer.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceProperty/KotlinInplacePropertyIntroducer.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.introduce.introduceProperty @@ -40,16 +29,16 @@ import javax.swing.* import javax.swing.event.PopupMenuEvent class KotlinInplacePropertyIntroducer( - property: KtProperty, - editor: Editor, - project: Project, - title: String, - doNotChangeVar: Boolean, - exprType: KotlinType?, - private var extractionResult: ExtractionResult, - private val availableTargets: List -): KotlinInplaceVariableIntroducer( - property, editor, project, title, KtExpression.EMPTY_ARRAY, null, false, property, false, doNotChangeVar, exprType, false + property: KtProperty, + editor: Editor, + project: Project, + title: String, + doNotChangeVar: Boolean, + exprType: KotlinType?, + private var extractionResult: ExtractionResult, + private val availableTargets: List +) : KotlinInplaceVariableIntroducer( + property, editor, project, title, KtExpression.EMPTY_ARRAY, null, false, property, false, doNotChangeVar, exprType, false ) { init { assert(availableTargets.isNotEmpty()) { "No targets available: ${property.getElementTextWithContext()}" } @@ -61,7 +50,7 @@ class KotlinInplacePropertyIntroducer( field = value runWriteActionAndRestartRefactoring { - with (extractionResult.config) { + with(extractionResult.config) { extractionResult = copy(generatorOptions = generatorOptions.copy(target = currentTarget)).generateDeclaration(property) property = extractionResult.declaration as KtProperty myElementToRename = property @@ -83,33 +72,33 @@ class KotlinInplacePropertyIntroducer( override fun initPanelControls() { if (availableTargets.size > 1) { addPanelControl( - ControlWrapper { - val propertyKindComboBox = with(JComboBox(availableTargets.map { it.targetName.capitalize() }.toTypedArray())) { - addPopupMenuListener( - object : PopupMenuListenerAdapter() { - override fun popupMenuWillBecomeInvisible(e: PopupMenuEvent?) { - ApplicationManager.getApplication().invokeLater { - currentTarget = availableTargets[selectedIndex] - } - } + ControlWrapper { + val propertyKindComboBox = with(JComboBox(availableTargets.map { it.targetName.capitalize() }.toTypedArray())) { + addPopupMenuListener( + object : PopupMenuListenerAdapter() { + override fun popupMenuWillBecomeInvisible(e: PopupMenuEvent?) { + ApplicationManager.getApplication().invokeLater { + currentTarget = availableTargets[selectedIndex] } - ) + } + } + ) - selectedIndex = availableTargets.indexOf(currentTarget) + selectedIndex = availableTargets.indexOf(currentTarget) - this - } - - val propertyKindLabel = JLabel("Introduce as: ") - propertyKindLabel.setDisplayedMnemonic('I') - propertyKindLabel.labelFor = propertyKindComboBox - - val panel = JPanel() - panel.add(propertyKindLabel) - panel.add(propertyKindComboBox) - - panel + this } + + val propertyKindLabel = JLabel("Introduce as: ") + propertyKindLabel.setDisplayedMnemonic('I') + propertyKindLabel.labelFor = propertyKindComboBox + + val panel = JPanel() + panel.add(propertyKindLabel) + panel.add(propertyKindComboBox) + + panel + } ) } @@ -117,7 +106,7 @@ class KotlinInplacePropertyIntroducer( val condition = { isInitializer() } createVarCheckBox?.let { - val initializer = object: Pass() { + val initializer = object : Pass() { override fun pass(t: JComponent) { (t as JCheckBox).isSelected = property.isVar } @@ -125,7 +114,7 @@ class KotlinInplacePropertyIntroducer( addPanelControl(ControlWrapper(it, condition, initializer)) } createExplicitTypeCheckBox?.let { - val initializer = object: Pass() { + val initializer = object : Pass() { override fun pass(t: JComponent) { (t as JCheckBox).isSelected = property.typeReference != null } @@ -137,13 +126,13 @@ class KotlinInplacePropertyIntroducer( val occurrenceCount = extractionResult.duplicateReplacers.size if (occurrenceCount > 1) { addPanelControl( - ControlWrapper { - val replaceAllCheckBox = NonFocusableCheckBox("Replace all occurrences ($occurrenceCount)") - replaceAllCheckBox.isSelected = replaceAll - replaceAllCheckBox.setMnemonic('R') - replaceAllCheckBox.addActionListener { replaceAll = replaceAllCheckBox.isSelected } - replaceAllCheckBox - } + ControlWrapper { + val replaceAllCheckBox = NonFocusableCheckBox("Replace all occurrences ($occurrenceCount)") + replaceAllCheckBox.isSelected = replaceAll + replaceAllCheckBox.setMnemonic('R') + replaceAllCheckBox.addActionListener { replaceAll = replaceAllCheckBox.isSelected } + replaceAllCheckBox + } ) } } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceTypeAlias/IntroduceTypeAliasHandler.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceTypeAlias/IntroduceTypeAliasHandler.kt index 3d4d1db44a3..ebfc9122e30 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceTypeAlias/IntroduceTypeAliasHandler.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceTypeAlias/IntroduceTypeAliasHandler.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.introduce.introduceTypeAlias @@ -48,16 +37,20 @@ open class KotlinIntroduceTypeAliasHandler : RefactoringActionHandler { val INSTANCE = KotlinIntroduceTypeAliasHandler() } - private fun selectElements(editor: Editor, file: KtFile, continuation: (elements: List, targetSibling: PsiElement) -> Unit) { + private fun selectElements( + editor: Editor, + file: KtFile, + continuation: (elements: List, targetSibling: PsiElement) -> Unit + ) { selectElementsWithTargetSibling( - REFACTORING_NAME, - editor, - file, - "Select target code block", - listOf(TYPE_ELEMENT, TYPE_CONSTRUCTOR), - { null }, - { _, parent -> listOf(parent.containingFile) }, - continuation + REFACTORING_NAME, + editor, + file, + "Select target code block", + listOf(TYPE_ELEMENT, TYPE_CONSTRUCTOR), + { null }, + { _, parent -> listOf(parent.containingFile) }, + continuation ) } @@ -71,11 +64,11 @@ open class KotlinIntroduceTypeAliasHandler : RefactoringActionHandler { } open fun doInvoke( - project: Project, - editor: Editor, - elements: List, - targetSibling: PsiElement, - descriptorSubstitutor: ((IntroduceTypeAliasDescriptor) -> IntroduceTypeAliasDescriptor)? = null + project: Project, + editor: Editor, + elements: List, + targetSibling: PsiElement, + descriptorSubstitutor: ((IntroduceTypeAliasDescriptor) -> IntroduceTypeAliasDescriptor)? = null ) { val elementToExtract = elements.singleOrNull() @@ -90,7 +83,11 @@ open class KotlinIntroduceTypeAliasHandler : RefactoringActionHandler { val introduceData = when (elementToExtract) { is KtTypeElement -> IntroduceTypeAliasData(elementToExtract, targetSibling) - else -> IntroduceTypeAliasData(elementToExtract!!.getStrictParentOfType() ?: elementToExtract as KtElement, targetSibling, true) + else -> IntroduceTypeAliasData( + elementToExtract!!.getStrictParentOfType() ?: elementToExtract as KtElement, + targetSibling, + true + ) } val analysisResult = introduceData.analyze() when (analysisResult) { @@ -103,9 +100,14 @@ open class KotlinIntroduceTypeAliasHandler : RefactoringActionHandler { if (ApplicationManager.getApplication().isUnitTestMode) { val (descriptor, conflicts) = descriptorSubstitutor!!(originalDescriptor).validate() project.checkConflictsInteractively(conflicts) { runRefactoring(descriptor, project, editor) } - } - else { - KotlinIntroduceTypeAliasDialog(project, originalDescriptor) { runRefactoring(it.currentDescriptor, project, editor) }.show() + } else { + KotlinIntroduceTypeAliasDialog(project, originalDescriptor) { + runRefactoring( + it.currentDescriptor, + project, + editor + ) + }.show() } } } @@ -136,6 +138,6 @@ class IntroduceTypeAliasAction : AbstractIntroduceAction() { override fun isAvailableOnElementInEditorAndFile(element: PsiElement, editor: Editor, file: PsiFile, context: DataContext): Boolean { return super.isAvailableOnElementInEditorAndFile(element, editor, file, context) && - (ModuleUtil.findModuleForPsiElement(file)?.languageVersionSettings?.supportsFeature(LanguageFeature.TypeAliases) ?: false) + (ModuleUtil.findModuleForPsiElement(file)?.languageVersionSettings?.supportsFeature(LanguageFeature.TypeAliases) ?: false) } } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceTypeAlias/ui/IntroduceTypeAliasParameterTablePanel.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceTypeAlias/ui/IntroduceTypeAliasParameterTablePanel.kt index 9d2d6d7ddb7..2bc732481d6 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceTypeAlias/ui/IntroduceTypeAliasParameterTablePanel.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceTypeAlias/ui/IntroduceTypeAliasParameterTablePanel.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.introduce.introduceTypeAlias.ui @@ -20,9 +9,10 @@ import org.jetbrains.kotlin.idea.refactoring.introduce.introduceTypeAlias.TypePa import org.jetbrains.kotlin.idea.refactoring.introduce.ui.AbstractParameterTablePanel import java.util.* -open class IntroduceTypeAliasParameterTablePanel : AbstractParameterTablePanel() { +open class IntroduceTypeAliasParameterTablePanel : + AbstractParameterTablePanel() { class TypeParameterInfo( - originalParameter: TypeParameter + originalParameter: TypeParameter ) : AbstractParameterTablePanel.AbstractParameterInfo(originalParameter) { init { name = originalParameter.name diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceTypeParameter/KotlinIntroduceTypeParameterHandler.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceTypeParameter/KotlinIntroduceTypeParameterHandler.kt index 1654c0a857c..b57db15ad14 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceTypeParameter/KotlinIntroduceTypeParameterHandler.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceTypeParameter/KotlinIntroduceTypeParameterHandler.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.introduce.introduceTypeParameter @@ -30,9 +19,9 @@ import com.intellij.psi.PsiFile import com.intellij.refactoring.RefactoringActionHandler import com.intellij.usageView.UsageViewTypeLocation import org.jetbrains.kotlin.idea.caches.resolve.analyze -import org.jetbrains.kotlin.idea.core.util.CodeInsightUtils import org.jetbrains.kotlin.idea.core.CollectingNameValidator import org.jetbrains.kotlin.idea.core.KotlinNameSuggester +import org.jetbrains.kotlin.idea.core.util.CodeInsightUtils import org.jetbrains.kotlin.idea.quickfix.createFromUsage.createTypeParameter.CreateTypeParameterByUnresolvedRefActionFactory import org.jetbrains.kotlin.idea.quickfix.createFromUsage.createTypeParameter.CreateTypeParameterFromUsageFix import org.jetbrains.kotlin.idea.quickfix.createFromUsage.createTypeParameter.getPossibleTypeParameterContainers @@ -68,30 +57,30 @@ object KotlinIntroduceTypeParameterHandler : RefactoringActionHandler { fun selectElements(editor: Editor, file: KtFile, continuation: (elements: List, targetParent: PsiElement) -> Unit) { selectElementsWithTargetParent( - REFACTORING_NAME, - editor, - file, - "Introduce type parameter to declaration", - listOf(CodeInsightUtils.ElementKind.TYPE_ELEMENT), - { null }, - { _, parent -> getPossibleTypeParameterContainers(parent) }, - continuation + REFACTORING_NAME, + editor, + file, + "Introduce type parameter to declaration", + listOf(CodeInsightUtils.ElementKind.TYPE_ELEMENT), + { null }, + { _, parent -> getPossibleTypeParameterContainers(parent) }, + continuation ) } fun doInvoke(project: Project, editor: Editor, elements: List, targetParent: PsiElement) { val targetOwner = targetParent as KtTypeParameterListOwner - val typeElementToExtract = elements.singleOrNull() as? KtTypeElement - ?: return showErrorHint(project, editor, "No type to refactor", REFACTORING_NAME) + val typeElementToExtract = + elements.singleOrNull() as? KtTypeElement ?: return showErrorHint(project, editor, "No type to refactor", REFACTORING_NAME) val typeElementToExtractPointer = typeElementToExtract.createSmartPointer() val scope = targetOwner.getResolutionScope() val suggestedNames = KotlinNameSuggester.suggestNamesForTypeParameters( - 1, - CollectingNameValidator(targetOwner.typeParameters.mapNotNull { it.name }) { - scope.findClassifier(Name.identifier(it), NoLookupLocation.FROM_IDE) == null - } + 1, + CollectingNameValidator(targetOwner.typeParameters.mapNotNull { it.name }) { + scope.findClassifier(Name.identifier(it), NoLookupLocation.FROM_IDE) == null + } ) val defaultName = suggestedNames.single() @@ -99,16 +88,17 @@ object KotlinIntroduceTypeParameterHandler : RefactoringActionHandler { val originalType = typeElementToExtract.getAbbreviatedTypeOrType(context) val createTypeParameterData = - CreateTypeParameterByUnresolvedRefActionFactory.extractFixData(typeElementToExtract, defaultName)?.let { - it.copy(typeParameters = listOf(it.typeParameters.single().copy(upperBoundType = originalType)), declaration = targetOwner) - } ?: return showErrorHint(project, editor, "Refactoring is not applicable in the current context", REFACTORING_NAME) + CreateTypeParameterByUnresolvedRefActionFactory.extractFixData(typeElementToExtract, defaultName)?.let { + it.copy(typeParameters = listOf(it.typeParameters.single().copy(upperBoundType = originalType)), declaration = targetOwner) + } ?: return showErrorHint(project, editor, "Refactoring is not applicable in the current context", REFACTORING_NAME) project.executeCommand(REFACTORING_NAME) { - val newTypeParameter = CreateTypeParameterFromUsageFix(typeElementToExtract, createTypeParameterData, false).doInvoke().singleOrNull() - ?: return@executeCommand + val newTypeParameter = + CreateTypeParameterFromUsageFix(typeElementToExtract, createTypeParameterData, false).doInvoke().singleOrNull() + ?: return@executeCommand val newTypeParameterPointer = newTypeParameter.createSmartPointer() - val postRename = postRename@ { + val postRename = postRename@{ val restoredTypeParameter = newTypeParameterPointer.element ?: return@postRename val restoredOwner = restoredTypeParameter.getStrictParentOfType() ?: return@postRename val restoredOriginalTypeElement = typeElementToExtractPointer.element ?: return@postRename @@ -132,16 +122,19 @@ object KotlinIntroduceTypeParameterHandler : RefactoringActionHandler { } processDuplicates( - duplicateRanges.keysToMap { - { - it.elements.singleOrNull()?.replace(parameterRefElement) - Unit - } - }, - project, - editor, - ElementDescriptionUtil.getElementDescription(restoredOwner, UsageViewTypeLocation.INSTANCE) + " '${restoredOwner.name}'", - "a reference to extracted type parameter" + duplicateRanges.keysToMap { + { + it.elements.singleOrNull()?.replace(parameterRefElement) + Unit + } + }, + project, + editor, + ElementDescriptionUtil.getElementDescription( + restoredOwner, + UsageViewTypeLocation.INSTANCE + ) + " '${restoredOwner.name}'", + "a reference to extracted type parameter" ) restoredTypeParameter.extendsBound?.let { @@ -151,13 +144,14 @@ object KotlinIntroduceTypeParameterHandler : RefactoringActionHandler { } if (!ApplicationManager.getApplication().isUnitTestMode) { - val dataContext = SimpleDataContext.getSimpleContext(CommonDataKeys.PSI_ELEMENT.name, newTypeParameter, - (editor as? EditorEx)?.dataContext) + val dataContext = SimpleDataContext.getSimpleContext( + CommonDataKeys.PSI_ELEMENT.name, newTypeParameter, + (editor as? EditorEx)?.dataContext + ) editor.selectionModel.removeSelection() editor.caretModel.moveToOffset(newTypeParameter.startOffset) VariableInplaceRenameHandlerWithFinishHook(postRename).doRename(newTypeParameter, editor, dataContext) - } - else { + } else { postRename() } } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceVariable/KotlinIntroduceVariableHandler.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceVariable/KotlinIntroduceVariableHandler.kt index d3fae346459..296cbe0a7ec 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceVariable/KotlinIntroduceVariableHandler.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceVariable/KotlinIntroduceVariableHandler.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.introduce.introduceVariable @@ -39,8 +28,8 @@ import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor import org.jetbrains.kotlin.idea.analysis.analyzeInContext import org.jetbrains.kotlin.idea.analysis.computeTypeInfoInContext import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade -import org.jetbrains.kotlin.idea.core.util.CodeInsightUtils import org.jetbrains.kotlin.idea.core.* +import org.jetbrains.kotlin.idea.core.util.CodeInsightUtils import org.jetbrains.kotlin.idea.intentions.ConvertToBlockBodyIntention import org.jetbrains.kotlin.idea.refactoring.* import org.jetbrains.kotlin.idea.refactoring.introduce.* @@ -97,17 +86,17 @@ object KotlinIntroduceVariableHandler : RefactoringActionHandler { } private class IntroduceVariableContext( - private val expression: KtExpression, - private val nameSuggestions: List>, - private val allReplaces: List, - private val commonContainer: PsiElement, - private val commonParent: PsiElement, - private val replaceOccurrence: Boolean, - private val noTypeInference: Boolean, - private val expressionType: KotlinType?, - private val componentFunctions: List, - private val bindingContext: BindingContext, - private val resolutionFacade: ResolutionFacade + private val expression: KtExpression, + private val nameSuggestions: List>, + private val allReplaces: List, + private val commonContainer: PsiElement, + private val commonParent: PsiElement, + private val replaceOccurrence: Boolean, + private val noTypeInference: Boolean, + private val expressionType: KotlinType?, + private val componentFunctions: List, + private val bindingContext: BindingContext, + private val resolutionFacade: ResolutionFacade ) { private val psiFactory = KtPsiFactory(expression) @@ -148,11 +137,11 @@ object KotlinIntroduceVariableHandler : RefactoringActionHandler { } private fun runRefactoring( - isVar: Boolean, - expression: KtExpression, - commonContainer: PsiElement, - commonParent: PsiElement, - allReplaces: List + isVar: Boolean, + expression: KtExpression, + commonContainer: PsiElement, + commonParent: PsiElement, + allReplaces: List ) { val initializer = (expression as? KtParenthesizedExpression)?.expression ?: expression val initializerText = if (initializer.mustBeParenthesizedInInitializerPosition()) "(${initializer.text})" else initializer.text @@ -165,8 +154,7 @@ object KotlinIntroduceVariableHandler : RefactoringActionHandler { append(" = ") append(initializerText) }.let { psiFactory.createDestructuringDeclaration(it) } - } - else { + } else { buildString { append("$varOvVal ") append(nameSuggestions.asSequence().single().first()) @@ -184,8 +172,7 @@ object KotlinIntroduceVariableHandler : RefactoringActionHandler { if (!needBraces) { property = commonContainer.addBefore(property, anchor) as KtDeclaration commonContainer.addBefore(psiFactory.createNewLine(), anchor) - } - else { + } else { var emptyBody: KtExpression = psiFactory.createEmptyBody() val firstChild = emptyBody.firstChild emptyBody.addAfter(psiFactory.createNewLine(), firstChild) @@ -205,8 +192,7 @@ object KotlinIntroduceVariableHandler : RefactoringActionHandler { if (body != null) { oldElement = body } - } - else if (commonContainer is KtContainerNode) { + } else if (commonContainer is KtContainerNode) { val children = commonContainer.children for (child in children) { if (child is KtExpression) { @@ -236,16 +222,15 @@ object KotlinIntroduceVariableHandler : RefactoringActionHandler { } emptyBody.accept( - object : KtTreeVisitorVoid() { - override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { - if (!expression.isOccurrence) return + object : KtTreeVisitorVoid() { + override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { + if (!expression.isOccurrence) return - expression.isOccurrence = false - references.add(SmartPointerManager.createPointer(expression)) - } - }) - } - else { + expression.isOccurrence = false + references.add(SmartPointerManager.createPointer(expression)) + } + }) + } else { val parent = anchor.parent val copyTo = parent.lastChild val copyFrom = anchor.nextSibling @@ -283,13 +268,11 @@ object KotlinIntroduceVariableHandler : RefactoringActionHandler { if (if (i != 0) replaceOccurrence else replace.shouldReplaceOccurrence(bindingContext, commonContainer)) { replaceExpression(replace, true) - } - else { + } else { val sibling = PsiTreeUtil.skipSiblingsBackward(replace, PsiWhiteSpace::class.java) if (sibling == property) { replace.parent.deleteChildRange(property.nextSibling, replace) - } - else { + } else { replace.delete() } } @@ -302,7 +285,13 @@ object KotlinIntroduceVariableHandler : RefactoringActionHandler { } fun runRefactoring(isVar: Boolean) { - if (commonContainer !is KtDeclarationWithBody) return runRefactoring(isVar, expression, commonContainer, commonParent, allReplaces) + if (commonContainer !is KtDeclarationWithBody) return runRefactoring( + isVar, + expression, + commonContainer, + commonParent, + allReplaces + ) commonContainer.bodyExpression.sure { "Original body is not found: " + commonContainer } @@ -333,7 +322,8 @@ object KotlinIntroduceVariableHandler : RefactoringActionHandler { private fun calculateAnchor(commonParent: PsiElement, commonContainer: PsiElement, allReplaces: List): PsiElement? { if (commonParent != commonContainer) return commonParent.parentsWithSelf.firstOrNull { it.parent == commonContainer } - val startOffset = allReplaces.fold(commonContainer.endOffset) { offset, expr -> min(offset, expr.substringContextOrThis.startOffset) } + val startOffset = + allReplaces.fold(commonContainer.endOffset) { offset, expr -> min(offset, expr.substringContextOrThis.startOffset) } return commonContainer.allChildren.lastOrNull { it.textRange.contains(startOffset) } ?: return null } @@ -342,19 +332,17 @@ object KotlinIntroduceVariableHandler : RefactoringActionHandler { } private fun KtExpression.findOccurrences(occurrenceContainer: PsiElement): List { - return toRange() - .match(occurrenceContainer, KotlinPsiUnifier.DEFAULT) - .mapNotNull { - val candidate = it.range.elements.first() + return toRange().match(occurrenceContainer, KotlinPsiUnifier.DEFAULT).mapNotNull { + val candidate = it.range.elements.first() - if (candidate.isAssignmentLHS()) return@mapNotNull null + if (candidate.isAssignmentLHS()) return@mapNotNull null - when (candidate) { - is KtExpression -> candidate - is KtStringTemplateEntryWithExpression -> candidate.expression - else -> throw AssertionError("Unexpected candidate element: " + candidate.text) - } - } + when (candidate) { + is KtExpression -> candidate + is KtStringTemplateEntryWithExpression -> candidate.expression + else -> throw AssertionError("Unexpected candidate element: " + candidate.text) + } + } } private fun KtExpression.shouldReplaceOccurrence(bindingContext: BindingContext, container: PsiElement?): Boolean { @@ -409,20 +397,20 @@ object KotlinIntroduceVariableHandler : RefactoringActionHandler { } private fun KtExpression.chooseApplicableComponentFunctionsForVariableDeclaration( - haveOccurrencesToReplace: Boolean, - editor: Editor?, - callback: (List) -> Unit + haveOccurrencesToReplace: Boolean, + editor: Editor?, + callback: (List) -> Unit ) { if (haveOccurrencesToReplace) return callback(emptyList()) return chooseApplicableComponentFunctions(this, editor, callback = callback) } private fun executeMultiDeclarationTemplate( - project: Project, - editor: Editor, - declaration: KtDestructuringDeclaration, - suggestedNames: List>, - postProcess: (KtDeclaration) -> Unit + project: Project, + editor: Editor, + declaration: KtDestructuringDeclaration, + suggestedNames: List>, + postProcess: (KtDeclaration) -> Unit ) { StartMarkAction.canStart(project)?.let { return } @@ -445,39 +433,39 @@ object KotlinIntroduceVariableHandler : RefactoringActionHandler { project.executeWriteCommand(INTRODUCE_VARIABLE) { TemplateManager.getInstance(project).startTemplate( - editor, - builder.buildInlineTemplate(), - object: TemplateEditingAdapter() { - private fun finishMarkAction() { - FinishMarkAction.finish(project, editor, startMarkAction) - } - - override fun templateFinished(template: Template, brokenOff: Boolean) { - if (!brokenOff) { - postProcess(declaration) - } - finishMarkAction() - } - - override fun templateCancelled(template: Template?) { - finishMarkAction() - } + editor, + builder.buildInlineTemplate(), + object : TemplateEditingAdapter() { + private fun finishMarkAction() { + FinishMarkAction.finish(project, editor, startMarkAction) } + + override fun templateFinished(template: Template, brokenOff: Boolean) { + if (!brokenOff) { + postProcess(declaration) + } + finishMarkAction() + } + + override fun templateCancelled(template: Template?) { + finishMarkAction() + } + } ) } } private fun doRefactoring( - project: Project, - editor: Editor?, - expression: KtExpression, - container: KtElement, - occurrenceContainer: KtElement, - resolutionFacade: ResolutionFacade, - bindingContext: BindingContext, - isVar: Boolean, - occurrencesToReplace: List?, - onNonInteractiveFinish: ((KtDeclaration) -> Unit)? + project: Project, + editor: Editor?, + expression: KtExpression, + container: KtElement, + occurrenceContainer: KtElement, + resolutionFacade: ResolutionFacade, + bindingContext: BindingContext, + isVar: Boolean, + occurrencesToReplace: List?, + onNonInteractiveFinish: ((KtDeclaration) -> Unit)? ) { val substringInfo = expression.extractableSubstringInfo val physicalExpression = expression.substringContextOrThis @@ -496,12 +484,14 @@ object KotlinIntroduceVariableHandler : RefactoringActionHandler { return showErrorHint(project, editor, KotlinRefactoringBundle.message("cannot.refactor.no.expression")) } - PsiTreeUtil.getNonStrictParentOfType(physicalExpression, - KtTypeReference::class.java, - KtConstructorCalleeExpression::class.java, - KtSuperExpression::class.java, - KtConstructorDelegationReferenceExpression::class.java, - KtAnnotationEntry::class.java)?.let { + PsiTreeUtil.getNonStrictParentOfType( + physicalExpression, + KtTypeReference::class.java, + KtConstructorCalleeExpression::class.java, + KtSuperExpression::class.java, + KtConstructorDelegationReferenceExpression::class.java, + KtAnnotationEntry::class.java + )?.let { return showErrorHint(project, editor, KotlinRefactoringBundle.message("cannot.refactor.no.container")) } @@ -511,7 +501,7 @@ object KotlinIntroduceVariableHandler : RefactoringActionHandler { val bindingTrace = ObservableBindingTrace(BindingTraceContext()) val typeNoExpectedType = substringInfo?.type - ?: physicalExpression.computeTypeInfoInContext(scope, physicalExpression, bindingTrace, dataFlowInfo).type + ?: physicalExpression.computeTypeInfoInContext(scope, physicalExpression, bindingTrace, dataFlowInfo).type val noTypeInference = expressionType != null && typeNoExpectedType != null && !TypeCheckerImpl(project).equalTypes(expressionType, typeNoExpectedType) @@ -527,8 +517,8 @@ object KotlinIntroduceVariableHandler : RefactoringActionHandler { val typeArgumentList = getQualifiedTypeArgumentList(KtPsiUtil.safeDeparenthesize(physicalExpression)) val isInplaceAvailable = editor != null - && editor.settings.isVariableInplaceRenameEnabled - && !ApplicationManager.getApplication().isUnitTestMode + && editor.settings.isVariableInplaceRenameEnabled + && !ApplicationManager.getApplication().isUnitTestMode val allOccurrences = occurrencesToReplace ?: expression.findOccurrences(occurrenceContainer) @@ -538,13 +528,12 @@ object KotlinIntroduceVariableHandler : RefactoringActionHandler { else -> listOf(expression) } val replaceOccurrence = substringInfo != null - || expression.shouldReplaceOccurrence(bindingContext, container) - || allReplaces.size > 1 + || expression.shouldReplaceOccurrence(bindingContext, container) + || allReplaces.size > 1 val commonParent = if (allReplaces.isNotEmpty()) { PsiTreeUtil.findCommonParent(allReplaces.map { it.substringContextOrThis }) as KtElement - } - else { + } else { expression.parent as KtElement } var commonContainer = commonParent as? KtFile ?: commonParent.getContainer()!! @@ -555,10 +544,10 @@ object KotlinIntroduceVariableHandler : RefactoringActionHandler { fun postProcess(declaration: KtDeclaration) { if (typeArgumentList != null) { val initializer = when (declaration) { - is KtProperty -> declaration.initializer - is KtDestructuringDeclaration -> declaration.initializer - else -> null - } ?: return + is KtProperty -> declaration.initializer + is KtDestructuringDeclaration -> declaration.initializer + else -> null + } ?: return runWriteAction { addTypeArgumentsIfNeeded(initializer, typeArgumentList) } } @@ -569,26 +558,27 @@ object KotlinIntroduceVariableHandler : RefactoringActionHandler { physicalExpression.chooseApplicableComponentFunctionsForVariableDeclaration(replaceOccurrence, editor) { componentFunctions -> val validator = NewDeclarationNameValidator( - commonContainer, - calculateAnchor(commonParent, commonContainer, allReplaces), - NewDeclarationNameValidator.Target.VARIABLES + commonContainer, + calculateAnchor(commonParent, commonContainer, allReplaces), + NewDeclarationNameValidator.Target.VARIABLES ) val suggestedNames = if (componentFunctions.isNotEmpty()) { val collectingValidator = CollectingNameValidator(filter = validator) componentFunctions.map { suggestNamesForComponent(it, project, collectingValidator) } - } - else { - KotlinNameSuggester.suggestNamesByExpressionAndType(expression, - substringInfo?.type, - bindingContext, - validator, - "value").let(::listOf) + } else { + KotlinNameSuggester.suggestNamesByExpressionAndType( + expression, + substringInfo?.type, + bindingContext, + validator, + "value" + ).let(::listOf) } val introduceVariableContext = IntroduceVariableContext( - expression, suggestedNames, allReplaces, commonContainer, commonParent, - replaceOccurrence, noTypeInference, expressionType, componentFunctions, bindingContext, resolutionFacade + expression, suggestedNames, allReplaces, commonContainer, commonParent, + replaceOccurrence, noTypeInference, expressionType, componentFunctions, bindingContext, resolutionFacade ) project.executeCommand(INTRODUCE_VARIABLE, null) { @@ -615,17 +605,17 @@ object KotlinIntroduceVariableHandler : RefactoringActionHandler { when (property) { is KtProperty -> { KotlinVariableInplaceIntroducer( - property, - introduceVariableContext.reference?.element, - introduceVariableContext.references.mapNotNull { it.element }.toTypedArray(), - suggestedNames.single(), - isVar, - /*todo*/ false, - expressionType, - noTypeInference, - project, - editor, - ::postProcess + property, + introduceVariableContext.reference?.element, + introduceVariableContext.references.mapNotNull { it.element }.toTypedArray(), + suggestedNames.single(), + isVar, + /*todo*/ false, + expressionType, + noTypeInference, + project, + editor, + ::postProcess ).startInplaceIntroduceTemplate() } @@ -640,7 +630,7 @@ object KotlinIntroduceVariableHandler : RefactoringActionHandler { } if (isInplaceAvailable && occurrencesToReplace == null) { - val chooser = object: OccurrencesChooser(editor) { + val chooser = object : OccurrencesChooser(editor) { override fun getOccurrenceRange(occurrence: KtExpression): TextRange? { return occurrence.extractableSubstringInfo?.contentRange ?: occurrence.textRange } @@ -648,8 +638,7 @@ object KotlinIntroduceVariableHandler : RefactoringActionHandler { ApplicationManager.getApplication().invokeLater { chooser.showChooser(expression, allOccurrences, callback) } - } - else { + } else { callback.pass(OccurrencesChooser.ReplaceChoice.ALL) } } @@ -661,16 +650,16 @@ object KotlinIntroduceVariableHandler : RefactoringActionHandler { } private fun KtExpression.getCandidateContainers( - resolutionFacade: ResolutionFacade, - originalContext: BindingContext + resolutionFacade: ResolutionFacade, + originalContext: BindingContext ): List> { val physicalExpression = substringContextOrThis val contentRange = extractableSubstringInfo?.contentRange val file = physicalExpression.containingKtFile - val references = physicalExpression - .collectDescendantsOfType { contentRange == null || contentRange.contains(it.textRange) } + val references = + physicalExpression.collectDescendantsOfType { contentRange == null || contentRange.contains(it.textRange) } fun isResolvableNextTo(neighbour: KtExpression): Boolean { val scope = neighbour.getResolutionScope(originalContext, resolutionFacade) @@ -681,7 +670,8 @@ object KotlinIntroduceVariableHandler : RefactoringActionHandler { val newDescriptor = newContext[BindingContext.REFERENCE_TARGET, it] if (originalDescriptor is ValueParameterDescriptor - && (originalContext[BindingContext.AUTO_CREATED_IT, originalDescriptor] ?: false)) { + && (originalContext[BindingContext.AUTO_CREATED_IT, originalDescriptor] ?: false) + ) { return@all originalDescriptor.containingDeclaration.source.getPsi().isAncestor(neighbour, true) } @@ -719,15 +709,15 @@ object KotlinIntroduceVariableHandler : RefactoringActionHandler { } fun doRefactoring( - project: Project, - editor: Editor?, - expressionToExtract: KtExpression?, - isVar: Boolean, - occurrencesToReplace: List?, - onNonInteractiveFinish: ((KtDeclaration) -> Unit)? + project: Project, + editor: Editor?, + expressionToExtract: KtExpression?, + isVar: Boolean, + occurrencesToReplace: List?, + onNonInteractiveFinish: ((KtDeclaration) -> Unit)? ) { val expression = expressionToExtract?.let { KtPsiUtil.safeDeparenthesize(it) } - ?: return showErrorHint(project, editor, KotlinRefactoringBundle.message("cannot.refactor.no.expression")) + ?: return showErrorHint(project, editor, KotlinRefactoringBundle.message("cannot.refactor.no.expression")) if (expression.isAssignmentLHS()) { return showErrorHint(project, editor, KotlinRefactoringBundle.message("cannot.refactor.no.expression")) @@ -740,8 +730,8 @@ object KotlinIntroduceVariableHandler : RefactoringActionHandler { fun runWithChosenContainers(container: KtElement, occurrenceContainer: KtElement) { doRefactoring( - project, editor, expression, container, occurrenceContainer, resolutionFacade, bindingContext, - isVar, occurrencesToReplace, onNonInteractiveFinish + project, editor, expression, container, occurrenceContainer, resolutionFacade, bindingContext, + isVar, occurrencesToReplace, onNonInteractiveFinish ) } @@ -769,8 +759,7 @@ object KotlinIntroduceVariableHandler : RefactoringActionHandler { selectElement(editor, file, listOf(CodeInsightUtils.ElementKind.EXPRESSION)) { doRefactoring(project, editor, it as KtExpression?, false, null, null) } - } - catch (e: IntroduceRefactoringException) { + } catch (e: IntroduceRefactoringException) { showErrorHint(project, editor, e.message!!) } } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceVariable/KotlinVariableInplaceIntroducer.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceVariable/KotlinVariableInplaceIntroducer.kt index f96992f4987..3de6108a4bc 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceVariable/KotlinVariableInplaceIntroducer.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceVariable/KotlinVariableInplaceIntroducer.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.introduce.introduceVariable @@ -45,24 +34,24 @@ import java.util.* import javax.swing.JCheckBox class KotlinVariableInplaceIntroducer( - val addedVariable: KtProperty, - originalExpression: KtExpression?, - occurrencesToReplace: Array, - suggestedNames: Collection, - val isVar: Boolean, - val doNotChangeVar: Boolean, - val expressionType: KotlinType?, - val noTypeInference: Boolean, - project: Project, - editor: Editor, - private val postProcess: (KtDeclaration) -> Unit -): AbstractKotlinInplaceIntroducer( - addedVariable, - originalExpression, - occurrencesToReplace, - KotlinIntroduceVariableHandler.INTRODUCE_VARIABLE, - project, - editor + val addedVariable: KtProperty, + originalExpression: KtExpression?, + occurrencesToReplace: Array, + suggestedNames: Collection, + val isVar: Boolean, + val doNotChangeVar: Boolean, + val expressionType: KotlinType?, + val noTypeInference: Boolean, + project: Project, + editor: Editor, + private val postProcess: (KtDeclaration) -> Unit +) : AbstractKotlinInplaceIntroducer( + addedVariable, + originalExpression, + occurrencesToReplace, + KotlinIntroduceVariableHandler.INTRODUCE_VARIABLE, + project, + editor ) { private val suggestedNames = suggestedNames.toTypedArray() private var expressionTypeCheckBox: JCheckBox? = null @@ -95,8 +84,7 @@ class KotlinVariableInplaceIntroducer( updateVariableName() if (isSelected) { addedVariable.typeReference = KtPsiFactory(myProject).createType(renderedType) - } - else { + } else { addedVariable.typeReference = null } } @@ -121,10 +109,12 @@ class KotlinVariableInplaceIntroducer( } } - override fun buildTemplateAndStart(refs: Collection, - stringUsages: Collection>, - scope: PsiElement, - containingFile: PsiFile): Boolean { + override fun buildTemplateAndStart( + refs: Collection, + stringUsages: Collection>, + scope: PsiElement, + containingFile: PsiFile + ): Boolean { myNameSuggestions = myNameSuggestions.mapTo(LinkedHashSet(), String::quoteIfNeeded) myEditor.caretModel.moveToOffset(nameIdentifier!!.startOffset) diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceVariable/introduceVariableUtils.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceVariable/introduceVariableUtils.kt index 298bd2dd70e..5d8d867a588 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceVariable/introduceVariableUtils.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceVariable/introduceVariableUtils.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.introduce.introduceVariable @@ -41,9 +30,9 @@ import org.jetbrains.kotlin.util.isValidOperator import java.util.* private fun getApplicableComponentFunctions( - contextExpression: KtExpression, - receiverType: KotlinType?, - receiverExpression: KtExpression? + contextExpression: KtExpression, + receiverType: KotlinType?, + receiverExpression: KtExpression? ): List { val facade = contextExpression.getResolutionFacade() val context = facade.analyze(contextExpression) @@ -53,32 +42,32 @@ private fun getApplicableComponentFunctions( PrimitiveType.values().mapTo(forbiddenClasses) { builtIns.getPrimitiveArrayClassDescriptor(it) } (receiverType ?: context.getType(contextExpression))?.let { - if ((listOf(it) + it.supertypes()).any { - val fqName = it.constructor.declarationDescriptor?.importableFqName - forbiddenClasses.any { it.fqNameSafe == fqName } - }) return emptyList() + if ((listOf(it) + it.supertypes()).any { type -> + val fqName = type.constructor.declarationDescriptor?.importableFqName + forbiddenClasses.any { descriptor -> descriptor.fqNameSafe == fqName } + } + ) return emptyList() } val scope = contextExpression.getResolutionScope(context, facade) val psiFactory = KtPsiFactory(contextExpression) @Suppress("UNCHECKED_CAST") - return generateSequence(1) { it + 1 } - .map { - val componentCallExpr = psiFactory.createExpressionByPattern("$0.$1", receiverExpression ?: contextExpression, "component$it()") - val newContext = componentCallExpr.analyzeInContext(scope, contextExpression) - componentCallExpr.getResolvedCall(newContext)?.resultingDescriptor as? FunctionDescriptor - } - .takeWhile { it != null && it.isValidOperator() } - .toList() as List + return generateSequence(1) { it + 1 }.map { + val componentCallExpr = psiFactory.createExpressionByPattern("$0.$1", receiverExpression ?: contextExpression, "component$it()") + val newContext = componentCallExpr.analyzeInContext(scope, contextExpression) + componentCallExpr.getResolvedCall(newContext)?.resultingDescriptor as? FunctionDescriptor + } + .takeWhile { it != null && it.isValidOperator() } + .toList() as List } internal fun chooseApplicableComponentFunctions( - contextExpression: KtExpression, - editor: Editor?, - type: KotlinType? = null, - receiverExpression: KtExpression? = null, - callback: (List) -> Unit + contextExpression: KtExpression, + editor: Editor?, + type: KotlinType? = null, + receiverExpression: KtExpression? = null, + callback: (List) -> Unit ) { val functions = getApplicableComponentFunctions(contextExpression, type, receiverExpression) if (functions.size <= 1) return callback(emptyList()) @@ -89,20 +78,20 @@ internal fun chooseApplicableComponentFunctions( val list = JBList("Create single variable", "Create destructuring declaration") JBPopupFactory.getInstance() - .createListPopupBuilder(list) - .setMovable(true) - .setResizable(false) - .setRequestFocus(true) - .setItemChoosenCallback { callback(if (list.selectedIndex == 0) emptyList() else functions) } - .createPopup() - .showInBestPositionFor(editor) + .createListPopupBuilder(list) + .setMovable(true) + .setResizable(false) + .setRequestFocus(true) + .setItemChoosenCallback { callback(if (list.selectedIndex == 0) emptyList() else functions) } + .createPopup() + .showInBestPositionFor(editor) } internal fun suggestNamesForComponent(descriptor: FunctionDescriptor, project: Project, validator: (String) -> Boolean): Set { return LinkedHashSet().apply { val descriptorName = descriptor.name.asString() val componentName = (DescriptorToSourceUtilsIde.getAnyDeclaration(project, descriptor) as? PsiNamedElement)?.name - ?: descriptorName + ?: descriptorName if (componentName == descriptorName) { descriptor.returnType?.let { addAll(KotlinNameSuggester.suggestNamesByType(it, validator)) } } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/ui/AbstractParameterTablePanel.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/ui/AbstractParameterTablePanel.kt index 87b7b426885..85c94acc422 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/ui/AbstractParameterTablePanel.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/ui/AbstractParameterTablePanel.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.introduce.ui @@ -33,7 +22,8 @@ import javax.swing.table.AbstractTableModel import kotlin.math.max import kotlin.math.min -abstract class AbstractParameterTablePanel> : JPanel(BorderLayout()) { +abstract class AbstractParameterTablePanel> : + JPanel(BorderLayout()) { companion object { val CHECKMARK_COLUMN = 0 val PARAMETER_NAME_COLUMN = 1 @@ -75,7 +65,7 @@ abstract class AbstractParameterTablePanel, - role: Role + references: Array, + role: Role ): PsiReferenceList? { val refsText = references.map { it.canonicalText } val refListText = if (refsText.isNotEmpty()) refsText.joinToString() else return null diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/memberInfo/KotlinClassMembersRefactoringSupport.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/memberInfo/KotlinClassMembersRefactoringSupport.kt index c2ca9d5168d..983cab38b19 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/memberInfo/KotlinClassMembersRefactoringSupport.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/memberInfo/KotlinClassMembersRefactoringSupport.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.memberInfo @@ -32,39 +21,39 @@ import org.jetbrains.kotlin.util.findCallableMemberBySignature class KotlinClassMembersRefactoringSupport : ClassMembersRefactoringSupport { override fun isProperMember(memberInfo: MemberInfoBase<*>): Boolean { val member = memberInfo.member - return member is KtNamedFunction - || member is KtProperty - || (member is KtParameter && member.isPropertyParameter()) - || (member is KtClassOrObject && memberInfo.overrides == null) + return member is KtNamedFunction || member is KtProperty || (member is KtParameter && member.isPropertyParameter()) || (member is KtClassOrObject && memberInfo.overrides == null) } override fun createDependentMembersCollector(clazz: Any, superClass: Any?): DependentMembersCollectorBase<*, *> { return object : DependentMembersCollectorBase( - clazz as KtClassOrObject, - superClass as PsiNamedElement? + clazz as KtClassOrObject, + superClass as PsiNamedElement? ) { override fun collect(member: KtNamedDeclaration) { member.accept( - object : KtTreeVisitorVoid() { - private val pullUpData = superClass?.let { KotlinPullUpData(clazz as KtClassOrObject, it as PsiNamedElement, emptyList()) } + object : KtTreeVisitorVoid() { + private val pullUpData = + superClass?.let { KotlinPullUpData(clazz as KtClassOrObject, it as PsiNamedElement, emptyList()) } - private val possibleContainingClasses = - listOf(clazz) + ((clazz as? KtClass)?.companionObjects ?: emptyList()) + private val possibleContainingClasses = + listOf(clazz) + ((clazz as? KtClass)?.companionObjects ?: emptyList()) - override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { - val referencedMember = expression.mainReference.resolve() as? KtNamedDeclaration ?: return - val containingClassOrObject = referencedMember.containingClassOrObject ?: return - if (containingClassOrObject !in possibleContainingClasses) return + override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { + val referencedMember = expression.mainReference.resolve() as? KtNamedDeclaration ?: return + val containingClassOrObject = referencedMember.containingClassOrObject ?: return + if (containingClassOrObject !in possibleContainingClasses) return - if (pullUpData != null) { - val memberDescriptor = referencedMember.unsafeResolveToDescriptor() as? CallableMemberDescriptor ?: return - val memberInSuper = memberDescriptor.substitute(pullUpData.sourceToTargetClassSubstitutor) ?: return - if (pullUpData.targetClassDescriptor.findCallableMemberBySignature(memberInSuper as CallableMemberDescriptor) != null) return - } - - myCollection.add(referencedMember) + if (pullUpData != null) { + val memberDescriptor = referencedMember.unsafeResolveToDescriptor() as? CallableMemberDescriptor ?: return + val memberInSuper = memberDescriptor.substitute(pullUpData.sourceToTargetClassSubstitutor) ?: return + if (pullUpData.targetClassDescriptor + .findCallableMemberBySignature(memberInSuper as CallableMemberDescriptor) != null + ) return } + + myCollection.add(referencedMember) } + } ) } } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/memberInfo/KotlinInterfaceDependencyMemberInfoModel.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/memberInfo/KotlinInterfaceDependencyMemberInfoModel.kt index 9aeac6076b3..579c8d2400d 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/memberInfo/KotlinInterfaceDependencyMemberInfoModel.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/memberInfo/KotlinInterfaceDependencyMemberInfoModel.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.memberInfo @@ -25,7 +14,7 @@ import org.jetbrains.kotlin.psi.KtNamedDeclaration import org.jetbrains.kotlin.utils.ifEmpty class KotlinInterfaceDependencyMemberInfoModel>( - aClass: KtClassOrObject + aClass: KtClassOrObject ) : DependencyMemberInfoModel(KotlinInterfaceMemberDependencyGraph(aClass), MemberInfoModel.WARNING) { init { setTooltipProvider { memberInfo -> diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/memberInfo/KotlinInterfaceMemberDependencyGraph.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/memberInfo/KotlinInterfaceMemberDependencyGraph.kt index 786a4d85048..59a7bb89073 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/memberInfo/KotlinInterfaceMemberDependencyGraph.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/memberInfo/KotlinInterfaceMemberDependencyGraph.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.memberInfo @@ -27,7 +16,7 @@ import org.jetbrains.kotlin.psi.KtNamedDeclaration import java.util.* class KotlinInterfaceMemberDependencyGraph>( - klass: KtClassOrObject + klass: KtClassOrObject ) : MemberDependencyGraph { private val delegateGraph = InterfaceMemberDependencyGraph>(klass.toLightClass()) @@ -39,7 +28,7 @@ class KotlinInterfaceMemberDependencyGraph()) as Set + .filterIsInstanceTo(LinkedHashSet()) as Set @Suppress("UNCHECKED_CAST") override fun getDependenciesOf(member: T): Set { @@ -48,6 +37,6 @@ class KotlinInterfaceMemberDependencyGraph()) as Set + .filterIsInstanceTo(LinkedHashSet()) as Set } } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/memberInfo/KotlinMemberInfo.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/memberInfo/KotlinMemberInfo.kt index 0e44cb96b77..811bca0c4be 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/memberInfo/KotlinMemberInfo.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/memberInfo/KotlinMemberInfo.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.memberInfo @@ -37,9 +26,9 @@ import org.jetbrains.kotlin.renderer.DescriptorRendererModifier import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull class KotlinMemberInfo @JvmOverloads constructor( - member: KtNamedDeclaration, - val isSuperClass: Boolean = false, - val isCompanionMember: Boolean = false + member: KtNamedDeclaration, + val isSuperClass: Boolean = false, + val isCompanionMember: Boolean = false ) : MemberInfoBase(member) { companion object { private val RENDERER = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.withOptions { @@ -55,13 +44,11 @@ class KotlinMemberInfo @JvmOverloads constructor( if (member.isInterfaceClass()) { displayName = RefactoringBundle.message("member.info.implements.0", member.name) overrides = false - } - else { + } else { displayName = RefactoringBundle.message("member.info.extends.0", member.name) overrides = true } - } - else { + } else { displayName = RENDERER.render(memberDescriptor) if (member.hasModifier(KtTokens.ABSTRACT_KEYWORD)) { displayName = "abstract $displayName" diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/memberInfo/KotlinMemberSelectionPanel.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/memberInfo/KotlinMemberSelectionPanel.kt index ef337c24d1e..509809c4161 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/memberInfo/KotlinMemberSelectionPanel.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/memberInfo/KotlinMemberSelectionPanel.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.memberInfo @@ -22,9 +11,10 @@ import com.intellij.ui.SeparatorFactory import org.jetbrains.kotlin.psi.KtNamedDeclaration import java.awt.BorderLayout -class KotlinMemberSelectionPanel(title: String, - memberInfo: List, - abstractColumnHeader: String? +class KotlinMemberSelectionPanel( + title: String, + memberInfo: List, + abstractColumnHeader: String? ) : AbstractMemberSelectionPanel() { private val table = createMemberSelectionTable(memberInfo, abstractColumnHeader) @@ -37,8 +27,8 @@ class KotlinMemberSelectionPanel(title: String, } private fun createMemberSelectionTable( - memberInfo: List, - abstractColumnHeader: String? + memberInfo: List, + abstractColumnHeader: String? ): KotlinMemberSelectionTable { return KotlinMemberSelectionTable(memberInfo, null, abstractColumnHeader) } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/memberInfo/KotlinUsesAndInterfacesDependencyMemberInfoModel.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/memberInfo/KotlinUsesAndInterfacesDependencyMemberInfoModel.kt index 2d49fc1a59f..7bc392ebcb0 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/memberInfo/KotlinUsesAndInterfacesDependencyMemberInfoModel.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/memberInfo/KotlinUsesAndInterfacesDependencyMemberInfoModel.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.memberInfo @@ -26,27 +15,30 @@ import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtNamedDeclaration open class KotlinUsesAndInterfacesDependencyMemberInfoModel>( - klass: KtClassOrObject, - superClass: PsiNamedElement?, - recursive: Boolean, - interfaceContainmentVerifier: (T) -> Boolean = { false } + klass: KtClassOrObject, + superClass: PsiNamedElement?, + recursive: Boolean, + interfaceContainmentVerifier: (T) -> Boolean = { false } ) : DelegatingMemberInfoModel( - ANDCombinedMemberInfoModel( - object : KotlinUsesDependencyMemberInfoModel(klass, superClass, recursive) { - override fun checkForProblems(memberInfo: M): Int { - val problem = super.checkForProblems(memberInfo) - if (problem == MemberInfoModel.OK) return MemberInfoModel.OK + ANDCombinedMemberInfoModel( + object : KotlinUsesDependencyMemberInfoModel(klass, superClass, recursive) { + override fun checkForProblems(memberInfo: M): Int { + val problem = super.checkForProblems(memberInfo) + if (problem == MemberInfoModel.OK) return MemberInfoModel.OK - val member = memberInfo.member - if (interfaceContainmentVerifier(member)) return MemberInfoModel.OK + val member = memberInfo.member + if (interfaceContainmentVerifier(member)) return MemberInfoModel.OK - return problem - } - }, - KotlinInterfaceDependencyMemberInfoModel(klass)) + return problem + } + }, + KotlinInterfaceDependencyMemberInfoModel(klass) + ) ) { @Suppress("UNCHECKED_CAST") fun setSuperClass(superClass: PsiNamedElement) { - ((delegatingTarget as ANDCombinedMemberInfoModel).model1 as UsesDependencyMemberInfoModel).setSuperClass(superClass) + ((delegatingTarget as ANDCombinedMemberInfoModel).model1 as UsesDependencyMemberInfoModel).setSuperClass( + superClass + ) } } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/memberInfo/KotlinUsesDependencyMemberInfoModel.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/memberInfo/KotlinUsesDependencyMemberInfoModel.kt index dae4f9f9a8c..d7c83a84195 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/memberInfo/KotlinUsesDependencyMemberInfoModel.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/memberInfo/KotlinUsesDependencyMemberInfoModel.kt @@ -26,9 +26,9 @@ import org.jetbrains.kotlin.psi.KtObjectDeclaration import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject open class KotlinUsesDependencyMemberInfoModel>( - klass : KtClassOrObject, - superClass: PsiNamedElement?, - recursive: Boolean + klass: KtClassOrObject, + superClass: PsiNamedElement?, + recursive: Boolean ) : UsesDependencyMemberInfoModel(klass, superClass, recursive) { override fun doCheck(memberInfo: M, problem: Int): Int { val member = memberInfo.member @@ -36,7 +36,8 @@ open class KotlinUsesDependencyMemberInfoModel, - moveCallback: MoveCallback? + directory: PsiDirectory, + elementsToMove: Array, + moveCallback: MoveCallback? ) = KotlinAwareMoveClassesOrPackagesToNewDirectoryDialog(directory, elementsToMove, moveCallback) } \ No newline at end of file diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveDeclarations/MoveDeclarationsDelegate.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveDeclarations/MoveDeclarationsDelegate.kt index db527ef7739..36ed939a397 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveDeclarations/MoveDeclarationsDelegate.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveDeclarations/MoveDeclarationsDelegate.kt @@ -128,8 +128,9 @@ sealed class MoveDeclarationsDelegate { if (outerInstanceParameterName != null) { val type = (containingClassOrObject!!.unsafeResolveToDescriptor() as ClassDescriptor).defaultType - val parameter = KtPsiFactory(project) - .createParameter("private val $outerInstanceParameterName: ${IdeDescriptorRenderers.SOURCE_CODE.renderType(type)}") + val parameter = KtPsiFactory(project).createParameter( + "private val $outerInstanceParameterName: ${IdeDescriptorRenderers.SOURCE_CODE.renderType(type)}" + ) createPrimaryConstructorParameterListIfAbsent().addParameter(parameter).isToBeShortened = true } } 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 abb76e8facd..72a6b88fade 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 @@ -68,7 +68,10 @@ interface Mover : (KtNamedDeclaration, KtElement) -> KtNamedDeclaration { else -> error("Unexpected element: ${targetContainer.getElementTextWithContext()}") }.apply { val container = originalElement.containingClassOrObject - if (container is KtObjectDeclaration && container.isCompanion() && container.declarations.singleOrNull() == originalElement) { + if (container is KtObjectDeclaration && + container.isCompanion() && + container.declarations.singleOrNull() == originalElement + ) { container.deleteSingle() } else { originalElement.deleteSingle() diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveDeclarations/ui/MoveKotlinNestedClassesModel.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveDeclarations/ui/MoveKotlinNestedClassesModel.kt index cb74805fc37..9e831df0a47 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveDeclarations/ui/MoveKotlinNestedClassesModel.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveDeclarations/ui/MoveKotlinNestedClassesModel.kt @@ -27,7 +27,7 @@ internal class MoveKotlinNestedClassesModel( private fun getCheckedTargetClass(): KtElement { val targetClass = this.targetClass ?: throw ConfigurationException("No destination class specified") - if (targetClass !is KtClassOrObject){ + if (targetClass !is KtClassOrObject) { throw ConfigurationException("Destination class must be a Kotlin class") } 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 09a8433405b..b0fac102b52 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveUtils.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveUtils.kt @@ -6,7 +6,6 @@ package org.jetbrains.kotlin.idea.refactoring.move import com.intellij.ide.util.DirectoryUtil -import com.intellij.openapi.options.ConfigurationException import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.Comparing @@ -55,7 +54,6 @@ import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver import org.jetbrains.kotlin.types.expressions.DoubleColonLHS import org.jetbrains.kotlin.utils.addIfNotNull import java.io.File -import java.nio.file.Path import java.util.* sealed class ContainerInfo { @@ -374,7 +372,9 @@ private fun getReferenceKind(reference: PsiReference, referencedElement: PsiElem if (element.getStrictParentOfType() != null) return ReferenceKind.IRRELEVANT - if (element.isExtensionRef() && reference.element.getNonStrictParentOfType() == null) return ReferenceKind.UNQUALIFIABLE + if (element.isExtensionRef() && + reference.element.getNonStrictParentOfType() == null + ) return ReferenceKind.UNQUALIFIABLE element.getParentOfTypeAndBranch { callableReference }?.let { val receiverExpression = it.receiverExpression diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/JavaToKotlinPostconversionPullUpHelper.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/JavaToKotlinPostconversionPullUpHelper.kt index 5c04b4001af..4c385c25a63 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/JavaToKotlinPostconversionPullUpHelper.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/JavaToKotlinPostconversionPullUpHelper.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.pullUp @@ -31,16 +20,16 @@ import org.jetbrains.kotlin.psi.psiUtil.getReceiverExpression import java.util.* class JavaToKotlinPostconversionPullUpHelper(private val data: PullUpData) : PullUpHelper { - override fun setCorrectVisibility(info: MemberInfo?) { } + override fun setCorrectVisibility(info: MemberInfo?) {} - override fun encodeContextInfo(info: MemberInfo?) { } + override fun encodeContextInfo(info: MemberInfo?) {} - override fun move(info: MemberInfo?, substitutor: PsiSubstitutor?) { } + override fun move(info: MemberInfo?, substitutor: PsiSubstitutor?) {} - override fun postProcessMember(member: PsiMember?) { } + override fun postProcessMember(member: PsiMember?) {} // TODO: To be implemented - override fun moveFieldInitializations(movedFields: LinkedHashSet?) { } + override fun moveFieldInitializations(movedFields: LinkedHashSet?) {} override fun updateUsage(element: PsiElement?) { if (element !is KtSimpleNameExpression) return diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/JavaToKotlinPreconversionPullUpHelper.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/JavaToKotlinPreconversionPullUpHelper.kt index ed49237cc60..5b8044bbf75 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/JavaToKotlinPreconversionPullUpHelper.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/JavaToKotlinPreconversionPullUpHelper.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.pullUp @@ -40,13 +29,13 @@ import org.jetbrains.kotlin.psi.* import java.util.* class JavaToKotlinPreconversionPullUpHelper( - private val data: PullUpData, - private val dummyTargetClass: PsiClass, - private val javaHelper: JavaPullUpHelper + private val data: PullUpData, + private val dummyTargetClass: PsiClass, + private val javaHelper: JavaPullUpHelper ) : PullUpHelper by javaHelper { private val membersToDummyDeclarations = HashMap() - private val encapsulateFieldsDescriptor = object: EncapsulateFieldsDescriptor { + private val encapsulateFieldsDescriptor = object : EncapsulateFieldsDescriptor { override fun getSelectedFields(): Array? = arrayOf() override fun isToEncapsulateGet() = true override fun isToEncapsulateSet() = true @@ -76,9 +65,8 @@ class JavaToKotlinPreconversionPullUpHelper( val fieldDescriptor = FieldDescriptorImpl(member, getterName, setterName, getter, setter) getter?.let { dummyAccessorByName[getterName] = dummyTargetClass.add(it) as PsiMethod } setter?.let { dummyAccessorByName[setterName] = dummyTargetClass.add(it) as PsiMethod } - fieldsToUsages[member] = ReferencesSearch - .search(member) - .mapNotNull { helper.createUsage(encapsulateFieldsDescriptor, fieldDescriptor, it) } + fieldsToUsages[member] = + ReferencesSearch.search(member).mapNotNull { helper.createUsage(encapsulateFieldsDescriptor, fieldDescriptor, it) } } override fun move(info: MemberInfo, substitutor: PsiSubstitutor) { @@ -103,8 +91,8 @@ class JavaToKotlinPreconversionPullUpHelper( if (type == null) { val substitutedUpperBound = substitutor.substitute(PsiIntersectionType.createIntersection(*typeParameter.superTypes)) subst.put(typeParameter, substitutedUpperBound) - } - else subst + } else + subst } javaHelper.move(info, adjustedSubstitutor) @@ -130,7 +118,7 @@ class JavaToKotlinPreconversionPullUpHelper( member.hasModifierProperty(PsiModifier.STATIC) && member !is PsiClass -> targetClass.getOrCreateCompanionObject() else -> targetClass } - val dummyDeclaration : KtNamedDeclaration = when (member) { + val dummyDeclaration: KtNamedDeclaration = when (member) { is PsiField -> psiFactory.createProperty("val foo = 0") is PsiMethod -> psiFactory.createFunction("fun foo() = 0") is PsiClass -> psiFactory.createClass("class Foo") @@ -173,9 +161,7 @@ class JavaToKotlinPreconversionPullUpHelper( val getter = targetLightClass.findMethodBySignature(fieldDescriptor.getterPrototype, false) val setter = targetLightClass.findMethodBySignature(fieldDescriptor.setterPrototype, false) - EncapsulateFieldHelper - .getHelper(usage.element!!.language) - ?.processUsage(usage, encapsulateFieldsDescriptor, setter, getter) + EncapsulateFieldHelper.getHelper(usage.element!!.language)?.processUsage(usage, encapsulateFieldsDescriptor, setter, getter) } } } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/KotlinPullUpData.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/KotlinPullUpData.kt index 8ef00faa8e4..3737cce847f 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/KotlinPullUpData.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/KotlinPullUpData.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.pullUp @@ -37,9 +26,11 @@ import org.jetbrains.kotlin.types.substitutions.getTypeSubstitution import org.jetbrains.kotlin.utils.keysToMap import java.util.* -class KotlinPullUpData(val sourceClass: KtClassOrObject, - val targetClass: PsiNamedElement, - val membersToMove: Collection) { +class KotlinPullUpData( + val sourceClass: KtClassOrObject, + val targetClass: PsiNamedElement, + val membersToMove: Collection +) { val resolutionFacade = sourceClass.getResolutionFacade() val sourceClassContext = resolutionFacade.analyzeWithAllCompilerChecks(listOf(sourceClass)).bindingContext @@ -61,10 +52,9 @@ class KotlinPullUpData(val sourceClass: KtClassOrObject, val targetClassSuperResolvedCall = superEntryForTargetClass.getResolvedCall(sourceClassContext) private val typeParametersInSourceClassContext by lazy { - sourceClassDescriptor.declaredTypeParameters + - sourceClass.getResolutionScope(sourceClassContext, resolutionFacade) - .collectDescriptorsFiltered(DescriptorKindFilter.NON_SINGLETON_CLASSIFIERS) - .filterIsInstance() + sourceClassDescriptor.declaredTypeParameters + sourceClass.getResolutionScope(sourceClassContext, resolutionFacade) + .collectDescriptorsFiltered(DescriptorKindFilter.NON_SINGLETON_CLASSIFIERS) + .filterIsInstance() } val sourceToTargetClassSubstitutor: TypeSubstitutor by lazy { @@ -75,12 +65,12 @@ class KotlinPullUpData(val sourceClass: KtClassOrObject, } val superClassSubstitution = getTypeSubstitution(targetClassDescriptor.defaultType, sourceClassDescriptor.defaultType) - ?: emptyMap() + ?: emptyMap() for ((typeConstructor, typeProjection) in superClassSubstitution) { val subClassTypeParameter = typeProjection.type.constructor.declarationDescriptor as? TypeParameterDescriptor - ?: continue + ?: continue val superClassTypeParameter = typeConstructor.declarationDescriptor - ?: continue + ?: continue substitution[subClassTypeParameter.typeConstructor] = TypeProjectionImpl(superClassTypeParameter.defaultType) } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/KotlinPullUpDialog.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/KotlinPullUpDialog.kt index d43814a14cd..72ea5ee65ec 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/KotlinPullUpDialog.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/KotlinPullUpDialog.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.pullUp @@ -21,12 +10,12 @@ import com.intellij.openapi.ui.DialogWrapper import com.intellij.psi.PsiClass import com.intellij.psi.PsiComment import com.intellij.psi.PsiNamedElement -import org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringSettings import com.intellij.refactoring.classMembers.MemberInfoChange import com.intellij.refactoring.classMembers.MemberInfoModel import com.intellij.refactoring.memberPullUp.PullUpProcessor import com.intellij.refactoring.util.DocCommentPolicy import org.jetbrains.kotlin.asJava.toLightClass +import org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringSettings import org.jetbrains.kotlin.idea.refactoring.isCompanionMemberOf import org.jetbrains.kotlin.idea.refactoring.isConstructorDeclaredProperty import org.jetbrains.kotlin.idea.refactoring.isInterfaceClass @@ -35,26 +24,26 @@ import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* class KotlinPullUpDialog( - project: Project, - classOrObject: KtClassOrObject, - superClasses: List, - memberInfoStorage: KotlinMemberInfoStorage + project: Project, + classOrObject: KtClassOrObject, + superClasses: List, + memberInfoStorage: KotlinMemberInfoStorage ) : KotlinPullUpDialogBase( - project, classOrObject, superClasses, memberInfoStorage, PULL_MEMBERS_UP + project, classOrObject, superClasses, memberInfoStorage, PULL_MEMBERS_UP ) { init { init() } private inner class MemberInfoModelImpl( - originalClass: KtClassOrObject, - superClass: PsiNamedElement?, - interfaceContainmentVerifier: (KtNamedDeclaration) -> Boolean + originalClass: KtClassOrObject, + superClass: PsiNamedElement?, + interfaceContainmentVerifier: (KtNamedDeclaration) -> Boolean ) : KotlinUsesAndInterfacesDependencyMemberInfoModel( - originalClass, - superClass, - false, - interfaceContainmentVerifier + originalClass, + superClass, + false, + interfaceContainmentVerifier ) { private var lastSuperClass: PsiNamedElement? = null @@ -81,7 +70,8 @@ class KotlinPullUpDialog( val member = memberInfo.member if (member.hasModifier(KtTokens.INLINE_KEYWORD) || member.hasModifier(KtTokens.EXTERNAL_KEYWORD) || - member.hasModifier(KtTokens.LATEINIT_KEYWORD)) return false + member.hasModifier(KtTokens.LATEINIT_KEYWORD) + ) return false if (member.isAbstractInInterface(sourceClass)) return false if (member.isConstructorParameterWithInterfaceTarget(superClass)) return false if (member.isCompanionMemberOf(sourceClass)) return false @@ -98,7 +88,7 @@ class KotlinPullUpDialog( if (member.isAbstractInInterface(sourceClass)) return true if (superClass != null && member.isConstructorParameterWithInterfaceTarget(superClass)) return true return ((member is KtProperty || member is KtParameter) && superClass !is PsiClass) - || (member is KtNamedFunction && superClass is PsiClass) + || (member is KtNamedFunction && superClass is PsiClass) } override fun isMemberEnabled(memberInfo: KotlinMemberInfo): Boolean { @@ -108,7 +98,8 @@ class KotlinPullUpDialog( if (member.hasModifier(KtTokens.CONST_KEYWORD)) return false if (superClass is KtClass && superClass.isInterface() && - (member.hasModifier(KtTokens.INTERNAL_KEYWORD) || member.hasModifier(KtTokens.PROTECTED_KEYWORD))) return false + (member.hasModifier(KtTokens.INTERNAL_KEYWORD) || member.hasModifier(KtTokens.PROTECTED_KEYWORD)) + ) return false if (superClass is PsiClass) { if (!member.canMoveMemberToJavaClass(superClass)) return false @@ -140,12 +131,12 @@ class KotlinPullUpDialog( override fun getSuperClass() = super.getSuperClass() override fun createMemberInfoModel(): MemberInfoModel = - MemberInfoModelImpl(sourceClass, preselection, getInterfaceContainmentVerifier { selectedMemberInfos }) + MemberInfoModelImpl(sourceClass, preselection, getInterfaceContainmentVerifier { selectedMemberInfos }) override fun getPreselection() = mySuperClasses.firstOrNull { !it.isInterfaceClass() } ?: mySuperClasses.firstOrNull() override fun createMemberSelectionTable(infos: MutableList) = - KotlinMemberSelectionTable(infos, null, "Make abstract") + KotlinMemberSelectionTable(infos, null, "Make abstract") override fun isOKActionEnabled() = selectedMemberInfos.size > 0 @@ -158,15 +149,18 @@ class KotlinPullUpDialog( } companion object { - fun createProcessor(sourceClass: KtClassOrObject, - targetClass: PsiNamedElement, - memberInfos: List): PullUpProcessor { + fun createProcessor( + sourceClass: KtClassOrObject, + targetClass: PsiNamedElement, + memberInfos: List + ): PullUpProcessor { val targetPsiClass = targetClass as? PsiClass ?: (targetClass as KtClass).toLightClass() return PullUpProcessor( sourceClass.toLightClass() ?: error("can't build lightClass for $sourceClass"), targetPsiClass, memberInfos.mapNotNull { it.toJavaMemberInfo() }.toTypedArray(), - DocCommentPolicy(KotlinRefactoringSettings.instance.PULL_UP_MEMBERS_JAVADOC)) + DocCommentPolicy(KotlinRefactoringSettings.instance.PULL_UP_MEMBERS_JAVADOC) + ) } } } \ No newline at end of file diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/KotlinPullUpHelper.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/KotlinPullUpHelper.kt index e39a7acb3e8..90c2cdbe699 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/KotlinPullUpHelper.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/KotlinPullUpHelper.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.pullUp @@ -114,7 +103,7 @@ class KotlinPullUpHelper( var initializerCandidate: KtExpression? = null for (statement in scope.statements) { - statement.asAssignment()?.let body@ { + statement.asAssignment()?.let body@{ val lhs = KtPsiUtil.safeDeparenthesize(it.left ?: return@body) val receiver = (lhs as? KtQualifiedExpression)?.receiverExpression if (receiver != null && receiver !is KtThisExpression) return@body @@ -203,8 +192,7 @@ class KotlinPullUpHelper( private fun processConstructorReference(expression: KtReferenceExpression, callingConstructorElement: KtElement) { val descriptor = data.resolutionFacade.analyze(expression)[BindingContext.REFERENCE_TARGET, expression] val constructorElement = (descriptor as? DeclarationDescriptorWithSource)?.source?.getPsi() ?: return - if (constructorElement == data.targetClass - || (constructorElement as? KtConstructor<*>)?.getContainingClassOrObject() == data.targetClass) { + if (constructorElement == data.targetClass || (constructorElement as? KtConstructor<*>)?.getContainingClassOrObject() == data.targetClass) { result.getOrPut(constructorElement as KtElement, { ArrayList() }).add(callingConstructorElement) } } @@ -238,9 +226,8 @@ class KotlinPullUpHelper( override fun getVertices() = propertyToInitializerInfo.keys override fun getTargets(source: KtProperty) = propertyToInitializerInfo[source]?.usedProperties - }, - { !propertyToInitializerInfo.containsKey(it) } - ) + } + ) { !propertyToInitializerInfo.containsKey(it) } propertyToInitializerInfo.keys.removeAll(unmovableProperties) result[targetConstructor] = propertyToInitializerInfo @@ -363,7 +350,7 @@ class KotlinPullUpHelper( val superRef = sourcePsiClass.implementsList ?.referenceElements ?.firstOrNull { it.resolve()?.unwrapped == realMemberPsi } - ?: return + ?: return val superTypeForTarget = substitutor.substitute(elementFactory.createType(superRef)) data.sourceClass.removeSuperTypeListEntry(currentSpecifier) @@ -421,7 +408,7 @@ class KotlinPullUpHelper( val newParameterTypes = lightMethod.parameterList.parameters.map { substitutor.substitute(it.type) } val objectType = PsiType.getJavaLangObject(PsiManager.getInstance(project), GlobalSearchScope.allScope(project)) val newTypeParameterBounds = lightMethod.typeParameters.map { - it.superTypes.map { substitutor.substitute(it) as? PsiClassType ?: objectType } + it.superTypes.map { type -> substitutor.substitute(type) as? PsiClassType ?: objectType } } val newMethod = org.jetbrains.kotlin.idea.refactoring.createJavaMethod(member, data.targetClass) RefactoringUtil.makeMethodAbstract(data.targetClass, newMethod) @@ -599,7 +586,7 @@ class KotlinPullUpHelper( } fun addUsedParameters(constructorElement: KtElement, info: InitializerInfo) { - if (!info.usedParameters.isNotEmpty()) return + if (info.usedParameters.isEmpty()) return val constructor: KtConstructor<*> = when (constructorElement) { is KtConstructor<*> -> constructorElement is KtClass -> constructorElement.createPrimaryConstructorIfAbsent() @@ -631,8 +618,8 @@ class KotlinPullUpHelper( else -> null } superCall?.valueArgumentList?.let { args -> - info.usedParameters.forEach { - args.addArgument(psiFactory.createArgument(psiFactory.createExpression(it.name ?: "_"))) + info.usedParameters.forEach { parameter -> + args.addArgument(psiFactory.createArgument(psiFactory.createExpression(parameter.name ?: "_"))) } } } @@ -652,7 +639,7 @@ class KotlinPullUpHelper( ) for (oldProperty in properties) { - val info = propertyToInitializerInfo[oldProperty]!! + val info = propertyToInitializerInfo.getValue(oldProperty) addUsedParameters(constructorElement, info) diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/KotlinPullUpHelperFactory.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/KotlinPullUpHelperFactory.kt index acde44bfcfb..3612351a5ca 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/KotlinPullUpHelperFactory.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/KotlinPullUpHelperFactory.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.pullUp @@ -71,9 +60,9 @@ class JavaToKotlinPullUpHelperFactory : PullUpHelperFactory { val project = targetClass.project val targetPackage = targetClass.containingKtFile.packageFqName.asString() val dummyFile = PsiFileFactory.getInstance(project).createFileFromText( - "dummy.java", - JavaFileType.INSTANCE, - if (targetPackage.isNotEmpty()) "package $targetPackage;\n" else "" + "dummy.java", + JavaFileType.INSTANCE, + if (targetPackage.isNotEmpty()) "package $targetPackage;\n" else "" ) val elementFactory = PsiElementFactory.SERVICE.getInstance(project) @@ -89,11 +78,8 @@ class JavaToKotlinPullUpHelperFactory : PullUpHelperFactory { } psiClass } - return outerPsiClasses - .asSequence() - .drop(1) - .plus(dummyTargetClass) - .fold(dummyFile.add(outerPsiClasses.first()), PsiElement::add) as PsiClass + return outerPsiClasses.asSequence().drop(1).plus(dummyTargetClass) + .fold(dummyFile.add(outerPsiClasses.first()), PsiElement::add) as PsiClass } override fun createPullUpHelper(data: PullUpData): PullUpHelper<*> { @@ -102,9 +88,9 @@ class JavaToKotlinPullUpHelperFactory : PullUpHelperFactory { createJavaToKotlinPullUpHelper(data)?.let { return it } return PullUpHelper.INSTANCE - .allForLanguage(JavaLanguage.INSTANCE) - .firstOrNull { it !is JavaToKotlinPullUpHelperFactory } - ?.createPullUpHelper(data) - ?: EmptyPullUpHelper + .allForLanguage(JavaLanguage.INSTANCE) + .firstOrNull { it !is JavaToKotlinPullUpHelperFactory } + ?.createPullUpHelper(data) + ?: EmptyPullUpHelper } } \ No newline at end of file diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/markingUtils.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/markingUtils.kt index 1fba2be3a0b..9d8070ccc5c 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/markingUtils.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/markingUtils.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.pullUp @@ -45,118 +34,119 @@ private var KtElement.replaceWithTargetThis: Boolean? by CopyablePsiUserDataProp private var KtElement.newTypeText: ((TypeSubstitutor) -> String?)? by CopyablePsiUserDataProperty(Key.create("NEW_TYPE_TEXT")) fun markElements( - declaration: KtNamedDeclaration, - context: BindingContext, - sourceClassDescriptor: ClassDescriptor, targetClassDescriptor: ClassDescriptor? + declaration: KtNamedDeclaration, + context: BindingContext, + sourceClassDescriptor: ClassDescriptor, targetClassDescriptor: ClassDescriptor? ): List { val affectedElements = ArrayList() declaration.accept( - object : KtVisitorVoid() { - private fun visitSuperOrThis(expression: KtInstanceExpressionWithLabel) { - if (targetClassDescriptor == null) return + object : KtVisitorVoid() { + private fun visitSuperOrThis(expression: KtInstanceExpressionWithLabel) { + if (targetClassDescriptor == null) return - val callee = expression.getQualifiedExpressionForReceiver()?.selectorExpression?.getCalleeExpressionIfAny() ?: return - val calleeTarget = callee.getResolvedCall(context)?.resultingDescriptor ?: return - if ((calleeTarget as? CallableMemberDescriptor)?.kind != CallableMemberDescriptor.Kind.DECLARATION) return - if (calleeTarget.containingDeclaration == targetClassDescriptor) { - expression.replaceWithTargetThis = true - affectedElements.add(expression) - } - } - - override fun visitElement(element: PsiElement) { - element.allChildren.forEach { it.accept(this) } - } - - override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { - val resolvedCall = expression.getResolvedCall(context) ?: return - val receiver = resolvedCall.getExplicitReceiverValue() - ?: resolvedCall.extensionReceiver - ?: resolvedCall.dispatchReceiver - ?: return - - val implicitThis = receiver.type.constructor.declarationDescriptor as? ClassDescriptor ?: return - if (implicitThis.isCompanionObject - && DescriptorUtils.isAncestor(sourceClassDescriptor, implicitThis, true)) { - val qualifierFqName = implicitThis.importableFqName ?: return - - expression.newFqName = FqName("${qualifierFqName.asString()}.${expression.getReferencedName()}") - affectedElements.add(expression) - } - } - - override fun visitThisExpression(expression: KtThisExpression) { - visitSuperOrThis(expression) - } - - override fun visitSuperExpression(expression: KtSuperExpression) { - visitSuperOrThis(expression) - } - - override fun visitTypeReference(typeReference: KtTypeReference) { - val oldType = context[BindingContext.TYPE, typeReference] ?: return - typeReference.newTypeText = f@ { substitutor -> - substitutor.substitute(oldType, Variance.INVARIANT)?.let { IdeDescriptorRenderers.SOURCE_CODE.renderType(it) } - } - affectedElements.add(typeReference) + val callee = expression.getQualifiedExpressionForReceiver()?.selectorExpression?.getCalleeExpressionIfAny() ?: return + val calleeTarget = callee.getResolvedCall(context)?.resultingDescriptor ?: return + if ((calleeTarget as? CallableMemberDescriptor)?.kind != CallableMemberDescriptor.Kind.DECLARATION) return + if (calleeTarget.containingDeclaration == targetClassDescriptor) { + expression.replaceWithTargetThis = true + affectedElements.add(expression) } } + + override fun visitElement(element: PsiElement) { + element.allChildren.forEach { it.accept(this) } + } + + override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { + val resolvedCall = expression.getResolvedCall(context) ?: return + val receiver = resolvedCall.getExplicitReceiverValue() + ?: resolvedCall.extensionReceiver + ?: resolvedCall.dispatchReceiver + ?: return + + val implicitThis = receiver.type.constructor.declarationDescriptor as? ClassDescriptor ?: return + if (implicitThis.isCompanionObject + && DescriptorUtils.isAncestor(sourceClassDescriptor, implicitThis, true) + ) { + val qualifierFqName = implicitThis.importableFqName ?: return + + expression.newFqName = FqName("${qualifierFqName.asString()}.${expression.getReferencedName()}") + affectedElements.add(expression) + } + } + + override fun visitThisExpression(expression: KtThisExpression) { + visitSuperOrThis(expression) + } + + override fun visitSuperExpression(expression: KtSuperExpression) { + visitSuperOrThis(expression) + } + + override fun visitTypeReference(typeReference: KtTypeReference) { + val oldType = context[BindingContext.TYPE, typeReference] ?: return + typeReference.newTypeText = f@{ substitutor -> + substitutor.substitute(oldType, Variance.INVARIANT)?.let { IdeDescriptorRenderers.SOURCE_CODE.renderType(it) } + } + affectedElements.add(typeReference) + } + } ) return affectedElements } fun applyMarking( - declaration: KtNamedDeclaration, - substitutor: TypeSubstitutor, targetClassDescriptor: ClassDescriptor + declaration: KtNamedDeclaration, + substitutor: TypeSubstitutor, targetClassDescriptor: ClassDescriptor ) { val psiFactory = KtPsiFactory(declaration) val targetThis = psiFactory.createExpression("this@${targetClassDescriptor.name.asString().quoteIfNeeded()}") val shorteningOptionsForThis = ShortenReferences.Options(removeThisLabels = true, removeThis = true) declaration.accept( - object : KtVisitorVoid() { - private fun visitSuperOrThis(expression: KtInstanceExpressionWithLabel) { - expression.replaceWithTargetThis?.let { - expression.replaceWithTargetThis = null + object : KtVisitorVoid() { + private fun visitSuperOrThis(expression: KtInstanceExpressionWithLabel) { + expression.replaceWithTargetThis?.let { + expression.replaceWithTargetThis = null - val newThisExpression = expression.replace(targetThis) as KtExpression - newThisExpression.getQualifiedExpressionForReceiverOrThis().addToShorteningWaitSet(shorteningOptionsForThis) - } - } - - override fun visitElement(element: PsiElement) { - for (it in element.allChildren.toList()) { - it.accept(this) - } - } - - override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { - expression.newFqName?.let { - expression.newFqName = null - - expression.mainReference.bindToFqName(it) - } - } - - override fun visitThisExpression(expression: KtThisExpression) { - this.visitSuperOrThis(expression) - } - - override fun visitSuperExpression(expression: KtSuperExpression) { - this.visitSuperOrThis(expression) - } - - override fun visitTypeReference(typeReference: KtTypeReference) { - typeReference.newTypeText?.let f@ { - typeReference.newTypeText = null - - val newTypeText = it(substitutor) ?: return@f - (typeReference.replace(psiFactory.createType(newTypeText)) as KtElement).addToShorteningWaitSet() - } + val newThisExpression = expression.replace(targetThis) as KtExpression + newThisExpression.getQualifiedExpressionForReceiverOrThis().addToShorteningWaitSet(shorteningOptionsForThis) } } + + override fun visitElement(element: PsiElement) { + for (it in element.allChildren.toList()) { + it.accept(this) + } + } + + override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { + expression.newFqName?.let { + expression.newFqName = null + + expression.mainReference.bindToFqName(it) + } + } + + override fun visitThisExpression(expression: KtThisExpression) { + this.visitSuperOrThis(expression) + } + + override fun visitSuperExpression(expression: KtSuperExpression) { + this.visitSuperOrThis(expression) + } + + override fun visitTypeReference(typeReference: KtTypeReference) { + typeReference.newTypeText?.let f@{ + typeReference.newTypeText = null + + val newTypeText = it(substitutor) ?: return@f + (typeReference.replace(psiFactory.createType(newTypeText)) as KtElement).addToShorteningWaitSet() + } + } + } ) } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/pullUpUtils.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/pullUpUtils.kt index 04538caffc8..96153c9d757 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/pullUpUtils.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/pullUpUtils.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.pullUp @@ -40,10 +29,10 @@ import org.jetbrains.kotlin.types.isError import org.jetbrains.kotlin.types.typeUtil.isUnit fun KtProperty.mustBeAbstractInInterface() = - hasInitializer() || hasDelegate() || (!hasInitializer() && !hasDelegate() && accessors.isEmpty()) + hasInitializer() || hasDelegate() || (!hasInitializer() && !hasDelegate() && accessors.isEmpty()) fun KtNamedDeclaration.isAbstractInInterface(originalClass: KtClassOrObject) = - originalClass is KtClass && originalClass.isInterface() && isAbstract() + originalClass is KtClass && originalClass.isInterface() && isAbstract() fun KtNamedDeclaration.canMoveMemberToJavaClass(targetClass: PsiClass): Boolean { return when (this) { @@ -93,9 +82,9 @@ private fun KtParameter.toProperty(): KtProperty = } fun doAddCallableMember( - memberCopy: KtCallableDeclaration, - clashingSuper: KtCallableDeclaration?, - targetClass: KtClassOrObject + memberCopy: KtCallableDeclaration, + clashingSuper: KtCallableDeclaration?, + targetClass: KtClassOrObject ): KtCallableDeclaration { val memberToAdd = if (memberCopy is KtParameter && memberCopy.needToBeAbstract(targetClass)) memberCopy.toProperty() else memberCopy @@ -120,8 +109,8 @@ fun KtClass.makeAbstract() { } fun KtClassOrObject.getSuperTypeEntryByDescriptor( - descriptor: ClassDescriptor, - context: BindingContext + descriptor: ClassDescriptor, + context: BindingContext ): KtSuperTypeListEntry? { return superTypeListEntries.firstOrNull { val referencedType = context[BindingContext.TYPE, it.typeReference] @@ -129,10 +118,12 @@ fun KtClassOrObject.getSuperTypeEntryByDescriptor( } } -fun makeAbstract(member: KtCallableDeclaration, - originalMemberDescriptor: CallableMemberDescriptor, - substitutor: TypeSubstitutor, - targetClass: KtClass) { +fun makeAbstract( + member: KtCallableDeclaration, + originalMemberDescriptor: CallableMemberDescriptor, + substitutor: TypeSubstitutor, + targetClass: KtClass +) { if (!targetClass.isInterface()) { member.addModifier(KtTokens.ABSTRACT_KEYWORD) } @@ -142,10 +133,9 @@ fun makeAbstract(member: KtCallableDeclaration, var type = originalMemberDescriptor.returnType if (type == null || type.isError) { type = builtIns.nullableAnyType - } - else { + } else { type = substitutor.substitute(type.anonymousObjectSuperTypeOrNull() ?: type, Variance.INVARIANT) - ?: builtIns.nullableAnyType + ?: builtIns.nullableAnyType } if (member is KtProperty || !type.isUnit()) { @@ -171,11 +161,11 @@ fun makeAbstract(member: KtCallableDeclaration, } fun addSuperTypeEntry( - delegator: KtSuperTypeListEntry, - targetClass: KtClassOrObject, - targetClassDescriptor: ClassDescriptor, - context: BindingContext, - substitutor: TypeSubstitutor + delegator: KtSuperTypeListEntry, + targetClass: KtClassOrObject, + targetClassDescriptor: ClassDescriptor, + context: BindingContext, + substitutor: TypeSubstitutor ) { val referencedType = context[BindingContext.TYPE, delegator.typeReference]!! val referencedClass = referencedType.constructor.declarationDescriptor as? ClassDescriptor ?: return @@ -190,14 +180,12 @@ fun addSuperTypeEntry( targetClass.addSuperTypeListEntry(newSpecifier).addToShorteningWaitSet() } -fun getInterfaceContainmentVerifier(getMemberInfos: () -> List): (KtNamedDeclaration) -> Boolean { - return result@ { member -> - val psiMethodToCheck = lightElementForMemberInfo(member) as? PsiMethod ?: return@result false - getMemberInfos().any { - if (!it.isSuperClass || it.overrides != false) return@any false +fun getInterfaceContainmentVerifier(getMemberInfos: () -> List): (KtNamedDeclaration) -> Boolean = result@{ member -> + val psiMethodToCheck = lightElementForMemberInfo(member) as? PsiMethod ?: return@result false + getMemberInfos().any { + if (!it.isSuperClass || it.overrides != false) return@any false - val psiSuperInterface = (it.member as? KtClass)?.toLightClass() - psiSuperInterface?.findMethodBySignature(psiMethodToCheck, true) != null - } + val psiSuperInterface = (it.member as? KtClass)?.toLightClass() + psiSuperInterface?.findMethodBySignature(psiMethodToCheck, true) != null } } \ No newline at end of file diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/pushDown/JavaToKotlinPushDownDelegate.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/pushDown/JavaToKotlinPushDownDelegate.kt index 22ceb2f9842..456c8b1cc6c 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/pushDown/JavaToKotlinPushDownDelegate.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/pushDown/JavaToKotlinPushDownDelegate.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.pushDown @@ -45,10 +34,10 @@ import org.jetbrains.kotlin.types.substitutions.getTypeSubstitutor class JavaToKotlinPushDownDelegate : JavaPushDownDelegate() { override fun checkTargetClassConflicts( - targetClass: PsiElement?, - pushDownData: PushDownData, - conflicts: MultiMap, - subClassData: NewSubClassData? + targetClass: PsiElement?, + pushDownData: PushDownData, + conflicts: MultiMap, + subClassData: NewSubClassData? ) { super.checkTargetClassConflicts(targetClass, pushDownData, conflicts, subClassData) @@ -83,12 +72,12 @@ class JavaToKotlinPushDownDelegate : JavaPushDownDelegate() { hasAbstractMembers = true } moveCallableMemberToClass( - ktMember, - memberDescriptor as CallableMemberDescriptor, - targetMemberClass, - targetMemberClassDescriptor, - substitutor, - memberInfo.isToAbstract + ktMember, + memberDescriptor as CallableMemberDescriptor, + targetMemberClass, + targetMemberClassDescriptor, + substitutor, + memberInfo.isToAbstract ).apply { if (subClass.isInterfaceClass()) { removeModifier(KtTokens.ABSTRACT_KEYWORD) @@ -98,10 +87,10 @@ class JavaToKotlinPushDownDelegate : JavaPushDownDelegate() { is PsiClass -> { if (memberInfo.overrides != null) { - val typeText = RefactoringUtil.findReferenceToClass(superClass.implementsList, member)?.j2kText() ?: continue@members + val typeText = + RefactoringUtil.findReferenceToClass(superClass.implementsList, member)?.j2kText() ?: continue@members subClass.addSuperTypeListEntry(psiFactory.createSuperTypeEntry(typeText)) - } - else { + } else { val ktClass = member.j2k() as? KtClassOrObject ?: continue@members addMemberToTarget(ktClass, subClass) } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/pushDown/KotlinPushDownDialog.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/pushDown/KotlinPushDownDialog.kt index baf7c584b1a..f670eb14a62 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/pushDown/KotlinPushDownDialog.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/pushDown/KotlinPushDownDialog.kt @@ -1,27 +1,16 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.pushDown import com.intellij.openapi.project.Project import com.intellij.psi.PsiNamedElement -import org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringSettings import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.classMembers.* import com.intellij.refactoring.ui.RefactoringDialog +import org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringSettings import org.jetbrains.kotlin.idea.refactoring.memberInfo.KotlinMemberInfo import org.jetbrains.kotlin.idea.refactoring.memberInfo.KotlinMemberSelectionPanel import org.jetbrains.kotlin.idea.refactoring.memberInfo.KotlinUsesDependencyMemberInfoModel @@ -40,9 +29,9 @@ import javax.swing.JLabel import javax.swing.JPanel class KotlinPushDownDialog( - project: Project, - private val memberInfos: List, - private val sourceClass: KtClass + project: Project, + private val memberInfos: List, + private val sourceClass: KtClass ) : RefactoringDialog(project, true) { init { title = PUSH_MEMBERS_DOWN @@ -68,23 +57,31 @@ class KotlinPushDownDialog( gbConstraints.gridwidth = GridBagConstraints.REMAINDER gbConstraints.fill = GridBagConstraints.BOTH gbConstraints.anchor = GridBagConstraints.WEST - panel.add(JLabel(RefactoringBundle.message("push.members.from.0.down.label", - sourceClass.qualifiedClassNameForRendering())), gbConstraints) + panel.add( + JLabel( + RefactoringBundle.message( + "push.members.from.0.down.label", + sourceClass.qualifiedClassNameForRendering() + ) + ), gbConstraints + ) return panel } override fun createCenterPanel(): JComponent? { val panel = JPanel(BorderLayout()) val memberSelectionPanel = KotlinMemberSelectionPanel( - RefactoringBundle.message("members.to.be.pushed.down.panel.title"), - memberInfos, - RefactoringBundle.message("keep.abstract.column.header")) + RefactoringBundle.message("members.to.be.pushed.down.panel.title"), + memberInfos, + RefactoringBundle.message("keep.abstract.column.header") + ) panel.add(memberSelectionPanel, BorderLayout.CENTER) memberInfoModel = object : DelegatingMemberInfoModel( - ANDCombinedMemberInfoModel( - KotlinUsesDependencyMemberInfoModel(sourceClass, null, false), - UsedByDependencyMemberInfoModel(sourceClass)) + ANDCombinedMemberInfoModel( + KotlinUsesDependencyMemberInfoModel(sourceClass, null, false), + UsedByDependencyMemberInfoModel(sourceClass) + ) ) { override fun isFixedAbstract(member: KotlinMemberInfo?) = null @@ -92,7 +89,8 @@ class KotlinPushDownDialog( val member = memberInfo.member if (member.hasModifier(KtTokens.INLINE_KEYWORD) || member.hasModifier(KtTokens.EXTERNAL_KEYWORD) || - member.hasModifier(KtTokens.LATEINIT_KEYWORD)) return false + member.hasModifier(KtTokens.LATEINIT_KEYWORD) + ) return false return member is KtNamedFunction || member is KtProperty } } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/pushDown/KotlinPushDownProcessor.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/pushDown/KotlinPushDownProcessor.kt index 0fc5b355f8f..4ff8f2cb210 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/pushDown/KotlinPushDownProcessor.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/pushDown/KotlinPushDownProcessor.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.pushDown @@ -49,8 +38,8 @@ import org.jetbrains.kotlin.utils.keysToMap import java.util.* class KotlinPushDownContext( - val sourceClass: KtClass, - val membersToMove: List + val sourceClass: KtClass, + val membersToMove: List ) { val resolutionFacade = sourceClass.getResolutionFacade() @@ -58,20 +47,18 @@ class KotlinPushDownContext( val sourceClassDescriptor = sourceClassContext[BindingContext.DECLARATION_TO_DESCRIPTOR, sourceClass] as ClassDescriptor - val memberDescriptors = membersToMove - .map { it.member } - .keysToMap { - when (it) { - is KtPsiClassWrapper -> it.psiClass.getJavaClassDescriptor(resolutionFacade)!! - else -> sourceClassContext[BindingContext.DECLARATION_TO_DESCRIPTOR, it]!! - } - } + val memberDescriptors = membersToMove.map { it.member }.keysToMap { + when (it) { + is KtPsiClassWrapper -> it.psiClass.getJavaClassDescriptor(resolutionFacade)!! + else -> sourceClassContext[BindingContext.DECLARATION_TO_DESCRIPTOR, it]!! + } + } } class KotlinPushDownProcessor( - project: Project, - sourceClass: KtClass, - membersToMove: List + project: Project, + sourceClass: KtClass, + membersToMove: List ) : BaseRefactoringProcessor(project) { private val context = KotlinPushDownContext(sourceClass, membersToMove) @@ -81,7 +68,7 @@ class KotlinPushDownProcessor( override fun getElements() = arrayOf(context.sourceClass) override fun getCodeReferencesText(usagesCount: Int, filesCount: Int) = - RefactoringBundle.message("classes.to.push.down.members.to", UsageViewBundle.getReferencesString(usagesCount, filesCount)) + RefactoringBundle.message("classes.to.push.down.members.to", UsageViewBundle.getReferencesString(usagesCount, filesCount)) override fun getCommentReferencesText(usagesCount: Int, filesCount: Int) = null } @@ -102,18 +89,17 @@ class KotlinPushDownProcessor( } override fun findUsages(): Array { - return HierarchySearchRequest(context.sourceClass, context.sourceClass.useScope, false) - .searchInheritors() - .mapNotNull { it.unwrapped } - .map(::SubclassUsage) - .toTypedArray() + return HierarchySearchRequest(context.sourceClass, context.sourceClass.useScope, false).searchInheritors() + .mapNotNull { it.unwrapped } + .map(::SubclassUsage) + .toTypedArray() } override fun preprocessUsages(refUsages: Ref>): Boolean { val usages = refUsages.get() ?: UsageInfo.EMPTY_ARRAY if (usages.isEmpty()) { - val message = "${context.sourceClassDescriptor.renderForConflicts()} doesn't have inheritors\n" + - "Pushing members down will result in them being deleted. Would you like to proceed?" + val message = "${context.sourceClassDescriptor + .renderForConflicts()} doesn't have inheritors\nPushing members down will result in them being deleted. Would you like to proceed?" val answer = Messages.showYesNoDialog(message.capitalize(), PUSH_MEMBERS_DOWN, Messages.getWarningIcon()) if (answer == Messages.NO) return false } @@ -128,7 +114,7 @@ class KotlinPushDownProcessor( private fun pushDownToClass(targetClass: KtClassOrObject) { val targetClassDescriptor = context.resolutionFacade.resolveToDescriptor(targetClass) as ClassDescriptor val substitutor = getTypeSubstitutor(context.sourceClassDescriptor.defaultType, targetClassDescriptor.defaultType) - ?: TypeSubstitutor.EMPTY + ?: TypeSubstitutor.EMPTY members@ for (memberInfo in context.membersToMove) { val member = memberInfo.member val memberDescriptor = context.memberDescriptors[member] ?: continue @@ -138,26 +124,25 @@ class KotlinPushDownProcessor( memberDescriptor as CallableMemberDescriptor moveCallableMemberToClass( - member as KtCallableDeclaration, - memberDescriptor, - targetClass, - targetClassDescriptor, - substitutor, - memberInfo.isToAbstract + member as KtCallableDeclaration, + memberDescriptor, + targetClass, + targetClassDescriptor, + substitutor, + memberInfo.isToAbstract ) } is KtClassOrObject, is KtPsiClassWrapper -> { if (memberInfo.overrides != null) { context.sourceClass.getSuperTypeEntryByDescriptor( - memberDescriptor as ClassDescriptor, - context.sourceClassContext + memberDescriptor as ClassDescriptor, + context.sourceClassContext )?.let { addSuperTypeEntry(it, targetClass, targetClassDescriptor, context.sourceClassContext, substitutor) } continue@members - } - else { + } else { addMemberToTarget(member, targetClass) } } @@ -183,21 +168,19 @@ class KotlinPushDownProcessor( } makeAbstract(member, memberDescriptor, TypeSubstitutor.EMPTY, context.sourceClass) member.typeReference?.addToShorteningWaitSet() - } - else { + } else { member.delete() } } is KtClassOrObject, is KtPsiClassWrapper -> { if (memberInfo.overrides != null) { context.sourceClass.getSuperTypeEntryByDescriptor( - memberDescriptor as ClassDescriptor, - context.sourceClassContext + memberDescriptor as ClassDescriptor, + context.sourceClassContext )?.let { context.sourceClass.removeSuperTypeListEntry(it) } - } - else { + } else { member.delete() } } @@ -213,8 +196,7 @@ class KotlinPushDownProcessor( } usages.forEach { (it.element as? KtClassOrObject)?.let { pushDownToClass(it) } } removeOriginalMembers() - } - finally { + } finally { clearMarking(markedElements) } } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/pushDown/pushDownConflictsUtils.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/pushDown/pushDownConflictsUtils.kt index ac592669650..1f9d16c6ef3 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/pushDown/pushDownConflictsUtils.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/pushDown/pushDownConflictsUtils.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.pushDown @@ -42,8 +31,10 @@ import org.jetbrains.kotlin.types.substitutions.getTypeSubstitutor import org.jetbrains.kotlin.util.findCallableMemberBySignature import java.util.* -fun analyzePushDownConflicts(context: KotlinPushDownContext, - usages: Array): MultiMap { +fun analyzePushDownConflicts( + context: KotlinPushDownContext, + usages: Array +): MultiMap { val targetClasses = usages.mapNotNull { it.element?.unwrapped } val conflicts = MultiMap() @@ -55,9 +46,7 @@ fun analyzePushDownConflicts(context: KotlinPushDownContext, if (!info.isChecked || ((member is KtClassOrObject || member is KtPsiClassWrapper) && info.overrides != null)) continue membersToPush += member - if ((member is KtNamedFunction || member is KtProperty) - && info.isToAbstract - && (context.memberDescriptors[member] as CallableMemberDescriptor).modality != Modality.ABSTRACT) { + if ((member is KtNamedFunction || member is KtProperty) && info.isToAbstract && (context.memberDescriptors[member] as CallableMemberDescriptor).modality != Modality.ABSTRACT) { membersToKeepAbstract += member } } @@ -70,28 +59,28 @@ fun analyzePushDownConflicts(context: KotlinPushDownContext, } private fun checkConflicts( - conflicts: MultiMap, - context: KotlinPushDownContext, - targetClass: PsiElement, - membersToKeepAbstract: List, - membersToPush: ArrayList + conflicts: MultiMap, + context: KotlinPushDownContext, + targetClass: PsiElement, + membersToKeepAbstract: List, + membersToPush: ArrayList ) { if (targetClass !is KtClassOrObject) { conflicts.putValue( - targetClass, - "Non-Kotlin ${RefactoringUIUtil.getDescription(targetClass, false)} won't be affected by the refactoring" + targetClass, + "Non-Kotlin ${RefactoringUIUtil.getDescription(targetClass, false)} won't be affected by the refactoring" ) return } val targetClassDescriptor = context.resolutionFacade.resolveToDescriptor(targetClass) as ClassDescriptor val substitutor = getTypeSubstitutor(context.sourceClassDescriptor.defaultType, targetClassDescriptor.defaultType) - ?: TypeSubstitutor.EMPTY + ?: TypeSubstitutor.EMPTY if (!context.sourceClass.isInterface() && targetClass is KtClass && targetClass.isInterface()) { val message = "${targetClassDescriptor.renderForConflicts()} " + - "inherits from ${context.sourceClassDescriptor.renderForConflicts()}.\n" + - "It won't be affected by the refactoring" + "inherits from ${context.sourceClassDescriptor.renderForConflicts()}.\n" + + "It won't be affected by the refactoring" conflicts.putValue(targetClass, message.capitalize()) } @@ -104,27 +93,30 @@ private fun checkConflicts( } private fun checkMemberClashing( - conflicts: MultiMap, - context: KotlinPushDownContext, - member: KtNamedDeclaration, - membersToKeepAbstract: List, - substitutor: TypeSubstitutor, - targetClass: KtClassOrObject, - targetClassDescriptor: ClassDescriptor) { + conflicts: MultiMap, + context: KotlinPushDownContext, + member: KtNamedDeclaration, + membersToKeepAbstract: List, + substitutor: TypeSubstitutor, + targetClass: KtClassOrObject, + targetClassDescriptor: ClassDescriptor +) { when (member) { is KtNamedFunction, is KtProperty -> { val memberDescriptor = context.memberDescriptors[member] as CallableMemberDescriptor - val clashingDescriptor = targetClassDescriptor.findCallableMemberBySignature(memberDescriptor.substitute(substitutor) as CallableMemberDescriptor) + val clashingDescriptor = + targetClassDescriptor.findCallableMemberBySignature(memberDescriptor.substitute(substitutor) as CallableMemberDescriptor) val clashingDeclaration = clashingDescriptor?.source?.getPsi() as? KtNamedDeclaration if (clashingDescriptor != null && clashingDeclaration != null) { if (memberDescriptor.modality != Modality.ABSTRACT && member !in membersToKeepAbstract) { - val message = "${targetClassDescriptor.renderForConflicts()} already contains ${clashingDescriptor.renderForConflicts()}" + val message = + "${targetClassDescriptor.renderForConflicts()} already contains ${clashingDescriptor.renderForConflicts()}" conflicts.putValue(clashingDeclaration, CommonRefactoringUtil.capitalize(message)) } if (!clashingDeclaration.hasModifier(KtTokens.OVERRIDE_KEYWORD)) { val message = "${clashingDescriptor.renderForConflicts()} in ${targetClassDescriptor.renderForConflicts()} " + - "will override corresponding member of ${context.sourceClassDescriptor.renderForConflicts()} " + - "after refactoring" + "will override corresponding member of ${context.sourceClassDescriptor.renderForConflicts()} " + + "after refactoring" conflicts.putValue(clashingDeclaration, CommonRefactoringUtil.capitalize(message)) } } @@ -134,49 +126,51 @@ private fun checkMemberClashing( targetClass.declarations .asSequence() .filterIsInstance() - .firstOrNull() { it.name == member.name } - ?.let { - val message = "${targetClassDescriptor.renderForConflicts()} " + - "already contains nested class named ${CommonRefactoringUtil.htmlEmphasize(member.name ?: "")}" - conflicts.putValue(it, message.capitalize()) - } + .firstOrNull() { it.name == member.name } + ?.let { + val message = "${targetClassDescriptor.renderForConflicts()} " + + "already contains nested class named ${CommonRefactoringUtil.htmlEmphasize(member.name ?: "")}" + conflicts.putValue(it, message.capitalize()) + } } } } private fun checkSuperCalls( - conflicts: MultiMap, - context: KotlinPushDownContext, - member: KtNamedDeclaration, - membersToPush: ArrayList + conflicts: MultiMap, + context: KotlinPushDownContext, + member: KtNamedDeclaration, + membersToPush: ArrayList ) { member.accept( - object : KtTreeVisitorVoid() { - override fun visitSuperExpression(expression: KtSuperExpression) { - val qualifiedExpression = expression.getQualifiedExpressionForReceiver() ?: return - val refExpr = qualifiedExpression.selectorExpression.getCalleeExpressionIfAny() as? KtSimpleNameExpression ?: return - for (descriptor in refExpr.mainReference.resolveToDescriptors(context.sourceClassContext)) { - val memberDescriptor = descriptor as? CallableMemberDescriptor ?: continue - val containingClass = memberDescriptor.containingDeclaration as? ClassDescriptor ?: continue - if (!DescriptorUtils.isSubclass(context.sourceClassDescriptor, containingClass)) continue - val memberInSource = context.sourceClassDescriptor.findCallableMemberBySignature(memberDescriptor)?.source?.getPsi() - ?: continue - if (memberInSource !in membersToPush) { - conflicts.putValue(qualifiedExpression, - "Pushed member won't be available in '${qualifiedExpression.text}'") - } + object : KtTreeVisitorVoid() { + override fun visitSuperExpression(expression: KtSuperExpression) { + val qualifiedExpression = expression.getQualifiedExpressionForReceiver() ?: return + val refExpr = qualifiedExpression.selectorExpression.getCalleeExpressionIfAny() as? KtSimpleNameExpression ?: return + for (descriptor in refExpr.mainReference.resolveToDescriptors(context.sourceClassContext)) { + val memberDescriptor = descriptor as? CallableMemberDescriptor ?: continue + val containingClass = memberDescriptor.containingDeclaration as? ClassDescriptor ?: continue + if (!DescriptorUtils.isSubclass(context.sourceClassDescriptor, containingClass)) continue + val memberInSource = context.sourceClassDescriptor.findCallableMemberBySignature(memberDescriptor)?.source?.getPsi() + ?: continue + if (memberInSource !in membersToPush) { + conflicts.putValue( + qualifiedExpression, + "Pushed member won't be available in '${qualifiedExpression.text}'" + ) } } } + } ) } internal fun checkExternalUsages( - conflicts: MultiMap, - member: PsiElement, - targetClassDescriptor: ClassDescriptor, - resolutionFacade: ResolutionFacade -): Unit { + conflicts: MultiMap, + member: PsiElement, + targetClassDescriptor: ClassDescriptor, + resolutionFacade: ResolutionFacade +) { for (ref in ReferencesSearch.search(member, member.resolveScope, false)) { val calleeExpr = ref.element as? KtSimpleNameExpression ?: continue val resolvedCall = calleeExpr.getResolvedCall(resolutionFacade.analyze(calleeExpr)) ?: continue @@ -191,32 +185,33 @@ internal fun checkExternalUsages( } private fun checkVisibility( - conflicts: MultiMap, - context: KotlinPushDownContext, - member: KtNamedDeclaration, - targetClassDescriptor: ClassDescriptor + conflicts: MultiMap, + context: KotlinPushDownContext, + member: KtNamedDeclaration, + targetClassDescriptor: ClassDescriptor ) { fun reportConflictIfAny(targetDescriptor: DeclarationDescriptor) { val target = (targetDescriptor as? DeclarationDescriptorWithSource)?.source?.getPsi() ?: return if (targetDescriptor is DeclarationDescriptorWithVisibility - && !Visibilities.isVisibleIgnoringReceiver(targetDescriptor, targetClassDescriptor)) { - val message = "${context.memberDescriptors[member]!!.renderForConflicts()} " + - "uses ${targetDescriptor.renderForConflicts()}, " + - "which is not accessible from the ${targetClassDescriptor.renderForConflicts()}" + && !Visibilities.isVisibleIgnoringReceiver(targetDescriptor, targetClassDescriptor) + ) { + val message = "${context.memberDescriptors.getValue(member).renderForConflicts()} " + + "uses ${targetDescriptor.renderForConflicts()}, " + + "which is not accessible from the ${targetClassDescriptor.renderForConflicts()}" conflicts.putValue(target, message.capitalize()) } } member.accept( - object : KtTreeVisitorVoid() { - override fun visitReferenceExpression(expression: KtReferenceExpression) { - super.visitReferenceExpression(expression) + object : KtTreeVisitorVoid() { + override fun visitReferenceExpression(expression: KtReferenceExpression) { + super.visitReferenceExpression(expression) - expression.references - .flatMap { (it as? KtReference)?.resolveToDescriptors(context.sourceClassContext) ?: emptyList() } - .forEach(::reportConflictIfAny) + expression.references + .flatMap { (it as? KtReference)?.resolveToDescriptors(context.sourceClassContext) ?: emptyList() } + .forEach(::reportConflictIfAny) - } } + } ) } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/pushDown/pushDownImpl.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/pushDown/pushDownImpl.kt index 63add42ac81..4bab5734ec5 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/pushDown/pushDownImpl.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/pushDown/pushDownImpl.kt @@ -30,12 +30,12 @@ import org.jetbrains.kotlin.types.TypeSubstitutor import org.jetbrains.kotlin.util.findCallableMemberBySignature internal fun moveCallableMemberToClass( - member: KtCallableDeclaration, - memberDescriptor: CallableMemberDescriptor, - targetClass: KtClassOrObject, - targetClassDescriptor: ClassDescriptor, - substitutor: TypeSubstitutor, - makeAbstract: Boolean + member: KtCallableDeclaration, + memberDescriptor: CallableMemberDescriptor, + targetClass: KtClassOrObject, + targetClassDescriptor: ClassDescriptor, + substitutor: TypeSubstitutor, + makeAbstract: Boolean ): KtCallableDeclaration { val targetMemberDescriptor = memberDescriptor.substitute(substitutor)?.let { targetClassDescriptor.findCallableMemberBySignature(it as CallableMemberDescriptor) @@ -44,11 +44,9 @@ internal fun moveCallableMemberToClass( return targetMember?.apply { if (memberDescriptor.modality != Modality.ABSTRACT && makeAbstract) { addModifier(KtTokens.OVERRIDE_KEYWORD) - } - else if (memberDescriptor.overriddenDescriptors.isEmpty()) { + } else if (memberDescriptor.overriddenDescriptors.isEmpty()) { removeModifier(KtTokens.OVERRIDE_KEYWORD) - } - else { + } else { addModifier(KtTokens.OVERRIDE_KEYWORD) } } ?: addMemberToTarget(member, targetClass).apply { diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/AbstractReferenceSubstitutionRenameHandler.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/AbstractReferenceSubstitutionRenameHandler.kt index 4e88959c111..900ae6aa7f2 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/AbstractReferenceSubstitutionRenameHandler.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/AbstractReferenceSubstitutionRenameHandler.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.rename @@ -35,7 +24,7 @@ import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType abstract class AbstractReferenceSubstitutionRenameHandler( - private val delegateHandler: RenameHandler = MemberInplaceRenameHandler() + private val delegateHandler: RenameHandler = MemberInplaceRenameHandler() ) : PsiElementRenameHandler() { companion object { fun getReferenceExpression(file: PsiFile, offset: Int): KtSimpleNameExpression? { diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/AutomaticInheritorRenamer.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/AutomaticInheritorRenamer.kt index 33ceffaabda..08d8456df86 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/AutomaticInheritorRenamer.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/AutomaticInheritorRenamer.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.rename @@ -19,16 +8,16 @@ package org.jetbrains.kotlin.idea.refactoring.rename import com.intellij.psi.PsiElement import com.intellij.psi.PsiNamedElement import com.intellij.psi.search.searches.ClassInheritorsSearch -import org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringSettings import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.rename.naming.AutomaticRenamer import com.intellij.refactoring.rename.naming.AutomaticRenamerFactory import com.intellij.usageView.UsageInfo import org.jetbrains.kotlin.asJava.toLightClass import org.jetbrains.kotlin.asJava.unwrapped +import org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringSettings import org.jetbrains.kotlin.psi.KtClass -class AutomaticInheritorRenamer(klass: KtClass, newName: String): AutomaticRenamer() { +class AutomaticInheritorRenamer(klass: KtClass, newName: String) : AutomaticRenamer() { init { val lightClass = klass.toLightClass() if (lightClass != null) { @@ -44,7 +33,8 @@ class AutomaticInheritorRenamer(klass: KtClass, newName: String): AutomaticRenam override fun getDialogTitle() = RefactoringBundle.message("rename.inheritors.title") override fun getDialogDescription() = RefactoringBundle.message("rename.inheritors.with.the.following.names.to") - override fun entityName() = RefactoringBundle.message("entity.name.inheritor")} + override fun entityName() = RefactoringBundle.message("entity.name.inheritor") +} class AutomaticInheritorRenamerFactory : AutomaticRenamerFactory { override fun isApplicable(element: PsiElement) = element is KtClass diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/AutomaticOverloadsRenamer.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/AutomaticOverloadsRenamer.kt index 9ceec4310d2..045951d264a 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/AutomaticOverloadsRenamer.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/AutomaticOverloadsRenamer.kt @@ -1,24 +1,12 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.rename import com.intellij.openapi.util.Key import com.intellij.psi.PsiElement -import org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringSettings import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.rename.naming.AutomaticRenamer import com.intellij.refactoring.rename.naming.AutomaticRenamerFactory @@ -28,6 +16,7 @@ import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor +import org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringSettings import org.jetbrains.kotlin.idea.util.expectedDescriptor import org.jetbrains.kotlin.idea.util.getAllAccessibleFunctions import org.jetbrains.kotlin.idea.util.getResolutionScope @@ -94,6 +83,6 @@ class AutomaticOverloadsRenamerFactory : AutomaticRenamerFactory { KotlinRefactoringSettings.instance.renameOverloads = enabled } - override fun createRenamer(element: PsiElement, newName: String, usages: Collection) - = AutomaticOverloadsRenamer(element as KtNamedFunction, newName) + override fun createRenamer(element: PsiElement, newName: String, usages: Collection) = + AutomaticOverloadsRenamer(element as KtNamedFunction, newName) } \ No newline at end of file diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/AutomaticParameterRenamer.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/AutomaticParameterRenamer.kt index 5ef2f363248..1e80128b8f1 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/AutomaticParameterRenamer.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/AutomaticParameterRenamer.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.rename @@ -19,12 +8,12 @@ package org.jetbrains.kotlin.idea.refactoring.rename import com.intellij.psi.PsiElement import com.intellij.psi.PsiMethod import com.intellij.psi.PsiNamedElement -import org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringSettings import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.rename.naming.AutomaticRenamer import com.intellij.refactoring.rename.naming.AutomaticRenamerFactory import com.intellij.usageView.UsageInfo import org.jetbrains.kotlin.asJava.namedUnwrappedElement +import org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringSettings import org.jetbrains.kotlin.idea.refactoring.canRefactor import org.jetbrains.kotlin.idea.search.declarationsSearch.HierarchySearchRequest import org.jetbrains.kotlin.idea.search.declarationsSearch.searchOverriders @@ -43,12 +32,11 @@ class AutomaticParameterRenamer(element: KtParameter, newName: String) : Automat for (overrider in HierarchySearchRequest(function, function.useScope).searchOverriders()) { val callable = overrider.namedUnwrappedElement ?: continue if (!callable.canRefactor()) continue - val parameter: PsiNamedElement? = - when (callable) { - is KtCallableDeclaration -> callable.valueParameters.firstOrNull { it.name == element.name } - is PsiMethod -> callable.parameterList.parameters.firstOrNull { it.name == element.name } - else -> null - } + val parameter: PsiNamedElement? = when (callable) { + is KtCallableDeclaration -> callable.valueParameters.firstOrNull { it.name == element.name } + is PsiMethod -> callable.parameterList.parameters.firstOrNull { it.name == element.name } + else -> null + } if (parameter == null) continue myElements += parameter } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/AutomaticVariableRenamer.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/AutomaticVariableRenamer.kt index 4f0ab670e17..44f7ce3f619 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/AutomaticVariableRenamer.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/AutomaticVariableRenamer.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.rename @@ -24,7 +13,6 @@ import com.intellij.psi.PsiNamedElement import com.intellij.psi.PsiVariable import com.intellij.psi.codeStyle.JavaCodeStyleManager import com.intellij.psi.util.PsiTreeUtil -import org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringSettings import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.rename.naming.AutomaticRenamer import com.intellij.refactoring.rename.naming.AutomaticRenamerFactory @@ -36,6 +24,7 @@ import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.VariableDescriptor import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor import org.jetbrains.kotlin.idea.core.unquote +import org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringSettings import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.isAncestor import org.jetbrains.kotlin.resolve.DescriptorUtils @@ -47,9 +36,9 @@ import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull import java.util.* class AutomaticVariableRenamer( - klass: PsiNamedElement, // PsiClass or JetClass - newClassName: String, - usages: Collection + klass: PsiNamedElement, // PsiClass or JetClass + newClassName: String, + usages: Collection ) : AutomaticRenamer() { private val toUnpluralize = ArrayList() @@ -58,16 +47,16 @@ class AutomaticVariableRenamer( val usageElement = usage.element ?: continue val parameterOrVariable = PsiTreeUtil.getParentOfType( - usageElement, - KtVariableDeclaration::class.java, - KtParameter::class.java + usageElement, + KtVariableDeclaration::class.java, + KtParameter::class.java ) as KtCallableDeclaration? ?: continue if (parameterOrVariable.typeReference?.isAncestor(usageElement) != true) continue val descriptor = try { parameterOrVariable.unsafeResolveToDescriptor() - } catch(e: NoDescriptorForDeclarationException) { + } catch (e: NoDescriptorForDeclarationException) { LOG.error(e) continue } @@ -96,8 +85,7 @@ class AutomaticVariableRenamer( val propertyName = if (psiVariable != null) { val codeStyleManager = JavaCodeStyleManager.getInstance(psiVariable.project) codeStyleManager.variableNameToPropertyName(name, codeStyleManager.getVariableKind(psiVariable)) - } - else name + } else name if (element in toUnpluralize) { val singular = StringUtil.unpluralize(propertyName) @@ -114,8 +102,7 @@ class AutomaticVariableRenamer( val varName = if (psiVariable != null) { val codeStyleManager = JavaCodeStyleManager.getInstance(psiVariable.project) codeStyleManager.propertyNameToVariableName(canonicalName, codeStyleManager.getVariableKind(psiVariable)) - } - else canonicalName + } else canonicalName return if (element in toUnpluralize) StringUtil.pluralize(varName) @@ -139,11 +126,11 @@ private fun KotlinType.isCollectionLikeOf(classPsiElement: PsiNamedElement): Boo } -open class AutomaticVariableRenamerFactory: AutomaticRenamerFactory { +open class AutomaticVariableRenamerFactory : AutomaticRenamerFactory { override fun isApplicable(element: PsiElement) = element is KtClass || element is KtTypeAlias override fun createRenamer(element: PsiElement, newName: String, usages: Collection) = - AutomaticVariableRenamer(element as PsiNamedElement, newName, usages) + AutomaticVariableRenamer(element as PsiNamedElement, newName, usages) override fun isEnabled() = KotlinRefactoringSettings.instance.renameVariables override fun setEnabled(enabled: Boolean) { @@ -159,12 +146,12 @@ class AutomaticVariableRenamerFactoryForJavaClass : AutomaticVariableRenamerFact override fun getOptionName() = null } -class AutomaticVariableInJavaRenamerFactory: AutomaticRenamerFactory { +class AutomaticVariableInJavaRenamerFactory : AutomaticRenamerFactory { override fun isApplicable(element: PsiElement) = element is KtClass && element.toLightClass() != null override fun createRenamer(element: PsiElement, newName: String, usages: Collection) = - // Using java variable renamer for java usages - com.intellij.refactoring.rename.naming.AutomaticVariableRenamer((element as KtClass).toLightClass()!!, newName, usages) + // Using java variable renamer for java usages + com.intellij.refactoring.rename.naming.AutomaticVariableRenamer((element as KtClass).toLightClass()!!, newName, usages) override fun isEnabled() = KotlinRefactoringSettings.instance.renameVariables override fun setEnabled(enabled: Boolean) { diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/BasicUnresolvableCollisionUsageInfo.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/BasicUnresolvableCollisionUsageInfo.kt index 75687c149a7..6168a4e7be2 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/BasicUnresolvableCollisionUsageInfo.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/BasicUnresolvableCollisionUsageInfo.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.rename @@ -20,8 +9,9 @@ import com.intellij.psi.PsiElement import com.intellij.refactoring.rename.UnresolvableCollisionUsageInfo class BasicUnresolvableCollisionUsageInfo( - element: PsiElement, - referencedElement: PsiElement, - private val _description: String) : UnresolvableCollisionUsageInfo(element, referencedElement) { + element: PsiElement, + referencedElement: PsiElement, + private val _description: String +) : UnresolvableCollisionUsageInfo(element, referencedElement) { override fun getDescription() = _description } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/JavaMemberByKotlinReferenceInplaceRenameHandler.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/JavaMemberByKotlinReferenceInplaceRenameHandler.kt index 4a4e100e09a..d6b51a2dcc2 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/JavaMemberByKotlinReferenceInplaceRenameHandler.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/JavaMemberByKotlinReferenceInplaceRenameHandler.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.rename @@ -37,9 +26,9 @@ import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType class JavaMemberByKotlinReferenceInplaceRenameHandler : MemberInplaceRenameHandler() { class Renamer( - elementToRename: PsiNameIdentifierOwner, - element: PsiElement, - editor: Editor + elementToRename: PsiNameIdentifierOwner, + element: PsiElement, + editor: Editor ) : MemberInplaceRenamer(elementToRename, element, editor) { override fun performRefactoringRename(newName: String, markAction: StartMarkAction) { super.performRefactoringRename(KtPsiUtil.unquoteIdentifier(newName), markAction) diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/KotlinMemberInplaceRenameHandler.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/KotlinMemberInplaceRenameHandler.kt index 331b4dbd258..d85467af6a5 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/KotlinMemberInplaceRenameHandler.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/KotlinMemberInplaceRenameHandler.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.rename @@ -69,11 +58,7 @@ class KotlinMemberInplaceRenameHandler : MemberInplaceRenameHandler() { // Move caret if constructor range doesn't intersect with the one of the containing class val offset = editor.caretModel.offset val editorPsiFile = PsiDocumentManager.getInstance(element.project).getPsiFile(editor.document) - if (nameIdentifier != null - && editorPsiFile == elementToRename.containingFile - && elementToRename is KtPrimaryConstructor - && offset !in nameIdentifier.textRange - && offset in elementToRename.textRange) { + if (nameIdentifier != null && editorPsiFile == elementToRename.containingFile && elementToRename is KtPrimaryConstructor && offset !in nameIdentifier.textRange && offset in elementToRename.textRange) { editor.caretModel.moveToOffset(nameIdentifier.textOffset) } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/KotlinResolveSnapshotProvider.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/KotlinResolveSnapshotProvider.kt index 33d1f572c48..ce7f80547aa 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/KotlinResolveSnapshotProvider.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/KotlinResolveSnapshotProvider.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.rename @@ -44,14 +33,14 @@ class KotlinResolveSnapshotProvider : ResolveSnapshotProvider() { init { scope.accept( - object: KtTreeVisitorVoid() { - override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { - if (expression.getQualifiedExpressionForSelector() != null) return super.visitSimpleNameExpression(expression) - val targetDescriptor = expression.resolveMainReferenceToDescriptors().singleOrNull() ?: return - if (targetDescriptor !is PropertyDescriptor) return - refExpressionToDescriptor[expression.createSmartPointer()] = targetDescriptor - } + object : KtTreeVisitorVoid() { + override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { + if (expression.getQualifiedExpressionForSelector() != null) return super.visitSimpleNameExpression(expression) + val targetDescriptor = expression.resolveMainReferenceToDescriptors().singleOrNull() ?: return + if (targetDescriptor !is PropertyDescriptor) return + refExpressionToDescriptor[expression.createSmartPointer()] = targetDescriptor } + } ) } @@ -65,8 +54,7 @@ class KotlinResolveSnapshotProvider : ResolveSnapshotProvider() { val containingDescriptor = targetDescriptor.containingDeclaration val qualifiedRefText = if (containingDescriptor is ClassDescriptor) { "${containingDescriptor.explicateAsTextForReceiver()}.${targetDescriptor.name.asString()}" - } - else { + } else { targetDescriptor.importableFqName?.asString() ?: continue } val qualifiedRefExpr = KtPsiFactory(project).createExpression(qualifiedRefText) diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/KotlinVariableInplaceRenameHandler.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/KotlinVariableInplaceRenameHandler.kt index cd6dc765edd..2b0d0f267e1 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/KotlinVariableInplaceRenameHandler.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/KotlinVariableInplaceRenameHandler.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -36,12 +36,12 @@ open class KotlinVariableInplaceRenameHandler : VariableInplaceRenameHandler() { } protected open class RenamerImpl : VariableInplaceRenamer { - constructor(elementToRename: PsiNamedElement, editor: Editor): super(elementToRename, editor) + constructor(elementToRename: PsiNamedElement, editor: Editor) : super(elementToRename, editor) constructor( - elementToRename: PsiNamedElement, - editor: Editor, - currentName: String, - oldName: String + elementToRename: PsiNamedElement, + editor: Editor, + currentName: String, + oldName: String ) : super(elementToRename, editor, editor.project!!, currentName, oldName) override fun acceptReference(reference: PsiReference): Boolean { diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/KtResolvableCollisionUsageInfo.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/KtResolvableCollisionUsageInfo.kt index b5bb21d7499..b3566908803 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/KtResolvableCollisionUsageInfo.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/KtResolvableCollisionUsageInfo.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.rename @@ -27,8 +16,8 @@ import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtSimpleNameExpression abstract class KtResolvableCollisionUsageInfo( - element: PsiElement, - referencedElement: PsiElement + element: PsiElement, + referencedElement: PsiElement ) : ResolvableCollisionUsageInfo(element, referencedElement) { // To prevent simple rename via PsiReference override fun getReference() = null @@ -37,9 +26,9 @@ abstract class KtResolvableCollisionUsageInfo( } class UsageInfoWithReplacement( - element: PsiElement, - referencedElement: PsiElement, - private val replacement: KtElement + element: PsiElement, + referencedElement: PsiElement, + private val replacement: KtElement ) : KtResolvableCollisionUsageInfo(element, referencedElement) { override fun apply() { element?.replaced(replacement)?.addToShorteningWaitSet(ShortenReferences.Options.ALL_ENABLED) @@ -47,9 +36,9 @@ class UsageInfoWithReplacement( } class UsageInfoWithFqNameReplacement( - element: KtSimpleNameExpression, - referencedElement: PsiElement, - private val newFqName: FqName + element: KtSimpleNameExpression, + referencedElement: PsiElement, + private val newFqName: FqName ) : KtResolvableCollisionUsageInfo(element, referencedElement) { override fun apply() { (element as? KtSimpleNameExpression)?.mainReference?.bindToFqName(newFqName) diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameBackingFieldReferenceHandler.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameBackingFieldReferenceHandler.kt index 9abbb690edd..93fb55062ee 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameBackingFieldReferenceHandler.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameBackingFieldReferenceHandler.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.rename @@ -26,7 +15,7 @@ import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.core.util.CodeInsightUtils import org.jetbrains.kotlin.psi.KtSimpleNameExpression -class RenameBackingFieldReferenceHandler: KotlinVariableInplaceRenameHandler() { +class RenameBackingFieldReferenceHandler : KotlinVariableInplaceRenameHandler() { override fun isAvailable(element: PsiElement?, editor: Editor, file: PsiFile): Boolean { val refExpression = file.findElementForRename(editor.caretModel.offset) ?: return false if (refExpression.text != "field") return false diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameClassByCompanionObjectShortReferenceHandler.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameClassByCompanionObjectShortReferenceHandler.kt index 5d1ba405e0e..4819320f886 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameClassByCompanionObjectShortReferenceHandler.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameClassByCompanionObjectShortReferenceHandler.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.rename @@ -27,7 +16,8 @@ import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class RenameClassByCompanionObjectShortReferenceHandler : AbstractReferenceSubstitutionRenameHandler() { override fun getElementToRename(dataContext: DataContext): PsiElement? { val refExpr = getReferenceExpression(dataContext) ?: return null - val descriptor = refExpr.analyze(BodyResolveMode.PARTIAL)[BindingContext.SHORT_REFERENCE_TO_COMPANION_OBJECT, refExpr] ?: return null + val descriptor = + refExpr.analyze(BodyResolveMode.PARTIAL)[BindingContext.SHORT_REFERENCE_TO_COMPANION_OBJECT, refExpr] ?: return null return DescriptorToSourceUtilsIde.getAnyDeclaration(dataContext.project, descriptor) } } \ No newline at end of file diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameDynamicMemberHandler.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameDynamicMemberHandler.kt index 10faac933ca..014a764209d 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameDynamicMemberHandler.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameDynamicMemberHandler.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.rename @@ -27,10 +16,10 @@ import org.jetbrains.kotlin.idea.core.util.CodeInsightUtils import org.jetbrains.kotlin.psi.KtSimpleNameExpression import org.jetbrains.kotlin.resolve.calls.tasks.isDynamic -class RenameDynamicMemberHandler: KotlinVariableInplaceRenameHandler() { +class RenameDynamicMemberHandler : KotlinVariableInplaceRenameHandler() { override fun isAvailable(element: PsiElement?, editor: Editor, file: PsiFile): Boolean { val callee = PsiTreeUtil.findElementOfClassAtOffset( - file, editor.caretModel.offset, KtSimpleNameExpression::class.java, false + file, editor.caretModel.offset, KtSimpleNameExpression::class.java, false ) ?: return false val calleeDescriptor = callee.resolveToCall()?.resultingDescriptor ?: return false return calleeDescriptor.isDynamic() diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameJavaSyntheticPropertyHandler.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameJavaSyntheticPropertyHandler.kt index 42c1196efea..107f5afb408 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameJavaSyntheticPropertyHandler.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameJavaSyntheticPropertyHandler.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.rename @@ -44,9 +33,9 @@ class RenameJavaSyntheticPropertyHandler : AbstractReferenceSubstitutionRenameHa } internal class SyntheticPropertyWrapper( - manager: PsiManager, - val descriptor: SyntheticJavaPropertyDescriptor - ): LightElement(manager, KotlinLanguage.INSTANCE), PsiNamedElement { + manager: PsiManager, + val descriptor: SyntheticJavaPropertyDescriptor + ) : LightElement(manager, KotlinLanguage.INSTANCE), PsiNamedElement { val getter: PsiMethod? get() = descriptor.getMethod.source.getPsi() as? PsiMethod val setter: PsiMethod? get() = descriptor.setMethod?.source?.getPsi() as? PsiMethod diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameJvmNameHandler.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameJvmNameHandler.kt index 05a8bd02ea0..1e11fe999b2 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameJvmNameHandler.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameJvmNameHandler.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.rename @@ -48,9 +37,9 @@ class RenameJvmNameHandler : PsiElementRenameHandler() { val nameExpression = getStringTemplate(dataContext) ?: return false if (!nameExpression.isPlain()) return false val entry = ((nameExpression.parent as? KtValueArgument)?.parent as? KtValueArgumentList)?.parent as? KtAnnotationEntry - ?: return false + ?: return false val annotationType = entry.analyze(BodyResolveMode.PARTIAL)[BindingContext.TYPE, entry.typeReference] - ?: return false + ?: return false return annotationType.constructor.declarationDescriptor?.importableFqName == DescriptorUtils.JVM_NAME } @@ -58,15 +47,15 @@ class RenameJvmNameHandler : PsiElementRenameHandler() { val nameExpression = getStringTemplate(dataContext) ?: return null val name = nameExpression.plainContent val entry = nameExpression.getStrictParentOfType() ?: return null - val annotationList = PsiTreeUtil.getParentOfType(entry, KtModifierList::class.java, KtFileAnnotationList::class.java) - val newElement = when (annotationList) { - is KtModifierList -> - (annotationList.parent as? KtDeclaration)?.toLightMethods()?.firstOrNull { it.name == name } ?: return null + val newElement = + when (val annotationList = PsiTreeUtil.getParentOfType(entry, KtModifierList::class.java, KtFileAnnotationList::class.java)) { + is KtModifierList -> (annotationList.parent as? KtDeclaration)?.toLightMethods()?.firstOrNull { it.name == name } + ?: return null - is KtFileAnnotationList -> annotationList.getContainingKtFile().findFacadeClass() ?: return null + is KtFileAnnotationList -> annotationList.getContainingKtFile().findFacadeClass() ?: return null - else -> return null - } + else -> return null + } return DataContext { id -> if (CommonDataKeys.PSI_ELEMENT.`is`(id)) return@DataContext newElement dataContext.getData(id) diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameKotlinClassifierProcessor.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameKotlinClassifierProcessor.kt index 5d6b0de7388..12f5ed484eb 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameKotlinClassifierProcessor.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameKotlinClassifierProcessor.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.rename @@ -19,7 +8,6 @@ package org.jetbrains.kotlin.idea.refactoring.rename import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiElement import com.intellij.psi.PsiReference -import org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringSettings import com.intellij.refactoring.listeners.RefactoringElementListener import com.intellij.usageView.UsageInfo import org.jetbrains.kotlin.asJava.classes.KtLightClass @@ -27,6 +15,7 @@ import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacade import org.jetbrains.kotlin.asJava.classes.KtLightClassForSourceDeclaration import org.jetbrains.kotlin.asJava.namedUnwrappedElement import org.jetbrains.kotlin.idea.caches.resolve.analyze +import org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringSettings import org.jetbrains.kotlin.idea.refactoring.withExpectedActuals import org.jetbrains.kotlin.idea.references.KtSimpleNameReference import org.jetbrains.kotlin.psi.* @@ -89,10 +78,10 @@ class RenameKotlinClassifierProcessor : RenameKotlinPsiProcessor() { } override fun findCollisions( - element: PsiElement, - newName: String, - allRenames: MutableMap, - result: MutableList + element: PsiElement, + newName: String, + allRenames: MutableMap, + result: MutableList ) { val declaration = element.namedUnwrappedElement as? KtNamedDeclaration ?: return @@ -125,8 +114,7 @@ class RenameKotlinClassifierProcessor : RenameKotlinPsiProcessor() { for (usage in usages) { if (usage.isAmbiguousImportUsage()) { ambiguousImportUsages += usage - } - else { + } else { simpleUsages += usage } } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameKotlinFileProcessor.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameKotlinFileProcessor.kt index eebf9449a00..68492e58073 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameKotlinFileProcessor.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameKotlinFileProcessor.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.rename @@ -44,10 +33,12 @@ class RenameKotlinFileProcessor : RenamePsiFileProcessor() { override fun canProcessElement(element: PsiElement) = element is KtFile && ProjectRootsUtil.isInProjectSource(element, includeScriptsOutsideSourceRoots = true) - override fun prepareRenaming(element: PsiElement, - newName: String, - allRenames: MutableMap, - scope: SearchScope) { + override fun prepareRenaming( + element: PsiElement, + newName: String, + allRenames: MutableMap, + scope: SearchScope + ) { val jetFile = element as? KtFile ?: return if (FileTypeManager.getInstance().getFileTypeByFileName(newName) != KotlinFileType.INSTANCE) { return diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameKotlinFunctionProcessor.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameKotlinFunctionProcessor.kt index b3bd2040c8b..a77618c1015 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameKotlinFunctionProcessor.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameKotlinFunctionProcessor.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.rename @@ -21,7 +10,6 @@ import com.intellij.openapi.project.Project import com.intellij.openapi.util.Pass import com.intellij.psi.* import com.intellij.psi.search.SearchScope -import org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringSettings import com.intellij.refactoring.listeners.RefactoringElementListener import com.intellij.refactoring.rename.RenameDialog import com.intellij.refactoring.rename.RenameJavaMethodProcessor @@ -40,10 +28,7 @@ import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper.InternalNameMapper.ge import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper.InternalNameMapper.mangleInternalName import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor -import org.jetbrains.kotlin.idea.refactoring.Pass -import org.jetbrains.kotlin.idea.refactoring.checkSuperMethods -import org.jetbrains.kotlin.idea.refactoring.checkSuperMethodsWithPopup -import org.jetbrains.kotlin.idea.refactoring.dropOverrideKeywordIfNecessary +import org.jetbrains.kotlin.idea.refactoring.* import org.jetbrains.kotlin.idea.references.KtReference import org.jetbrains.kotlin.idea.search.declarationsSearch.findDeepestSuperMethodsKotlinAware import org.jetbrains.kotlin.idea.search.declarationsSearch.findDeepestSuperMethodsNoWrapping @@ -113,9 +98,10 @@ class RenameKotlinFunctionProcessor : RenameKotlinPsiProcessor() { get() = originalDeclaration } - private fun substituteForExpectOrActual(element: PsiElement?) = (element?.namedUnwrappedElement as? KtNamedDeclaration)?.liftToExpected() + private fun substituteForExpectOrActual(element: PsiElement?) = + (element?.namedUnwrappedElement as? KtNamedDeclaration)?.liftToExpected() - override fun substituteElementToRename(element: PsiElement, editor: Editor?): PsiElement? { + override fun substituteElementToRename(element: PsiElement, editor: Editor?): PsiElement? { substituteForExpectOrActual(element)?.let { return it } val wrappedMethod = wrapPsiMethod(element) ?: return element diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameKotlinParameterProcessor.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameKotlinParameterProcessor.kt index e622c79842d..c5f3f5cad14 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameKotlinParameterProcessor.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameKotlinParameterProcessor.kt @@ -1,26 +1,15 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.rename import com.intellij.psi.PsiElement -import org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringSettings import com.intellij.refactoring.listeners.RefactoringElementListener import com.intellij.usageView.UsageInfo import org.jetbrains.kotlin.asJava.namedUnwrappedElement +import org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringSettings import org.jetbrains.kotlin.psi.KtFunction import org.jetbrains.kotlin.psi.KtNamedDeclaration import org.jetbrains.kotlin.psi.KtParameter @@ -36,10 +25,10 @@ class RenameKotlinParameterProcessor : RenameKotlinPsiProcessor() { } override fun findCollisions( - element: PsiElement, - newName: String, - allRenames: MutableMap, - result: MutableList + element: PsiElement, + newName: String, + allRenames: MutableMap, + result: MutableList ) { val declaration = element.namedUnwrappedElement as? KtNamedDeclaration ?: return diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameKotlinPropertyProcessor.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameKotlinPropertyProcessor.kt index 0cc7b4b146f..452a49afa14 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameKotlinPropertyProcessor.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameKotlinPropertyProcessor.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.rename @@ -25,7 +14,6 @@ import com.intellij.psi.* import com.intellij.psi.search.SearchScope import com.intellij.psi.search.searches.DirectClassInheritorsSearch import com.intellij.psi.search.searches.OverridingMethodsSearch -import org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringSettings import com.intellij.refactoring.listeners.RefactoringElementListener import com.intellij.refactoring.rename.RenameProcessor import com.intellij.refactoring.util.MoveRenameUsageInfo @@ -49,6 +37,7 @@ import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor import org.jetbrains.kotlin.idea.core.getDeepestSuperDeclarations import org.jetbrains.kotlin.idea.core.isEnumCompanionPropertyWithEntryConflict import org.jetbrains.kotlin.idea.core.unquote +import org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringSettings import org.jetbrains.kotlin.idea.refactoring.checkSuperMethodsWithPopup import org.jetbrains.kotlin.idea.refactoring.dropOverrideKeywordIfNecessary import org.jetbrains.kotlin.idea.references.KtDestructuringDeclarationReference @@ -103,9 +92,7 @@ class RenameKotlinPropertyProcessor : RenameKotlinPsiProcessor() { return when { getterJvmName == null && setterJvmName == null -> allReferences element is KtElement -> allReferences.filter { - it is KtReference - || (getterJvmName == null && (it.resolve() as? PsiNamedElement)?.name != setterJvmName) - || (setterJvmName == null && (it.resolve() as? PsiNamedElement)?.name != getterJvmName) + it is KtReference || (getterJvmName == null && (it.resolve() as? PsiNamedElement)?.name != setterJvmName) || (setterJvmName == null && (it.resolve() as? PsiNamedElement)?.name != getterJvmName) } element is KtLightDeclaration<*, *> -> { val name = element.name @@ -116,10 +103,10 @@ class RenameKotlinPropertyProcessor : RenameKotlinPsiProcessor() { } private fun checkAccidentalOverrides( - declaration: KtNamedDeclaration, - newName: String, - descriptor: VariableDescriptor, - result: MutableList + declaration: KtNamedDeclaration, + newName: String, + descriptor: VariableDescriptor, + result: MutableList ) { fun reportAccidentalOverride(candidate: PsiNamedElement) { val what = UsageViewUtil.getType(declaration).capitalize() @@ -138,23 +125,23 @@ class RenameKotlinPropertyProcessor : RenameKotlinPsiProcessor() { } DFS.dfs( - listOf(initialClassDescriptor), - DFS.Neighbors { DescriptorUtils.getSuperclassDescriptors(it) }, - object : DFS.AbstractNodeHandler() { - override fun beforeChildren(current: ClassDescriptor): Boolean { - if (current == initialClassDescriptor) return true - (current.findCallableMemberBySignature(prototype))?.let { candidateDescriptor -> - val candidate = candidateDescriptor.source.getPsi() as? PsiNamedElement ?: return false - reportAccidentalOverride(candidate) - return false - } - return true - } - - override fun result() { - + listOf(initialClassDescriptor), + DFS.Neighbors { DescriptorUtils.getSuperclassDescriptors(it) }, + object : DFS.AbstractNodeHandler() { + override fun beforeChildren(current: ClassDescriptor): Boolean { + if (current == initialClassDescriptor) return true + (current.findCallableMemberBySignature(prototype))?.let { candidateDescriptor -> + val candidate = candidateDescriptor.source.getPsi() as? PsiNamedElement ?: return false + reportAccidentalOverride(candidate) + return false } + return true } + + override fun result() { + + } + } ) if (!declaration.hasModifier(KtTokens.PRIVATE_KEYWORD)) { @@ -167,42 +154,42 @@ class RenameKotlinPropertyProcessor : RenameKotlinPsiProcessor() { } } DFS.dfs( - listOf(initialPsiClass), - DFS.Neighbors { DirectClassInheritorsSearch.search(it) }, - object : DFS.AbstractNodeHandler() { - override fun beforeChildren(current: PsiClass): Boolean { - if (current == initialPsiClass) return true + listOf(initialPsiClass), + DFS.Neighbors { DirectClassInheritorsSearch.search(it) }, + object : DFS.AbstractNodeHandler() { + override fun beforeChildren(current: PsiClass): Boolean { + if (current == initialPsiClass) return true - if (current is KtLightClass) { - val property = current.kotlinOrigin?.findPropertyByName(newName) ?: return true - reportAccidentalOverride(property) + if (current is KtLightClass) { + val property = current.kotlinOrigin?.findPropertyByName(newName) ?: return true + reportAccidentalOverride(property) + return false + } + + for (psiMethod in prototypes) { + current.findMethodBySignature(psiMethod, false)?.let { + val candidate = it.unwrapped as? PsiNamedElement ?: return true + reportAccidentalOverride(candidate) return false } - - for (psiMethod in prototypes) { - current.findMethodBySignature(psiMethod, false)?.let { - val candidate = it.unwrapped as? PsiNamedElement ?: return true - reportAccidentalOverride(candidate) - return false - } - } - - return true } - override fun result() { - - } + return true } + + override fun result() { + + } + } ) } } override fun findCollisions( - element: PsiElement, - newName: String, - allRenames: MutableMap, - result: MutableList + element: PsiElement, + newName: String, + allRenames: MutableMap, + result: MutableList ) { val declaration = element.namedUnwrappedElement as? KtNamedDeclaration ?: return val resolutionFacade = declaration.getResolutionFacade() @@ -225,14 +212,14 @@ class RenameKotlinPropertyProcessor : RenameKotlinPsiProcessor() { if (ApplicationManager.getApplication()!!.isUnitTestMode) return deepestSuperDeclaration val containsText: String? = - deepestSuperDeclaration.fqName?.parent()?.asString() ?: - (deepestSuperDeclaration.parent as? KtClassOrObject)?.name + deepestSuperDeclaration.fqName?.parent()?.asString() ?: (deepestSuperDeclaration.parent as? KtClassOrObject)?.name val result = Messages.showYesNoCancelDialog( - deepestSuperDeclaration.project, - if (containsText != null) "Do you want to rename base property from \n$containsText" else "Do you want to rename base property", - "Rename warning", - Messages.getQuestionIcon()) + deepestSuperDeclaration.project, + if (containsText != null) "Do you want to rename base property from \n$containsText" else "Do you want to rename base property", + "Rename warning", + Messages.getQuestionIcon() + ) return when (result) { Messages.YES -> deepestSuperDeclaration @@ -245,7 +232,7 @@ class RenameKotlinPropertyProcessor : RenameKotlinPsiProcessor() { val namedUnwrappedElement = element.namedUnwrappedElement ?: return null val callableDeclaration = namedUnwrappedElement as? KtCallableDeclaration - ?: throw IllegalStateException("Can't be for element $element there because of canProcessElement()") + ?: throw IllegalStateException("Can't be for element $element there because of canProcessElement()") val declarationToRename = chooseCallableToRename(callableDeclaration) ?: return null @@ -263,7 +250,7 @@ class RenameKotlinPropertyProcessor : RenameKotlinPsiProcessor() { val namedUnwrappedElement = element.namedUnwrappedElement ?: return val callableDeclaration = namedUnwrappedElement as? KtCallableDeclaration - ?: throw IllegalStateException("Can't be for element $element there because of canProcessElement()") + ?: throw IllegalStateException("Can't be for element $element there because of canProcessElement()") fun preprocessAndPass(substitutedJavaElement: PsiElement) { val (getterJvmName, setterJvmName) = getJvmNames(namedUnwrappedElement) @@ -271,12 +258,10 @@ class RenameKotlinPropertyProcessor : RenameKotlinPsiProcessor() { val name = element.name if (element.name != getterJvmName && element.name != setterJvmName) { substitutedJavaElement - } - else { + } else { substitutedJavaElement.toLightMethods().firstOrNull { it.name == name } } - } - else substitutedJavaElement + } else substitutedJavaElement renameCallback.pass(elementToProcess) } @@ -291,7 +276,8 @@ class RenameKotlinPropertyProcessor : RenameKotlinPsiProcessor() { } } - class PropertyMethodWrapper(private val propertyMethod: PsiMethod) : PsiNamedElement by propertyMethod, NavigationItem by propertyMethod { + class PropertyMethodWrapper(private val propertyMethod: PsiMethod) : PsiNamedElement by propertyMethod, + NavigationItem by propertyMethod { override fun getName() = propertyMethod.name override fun setName(name: String) = this override fun copy() = this @@ -301,7 +287,7 @@ class RenameKotlinPropertyProcessor : RenameKotlinPsiProcessor() { super.prepareRenaming(element, newName, allRenames, scope) val namedUnwrappedElement = element.namedUnwrappedElement - val propertyMethods = when(namedUnwrappedElement) { + val propertyMethods = when (namedUnwrappedElement) { is KtProperty -> runReadAction { LightClassUtil.getLightClassPropertyMethods(namedUnwrappedElement) } is KtParameter -> runReadAction { LightClassUtil.getLightClassPropertyMethods(namedUnwrappedElement) } else -> throw IllegalStateException("Can't be for element $element there because of canProcessElement()") @@ -316,13 +302,16 @@ class RenameKotlinPropertyProcessor : RenameKotlinPsiProcessor() { if (newPropertyName != null && getter != null && setter != null && (element == getter || element == setter) - && propertyNameByAccessor(getter.name, getter) == propertyNameByAccessor(setter.name, setter)) { + && propertyNameByAccessor(getter.name, getter) == propertyNameByAccessor(setter.name, setter) + ) { val accessorToRename = if (element == getter) setter else getter val newAccessorName = if (element == getter) JvmAbi.setterName(newPropertyName) else JvmAbi.getterName(newPropertyName) - if (ApplicationManager.getApplication().isUnitTestMode - || Messages.showYesNoDialog("Do you want to rename ${accessorToRename.name}() as well?", - "Rename", - Messages.getQuestionIcon()) == Messages.YES) { + if (ApplicationManager.getApplication().isUnitTestMode || Messages.showYesNoDialog( + "Do you want to rename ${accessorToRename.name}() as well?", + "Rename", + Messages.getQuestionIcon() + ) == Messages.YES + ) { allRenames[accessorToRename] = newAccessorName } } @@ -353,7 +342,12 @@ class RenameKotlinPropertyProcessor : RenameKotlinPsiProcessor() { } //TODO: a very long and complicated method, even recursive. mb refactor it somehow? at least split by PsiElement types? - override tailrec fun renameElement(element: PsiElement, newName: String, usages: Array, listener: RefactoringElementListener?) { + override tailrec fun renameElement( + element: PsiElement, + newName: String, + usages: Array, + listener: RefactoringElementListener? + ) { val newNameUnquoted = newName.unquote() if (element is KtLightMethod) { if (element.modifierList.findAnnotation(DescriptorUtils.JVM_NAME.asString()) != null) { @@ -413,17 +407,23 @@ class RenameKotlinPropertyProcessor : RenameKotlinPsiProcessor() { } } - super.renameElement(element.copy(), JvmAbi.setterName(newNameUnquoted).quoteIfNeeded(), - refKindUsages[UsageKind.SETTER_USAGE]?.toTypedArray() ?: arrayOf(), - null) + super.renameElement( + element.copy(), JvmAbi.setterName(newNameUnquoted).quoteIfNeeded(), + refKindUsages[UsageKind.SETTER_USAGE]?.toTypedArray() ?: arrayOf(), + null + ) - super.renameElement(element.copy(), JvmAbi.getterName(newNameUnquoted).quoteIfNeeded(), - refKindUsages[UsageKind.GETTER_USAGE]?.toTypedArray() ?: arrayOf(), - null) + super.renameElement( + element.copy(), JvmAbi.getterName(newNameUnquoted).quoteIfNeeded(), + refKindUsages[UsageKind.GETTER_USAGE]?.toTypedArray() ?: arrayOf(), + null + ) - super.renameElement(element, newName, - refKindUsages[UsageKind.SIMPLE_PROPERTY_USAGE]?.toTypedArray() ?: arrayOf(), - null) + super.renameElement( + element, newName, + refKindUsages[UsageKind.SIMPLE_PROPERTY_USAGE]?.toTypedArray() ?: arrayOf(), + null + ) usages.forEach { (it as? KtResolvableCollisionUsageInfo)?.apply() } @@ -432,11 +432,13 @@ class RenameKotlinPropertyProcessor : RenameKotlinPsiProcessor() { listener?.elementRenamed(element) } - private fun addRenameElements(psiMethod: PsiMethod?, - oldName: String?, - newName: String?, - allRenames: MutableMap, - scope: SearchScope) { + private fun addRenameElements( + psiMethod: PsiMethod?, + oldName: String?, + newName: String?, + allRenames: MutableMap, + scope: SearchScope + ) { if (psiMethod == null) return OverridingMethodsSearch.search(psiMethod, scope, true).forEach { overrider -> @@ -452,9 +454,9 @@ class RenameKotlinPropertyProcessor : RenameKotlinPsiProcessor() { val isGetter = overriderElement.parameterList.parametersCount == 0 allRenames[overriderElement] = if (isGetter) JvmAbi.getterName(newName) else JvmAbi.setterName(newName) } - } - else { - val demangledName = if (newName != null && overrider is KtLightMethod && overrider.isMangled) demangleInternalName(newName) else null + } else { + val demangledName = + if (newName != null && overrider is KtLightMethod && overrider.isMangled) demangleInternalName(newName) else null val adjustedName = demangledName ?: newName val newOverriderName = RefactoringUtil.suggestNewOverriderName(overriderName, oldName, adjustedName) if (newOverriderName != null) { diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameKotlinPsiProcessor.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameKotlinPsiProcessor.kt index 4accf3af365..452aab0bae7 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameKotlinPsiProcessor.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameKotlinPsiProcessor.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.rename @@ -58,12 +47,12 @@ abstract class RenameKotlinPsiProcessor : RenamePsiElementProcessor() { ref: PsiReference, referenceElement: PsiElement ) : MoveRenameUsageInfo( - referenceElement, - ref, - ref.getRangeInElement().getStartOffset(), - ref.getRangeInElement().getEndOffset(), - element, - false + referenceElement, + ref, + ref.getRangeInElement().getStartOffset(), + ref.getRangeInElement().getEndOffset(), + element, + false ) override fun canProcessElement(element: PsiElement): Boolean = element is KtNamedDeclaration @@ -77,9 +66,7 @@ abstract class RenameKotlinPsiProcessor : RenamePsiElementProcessor() { kotlinOptions = KotlinReferencesSearchOptions(searchForComponentConventions = false) ) val references = ReferencesSearch.search(searchParameters).toMutableList() - if (element is KtNamedFunction - || (element is KtProperty && !element.isLocal) - || (element is KtParameter && element.hasValOrVar())) { + if (element is KtNamedFunction || (element is KtProperty && !element.isLocal) || (element is KtParameter && element.hasValOrVar())) { element.toLightMethods().flatMapTo(references) { MethodReferencesSearch.search(it) } } return references @@ -91,10 +78,10 @@ abstract class RenameKotlinPsiProcessor : RenamePsiElementProcessor() { if (targetElement is KtLightMethod && targetElement.isMangled) { KotlinTypeMapper.InternalNameMapper.getModuleNameSuffix(targetElement.name)?.let { return MangledJavaRefUsageInfo( - it, - element, - ref, - referenceElement + it, + element, + ref, + referenceElement ) } } @@ -140,12 +127,14 @@ abstract class RenameKotlinPsiProcessor : RenamePsiElementProcessor() { protected fun UsageInfo.isAmbiguousImportUsage(): Boolean { val ref = reference as? PsiPolyVariantReference ?: return false val refElement = ref.element - return refElement.parents.any { (it is KtImportDirective && !it.isAllUnder) || (it is PsiImportStaticStatement && !it.isOnDemand) } - && ref.multiResolve(false).mapNotNullTo(HashSet()) { it.element?.unwrapped }.size > 1 + return refElement.parents + .any { (it is KtImportDirective && !it.isAllUnder) || (it is PsiImportStaticStatement && !it.isOnDemand) } && ref.multiResolve( + false + ).mapNotNullTo(HashSet()) { it.element?.unwrapped }.size > 1 } protected fun renameMangledUsageIfPossible(usage: UsageInfo, element: PsiElement, newName: String): Boolean { - val chosenName = if (usage is MangledJavaRefUsageInfo) { + val chosenName = (if (usage is MangledJavaRefUsageInfo) { KotlinTypeMapper.InternalNameMapper.mangleInternalName(newName, usage.manglingSuffix) } else { val reference = usage.reference @@ -154,8 +143,7 @@ abstract class RenameKotlinPsiProcessor : RenamePsiElementProcessor() { KotlinTypeMapper.InternalNameMapper.demangleInternalName(newName) } else null } else null - } - if (chosenName == null) return false + }) ?: return false usage.reference?.handleElementRename(chosenName) return true } @@ -183,13 +171,12 @@ abstract class RenameKotlinPsiProcessor : RenamePsiElementProcessor() { if (!renameMangledUsageIfPossible(it, element, newName)) { ref.handleElementRename(newName) } - } - else { + } else { ref.element.getStrictParentOfType()?.let { importDirective -> val fqName = importDirective.importedFqName!! val newFqName = fqName.parent().child(Name.identifier(newName)) val importList = importDirective.parent as KtImportList - if (importList.imports.none { it.importedFqName == newFqName }) { + if (importList.imports.none { directive -> directive.importedFqName == newFqName }) { val newImportDirective = KtPsiFactory(element).createImportDirective(ImportPath(newFqName, false)) importDirective.parent.addAfter(newImportDirective, importDirective) } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameKotlinTypeParameterProcessor.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameKotlinTypeParameterProcessor.kt index 3eb25e45034..fc2adb00ba0 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameKotlinTypeParameterProcessor.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameKotlinTypeParameterProcessor.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.rename @@ -24,10 +13,10 @@ class RenameKotlinTypeParameterProcessor : RenameKotlinPsiProcessor() { override fun canProcessElement(element: PsiElement) = element is KtTypeParameter override fun findCollisions( - element: PsiElement, - newName: String, - allRenames: MutableMap, - result: MutableList + element: PsiElement, + newName: String, + allRenames: MutableMap, + result: MutableList ) { val declaration = element as? KtTypeParameter ?: return checkRedeclarations(declaration, newName, result) diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameOnSecondaryConstructorHandler.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameOnSecondaryConstructorHandler.kt index 78da4334fbc..3a3eb13cb24 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameOnSecondaryConstructorHandler.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameOnSecondaryConstructorHandler.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.rename @@ -34,8 +23,14 @@ class RenameOnSecondaryConstructorHandler : RenameHandler { val file = CommonDataKeys.PSI_FILE.getData(dataContext) ?: return false val element = PsiTreeUtil.findElementOfClassAtOffsetWithStopSet( - file, editor.caretModel.offset, KtSecondaryConstructor::class.java, false, - KtBlockExpression::class.java, KtValueArgumentList::class.java, KtParameterList::class.java, KtConstructorDelegationCall::class.java + file, + editor.caretModel.offset, + KtSecondaryConstructor::class.java, + false, + KtBlockExpression::class.java, + KtValueArgumentList::class.java, + KtParameterList::class.java, + KtConstructorDelegationCall::class.java ) return element != null } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/renameConflictUtils.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/renameConflictUtils.kt index 23687afb234..2cd3a9b592b 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/renameConflictUtils.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/renameConflictUtils.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.rename @@ -77,14 +66,13 @@ internal fun PsiNamedElement.renderDescription(): String { return "$type '$name'".trim() } -internal fun PsiElement.representativeContainer(): PsiNamedElement? = - when (this) { - is KtDeclaration -> containingClassOrObject - ?: getStrictParentOfType() - ?: JavaPsiFacade.getInstance(project).findPackage(containingKtFile.packageFqName.asString()) - is PsiMember -> containingClass - else -> null - } +internal fun PsiElement.representativeContainer(): PsiNamedElement? = when (this) { + is KtDeclaration -> containingClassOrObject + ?: getStrictParentOfType() + ?: JavaPsiFacade.getInstance(project).findPackage(containingKtFile.packageFqName.asString()) + is PsiMember -> containingClass + else -> null +} internal fun DeclarationDescriptor.canonicalRender(): String = DescriptorRenderer.FQ_NAMES_IN_TYPES.render(this) @@ -95,15 +83,12 @@ internal fun checkRedeclarations( resolutionFacade: ResolutionFacade = declaration.getResolutionFacade(), descriptor: DeclarationDescriptor = declaration.unsafeResolveToDescriptor(resolutionFacade) ) { - fun DeclarationDescriptor.isTopLevelPrivate(): Boolean { - return this is DeclarationDescriptorWithVisibility - && visibility == Visibilities.PRIVATE - && containingDeclaration is PackageFragmentDescriptor - } + fun DeclarationDescriptor.isTopLevelPrivate(): Boolean = + this is DeclarationDescriptorWithVisibility && visibility == Visibilities.PRIVATE && containingDeclaration is PackageFragmentDescriptor - fun isInSameFile(d1: DeclarationDescriptor, d2: DeclarationDescriptor): Boolean { - return (d1 as? DeclarationDescriptorWithSource)?.source?.getPsi()?.containingFile == (d2 as? DeclarationDescriptorWithSource)?.source?.getPsi()?.containingFile - } + fun isInSameFile(d1: DeclarationDescriptor, d2: DeclarationDescriptor): Boolean = + (d1 as? DeclarationDescriptorWithSource)?.source?.getPsi()?.containingFile == (d2 as? DeclarationDescriptorWithSource)?.source + ?.getPsi()?.containingFile fun MemberScope.findSiblingsByName(): List { val descriptorKindFilter = when (descriptor) { @@ -132,7 +117,7 @@ internal fun checkRedeclarations( return SmartList().apply { typeParameters.filterTo(this) { it.name.asString() == newName } val containingDeclaration = (containingDescriptor as? DeclarationDescriptorWithSource)?.source?.getPsi() as? KtDeclaration - ?: return emptyList() + ?: return emptyList() val dummyVar = KtPsiFactory(containingDeclaration).createProperty("val foo: $newName") val outerScope = containingDeclaration.getResolutionScope() val context = dummyVar.analyzeInContext(outerScope, containingDeclaration) @@ -143,12 +128,11 @@ internal fun checkRedeclarations( return when (containingDescriptor) { is ClassDescriptor -> containingDescriptor.unsubstitutedMemberScope.findSiblingsByName() is PackageFragmentDescriptor -> containingDescriptor.getMemberScope().findSiblingsByName().filter { - it != descriptor - && (!(descriptor.isTopLevelPrivate() || it.isTopLevelPrivate()) || isInSameFile(descriptor, it)) + it != descriptor && (!(descriptor.isTopLevelPrivate() || it.isTopLevelPrivate()) || isInSameFile(descriptor, it)) } else -> { - val block = (descriptor as? DeclarationDescriptorWithSource)?.source?.getPsi()?.parent as? KtBlockExpression - ?: return emptyList() + val block = + (descriptor as? DeclarationDescriptorWithSource)?.source?.getPsi()?.parent as? KtBlockExpression ?: return emptyList() block.statements.mapNotNull { if (it.name != newName) return@mapNotNull null val isAccepted = when (descriptor) { @@ -184,8 +168,8 @@ internal fun checkRedeclarations( } private fun LexicalScope.getRelevantDescriptors( - declaration: PsiNamedElement, - name: String + declaration: PsiNamedElement, + name: String ): Collection { val nameAsName = Name.identifier(name) return when (declaration) { @@ -197,11 +181,11 @@ private fun LexicalScope.getRelevantDescriptors( } fun reportShadowing( - declaration: PsiNamedElement, - elementToBindUsageInfoTo: PsiElement, - candidateDescriptor: DeclarationDescriptor, - refElement: PsiElement, - result: MutableList + declaration: PsiNamedElement, + elementToBindUsageInfoTo: PsiElement, + candidateDescriptor: DeclarationDescriptor, + refElement: PsiElement, + result: MutableList ) { val candidate = DescriptorToSourceUtilsIde.getAnyDeclaration(declaration.project, candidateDescriptor) as? PsiNamedElement ?: return if (declaration.parent == candidate.parent) return @@ -211,25 +195,24 @@ fun reportShadowing( // todo: break into smaller functions private fun checkUsagesRetargeting( - elementToBindUsageInfosTo: PsiElement, - declaration: PsiNamedElement, - name: String, - isNewName: Boolean, - accessibleDescriptors: Collection, - originalUsages: MutableList, - newUsages: MutableList + elementToBindUsageInfosTo: PsiElement, + declaration: PsiNamedElement, + name: String, + isNewName: Boolean, + accessibleDescriptors: Collection, + originalUsages: MutableList, + newUsages: MutableList ) { val usageIterator = originalUsages.listIterator() while (usageIterator.hasNext()) { val usage = usageIterator.next() val refElement = usage.element as? KtSimpleNameExpression ?: continue val context = refElement.analyze(BodyResolveMode.PARTIAL) - val scope = refElement - .parentsWithSelf - .filterIsInstance() - .mapNotNull { context[BindingContext.LEXICAL_SCOPE, it] } - .firstOrNull() - ?: continue + val scope = refElement.parentsWithSelf + .filterIsInstance() + .mapNotNull { context[BindingContext.LEXICAL_SCOPE, it] } + .firstOrNull() + ?: continue if (scope.getRelevantDescriptors(declaration, name).isEmpty()) { if (declaration !is KtProperty && declaration !is KtParameter) continue @@ -251,10 +234,10 @@ private fun checkUsagesRetargeting( if (referencedClassInNewContext == null || ErrorUtils.isError(referencedClassInNewContext) || referencedClass.canonicalRender() == candidateText - || accessibleDescriptors.any { it.canonicalRender() == candidateText }) { + || accessibleDescriptors.any { it.canonicalRender() == candidateText } + ) { usageIterator.set(UsageInfoWithFqNameReplacement(refElement, declaration, newFqName)) - } - else { + } else { reportShadowing(declaration, elementToBindUsageInfosTo, referencedClassInNewContext, refElement, newUsages) } continue @@ -265,24 +248,20 @@ private fun checkUsagesRetargeting( val qualifiedExpression = if (resolvedCall.noReceivers()) { val resultingDescriptor = resolvedCall.resultingDescriptor - val fqName = - resultingDescriptor.importableFqName - ?: (resultingDescriptor as? ClassifierDescriptor)?.let { - FqName(IdeDescriptorRenderers.SOURCE_CODE.renderClassifierName(it)) - } - ?: continue + val fqName = resultingDescriptor.importableFqName + ?: (resultingDescriptor as? ClassifierDescriptor)?.let { + FqName(IdeDescriptorRenderers.SOURCE_CODE.renderClassifierName(it)) + } + ?: continue if (fqName.parent().isRoot) { callExpression.copied() - } - else { + } else { psiFactory.createExpressionByPattern("${fqName.parent().asString()}.$0", callExpression) } - } - else { + } else { resolvedCall.getExplicitReceiverValue()?.let { fullCallExpression.copied() - } - ?: resolvedCall.getImplicitReceiverValue()?.let { implicitReceiver -> + } ?: resolvedCall.getImplicitReceiverValue()?.let { implicitReceiver -> val expectedLabelName = implicitReceiver.declarationDescriptor.getThisLabelName() val implicitReceivers = scope.getImplicitReceiversHierarchy() val receiversWithExpectedName = implicitReceivers.filter { @@ -290,18 +269,16 @@ private fun checkUsagesRetargeting( } val canQualifyThis = receiversWithExpectedName.isEmpty() - || receiversWithExpectedName.size == 1 && (declaration !is KtClassOrObject || expectedLabelName != name) + || receiversWithExpectedName.size == 1 && (declaration !is KtClassOrObject || expectedLabelName != name) if (canQualifyThis) { psiFactory.createExpressionByPattern("${implicitReceiver.explicateAsText()}.$0", callExpression) - } - else { + } else { val defaultReceiverClassText = - implicitReceivers.firstOrNull()?.value?.type?.constructor?.declarationDescriptor?.canonicalRender() + implicitReceivers.firstOrNull()?.value?.type?.constructor?.declarationDescriptor?.canonicalRender() val canInsertUnqualifiedThis = accessibleDescriptors.any { it.canonicalRender() == defaultReceiverClassText } if (canInsertUnqualifiedThis) { psiFactory.createExpressionByPattern("this.$0", callExpression) - } - else { + } else { callExpression.copied() } } @@ -322,7 +299,8 @@ private fun checkUsagesRetargeting( if (newResolvedCall != null && !accessibleDescriptors.any { it.canonicalRender() == candidateText } - && resolvedCall.candidateDescriptor.canonicalRender() != candidateText) { + && resolvedCall.candidateDescriptor.canonicalRender() != candidateText + ) { reportShadowing(declaration, elementToBindUsageInfosTo, newResolvedCall.candidateDescriptor, refElement, newUsages) continue } @@ -334,19 +312,19 @@ private fun checkUsagesRetargeting( } internal fun checkOriginalUsagesRetargeting( - declaration: KtNamedDeclaration, - newName: String, - originalUsages: MutableList, - newUsages: MutableList + declaration: KtNamedDeclaration, + newName: String, + originalUsages: MutableList, + newUsages: MutableList ) { val accessibleDescriptors = declaration.getResolutionScope().getRelevantDescriptors(declaration, newName) checkUsagesRetargeting(declaration, declaration, newName, true, accessibleDescriptors, originalUsages, newUsages) } internal fun checkNewNameUsagesRetargeting( - declaration: KtNamedDeclaration, - newName: String, - newUsages: MutableList + declaration: KtNamedDeclaration, + newName: String, + newUsages: MutableList ) { val currentName = declaration.name ?: return val descriptor = declaration.unsafeResolveToDescriptor() @@ -358,14 +336,14 @@ internal fun checkNewNameUsagesRetargeting( val usagesByCandidate = LinkedHashMap>() searchScope.accept( - object: KtTreeVisitorVoid() { - override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { - if (expression.getReferencedName() != newName) return - val ref = expression.mainReference - val candidate = ref.resolve() as? PsiNamedElement ?: return - usagesByCandidate.getOrPut(candidate) { SmartList() }.add(MoveRenameUsageInfo(ref, candidate)) - } + object : KtTreeVisitorVoid() { + override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { + if (expression.getReferencedName() != newName) return + val ref = expression.mainReference + val candidate = ref.resolve() as? PsiNamedElement ?: return + usagesByCandidate.getOrPut(candidate) { SmartList() }.add(MoveRenameUsageInfo(ref, candidate)) } + } ) for ((candidate, usages) in usagesByCandidate) { @@ -377,10 +355,10 @@ internal fun checkNewNameUsagesRetargeting( } for (candidateDescriptor in declaration.getResolutionScope().getRelevantDescriptors(declaration, newName)) { - val candidate = DescriptorToSourceUtilsIde.getAnyDeclaration(declaration.project, candidateDescriptor) as? PsiNamedElement ?: continue - val usages = ReferencesSearch - .search(candidate, candidate.useScope.restrictToKotlinSources() and declaration.useScope) - .mapTo(SmartList()) { MoveRenameUsageInfo(it, candidate) } + val candidate = + DescriptorToSourceUtilsIde.getAnyDeclaration(declaration.project, candidateDescriptor) as? PsiNamedElement ?: continue + val usages = ReferencesSearch.search(candidate, candidate.useScope.restrictToKotlinSources() and declaration.useScope) + .mapTo(SmartList()) { MoveRenameUsageInfo(it, candidate) } checkUsagesRetargeting(candidate, declaration, currentName, false, listOf(descriptor), usages, newUsages) usages.filterIsInstanceTo>(newUsages) } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/renameUtil.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/renameUtil.kt index 0ed231237ed..ab959cd7ab3 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/renameUtil.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/renameUtil.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.rename @@ -33,9 +22,9 @@ import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.resolve.source.getPsi fun checkConflictsAndReplaceUsageInfos( - element: PsiElement, - allRenames: Map, - result: MutableList + element: PsiElement, + allRenames: Map, + result: MutableList ) { element.getOverriddenFunctionWithDefaultValues(allRenames)?.let { baseFunction -> result += LostDefaultValuesInOverridingFunctionUsageInfo(element.unwrapped as KtNamedFunction, baseFunction) @@ -58,20 +47,20 @@ private fun PsiElement.getOverriddenFunctionWithDefaultValues(allRenames: Map PsiFile.findElementForRename(offset: Int): T? { return PsiTreeUtil.findElementOfClassAtOffset(this, offset, T::class.java, false) - ?: PsiTreeUtil.findElementOfClassAtOffset(this, (offset - 1).coerceAtLeast(0), T::class.java, false) + ?: PsiTreeUtil.findElementOfClassAtOffset(this, (offset - 1).coerceAtLeast(0), T::class.java, false) } \ No newline at end of file diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/safeDelete/KotlinJavaSafeDeleteDelegate.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/safeDelete/KotlinJavaSafeDeleteDelegate.kt index 6b3bc9e5afd..f8a3de9abe4 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/safeDelete/KotlinJavaSafeDeleteDelegate.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/safeDelete/KotlinJavaSafeDeleteDelegate.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.safeDelete @@ -36,7 +25,7 @@ import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils class KotlinJavaSafeDeleteDelegate : JavaSafeDeleteDelegate { override fun createUsageInfoForParameter( - reference: PsiReference, usages: MutableList, parameter: PsiParameter, method: PsiMethod + reference: PsiReference, usages: MutableList, parameter: PsiParameter, method: PsiMethod ) { if (reference !is KtReference) return @@ -57,7 +46,7 @@ class KotlinJavaSafeDeleteDelegate : JavaSafeDeleteDelegate { val args = callExpression.valueArguments val namedArguments = args.filter { arg -> arg is KtValueArgument && arg.getArgumentName()?.text == parameter.name } - if (!namedArguments.isEmpty()) { + if (namedArguments.isNotEmpty()) { usages.add(SafeDeleteValueArgumentListUsageInfo(parameter, namedArguments.first())) return } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/safeDelete/KotlinSafeDeleteOverrideAnnotation.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/safeDelete/KotlinSafeDeleteOverrideAnnotation.kt index 2872cf18094..9eba258eeb4 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/safeDelete/KotlinSafeDeleteOverrideAnnotation.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/safeDelete/KotlinSafeDeleteOverrideAnnotation.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.safeDelete @@ -21,7 +10,7 @@ import com.intellij.refactoring.safeDelete.usageInfo.SafeDeleteCustomUsageInfo import com.intellij.refactoring.safeDelete.usageInfo.SafeDeleteUsageInfo class KotlinSafeDeleteOverrideAnnotation( - element: PsiElement, referencedElement: PsiElement + element: PsiElement, referencedElement: PsiElement ) : SafeDeleteUsageInfo(element, referencedElement), SafeDeleteCustomUsageInfo { override fun performRefactoring() { element?.removeOverrideModifier() diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/safeDelete/KotlinSafeDeleteOverridingUsageInfo.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/safeDelete/KotlinSafeDeleteOverridingUsageInfo.kt index c56feb8004a..bac22006c88 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/safeDelete/KotlinSafeDeleteOverridingUsageInfo.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/safeDelete/KotlinSafeDeleteOverridingUsageInfo.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.safeDelete @@ -22,7 +11,7 @@ import com.intellij.refactoring.safeDelete.usageInfo.SafeDeleteUsageInfo import org.jetbrains.kotlin.psi.KtPsiUtil class KotlinSafeDeleteOverridingUsageInfo( - overridingElement: PsiElement, superElement: PsiElement + overridingElement: PsiElement, superElement: PsiElement ) : SafeDeleteUsageInfo(overridingElement, superElement), SafeDeleteCustomUsageInfo { val overridingElement: PsiElement get() = element!! diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/safeDelete/SafeDeleteImportDirectiveUsageInfo.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/safeDelete/SafeDeleteImportDirectiveUsageInfo.kt index 14e9dc3faef..df44c346930 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/safeDelete/SafeDeleteImportDirectiveUsageInfo.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/safeDelete/SafeDeleteImportDirectiveUsageInfo.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.safeDelete @@ -28,7 +17,7 @@ import org.jetbrains.kotlin.psi.KtImportDirective import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class SafeDeleteImportDirectiveUsageInfo( - importDirective: KtImportDirective, declaration: PsiElement + importDirective: KtImportDirective, declaration: PsiElement ) : SafeDeleteReferenceSimpleDeleteUsageInfo(importDirective, declaration, importDirective.isSafeToDelete(declaration)) private fun KtImportDirective.isSafeToDelete(element: PsiElement): Boolean { diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/safeDelete/SafeDeleteSuperTypeUsageInfo.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/safeDelete/SafeDeleteSuperTypeUsageInfo.kt index fd6633cfa6b..2dee67b37ee 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/safeDelete/SafeDeleteSuperTypeUsageInfo.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/safeDelete/SafeDeleteSuperTypeUsageInfo.kt @@ -1,3 +1,8 @@ +/* + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. + */ + package org.jetbrains.kotlin.idea.refactoring.safeDelete import com.intellij.psi.PsiElement @@ -6,8 +11,8 @@ import org.jetbrains.kotlin.psi.KtSuperTypeEntry import org.jetbrains.kotlin.psi.KtSuperTypeList class SafeDeleteSuperTypeUsageInfo( - entry: KtSuperTypeEntry, - referencedElement: PsiElement + entry: KtSuperTypeEntry, + referencedElement: PsiElement ) : SafeDeleteReferenceUsageInfo(entry, referencedElement, true) { private val entry: KtSuperTypeEntry? get() = element as? KtSuperTypeEntry diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/safeDelete/SafeDeleteTypeArgumentListUsageInfo.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/safeDelete/SafeDeleteTypeArgumentListUsageInfo.kt index 3176ff60379..a120d32e959 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/safeDelete/SafeDeleteTypeArgumentListUsageInfo.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/safeDelete/SafeDeleteTypeArgumentListUsageInfo.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.safeDelete @@ -22,7 +11,7 @@ import org.jetbrains.kotlin.psi.KtTypeParameter import org.jetbrains.kotlin.psi.KtTypeProjection class SafeDeleteTypeArgumentListUsageInfo( - typeProjection: KtTypeProjection, parameter: KtTypeParameter + typeProjection: KtTypeProjection, parameter: KtTypeParameter ) : SafeDeleteReferenceSimpleDeleteUsageInfo(typeProjection, parameter, true) { override fun deleteElement() { element?.deleteElementAndCleanParent() diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/safeDelete/SafeDeleteValueArgumentListUsageInfo.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/safeDelete/SafeDeleteValueArgumentListUsageInfo.kt index b2808c7bb33..fd0a3f91d95 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/safeDelete/SafeDeleteValueArgumentListUsageInfo.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/safeDelete/SafeDeleteValueArgumentListUsageInfo.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.safeDelete @@ -23,8 +12,8 @@ import org.jetbrains.kotlin.psi.KtValueArgumentList import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer class SafeDeleteValueArgumentListUsageInfo( - parameter: PsiElement, - vararg valueArguments: KtValueArgument + parameter: PsiElement, + vararg valueArguments: KtValueArgument ) : SafeDeleteReferenceSimpleDeleteUsageInfo(valueArguments.first(), parameter, true) { private val valueArgumentPointers = valueArguments.map { it.createSmartPointer() } @@ -34,8 +23,7 @@ class SafeDeleteValueArgumentListUsageInfo( val parent = valueArgument.parent if (parent is KtValueArgumentList) { parent.removeArgument(valueArgument) - } - else { + } else { valueArgument.delete() } } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/safeDelete/utils.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/safeDelete/utils.kt index 678162e22d7..fa130f8aeb9 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/safeDelete/utils.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/safeDelete/utils.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.safeDelete @@ -43,13 +32,13 @@ fun PsiElement.canDeleteElement(): Boolean { } return this is KtClassOrObject - || this is KtSecondaryConstructor - || this is KtNamedFunction - || this is PsiMethod - || this is PsiClass - || this is KtProperty - || this is KtTypeParameter - || this is KtTypeAlias + || this is KtSecondaryConstructor + || this is KtNamedFunction + || this is PsiMethod + || this is PsiClass + || this is KtProperty + || this is KtTypeParameter + || this is KtTypeAlias } fun PsiElement.removeOverrideModifier() { @@ -58,8 +47,8 @@ fun PsiElement.removeOverrideModifier() { (this as KtModifierListOwner).modifierList?.getModifier(KtTokens.OVERRIDE_KEYWORD)?.delete() } is PsiMethod -> { - modifierList.annotations.firstOrNull { - annotation -> annotation.qualifiedName == "java.lang.Override" + modifierList.annotations.firstOrNull { annotation -> + annotation.qualifiedName == "java.lang.Override" }?.delete() } } @@ -100,11 +89,11 @@ private fun collectParametersHierarchy(method: PsiMethod, parameter: PsiParamete addParameter(currentMethod, parametersToDelete, parameter) currentMethod.findSuperMethods(true) - .filter { it !in visited } - .forEach { queue.offer(it) } + .filter { it !in visited } + .forEach { queue.offer(it) } OverridingMethodsSearch.search(currentMethod) - .filter { it !in visited } - .forEach { queue.offer(it) } + .filter { it !in visited } + .forEach { queue.offer(it) } } return parametersToDelete } @@ -117,8 +106,7 @@ private fun addParameter(method: PsiMethod, result: MutableSet, para if (declaration is KtFunction) { result.add(declaration.valueParameters[parameterIndex]) } - } - else { + } else { result.add(method.parameterList.parameters[parameterIndex]) } } \ No newline at end of file diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/ui/KotlinFileChooserDialog.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/ui/KotlinFileChooserDialog.kt index 5d7d71413f1..d7f88a1d9ce 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/ui/KotlinFileChooserDialog.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/ui/KotlinFileChooserDialog.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.ui @@ -29,29 +18,26 @@ import org.jetbrains.kotlin.psi.KtFile import javax.swing.tree.DefaultMutableTreeNode class KotlinFileChooserDialog( - title: String, - project: Project + title: String, + project: Project ) : AbstractTreeClassChooserDialog( - title, - project, - project.projectScope().restrictToKotlinSources(), - KtFile::class.java, - null, - null, - null, - false, - false + title, + project, + project.projectScope().restrictToKotlinSources(), + KtFile::class.java, + null, + null, + null, + false, + false ) { - override fun getSelectedFromTreeUserObject(node: DefaultMutableTreeNode): KtFile? { - val userObject = node.userObject - return when (userObject) { - is KtFileTreeNode -> userObject.ktFile - is KtClassOrObjectTreeNode -> { - val containingFile = userObject.value.containingKtFile - if (containingFile.declarations.size == 1) containingFile else null - } - else -> null + override fun getSelectedFromTreeUserObject(node: DefaultMutableTreeNode): KtFile? = when (val userObject = node.userObject) { + is KtFileTreeNode -> userObject.ktFile + is KtClassOrObjectTreeNode -> { + val containingFile = userObject.value.containingKtFile + if (containingFile.declarations.size == 1) containingFile else null } + else -> null } override fun getClassesByName(name: String, checkBoxState: Boolean, pattern: String, searchScope: GlobalSearchScope): List { diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/ui/KotlinTypeReferenceEditorComboWithBrowseButton.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/ui/KotlinTypeReferenceEditorComboWithBrowseButton.kt index d0c45a95046..674dca1e1ce 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/ui/KotlinTypeReferenceEditorComboWithBrowseButton.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/ui/KotlinTypeReferenceEditorComboWithBrowseButton.kt @@ -1,17 +1,6 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2000-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.refactoring.ui @@ -29,13 +18,13 @@ import org.jetbrains.kotlin.psi.KtTypeCodeFragment import java.awt.event.ActionListener class KotlinTypeReferenceEditorComboWithBrowseButton( - browseActionListener: ActionListener, - text: String?, - contextElement: PsiElement, - recentsKey: String + browseActionListener: ActionListener, + text: String?, + contextElement: PsiElement, + recentsKey: String ) : ComponentWithBrowseButton( - EditorComboBox(createDocument(text, contextElement), contextElement.project, KotlinFileType.INSTANCE), - browseActionListener + EditorComboBox(createDocument(text, contextElement), contextElement.project, KotlinFileType.INSTANCE), + browseActionListener ), TextAccessor { companion object { private fun createDocument(text: String?, contextElement: PsiElement): Document? { @@ -54,8 +43,7 @@ class KotlinTypeReferenceEditorComboWithBrowseButton( if (text != null) { if (text.isNotEmpty()) { childComponent.prependItem(text) - } - else { + } else { childComponent.selectedItem = null } } diff --git a/idea/src/org/jetbrains/kotlin/idea/roots/KotlinNonJvmSourceRootConverterProvider.kt b/idea/src/org/jetbrains/kotlin/idea/roots/KotlinNonJvmSourceRootConverterProvider.kt index b1fa7e33a3e..4ca67328911 100644 --- a/idea/src/org/jetbrains/kotlin/idea/roots/KotlinNonJvmSourceRootConverterProvider.kt +++ b/idea/src/org/jetbrains/kotlin/idea/roots/KotlinNonJvmSourceRootConverterProvider.kt @@ -1,5 +1,5 @@ /* - * Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -31,19 +31,17 @@ import org.jetbrains.jps.model.module.JpsTypedModuleSourceRoot import org.jetbrains.jps.model.serialization.facet.JpsFacetSerializer import org.jetbrains.jps.model.serialization.module.JpsModuleRootModelSerializer.* import org.jetbrains.kotlin.config.getFacetPlatformByConfigurationElement +import org.jetbrains.kotlin.idea.core.util.toVirtualFile import org.jetbrains.kotlin.idea.facet.KotlinFacetType import org.jetbrains.kotlin.idea.framework.JavaRuntimeDetectionUtil import org.jetbrains.kotlin.idea.framework.JsLibraryStdDetectionUtil import org.jetbrains.kotlin.idea.framework.getLibraryJar -import org.jetbrains.kotlin.idea.core.util.toVirtualFile import org.jetbrains.kotlin.platform.CommonPlatforms import org.jetbrains.kotlin.platform.TargetPlatform import org.jetbrains.kotlin.platform.isCommon import org.jetbrains.kotlin.platform.js.JsPlatforms -import org.jetbrains.kotlin.platform.js.isJs import org.jetbrains.kotlin.platform.jvm.JvmPlatforms import org.jetbrains.kotlin.platform.jvm.isJvm -import org.jetbrains.kotlin.platform.idePlatformKind import org.jetbrains.kotlin.utils.PathUtil class KotlinNonJvmSourceRootConverterProvider : ConverterProvider("kotlin-non-jvm-source-roots") { @@ -59,7 +57,9 @@ class KotlinNonJvmSourceRootConverterProvider : ConverterProvider("kotlin-non-jv private val PLATFORM_TO_STDLIB_DETECTORS: Map) -> Boolean> = mapOf( JvmPlatforms.unspecifiedJvmPlatform to { roots: Array -> JavaRuntimeDetectionUtil.getRuntimeJar(roots.toList()) != null }, JsPlatforms.defaultJsPlatform to { roots: Array -> JsLibraryStdDetectionUtil.getJsStdLibJar(roots.toList()) != null }, - CommonPlatforms.defaultCommonPlatform to { roots: Array -> getLibraryJar(roots, PathUtil.KOTLIN_STDLIB_COMMON_JAR_PATTERN) != null } + CommonPlatforms.defaultCommonPlatform to { roots: Array -> + getLibraryJar(roots, PathUtil.KOTLIN_STDLIB_COMMON_JAR_PATTERN) != null + } ) } diff --git a/idea/src/org/jetbrains/kotlin/idea/roots/projectRootUtils.kt b/idea/src/org/jetbrains/kotlin/idea/roots/projectRootUtils.kt index 102e01cc7d9..8ac32cd8b7a 100644 --- a/idea/src/org/jetbrains/kotlin/idea/roots/projectRootUtils.kt +++ b/idea/src/org/jetbrains/kotlin/idea/roots/projectRootUtils.kt @@ -1,5 +1,5 @@ /* - * Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @@ -20,18 +20,22 @@ import com.intellij.psi.PsiFile import com.intellij.util.containers.ContainerUtil import org.jetbrains.jps.model.JpsElement import org.jetbrains.jps.model.ex.JpsElementBase -import org.jetbrains.jps.model.java.* +import org.jetbrains.jps.model.java.JavaModuleSourceRootTypes +import org.jetbrains.jps.model.java.JavaResourceRootType +import org.jetbrains.jps.model.java.JavaSourceRootProperties +import org.jetbrains.jps.model.java.JavaSourceRootType import org.jetbrains.jps.model.module.JpsModuleSourceRoot import org.jetbrains.jps.model.module.JpsModuleSourceRootType import org.jetbrains.kotlin.config.* import org.jetbrains.kotlin.idea.framework.KotlinSdkType -import java.util.ArrayList +import java.util.* private fun JpsModuleSourceRoot.getOrCreateProperties() = getProperties(rootType)?.also { (it as? JpsElementBase<*>)?.setParent(null) } ?: rootType.createDefaultProperties() fun JpsModuleSourceRoot.getMigratedSourceRootTypeWithProperties(): Pair, JpsElement>? { val currentRootType = rootType + @Suppress("UNCHECKED_CAST") val newSourceRootType: JpsModuleSourceRootType = when (currentRootType) { JavaSourceRootType.SOURCE -> SourceKotlinRootType as JpsModuleSourceRootType @@ -72,7 +76,7 @@ private fun Module.collectKotlinAwareDestinationSourceRoots(): List .toList() } -fun isOutsideSourceRootSet(psiFile : PsiFile?, sourceRootTypes: Set>): Boolean { +fun isOutsideSourceRootSet(psiFile: PsiFile?, sourceRootTypes: Set>): Boolean { if (psiFile == null || psiFile is PsiCodeFragment) return false val file = psiFile.virtualFile ?: return false if (file.fileSystem is NonPhysicalFileSystem) return false @@ -80,7 +84,7 @@ fun isOutsideSourceRootSet(psiFile : PsiFile?, sourceRootTypes: Set): Boolean { + private fun areDefinitionsForGradleKts(allApplicableDefinitions: List): Boolean = if (allApplicableDefinitions.size == 2) { - return allApplicableDefinitions[0].asLegacyOrNull()?.scriptFilePattern?.pattern == "^(settings|.+\\.settings)\\.gradle\\.kts\$" - && allApplicableDefinitions[1].asLegacyOrNull()?.scriptFilePattern?.pattern == ".*\\.gradle\\.kts" - } - return false - } + (allApplicableDefinitions[0].asLegacyOrNull()?.scriptFilePattern + ?.pattern == "^(settings|.+\\.settings)\\.gradle\\.kts\$" && + allApplicableDefinitions[1].asLegacyOrNull()?.scriptFilePattern + ?.pattern == ".*\\.gradle\\.kts") + } else + false companion object { private val KEY = Key.create("MultipleScriptDefinitionsChecker") - private fun createNotification(psiFile: KtFile, defs: List): EditorNotificationPanel { - return EditorNotificationPanel().apply { + private fun createNotification(psiFile: KtFile, defs: List): EditorNotificationPanel = + EditorNotificationPanel().apply { setText("Multiple script definitions are applicable for this script. ${defs.first().name} is used") - createComponentActionLabel("Show all") { + createComponentActionLabel("Show all") { label -> val list = JBPopupFactory.getInstance().createListPopup( object : BaseListPopupStep(null, defs) { - override fun getTextFor(value: ScriptDefinition): String { - return value.asLegacyOrNull()?.let { + override fun getTextFor(value: ScriptDefinition): String = + value.asLegacyOrNull()?.let { it.name + " (${it.scriptFilePattern})" } ?: value.asLegacyOrNull()?.let { it.name + " (${KotlinParserDefinition.STD_SCRIPT_EXT})" } ?: value.name + " (${value.fileExtension})" - } } ) - list.showUnderneathOf(it) + list.showUnderneathOf(label) } createComponentActionLabel("Ignore") { @@ -93,7 +93,6 @@ class MultipleScriptDefinitionsChecker(private val project: Project) : EditorNot ShowSettingsUtilImpl.showSettingsDialog(psiFile.project, KotlinScriptingSettingsConfigurable.ID, "") } } - } private fun EditorNotificationPanel.createComponentActionLabel(labelText: String, callback: (HyperlinkLabel) -> Unit) { val label: Ref = Ref.create() diff --git a/idea/src/org/jetbrains/kotlin/idea/search/ideaExtensions/KotlinTargetElementEvaluator.kt b/idea/src/org/jetbrains/kotlin/idea/search/ideaExtensions/KotlinTargetElementEvaluator.kt index 00e2f45d215..c93f6ab7474 100644 --- a/idea/src/org/jetbrains/kotlin/idea/search/ideaExtensions/KotlinTargetElementEvaluator.kt +++ b/idea/src/org/jetbrains/kotlin/idea/search/ideaExtensions/KotlinTargetElementEvaluator.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.search.ideaExtensions @@ -106,7 +95,7 @@ class KotlinTargetElementEvaluator : TargetElementEvaluatorEx, TargetElementUtil if (BitUtil.isSet(flags, TargetElementUtil.REFERENCED_ELEMENT_ACCEPTED)) { return findLambdaOpenLBraceForGeneratedIt(ref) - ?: findReceiverForThisInExtensionFunction(ref) + ?: findReceiverForThisInExtensionFunction(ref) } return null diff --git a/idea/src/org/jetbrains/kotlin/idea/slicer/KotlinSliceDereferenceUsage.kt b/idea/src/org/jetbrains/kotlin/idea/slicer/KotlinSliceDereferenceUsage.kt index 92a7e66ac5a..fa67006e8d6 100644 --- a/idea/src/org/jetbrains/kotlin/idea/slicer/KotlinSliceDereferenceUsage.kt +++ b/idea/src/org/jetbrains/kotlin/idea/slicer/KotlinSliceDereferenceUsage.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.slicer @@ -22,9 +11,9 @@ import com.intellij.usages.UsagePresentation import com.intellij.util.Processor class KotlinSliceDereferenceUsage( - element: PsiElement, - parent: KotlinSliceUsage, - lambdaLevel: Int + element: PsiElement, + parent: KotlinSliceUsage, + lambdaLevel: Int ) : KotlinSliceUsage(element, parent, lambdaLevel, false) { override fun processChildren(processor: Processor) { // no children diff --git a/idea/src/org/jetbrains/kotlin/idea/slicer/KotlinSliceUsageCellRenderer.kt b/idea/src/org/jetbrains/kotlin/idea/slicer/KotlinSliceUsageCellRenderer.kt index 7f955537498..00d92a81766 100644 --- a/idea/src/org/jetbrains/kotlin/idea/slicer/KotlinSliceUsageCellRenderer.kt +++ b/idea/src/org/jetbrains/kotlin/idea/slicer/KotlinSliceUsageCellRenderer.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.slicer @@ -56,10 +45,7 @@ object KotlinSliceUsageCellRenderer : SliceUsageCellRendererBase() { append(" (Tracking enclosing lambda)".repeat(sliceUsage.lambdaLevel), SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES) val declaration = sliceUsage.element?.parents?.firstOrNull { - it is KtClass || - it is KtObjectDeclaration && !it.isObjectLiteral() || - it is KtDeclarationWithBody || - it is KtProperty && it.isLocal + it is KtClass || it is KtObjectDeclaration && !it.isObjectLiteral() || it is KtDeclarationWithBody || it is KtProperty && it.isLocal } as? KtDeclaration ?: return val descriptor = declaration.unsafeResolveToDescriptor() append(" in ${descriptorRenderer.render(descriptor)}", SimpleTextAttributes.GRAY_ATTRIBUTES) diff --git a/idea/src/org/jetbrains/kotlin/idea/slicer/KotlinUsageContextDataFlowPanelBase.kt b/idea/src/org/jetbrains/kotlin/idea/slicer/KotlinUsageContextDataFlowPanelBase.kt index add6789767a..69815f8092c 100644 --- a/idea/src/org/jetbrains/kotlin/idea/slicer/KotlinUsageContextDataFlowPanelBase.kt +++ b/idea/src/org/jetbrains/kotlin/idea/slicer/KotlinUsageContextDataFlowPanelBase.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.slicer @@ -42,9 +31,9 @@ import javax.swing.JPanel import javax.swing.SwingConstants sealed class KotlinUsageContextDataFlowPanelBase( - project: Project, - presentation: UsageViewPresentation, - private val isInflow: Boolean + project: Project, + presentation: UsageViewPresentation, + private val isInflow: Boolean ) : UsageContextPanelBase(project, presentation) { private var panel: JPanel? = null @@ -90,8 +79,7 @@ sealed class KotlinUsageContextDataFlowPanelBase( removeAll() val title = UsageViewBundle.message("select.the.usage.to.preview", myPresentation.usagesWord) add(JLabel(title, SwingConstants.CENTER), BorderLayout.CENTER) - } - else { + } else { val element = infos.firstOrNull()?.element ?: return if (panel != null) { Disposer.dispose(panel as Disposable) @@ -113,8 +101,8 @@ sealed class KotlinUsageContextDataFlowPanelBase( } class KotlinUsageContextDataInflowPanel( - project: Project, - presentation: UsageViewPresentation + project: Project, + presentation: UsageViewPresentation ) : KotlinUsageContextDataFlowPanelBase(project, presentation, true) { class Provider : ProviderBase() { override fun create(usageView: UsageView): UsageContextPanel { @@ -126,8 +114,8 @@ class KotlinUsageContextDataInflowPanel( } class KotlinUsageContextDataOutflowPanel( - project: Project, - presentation: UsageViewPresentation + project: Project, + presentation: UsageViewPresentation ) : KotlinUsageContextDataFlowPanelBase(project, presentation, false) { class Provider : ProviderBase() { override fun create(usageView: UsageView): UsageContextPanel { diff --git a/idea/src/org/jetbrains/kotlin/idea/slicer/Slicer.kt b/idea/src/org/jetbrains/kotlin/idea/slicer/Slicer.kt index 3fd09d77ae5..210243feff6 100644 --- a/idea/src/org/jetbrains/kotlin/idea/slicer/Slicer.kt +++ b/idea/src/org/jetbrains/kotlin/idea/slicer/Slicer.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.slicer @@ -360,7 +349,8 @@ class InflowSlicer( MagicKind.BOUND_CALLABLE_REFERENCE, MagicKind.UNBOUND_CALLABLE_REFERENCE -> { val callableRefExpr = expressionValue.element as? KtCallableReferenceExpression ?: return val referencedDescriptor = analyze()[BindingContext.REFERENCE_TARGET, callableRefExpr.callableReference] ?: return - val referencedDeclaration = (referencedDescriptor as? DeclarationDescriptorWithSource)?.originalSource?.getPsi() ?: return + val referencedDeclaration = + (referencedDescriptor as? DeclarationDescriptorWithSource)?.originalSource?.getPsi() ?: return referencedDeclaration.passToProcessor(parentUsage.lambdaLevel - 1) } else -> return diff --git a/idea/src/org/jetbrains/kotlin/idea/testIntegration/KotlinCreateTestDialog.kt b/idea/src/org/jetbrains/kotlin/idea/testIntegration/KotlinCreateTestDialog.kt index 395a88d4582..a7b89a000f2 100644 --- a/idea/src/org/jetbrains/kotlin/idea/testIntegration/KotlinCreateTestDialog.kt +++ b/idea/src/org/jetbrains/kotlin/idea/testIntegration/KotlinCreateTestDialog.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.testIntegration @@ -22,11 +11,13 @@ import com.intellij.psi.PsiClass import com.intellij.psi.PsiPackage import com.intellij.testIntegration.createTest.CreateTestDialog -class KotlinCreateTestDialog(project: Project, - title: String, - targetClass: PsiClass?, - targetPackage: PsiPackage?, - targetModule: Module) : CreateTestDialog(project, title, targetClass, targetPackage, targetModule) { +class KotlinCreateTestDialog( + project: Project, + title: String, + targetClass: PsiClass?, + targetPackage: PsiPackage?, + targetModule: Module +) : CreateTestDialog(project, title, targetClass, targetPackage, targetModule) { var explicitClassName: String? = null override fun getClassName() = explicitClassName ?: super.getClassName() diff --git a/idea/src/org/jetbrains/kotlin/idea/testIntegration/KotlinCreateTestIntention.kt b/idea/src/org/jetbrains/kotlin/idea/testIntegration/KotlinCreateTestIntention.kt index d48587c4f98..2395bf02d0d 100644 --- a/idea/src/org/jetbrains/kotlin/idea/testIntegration/KotlinCreateTestIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/testIntegration/KotlinCreateTestIntention.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.testIntegration @@ -166,7 +155,9 @@ class KotlinCreateTestIntention : SelfTargetingRangeIntention("Convert class '${generatedClass.name}' to Kotlin", this) { runWriteAction { - generatedClass.methods.forEach { it.throwsList.referenceElements.forEach { referenceElement -> referenceElement.delete() } } + generatedClass.methods.forEach { + it.throwsList.referenceElements.forEach { referenceElement -> referenceElement.delete() } + } } if (existingClass != null) { diff --git a/idea/src/org/jetbrains/kotlin/idea/testIntegration/KotlinTestCreator.kt b/idea/src/org/jetbrains/kotlin/idea/testIntegration/KotlinTestCreator.kt index e9a579c31f1..259286d6045 100644 --- a/idea/src/org/jetbrains/kotlin/idea/testIntegration/KotlinTestCreator.kt +++ b/idea/src/org/jetbrains/kotlin/idea/testIntegration/KotlinTestCreator.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.testIntegration @@ -27,9 +16,8 @@ import org.jetbrains.kotlin.psi.psiUtil.parents class KotlinTestCreator : TestCreator { private fun getTarget(editor: Editor, file: PsiFile): KtNamedDeclaration? { - return file.findElementAt(editor.caretModel.offset) - ?.parents - ?.firstOrNull { it is KtClassOrObject || it is KtNamedDeclaration && it.parent is KtFile } as? KtNamedDeclaration + return file.findElementAt(editor.caretModel.offset)?.parents + ?.firstOrNull { it is KtClassOrObject || it is KtNamedDeclaration && it.parent is KtFile } as? KtNamedDeclaration } override fun isAvailable(project: Project, editor: Editor, file: PsiFile): Boolean { diff --git a/idea/src/org/jetbrains/kotlin/idea/testIntegration/testIntegrationUtils.kt b/idea/src/org/jetbrains/kotlin/idea/testIntegration/testIntegrationUtils.kt index 1752a34f371..0b0bbc1dafd 100644 --- a/idea/src/org/jetbrains/kotlin/idea/testIntegration/testIntegrationUtils.kt +++ b/idea/src/org/jetbrains/kotlin/idea/testIntegration/testIntegrationUtils.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.testIntegration @@ -27,5 +16,5 @@ fun findSuitableFrameworks(klass: KtClassOrObject): List { val lightClass = klass.toLightClass() ?: return emptyList() val frameworks = Extensions.getExtensions(TestFramework.EXTENSION_NAME).filter { it.language == JavaLanguage.INSTANCE } return frameworks.firstOrNull { it.isTestClass(lightClass) }?.let { listOf(it) } - ?: frameworks.filterTo(SmartList()) { it.isPotentialTestClass(lightClass) } + ?: frameworks.filterTo(SmartList()) { it.isPotentialTestClass(lightClass) } } diff --git a/idea/src/org/jetbrains/kotlin/idea/util/DialogWithEditor.kt b/idea/src/org/jetbrains/kotlin/idea/util/DialogWithEditor.kt index 2df19287508..38ddef15091 100644 --- a/idea/src/org/jetbrains/kotlin/idea/util/DialogWithEditor.kt +++ b/idea/src/org/jetbrains/kotlin/idea/util/DialogWithEditor.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.util @@ -30,9 +19,9 @@ import javax.swing.JComponent import javax.swing.JPanel open class DialogWithEditor( - val project: Project, - title: String, - val initialText: String + val project: Project, + title: String, + val initialText: String ) : DialogWrapper(project, true) { val editor: Editor = createEditor() diff --git a/idea/src/org/jetbrains/kotlin/idea/util/ImportInsertHelperImpl.kt b/idea/src/org/jetbrains/kotlin/idea/util/ImportInsertHelperImpl.kt index 5eba6d378f2..b81ee058697 100644 --- a/idea/src/org/jetbrains/kotlin/idea/util/ImportInsertHelperImpl.kt +++ b/idea/src/org/jetbrains/kotlin/idea/util/ImportInsertHelperImpl.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2016 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.util @@ -145,8 +134,9 @@ class ImportInsertHelperImpl(private val project: Project) : ImportInsertHelper( is PackageViewDescriptor -> topLevelScope.findPackage(name) else -> null } - if (conflict != null - && imports.any { !it.isAllUnder && it.importPath?.fqName == conflict.importableFqName && it.importPath?.importedName == name } + if (conflict != null && imports.any { + !it.isAllUnder && it.importPath?.fqName == conflict.importableFqName && it.importPath?.importedName == name + } ) { return ImportDescriptorResult.FAIL } diff --git a/idea/src/org/jetbrains/kotlin/idea/util/java9StructureUtil.kt b/idea/src/org/jetbrains/kotlin/idea/util/java9StructureUtil.kt index 32226103c5c..58cff234eb9 100644 --- a/idea/src/org/jetbrains/kotlin/idea/util/java9StructureUtil.kt +++ b/idea/src/org/jetbrains/kotlin/idea/util/java9StructureUtil.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.util @@ -26,12 +15,8 @@ fun findFirstPsiJavaModule(module: Module): PsiJavaModule? { val project = module.project val moduleInfoFiles = FilenameIndex.getFilesByName(project, PsiJavaModule.MODULE_INFO_FILE, module.moduleScope) - return moduleInfoFiles - .asSequence() - .filterIsInstance() - .map { it.moduleDeclaration } - .firstOrNull { it != null } + return moduleInfoFiles.asSequence().filterIsInstance().map { it.moduleDeclaration }.firstOrNull { it != null } } fun findRequireDirective(module: PsiJavaModule, requiredName: String): PsiRequiresStatement? = - module.requires.find { it.moduleName == requiredName } + module.requires.find { it.moduleName == requiredName } diff --git a/idea/src/org/jetbrains/kotlin/idea/util/projectStructureUtil.kt b/idea/src/org/jetbrains/kotlin/idea/util/projectStructureUtil.kt index e260211694b..d29665689c8 100644 --- a/idea/src/org/jetbrains/kotlin/idea/util/projectStructureUtil.kt +++ b/idea/src/org/jetbrains/kotlin/idea/util/projectStructureUtil.kt @@ -1,17 +1,6 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.util.projectStructure @@ -46,8 +35,7 @@ fun OrderEnumerator.findLibrary(predicate: (Library) -> Boolean): Library? { if (predicate(library!!)) { lib = library false - } - else { + } else { true } } diff --git a/idea/tests/org/jetbrains/kotlin/DataFlowValueRenderingTest.kt b/idea/tests/org/jetbrains/kotlin/DataFlowValueRenderingTest.kt index 915f84fa85d..103160cf86d 100644 --- a/idea/tests/org/jetbrains/kotlin/DataFlowValueRenderingTest.kt +++ b/idea/tests/org/jetbrains/kotlin/DataFlowValueRenderingTest.kt @@ -22,7 +22,7 @@ import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver import org.jetbrains.kotlin.test.KotlinTestUtils import java.io.File -abstract class AbstractDataFlowValueRenderingTest: KotlinLightCodeInsightFixtureTestCase() { +abstract class AbstractDataFlowValueRenderingTest : KotlinLightCodeInsightFixtureTestCase() { private fun IdentifierInfo.render(): String? = when (this) { is IdentifierInfo.Expression -> expression.text @@ -34,13 +34,11 @@ abstract class AbstractDataFlowValueRenderingTest: KotlinLightCodeInsightFixture } private fun DataFlowValue.render() = - // If it is not a stable identifier, there's no point in rendering it - if (!isStable) null - else identifierInfo.render() + // If it is not a stable identifier, there's no point in rendering it + if (!isStable) null + else identifierInfo.render() - override fun getTestDataPath() : String { - return PluginTestCaseBase.getTestDataPathBase() + "/dataFlowValueRendering/" - } + override fun getTestDataPath(): String = PluginTestCaseBase.getTestDataPathBase() + "/dataFlowValueRendering/" override fun getProjectDescriptor(): LightProjectDescriptor { return LightCodeInsightFixtureTestCase.JAVA_LATEST diff --git a/idea/tests/org/jetbrains/kotlin/addImport/AbstractAddImportTest.kt b/idea/tests/org/jetbrains/kotlin/addImport/AbstractAddImportTest.kt index 39f013a2b44..bc05461a0f5 100644 --- a/idea/tests/org/jetbrains/kotlin/addImport/AbstractAddImportTest.kt +++ b/idea/tests/org/jetbrains/kotlin/addImport/AbstractAddImportTest.kt @@ -19,8 +19,7 @@ import org.jetbrains.kotlin.test.InTextDirectivesUtils abstract class AbstractAddImportTest : AbstractImportsTest() { override fun doTest(file: KtFile): String? { - var descriptorName = InTextDirectivesUtils.findStringWithPrefixes(file.text, "// IMPORT:") - ?: error("No IMPORT directive defined") + var descriptorName = InTextDirectivesUtils.findStringWithPrefixes(file.text, "// IMPORT:") ?: error("No IMPORT directive defined") var filter: (DeclarationDescriptor) -> Boolean = { true } if (descriptorName.startsWith("class:")) { @@ -31,14 +30,15 @@ abstract class AbstractAddImportTest : AbstractImportsTest() { val descriptors = file.resolveImportReference(FqName(descriptorName)).filter(filter) when { - descriptors.isEmpty() -> - error("No descriptor $descriptorName found") + descriptors.isEmpty() -> error("No descriptor $descriptorName found") - descriptors.size > 1 -> - error("Multiple descriptors found:\n " + descriptors.map { DescriptorRenderer.FQ_NAMES_IN_TYPES.render(it) }.joinToString("\n ")) + descriptors.size > 1 -> error("Multiple descriptors found:\n " + descriptors.joinToString("\n ") { + DescriptorRenderer.FQ_NAMES_IN_TYPES.render(it) + }) else -> { - val success = ImportInsertHelper.getInstance(project).importDescriptor(file, descriptors.single()) != ImportDescriptorResult.FAIL + val success = ImportInsertHelper.getInstance(project) + .importDescriptor(file, descriptors.single()) != ImportDescriptorResult.FAIL if (!success) { val document = PsiDocumentManager.getInstance(project).getDocument(file)!! document.replaceString(0, document.textLength, "Failed to add import") diff --git a/idea/tests/org/jetbrains/kotlin/asJava/KtFileLightClassTest.kt b/idea/tests/org/jetbrains/kotlin/asJava/KtFileLightClassTest.kt index 8b7c7a0188f..5cfc15720c4 100644 --- a/idea/tests/org/jetbrains/kotlin/asJava/KtFileLightClassTest.kt +++ b/idea/tests/org/jetbrains/kotlin/asJava/KtFileLightClassTest.kt @@ -57,14 +57,16 @@ class KtFileLightClassTest : KotlinLightCodeInsightFixtureTestCase() { fun testNoFacadeForScript() { val file = myFixture.configureByText("foo.kts", "package foo") as KtFile assertEquals(0, file.classes.size) - val facadeFiles = KotlinAsJavaSupport.getInstance(project).findFilesForFacade(FqName("foo.FooKt"), GlobalSearchScope.allScope(project)) + val facadeFiles = + KotlinAsJavaSupport.getInstance(project).findFilesForFacade(FqName("foo.FooKt"), GlobalSearchScope.allScope(project)) assertEquals(0, facadeFiles.size) } fun testNoFacadeForHeaderClass() { val file = myFixture.configureByText("foo.kt", "header fun foo(): Int") as KtFile assertEquals(0, file.classes.size) - val facadeFiles = KotlinAsJavaSupport.getInstance(project).findFilesForFacade(FqName("foo.FooKt"), GlobalSearchScope.allScope(project)) + val facadeFiles = + KotlinAsJavaSupport.getInstance(project).findFilesForFacade(FqName("foo.FooKt"), GlobalSearchScope.allScope(project)) assertEquals(0, facadeFiles.size) } @@ -73,13 +75,15 @@ class KtFileLightClassTest : KotlinLightCodeInsightFixtureTestCase() { } fun testInjectedCode() { - myFixture.configureByText("foo.kt", """ + myFixture.configureByText( + "foo.kt", """ import org.intellij.lang.annotations.Language fun foo(@Language("kotlin") a: String){a.toString()} fun bar(){ foo("class A") } - """) + """ + ) myFixture.testHighlighting("foo.kt") @@ -106,9 +110,9 @@ class KtFileLightClassTest : KotlinLightCodeInsightFixtureTestCase() { fun lightElement(file: PsiFile): PsiElement = (file as KtFile).classes.single() .methods.first { it.name == "bar" } .annotations.first { it.qualifiedName == "kotlin.Deprecated" }.also { - // Otherwise following asserts have no sense - TestCase.assertTrue("psi element should be light ", it is KtLightElement<*, *>) - } + // Otherwise following asserts have no sense + TestCase.assertTrue("psi element should be light ", it is KtLightElement<*, *>) + } val copied = psiFile.copied() diff --git a/idea/tests/org/jetbrains/kotlin/asJava/KtLightAnnotationTest.kt b/idea/tests/org/jetbrains/kotlin/asJava/KtLightAnnotationTest.kt index a8d34d3cbbf..d187c433e1c 100644 --- a/idea/tests/org/jetbrains/kotlin/asJava/KtLightAnnotationTest.kt +++ b/idea/tests/org/jetbrains/kotlin/asJava/KtLightAnnotationTest.kt @@ -30,10 +30,12 @@ import org.junit.runner.RunWith @RunWith(JUnit3WithIdeaConfigurationRunner::class) class KtLightAnnotationTest : KotlinLightCodeInsightFixtureTestCase() { - override fun getProjectDescriptor(): LightProjectDescriptor = KotlinJdkAndLibraryProjectDescriptor(ForTestCompileRuntime.runtimeJarForTests()) + override fun getProjectDescriptor(): LightProjectDescriptor = + KotlinJdkAndLibraryProjectDescriptor(ForTestCompileRuntime.runtimeJarForTests()) fun testBooleanAnnotationDefaultValue() { - myFixture.addClass(""" + myFixture.addClass( + """ import java.lang.annotation.ElementType; import java.lang.annotation.Target; @@ -41,24 +43,28 @@ class KtLightAnnotationTest : KotlinLightCodeInsightFixtureTestCase() { public @interface Autowired { boolean required() default true; } - """.trimIndent()) + """.trimIndent() + ) - myFixture.configureByText("AnnotatedClass.kt", """ + myFixture.configureByText( + "AnnotatedClass.kt", """ class AnnotatedClass{ @Autowired lateinit var bean: String } - """.trimIndent()) + """.trimIndent() + ) myFixture.testHighlighting("Autowired.java", "AnnotatedClass.kt") val annotations = myFixture.findClass("AnnotatedClass").fields.single() - .expectAnnotations(2).single { it.qualifiedName == "Autowired" } + .expectAnnotations(2).single { it.qualifiedName == "Autowired" } val annotationAttributeVal = annotations.findAttributeValue("required") as PsiElement assertTextRangeAndValue("true", true, annotationAttributeVal) } fun testStringAnnotationWithUnnamedParameter() { - myFixture.addClass(""" + myFixture.addClass( + """ import java.lang.annotation.ElementType; import java.lang.annotation.Target; @@ -66,17 +72,20 @@ class KtLightAnnotationTest : KotlinLightCodeInsightFixtureTestCase() { public @interface Qualifier { String value(); } - """.trimIndent()) + """.trimIndent() + ) - myFixture.configureByText("AnnotatedClass.kt", """ + myFixture.configureByText( + "AnnotatedClass.kt", """ class AnnotatedClass { fun bar(@Qualifier("foo") param: String){} } - """.trimIndent()) + """.trimIndent() + ) myFixture.testHighlighting("Qualifier.java", "AnnotatedClass.kt") val annotation = myFixture.findClass("AnnotatedClass").methods.first { it.name == "bar" }.parameterList.parameters.single() - .expectAnnotations(2).single { it.qualifiedName == "Qualifier" } + .expectAnnotations(2).single { it.qualifiedName == "Qualifier" } val annotationAttributeVal = annotation.findAttributeValue("value") as PsiExpression assertTextRangeAndValue("\"foo\"", "foo", annotationAttributeVal) TestCase.assertEquals( @@ -86,18 +95,22 @@ class KtLightAnnotationTest : KotlinLightCodeInsightFixtureTestCase() { } fun testAnnotationsInAnnotationsDeclarations() { - myFixture.addClass(""" + myFixture.addClass( + """ public @interface OuterAnnotation { InnerAnnotation attribute(); @interface InnerAnnotation { } } - """.trimIndent()) + """.trimIndent() + ) - myFixture.configureByText("AnnotatedClass.kt", """ + myFixture.configureByText( + "AnnotatedClass.kt", """ @OuterAnnotation(attribute = OuterAnnotation.InnerAnnotation()) open class AnnotatedClass - """.trimIndent()) + """.trimIndent() + ) myFixture.testHighlighting("OuterAnnotation.java", "AnnotatedClass.kt") val annotations = myFixture.findClass("AnnotatedClass").expectAnnotations(1) @@ -272,18 +285,22 @@ class KtLightAnnotationTest : KotlinLightCodeInsightFixtureTestCase() { } fun testAnnotationsInAnnotationsArrayDeclarations() { - myFixture.addClass(""" + myFixture.addClass( + """ public @interface OuterAnnotation { InnerAnnotation[] attributes(); @interface InnerAnnotation { } } - """.trimIndent()) + """.trimIndent() + ) - myFixture.configureByText("AnnotatedClass.kt", """ + myFixture.configureByText( + "AnnotatedClass.kt", """ @OuterAnnotation(attributes = arrayOf(OuterAnnotation.InnerAnnotation())) open class AnnotatedClass - """.trimIndent()) + """.trimIndent() + ) myFixture.testHighlighting("OuterAnnotation.java", "AnnotatedClass.kt") val annotations = myFixture.findClass("AnnotatedClass").expectAnnotations(1) @@ -294,18 +311,22 @@ class KtLightAnnotationTest : KotlinLightCodeInsightFixtureTestCase() { fun testAnnotationsInAnnotationsFinalDeclarations() { - myFixture.addClass(""" + myFixture.addClass( + """ public @interface OuterAnnotation { InnerAnnotation attribute(); @interface InnerAnnotation { } } - """.trimIndent()) + """.trimIndent() + ) - myFixture.configureByText("AnnotatedClass.kt", """ + myFixture.configureByText( + "AnnotatedClass.kt", """ @OuterAnnotation(attribute = OuterAnnotation.InnerAnnotation()) class AnnotatedClass - """.trimIndent()) + """.trimIndent() + ) myFixture.testHighlighting("OuterAnnotation.java", "AnnotatedClass.kt") val annotations = myFixture.findClass("AnnotatedClass").expectAnnotations(1) @@ -315,7 +336,8 @@ class KtLightAnnotationTest : KotlinLightCodeInsightFixtureTestCase() { } fun testAnnotationsInAnnotationsInAnnotationsDeclarations() { - myFixture.addClass(""" + myFixture.addClass( + """ public @interface OuterAnnotation { InnerAnnotation attribute(); @interface InnerAnnotation { @@ -324,12 +346,15 @@ class KtLightAnnotationTest : KotlinLightCodeInsightFixtureTestCase() { } } } - """.trimIndent()) + """.trimIndent() + ) - myFixture.configureByText("AnnotatedClass.kt", """ + myFixture.configureByText( + "AnnotatedClass.kt", """ @OuterAnnotation(attribute = OuterAnnotation.InnerAnnotation(attribute = OuterAnnotation.InnerAnnotation.InnerInnerAnnotation())) open class AnnotatedClass //There is another exception if class is not open - """.trimIndent()) + """.trimIndent() + ) myFixture.testHighlighting("OuterAnnotation.java", "AnnotatedClass.kt") val annotations = myFixture.findClass("AnnotatedClass").expectAnnotations(1) @@ -342,14 +367,16 @@ class KtLightAnnotationTest : KotlinLightCodeInsightFixtureTestCase() { } fun testKotlinAnnotations() { - myFixture.configureByText("AnnotatedClass.kt", """ + myFixture.configureByText( + "AnnotatedClass.kt", """ annotation class Anno1(val anno2: Anno2) annotation class Anno2(val anno3: Anno3) annotation class Anno3 @Anno1(Anno2(Anno3())) class AnnotatedClass - """.trimIndent()) + """.trimIndent() + ) myFixture.testHighlighting("AnnotatedClass.kt") val annotations = myFixture.findClass("AnnotatedClass").expectAnnotations(1) @@ -363,11 +390,13 @@ class KtLightAnnotationTest : KotlinLightCodeInsightFixtureTestCase() { } fun testKotlinAnnotationWithStringArray() { - myFixture.configureByText("AnnotatedClass.kt", """ + myFixture.configureByText( + "AnnotatedClass.kt", """ annotation class Anno(val params: Array) @Anno(arrayOf("abc", "def")) class AnnotatedClass - """.trimIndent()) + """.trimIndent() + ) myFixture.testHighlighting("AnnotatedClass.kt") val annotations = myFixture.findClass("AnnotatedClass").expectAnnotations(1) @@ -383,11 +412,13 @@ class KtLightAnnotationTest : KotlinLightCodeInsightFixtureTestCase() { fun testKotlinAnnotationWithStringArrayLiteral() { configureKotlinVersion("1.2") - myFixture.configureByText("AnnotatedClass.kt", """ + myFixture.configureByText( + "AnnotatedClass.kt", """ annotation class Anno(val params: Array) @Anno(params = ["abc", "def"]) class AnnotatedClass - """.trimIndent()) + """.trimIndent() + ) myFixture.testHighlighting("AnnotatedClass.kt") val annotations = myFixture.findClass("AnnotatedClass").expectAnnotations(1) @@ -401,13 +432,15 @@ class KtLightAnnotationTest : KotlinLightCodeInsightFixtureTestCase() { fun testKotlinAnnotationsArray() { - myFixture.configureByText("AnnotatedClass.kt", """ + myFixture.configureByText( + "AnnotatedClass.kt", """ annotation class Anno1(val anno2: Array) annotation class Anno2(val v:Int) @Anno1(anno2 = arrayOf(Anno2(1), Anno2(2))) class AnnotatedClass - """.trimIndent()) + """.trimIndent() + ) myFixture.testHighlighting("AnnotatedClass.kt") val annotation = myFixture.findClass("AnnotatedClass").expectAnnotations(1).single() @@ -439,18 +472,22 @@ class KtLightAnnotationTest : KotlinLightCodeInsightFixtureTestCase() { fun testVarargAnnotation() { - myFixture.configureByText("Outer.java", """ + myFixture.configureByText( + "Outer.java", """ @interface Outer{ Inner[] value() default {}; } @interface Inner{ } - """) - myFixture.configureByText("AnnotatedClass.kt", """ + """ + ) + myFixture.configureByText( + "AnnotatedClass.kt", """ @Outer(Inner()) class MyAnnotated {} - """.trimIndent()) + """.trimIndent() + ) val annotations = myFixture.findClass("MyAnnotated").expectAnnotations(1) annotations[0].let { annotation -> @@ -469,13 +506,17 @@ class KtLightAnnotationTest : KotlinLightCodeInsightFixtureTestCase() { fun testKtVarargAnnotation() { - myFixture.configureByText("Anno.kt", """ + myFixture.configureByText( + "Anno.kt", """ annotation class Anno(vararg val vars: String) - """) - myFixture.configureByText("AnnotatedClass.kt", """ + """ + ) + myFixture.configureByText( + "AnnotatedClass.kt", """ @Anno("hello", "world") class MyAnnotated - """.trimIndent()) + """.trimIndent() + ) val annotations = myFixture.findClass("MyAnnotated").expectAnnotations(1) val annotationAttributeVal = annotations.first().findAttributeValue("vars") @@ -521,16 +562,20 @@ class KtLightAnnotationTest : KotlinLightCodeInsightFixtureTestCase() { fun testVarargClasses() = doVarargTest("""Class""", listOf("Any::class", "String::class", "Int::class")) fun testVarargWithSpread() { - myFixture.addClass(""" + myFixture.addClass( + """ public @interface Annotation { String[] value(); } - """.trimIndent()) + """.trimIndent() + ) - myFixture.configureByText("AnnotatedClass.kt", """ + myFixture.configureByText( + "AnnotatedClass.kt", """ @Annotation(value = *arrayOf("a", "b", "c")) open class AnnotatedClass - """.trimIndent()) + """.trimIndent() + ) myFixture.testHighlighting("Annotation.java", "AnnotatedClass.kt") val annotations = myFixture.findClass("AnnotatedClass").expectAnnotations(1) @@ -543,16 +588,20 @@ class KtLightAnnotationTest : KotlinLightCodeInsightFixtureTestCase() { } fun testVarargWithSpreadComplex() { - myFixture.addClass(""" + myFixture.addClass( + """ public @interface Annotation { String[] value(); } - """.trimIndent()) + """.trimIndent() + ) - myFixture.configureByText("AnnotatedClass.kt", """ + myFixture.configureByText( + "AnnotatedClass.kt", """ @Annotation(value = arrayOf(*arrayOf("a", "b"), "c", *arrayOf("d", "e"))) open class AnnotatedClass - """.trimIndent()) + """.trimIndent() + ) myFixture.testHighlighting("Annotation.java", "AnnotatedClass.kt") val annotations = myFixture.findClass("AnnotatedClass").expectAnnotations(1) @@ -565,16 +614,20 @@ class KtLightAnnotationTest : KotlinLightCodeInsightFixtureTestCase() { } fun testVarargWithArrayLiteral() { - myFixture.addClass(""" + myFixture.addClass( + """ public @interface Annotation { String[] value(); } - """.trimIndent()) + """.trimIndent() + ) - myFixture.configureByText("AnnotatedClass.kt", """ + myFixture.configureByText( + "AnnotatedClass.kt", """ @Annotation(value = ["a", "b", "c"]) open class AnnotatedClass - """.trimIndent()) + """.trimIndent() + ) myFixture.testHighlighting("Annotation.java", "AnnotatedClass.kt") val annotations = myFixture.findClass("AnnotatedClass").expectAnnotations(1) @@ -587,16 +640,20 @@ class KtLightAnnotationTest : KotlinLightCodeInsightFixtureTestCase() { } fun testVarargWithSingleArg() { - myFixture.addClass(""" + myFixture.addClass( + """ public @interface Annotation { String[] value(); } - """.trimIndent()) + """.trimIndent() + ) - myFixture.configureByText("AnnotatedClass.kt", """ + myFixture.configureByText( + "AnnotatedClass.kt", """ @Annotation("a") open class AnnotatedClass - """.trimIndent()) + """.trimIndent() + ) myFixture.testHighlighting("Annotation.java", "AnnotatedClass.kt") val annotations = myFixture.findClass("AnnotatedClass").expectAnnotations(1) @@ -609,16 +666,20 @@ class KtLightAnnotationTest : KotlinLightCodeInsightFixtureTestCase() { } fun testVarargWithArrayLiteralAndSpread() { - myFixture.addClass(""" + myFixture.addClass( + """ public @interface Annotation { String[] value(); } - """.trimIndent()) + """.trimIndent() + ) - myFixture.configureByText("AnnotatedClass.kt", """ + myFixture.configureByText( + "AnnotatedClass.kt", """ @Annotation(*["a", "b", "c"]) open class AnnotatedClass - """.trimIndent()) + """.trimIndent() + ) myFixture.testHighlighting("Annotation.java", "AnnotatedClass.kt") val annotations = myFixture.findClass("AnnotatedClass").expectAnnotations(1) @@ -634,7 +695,8 @@ class KtLightAnnotationTest : KotlinLightCodeInsightFixtureTestCase() { //See https://youtrack.jetbrains.com/issue/KT-34107 return - myFixture.configureByText("RAnno.java", """ + myFixture.configureByText( + "RAnno.java", """ import java.lang.annotation.Repeatable; @interface RContainer{ @@ -645,13 +707,16 @@ class KtLightAnnotationTest : KotlinLightCodeInsightFixtureTestCase() { public @interface RAnno { String[] value() default {}; } - """) - myFixture.configureByText("AnnotatedClass.kt", """ + """ + ) + myFixture.configureByText( + "AnnotatedClass.kt", """ @RAnno() @RAnno("1") @RAnno("1", "2") class AnnotatedClass - """.trimIndent()) + """.trimIndent() + ) val annotations = myFixture.findClass("AnnotatedClass").expectAnnotations(3) annotations[0].let { annotation -> @@ -701,12 +766,14 @@ class KtLightAnnotationTest : KotlinLightCodeInsightFixtureTestCase() { } fun testWrongNamesPassed() { - myFixture.configureByText("AnnotatedClass.kt", """ + myFixture.configureByText( + "AnnotatedClass.kt", """ annotation class Anno1(val i:Int , val j: Int) @Anno1(k = 3, l = 5) class AnnotatedClass - """.trimIndent()) + """.trimIndent() + ) val annotations = myFixture.findClass("AnnotatedClass").expectAnnotations(1) val annotation = annotations.first() @@ -717,12 +784,14 @@ class KtLightAnnotationTest : KotlinLightCodeInsightFixtureTestCase() { } fun testWrongValuesPassed() { - myFixture.configureByText("AnnotatedClass.kt", """ + myFixture.configureByText( + "AnnotatedClass.kt", """ annotation class Anno1(val i: Int , val j: Int) @Anno1(i = true, j = false) class AnnotatedClass - """.trimIndent()) + """.trimIndent() + ) val annotations = myFixture.findClass("AnnotatedClass").expectAnnotations(1) val annotation = annotations.first() @@ -731,12 +800,14 @@ class KtLightAnnotationTest : KotlinLightCodeInsightFixtureTestCase() { } fun testDuplicateParameters() { - myFixture.configureByText("AnnotatedClass.kt", """ + myFixture.configureByText( + "AnnotatedClass.kt", """ annotation class Anno1(val i:Int , val i: Boolean) @Anno1(i = true, i = 3) class AnnotatedClass - """.trimIndent()) + """.trimIndent() + ) val annotations = myFixture.findClass("AnnotatedClass").expectAnnotations(1) val annotation = annotations.first() @@ -748,12 +819,14 @@ class KtLightAnnotationTest : KotlinLightCodeInsightFixtureTestCase() { //See https://youtrack.jetbrains.com/issue/KT-34107 return - myFixture.configureByText("AnnotatedClass.kt", """ + myFixture.configureByText( + "AnnotatedClass.kt", """ annotation class Anno1(val i: Int = 0) @Anno1() class AnnotatedClass - """.trimIndent()) + """.trimIndent() + ) val (annotation) = myFixture.findClass("AnnotatedClass").expectAnnotations(1) assertTextAndRange("0", annotation.findAttributeValue("i")!!) diff --git a/idea/tests/org/jetbrains/kotlin/asJava/LightClassFromTextTest.kt b/idea/tests/org/jetbrains/kotlin/asJava/LightClassFromTextTest.kt index 15b65ac27b5..e5d7dbea213 100644 --- a/idea/tests/org/jetbrains/kotlin/asJava/LightClassFromTextTest.kt +++ b/idea/tests/org/jetbrains/kotlin/asJava/LightClassFromTextTest.kt @@ -68,7 +68,8 @@ class LightClassFromTextTest : KotlinLightCodeInsightFixtureTestCase() { fun testMultifileClass() { myFixture.configureByFiles("multifile1.kt", "multifile2.kt") - val facadeClass = classesFromText(""" + val facadeClass = classesFromText( + """ @file:kotlin.jvm.JvmMultifileClass @file:kotlin.jvm.JvmName("Foo") @@ -77,7 +78,8 @@ class LightClassFromTextTest : KotlinLightCodeInsightFixtureTestCase() { fun boo() { } - """).single() + """ + ).single() assertEquals(1, facadeClass.findMethodsByName("jar", false).size) assertEquals(1, facadeClass.findMethodsByName("boo", false).size) @@ -88,7 +90,8 @@ class LightClassFromTextTest : KotlinLightCodeInsightFixtureTestCase() { fun testReferenceToOuterContext() { val contextFile = myFixture.configureByText("Example.kt", "package foo\n class Example") as KtFile - val syntheticClass = classesFromText(""" + val syntheticClass = classesFromText( + """ package bar import foo.Example @@ -96,7 +99,8 @@ class LightClassFromTextTest : KotlinLightCodeInsightFixtureTestCase() { class Usage { fun f(): Example = Example() } - """).single() + """ + ).single() val exampleClass = contextFile.classes.single() assertEquals("Example", exampleClass.name) diff --git a/idea/tests/org/jetbrains/kotlin/idea/AbstractExpressionSelectionTest.kt b/idea/tests/org/jetbrains/kotlin/idea/AbstractExpressionSelectionTest.kt index 871984c53f8..38e5409d1ed 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/AbstractExpressionSelectionTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/AbstractExpressionSelectionTest.kt @@ -21,16 +21,11 @@ abstract class AbstractExpressionSelectionTest : KotlinLightCodeInsightTestCase( val expectedExpression = KotlinTestUtils.getLastCommentInFile(getFile() as KtFile) try { - selectElement( - getEditor(), - getFile() as KtFile, - listOf(CodeInsightUtils.ElementKind.EXPRESSION) - ) { + selectElement(getEditor(), getFile() as KtFile, listOf(CodeInsightUtils.ElementKind.EXPRESSION)) { assertNotNull("Selected expression mustn't be null", it) assertEquals(expectedExpression, it?.text) } - } - catch (e: IntroduceRefactoringException) { + } catch (e: IntroduceRefactoringException) { assertEquals(expectedExpression, "") } } diff --git a/idea/tests/org/jetbrains/kotlin/idea/DummyFileResolveCachingTest.kt b/idea/tests/org/jetbrains/kotlin/idea/DummyFileResolveCachingTest.kt index c204d2664fc..cab3f0fed9a 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/DummyFileResolveCachingTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/DummyFileResolveCachingTest.kt @@ -26,10 +26,8 @@ class DummyFileResolveCachingTest : LightCodeInsightFixtureTestCase() { val dummyFileText = "import java.util.Properties" val dummyFile = KtPsiFactory(project).createAnalyzableFile("Dummy.kt", dummyFileText, file) - fun findClassifier(identifier: String) = - dummyFile.getResolutionFacade() - .getFileResolutionScope(dummyFile) - .findClassifier(Name.identifier(identifier), NoLookupLocation.FROM_IDE) + fun findClassifier(identifier: String) = dummyFile.getResolutionFacade().getFileResolutionScope(dummyFile) + .findClassifier(Name.identifier(identifier), NoLookupLocation.FROM_IDE) assertNotNull(findClassifier("Properties")) diff --git a/idea/tests/org/jetbrains/kotlin/idea/OutdatedKotlinRuntimeNotificationTest.kt b/idea/tests/org/jetbrains/kotlin/idea/OutdatedKotlinRuntimeNotificationTest.kt index 64d1f692edd..25846a7b4c4 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/OutdatedKotlinRuntimeNotificationTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/OutdatedKotlinRuntimeNotificationTest.kt @@ -41,13 +41,17 @@ class KotlinRuntimeLibraryUtilTest : TestCase() { } private fun outdated(bundledRuntime: String, library: String) { - Assert.assertTrue("Should be outdated: bundled=$bundledRuntime, library=$library", - isRuntimeOutdated(library, bundledRuntime)) + Assert.assertTrue( + "Should be outdated: bundled=$bundledRuntime, library=$library", + isRuntimeOutdated(library, bundledRuntime) + ) } private fun notOutdated(bundledRuntime: String, library: String) { - Assert.assertFalse("Should NOT be outdated: bundled=$bundledRuntime, library=$library", - isRuntimeOutdated(library, bundledRuntime)) + Assert.assertFalse( + "Should NOT be outdated: bundled=$bundledRuntime, library=$library", + isRuntimeOutdated(library, bundledRuntime) + ) } } \ No newline at end of file diff --git a/idea/tests/org/jetbrains/kotlin/idea/actions/AbstractGotoTestOrCodeActionTest.kt b/idea/tests/org/jetbrains/kotlin/idea/actions/AbstractGotoTestOrCodeActionTest.kt index 5fca0408233..de2cc5197e1 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/actions/AbstractGotoTestOrCodeActionTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/actions/AbstractGotoTestOrCodeActionTest.kt @@ -10,7 +10,7 @@ import com.intellij.psi.PsiFile import com.intellij.testIntegration.GotoTestOrCodeHandler abstract class AbstractGotoTestOrCodeActionTest : AbstractNavigationTest() { - private object Handler: GotoTestOrCodeHandler() { + private object Handler : GotoTestOrCodeHandler() { public override fun getSourceAndTargetElements(editor: Editor?, file: PsiFile?) = super.getSourceAndTargetElements(editor, file) } diff --git a/idea/tests/org/jetbrains/kotlin/idea/actions/AbstractNavigationTest.kt b/idea/tests/org/jetbrains/kotlin/idea/actions/AbstractNavigationTest.kt index 2910f5b7014..628d8bef1d2 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/actions/AbstractNavigationTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/actions/AbstractNavigationTest.kt @@ -38,16 +38,15 @@ abstract class AbstractNavigationTest : KotlinLightCodeInsightFixtureTestCase() val mainFileName = mainFile.name val mainFileBaseName = mainFileName.substring(0, mainFileName.indexOf('.')) configureExtra(mainFileBaseName, fileText) - mainFile.parentFile - .listFiles { _, name -> - name != mainFileName && name.startsWith("$mainFileBaseName.") && (name.endsWith(".kt") || name.endsWith(".java") || name.endsWith(".xml")) - } - .forEach{ myFixture.configureByFile(it.name) } + mainFile.parentFile.listFiles { _, name -> + name != mainFileName && name.startsWith("$mainFileBaseName.") && (name.endsWith(".kt") || name.endsWith(".java") || name.endsWith( + ".xml" + )) + }.forEach { myFixture.configureByFile(it.name) } val file = myFixture.configureByFile(mainFileName) NavigationTestUtils.assertGotoDataMatching(editor, getSourceAndTargetElements(editor, file)) - } - finally { + } finally { ConfigLibraryUtil.unconfigureLibrariesByDirective(module, fileText) } } diff --git a/idea/tests/org/jetbrains/kotlin/idea/actions/NewKotlinFileActionTest.kt b/idea/tests/org/jetbrains/kotlin/idea/actions/NewKotlinFileActionTest.kt index 7c933b287d3..0d0dd540f0b 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/actions/NewKotlinFileActionTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/actions/NewKotlinFileActionTest.kt @@ -11,10 +11,10 @@ import org.junit.Assert import org.junit.runner.RunWith @RunWith(JUnit3WithIdeaConfigurationRunner::class) -class NewKotlinFileActionTest: LightCodeInsightFixtureTestCase() { +class NewKotlinFileActionTest : LightCodeInsightFixtureTestCase() { companion object { - private val EMPTY_PARTS_ERROR = "Name can't have empty parts" - private val EMPTY_ERROR = "Name can't be empty" + private const val EMPTY_PARTS_ERROR = "Name can't have empty parts" + private const val EMPTY_ERROR = "Name can't be empty" } fun testEmptyName() { diff --git a/idea/tests/org/jetbrains/kotlin/idea/actions/QualifiedNamesTest.kt b/idea/tests/org/jetbrains/kotlin/idea/actions/QualifiedNamesTest.kt index 1b30a60ffbf..5c68ed20781 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/actions/QualifiedNamesTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/actions/QualifiedNamesTest.kt @@ -19,8 +19,8 @@ import java.util.* class QualifiedNamesTest : KotlinLightCodeInsightTestCase() { fun testClassRef() { configureFromFileText_( - "class.kt", - """ + "class.kt", + """ package foo.bar class Klass { @@ -37,14 +37,23 @@ class QualifiedNamesTest : KotlinLightCodeInsightTestCase() { } """ ) - assertEquals(listOf("foo.bar.Klass", "foo.bar.Klass.Nested", "foo.bar.Klass.Companion", "foo.bar.Object", "foo.bar.ClassKt#getAnonymous", null), - getQualifiedNamesForDeclarations()) + assertEquals( + listOf( + "foo.bar.Klass", + "foo.bar.Klass.Nested", + "foo.bar.Klass.Companion", + "foo.bar.Object", + "foo.bar.ClassKt#getAnonymous", + null + ), + getQualifiedNamesForDeclarations() + ) } fun testFunRef() { configureFromFileText_( - "fun.kt", - """ + "fun.kt", + """ package foo.bar class Klass { @@ -59,8 +68,16 @@ class QualifiedNamesTest : KotlinLightCodeInsightTestCase() { val topLevelVal = ":)" """ ) - assertEquals(listOf("foo.bar.Klass", "foo.bar.Klass#memberFun", "foo.bar.Klass#getMemberVal", "foo.bar.FunKt#topLevelFun", "foo.bar.FunKt#getTopLevelVal"), - getQualifiedNamesForDeclarations()) + assertEquals( + listOf( + "foo.bar.Klass", + "foo.bar.Klass#memberFun", + "foo.bar.Klass#getMemberVal", + "foo.bar.FunKt#topLevelFun", + "foo.bar.FunKt#getTopLevelVal" + ), + getQualifiedNamesForDeclarations() + ) } private fun getQualifiedNamesForDeclarations(): List { diff --git a/idea/tests/org/jetbrains/kotlin/idea/caches/KotlinShortNamesCacheTest.kt b/idea/tests/org/jetbrains/kotlin/idea/caches/KotlinShortNamesCacheTest.kt index 83f797ef19a..6553aa4ecce 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/caches/KotlinShortNamesCacheTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/caches/KotlinShortNamesCacheTest.kt @@ -88,19 +88,21 @@ class KotlinShortNamesCacheTest : KotlinLightCodeInsightFixtureTestCase() { fun PsiMember.fqName() = PsiUtil.getMemberQualifiedName(this) - fun methodArrayDebugToString(a: Array) - = a.map { "${(it as KtLightMethod).getKotlinFqName()} static=${it.hasModifierProperty(PsiModifier.STATIC)}" }.joinToString("\n") + fun methodArrayDebugToString(a: Array) = + a.map { "${(it as KtLightMethod).getKotlinFqName()} static=${it.hasModifierProperty(PsiModifier.STATIC)}" }.joinToString("\n") - fun accessorArrayDebugToString(a: Array) - = a.map { "${(it as KtLightMethod).fqName()} property=${(it.lightMemberOrigin?.originalElement as KtProperty).fqName} static=${it.hasModifierProperty(PsiModifier.STATIC)}" }.joinToString("\n") + fun accessorArrayDebugToString(a: Array) = a.map { + "${(it as KtLightMethod).fqName()} property=${(it.lightMemberOrigin + ?.originalElement as KtProperty).fqName} static=${it.hasModifierProperty(PsiModifier.STATIC)}" + }.joinToString("\n") fun checkMethodFound(methods: Array, stringFqName: String, static: Boolean) { - assertNotNull("Method $stringFqName with static=$static not found\n" + methodArrayDebugToString(methods), - methods.find { - stringFqName == (it as KtLightMethod).fqName().toString() - && - it.hasModifierProperty(PsiModifier.STATIC) == static - }) + assertNotNull( + "Method $stringFqName with static=$static not found\n" + methodArrayDebugToString(methods), + methods.find { + stringFqName == (it as KtLightMethod).fqName().toString() && it.hasModifierProperty(PsiModifier.STATIC) == static + } + ) } fun checkIsSingleMethodFound(scope: GlobalSearchScope, stringFqName: String, static: Boolean, query: String = shortName(stringFqName)) { @@ -110,7 +112,12 @@ class KotlinShortNamesCacheTest : KotlinLightCodeInsightFixtureTestCase() { } } - fun checkIsSingleMethodFoundCompanion(scope: GlobalSearchScope, delegateFqName: String, originalFqName: String, query: String = shortName(originalFqName)) { + fun checkIsSingleMethodFoundCompanion( + scope: GlobalSearchScope, + delegateFqName: String, + originalFqName: String, + query: String = shortName(originalFqName) + ) { cacheInstance.getMethodsByName(query, scope).let { checkMethodFound(it, delegateFqName, true) checkMethodFound(it, originalFqName, false) @@ -137,8 +144,10 @@ class KotlinShortNamesCacheTest : KotlinLightCodeInsightFixtureTestCase() { checkIsVarAccessorsFound(scope, stringVarFqName, getter, setter, static) } - fun checkIsVarAccessorsFoundCompanion(scope: GlobalSearchScope, stringVarFqName: String, getterFqName: String, setterFqName: String, - delegateGetterFqName: String, delegateSetterFqName: String) { + fun checkIsVarAccessorsFoundCompanion( + scope: GlobalSearchScope, stringVarFqName: String, getterFqName: String, setterFqName: String, + delegateGetterFqName: String, delegateSetterFqName: String + ) { val varName = shortName(stringVarFqName) @@ -160,27 +169,31 @@ class KotlinShortNamesCacheTest : KotlinLightCodeInsightFixtureTestCase() { val varName = varFqName.shortName().asString() val companionParent = varFqName.parent().parent().asString() - checkIsVarAccessorsFoundCompanion(scope, stringVarFqName, getter, setter, - companionParent + "." + JvmAbi.getterName(varName), - companionParent + "." + JvmAbi.setterName(varName)) + checkIsVarAccessorsFoundCompanion( + scope, stringVarFqName, getter, setter, + companionParent + "." + JvmAbi.getterName(varName), + companionParent + "." + JvmAbi.setterName(varName) + ) } fun accessorsFqNameStringFor(stringVarFqName: String): Pair { val varFqName = FqName(stringVarFqName) val varShortName = varFqName.shortName().asString() val stringVarParentFqName = varFqName.parent().asString() - return Pair(stringVarParentFqName + "." + JvmAbi.getterName(varShortName), - stringVarParentFqName + "." + JvmAbi.setterName(varShortName)) + return Pair( + stringVarParentFqName + "." + JvmAbi.getterName(varShortName), + stringVarParentFqName + "." + JvmAbi.setterName(varShortName) + ) } fun checkAccessorFound(methods: Array, stringFqName: String, propertyFqName: String, static: Boolean) { assertNotNull("Accessor $stringFqName property=$propertyFqName static=$static not found\n" + accessorArrayDebugToString(methods), methods.find { stringFqName == (it as KtLightMethod).fqName().toString() - && - (it.lightMemberOrigin?.originalElement as KtProperty).fqName?.asString() == propertyFqName - && - it.hasModifierProperty(PsiModifier.STATIC) == static + && + (it.lightMemberOrigin?.originalElement as KtProperty).fqName?.asString() == propertyFqName + && + it.hasModifierProperty(PsiModifier.STATIC) == static }) } @@ -198,8 +211,10 @@ class KotlinShortNamesCacheTest : KotlinLightCodeInsightFixtureTestCase() { fun doTestGetMethodsByNameWithAccessors(file: String) { myFixture.configureByFile(file) val scope = GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module) - checkIsVarAccessorsFound(scope, "topLevelVar", "KotlinShortNameCacheTestData.getTopLevelVar", - "KotlinShortNameCacheTestData.setTopLevelVar", true) + checkIsVarAccessorsFound( + scope, "topLevelVar", "KotlinShortNameCacheTestData.getTopLevelVar", + "KotlinShortNameCacheTestData.setTopLevelVar", true + ) checkIsVarAccessorsFound(scope, "B1.staticObjectVar", true) checkIsVarAccessorsFound(scope, "B1.nonStaticObjectVar", false) @@ -220,13 +235,14 @@ class KotlinShortNamesCacheTest : KotlinLightCodeInsightFixtureTestCase() { assertNotNull("Field $stringFqName with static=$static not found\n" + fieldArrayDebugToString(methods), methods.find { stringFqName == (it as KtLightField).fqName().toString() - && - it.hasModifierProperty(PsiModifier.STATIC) == static + && + it.hasModifierProperty(PsiModifier.STATIC) == static }) } - fun fieldArrayDebugToString(a: Array) - = a.map { "${(it as KtLightField).fqName()} property=${(it.kotlinOrigin as KtProperty).fqName} static=${it.hasModifierProperty(PsiModifier.STATIC)}" }.joinToString("\n") + fun fieldArrayDebugToString(a: Array) = a.joinToString("\n") { + "${(it as KtLightField).fqName()} property=${(it.kotlinOrigin as KtProperty).fqName} static=${it.hasModifierProperty(PsiModifier.STATIC)}" + } fun checkIsSingleFieldFound(scope: GlobalSearchScope, stringFqName: String, static: Boolean, query: String = shortName(stringFqName)) { diff --git a/idea/tests/org/jetbrains/kotlin/idea/caches/resolve/AbstractIdeLightClassTest.kt b/idea/tests/org/jetbrains/kotlin/idea/caches/resolve/AbstractIdeLightClassTest.kt index f89df2f17bd..ffe30012ad4 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/caches/resolve/AbstractIdeLightClassTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/caches/resolve/AbstractIdeLightClassTest.kt @@ -95,13 +95,15 @@ abstract class AbstractIdeCompiledLightClassTest : KotlinDaemonAnalyzerTestCase( if (KotlinTestUtils.isAllFilesPresentTest(testName)) return val filePathWithoutExtension = "${KotlinTestUtils.getTestsRoot(this::class.java)}/${getTestName(false)}" - val testFile = File("$filePathWithoutExtension.kt").takeIf { it.exists() } ?: - File("$filePathWithoutExtension.kts").takeIf { it.exists() } + val testFile = + File("$filePathWithoutExtension.kt").takeIf { it.exists() } ?: File("$filePathWithoutExtension.kts").takeIf { it.exists() } Assert.assertNotNull("Test file not found!", testFile) - val libraryJar = MockLibraryUtil.compileJvmLibraryToJar(testFile!!.canonicalPath, libName(), - extraClasspath = listOf(ForTestCompileRuntime.jetbrainsAnnotationsForTests().path)) + val libraryJar = MockLibraryUtil.compileJvmLibraryToJar( + testFile!!.canonicalPath, libName(), + extraClasspath = listOf(ForTestCompileRuntime.jetbrainsAnnotationsForTests().path) + ) val jarUrl = "jar://" + FileUtilRt.toSystemIndependentName(libraryJar.absolutePath) + "!/" ModuleRootModificationUtil.addModuleLibrary(module, jarUrl) } @@ -111,7 +113,7 @@ abstract class AbstractIdeCompiledLightClassTest : KotlinDaemonAnalyzerTestCase( fun doTest(testDataPath: String) { val testDataFile = File(testDataPath) val expectedFile = KotlinTestUtils.replaceExtension( - testDataFile, "compiled.java" + testDataFile, "compiled.java" ).let { if (it.exists()) it else KotlinTestUtils.replaceExtension(testDataFile, "java") } testLightClass(expectedFile, testDataFile, { it }, { findClass(it, null, project)?.apply { @@ -127,17 +129,16 @@ private fun testLightClass(expected: File, testData: File, normalize: (String) - testData, findLightClass = findLightClass, normalizeText = { text -> - //NOTE: ide and compiler differ in names generated for parameters with unspecified names - text - .replace("java.lang.String s,", "java.lang.String p,") - .replace("java.lang.String s)", "java.lang.String p)") - .replace("java.lang.String s1", "java.lang.String p1") - .replace("java.lang.String s2", "java.lang.String p2") - .replace("java.lang.Object o)", "java.lang.Object p)") - .replace("java.lang.String[] strings", "java.lang.String[] p") - .removeLinesStartingWith("@" + JvmAnnotationNames.METADATA_FQ_NAME.asString()) - .run(normalize) - } + //NOTE: ide and compiler differ in names generated for parameters with unspecified names + text.replace("java.lang.String s,", "java.lang.String p,") + .replace("java.lang.String s)", "java.lang.String p)") + .replace("java.lang.String s1", "java.lang.String p1") + .replace("java.lang.String s2", "java.lang.String p2") + .replace("java.lang.Object o)", "java.lang.Object p)") + .replace("java.lang.String[] strings", "java.lang.String[] p") + .removeLinesStartingWith("@" + JvmAnnotationNames.METADATA_FQ_NAME.asString()) + .run(normalize) + } ) } @@ -146,10 +147,12 @@ private fun findClass(fqName: String, ktFile: KtFile?, project: Project): PsiCla return it.toLightClass() } - return JavaPsiFacade.getInstance(project).findClass(fqName, GlobalSearchScope.allScope(project)) ?: - PsiTreeUtil.findChildrenOfType(ktFile, KtClassOrObject::class.java) - .find { fqName.endsWith(it.nameAsName!!.asString()) } - ?.let { KtLightClassForSourceDeclaration.create(it) } + return JavaPsiFacade.getInstance(project).findClass(fqName, GlobalSearchScope.allScope(project)) ?: PsiTreeUtil.findChildrenOfType( + ktFile, + KtClassOrObject::class.java + ) + .find { fqName.endsWith(it.nameAsName!!.asString()) } + ?.let { KtLightClassForSourceDeclaration.create(it) } } object LightClassLazinessChecker { @@ -201,7 +204,7 @@ object LightClassLazinessChecker { fun check(lightClass: KtLightClass, tracker: Tracker, lazinessMode: Mode) { // lighter classes not implemented for locals - if (lightClass.kotlinOrigin?.isLocal ?: false) return + if (lightClass.kotlinOrigin?.isLocal == true) return tracker.allowLevel(LIGHT) @@ -258,15 +261,13 @@ object LightClassLazinessChecker { modifierListOwner.clsDelegate.modifierList!!.annotations.groupBy { delegateAnnotation -> delegateAnnotation.qualifiedName!! - }.map { - (fqName, clsAnnotations) -> + }.map { (fqName, clsAnnotations) -> val annotations = (modifierListOwner as? PsiModifierListOwner)?.modifierList?.annotations val lightAnnotations = annotations?.filter { it.qualifiedName == fqName }.orEmpty() if (fqName != Nullable::class.java.name && fqName != NotNull::class.java.name) { assertEquals(clsAnnotations.size, lightAnnotations.size, "Missing $fqName annotation") - } - else { + } else { // having duplicating nullability annotations is fine // see KtLightNullabilityAnnotation assertTrue( @@ -278,8 +279,7 @@ object LightClassLazinessChecker { ) { it.toString() }}" ) } - clsAnnotations.zip(lightAnnotations).forEach { - (clsAnnotation, lightAnnotation) -> + clsAnnotations.zip(lightAnnotations).forEach { (clsAnnotation, lightAnnotation) -> if (lightAnnotation !is KtLightNullabilityAnnotation<*>) assertNotNull( lightAnnotation!!.nameReferenceElement, @@ -298,9 +298,9 @@ object LightClassLazinessChecker { private fun PsiAnnotation.values() = parameterList.attributes.map { it.value.stringValue() } private data class ClassInfo( - val fieldNames: Collection, - val methodNames: Collection, - val modifiers: List + val fieldNames: Collection, + val methodNames: Collection, + val modifiers: List ) private fun classInfo(psiClass: PsiClass) = with(psiClass) { @@ -309,32 +309,32 @@ object LightClassLazinessChecker { } private data class FieldInfo( - val name: String, - val modifiers: List + val name: String, + val modifiers: List ) private fun fieldInfo(field: PsiField) = with(field) { checkModifierList(modifierList!!) FieldInfo( - name!!, PsiModifier.MODIFIERS.asList().filter { modifierList!!.hasModifierProperty(it) } + name, PsiModifier.MODIFIERS.asList().filter { modifierList!!.hasModifierProperty(it) } ) } private data class MethodInfo( - val name: String, - val modifiers: List, - val isConstructor: Boolean, - val parameterCount: Int, - val isVarargs: Boolean + val name: String, + val modifiers: List, + val isConstructor: Boolean, + val parameterCount: Int, + val isVarargs: Boolean ) private fun methodInfo(method: PsiMethod, lazinessMode: Mode) = with(method) { checkModifierList(method.modifierList) MethodInfo( - name, relevantModifiers(lazinessMode), - isConstructor, method.parameterList.parametersCount, isVarArgs + name, relevantModifiers(lazinessMode), + isConstructor, method.parameterList.parametersCount, isVarArgs ) } diff --git a/idea/tests/org/jetbrains/kotlin/idea/caches/resolve/HighlightingWithDependentLibrariesTest.kt b/idea/tests/org/jetbrains/kotlin/idea/caches/resolve/HighlightingWithDependentLibrariesTest.kt index 6e596f99454..da992e19de5 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/caches/resolve/HighlightingWithDependentLibrariesTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/caches/resolve/HighlightingWithDependentLibrariesTest.kt @@ -23,9 +23,9 @@ class HighlightingWithDependentLibrariesTest : KotlinLightCodeInsightFixtureTest override fun getProjectDescriptor() = object : KotlinLightProjectDescriptor() { override fun configureModule(module: Module, model: ModifiableRootModel) { val compiledJar1 = - MockLibraryUtil.compileJvmLibraryToJar("$TEST_DATA_PATH/lib1", "lib1") + MockLibraryUtil.compileJvmLibraryToJar("$TEST_DATA_PATH/lib1", "lib1") val compiledJar2 = - MockLibraryUtil.compileJvmLibraryToJar("$TEST_DATA_PATH/lib2", "lib2", extraClasspath = listOf(compiledJar1.canonicalPath)) + MockLibraryUtil.compileJvmLibraryToJar("$TEST_DATA_PATH/lib2", "lib2", extraClasspath = listOf(compiledJar1.canonicalPath)) model.addLibraryEntry(createLibrary(compiledJar1, "baseLibrary")) model.addLibraryEntry(createLibrary(compiledJar2, "dependentLibrary")) diff --git a/idea/tests/org/jetbrains/kotlin/idea/caches/resolve/IdeaModuleInfoTest.kt b/idea/tests/org/jetbrains/kotlin/idea/caches/resolve/IdeaModuleInfoTest.kt index 3fa4c6177ea..fc32d8a45da 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/caches/resolve/IdeaModuleInfoTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/caches/resolve/IdeaModuleInfoTest.kt @@ -421,9 +421,9 @@ class IdeaModuleInfoTest : ModuleTestCase() { } private fun Module.addDependency( - other: Module, - dependencyScope: DependencyScope = DependencyScope.COMPILE, - exported: Boolean = false + other: Module, + dependencyScope: DependencyScope = DependencyScope.COMPILE, + exported: Boolean = false ) = ModuleRootModificationUtil.addDependency(this, other, dependencyScope, exported) private val VirtualFile.moduleInfo: IdeaModuleInfo diff --git a/idea/tests/org/jetbrains/kotlin/idea/caches/resolve/MultiModuleHighlightingTest.kt b/idea/tests/org/jetbrains/kotlin/idea/caches/resolve/MultiModuleHighlightingTest.kt index 7d91da90a36..824a1cc3fcb 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/caches/resolve/MultiModuleHighlightingTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/caches/resolve/MultiModuleHighlightingTest.kt @@ -143,7 +143,7 @@ open class MultiModuleHighlightingTest : AbstractMultiModuleHighlightingTest() { val m1 = m2ContentRoot.findChild("m1.kt")!! val m1doc = FileDocumentManager.getInstance().getDocument(m1)!! project.executeWriteCommand("a") { - m1doc.insertString(m1doc.textLength , "fun foo() = 1") + m1doc.insertString(m1doc.textLength, "fun foo() = 1") PsiDocumentManager.getInstance(myProject).commitAllDocuments() } @@ -158,7 +158,7 @@ open class MultiModuleHighlightingTest : AbstractMultiModuleHighlightingTest() { val m2 = m1ContentRoot.findChild("m2.kt")!! val m2doc = FileDocumentManager.getInstance().getDocument(m2)!! project.executeWriteCommand("a") { - m2doc.insertString(m2doc.textLength , "fun foo() = 1") + m2doc.insertString(m2doc.textLength, "fun foo() = 1") PsiDocumentManager.getInstance(myProject).commitAllDocuments() } diff --git a/idea/tests/org/jetbrains/kotlin/idea/caches/resolve/PsiElementChecker.kt b/idea/tests/org/jetbrains/kotlin/idea/caches/resolve/PsiElementChecker.kt index 73c6f6b6b99..26fe638f7ec 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/caches/resolve/PsiElementChecker.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/caches/resolve/PsiElementChecker.kt @@ -111,8 +111,7 @@ object PsiElementChecker { node toString() Assert.assertTrue(isEquivalentTo(this)) - } - catch (t: Throwable) { + } catch (t: Throwable) { throw AssertionErrorWithCause("Failed for ${this::class.java} ${this}", t) } } diff --git a/idea/tests/org/jetbrains/kotlin/idea/codeInsight/AbstractInspectionTest.kt b/idea/tests/org/jetbrains/kotlin/idea/codeInsight/AbstractInspectionTest.kt index 3b8ecdd5d05..49e5e929e34 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/codeInsight/AbstractInspectionTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/codeInsight/AbstractInspectionTest.kt @@ -80,7 +80,7 @@ abstract class AbstractInspectionTest : KotlinLightCodeInsightFixtureTestCase() testDataPath = "${KotlinTestUtils.getHomeDirectory()}/$srcDir" val afterFiles = srcDir.listFiles { it -> it.name == "inspectionData" }?.single()?.listFiles { it -> it.extension == "after" } - ?: emptyArray() + ?: emptyArray() val psiFiles = srcDir.walkTopDown().onEnter { it.name != "inspectionData" }.mapNotNull { file -> when { file.isDirectory -> null diff --git a/idea/tests/org/jetbrains/kotlin/idea/codeInsight/AbstractMultiFileInspectionTest.kt b/idea/tests/org/jetbrains/kotlin/idea/codeInsight/AbstractMultiFileInspectionTest.kt index cb187d98587..a7b87561ec8 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/codeInsight/AbstractMultiFileInspectionTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/codeInsight/AbstractMultiFileInspectionTest.kt @@ -29,36 +29,35 @@ abstract class AbstractMultiFileInspectionTest : KotlinMultiFileTestCase() { val withFullJdk = config["withFullJdk"]?.asBoolean ?: false isMultiModule = config["isMultiModule"]?.asBoolean ?: false - doTest({ _, _ -> - val sdk = if (withFullJdk) fullJdk() else mockJdk() - addJdk(testRootDisposable) { sdk } + doTest( + { _, _ -> + val sdk = if (withFullJdk) fullJdk() else mockJdk() + addJdk(testRootDisposable) { sdk } - try { - if (withRuntime) { - project.allModules().forEach { module -> - ConfigLibraryUtil.configureKotlinRuntimeAndSdk(module, sdk) - } - } + try { + if (withRuntime) { + project.allModules().forEach { module -> + ConfigLibraryUtil.configureKotlinRuntimeAndSdk(module, sdk) + } + } - runInspection(Class.forName(config.getString("inspectionClass")), project, - withTestDir = configFile.parent) - } - finally { - if (withRuntime) { - project.allModules().forEach { module -> - ConfigLibraryUtil.unConfigureKotlinRuntimeAndSdk(module, sdk) - } - } - } - }, - getTestDirName(true)) + runInspection( + Class.forName(config.getString("inspectionClass")), project, + withTestDir = configFile.parent + ) + } finally { + if (withRuntime) { + project.allModules().forEach { module -> + ConfigLibraryUtil.unConfigureKotlinRuntimeAndSdk(module, sdk) + } + } + } + }, + getTestDirName(true) + ) } - override fun getTestRoot() : String { - return "/multiFileInspections/" - } + override fun getTestRoot(): String = "/multiFileInspections/" - override fun getTestDataPath() : String { - return getTestDataPathBase() - } + override fun getTestDataPath(): String = getTestDataPathBase() } diff --git a/idea/tests/org/jetbrains/kotlin/idea/codeInsight/AbstractOverrideImplementTest.kt b/idea/tests/org/jetbrains/kotlin/idea/codeInsight/AbstractOverrideImplementTest.kt index cd80450263d..319035bfa89 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/codeInsight/AbstractOverrideImplementTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/codeInsight/AbstractOverrideImplementTest.kt @@ -74,10 +74,10 @@ abstract class AbstractOverrideImplementTest : KotlinLightCodeInsightFixtureTest val project = myFixture.project val aClass = JavaPsiFacade.getInstance(project).findClass(className, GlobalSearchScope.allScope(project)) - ?: error("Can't find class: $className") + ?: error("Can't find class: $className") val method = aClass.findMethodsByName(methodName, false)[0] - ?: error("Can't find method '$methodName' in class $className") + ?: error("Can't find method '$methodName' in class $className") generateImplementation(method) @@ -113,7 +113,7 @@ abstract class AbstractOverrideImplementTest : KotlinLightCodeInsightFixtureTest private fun doOverrideImplement(handler: OverrideImplementMembersHandler, memberToOverride: String?) { val elementAtCaret = myFixture.file.findElementAt(myFixture.editor.caretModel.offset) val classOrObject = PsiTreeUtil.getParentOfType(elementAtCaret, KtClassOrObject::class.java) - ?: error("Caret should be inside class or object") + ?: error("Caret should be inside class or object") val chooserObjects = handler.collectMembersToGenerate(classOrObject) @@ -125,10 +125,8 @@ abstract class AbstractOverrideImplementTest : KotlinLightCodeInsightFixtureTest } assertEquals(1, filtered.size, "Invalid number of available chooserObjects for override") filtered.single() - } - else { - chooserObjects.single { - chooserObject -> + } else { + chooserObjects.single { chooserObject -> chooserObject.descriptor.name.asString() == memberToOverride } } @@ -139,9 +137,10 @@ abstract class AbstractOverrideImplementTest : KotlinLightCodeInsightFixtureTest private fun doMultiOverrideImplement(handler: OverrideImplementMembersHandler) { val elementAtCaret = myFixture.file.findElementAt(myFixture.editor.caretModel.offset) val classOrObject = PsiTreeUtil.getParentOfType(elementAtCaret, KtClassOrObject::class.java) - ?: error("Caret should be inside class or object") + ?: error("Caret should be inside class or object") - val chooserObjects = handler.collectMembersToGenerate(classOrObject).sortedBy { it.descriptor.name.asString() + " in " + it.immediateSuper.containingDeclaration.name.asString() } + val chooserObjects = handler.collectMembersToGenerate(classOrObject) + .sortedBy { it.descriptor.name.asString() + " in " + it.immediateSuper.containingDeclaration.name.asString() } performGenerateCommand(classOrObject, chooserObjects) } @@ -158,15 +157,15 @@ abstract class AbstractOverrideImplementTest : KotlinLightCodeInsightFixtureTest } private fun performGenerateCommand( - classOrObject: KtClassOrObject, - selectedElements: List) { + classOrObject: KtClassOrObject, + selectedElements: List + ) { try { val copyDoc = InTextDirectivesUtils.isDirectiveDefined(classOrObject.containingFile.text, "// COPY_DOC") myFixture.project.executeWriteCommand("") { OverrideImplementMembersHandler.generateMembers(myFixture.editor, classOrObject, selectedElements, copyDoc) } - } - catch (throwable: Throwable) { + } catch (throwable: Throwable) { throw rethrow(throwable) } @@ -182,8 +181,7 @@ abstract class AbstractOverrideImplementTest : KotlinLightCodeInsightFixtureTest document.replaceString(0, document.textLength, file.dumpTextWithErrors()) } myFixture.checkResultByFile(fileName) - } - catch (error: AssertionError) { + } catch (error: AssertionError) { KotlinTestUtils.assertEqualsToFile(expectedFile, TagsTestDataUtil.generateTextWithCaretAndSelection(myFixture.editor)) } } diff --git a/idea/tests/org/jetbrains/kotlin/idea/codeInsight/generate/AbstractCodeInsightActionTest.kt b/idea/tests/org/jetbrains/kotlin/idea/codeInsight/generate/AbstractCodeInsightActionTest.kt index 327eeadb50e..08ce7d224b8 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/codeInsight/generate/AbstractCodeInsightActionTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/codeInsight/generate/AbstractCodeInsightActionTest.kt @@ -18,10 +18,10 @@ import org.jetbrains.kotlin.idea.project.forcedTargetPlatform import org.jetbrains.kotlin.idea.test.ConfigLibraryUtil import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor -import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.platform.CommonPlatforms import org.jetbrains.kotlin.platform.js.JsPlatforms import org.jetbrains.kotlin.platform.jvm.JvmPlatforms +import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.test.InTextDirectivesUtils import org.jetbrains.kotlin.test.KotlinTestUtils import java.io.File @@ -103,14 +103,11 @@ abstract class AbstractCodeInsightActionTest : KotlinLightCodeInsightFixtureTest myFixture.checkResult(FileUtil.loadFile(afterFile, true)) checkExtra() } - } - catch (e: ComparisonFailure) { + } catch (e: ComparisonFailure) { KotlinTestUtils.assertEqualsToFile(afterFile, myFixture.editor) - } - catch (e: CommonRefactoringUtil.RefactoringErrorHintException) { + } catch (e: CommonRefactoringUtil.RefactoringErrorHintException) { KotlinTestUtils.assertEqualsToFile(conflictFile, e.message!!) - } - finally { + } finally { mainPsiFile?.forcedTargetPlatform = null ConfigLibraryUtil.unconfigureLibrariesByDirective(module, fileText) } diff --git a/idea/tests/org/jetbrains/kotlin/idea/codeInsight/generate/AbstractGenerateHashCodeAndEqualsActionTest.kt b/idea/tests/org/jetbrains/kotlin/idea/codeInsight/generate/AbstractGenerateHashCodeAndEqualsActionTest.kt index 98eb1d45e00..f83428eeb10 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/codeInsight/generate/AbstractGenerateHashCodeAndEqualsActionTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/codeInsight/generate/AbstractGenerateHashCodeAndEqualsActionTest.kt @@ -20,8 +20,7 @@ abstract class AbstractGenerateHashCodeAndEqualsActionTest : AbstractCodeInsight val useInstanceOfOnEqualsParameterOld = codeInsightSettings.USE_INSTANCEOF_ON_EQUALS_PARAMETER try { - codeInsightSettings.USE_INSTANCEOF_ON_EQUALS_PARAMETER = - InTextDirectivesUtils.isDirectiveDefined(fileText, "// USE_IS_CHECK") + codeInsightSettings.USE_INSTANCEOF_ON_EQUALS_PARAMETER = InTextDirectivesUtils.isDirectiveDefined(fileText, "// USE_IS_CHECK") super.doTest(path) } finally { codeInsightSettings.USE_INSTANCEOF_ON_EQUALS_PARAMETER = useInstanceOfOnEqualsParameterOld diff --git a/idea/tests/org/jetbrains/kotlin/idea/codeInsight/generate/AbstractGenerateTestSupportMethodActionTest.kt b/idea/tests/org/jetbrains/kotlin/idea/codeInsight/generate/AbstractGenerateTestSupportMethodActionTest.kt index 8bc834f9baa..5efaae03728 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/codeInsight/generate/AbstractGenerateTestSupportMethodActionTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/codeInsight/generate/AbstractGenerateTestSupportMethodActionTest.kt @@ -23,10 +23,9 @@ abstract class AbstractGenerateTestSupportMethodActionTest : AbstractCodeInsight } } - override fun createAction(fileText: String) = - (super.createAction(fileText) as KotlinGenerateTestSupportActionBase).apply { - testFrameworkToUse = InTextDirectivesUtils.findStringWithPrefixes(fileText, "// TEST_FRAMEWORK:") - } + override fun createAction(fileText: String) = (super.createAction(fileText) as KotlinGenerateTestSupportActionBase).apply { + testFrameworkToUse = InTextDirectivesUtils.findStringWithPrefixes(fileText, "// TEST_FRAMEWORK:") + } override fun doTest(path: String) { setUpTestSourceRoot() diff --git a/idea/tests/org/jetbrains/kotlin/idea/codeInsight/moveUpDown/AbstractCodeMoverTest.kt b/idea/tests/org/jetbrains/kotlin/idea/codeInsight/moveUpDown/AbstractCodeMoverTest.kt index 2df2557ea8c..1620d908bbd 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/codeInsight/moveUpDown/AbstractCodeMoverTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/codeInsight/moveUpDown/AbstractCodeMoverTest.kt @@ -52,7 +52,7 @@ abstract class AbstractMoveStatementTest : AbstractCodeMoverTest() { abstract class AbstractMoveLeftRightTest : AbstractCodeMoverTest() { protected fun doTest(path: String) { - doTest(path) { _, _ -> } + doTest(path) { _, _ -> } } } @@ -72,8 +72,7 @@ abstract class AbstractCodeMoverTest : KotlinLightCodeInsightTestCase() { configureByFile(path) val fileText = FileUtil.loadFile(File(path), true) - val direction = InTextDirectivesUtils.findStringWithPrefixes(fileText, "// MOVE: ") - ?: error("No MOVE directive found") + val direction = InTextDirectivesUtils.findStringWithPrefixes(fileText, "// MOVE: ") ?: error("No MOVE directive found") val action = when (direction) { "up" -> MoveStatementUpAction() @@ -111,16 +110,14 @@ abstract class AbstractCodeMoverTest : KotlinLightCodeInsightTestCase() { TestCase.assertEquals(isApplicableExpected, !actionDoesNothing) if (isApplicableExpected) { - val afterFilePath = path + ".after" + val afterFilePath = "$path.after" try { checkResultByFile(afterFilePath) - } - catch (e: ComparisonFailure) { + } catch (e: ComparisonFailure) { KotlinTestUtils.assertEqualsToFile(File(afterFilePath), editor) } } - } - finally { + } finally { codeStyleSettings.clearCodeStyleSettings() } } diff --git a/idea/tests/org/jetbrains/kotlin/idea/codeInsight/smartEnter/SmartEnterTest.kt b/idea/tests/org/jetbrains/kotlin/idea/codeInsight/smartEnter/SmartEnterTest.kt index cb9f14648d6..b1961d9364f 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/codeInsight/smartEnter/SmartEnterTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/codeInsight/smartEnter/SmartEnterTest.kt @@ -16,35 +16,35 @@ import org.junit.runner.RunWith @RunWith(JUnit3WithIdeaConfigurationRunner::class) class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { fun testIfCondition() = doFunTest( - """ + """ if """ - , - """ + , + """ if () { } """ ) fun testIfCondition2() = doFunTest( - """ + """ if """ - , - """ + , + """ if () { } """ ) fun testIfWithFollowingCode() = doFunTest( - """ + """ if return true """ - , - """ + , + """ if () { } @@ -53,23 +53,23 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testIfCondition3() = doFunTest( - """ + """ if ( """ - , - """ + , + """ if () { } """ ) fun testIfCondition4() = doFunTest( - """ + """ if (true) { } """ - , - """ + , + """ if (true) { } @@ -77,11 +77,11 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testIfCondition5() = doFunTest( - """ + """ if (true) { """ - , - """ + , + """ if (true) { } @@ -89,13 +89,13 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testIfCondition6() = doFunTest( - """ + """ if (true) { println() } """ - , - """ + , + """ if (true) { println() @@ -104,34 +104,34 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testIfThenOneLine1() = doFunTest( - """ + """ if (true) println() """ - , - """ + , + """ if (true) println() """ ) fun testIfThenOneLine2() = doFunTest( - """ + """ if (true) println() """ - , - """ + , + """ if (true) println() """ ) fun testIfThenMultiLine1() = doFunTest( - """ + """ if (true) println() """ - , - """ + , + """ if (true) println() @@ -139,12 +139,12 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testIfThenMultiLine2() = doFunTest( - """ + """ if (true) println() """ - , - """ + , + """ if (true) println() @@ -153,12 +153,12 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { // TODO: indent for println fun testIfThenMultiLine3() = doFunTest( - """ + """ if (true) println() """ - , - """ + , + """ if (true) { } @@ -167,11 +167,11 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testIfWithReformat() = doFunTest( - """ + """ if (true) { } """, - """ + """ if (true) { } @@ -179,11 +179,11 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testElse() = doFunTest( - """ + """ if (true) { } else """, - """ + """ if (true) { } else { @@ -192,11 +192,11 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testElseOneLine1() = doFunTest( - """ + """ if (true) { } else println() """, - """ + """ if (true) { } else println() @@ -204,11 +204,11 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testElseOneLine2() = doFunTest( - """ + """ if (true) { } else println() """, - """ + """ if (true) { } else println() @@ -216,12 +216,12 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testElseTwoLines1() = doFunTest( - """ + """ if (true) { } else println() """, - """ + """ if (true) { } else println() @@ -230,12 +230,12 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testElseTwoLines2() = doFunTest( - """ + """ if (true) { } else println() """, - """ + """ if (true) { } else println() @@ -245,11 +245,11 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { // TODO: remove space in expected data fun testElseWithSpace() = doFunTest( - """ + """ if (true) { } else """, - """ + """ if (true) { } else { @@ -259,45 +259,45 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { fun testWhile() = doFunTest( - """ + """ while """ - , - """ + , + """ while () { } """ ) fun testWhile2() = doFunTest( - """ + """ while """ - , - """ + , + """ while () { } """ ) fun testWhile3() = doFunTest( - """ + """ while ( """ - , - """ + , + """ while () { } """ ) fun testWhile4() = doFunTest( - """ + """ while (true) { } """ - , - """ + , + """ while (true) { } @@ -305,11 +305,11 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testWhile5() = doFunTest( - """ + """ while (true) { """ - , - """ + , + """ while (true) { } @@ -317,13 +317,13 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testWhile6() = doFunTest( - """ + """ while (true) { println() } """ - , - """ + , + """ while (true) { println() @@ -332,31 +332,31 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testWhile7() = doFunTest( - """ + """ while () """, - """ + """ while () { } """ ) fun testWhileSingle() = doFunTest( - """ + """ while (true) println() """, - """ + """ while (true) println() """ ) fun testWhileMultiLine1() = doFunTest( - """ + """ while (true) println() """, - """ + """ while (true) println() @@ -364,11 +364,11 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testWhileMultiLine2() = doFunTest( - """ + """ while (true) println() """, - """ + """ while (true) { } @@ -377,34 +377,34 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testForStatement() = doFunTest( - """ + """ for """ - , - """ + , + """ for () { } """ ) fun testForStatement2() = doFunTest( - """ + """ for """ - , - """ + , + """ for () { } """ ) fun testForStatement4() = doFunTest( - """ + """ for (i in 1..10) { } """ - , - """ + , + """ for (i in 1..10) { } @@ -412,11 +412,11 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testForStatement5() = doFunTest( - """ + """ for (i in 1..10) { """ - , - """ + , + """ for (i in 1..10) { } @@ -424,13 +424,13 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testForStatement6() = doFunTest( - """ + """ for (i in 1..10) { println() } """ - , - """ + , + """ for (i in 1..10) { println() @@ -439,33 +439,33 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testForStatementSingle() = doFunTest( - """ + """ for (i in 1..10) println() """ - , - """ + , + """ for (i in 1..10) println() """ ) fun testForStatementSingleEmpty() = doFunTest( - """ + """ for () println() """ - , - """ + , + """ for () println() """ ) fun testForStatementOnLoopParameter() = doFunTest( - """ + """ for (some) println() """ - , - """ + , + """ for (some) { } @@ -474,11 +474,11 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testForMultiLine1() = doFunTest( - """ + """ for (i in 1..10) println() """, - """ + """ for (i in 1..10) { } @@ -487,11 +487,11 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testForMultiLine2() = doFunTest( - """ + """ for (i in 1..10) println() """, - """ + """ for (i in 1..10) println() @@ -499,11 +499,11 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testWhen() = doFunTest( - """ + """ when """ - , - """ + , + """ when { } @@ -511,11 +511,11 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testWhen1() = doFunTest( - """ + """ when """ - , - """ + , + """ when { } @@ -523,12 +523,12 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testWhen2() = doFunTest( - """ + """ when (true) { } """ - , - """ + , + """ when (true) { } @@ -536,11 +536,11 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testWhen3() = doFunTest( - """ + """ when (true) { """ - , - """ + , + """ when (true) { } @@ -548,13 +548,13 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testWhen4() = doFunTest( - """ + """ when (true) { false -> println("false") } """ - , - """ + , + """ when (true) { false -> println("false") @@ -563,22 +563,22 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testWhen5() = doFunTest( - """ + """ when () """ - , - """ + , + """ when () { } """ ) fun testWhen6() = doFunTest( - """ + """ when (true) """ - , - """ + , + """ when (true) { } @@ -587,12 +587,12 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { // Check that no addition {} inserted fun testWhenBadParsed() = doFunTest( - """ + """ when ({ } """ - , - """ + , + """ when ({ } @@ -600,35 +600,35 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testDoWhile() = doFunTest( - """ + """ do """ - , - """ + , + """ do { } while ()${' '} """ ) fun testDoWhile2() = doFunTest( - """ + """ do """ - , - """ + , + """ do { } while () """ ) fun testDoWhile3() = doFunTest( - """ + """ do { println(hi) } """ - , - """ + , + """ do { println(hi) } while () @@ -636,24 +636,24 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testDoWhile5() = doFunTest( - """ + """ do { } while () """ - , - """ + , + """ do { } while () """ ) fun testDoWhile6() = doFunTest( - """ + """ do { } while (true) """ - , - """ + , + """ do { } while (true) @@ -661,12 +661,12 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testDoWhile7() = doFunTest( - """ + """ do { } while (true) """ - , - """ + , + """ do { } while (true) @@ -674,12 +674,12 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testDoWhile8() = doFunTest( - """ + """ do { } while (true) """ - , - """ + , + """ do { } while (true) @@ -687,22 +687,22 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testDoWhile9() = doFunTest( - """ + """ do while """ - , - """ + , + """ do { } while () """ ) fun testDoWhile10() = doFunTest( - """ + """ do while (true) """ - , - """ + , + """ do { } while (true) @@ -710,13 +710,13 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testDoWhile11() = doFunTest( - """ + """ do { println("some") } while """ - , - """ + , + """ do { println("some") } while () @@ -724,13 +724,13 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testDoWhile12() = doFunTest( - """ + """ do { println("some") } while (true """ - , - """ + , + """ do { println("some") @@ -739,12 +739,12 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testDoWhile13() = doFunTest( - """ + """ do println("some") """ - , - """ + , + """ do { println("some") } while () @@ -752,12 +752,12 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testDoWhile14() = doFunTest( - """ + """ do println("some") """ - , - """ + , + """ do { println("some") } while () @@ -765,12 +765,12 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testDoWhileOneLine1() = doFunTest( - """ + """ do println("some") while (true) println("hi") """ - , - """ + , + """ do println("some") while (true) println("hi") @@ -778,12 +778,12 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testDoWhileOneLine2() = doFunTest( - """ + """ do println("some") while (true) println("hi") """ - , - """ + , + """ do println("some") while (true) println("hi") @@ -791,12 +791,12 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testDoWhileMultiLine1() = doFunTest( - """ + """ do println() while (true) """, - """ + """ do println() @@ -805,12 +805,12 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testDoWhileMultiLine2() = doFunTest( - """ + """ do println() while (true) """, - """ + """ do { println() @@ -819,12 +819,12 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testDoWhileMultiLine3() = doFunTest( - """ + """ do println() while (true) """, - """ + """ do { println() @@ -833,11 +833,11 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testFunBody() = doFileTest( - """ + """ fun test() """ - , - """ + , + """ fun test() { } @@ -845,11 +845,11 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testFunBody1() = doFileTest( - """ + """ fun test """ - , - """ + , + """ fun test() { } @@ -857,11 +857,11 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testFunBody2() = doFileTest( - """ + """ fun (p: Int, s: String """ - , - """ + , + """ fun(p: Int, s: String) { } @@ -869,13 +869,13 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testFunBody3() = doFileTest( - """ + """ interface Some { fun (p: Int) } """ - , - """ + , + """ interface Some { fun(p: Int) @@ -884,13 +884,13 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testFunBody4() = doFileTest( - """ + """ class Some { abstract fun (p: Int) } """ - , - """ + , + """ class Some { abstract fun(p: Int) @@ -899,13 +899,13 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testFunBody5() = doFileTest( - """ + """ class Some { fun test(p: Int) = 1 } """ - , - """ + , + """ class Some { fun test(p: Int) = 1 @@ -914,12 +914,12 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testFunBody6() = doFileTest( - """ + """ fun test(p: Int) { } """ - , - """ + , + """ fun test(p: Int) { } @@ -927,12 +927,12 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testFunBody7() = doFileTest( - """ + """ trait T fun other() where U: T """, - """ + """ trait T fun other() where U : T { @@ -942,10 +942,10 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testFunBody8() = doFileTest( - """ + """ fun Int.other """, - """ + """ fun Int.other() { } @@ -953,22 +953,22 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testFunBody9() = doFileTest( - """ + """ fun test(){} """, - """ + """ fun test() {} """ ) fun testInLambda1() = doFunTest( - """ + """ some { p -> } """, - """ + """ some { p -> @@ -977,11 +977,11 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testInLambda2() = doFunTest( - """ + """ some { p -> } """, - """ + """ some { p -> } @@ -989,11 +989,11 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testInLambda3() = doFunTest( - """ + """ some { (p: Int) : Int -> } """, - """ + """ some { (p: Int) : Int -> } @@ -1001,12 +1001,12 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testInLambda4() = doFunTest( - """ + """ some { (p: Int) : Int -> } """, - """ + """ some { (p: Int) : Int -> @@ -1015,12 +1015,12 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testSetter1() = doFileTest( - """ + """ var a : Int = 0 set """ - , - """ + , + """ var a : Int = 0 set @@ -1028,12 +1028,12 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testSetter2() = doFileTest( - """ + """ var a : Int = 0 set( """ - , - """ + , + """ var a : Int = 0 set(value) { @@ -1042,12 +1042,12 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testSetter3() = doFileTest( - """ + """ var a : Int = 0 set() """ - , - """ + , + """ var a : Int = 0 set(value) { @@ -1056,12 +1056,12 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testSetter4() = doFileTest( - """ + """ var a : Int = 0 set(v) """ - , - """ + , + """ var a : Int = 0 set(v) { @@ -1070,13 +1070,13 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testSetter5() = doFileTest( - """ + """ var a : Int = 0 set() { } """ - , - """ + , + """ var a : Int = 0 set(value) { @@ -1085,13 +1085,13 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testSetter6() = doFileTest( - """ + """ var a : Int = 0 set(v) { } """ - , - """ + , + """ var a : Int = 0 set(v) { @@ -1100,12 +1100,12 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testSetter7() = doFileTest( - """ + """ var a : Int = 0 set(value){} """ - , - """ + , + """ var a : Int = 0 set(value) {} @@ -1113,12 +1113,12 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testSetterPrivate1() = doFileTest( - """ + """ var a : Int = 0 private set """ - , - """ + , + """ var a : Int = 0 private set @@ -1126,12 +1126,12 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testSetterPrivate2() = doFileTest( - """ + """ var a : Int = 0 private set( """ - , - """ + , + """ var a : Int = 0 private set(value) { @@ -1140,12 +1140,12 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testSetterPrivate3() = doFileTest( - """ + """ var a : Int = 0 private set() """ - , - """ + , + """ var a : Int = 0 private set(value) { @@ -1154,12 +1154,12 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testSetterPrivate4() = doFileTest( - """ + """ var a : Int = 0 private set(v) """ - , - """ + , + """ var a : Int = 0 private set(v) { @@ -1168,13 +1168,13 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testSetterPrivate5() = doFileTest( - """ + """ var a : Int = 0 private set() { } """ - , - """ + , + """ var a : Int = 0 private set(value) { @@ -1183,13 +1183,13 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testSetterPrivate6() = doFileTest( - """ + """ var a : Int = 0 private set(v) { } """ - , - """ + , + """ var a : Int = 0 private set(v) { @@ -1198,11 +1198,11 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testTryBody() = doFunTest( - """ + """ try """ - , - """ + , + """ try { } @@ -1210,12 +1210,12 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testCatchBody() = doFunTest( - """ + """ try { } catch(e: Exception) """ - , - """ + , + """ try { } catch (e: Exception) { @@ -1224,12 +1224,12 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testCatchParameter1() = doFunTest( - """ + """ try { } catch """ - , - """ + , + """ try { } catch () { } @@ -1237,12 +1237,12 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testCatchParameter2() = doFunTest( - """ + """ try { } catch( """ - , - """ + , + """ try { } catch () { } @@ -1250,12 +1250,12 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testCatchParameter3() = doFunTest( - """ + """ try { } catch( {} """ - , - """ + , + """ try { } catch () { } @@ -1263,12 +1263,12 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testCatchParameter4() = doFunTest( - """ + """ try { } catch(e: Exception """ - , - """ + , + """ try { } catch (e: Exception) { @@ -1277,13 +1277,13 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testFinallyBody() = doFunTest( - """ + """ try { } catch(e: Exception) { } finally """ - , - """ + , + """ try { } catch (e: Exception) { } finally { @@ -1293,15 +1293,15 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testLambdaParam() = doFileTest( - """ + """ fun foo(a: Any, block: () -> Unit) { } fun test() { foo(Any()) } """ - , - """ + , + """ fun foo(a: Any, block: () -> Unit) { } fun test() { @@ -1311,15 +1311,15 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testExtensionLambdaParam() = doFileTest( - """ + """ fun foo(a: Any, block: Any.() -> Unit) { } fun test() { foo(Any()) } """ - , - """ + , + """ fun foo(a: Any, block: Any.() -> Unit) { } fun test() { @@ -1329,13 +1329,13 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testClassInit() = doFileTest( - """ + """ class Foo { init } """ - , - """ + , + """ class Foo { init { @@ -1345,11 +1345,11 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testClassBody1() = doFileTest( - """ + """ class Foo """ - , - """ + , + """ class Foo { } @@ -1357,11 +1357,11 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testClassBody2() = doFileTest( - """ + """ class Foo """ - , - """ + , + """ class Foo { } @@ -1369,12 +1369,12 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testObjectExpressionBody1() = doFileTest( - """ + """ interface I val a = object : I """ - , - """ + , + """ interface I val a = object : I { @@ -1383,14 +1383,14 @@ class SmartEnterTest : KotlinLightCodeInsightFixtureTestCase() { ) fun testObjectExpressionBody2() = doFileTest( - """ + """ interface I val a = object : I val b = "" """ - , - """ + , + """ interface I val a = object : I { diff --git a/idea/tests/org/jetbrains/kotlin/idea/configuration/AbstractConfigureKotlinTest.kt b/idea/tests/org/jetbrains/kotlin/idea/configuration/AbstractConfigureKotlinTest.kt index b0e12523cc8..7eb02ffa737 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/configuration/AbstractConfigureKotlinTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/configuration/AbstractConfigureKotlinTest.kt @@ -120,8 +120,8 @@ abstract class AbstractConfigureKotlinTest : PlatformTestCase() { val testName = getTestName(true) return if (testName.contains("_")) { testName.substring(0, testName.indexOf("_")) - } - else testName + } else + testName } protected val projectRoot: String @@ -150,11 +150,11 @@ abstract class AbstractConfigureKotlinTest : PlatformTestCase() { } private fun configure( - modules: List, - runtimeState: FileState, - configurator: KotlinWithLibraryConfigurator, - jarFromDist: String, - jarFromTemp: String + modules: List, + runtimeState: FileState, + configurator: KotlinWithLibraryConfigurator, + jarFromDist: String, + jarFromTemp: String ) { val project = modules.first().project val collector = createConfigureKotlinNotificationCollector(project) @@ -181,14 +181,19 @@ abstract class AbstractConfigureKotlinTest : PlatformTestCase() { protected fun assertNotConfigured(module: Module, configurator: KotlinWithLibraryConfigurator) { TestCase.assertFalse( - String.format("Module %s should not be configured as %s Module", module.name, configurator.presentableText), - configurator.isConfigured(module)) + String.format("Module %s should not be configured as %s Module", module.name, configurator.presentableText), + configurator.isConfigured(module) + ) } protected fun assertConfigured(module: Module, configurator: KotlinWithLibraryConfigurator) { - TestCase.assertTrue(String.format("Module %s should be configured with configurator '%s'", module.name, - configurator.presentableText), - configurator.isConfigured(module)) + TestCase.assertTrue( + String.format( + "Module %s should be configured with configurator '%s'", module.name, + configurator.presentableText + ), + configurator.isConfigured(module) + ) } protected fun assertProperlyConfigured(module: Module, configurator: KotlinWithLibraryConfigurator) { diff --git a/idea/tests/org/jetbrains/kotlin/idea/configuration/ConfigureKotlinInTempDirTest.kt b/idea/tests/org/jetbrains/kotlin/idea/configuration/ConfigureKotlinInTempDirTest.kt index 1fd374a4fe2..a55ee5ecc7b 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/configuration/ConfigureKotlinInTempDirTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/configuration/ConfigureKotlinInTempDirTest.kt @@ -90,7 +90,10 @@ open class ConfigureKotlinInTempDirTest : AbstractConfigureKotlinInTempDirTest() Assert.assertEquals(true, settings.useProjectSettings) Assert.assertEquals("1.1", settings.languageLevel!!.description) Assert.assertEquals("1.1", settings.apiLevel!!.description) - Assert.assertEquals("-version -Xallow-kotlin-package -Xskip-metadata-version-check", settings.compilerSettings!!.additionalArguments) + Assert.assertEquals( + "-version -Xallow-kotlin-package -Xskip-metadata-version-check", + settings.compilerSettings!!.additionalArguments + ) } fun testLoadAndSaveProjectWithV2FacetConfig() { @@ -109,7 +112,10 @@ open class ConfigureKotlinInTempDirTest : AbstractConfigureKotlinInTempDirTest() application.isSaveAllowed = true application.saveAll() val moduleFileContentAfter = String(module.moduleFile!!.contentsToByteArray()) - Assert.assertEquals(moduleFileContentBefore.replace("platform=\"Native \"", "platform=\"Native \" allPlatforms=\"Native []\""), moduleFileContentAfter) + Assert.assertEquals( + moduleFileContentBefore.replace("platform=\"Native \"", "platform=\"Native \" allPlatforms=\"Native []\""), + moduleFileContentAfter + ) } //TODO(auskov): test parsing common target platform with multiple versions of java, add parsing common platforms @@ -119,7 +125,10 @@ open class ConfigureKotlinInTempDirTest : AbstractConfigureKotlinInTempDirTest() application.isSaveAllowed = true application.saveAll() val moduleFileContentAfter = String(module.moduleFile!!.contentsToByteArray()) - Assert.assertEquals(moduleFileContentBefore.replace("platform=\"JVM 1.8\"", "platform=\"JVM 1.8\" allPlatforms=\"JVM [1.8]\""), moduleFileContentAfter) + Assert.assertEquals( + moduleFileContentBefore.replace("platform=\"JVM 1.8\"", "platform=\"JVM 1.8\" allPlatforms=\"JVM [1.8]\""), + moduleFileContentAfter + ) } fun testLoadAndSaveProjectHMPPFacetConfig() { @@ -128,7 +137,10 @@ open class ConfigureKotlinInTempDirTest : AbstractConfigureKotlinInTempDirTest() application.isSaveAllowed = true application.saveAll() val moduleFileContentAfter = String(module.moduleFile!!.contentsToByteArray()) - Assert.assertEquals(moduleFileContentBefore.replace("platform=\"JVM 1.8\"", "platform=\"JVM 1.8\" allPlatforms=\"JVM [1.8]\""), moduleFileContentAfter) + Assert.assertEquals( + moduleFileContentBefore.replace("platform=\"JVM 1.8\"", "platform=\"JVM 1.8\" allPlatforms=\"JVM [1.8]\""), + moduleFileContentAfter + ) } diff --git a/idea/tests/org/jetbrains/kotlin/idea/configuration/KotlinFrameworkSupportProviderTest.kt b/idea/tests/org/jetbrains/kotlin/idea/configuration/KotlinFrameworkSupportProviderTest.kt index eb16bc488c8..6e630aa9994 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/configuration/KotlinFrameworkSupportProviderTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/configuration/KotlinFrameworkSupportProviderTest.kt @@ -22,7 +22,7 @@ class KotlinFrameworkSupportProviderTest : FrameworkSupportProviderTestCase() { selectFramework(provider).createLibraryDescription() addSupport() - with (KotlinCommonCompilerArgumentsHolder.getInstance(module.project).settings) { + with(KotlinCommonCompilerArgumentsHolder.getInstance(module.project).settings) { TestCase.assertEquals(VersionView.LatestStable, languageVersionView) TestCase.assertEquals(VersionView.LatestStable, apiVersionView) } diff --git a/idea/tests/org/jetbrains/kotlin/idea/coverage/AbstractKotlinCoverageOutputFilesTest.kt b/idea/tests/org/jetbrains/kotlin/idea/coverage/AbstractKotlinCoverageOutputFilesTest.kt index 811a98f137a..6a956781130 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/coverage/AbstractKotlinCoverageOutputFilesTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/coverage/AbstractKotlinCoverageOutputFilesTest.kt @@ -8,13 +8,12 @@ package org.jetbrains.kotlin.idea.coverage import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.VirtualFile import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase -import org.jetbrains.kotlin.idea.test.PluginTestCaseBase import org.jetbrains.kotlin.idea.util.application.runWriteAction import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.test.KotlinTestUtils import java.io.File -abstract class AbstractKotlinCoverageOutputFilesTest: KotlinLightCodeInsightFixtureTestCase() { +abstract class AbstractKotlinCoverageOutputFilesTest : KotlinLightCodeInsightFixtureTestCase() { fun doTest(path: String) { val kotlinFile = myFixture.configureByFile(fileName()) as KtFile val outDir = myFixture.tempDirFixture.findOrCreateDir("coverageTestOut") @@ -27,8 +26,7 @@ abstract class AbstractKotlinCoverageOutputFilesTest: KotlinLightCodeInsightFixt val actualClasses = KotlinCoverageExtension.collectGeneratedClassQualifiedNames(outDir, kotlinFile) KotlinTestUtils.assertEqualsToFile(File(testPath().replace(".kt", ".expected.txt")), actualClasses!!.joinToString("\n")) - } - finally { + } finally { runWriteAction { outDir.delete(null) } diff --git a/idea/tests/org/jetbrains/kotlin/idea/decompiler/AbstractInternalCompiledClassesTest.kt b/idea/tests/org/jetbrains/kotlin/idea/decompiler/AbstractInternalCompiledClassesTest.kt index 3beea24a228..d304a832700 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/decompiler/AbstractInternalCompiledClassesTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/decompiler/AbstractInternalCompiledClassesTest.kt @@ -15,26 +15,29 @@ import org.jetbrains.kotlin.name.ClassId import org.junit.Assert abstract class AbstractInternalCompiledClassesTest : KotlinLightCodeInsightFixtureTestCase() { - private fun isFileWithHeader(predicate: (IDEKotlinBinaryClassCache.KotlinBinaryClassHeaderData, ClassId) -> Boolean) : VirtualFile.() -> Boolean = { - val info = IDEKotlinBinaryClassCache.getInstance().getKotlinBinaryClassHeaderData(this) - info != null && predicate(info, info.classId) - } + private fun isFileWithHeader(predicate: (IDEKotlinBinaryClassCache.KotlinBinaryClassHeaderData, ClassId) -> Boolean): VirtualFile.() -> Boolean = + { + val info = IDEKotlinBinaryClassCache.getInstance().getKotlinBinaryClassHeaderData(this) + info != null && predicate(info, info.classId) + } protected fun isSyntheticClass(): VirtualFile.() -> Boolean = - isFileWithHeader { header, _ -> header.kind == KotlinClassHeader.Kind.SYNTHETIC_CLASS } + isFileWithHeader { header, _ -> header.kind == KotlinClassHeader.Kind.SYNTHETIC_CLASS } protected fun doTestNoPsiFilesAreBuiltForLocalClass(): Unit = - doTestNoPsiFilesAreBuiltFor("local", isFileWithHeader { _, classId -> classId.isLocal }) + doTestNoPsiFilesAreBuiltFor("local", isFileWithHeader { _, classId -> classId.isLocal }) protected fun doTestNoPsiFilesAreBuiltForSyntheticClasses(): Unit = - doTestNoPsiFilesAreBuiltFor("synthetic", isSyntheticClass()) + doTestNoPsiFilesAreBuiltFor("synthetic", isSyntheticClass()) protected fun doTestNoPsiFilesAreBuiltFor(fileKind: String, acceptFile: VirtualFile.() -> Boolean) { val project = project doTest(fileKind, acceptFile) { val psiFile = PsiManager.getInstance(project).findFile(this) - Assert.assertNull("PSI files for $fileKind classes should not be build, is was build for: ${this.presentableName}", - psiFile) + Assert.assertNull( + "PSI files for $fileKind classes should not be build, is was build for: ${this.presentableName}", + psiFile + ) } } @@ -47,16 +50,17 @@ abstract class AbstractInternalCompiledClassesTest : KotlinLightCodeInsightFixtu performTest() } } - Assert.assertTrue("Should find at least one file of kind ($fileKind). This assertion can fail in following scenarios:\n" + - "1. Test data is bad and doesn't cover this case.\n2. ABI has changed and test no longer checks anything.", - foundAtLeastOneFile) + Assert.assertTrue( + "Should find at least one file of kind ($fileKind). This assertion can fail in following scenarios:\n" + + "1. Test data is bad and doesn't cover this case.\n2. ABI has changed and test no longer checks anything.", + foundAtLeastOneFile + ) } protected fun VirtualFile.checkRecursively(body: VirtualFile.() -> Unit) { if (!isDirectory) { body() - } - else { + } else { for (file in children!!) { file.checkRecursively(body) } diff --git a/idea/tests/org/jetbrains/kotlin/idea/decompiler/navigation/AbstractNavigateToLibraryTest.kt b/idea/tests/org/jetbrains/kotlin/idea/decompiler/navigation/AbstractNavigateToLibraryTest.kt index c02327633e1..e79810a3550 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/decompiler/navigation/AbstractNavigateToLibraryTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/decompiler/navigation/AbstractNavigateToLibraryTest.kt @@ -68,18 +68,16 @@ class NavigationChecker(val file: PsiFile, val referenceTargetChecker: (PsiEleme return NavigationTestUtils.getNavigateElementsText(file.project, collectInterestingNavigationElements()) } - private fun collectInterestingNavigationElements() = - collectInterestingReferences().map { - val target = it.resolve() - TestCase.assertNotNull(target) - target!!.navigationElement - } + private fun collectInterestingNavigationElements() = collectInterestingReferences().map { + val target = it.resolve() + TestCase.assertNotNull(target) + target!!.navigationElement + } private fun collectInterestingReferences(): Collection { val referenceContainersToReferences = LinkedHashMap() - for (offset in 0..file.textLength - 1) { - val ref = file.findReferenceAt(offset) - val refs = when (ref) { + for (offset in 0 until file.textLength) { + val refs = when (val ref = file.findReferenceAt(offset)) { is KtReference -> listOf(ref) is PsiMultiReference -> ref.references.filterIsInstance() else -> emptyList() diff --git a/idea/tests/org/jetbrains/kotlin/idea/decompiler/navigation/LightNavigateToStdlibSourceTest.kt b/idea/tests/org/jetbrains/kotlin/idea/decompiler/navigation/LightNavigateToStdlibSourceTest.kt index 66ee800a5cc..ba26d2c663a 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/decompiler/navigation/LightNavigateToStdlibSourceTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/decompiler/navigation/LightNavigateToStdlibSourceTest.kt @@ -64,7 +64,8 @@ class LightNavigateToStdlibSourceTest : KotlinLightCodeInsightFixtureTestCase() fun testRefToPrintlnWithJVM() { doTest( "fun foo() { println() }", - "Console.kt") + "Console.kt" + ) } @ProjectDescriptorKind(KOTLIN_JAVASCRIPT) @@ -79,14 +80,16 @@ class LightNavigateToStdlibSourceTest : KotlinLightCodeInsightFixtureTestCase() fun testRefToPrintlnWithJVMAndJS() { doTest( "fun foo() { println() }", - "Console.kt") + "Console.kt" + ) } @ProjectDescriptorKind(KOTLIN_JAVASCRIPT_WITH_ADDITIONAL_JVM_WITH_STDLIB) fun testRefToPrintlnWithJSAndJVM() { doTest( "fun foo() { println() }", - "console.kt") + "console.kt" + ) } override fun getProjectDescriptor() = getProjectDescriptorFromAnnotation() diff --git a/idea/tests/org/jetbrains/kotlin/idea/decompiler/navigation/NavigateFromLibrarySourcesTest.kt b/idea/tests/org/jetbrains/kotlin/idea/decompiler/navigation/NavigateFromLibrarySourcesTest.kt index a5e580fecf4..968e96fc13a 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/decompiler/navigation/NavigateFromLibrarySourcesTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/decompiler/navigation/NavigateFromLibrarySourcesTest.kt @@ -20,7 +20,7 @@ import org.junit.runner.RunWith import kotlin.test.assertTrue @RunWith(JUnit3WithIdeaConfigurationRunner::class) -class NavigateFromLibrarySourcesTest: AbstractNavigateFromLibrarySourcesTest() { +class NavigateFromLibrarySourcesTest : AbstractNavigateFromLibrarySourcesTest() { fun testJdkClass() { checkNavigationFromLibrarySource("Thread", "java.lang.Thread") } diff --git a/idea/tests/org/jetbrains/kotlin/idea/decompiler/navigation/NavigationWithMultipleLibrariesTest.kt b/idea/tests/org/jetbrains/kotlin/idea/decompiler/navigation/NavigationWithMultipleLibrariesTest.kt index 94f061b4232..73524103790 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/decompiler/navigation/NavigationWithMultipleLibrariesTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/decompiler/navigation/NavigationWithMultipleLibrariesTest.kt @@ -31,6 +31,7 @@ import org.jetbrains.kotlin.test.util.projectLibrary import org.junit.Assert import org.junit.runner.RunWith import java.io.File + @RunWith(JUnit3WithIdeaConfigurationRunner::class) class NavigationWithMultipleCustomLibrariesTest : AbstractNavigationToSourceOrDecompiledTest() { @@ -73,7 +74,8 @@ class NavigationWithMultipleRuntimesTest : AbstractNavigationToSourceOrDecompile val modifiableModel = library.modifiableModel modifiableModel.addRoot(jarUrl, OrderRootType.CLASSES) if (withSources) { - val sourcesJar = ForTestCompileRuntime.runtimeSourcesJarForTests().copyTo(File(createTempDirectory(), "$libraryName-sources.jar")) + val sourcesJar = + ForTestCompileRuntime.runtimeSourcesJarForTests().copyTo(File(createTempDirectory(), "$libraryName-sources.jar")) modifiableModel.addRoot(sourcesJar.jarRoot, OrderRootType.SOURCES) } modifiableModel.commit() @@ -82,7 +84,7 @@ class NavigationWithMultipleRuntimesTest : AbstractNavigationToSourceOrDecompile } } -abstract class AbstractNavigationToSourceOrDecompiledTest: AbstractNavigationWithMultipleLibrariesTest() { +abstract class AbstractNavigationToSourceOrDecompiledTest : AbstractNavigationWithMultipleLibrariesTest() { fun doTest(withSources: Boolean, expectedFileName: String) { val srcPath = testDataPath + "src" val moduleA = module("moduleA", srcPath) diff --git a/idea/tests/org/jetbrains/kotlin/idea/decompiler/stubBuilder/AbstractLoadJavaClsStubTest.kt b/idea/tests/org/jetbrains/kotlin/idea/decompiler/stubBuilder/AbstractLoadJavaClsStubTest.kt index 25d5435ff2c..564ba58ec03 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/decompiler/stubBuilder/AbstractLoadJavaClsStubTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/decompiler/stubBuilder/AbstractLoadJavaClsStubTest.kt @@ -9,7 +9,6 @@ import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiManager import com.intellij.testFramework.BinaryLightVirtualFile import com.intellij.testFramework.LightVirtualFile -import com.intellij.testFramework.registerServiceInstance import com.intellij.util.indexing.FileContentImpl import org.jetbrains.kotlin.cli.jvm.compiler.EnvironmentConfigFiles import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment @@ -73,14 +72,19 @@ abstract class AbstractLoadJavaClsStubTest : TestCaseWithTmpdir() { if (stubTreeFromCls != null) { val stubsFromDeserializedDescriptors = run { - val decompiledProvider = KotlinDecompiledFileViewProvider(PsiManager.getInstance(environment.project), file, true) { provider -> - KtClsFile(provider) - } + val decompiledProvider = + KotlinDecompiledFileViewProvider(PsiManager.getInstance(environment.project), file, true) { provider -> + KtClsFile(provider) + } KtFileStubBuilder().buildStubTree(KtClsFile(decompiledProvider)) } - Assert.assertEquals("File: ${file.name}", stubsFromDeserializedDescriptors.serializeToString(), stubTreeFromCls.serializeToString()) + Assert.assertEquals( + "File: ${file.name}", + stubsFromDeserializedDescriptors.serializeToString(), + stubTreeFromCls.serializeToString() + ) } } } diff --git a/idea/tests/org/jetbrains/kotlin/idea/decompiler/stubBuilder/BuiltInDecompilerTest.kt b/idea/tests/org/jetbrains/kotlin/idea/decompiler/stubBuilder/BuiltInDecompilerTest.kt index 94554faabfd..cd21691600a 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/decompiler/stubBuilder/BuiltInDecompilerTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/decompiler/stubBuilder/BuiltInDecompilerTest.kt @@ -58,8 +58,8 @@ class BuiltInDecompilerForWrongAbiVersionTest : AbstractBuiltInDecompilerTest() fun testStubTreesEqualForIncompatibleAbiVersion() { val serializedStub = doTest("test") KotlinTestUtils.assertEqualsToFile( - File(testDataPath + "test.text"), - myFixture.file.text.replace(BuiltInsBinaryVersion.INSTANCE.toString(), "\$VERSION\$") + File(testDataPath + "test.text"), + myFixture.file.text.replace(BuiltInsBinaryVersion.INSTANCE.toString(), "\$VERSION\$") ) KotlinTestUtils.assertEqualsToFile(File(testDataPath + "test.stubs"), serializedStub) } diff --git a/idea/tests/org/jetbrains/kotlin/idea/decompiler/stubBuilder/ClsStubConsistencyTest.kt b/idea/tests/org/jetbrains/kotlin/idea/decompiler/stubBuilder/ClsStubConsistencyTest.kt index 9b3d392d2a1..9223b9c22d4 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/decompiler/stubBuilder/ClsStubConsistencyTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/decompiler/stubBuilder/ClsStubConsistencyTest.kt @@ -24,7 +24,7 @@ import org.junit.runner.RunWith class ClsStubConsistencyTest : KotlinLightCodeInsightFixtureTestCase() { private fun doTest(id: ClassId) { val packageFile = VirtualFileFinder.SERVICE.getInstance(project).findVirtualFileWithHeader(id) - ?: throw AssertionError("File not found for id: $id") + ?: throw AssertionError("File not found for id: $id") val decompiledText = buildDecompiledTextForClassFile(packageFile).text val fileWithDecompiledText = KtPsiFactory(project).createFile(decompiledText) val stubTreeFromDecompiledText = KtFileStubBuilder().buildStubTree(fileWithDecompiledText) diff --git a/idea/tests/org/jetbrains/kotlin/idea/decompiler/textBuilder/AbstractDecompiledTextBaseTest.kt b/idea/tests/org/jetbrains/kotlin/idea/decompiler/textBuilder/AbstractDecompiledTextBaseTest.kt index 16788b2b155..98f147b7a8d 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/decompiler/textBuilder/AbstractDecompiledTextBaseTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/decompiler/textBuilder/AbstractDecompiledTextBaseTest.kt @@ -20,10 +20,10 @@ import org.jetbrains.kotlin.test.KotlinTestUtils import java.io.File abstract class AbstractDecompiledTextBaseTest( - baseDirectory: String, - private val isJsLibrary: Boolean = false, - private val allowKotlinPackage: Boolean = false, - private val withRuntime: Boolean = false + baseDirectory: String, + private val isJsLibrary: Boolean = false, + private val allowKotlinPackage: Boolean = false, + private val withRuntime: Boolean = false ) : KotlinLightCodeInsightFixtureTestCase() { protected val TEST_DATA_PATH: String = PluginTestCaseBase.getTestDataPathBase() + baseDirectory diff --git a/idea/tests/org/jetbrains/kotlin/idea/decompiler/textBuilder/AbstractDecompiledTextTest.kt b/idea/tests/org/jetbrains/kotlin/idea/decompiler/textBuilder/AbstractDecompiledTextTest.kt index 76a370a48f0..ef3038ec7d7 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/decompiler/textBuilder/AbstractDecompiledTextTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/decompiler/textBuilder/AbstractDecompiledTextTest.kt @@ -20,8 +20,8 @@ import org.jetbrains.kotlin.psi.stubs.elements.KtFileStubBuilder import org.junit.Assert import kotlin.test.assertTrue -abstract class AbstractDecompiledTextTest(baseDirectory: String, allowKotlinPackage: Boolean) - : AbstractDecompiledTextBaseTest(baseDirectory, allowKotlinPackage = allowKotlinPackage) { +abstract class AbstractDecompiledTextTest(baseDirectory: String, allowKotlinPackage: Boolean) : + AbstractDecompiledTextBaseTest(baseDirectory, allowKotlinPackage = allowKotlinPackage) { override fun getFileToDecompile(): VirtualFile = getClassFile(TEST_PACKAGE, getTestName(false), module!!) override fun checkStubConsistency(file: VirtualFile, decompiledText: String) { @@ -34,7 +34,7 @@ abstract class AbstractDecompiledTextTest(baseDirectory: String, allowKotlinPack } override fun checkPsiFile(psiFile: PsiFile) = - assertTrue(psiFile is KtClsFile, "Expecting decompiled kotlin file, was: " + psiFile::class.java) + assertTrue(psiFile is KtClsFile, "Expecting decompiled kotlin file, was: " + psiFile::class.java) override fun textToCheck(psiFile: PsiFile) = psiFile.text } @@ -53,11 +53,11 @@ fun findTestLibraryRoot(module: Module): VirtualFile? { } fun getClassFile( - packageName: String, - className: String, - module: Module + packageName: String, + className: String, + module: Module ): VirtualFile { val root = findTestLibraryRoot(module)!! val packageDir = root.findFileByRelativePath(packageName.replace(".", "/"))!! - return packageDir.findChild(className + ".class")!! + return packageDir.findChild("$className.class")!! } \ No newline at end of file diff --git a/idea/tests/org/jetbrains/kotlin/idea/decompiler/textBuilder/DecompiledTextConsistencyTest.kt b/idea/tests/org/jetbrains/kotlin/idea/decompiler/textBuilder/DecompiledTextConsistencyTest.kt index 1e0b6c396eb..7b2fc8f097e 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/decompiler/textBuilder/DecompiledTextConsistencyTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/decompiler/textBuilder/DecompiledTextConsistencyTest.kt @@ -34,20 +34,20 @@ import org.junit.runner.RunWith @RunWith(JUnit3WithIdeaConfigurationRunner::class) class DecompiledTextConsistencyTest : LightCodeInsightFixtureTestCase() { override fun getProjectDescriptor() = - object : KotlinWithJdkAndRuntimeLightProjectDescriptor() { - override fun getSdk() = PluginTestCaseBase.fullJdk() - } + object : KotlinWithJdkAndRuntimeLightProjectDescriptor() { + override fun getSdk() = PluginTestCaseBase.fullJdk() + } fun testConsistency() { for ((packageFacadeFqName, topLevelMembers) in listOf( - FqName("kotlin.collections.CollectionsKt") to "mutableListOf", - FqName("kotlin.collections.TypeAliasesKt") to null + FqName("kotlin.collections.CollectionsKt") to "mutableListOf", + FqName("kotlin.collections.TypeAliasesKt") to null )) { val classId = ClassId.topLevel(packageFacadeFqName) val classFile = VirtualFileFinder.SERVICE.getInstance(project).findVirtualFileWithHeader(classId)!! val module = TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration( - project, listOf(), BindingTraceContext(), KotlinTestUtils.newConfiguration(), ::IDEPackagePartProvider + project, listOf(), BindingTraceContext(), KotlinTestUtils.newConfiguration(), ::IDEPackagePartProvider ).moduleDescriptor val projectBasedText = buildDecompiledTextForClassFile(classFile, ResolverForDecompilerImpl(module)).text @@ -65,17 +65,17 @@ class DecompiledTextConsistencyTest : LightCodeInsightFixtureTestCase() { private inner class ResolverForDecompilerImpl(val module: ModuleDescriptor) : ResolverForDecompiler { override fun resolveTopLevelClass(classId: ClassId): ClassDescriptor? = - module.resolveTopLevelClass(classId.asSingleFqName(), NoLookupLocation.FROM_TEST) + module.resolveTopLevelClass(classId.asSingleFqName(), NoLookupLocation.FROM_TEST) override fun resolveDeclarationsInFacade(facadeFqName: FqName): List = - module.getPackage(facadeFqName.parent()).memberScope.getContributedDescriptors().filter { descriptor -> - (descriptor is MemberDescriptor && descriptor !is ClassDescriptor && isFromFacade(descriptor, facadeFqName)) && - !KotlinBuiltIns.isBuiltIn(descriptor) - }.sortedWith(MemberComparator.INSTANCE) + module.getPackage(facadeFqName.parent()).memberScope.getContributedDescriptors().filter { descriptor -> + (descriptor is MemberDescriptor && descriptor !is ClassDescriptor && isFromFacade(descriptor, facadeFqName)) && + !KotlinBuiltIns.isBuiltIn(descriptor) + }.sortedWith(MemberComparator.INSTANCE) private fun isFromFacade(descriptor: MemberDescriptor, facadeFqName: FqName): Boolean = - descriptor is DeserializedMemberDescriptor && - descriptor.isFromJvmPackagePart() && - facadeFqName == JvmFileClassUtil.getPartFqNameForDeserialized(descriptor) + descriptor is DeserializedMemberDescriptor && descriptor.isFromJvmPackagePart() && facadeFqName == JvmFileClassUtil.getPartFqNameForDeserialized( + descriptor + ) } } diff --git a/idea/tests/org/jetbrains/kotlin/idea/decompiler/textBuilder/DecompiledTextForWrongAbiVersionTest.kt b/idea/tests/org/jetbrains/kotlin/idea/decompiler/textBuilder/DecompiledTextForWrongAbiVersionTest.kt index d75d3460356..f6d03c000d7 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/decompiler/textBuilder/DecompiledTextForWrongAbiVersionTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/decompiler/textBuilder/DecompiledTextForWrongAbiVersionTest.kt @@ -18,6 +18,7 @@ import org.jetbrains.kotlin.test.KotlinTestUtils import org.junit.Assert import org.junit.runner.RunWith import java.io.File + @RunWith(JUnit3WithIdeaConfigurationRunner::class) class DecompiledTextForWrongAbiVersionTest : AbstractInternalCompiledClassesTest() { diff --git a/idea/tests/org/jetbrains/kotlin/idea/editor/TemplateTokenSequenceTest.kt b/idea/tests/org/jetbrains/kotlin/idea/editor/TemplateTokenSequenceTest.kt index 628138f7806..ff2499ecb49 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/editor/TemplateTokenSequenceTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/editor/TemplateTokenSequenceTest.kt @@ -12,32 +12,35 @@ import org.junit.Assert class TemplateTokenSequenceTest : TestCase() { fun doTest(input: String, expected: String) { val output = createTemplateSequenceTokenString(input) - Assert.assertEquals("Unexpected template sequence output for $input: " , expected, output) + Assert.assertEquals("Unexpected template sequence output for $input: ", expected, output) } - fun `test multiple template tokens`(){ - doTest("literal \${a.length} literal \${b.length}", "LITERAL_CHUNK(literal )ENTRY_CHUNK(\${a.length})LITERAL_CHUNK( literal )ENTRY_CHUNK(\${b.length})") + fun `test multiple template tokens`() { + doTest( + "literal \${a.length} literal \${b.length}", + "LITERAL_CHUNK(literal )ENTRY_CHUNK(\${a.length})LITERAL_CHUNK( literal )ENTRY_CHUNK(\${b.length})" + ) } - fun `test broken entry`(){ + fun `test broken entry`() { doTest("literal \${a.lengt \n literal", "LITERAL_CHUNK(literal )LITERAL_CHUNK(\${a.lengt )NEW_LINE()LITERAL_CHUNK( literal)") } - fun `test multiple short entries`(){ + fun `test multiple short entries`() { doTest("literal \$a literal \$a", "LITERAL_CHUNK(literal )ENTRY_CHUNK(\$a)LITERAL_CHUNK( literal )ENTRY_CHUNK(\$a)") } - fun `test leading new lines`(){ + fun `test leading new lines`() { doTest("\n\nliteral", "NEW_LINE()NEW_LINE()LITERAL_CHUNK(literal)") } //last empty line is skipped - fun `test trailing new lines`(){ + fun `test trailing new lines`() { doTest("literal\n\n", "LITERAL_CHUNK(literal)NEW_LINE()NEW_LINE()") } - fun `test multi new lines`(){ + fun `test multi new lines`() { doTest("literal\n\nliteral", "LITERAL_CHUNK(literal)NEW_LINE()NEW_LINE()LITERAL_CHUNK(literal)") } diff --git a/idea/tests/org/jetbrains/kotlin/idea/editor/quickDoc/QuickDocInCompletionTest.kt b/idea/tests/org/jetbrains/kotlin/idea/editor/quickDoc/QuickDocInCompletionTest.kt index 6c9233a6e66..12b294d8acb 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/editor/quickDoc/QuickDocInCompletionTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/editor/quickDoc/QuickDocInCompletionTest.kt @@ -17,7 +17,7 @@ import org.junit.Assert import org.junit.runner.RunWith @RunWith(JUnit3WithIdeaConfigurationRunner::class) -class QuickDocInCompletionTest: KotlinLightCodeInsightFixtureTestCase() { +class QuickDocInCompletionTest : KotlinLightCodeInsightFixtureTestCase() { override fun getTestDataPath(): String { return PluginTestCaseBase.getTestDataPathBase() + "/kdoc/inCompletion/" } @@ -39,6 +39,7 @@ class QuickDocInCompletionTest: KotlinLightCodeInsightFixtureTestCase() { val lookupElements = myFixture.completeBasic() val lookupObject = lookupElements.first().`object` return KotlinQuickDocumentationProvider().getDocumentationElementForLookupItem( - myFixture.psiManager, lookupObject, null) + myFixture.psiManager, lookupObject, null + ) } } \ No newline at end of file diff --git a/idea/tests/org/jetbrains/kotlin/idea/editor/quickDoc/QuickDocInHierarchyTest.kt b/idea/tests/org/jetbrains/kotlin/idea/editor/quickDoc/QuickDocInHierarchyTest.kt index debd94d2d85..9a7ab14a185 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/editor/quickDoc/QuickDocInHierarchyTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/editor/quickDoc/QuickDocInHierarchyTest.kt @@ -38,9 +38,9 @@ class QuickDocInHierarchyTest() : CodeInsightTestCase() { val provider = BrowseHierarchyActionBase.findProvider(LanguageTypeHierarchy.INSTANCE, file, file, context)!! val hierarchyTreeStructure = TypeHierarchyTreeStructure( - project, - provider.getTarget(context) as PsiClass?, - HierarchyBrowserBaseEx.SCOPE_PROJECT + project, + provider.getTarget(context) as PsiClass?, + HierarchyBrowserBaseEx.SCOPE_PROJECT ) val hierarchyNodeDescriptor = hierarchyTreeStructure.baseDescriptor as TypeHierarchyNodeDescriptor val doc = KotlinQuickDocumentationProvider().generateDoc(hierarchyNodeDescriptor.psiClass as PsiElement, null)!! diff --git a/idea/tests/org/jetbrains/kotlin/idea/editor/quickDoc/QuickDocNavigationTest.kt b/idea/tests/org/jetbrains/kotlin/idea/editor/quickDoc/QuickDocNavigationTest.kt index 26b44bbdf4c..6f3b534df2f 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/editor/quickDoc/QuickDocNavigationTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/editor/quickDoc/QuickDocNavigationTest.kt @@ -47,7 +47,8 @@ class QuickDocNavigationTest() : KotlinLightCodeInsightFixtureTestCase() { Assert.assertEquals("reader", (target as KtFunction).name) val secondaryTarget = KotlinQuickDocumentationProvider().getDocumentationElementForLink( - myFixture.psiManager, "InputStream", target) + myFixture.psiManager, "InputStream", target + ) UsefulTestCase.assertInstanceOf(secondaryTarget, PsiClass::class.java) Assert.assertEquals("InputStream", (secondaryTarget as PsiClass).name) } @@ -74,6 +75,7 @@ class QuickDocNavigationTest() : KotlinLightCodeInsightFixtureTestCase() { myFixture.configureByFile(getTestName(true) + ".kt") val source = myFixture.elementAtCaret.getParentOfType(false) return KotlinQuickDocumentationProvider().getDocumentationElementForLink( - myFixture.psiManager, linkText, source) + myFixture.psiManager, linkText, source + ) } } diff --git a/idea/tests/org/jetbrains/kotlin/idea/externalAnnotations/ExternalAnnotationTest.kt b/idea/tests/org/jetbrains/kotlin/idea/externalAnnotations/ExternalAnnotationTest.kt index 98597e2d80c..d47bf27bba9 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/externalAnnotations/ExternalAnnotationTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/externalAnnotations/ExternalAnnotationTest.kt @@ -1,3 +1,8 @@ +/* + * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. + * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. + */ + package org.jetbrains.kotlin.idea.externalAnnotations import com.intellij.openapi.module.Module @@ -7,7 +12,6 @@ import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.psi.codeStyle.JavaCodeStyleSettings import com.intellij.testFramework.LightPlatformTestCase -import com.intellij.testFramework.TestDataPath import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor import org.jetbrains.kotlin.idea.util.application.runWriteAction @@ -68,7 +72,7 @@ class ExternalAnnotationTest : KotlinLightCodeInsightFixtureTestCase() { override fun configureModule(module: Module, model: ModifiableRootModel) { super.configureModule(module, model) model.getModuleExtension(JavaModuleExternalPaths::class.java) - .setExternalAnnotationUrls(arrayOf(VfsUtilCore.pathToUrl(externalAnnotationsPath))) + .setExternalAnnotationUrls(arrayOf(VfsUtilCore.pathToUrl(externalAnnotationsPath))) } } diff --git a/idea/tests/org/jetbrains/kotlin/idea/filters/AbstractKotlinExceptionFilterTest.kt b/idea/tests/org/jetbrains/kotlin/idea/filters/AbstractKotlinExceptionFilterTest.kt index a63fee515f3..436821a535a 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/filters/AbstractKotlinExceptionFilterTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/filters/AbstractKotlinExceptionFilterTest.kt @@ -67,14 +67,15 @@ abstract class AbstractKotlinExceptionFilterTest : KotlinCodeInsightTestCase() { } MockLibraryUtil.compileKotlin(path, File(outDir.path), extraClasspath = *arrayOf(mockLibraryPath)) classLoader = URLClassLoader( - arrayOf(URL(outDir.url + "/"), mockLibraryJar.toURI().toURL()), - ForTestCompileRuntime.runtimeJarClassLoader()) - } - else { + arrayOf(URL(outDir.url + "/"), mockLibraryJar.toURI().toURL()), + ForTestCompileRuntime.runtimeJarClassLoader() + ) + } else { MockLibraryUtil.compileKotlin(path, File(outDir.path)) classLoader = URLClassLoader( - arrayOf(URL(outDir.url + "/")), - ForTestCompileRuntime.runtimeJarClassLoader()) + arrayOf(URL(outDir.url + "/")), + ForTestCompileRuntime.runtimeJarClassLoader() + ) } val stackTraceElement = try { @@ -82,15 +83,15 @@ abstract class AbstractKotlinExceptionFilterTest : KotlinCodeInsightTestCase() { val clazz = classLoader.loadClass(className.asString()) clazz.getMethod("box")?.invoke(null) throw AssertionError("class ${className.asString()} should have box() method and throw exception") - } - catch(e: InvocationTargetException) { + } catch (e: InvocationTargetException) { e.targetException.stackTrace[0] } val filter = KotlinExceptionFilterFactory().create(GlobalSearchScope.allScope(project)) val prefix = InTextDirectivesUtils.findStringWithPrefixes(fileText, "// PREFIX: ") ?: "at" val stackTraceString = stackTraceElement.toString() - var result = filter.applyFilter("$prefix $stackTraceString", 0) ?: throw AssertionError("Couldn't apply filter to $stackTraceElement") + var result = filter.applyFilter("$prefix $stackTraceString", 0) + ?: throw AssertionError("Couldn't apply filter to $stackTraceElement") if (InTextDirectivesUtils.isDirectiveDefined(fileText, "SMAP_APPLIED")) { val fileHyperlinkInfo = result.firstHyperlinkInfo as FileHyperlinkInfo @@ -100,8 +101,8 @@ abstract class AbstractKotlinExceptionFilterTest : KotlinCodeInsightTestCase() { val line = descriptor.line + 1 val newStackString = stackTraceString - .replace(mainFile.name, file.name) - .replace(Regex("\\:\\d+\\)"), ":$line)") + .replace(mainFile.name, file.name) + .replace(Regex(":\\d+\\)"), ":$line)") result = filter.applyFilter("$prefix $newStackString", 0) ?: throw AssertionError("Couldn't apply filter to $stackTraceElement") } @@ -111,8 +112,8 @@ abstract class AbstractKotlinExceptionFilterTest : KotlinCodeInsightTestCase() { val expectedFileName = InTextDirectivesUtils.findStringWithPrefixes(fileText, "// FILE: ")!! val expectedVirtualFile = File(rootDir, expectedFileName).toVirtualFile() - ?: File(MOCK_LIBRARY_SOURCES, expectedFileName).toVirtualFile() - ?: throw AssertionError("Couldn't find file: name = $expectedFileName") + ?: File(MOCK_LIBRARY_SOURCES, expectedFileName).toVirtualFile() + ?: throw AssertionError("Couldn't find file: name = $expectedFileName") val expectedLineNumber = InTextDirectivesUtils.getPrefixedInt(fileText, "// LINE: ")!! @@ -120,6 +121,10 @@ abstract class AbstractKotlinExceptionFilterTest : KotlinCodeInsightTestCase() { val expectedOffset = document.getLineStartOffset(expectedLineNumber - 1) // TODO compare virtual files - assertEquals("Wrong result for line $stackTraceElement", expectedFileName + ":" + expectedOffset, descriptor.file.name + ":" + descriptor.offset) + assertEquals( + "Wrong result for line $stackTraceElement", + "$expectedFileName:$expectedOffset", + descriptor.file.name + ":" + descriptor.offset + ) } } diff --git a/idea/tests/org/jetbrains/kotlin/idea/highlighter/AbstractHighlightExitPointsTest.kt b/idea/tests/org/jetbrains/kotlin/idea/highlighter/AbstractHighlightExitPointsTest.kt index 4bcc2f73316..46382ade8e0 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/highlighter/AbstractHighlightExitPointsTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/highlighter/AbstractHighlightExitPointsTest.kt @@ -18,9 +18,10 @@ abstract class AbstractHighlightExitPointsTest : KotlinLightCodeInsightFixtureTe val text = myFixture.file.text val expectedToBeHighlighted = InTextDirectivesUtils.findLinesWithPrefixesRemoved(text, "//HIGHLIGHTED:") - val searchResultsTextAttributes = EditorColorsManager.getInstance().globalScheme.getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES) + val searchResultsTextAttributes = + EditorColorsManager.getInstance().globalScheme.getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES) val highlighters = myFixture.editor.markupModel.allHighlighters - .filter { it.textAttributes == searchResultsTextAttributes } + .filter { it.textAttributes == searchResultsTextAttributes } val actual = highlighters.map { text.substring(it.startOffset, it.endOffset) } assertEquals(expectedToBeHighlighted, actual) } diff --git a/idea/tests/org/jetbrains/kotlin/idea/highlighter/FormatHtmlUtil.kt b/idea/tests/org/jetbrains/kotlin/idea/highlighter/FormatHtmlUtil.kt index cf3c9ee0725..6ddf84ef935 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/highlighter/FormatHtmlUtil.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/highlighter/FormatHtmlUtil.kt @@ -24,6 +24,6 @@ fun formatHtml(html: String): String { } message = message.replace("
    ", "
    \n").replace(" ", " ") message = message.replace("<", "<`").replace(">", ">") - message = message.lines().map { it.trimEnd() }.filterNot { it.isEmpty () }.joinToString("\n") + message = message.lines().map { it.trimEnd() }.filterNot { it.isEmpty() }.joinToString("\n") return message } diff --git a/idea/tests/org/jetbrains/kotlin/idea/highlighter/Jsr305HighlightingTest.kt b/idea/tests/org/jetbrains/kotlin/idea/highlighter/Jsr305HighlightingTest.kt index bbf24a63bab..1c81b4cd776 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/highlighter/Jsr305HighlightingTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/highlighter/Jsr305HighlightingTest.kt @@ -13,8 +13,8 @@ import org.jetbrains.kotlin.config.KotlinFacetSettingsProvider import org.jetbrains.kotlin.idea.stubs.createFacet import org.jetbrains.kotlin.idea.test.KotlinJdkAndLibraryProjectDescriptor import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase -import org.jetbrains.kotlin.test.JUnit3WithIdeaConfigurationRunner import org.jetbrains.kotlin.platform.jvm.JvmPlatforms +import org.jetbrains.kotlin.test.JUnit3WithIdeaConfigurationRunner import org.jetbrains.kotlin.test.MockLibraryUtil import org.jetbrains.kotlin.utils.ReportLevel import org.junit.runner.RunWith @@ -23,14 +23,16 @@ import org.junit.runner.RunWith class Jsr305HighlightingTest : KotlinLightCodeInsightFixtureTestCase() { override fun getProjectDescriptor(): LightProjectDescriptor { val foreignAnnotationsJar = MockLibraryUtil.compileJvmLibraryToJar("third-party/annotations", "foreign-annotations") - val libraryJar = MockLibraryUtil.compileJvmLibraryToJar("idea/testData/highlighterJsr305/library", "jsr305-library", - extraClasspath = listOf(foreignAnnotationsJar.absolutePath)) + val libraryJar = MockLibraryUtil.compileJvmLibraryToJar( + "idea/testData/highlighterJsr305/library", "jsr305-library", + extraClasspath = listOf(foreignAnnotationsJar.absolutePath) + ) return object : KotlinJdkAndLibraryProjectDescriptor( - listOf( - ForTestCompileRuntime.runtimeJarForTests(), - foreignAnnotationsJar, - libraryJar - ) + listOf( + ForTestCompileRuntime.runtimeJarForTests(), + foreignAnnotationsJar, + libraryJar + ) ) { override fun configureModule(module: Module, model: ModifiableRootModel) { super.configureModule(module, model) @@ -39,7 +41,7 @@ class Jsr305HighlightingTest : KotlinLightCodeInsightFixtureTestCase() { facetSettings?.apply { val jsrStateByTestName = - ReportLevel.findByDescription(getTestName(true)) ?: return@apply + ReportLevel.findByDescription(getTestName(true)) ?: return@apply compilerSettings!!.additionalArguments += " -Xjsr305=${jsrStateByTestName.description}" updateMergedArguments() diff --git a/idea/tests/org/jetbrains/kotlin/idea/highlighter/KotlinHighlightingLexerTest.kt b/idea/tests/org/jetbrains/kotlin/idea/highlighter/KotlinHighlightingLexerTest.kt index 0f59cd86b85..72c9e460e34 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/highlighter/KotlinHighlightingLexerTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/highlighter/KotlinHighlightingLexerTest.kt @@ -14,15 +14,19 @@ class KotlinHighlightingLexerTest : LexerTestCase() { override fun createLexer() = KotlinHighlightingLexer() fun testCharLiteralValidEscape() { - doTest("'\\n'", """CHARACTER_LITERAL (''') + doTest( + "'\\n'", """CHARACTER_LITERAL (''') |VALID_STRING_ESCAPE_TOKEN ('\n') - |CHARACTER_LITERAL (''')""".trimMargin()) + |CHARACTER_LITERAL (''')""".trimMargin() + ) } fun testCharLiteralInvalidEscape() { - doTest("'\\q'", """CHARACTER_LITERAL (''') + doTest( + "'\\q'", """CHARACTER_LITERAL (''') |INVALID_CHARACTER_ESCAPE_TOKEN ('\q') - |CHARACTER_LITERAL (''')""".trimMargin()) + |CHARACTER_LITERAL (''')""".trimMargin() + ) } override fun getDirPath() = throw UnsupportedOperationException() diff --git a/idea/tests/org/jetbrains/kotlin/idea/highlighter/KotlinRainbowHighlighterTest.kt b/idea/tests/org/jetbrains/kotlin/idea/highlighter/KotlinRainbowHighlighterTest.kt index 1d9be6bdc37..01f93075b44 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/highlighter/KotlinRainbowHighlighterTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/highlighter/KotlinRainbowHighlighterTest.kt @@ -15,20 +15,24 @@ class KotlinRainbowHighlighterTest : KotlinLightCodeInsightFixtureTestCase() { override fun getProjectDescriptor() = KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE fun testRainbowSimple() { - checkRainbow(""" + checkRainbow( + """ fun main(args: Array) { val local1 = "" println(local1 + args) } - """) + """ + ) } fun testRainbowNestedIt() { - checkRainbow(""" + checkRainbow( + """ fun main(args: Array) { listOf("abc", "def").filter { it.any { it == 'a' } } } - """) + """ + ) } fun testRainbowNestedVal() { @@ -49,16 +53,19 @@ class KotlinRainbowHighlighterTest : KotlinLightCodeInsightFixtureTestCase() { } fun testAssignmentIt() { - checkRainbow(""" + checkRainbow( + """ val f : (Int) -> Unit = { val t = it it } - """) + """ + ) } fun testRainbowNestedAnonymousFunction() { - checkRainbow(""" + checkRainbow( + """ fun main() { listOf("abc", "def").filter(fun(it): Boolean { return it.any(fun(it): Boolean { @@ -66,43 +73,51 @@ class KotlinRainbowHighlighterTest : KotlinLightCodeInsightFixtureTestCase() { }) }) } - """) + """ + ) } fun testKDoc() { - checkRainbow(""" + checkRainbow( + """ /** * @param args foo */ fun main(args: Array) { } - """) + """ + ) } fun testQualified() { - checkRainbow(""" + checkRainbow( + """ data class Foo(val bar: String) fun main(foo: Foo) { println(foo.bar) System.out.println(foo) } - """) + """ + ) } fun testDestructuring() { - checkRainbow(""" + checkRainbow( + """ fun foo() { val (a, b) = 1 to 2 println(a) println(b) } - """) + """ + ) } fun testInitBlock() { - checkRainbow(""" + checkRainbow( + """ class Some { init { val x = 128 @@ -116,7 +131,8 @@ class KotlinRainbowHighlighterTest : KotlinLightCodeInsightFixtureTestCase() { println(b + x) } } - }""") + }""" + ) } private fun checkRainbow(code: String) { diff --git a/idea/tests/org/jetbrains/kotlin/idea/highlighter/NoErrorsInStdlibTest.kt b/idea/tests/org/jetbrains/kotlin/idea/highlighter/NoErrorsInStdlibTest.kt index 79fcce7bcd3..9bae44bfa04 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/highlighter/NoErrorsInStdlibTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/highlighter/NoErrorsInStdlibTest.kt @@ -43,7 +43,7 @@ class NoErrorsInStdlibTest : KotlinLightCodeInsightFixtureTestCase() { if (errors.isNotEmpty()) { System.err.println("${psiFile.getName()}: ${errors.size} errors") AnalyzerWithCompilerReport.reportDiagnostics( - bindingContext.diagnostics, PrintingMessageCollector(System.err, MessageRenderer.PLAIN_FULL_PATHS, false) + bindingContext.diagnostics, PrintingMessageCollector(System.err, MessageRenderer.PLAIN_FULL_PATHS, false) ) totalErrors += errors.size diff --git a/idea/tests/org/jetbrains/kotlin/idea/inspections/InspectionDescriptionTest.kt b/idea/tests/org/jetbrains/kotlin/idea/inspections/InspectionDescriptionTest.kt index c3b2c695b61..c5357ac2eea 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/inspections/InspectionDescriptionTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/inspections/InspectionDescriptionTest.kt @@ -38,9 +38,11 @@ class InspectionDescriptionTest : LightPlatformTestCase() { val shortName = toolWrapper.shortName val tool = shortNames[shortName] if (tool != null) { - errors.append("Short names must be unique: " + shortName + "\n" + - "inspection: '" + desc(tool) + "\n" + - " and '" + desc(toolWrapper)) + errors.append( + "Short names must be unique: " + shortName + "\n" + + "inspection: '" + desc(tool) + "\n" + + " and '" + desc(toolWrapper) + ) } shortNames.put(shortName, toolWrapper) } @@ -55,13 +57,13 @@ class InspectionDescriptionTest : LightPlatformTestCase() { } private fun loadKotlinInspectionExtensions() = - LocalInspectionEP.LOCAL_INSPECTION.extensions.filter { - it.pluginDescriptor.pluginId == KotlinPluginUtil.KOTLIN_PLUGIN_ID - } + LocalInspectionEP.LOCAL_INSPECTION.extensions.filter { + it.pluginDescriptor.pluginId == KotlinPluginUtil.KOTLIN_PLUGIN_ID + } private fun desc(tool: InspectionToolWrapper): String { return tool.toString() + " ('" + tool.descriptionContextClass + "') " + - "in " + if (tool.extension == null) null else tool.extension.pluginDescriptor + "in " + if (tool.extension == null) null else tool.extension.pluginDescriptor } fun testExtensionPoints() { @@ -76,9 +78,11 @@ class InspectionDescriptionTest : LightPlatformTestCase() { val shortName = ep.getShortName() val ep1 = shortNames[shortName] if (ep1 != null) { - errors.append("Short names must be unique: '" + shortName + "':\n" + - "inspection: '" + ep1.implementationClass + "' in '" + ep1.pluginDescriptor + "'\n" + - "; and '" + ep.implementationClass + "' in '" + ep.pluginDescriptor + "'") + errors.append( + "Short names must be unique: '" + shortName + "':\n" + + "inspection: '" + ep1.implementationClass + "' in '" + ep1.pluginDescriptor + "'\n" + + "; and '" + ep.implementationClass + "' in '" + ep.pluginDescriptor + "'" + ) } shortNames.put(shortName, ep) } @@ -122,18 +126,19 @@ class InspectionDescriptionTest : LightPlatformTestCase() { UsefulTestCase.assertEmpty(failMessages.joinToString("\n"), failMessages) } - private fun checkValue(failMessages: MutableCollection, - toolName: String, - attributeName: String, - xmlValue: String?, - defaultXmlValue: String?, - javaValue: String?) { + private fun checkValue( + failMessages: MutableCollection, + toolName: String, + attributeName: String, + xmlValue: String?, + defaultXmlValue: String?, + javaValue: String? + ) { if (StringUtil.isNotEmpty(xmlValue)) { if (javaValue != xmlValue) { failMessages.add("$toolName: mismatched $attributeName. Xml: $xmlValue; Java: $javaValue") } - } - else if (StringUtil.isNotEmpty(javaValue)) { + } else if (StringUtil.isNotEmpty(javaValue)) { if (javaValue != defaultXmlValue) { failMessages.add("$toolName: $attributeName overridden in wrong way, will work in tests only. Please set appropriate $attributeName value in XML ($javaValue)") } diff --git a/idea/tests/org/jetbrains/kotlin/idea/inspections/InspectionUtils.kt b/idea/tests/org/jetbrains/kotlin/idea/inspections/InspectionUtils.kt index 167b92c89ef..2805fb977e2 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/inspections/InspectionUtils.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/inspections/InspectionUtils.kt @@ -53,7 +53,8 @@ fun runInspection( val localInspection = when (inspection) { is LocalInspectionTool -> inspection - is GlobalInspectionTool -> inspection.sharedLocalInspectionTool ?: error("Global inspection ${inspection::class} without local counterpart") + is GlobalInspectionTool -> inspection.sharedLocalInspectionTool + ?: error("Global inspection ${inspection::class} without local counterpart") else -> error("Unknown class for inspection instance") } diff --git a/idea/tests/org/jetbrains/kotlin/idea/inspections/KotlinCleanupInspectionTest.kt b/idea/tests/org/jetbrains/kotlin/idea/inspections/KotlinCleanupInspectionTest.kt index d497912bc6e..6b7031ec74d 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/inspections/KotlinCleanupInspectionTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/inspections/KotlinCleanupInspectionTest.kt @@ -17,9 +17,8 @@ import org.jetbrains.kotlin.test.JUnit3WithIdeaConfigurationRunner import org.junit.runner.RunWith @RunWith(JUnit3WithIdeaConfigurationRunner::class) -class KotlinCleanupInspectionTest(): KotlinLightCodeInsightFixtureTestCase() { - override fun getTestDataPath(): String - = PluginTestCaseBase.getTestDataPathBase() + "/inspections/cleanup" +class KotlinCleanupInspectionTest() : KotlinLightCodeInsightFixtureTestCase() { + override fun getTestDataPath(): String = PluginTestCaseBase.getTestDataPathBase() + "/inspections/cleanup" override fun getProjectDescriptor(): LightProjectDescriptor = KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE diff --git a/idea/tests/org/jetbrains/kotlin/idea/intentions/AbstractMultiFileIntentionTest.kt b/idea/tests/org/jetbrains/kotlin/idea/intentions/AbstractMultiFileIntentionTest.kt index bb3df17b54c..181215197c6 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/intentions/AbstractMultiFileIntentionTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/intentions/AbstractMultiFileIntentionTest.kt @@ -53,8 +53,10 @@ abstract class AbstractMultiFileIntentionTest : KotlinLightCodeInsightFixtureTes val conflictFile = rootDir.findFileByRelativePath("$mainFilePath.conflicts") try { - Assert.assertTrue("isAvailable() for ${intentionAction::class.java} should return $isApplicableExpected", - isApplicableExpected == intentionAction.isAvailable(project, editor, mainFile)) + Assert.assertTrue( + "isAvailable() for ${intentionAction::class.java} should return $isApplicableExpected", + isApplicableExpected == intentionAction.isAvailable(project, editor, mainFile) + ) config.getNullableString("intentionText")?.let { TestCase.assertEquals("Intention text mismatch", it, intentionAction.text) } @@ -66,12 +68,11 @@ abstract class AbstractMultiFileIntentionTest : KotlinLightCodeInsightFixtureTes } assert(conflictFile == null) { "Conflict file $conflictFile should not exist" } - } - catch (e: CommonRefactoringUtil.RefactoringErrorHintException) { + } catch (e: CommonRefactoringUtil.RefactoringErrorHintException) { val expectedConflicts = LoadTextUtil.loadText(conflictFile!!).toString().trim() assertEquals(expectedConflicts, e.message) } - } + } } protected fun doTest(path: String, action: (VirtualFile) -> Unit) { diff --git a/idea/tests/org/jetbrains/kotlin/idea/internal/AbstractBytecodeToolWindowTest.kt b/idea/tests/org/jetbrains/kotlin/idea/internal/AbstractBytecodeToolWindowTest.kt index 519aa82892c..b3d8d879577 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/internal/AbstractBytecodeToolWindowTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/internal/AbstractBytecodeToolWindowTest.kt @@ -17,7 +17,7 @@ import org.jetbrains.kotlin.test.InTextDirectivesUtils import org.jetbrains.kotlin.test.KotlinTestUtils import java.io.File -abstract class AbstractBytecodeToolWindowTest: KotlinLightCodeInsightFixtureTestCase() { +abstract class AbstractBytecodeToolWindowTest : KotlinLightCodeInsightFixtureTestCase() { override fun getTestDataPath() = KotlinTestUtils.getHomeDirectory() override fun getProjectDescriptor() = KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE diff --git a/idea/tests/org/jetbrains/kotlin/idea/jvm/KotlinJvmDeclarationSearcherTest.kt b/idea/tests/org/jetbrains/kotlin/idea/jvm/KotlinJvmDeclarationSearcherTest.kt index 30d45a8f46d..e5e96b0045a 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/jvm/KotlinJvmDeclarationSearcherTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/jvm/KotlinJvmDeclarationSearcherTest.kt @@ -165,14 +165,11 @@ private fun matchElementsToConditions(elements: Collection, conditions: L while (checkList.isNotEmpty()) { val condition = checkList.removeAt(0) - val matched = elementsToCheck.find { condition(it) } - ?: return MatchResult.UnmatchedCondition(condition) - if (!elementsToCheck.remove(matched)) - throw IllegalStateException("cant remove matched element: $matched") + val matched = elementsToCheck.find { condition(it) } ?: return MatchResult.UnmatchedCondition(condition) + if (!elementsToCheck.remove(matched)) throw IllegalStateException("cant remove matched element: $matched") } - if (elementsToCheck.isEmpty()) - return MatchResult.Matched - return MatchResult.UnmatchedElements(elementsToCheck) + return if (elementsToCheck.isEmpty()) MatchResult.Matched + else MatchResult.UnmatchedElements(elementsToCheck) } private sealed class MatchResult(val succeed: Boolean) { diff --git a/idea/tests/org/jetbrains/kotlin/idea/kdoc/KDocFinderTest.kt b/idea/tests/org/jetbrains/kotlin/idea/kdoc/KDocFinderTest.kt index 66a8c5f7201..93d724f388e 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/kdoc/KDocFinderTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/kdoc/KDocFinderTest.kt @@ -35,7 +35,8 @@ class KDocFinderTest() : LightPlatformCodeInsightFixtureTestCase() { myFixture.configureByFile(getTestName(false) + ".kt") val declaration = (myFixture.file as KtFile).declarations[0] val descriptor = declaration.unsafeResolveToDescriptor() as ClassDescriptor - val overriddenFunctionDescriptor = descriptor.defaultType.memberScope.getContributedFunctions(Name.identifier("xyzzy"), NoLookupLocation.FROM_TEST).single() + val overriddenFunctionDescriptor = + descriptor.defaultType.memberScope.getContributedFunctions(Name.identifier("xyzzy"), NoLookupLocation.FROM_TEST).single() val doc = overriddenFunctionDescriptor.findKDoc() Assert.assertEquals("Doc for method xyzzy", doc!!.getContent()) } @@ -44,7 +45,8 @@ class KDocFinderTest() : LightPlatformCodeInsightFixtureTestCase() { myFixture.configureByFile(getTestName(false) + ".kt") val declaration = (myFixture.file as KtFile).declarations.single { it.name == "Bar" } val descriptor = declaration.unsafeResolveToDescriptor() as ClassDescriptor - val overriddenFunctionDescriptor = descriptor.defaultType.memberScope.getContributedFunctions(Name.identifier("xyzzy"), NoLookupLocation.FROM_TEST).single() + val overriddenFunctionDescriptor = + descriptor.defaultType.memberScope.getContributedFunctions(Name.identifier("xyzzy"), NoLookupLocation.FROM_TEST).single() val doc = overriddenFunctionDescriptor.findKDoc() Assert.assertEquals("Doc for method xyzzy", doc!!.getContent()) } @@ -53,7 +55,8 @@ class KDocFinderTest() : LightPlatformCodeInsightFixtureTestCase() { myFixture.configureByFile(getTestName(false) + ".kt") val declaration = (myFixture.file as KtFile).declarations.single { it.name == "Bar" } val descriptor = declaration.unsafeResolveToDescriptor() as ClassDescriptor - val overriddenFunctionDescriptor = descriptor.defaultType.memberScope.getContributedFunctions(Name.identifier("xyzzy"), NoLookupLocation.FROM_TEST).single() + val overriddenFunctionDescriptor = + descriptor.defaultType.memberScope.getContributedFunctions(Name.identifier("xyzzy"), NoLookupLocation.FROM_TEST).single() val doc = overriddenFunctionDescriptor.findKDoc() Assert.assertEquals("Doc for method xyzzy", doc!!.getContent()) } @@ -62,7 +65,8 @@ class KDocFinderTest() : LightPlatformCodeInsightFixtureTestCase() { myFixture.configureByFile(getTestName(false) + ".kt") val declaration = (myFixture.file as KtFile).declarations.single { it.name == "Foo" } val descriptor = declaration.unsafeResolveToDescriptor() as ClassDescriptor - val propertyDescriptor = descriptor.defaultType.memberScope.getContributedVariables(Name.identifier("xyzzy"), NoLookupLocation.FROM_TEST).single() + val propertyDescriptor = + descriptor.defaultType.memberScope.getContributedVariables(Name.identifier("xyzzy"), NoLookupLocation.FROM_TEST).single() val doc = propertyDescriptor.findKDoc() Assert.assertEquals("Doc for property xyzzy", doc!!.getContent()) } diff --git a/idea/tests/org/jetbrains/kotlin/idea/kdoc/KDocSampleTest.kt b/idea/tests/org/jetbrains/kotlin/idea/kdoc/KDocSampleTest.kt index 205940c4f04..851eb2b918f 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/kdoc/KDocSampleTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/kdoc/KDocSampleTest.kt @@ -105,20 +105,19 @@ class KDocSampleTest : AbstractMultiModuleTest() { if (directives.isEmpty()) { throw FileComparisonFailure( - "'// INFO:' directive was expected", - textData, - textData + "\n\n//INFO: " + info, - testDataFile.absolutePath) - } - else { + "'// INFO:' directive was expected", + textData, + textData + "\n\n//INFO: " + info, + testDataFile.absolutePath + ) + } else { val expectedInfo = directives.joinToString("\n", postfix = "\n") if (expectedInfo.endsWith("...\n")) { if (!info!!.startsWith(expectedInfo.removeSuffix("...\n"))) { wrapToFileComparisonFailure(info, testDataFile.absolutePath, textData) } - } - else if (expectedInfo != info) { + } else if (expectedInfo != info) { wrapToFileComparisonFailure(info!!, testDataFile.absolutePath, textData) } } diff --git a/idea/tests/org/jetbrains/kotlin/idea/lightClasses/LightElementsEqualsTest.kt b/idea/tests/org/jetbrains/kotlin/idea/lightClasses/LightElementsEqualsTest.kt index 656d9bd0045..31865187fe4 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/lightClasses/LightElementsEqualsTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/lightClasses/LightElementsEqualsTest.kt @@ -37,13 +37,13 @@ class LightElementsEqualsTest : KotlinLightCodeInsightFixtureTestCase() { val firstConversion = element.toLightElements() val secondConversion = element.toLightElements() TestCase.assertEquals( - "LightElements from ${element.text} should be equal if they retrieved twice", - firstConversion, secondConversion + "LightElements from ${element.text} should be equal if they retrieved twice", + firstConversion, secondConversion ) for ((e1, e2) in firstConversion zip secondConversion) { TestCase.assertEquals( - "LightElements '$e1'(${e1.javaClass}) and '$e2'(${e2.javaClass}) from `${element.text}` should have equal hashcode as long as they are equal", - e1.hashCode(), e2.hashCode() + "LightElements '$e1'(${e1.javaClass}) and '$e2'(${e2.javaClass}) from `${element.text}` should have equal hashcode as long as they are equal", + e1.hashCode(), e2.hashCode() ) } @@ -80,8 +80,8 @@ class LightElementsEqualsTest : KotlinLightCodeInsightFixtureTestCase() { val directlyFlattenMethods = theAPsiClass.methods.asSequence().flatMap { psiElementsFlatten(it) } val contentOfToLightMethods = (theAPsiClass as KtLightClass).kotlinOrigin!!.declarations.asSequence() - .flatMap { it.toLightMethods().asSequence() } - .flatMap { psiElementsFlatten(it) } + .flatMap { it.toLightMethods().asSequence() } + .flatMap { psiElementsFlatten(it) } for ((e1, e2) in directlyFlattenMethods zip contentOfToLightMethods) { TestCase.assertEquals(e1, e2) TestCase.assertEquals(e1.hashCode(), e2.hashCode()) @@ -91,13 +91,13 @@ class LightElementsEqualsTest : KotlinLightCodeInsightFixtureTestCase() { private fun psiElementsFlatten(psiElement: PsiElement): Sequence { return when (psiElement) { is PsiClass -> sequenceOf(psiElement, psiElement.modifierList).filterNotNull() + - psiElement.methods.asSequence().flatMap { psiElementsFlatten(it) } + - psiElement.fields.asSequence().flatMap { psiElementsFlatten(it) } + psiElement.methods.asSequence().flatMap { psiElementsFlatten(it) } + + psiElement.fields.asSequence().flatMap { psiElementsFlatten(it) } is PsiMethod -> sequenceOf(psiElement, psiElement.parameterList) + psiElementsFlatten(psiElement.parameterList) is PsiParameterList -> sequenceOf(psiElement) + - psiElement.parameters.asSequence().flatMap { psiElementsFlatten(it) } + psiElement.parameters.asSequence().flatMap { psiElementsFlatten(it) } is PsiModifierList -> sequenceOf(psiElement) + - psiElement.annotations.asSequence().flatMap { psiElementsFlatten(it) } + psiElement.annotations.asSequence().flatMap { psiElementsFlatten(it) } is PsiAnnotation -> sequenceOf(psiElement, psiElement.parameterList) + psiElementsFlatten(psiElement.parameterList) else -> sequenceOf(psiElement) diff --git a/idea/tests/org/jetbrains/kotlin/idea/parameterInfo/AbstractParameterInfoTest.kt b/idea/tests/org/jetbrains/kotlin/idea/parameterInfo/AbstractParameterInfoTest.kt index 614b33cabbe..68768ef74dd 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/parameterInfo/AbstractParameterInfoTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/parameterInfo/AbstractParameterInfoTest.kt @@ -64,7 +64,7 @@ abstract class AbstractParameterInfoTest : LightCodeInsightFixtureTestCase() { val handlers = ShowParameterInfoHandler.getHandlers(project, KotlinLanguage.INSTANCE)!! val handler = handlers.firstOrNull { it.findElementForParameterInfo(context) != null } - ?: error("Could not find parameter info handler") + ?: error("Could not find parameter info handler") val mockCreateParameterInfoContext = MockCreateParameterInfoContext(file, myFixture) val parameterOwner = handler.findElementForParameterInfo(mockCreateParameterInfoContext) as PsiElement diff --git a/idea/tests/org/jetbrains/kotlin/idea/parameterInfo/ArgumentNameHintsTest.kt b/idea/tests/org/jetbrains/kotlin/idea/parameterInfo/ArgumentNameHintsTest.kt index 68e17ef7ddb..62c7b6bd56d 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/parameterInfo/ArgumentNameHintsTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/parameterInfo/ArgumentNameHintsTest.kt @@ -20,7 +20,8 @@ class ArgumentNameHintsTest : KotlinLightCodeInsightFixtureTestCase() { } fun `test insert literal arguments`() { - check(""" + check( + """ fun test(file: File) { val testNow = System.currentTimeMillis() > 34000 val times = 1 @@ -35,18 +36,22 @@ class ArgumentNameHintsTest : KotlinLightCodeInsightFixtureTestCase() { fun configure(testNow: Boolean, times: Int, pii: Float, title: String, terminate: Char, file: File) { System.out.println() System.out.println() - }""") + }""" + ) } fun `test do not show for Exceptions`() { - check(""" + check( + """ fun test() { val t = IllegalStateException("crime"); - }""") + }""" + ) } fun `test single varargs hint`() { - check(""" + check( + """ fun main() { testBooleanVarargs(13, false) } @@ -55,11 +60,13 @@ class ArgumentNameHintsTest : KotlinLightCodeInsightFixtureTestCase() { return false } } -""") +""" + ) } fun `test no hint if varargs null`() { - check(""" + check( + """ fun main() { testBooleanVarargs(13) } @@ -67,12 +74,14 @@ class ArgumentNameHintsTest : KotlinLightCodeInsightFixtureTestCase() { fun testBooleanVarargs(test: Int, vararg booleans: Boolean): Boolean { return false } -""") +""" + ) } fun `test multiple vararg hint`() { - check(""" + check( + """ fun main() { testBooleanVarargs(13, false, true, false) } @@ -80,11 +89,13 @@ class ArgumentNameHintsTest : KotlinLightCodeInsightFixtureTestCase() { fun testBooleanVarargs(test: Int, vararg booleans: Boolean): Boolean { return false } -""") +""" + ) } fun `test inline positive and negative numbers`() { - check(""" + check( + """ fun main() { val obj = Any() count(-1, obj); @@ -94,32 +105,38 @@ class ArgumentNameHintsTest : KotlinLightCodeInsightFixtureTestCase() { fun count(test: Int, obj: Any) { } } -""") +""" + ) } fun `test show ambiguous`() { - check(""" + check( + """ fun main() { test(10, x); } fun test(a: Int, bS: String) {} fun test(a: Int, bI: Int) {} -""") +""" + ) } fun `test show non-ambiguous overload`() { - check(""" + check( + """ fun main() { test(10, 15); } fun test() {} fun test(a: Int, bS: String) {} fun test(a: Int, bI: Int) {} -""") +""" + ) } fun `test show ambiguous constructor`() { - check(""" + check( + """ fun main() { X(10, x); } @@ -129,11 +146,13 @@ class X { constructor(a: Int, bI: Int) {} constructor(a: Int, bS: String) {} } -""") +""" + ) } fun `test invoke`() { - check(""" + check( + """ fun main() { val x = X() x(10, x); @@ -143,42 +162,54 @@ class X { class X { operator fun invoke(a: Int, bI: Int) {} } -""") +""" + ) } fun `test annotation`() { - check(""" + check( + """ annotation class ManyArgs(val name: String, val surname: String) @ManyArgs("Ilya", "Sergey") class AnnotatedMuch -""") +""" + ) } fun `test functional type`() { - check(""" + check( + """ fun T.test(block: (T) -> Unit) = block(this) - """) + """ + ) } fun `test functional type with parameter name`() { - check(""" + check( + """ fun T.test(block: (receiver: T, Int) -> Unit) = block(this, 0) - """) + """ + ) } fun `test dynamic`() { - check("""fun foo(x: dynamic) { + check( + """fun foo(x: dynamic) { x.foo("123") - }""") + }""" + ) } fun `test spread`() { - check("""fun foo(vararg x: Int) { + check( + """fun foo(vararg x: Int) { intArrayOf(1, 0).apply { foo(*this) } - }""") + }""" + ) } fun `test line break`() { - check("""fun foo(vararg x: Int) { + check( + """fun foo(vararg x: Int) { foo( 1, 2, diff --git a/idea/tests/org/jetbrains/kotlin/idea/parameterInfo/InlayTypeHintsTest.kt b/idea/tests/org/jetbrains/kotlin/idea/parameterInfo/InlayTypeHintsTest.kt index 7c0dad41520..645cf93393e 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/parameterInfo/InlayTypeHintsTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/parameterInfo/InlayTypeHintsTest.kt @@ -38,7 +38,8 @@ class InlayTypeHintsTest : KotlinLightCodeInsightFixtureTestCase() { } fun testQualifiedReferences() { - checkLocalVariable(""" + checkLocalVariable( + """ package p class A { class B { @@ -57,7 +58,8 @@ class InlayTypeHintsTest : KotlinLightCodeInsightFixtureTestCase() { val v5 = A.F.enumCase val v6 = p.A() } - """) + """ + ) } fun testPropertyType() { diff --git a/idea/tests/org/jetbrains/kotlin/idea/quickfix/AbstractQuickFixTest.kt b/idea/tests/org/jetbrains/kotlin/idea/quickfix/AbstractQuickFixTest.kt index 7026a3bc2d7..a6a1e49dc9d 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/quickfix/AbstractQuickFixTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/quickfix/AbstractQuickFixTest.kt @@ -91,8 +91,8 @@ abstract class AbstractQuickFixTest : KotlinLightCodeInsightFixtureTestCase(), Q private fun getPathAccordingToPackage(name: String, text: String): String { val packagePath = text.lines().let { it.find { it.trim().startsWith("package") } } - ?.removePrefix("package") - ?.trim()?.replace(".", "/") ?: "" + ?.removePrefix("package") + ?.trim()?.replace(".", "/") ?: "" return packagePath + "/" + name } @@ -119,8 +119,7 @@ abstract class AbstractQuickFixTest : KotlinLightCodeInsightFixtureTestCase(), Q fileName = getPathAccordingToPackage(fileName, contents) myFixture.addFileToProject(fileName, contents) myFixture.configureByFile(fileName) - } - else { + } else { myFixture.configureByText(fileName, contents) } @@ -138,22 +137,17 @@ abstract class AbstractQuickFixTest : KotlinLightCodeInsightFixtureTestCase(), Q } UsefulTestCase.assertEmpty(expectedErrorMessage) - } - catch (e: FileComparisonFailure) { + } catch (e: FileComparisonFailure) { throw e - } - catch (e: AssertionError) { + } catch (e: AssertionError) { throw e - } - catch (e: Throwable) { + } catch (e: Throwable) { if (expectedErrorMessage == null) { throw e - } - else { + } else { Assert.assertEquals("Wrong exception message", expectedErrorMessage, e.message) } - } - finally { + } finally { for (fixtureClass in fixtureClasses) { TestFixtureExtension.unloadFixture(fixtureClass) } @@ -195,8 +189,10 @@ abstract class AbstractQuickFixTest : KotlinLightCodeInsightFixtureTestCase(), Q UIUtil.dispatchAllInvocationEvents() if (!shouldBeAvailableAfterExecution()) { - assertNull("Action '${actionHint.expectedText}' is still available after its invocation in test " + fileName, - findActionWithText(actionHint.expectedText)) + assertNull( + "Action '${actionHint.expectedText}' is still available after its invocation in test " + fileName, + findActionWithText(actionHint.expectedText) + ) } myFixture.checkResultByFile(File(fileName).name + ".after") @@ -204,8 +200,7 @@ abstract class AbstractQuickFixTest : KotlinLightCodeInsightFixtureTestCase(), Q if (stubComparisonFailure != null) { throw stubComparisonFailure } - } - else { + } else { assertNull("Action with text ${actionHint.expectedText} is present, but should not", intention) } } @@ -228,7 +223,9 @@ abstract class AbstractQuickFixTest : KotlinLightCodeInsightFixtureTestCase(), Q actions.removeAll { action -> !aClass.isAssignableFrom(action.javaClass) || validActions.contains(action.text) } if (!actions.isEmpty()) { - Assert.fail("Unexpected intention actions present\n " + actions.map { action -> action.javaClass.toString() + " " + action.toString() + "\n" } + Assert.fail("Unexpected intention actions present\n " + actions.map { action -> + action.javaClass.toString() + " " + action.toString() + "\n" + } ) } @@ -237,8 +234,7 @@ abstract class AbstractQuickFixTest : KotlinLightCodeInsightFixtureTestCase(), Q Assert.fail("Unexpected intention action " + action.javaClass + " found") } } - } - else { + } else { // Action shouldn't be found. Check that other actions are expected and thus tested action isn't there under another name. DirectiveBasedActionUtils.checkAvailableActionsAreExpected(myFixture.file, actions) } @@ -277,8 +273,7 @@ abstract class AbstractQuickFixTest : KotlinLightCodeInsightFixtureTestCase(), Q val testDataPath = super.getTestDataPath() try { return File(testDataPath).getCanonicalPath() - } - catch (e: IOException) { + } catch (e: IOException) { e.printStackTrace() return testDataPath } diff --git a/idea/tests/org/jetbrains/kotlin/idea/quickfix/AddRequireModuleTest.kt b/idea/tests/org/jetbrains/kotlin/idea/quickfix/AddRequireModuleTest.kt index d87d6eb0050..c081172ee53 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/quickfix/AddRequireModuleTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/quickfix/AddRequireModuleTest.kt @@ -24,36 +24,39 @@ class KotlinAddRequiredModuleTest : KotlinLightJava9ModulesCodeInsightFixtureTes fun testAddRequiresToModuleInfo() { moduleInfo("module MAIN {}", MAIN) val editedFile = addKotlinFile( - "pkgB/B.kt", - """ + "pkgB/B.kt", + """ package pkgB import pkgA.A class B(a: /*|*/A) """, - MAIN) + MAIN + ) myFixture.configureFromExistingVirtualFile(editedFile) findActionAndExecute(messageM2) assertNoErrors() checkModuleInfo( - """ + """ module MAIN { requires M_TWO; } - """) + """ + ) } fun testNoIdeaModuleDependency() { moduleInfo("module M_THREE {}", M3) val editedFile = addKotlinFile( - "pkgB/B.kt", - """ + "pkgB/B.kt", + """ package pkgB import pkgA.A class B(a: /*|*/A) """, - M3) + M3 + ) myFixture.configureFromExistingVirtualFile(editedFile) val actions = myFixture.filterAvailableIntentions(messageM2) @@ -63,24 +66,26 @@ class KotlinAddRequiredModuleTest : KotlinLightJava9ModulesCodeInsightFixtureTes fun testAddRequiresToInfoForJavaModule() { moduleInfo("module MAIN {}", MAIN) val editedFile = addKotlinFile( - "test.kt", - """ + "test.kt", + """ fun test() { java.util.logging./*|*/FileHandler() // <-- error; "add 'requires java.logging'" quick fix expected } """, - MAIN) + MAIN + ) myFixture.configureFromExistingVirtualFile(editedFile) findActionAndExecute(QuickFixBundle.message("module.info.add.requires.name", "java.logging")) assertNoErrors() checkModuleInfo( - """ + """ module MAIN { requires java.logging; } - """) + """ + ) } private fun assertNoErrors() { diff --git a/idea/tests/org/jetbrains/kotlin/idea/quickfix/CommonIntentionActionsTest.kt b/idea/tests/org/jetbrains/kotlin/idea/quickfix/CommonIntentionActionsTest.kt index 400f4e92059..28219d43a1d 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/quickfix/CommonIntentionActionsTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/quickfix/CommonIntentionActionsTest.kt @@ -59,60 +59,72 @@ class CommonIntentionActionsTest : LightPlatformCodeInsightFixtureTestCase() { override fun getProjectDescriptor() = KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE_FULL_JDK fun testMakeNotFinal() { - myFixture.configureByText("foo.kt", """ + myFixture.configureByText( + "foo.kt", """ class Foo { fun bar(){} } - """) + """ + ) myFixture.launchAction( - createModifierActions( - myFixture.atCaret(), TestModifierRequest(JvmModifier.FINAL, false) - ).findWithText("Make 'bar' open") + createModifierActions( + myFixture.atCaret(), TestModifierRequest(JvmModifier.FINAL, false) + ).findWithText("Make 'bar' open") ) - myFixture.checkResult(""" + myFixture.checkResult( + """ class Foo { open fun bar(){} } - """) + """ + ) } fun testMakePrivate() { - myFixture.configureByText("foo.kt", """ + myFixture.configureByText( + "foo.kt", """ class Foo { fun bar(){} } - """) + """ + ) myFixture.launchAction( - createModifierActions( - myFixture.atCaret(), TestModifierRequest(JvmModifier.PRIVATE, true) - ).findWithText("Make 'Foo' private") + createModifierActions( + myFixture.atCaret(), TestModifierRequest(JvmModifier.PRIVATE, true) + ).findWithText("Make 'Foo' private") ) - myFixture.checkResult(""" + myFixture.checkResult( + """ private class Foo { fun bar(){} } - """) + """ + ) } fun testMakeNotPrivate() { - myFixture.configureByText("foo.kt", """ + myFixture.configureByText( + "foo.kt", """ private class Foo { fun bar(){} } - """.trim()) + """.trim() + ) myFixture.launchAction( - createModifierActions( - myFixture.atCaret(), TestModifierRequest(JvmModifier.PRIVATE, false) - ).findWithText("Remove 'private' modifier") + createModifierActions( + myFixture.atCaret(), TestModifierRequest(JvmModifier.PRIVATE, false) + ).findWithText("Remove 'private' modifier") ) - myFixture.checkResult(""" + myFixture.checkResult( + """ class Foo { fun bar(){} } - """.trim(), true) + """.trim(), true + ) } fun testMakePrivatePublic() { @@ -342,7 +354,9 @@ class CommonIntentionActionsTest : LightPlatformCodeInsightFixtureTestCase() { } private fun annotationsString(findElementByText: KtModifierListOwner) = findElementByText.toLightElements() - .joinToString { elem -> "${elem.javaClass.simpleName} -> ${(elem as PsiModifierListOwner).annotations.mapNotNull { it.qualifiedName }.joinToString()}" } + .joinToString { elem -> + "${elem.javaClass.simpleName} -> ${(elem as PsiModifierListOwner).annotations.mapNotNull { it.qualifiedName }.joinToString()}" + } fun testDontMakePublicPublic() { myFixture.configureByText( @@ -355,192 +369,228 @@ class CommonIntentionActionsTest : LightPlatformCodeInsightFixtureTestCase() { } fun testDontMakeFunInObjectsOpen() { - myFixture.configureByText("foo.kt", """ + myFixture.configureByText( + "foo.kt", """ object Foo { fun bar(){} } - """.trim()) + """.trim() + ) assertEmpty(createModifierActions(myFixture.atCaret(), TestModifierRequest(JvmModifier.FINAL, false))) } fun testAddVoidVoidMethod() { - myFixture.configureByText("foo.kt", """ + myFixture.configureByText( + "foo.kt", """ |class Foo { | fun bar() {} |} - """.trim().trimMargin()) + """.trim().trimMargin() + ) myFixture.launchAction( - createMethodActions( - myFixture.atCaret(), - methodRequest(project, "baz", JvmModifier.PRIVATE, PsiType.VOID) - ).findWithText("Add method 'baz' to 'Foo'") + createMethodActions( + myFixture.atCaret(), + methodRequest(project, "baz", JvmModifier.PRIVATE, PsiType.VOID) + ).findWithText("Add method 'baz' to 'Foo'") ) - myFixture.checkResult(""" + myFixture.checkResult( + """ |class Foo { | fun bar() {} | private fun baz() { | | } |} - """.trim().trimMargin(), true) + """.trim().trimMargin(), true + ) } fun testAddIntIntMethod() { - myFixture.configureByText("foo.kt", """ + myFixture.configureByText( + "foo.kt", """ |class Foo { | fun bar() {} |} - """.trim().trimMargin()) + """.trim().trimMargin() + ) myFixture.launchAction( - createMethodActions( - myFixture.atCaret(), - SimpleMethodRequest(project, - methodName = "baz", - modifiers = listOf(JvmModifier.PUBLIC), - returnType = expectedTypes(PsiType.INT), - parameters = expectedParams(PsiType.INT)) - ).findWithText("Add method 'baz' to 'Foo'") + createMethodActions( + myFixture.atCaret(), + SimpleMethodRequest( + project, + methodName = "baz", + modifiers = listOf(JvmModifier.PUBLIC), + returnType = expectedTypes(PsiType.INT), + parameters = expectedParams(PsiType.INT) + ) + ).findWithText("Add method 'baz' to 'Foo'") ) - myFixture.checkResult(""" + myFixture.checkResult( + """ |class Foo { | fun bar() {} | fun baz(param0: Int): Int { | TODO("Not yet implemented") | } |} - """.trim().trimMargin(), true) + """.trim().trimMargin(), true + ) } fun testAddIntPrimaryConstructor() { - myFixture.configureByText("foo.kt", """ + myFixture.configureByText( + "foo.kt", """ |class Foo { |} - """.trim().trimMargin()) + """.trim().trimMargin() + ) myFixture.launchAction( - createConstructorActions( - myFixture.atCaret(), constructorRequest(project, listOf(pair("param0", PsiType.INT as PsiType))) - ).findWithText("Add primary constructor to 'Foo'") + createConstructorActions( + myFixture.atCaret(), constructorRequest(project, listOf(pair("param0", PsiType.INT as PsiType))) + ).findWithText("Add primary constructor to 'Foo'") ) - myFixture.checkResult(""" + myFixture.checkResult( + """ |class Foo(param0: Int) { |} - """.trim().trimMargin(), true) + """.trim().trimMargin(), true + ) } fun testAddIntSecondaryConstructor() { - myFixture.configureByText("foo.kt", """ + myFixture.configureByText( + "foo.kt", """ |class Foo() { |} - """.trim().trimMargin()) + """.trim().trimMargin() + ) myFixture.launchAction( - createConstructorActions( - myFixture.atCaret(), - constructorRequest(project, listOf(pair("param0", PsiType.INT as PsiType))) - ).findWithText("Add secondary constructor to 'Foo'") + createConstructorActions( + myFixture.atCaret(), + constructorRequest(project, listOf(pair("param0", PsiType.INT as PsiType))) + ).findWithText("Add secondary constructor to 'Foo'") ) - myFixture.checkResult(""" + myFixture.checkResult( + """ |class Foo() { | constructor(param0: Int) { | | } |} - """.trim().trimMargin(), true) + """.trim().trimMargin(), true + ) } fun testChangePrimaryConstructorInt() { - myFixture.configureByText("foo.kt", """ + myFixture.configureByText( + "foo.kt", """ |class Foo() { |} - """.trim().trimMargin()) + """.trim().trimMargin() + ) myFixture.launchAction( - createConstructorActions( - myFixture.atCaret(), - constructorRequest(project, listOf(pair("param0", PsiType.INT as PsiType))) - ).findWithText("Add 'int' as 1st parameter to method 'Foo'") + createConstructorActions( + myFixture.atCaret(), + constructorRequest(project, listOf(pair("param0", PsiType.INT as PsiType))) + ).findWithText("Add 'int' as 1st parameter to method 'Foo'") ) - myFixture.checkResult(""" + myFixture.checkResult( + """ |class Foo(param0: Int) { |} - """.trim().trimMargin(), true) + """.trim().trimMargin(), true + ) } fun testRemoveConstructorParameters() { - myFixture.configureByText("foo.kt", """ + myFixture.configureByText( + "foo.kt", """ |class Foo(i: Int) { |} - """.trim().trimMargin()) + """.trim().trimMargin() + ) myFixture.launchAction( - createConstructorActions( - myFixture.atCaret(), - constructorRequest(project, emptyList()) - ).findWithText("Remove 1st parameter from method 'Foo'") + createConstructorActions( + myFixture.atCaret(), + constructorRequest(project, emptyList()) + ).findWithText("Remove 1st parameter from method 'Foo'") ) - myFixture.checkResult(""" + myFixture.checkResult( + """ |class Foo() { |} - """.trim().trimMargin(), true) + """.trim().trimMargin(), true + ) } fun testAddStringVarProperty() { - myFixture.configureByText("foo.kt", """ + myFixture.configureByText( + "foo.kt", """ |class Foo { | fun bar() {} |} - """.trim().trimMargin()) + """.trim().trimMargin() + ) myFixture.launchAction( createMethodActions( - myFixture.atCaret(), + myFixture.atCaret(), SimpleMethodRequest( project, methodName = "setBaz", modifiers = listOf(JvmModifier.PUBLIC), returnType = expectedTypes(), parameters = expectedParams(PsiType.getTypeByName("java.lang.String", project, project.allScope())) - ) - ).findWithText("Add 'var' property 'baz' to 'Foo'") + ) + ).findWithText("Add 'var' property 'baz' to 'Foo'") ) - myFixture.checkResult(""" + myFixture.checkResult( + """ |class Foo { | var baz: String = TODO("initialize me") | | fun bar() {} |} - """.trim().trimMargin(), true) + """.trim().trimMargin(), true + ) } fun testAddLateInitStringVarProperty() { - myFixture.configureByText("foo.kt", """ + myFixture.configureByText( + "foo.kt", """ |class Foo { | fun bar() {} |} - """.trim().trimMargin()) + """.trim().trimMargin() + ) myFixture.launchAction( createMethodActions( - myFixture.atCaret(), + myFixture.atCaret(), SimpleMethodRequest( project, methodName = "setBaz", modifiers = listOf(JvmModifier.PUBLIC), returnType = expectedTypes(), parameters = expectedParams(PsiType.getTypeByName("java.lang.String", project, project.allScope())) - ) - ).findWithText("Add 'lateinit var' property 'baz' to 'Foo'") + ) + ).findWithText("Add 'lateinit var' property 'baz' to 'Foo'") ) - myFixture.checkResult(""" + myFixture.checkResult( + """ |class Foo { | lateinit var baz: String | | fun bar() {} |} - """.trim().trimMargin(), true) + """.trim().trimMargin(), true + ) } fun testAddStringVarField() { @@ -602,31 +652,35 @@ class CommonIntentionActionsTest : LightPlatformCodeInsightFixtureTestCase() { EP_NAME.extensions.flatMap { it.createAddFieldActions(atCaret, fieldRequest) } fun testAddStringValProperty() { - myFixture.configureByText("foo.kt", """ + myFixture.configureByText( + "foo.kt", """ |class Foo { | fun bar() {} |} - """.trim().trimMargin()) + """.trim().trimMargin() + ) myFixture.launchAction( createMethodActions( - myFixture.atCaret(), + myFixture.atCaret(), SimpleMethodRequest( project, methodName = "getBaz", modifiers = listOf(JvmModifier.PUBLIC), returnType = expectedTypes(PsiType.getTypeByName("java.lang.String", project, project.allScope())), parameters = expectedParams() - ) - ).findWithText("Add 'val' property 'baz' to 'Foo'") + ) + ).findWithText("Add 'val' property 'baz' to 'Foo'") ) - myFixture.checkResult(""" + myFixture.checkResult( + """ |class Foo { | val baz: String = TODO("initialize me") | | fun bar() {} |} - """.trim().trimMargin(), true) + """.trim().trimMargin(), true + ) } @@ -668,8 +722,8 @@ private class TestModifierRequest(private val _modifier: JvmModifier, private va @Suppress("CAST_NEVER_SUCCEEDS") internal fun List.findWithText(text: String): IntentionAction = - this.firstOrNull { it.text == text } ?: - Assert.fail("intention with text '$text' was not found, only ${this.joinToString { "\"${it.text}\"" }} available") as Nothing + this.firstOrNull { it.text == text } + ?: Assert.fail("intention with text '$text' was not found, only ${this.joinToString { "\"${it.text}\"" }} available") as Nothing diff --git a/idea/tests/org/jetbrains/kotlin/idea/refactoring/AbstractMemberPullPushTest.kt b/idea/tests/org/jetbrains/kotlin/idea/refactoring/AbstractMemberPullPushTest.kt index a090ed259eb..69cf503f057 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/refactoring/AbstractMemberPullPushTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/refactoring/AbstractMemberPullPushTest.kt @@ -54,8 +54,7 @@ abstract class AbstractMemberPullPushTest : KotlinLightCodeInsightFixtureTestCas for ((extraPsiFile, extraFile) in extraFilesToPsi) { KotlinTestUtils.assertEqualsToFile(File("${extraFile.path}.after"), extraPsiFile.text) } - } - catch(e: Exception) { + } catch (e: Exception) { val message = when (e) { is BaseRefactoringProcessor.ConflictsInTestsException -> e.messages.sorted().joinToString("\n") is CommonRefactoringUtil.RefactoringErrorHintException -> e.message!! @@ -69,8 +68,10 @@ abstract class AbstractMemberPullPushTest : KotlinLightCodeInsightFixtureTestCas internal fun markMembersInfo(file: PsiFile) { for ((element, info) in file.findElementsByCommentPrefix("// INFO: ")) { val parsedInfo = JsonParser().parse(info).asJsonObject - element.elementInfo = ElementInfo(parsedInfo["checked"]?.asBoolean ?: false, - parsedInfo["toAbstract"]?.asBoolean ?: false) + element.elementInfo = ElementInfo( + parsedInfo["checked"]?.asBoolean ?: false, + parsedInfo["toAbstract"]?.asBoolean ?: false + ) } } diff --git a/idea/tests/org/jetbrains/kotlin/idea/refactoring/AbstractMultifileRefactoringTest.kt b/idea/tests/org/jetbrains/kotlin/idea/refactoring/AbstractMultifileRefactoringTest.kt index 5e3255cb3ff..3110a34c9ee 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/refactoring/AbstractMultifileRefactoringTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/refactoring/AbstractMultifileRefactoringTest.kt @@ -59,7 +59,7 @@ abstract class AbstractMultifileRefactoringTest : KotlinLightCodeInsightFixtureT } } - protected fun getTestDirName(lowercaseFirstLetter : Boolean) : String { + protected fun getTestDirName(lowercaseFirstLetter: Boolean): String { val testName = getTestName(lowercaseFirstLetter) val endIndex = testName.lastIndexOf('_') if (endIndex < 0) return testName @@ -86,11 +86,11 @@ abstract class AbstractMultifileRefactoringTest : KotlinLightCodeInsightFixtureT } fun runRefactoringTest( - path: String, - config: JsonObject, - rootDir: VirtualFile, - project: Project, - action: AbstractMultifileRefactoringTest.RefactoringAction + path: String, + config: JsonObject, + rootDir: VirtualFile, + project: Project, + action: AbstractMultifileRefactoringTest.RefactoringAction ) { val testDir = path.substring(0, path.lastIndexOf("/")) val mainFilePath = config.getNullableString("mainFile") ?: config.getAsJsonArray("filesToMove").first().asString @@ -105,9 +105,9 @@ fun runRefactoringTest( val caretOffsets = document.extractMultipleMarkerOffsets(project) val elementsAtCaret = caretOffsets.map { TargetElementUtil.getInstance().findTargetElement( - editor, - TargetElementUtil.REFERENCED_ELEMENT_ACCEPTED or TargetElementUtil.ELEMENT_NAME_ACCEPTED, - it + editor, + TargetElementUtil.REFERENCED_ELEMENT_ACCEPTED or TargetElementUtil.ELEMENT_NAME_ACCEPTED, + it )!! } @@ -115,16 +115,14 @@ fun runRefactoringTest( action.runRefactoring(rootDir, mainPsiFile, elementsAtCaret, config) assert(!conflictFile.exists()) - } - catch(e: BaseRefactoringProcessor.ConflictsInTestsException) { + } catch (e: BaseRefactoringProcessor.ConflictsInTestsException) { KotlinTestUtils.assertEqualsToFile(conflictFile, e.messages.distinct().sorted().joinToString("\n")) BaseRefactoringProcessor.ConflictsInTestsException.withIgnoredConflicts { // Run refactoring again with ConflictsInTestsException suppressed action.runRefactoring(rootDir, mainPsiFile, elementsAtCaret, config) } - } - finally { + } finally { EditorFactory.getInstance()!!.releaseEditor(editor) } } \ No newline at end of file diff --git a/idea/tests/org/jetbrains/kotlin/idea/refactoring/AbstractNameSuggestionProviderTest.kt b/idea/tests/org/jetbrains/kotlin/idea/refactoring/AbstractNameSuggestionProviderTest.kt index 9fce04f27ee..93a8535eea3 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/refactoring/AbstractNameSuggestionProviderTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/refactoring/AbstractNameSuggestionProviderTest.kt @@ -29,8 +29,8 @@ abstract class AbstractNameSuggestionProviderTest : KotlinLightCodeInsightFixtur protected fun doTest(path: String) { val file = myFixture.configureByFile(fileName()) val targetElement = TargetElementUtil.findTargetElement( - myFixture.editor, - TargetElementUtil.ELEMENT_NAME_ACCEPTED or TargetElementUtil.REFERENCED_ELEMENT_ACCEPTED + myFixture.editor, + TargetElementUtil.ELEMENT_NAME_ACCEPTED or TargetElementUtil.REFERENCED_ELEMENT_ACCEPTED )!! val expectedNames = InTextDirectivesUtils.findListWithPrefixes(file.text, "// SUGGESTED_NAMES: ") val actualNames = getSuggestNames(targetElement) diff --git a/idea/tests/org/jetbrains/kotlin/idea/refactoring/InplaceRenameTest.kt b/idea/tests/org/jetbrains/kotlin/idea/refactoring/InplaceRenameTest.kt index 643ff9a9aaa..54c73e1801e 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/refactoring/InplaceRenameTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/refactoring/InplaceRenameTest.kt @@ -191,8 +191,10 @@ class InplaceRenameTest : LightPlatformCodeInsightTestCase() { val element = file.findElementForRename(editor.caretModel.offset)!! assertNotNull(element) - val dataContext = SimpleDataContext.getSimpleContext(CommonDataKeys.PSI_ELEMENT.name, element, - getCurrentEditorDataContext()) + val dataContext = SimpleDataContext.getSimpleContext( + CommonDataKeys.PSI_ELEMENT.name, element, + getCurrentEditorDataContext() + ) val handler = RenameKotlinImplicitLambdaParameter() assertTrue(handler.isRenaming(dataContext), "In-place rename not allowed for " + element) @@ -241,8 +243,7 @@ class InplaceRenameTest : LightPlatformCodeInsightTestCase() { if (newName == null) { assertFalse(handler.isRenaming(dataContext), "In-place rename is allowed for " + element) - } - else { + } else { try { assertTrue(handler.isRenaming(dataContext), "In-place rename not allowed for " + element) CodeInsightTestUtil.doInlineRename(handler, newName, getEditor(), element) diff --git a/idea/tests/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinChangeSignatureTest.kt b/idea/tests/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinChangeSignatureTest.kt index 61809082095..892710bb7c9 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinChangeSignatureTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinChangeSignatureTest.kt @@ -50,6 +50,7 @@ import org.jetbrains.kotlin.utils.sure import org.junit.runner.RunWith import java.io.File import java.util.* + @RunWith(JUnit3WithIdeaConfigurationRunner::class) class KotlinChangeSignatureTest : KotlinLightCodeInsightFixtureTestCase() { companion object { @@ -102,13 +103,13 @@ class KotlinChangeSignatureTest : KotlinLightCodeInsightFixtureTestCase() { val element = (KotlinChangeSignatureHandler().findTargetMember(file, editor) as KtElement?).sure { "Target element is null" } val context = file - .findElementAt(editor.caretModel.offset) - ?.getNonStrictParentOfType() - .sure { "Context element is null" } + .findElementAt(editor.caretModel.offset) + ?.getNonStrictParentOfType() + .sure { "Context element is null" } val bindingContext = element.analyze(BodyResolveMode.FULL) val callableDescriptor = KotlinChangeSignatureHandler - .findDescriptor(element, project, editor, bindingContext) - .sure { "Target descriptor is null" } + .findDescriptor(element, project, editor, bindingContext) + .sure { "Target descriptor is null" } return createChangeInfo(project, callableDescriptor, KotlinChangeSignatureConfiguration.Empty, context)!! } @@ -122,8 +123,7 @@ class KotlinChangeSignatureTest : KotlinLightCodeInsightFixtureTestCase() { try { testAction() TestCase.fail("No conflicts found") - } - catch (e: Throwable) { + } catch (e: Throwable) { val message = when { e is BaseRefactoringProcessor.ConflictsInTestsException -> StringUtil.join(e.messages.sorted(), "\n") e is CommonRefactoringUtil.RefactoringErrorHintException -> e.message @@ -141,8 +141,7 @@ class KotlinChangeSignatureTest : KotlinLightCodeInsightFixtureTestCase() { try { doTest(configure) TestCase.fail("No conflicts found") - } - catch (e: RuntimeException) { + } catch (e: RuntimeException) { if ((e.message ?: "").contains("Cannot modify file")) return val message = when { @@ -175,25 +174,25 @@ class KotlinChangeSignatureTest : KotlinLightCodeInsightFixtureTestCase() { init { method.parameterList.parameters - .withIndex() - .mapTo(newParameters) { - val (i, param) = it - ParameterInfoImpl(i, param.name, param.type) - } + .withIndex() + .mapTo(newParameters) { + val (i, param) = it + ParameterInfoImpl(i, param.name, param.type) + } } fun createProcessor(): ChangeSignatureProcessor { return ChangeSignatureProcessor( - project, - method, - false, - VisibilityUtil.getVisibilityModifier(method.modifierList), - newName, - CanonicalTypes.createTypeWrapper(newReturnType), - newParameters.toTypedArray(), - arrayOf(), - parameterPropagationTargets, - emptySet() + project, + method, + false, + VisibilityUtil.getVisibilityModifier(method.modifierList), + newName, + CanonicalTypes.createTypeWrapper(newReturnType), + newParameters.toTypedArray(), + arrayOf(), + parameterPropagationTargets, + emptySet() ) } } @@ -204,10 +203,7 @@ class KotlinChangeSignatureTest : KotlinLightCodeInsightFixtureTestCase() { val targetElement = TargetElementUtil.findTargetElement(editor, ELEMENT_NAME_ACCEPTED or REFERENCED_ELEMENT_ACCEPTED) val targetMethod = (targetElement as? PsiMethod).sure { " is not on method name" } - JavaRefactoringConfiguration(targetMethod) - .apply { configure() } - .createProcessor() - .run() + JavaRefactoringConfiguration(targetMethod).apply { configure() }.createProcessor().run() compareEditorsWithExpectedData() } @@ -221,8 +217,7 @@ class KotlinChangeSignatureTest : KotlinLightCodeInsightFixtureTestCase() { val afterFilePath = file.replace("Before.", "After.") try { myFixture.checkResultByFile(file, afterFilePath, true) - } - catch (e: ComparisonFailure) { + } catch (e: ComparisonFailure) { KotlinTestUtils.assertEqualsToFile(File(testDataPath + afterFilePath), psiFile.text) } @@ -269,11 +264,11 @@ class KotlinChangeSignatureTest : KotlinLightCodeInsightFixtureTestCase() { newVisibility = Visibilities.PROTECTED val newParameter = KotlinParameterInfo( - callableDescriptor = originalBaseFunctionDescriptor, - name = "x", - originalTypeInfo = KotlinTypeInfo(false, BUILT_INS.anyType), - defaultValueForCall = KtPsiFactory(project).createExpression("12"), - valOrVar = KotlinValVar.Val + callableDescriptor = originalBaseFunctionDescriptor, + name = "x", + originalTypeInfo = KotlinTypeInfo(false, BUILT_INS.anyType), + defaultValueForCall = KtPsiFactory(project).createExpression("12"), + valOrVar = KotlinValVar.Val ) addParameter(newParameter) } @@ -346,12 +341,16 @@ class KotlinChangeSignatureTest : KotlinLightCodeInsightFixtureTestCase() { val newParameters = newParameters setNewParameter(2, newParameters[1]) setNewParameter(1, newParameters[0]) - setNewParameter(0, KotlinParameterInfo(originalBaseFunctionDescriptor, - -1, - "x0", - KotlinTypeInfo(false, BUILT_INS.nullableAnyType), - null, - defaultValueForCall)) + setNewParameter( + 0, KotlinParameterInfo( + originalBaseFunctionDescriptor, + -1, + "x0", + KotlinTypeInfo(false, BUILT_INS.nullableAnyType), + null, + defaultValueForCall + ) + ) } fun testFakeOverride() = doTest { @@ -397,12 +396,16 @@ class KotlinChangeSignatureTest : KotlinLightCodeInsightFixtureTestCase() { fun testEnumEntriesWithoutSuperCalls() = doTest { val defaultValueForCall = KtPsiFactory(project).createExpression("1") - addParameter(KotlinParameterInfo(originalBaseFunctionDescriptor, - -1, - "n", - KotlinTypeInfo(false, BUILT_INS.intType), - null, - defaultValueForCall)) + addParameter( + KotlinParameterInfo( + originalBaseFunctionDescriptor, + -1, + "n", + KotlinTypeInfo(false, BUILT_INS.intType), + null, + defaultValueForCall + ) + ) } fun testParameterChangeInOverrides() = doTest { @@ -412,30 +415,42 @@ class KotlinChangeSignatureTest : KotlinLightCodeInsightFixtureTestCase() { fun testConstructorJavaUsages() = doTest { val defaultValueForCall = KtPsiFactory(project).createExpression("\"abc\"") - addParameter(KotlinParameterInfo(originalBaseFunctionDescriptor, - -1, - "s", - KotlinTypeInfo(false, BUILT_INS.stringType), - null, - defaultValueForCall)) + addParameter( + KotlinParameterInfo( + originalBaseFunctionDescriptor, + -1, + "s", + KotlinTypeInfo(false, BUILT_INS.stringType), + null, + defaultValueForCall + ) + ) } fun testFunctionJavaUsagesAndOverridesAddParam() = doTest { val psiFactory = KtPsiFactory(project) val defaultValueForCall1 = psiFactory.createExpression("\"abc\"") val defaultValueForCall2 = psiFactory.createExpression("\"def\"") - addParameter(KotlinParameterInfo(originalBaseFunctionDescriptor, - -1, - "s", - KotlinTypeInfo(false, BUILT_INS.stringType), - null, - defaultValueForCall1)) - addParameter(KotlinParameterInfo(originalBaseFunctionDescriptor, - -1, - "o", - KotlinTypeInfo(false, BUILT_INS.nullableAnyType), - null, - defaultValueForCall2)) + addParameter( + KotlinParameterInfo( + originalBaseFunctionDescriptor, + -1, + "s", + KotlinTypeInfo(false, BUILT_INS.stringType), + null, + defaultValueForCall1 + ) + ) + addParameter( + KotlinParameterInfo( + originalBaseFunctionDescriptor, + -1, + "o", + KotlinTypeInfo(false, BUILT_INS.nullableAnyType), + null, + defaultValueForCall2 + ) + ) } fun testFunctionJavaUsagesAndOverridesChangeNullability() = doTest { @@ -524,26 +539,53 @@ class KotlinChangeSignatureTest : KotlinLightCodeInsightFixtureTestCase() { fun testAddNewReceiver() = doTest { val defaultValueForCall = KtPsiFactory(project).createExpression("X(0)") - receiverParameterInfo = KotlinParameterInfo(originalBaseFunctionDescriptor, -1, "_", KotlinTypeInfo(false, BUILT_INS.anyType), null, defaultValueForCall) - .apply { currentTypeInfo = KotlinTypeInfo(false, null, "X") } + receiverParameterInfo = KotlinParameterInfo( + originalBaseFunctionDescriptor, + -1, + "_", + KotlinTypeInfo(false, BUILT_INS.anyType), + null, + defaultValueForCall + ) + .apply { currentTypeInfo = KotlinTypeInfo(false, null, "X") } } fun testAddNewReceiverForMember() = doTest { val defaultValueForCall = KtPsiFactory(project).createExpression("X(0)") - receiverParameterInfo = KotlinParameterInfo(originalBaseFunctionDescriptor, -1, "_", KotlinTypeInfo(false, BUILT_INS.anyType), null, defaultValueForCall) - .apply { currentTypeInfo = KotlinTypeInfo(false, null, "X") } + receiverParameterInfo = KotlinParameterInfo( + originalBaseFunctionDescriptor, + -1, + "_", + KotlinTypeInfo(false, BUILT_INS.anyType), + null, + defaultValueForCall + ) + .apply { currentTypeInfo = KotlinTypeInfo(false, null, "X") } } fun testAddNewReceiverForMemberConflict() = doTestConflict { val defaultValueForCall = KtPsiFactory(project).createExpression("X(0)") - receiverParameterInfo = KotlinParameterInfo(originalBaseFunctionDescriptor, -1, "_", KotlinTypeInfo(false, BUILT_INS.anyType), null, defaultValueForCall) - .apply { currentTypeInfo = KotlinTypeInfo(false, null, "X") } + receiverParameterInfo = KotlinParameterInfo( + originalBaseFunctionDescriptor, + -1, + "_", + KotlinTypeInfo(false, BUILT_INS.anyType), + null, + defaultValueForCall + ) + .apply { currentTypeInfo = KotlinTypeInfo(false, null, "X") } } fun testAddNewReceiverConflict() = doTestConflict { val defaultValueForCall = KtPsiFactory(project).createExpression("X(0)") - receiverParameterInfo = KotlinParameterInfo(originalBaseFunctionDescriptor, -1, "_", KotlinTypeInfo(false, BUILT_INS.anyType), null, defaultValueForCall) - .apply { currentTypeInfo = KotlinTypeInfo(false, null, "X") } + receiverParameterInfo = KotlinParameterInfo( + originalBaseFunctionDescriptor, + -1, + "_", + KotlinTypeInfo(false, BUILT_INS.anyType), + null, + defaultValueForCall + ).apply { currentTypeInfo = KotlinTypeInfo(false, null, "X") } } fun testRemoveReceiver() = doTest { removeParameter(0) } @@ -599,36 +641,90 @@ class KotlinChangeSignatureTest : KotlinLightCodeInsightFixtureTestCase() { fun testSecondaryConstructor() = doTest { val defaultValueForCall = KtPsiFactory(project).createExpression("\"foo\"") - addParameter(KotlinParameterInfo(originalBaseFunctionDescriptor, -1, "s", KotlinTypeInfo(false, BUILT_INS.stringType), null, defaultValueForCall)) + addParameter( + KotlinParameterInfo( + originalBaseFunctionDescriptor, + -1, + "s", + KotlinTypeInfo(false, BUILT_INS.stringType), + null, + defaultValueForCall + ) + ) } fun testJavaConstructorInDelegationCall() = doJavaTest { newParameters.add(ParameterInfoImpl(-1, "s", stringPsiType, "\"foo\"")) } fun testPrimaryConstructorByThisRef() = doTest { val defaultValueForCall = KtPsiFactory(project).createExpression("\"foo\"") - addParameter(KotlinParameterInfo(originalBaseFunctionDescriptor, -1, "s", KotlinTypeInfo(false, BUILT_INS.stringType), null, defaultValueForCall)) + addParameter( + KotlinParameterInfo( + originalBaseFunctionDescriptor, + -1, + "s", + KotlinTypeInfo(false, BUILT_INS.stringType), + null, + defaultValueForCall + ) + ) } fun testPrimaryConstructorBySuperRef() = doTest { val defaultValueForCall = KtPsiFactory(project).createExpression("\"foo\"") - addParameter(KotlinParameterInfo(originalBaseFunctionDescriptor, -1, "s", KotlinTypeInfo(false, BUILT_INS.stringType), null, defaultValueForCall)) + addParameter( + KotlinParameterInfo( + originalBaseFunctionDescriptor, + -1, + "s", + KotlinTypeInfo(false, BUILT_INS.stringType), + null, + defaultValueForCall + ) + ) } fun testSecondaryConstructorByThisRef() = doTest { val defaultValueForCall = KtPsiFactory(project).createExpression("\"foo\"") - addParameter(KotlinParameterInfo(originalBaseFunctionDescriptor, -1, "s", KotlinTypeInfo(false, BUILT_INS.stringType), null, defaultValueForCall)) + addParameter( + KotlinParameterInfo( + originalBaseFunctionDescriptor, + -1, + "s", + KotlinTypeInfo(false, BUILT_INS.stringType), + null, + defaultValueForCall + ) + ) } fun testSecondaryConstructorBySuperRef() = doTest { val defaultValueForCall = KtPsiFactory(project).createExpression("\"foo\"") - addParameter(KotlinParameterInfo(methodDescriptor.baseDescriptor, -1, "s", KotlinTypeInfo(false, BUILT_INS.stringType), null, defaultValueForCall)) + addParameter( + KotlinParameterInfo( + methodDescriptor.baseDescriptor, + -1, + "s", + KotlinTypeInfo(false, BUILT_INS.stringType), + null, + defaultValueForCall + ) + ) } fun testJavaConstructorBySuperRef() = doJavaTest { newParameters.add(ParameterInfoImpl(-1, "s", stringPsiType, "\"foo\"")) } fun testNoConflictWithReceiverName() = doTest { val defaultValueForCall = KtPsiFactory(project).createExpression("0") - addParameter(KotlinParameterInfo(originalBaseFunctionDescriptor, -1, "i", KotlinTypeInfo(false, BUILT_INS.intType), null, defaultValueForCall)) + addParameter( + KotlinParameterInfo( + originalBaseFunctionDescriptor, + -1, + "i", + KotlinTypeInfo(false, BUILT_INS.intType), + null, + defaultValueForCall + ) + ) } fun testRemoveParameterBeforeLambda() = doTest { removeParameter(1) } @@ -666,7 +762,16 @@ class KotlinChangeSignatureTest : KotlinLightCodeInsightFixtureTestCase() { fun testPrimaryConstructorByRef() = doTest { val defaultValueForCall = KtPsiFactory(project).createExpression("1") - addParameter(KotlinParameterInfo(originalBaseFunctionDescriptor, -1, "n", KotlinTypeInfo(false, BUILT_INS.intType), null, defaultValueForCall)) + addParameter( + KotlinParameterInfo( + originalBaseFunctionDescriptor, + -1, + "n", + KotlinTypeInfo(false, BUILT_INS.intType), + null, + defaultValueForCall + ) + ) } fun testReceiverToParameterExplicitReceiver() = doTest { receiverParameterInfo = null } @@ -696,22 +801,26 @@ class KotlinChangeSignatureTest : KotlinLightCodeInsightFixtureTestCase() { fun testAddPropertyReceiverConflict() = doTestConflict { val defaultValueForCall = KtPsiFactory(project).createExpression("\"\"") - receiverParameterInfo = KotlinParameterInfo(originalBaseFunctionDescriptor, - -1, - "receiver", - KotlinTypeInfo(false, BUILT_INS.stringType), - null, - defaultValueForCall) + receiverParameterInfo = KotlinParameterInfo( + originalBaseFunctionDescriptor, + -1, + "receiver", + KotlinTypeInfo(false, BUILT_INS.stringType), + null, + defaultValueForCall + ) } fun testAddPropertyReceiver() = doTest { val defaultValueForCall = KtPsiFactory(project).createExpression("\"\"") - receiverParameterInfo = KotlinParameterInfo(originalBaseFunctionDescriptor, - -1, - "receiver", - KotlinTypeInfo(false, BUILT_INS.stringType), - null, - defaultValueForCall) + receiverParameterInfo = KotlinParameterInfo( + originalBaseFunctionDescriptor, + -1, + "receiver", + KotlinTypeInfo(false, BUILT_INS.stringType), + null, + defaultValueForCall + ) } fun testChangePropertyReceiver() = doTest { receiverParameterInfo!!.currentTypeInfo = KotlinTypeInfo(false, BUILT_INS.intType) } @@ -720,11 +829,18 @@ class KotlinChangeSignatureTest : KotlinLightCodeInsightFixtureTestCase() { fun testAddTopLevelPropertyReceiver() = doTest { val defaultValueForCall = KtPsiFactory(project).createExpression("A()") - receiverParameterInfo = KotlinParameterInfo(originalBaseFunctionDescriptor, -1, "receiver", KotlinTypeInfo(false), null, defaultValueForCall) - .apply { currentTypeInfo = KotlinTypeInfo(false, null, "test.A") } + receiverParameterInfo = KotlinParameterInfo( + originalBaseFunctionDescriptor, + -1, + "receiver", + KotlinTypeInfo(false), + null, + defaultValueForCall + ).apply { currentTypeInfo = KotlinTypeInfo(false, null, "test.A") } } - fun testChangeTopLevelPropertyReceiver() = doTest { receiverParameterInfo!!.currentTypeInfo = KotlinTypeInfo(false, BUILT_INS.stringType) } + fun testChangeTopLevelPropertyReceiver() = + doTest { receiverParameterInfo!!.currentTypeInfo = KotlinTypeInfo(false, BUILT_INS.stringType) } fun testRemoveTopLevelPropertyReceiver() = doTest { receiverParameterInfo = null } @@ -737,13 +853,25 @@ class KotlinChangeSignatureTest : KotlinLightCodeInsightFixtureTestCase() { val psiFactory = KtPsiFactory(project) val defaultValueForCall1 = psiFactory.createExpression("1") - val newParameter1 = KotlinParameterInfo(originalBaseFunctionDescriptor, -1, "n", KotlinTypeInfo(false), null, defaultValueForCall1) - .apply { currentTypeInfo = KotlinTypeInfo(false, BUILT_INS.intType) } + val newParameter1 = KotlinParameterInfo( + originalBaseFunctionDescriptor, + -1, + "n", + KotlinTypeInfo(false), + null, + defaultValueForCall1 + ).apply { currentTypeInfo = KotlinTypeInfo(false, BUILT_INS.intType) } addParameter(newParameter1) val defaultValueForCall2 = psiFactory.createExpression("\"abc\"") - val newParameter2 = KotlinParameterInfo(originalBaseFunctionDescriptor, -1, "s", KotlinTypeInfo(false), null, defaultValueForCall2) - .apply { currentTypeInfo = KotlinTypeInfo(false, BUILT_INS.stringType) } + val newParameter2 = KotlinParameterInfo( + originalBaseFunctionDescriptor, + -1, + "s", + KotlinTypeInfo(false), + null, + defaultValueForCall2 + ).apply { currentTypeInfo = KotlinTypeInfo(false, BUILT_INS.stringType) } addParameter(newParameter2) val classA = KotlinFullClassNameIndex.getInstance().get("A", project, project.allScope()).first() @@ -767,21 +895,48 @@ class KotlinChangeSignatureTest : KotlinLightCodeInsightFixtureTestCase() { fun testPropagateWithParameterDuplication() = doTestConflict { val defaultValueForCall = KtPsiFactory(project).createExpression("1") - addParameter(KotlinParameterInfo(originalBaseFunctionDescriptor, -1, "n", KotlinTypeInfo(false, BUILT_INS.intType), null, defaultValueForCall)) + addParameter( + KotlinParameterInfo( + originalBaseFunctionDescriptor, + -1, + "n", + KotlinTypeInfo(false, BUILT_INS.intType), + null, + defaultValueForCall + ) + ) primaryPropagationTargets = listOf(KotlinTopLevelFunctionFqnNameIndex.getInstance().get("bar", project, project.allScope()).first()) } fun testPropagateWithVariableDuplication() = doTestConflict { val defaultValueForCall = KtPsiFactory(project).createExpression("1") - addParameter(KotlinParameterInfo(originalBaseFunctionDescriptor, -1, "n", KotlinTypeInfo(false, BUILT_INS.intType), null, defaultValueForCall)) + addParameter( + KotlinParameterInfo( + originalBaseFunctionDescriptor, + -1, + "n", + KotlinTypeInfo(false, BUILT_INS.intType), + null, + defaultValueForCall + ) + ) primaryPropagationTargets = listOf(KotlinTopLevelFunctionFqnNameIndex.getInstance().get("bar", project, project.allScope()).first()) } fun testPropagateWithThisQualificationInClassMember() = doTest { val defaultValueForCall = KtPsiFactory(project).createExpression("1") - addParameter(KotlinParameterInfo(originalBaseFunctionDescriptor, -1, "n", KotlinTypeInfo(false, BUILT_INS.intType), null, defaultValueForCall)) + addParameter( + KotlinParameterInfo( + originalBaseFunctionDescriptor, + -1, + "n", + KotlinTypeInfo(false, BUILT_INS.intType), + null, + defaultValueForCall + ) + ) val classA = KotlinFullClassNameIndex.getInstance().get("A", project, project.allScope()).first() val functionBar = classA.declarations.first { it is KtNamedFunction && it.name == "bar" } @@ -790,7 +945,16 @@ class KotlinChangeSignatureTest : KotlinLightCodeInsightFixtureTestCase() { fun testPropagateWithThisQualificationInExtension() = doTest { val defaultValueForCall = KtPsiFactory(project).createExpression("1") - addParameter(KotlinParameterInfo(originalBaseFunctionDescriptor, -1, "n", KotlinTypeInfo(false, BUILT_INS.intType), null, defaultValueForCall)) + addParameter( + KotlinParameterInfo( + originalBaseFunctionDescriptor, + -1, + "n", + KotlinTypeInfo(false, BUILT_INS.intType), + null, + defaultValueForCall + ) + ) primaryPropagationTargets = listOf(KotlinTopLevelFunctionFqnNameIndex.getInstance().get("bar", project, project.allScope()).first()) } @@ -802,14 +966,32 @@ class KotlinChangeSignatureTest : KotlinLightCodeInsightFixtureTestCase() { fun testPrimaryConstructorParameterPropagation() = doTest { val defaultValueForCall = KtPsiFactory(project).createExpression("1") - addParameter(KotlinParameterInfo(originalBaseFunctionDescriptor, -1, "n", KotlinTypeInfo(false, BUILT_INS.intType), null, defaultValueForCall)) + addParameter( + KotlinParameterInfo( + originalBaseFunctionDescriptor, + -1, + "n", + KotlinTypeInfo(false, BUILT_INS.intType), + null, + defaultValueForCall + ) + ) primaryPropagationTargets = findCallers(method.getRepresentativeLightMethod()!!) } fun testSecondaryConstructorParameterPropagation() = doTest { val defaultValueForCall = KtPsiFactory(project).createExpression("1") - addParameter(KotlinParameterInfo(originalBaseFunctionDescriptor, -1, "n", KotlinTypeInfo(false, BUILT_INS.intType), null, defaultValueForCall)) + addParameter( + KotlinParameterInfo( + originalBaseFunctionDescriptor, + -1, + "n", + KotlinTypeInfo(false, BUILT_INS.intType), + null, + defaultValueForCall + ) + ) primaryPropagationTargets = findCallers(method.getRepresentativeLightMethod()!!) } @@ -837,12 +1019,30 @@ class KotlinChangeSignatureTest : KotlinLightCodeInsightFixtureTestCase() { private fun doTestJvmOverloadedAddDefault(index: Int) = doTest { val defaultValue = KtPsiFactory(project).createExpression("2") - addParameter(KotlinParameterInfo(originalBaseFunctionDescriptor, -1, "n", KotlinTypeInfo(false, BUILT_INS.intType), defaultValue, defaultValue), index) + addParameter( + KotlinParameterInfo( + originalBaseFunctionDescriptor, + -1, + "n", + KotlinTypeInfo(false, BUILT_INS.intType), + defaultValue, + defaultValue + ), index + ) } private fun doTestJvmOverloadedAddNonDefault(index: Int) = doTest { val defaultValue = KtPsiFactory(project).createExpression("2") - addParameter(KotlinParameterInfo(originalBaseFunctionDescriptor, -1, "n", KotlinTypeInfo(false, BUILT_INS.intType), null, defaultValue), index) + addParameter( + KotlinParameterInfo( + originalBaseFunctionDescriptor, + -1, + "n", + KotlinTypeInfo(false, BUILT_INS.intType), + null, + defaultValue + ), index + ) } fun testJvmOverloadedAddDefault1() = doTestJvmOverloadedAddDefault(0) @@ -879,8 +1079,26 @@ class KotlinChangeSignatureTest : KotlinLightCodeInsightFixtureTestCase() { val psiFactory = KtPsiFactory(project) val defaultValue1 = psiFactory.createExpression("4") val defaultValue2 = psiFactory.createExpression("5") - addParameter(KotlinParameterInfo(originalBaseFunctionDescriptor, -1, "d", KotlinTypeInfo(false, BUILT_INS.intType), null, defaultValue1), 2) - addParameter(KotlinParameterInfo(originalBaseFunctionDescriptor, -1, "e", KotlinTypeInfo(false, BUILT_INS.intType), null, defaultValue2)) + addParameter( + KotlinParameterInfo( + originalBaseFunctionDescriptor, + -1, + "d", + KotlinTypeInfo(false, BUILT_INS.intType), + null, + defaultValue1 + ), 2 + ) + addParameter( + KotlinParameterInfo( + originalBaseFunctionDescriptor, + -1, + "e", + KotlinTypeInfo(false, BUILT_INS.intType), + null, + defaultValue2 + ) + ) } fun testRemoveParameterKeepFormat1() = doTest { removeParameter(0) } @@ -903,14 +1121,18 @@ class KotlinChangeSignatureTest : KotlinLightCodeInsightFixtureTestCase() { } fun testAddDataClassParameter() = doTest { - addParameter(KotlinParameterInfo(originalBaseFunctionDescriptor, - -1, - "c", - KotlinTypeInfo(false, BUILT_INS.intType), - null, - KtPsiFactory(project).createExpression("3"), - KotlinValVar.Val), - 1) + addParameter( + KotlinParameterInfo( + originalBaseFunctionDescriptor, + -1, + "c", + KotlinTypeInfo(false, BUILT_INS.intType), + null, + KtPsiFactory(project).createExpression("3"), + KotlinValVar.Val + ), + 1 + ) } fun testRemoveDataClassParameter() = doTest { removeParameter(1) } @@ -919,23 +1141,31 @@ class KotlinChangeSignatureTest : KotlinLightCodeInsightFixtureTestCase() { val psiFactory = KtPsiFactory(project) swapParameters(1, 2) - setNewParameter(0, - KotlinParameterInfo(originalBaseFunctionDescriptor, - -1, - "d", - KotlinTypeInfo(false, BUILT_INS.intType), - null, - psiFactory.createExpression("4"), - KotlinValVar.Val)) + setNewParameter( + 0, + KotlinParameterInfo( + originalBaseFunctionDescriptor, + -1, + "d", + KotlinTypeInfo(false, BUILT_INS.intType), + null, + psiFactory.createExpression("4"), + KotlinValVar.Val + ) + ) - setNewParameter(2, - KotlinParameterInfo(originalBaseFunctionDescriptor, - -1, - "e", - KotlinTypeInfo(false, BUILT_INS.intType), - null, - psiFactory.createExpression("5"), - KotlinValVar.Val)) + setNewParameter( + 2, + KotlinParameterInfo( + originalBaseFunctionDescriptor, + -1, + "e", + KotlinTypeInfo(false, BUILT_INS.intType), + null, + psiFactory.createExpression("5"), + KotlinValVar.Val + ) + ) } fun testImplicitReceiverInRecursiveCall() = doTest { @@ -960,13 +1190,13 @@ class KotlinChangeSignatureTest : KotlinLightCodeInsightFixtureTestCase() { fun testInvokeConventionAddParameter() = doTest { addParameter( - KotlinParameterInfo( - originalBaseFunctionDescriptor, - -1, - "b", - KotlinTypeInfo(false, BUILT_INS.booleanType), - defaultValueForCall = KtPsiFactory(project).createExpression("false") - ) + KotlinParameterInfo( + originalBaseFunctionDescriptor, + -1, + "b", + KotlinTypeInfo(false, BUILT_INS.booleanType), + defaultValueForCall = KtPsiFactory(project).createExpression("false") + ) ) } @@ -984,13 +1214,13 @@ class KotlinChangeSignatureTest : KotlinLightCodeInsightFixtureTestCase() { fun testGetConventionAddParameter() = doTest { addParameter( - KotlinParameterInfo( - originalBaseFunctionDescriptor, - -1, - "b", - KotlinTypeInfo(false, BUILT_INS.booleanType), - defaultValueForCall = KtPsiFactory(project).createExpression("false") - ) + KotlinParameterInfo( + originalBaseFunctionDescriptor, + -1, + "b", + KotlinTypeInfo(false, BUILT_INS.booleanType), + defaultValueForCall = KtPsiFactory(project).createExpression("false") + ) ) } diff --git a/idea/tests/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinMultiModuleChangeSignatureTest.kt b/idea/tests/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinMultiModuleChangeSignatureTest.kt index 30261733111..cc79cc4264f 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinMultiModuleChangeSignatureTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinMultiModuleChangeSignatureTest.kt @@ -44,13 +44,13 @@ class KotlinMultiModuleChangeSignatureTest : KotlinMultiFileTestCase() { private fun KotlinChangeInfo.addParameter(name: String, type: KotlinType, defaultValue: String) { addParameter( - KotlinParameterInfo( - originalBaseFunctionDescriptor, - -1, - name, - KotlinTypeInfo(false, type), - defaultValueForCall = KtPsiFactory(project).createExpression(defaultValue) - ) + KotlinParameterInfo( + originalBaseFunctionDescriptor, + -1, + name, + KotlinTypeInfo(false, type), + defaultValueForCall = KtPsiFactory(project).createExpression(defaultValue) + ) ) } diff --git a/idea/tests/org/jetbrains/kotlin/idea/refactoring/inline/AbstractInlineTest.kt b/idea/tests/org/jetbrains/kotlin/idea/refactoring/inline/AbstractInlineTest.kt index 8d71ef43a0f..5fd9a8802d2 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/refactoring/inline/AbstractInlineTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/refactoring/inline/AbstractInlineTest.kt @@ -46,7 +46,8 @@ abstract class AbstractInlineTest : KotlinLightCodeInsightFixtureTestCase() { try { val afterFileExists = afterFile.exists() - val targetElement = TargetElementUtil.findTargetElement(myFixture.editor, ELEMENT_NAME_ACCEPTED or REFERENCED_ELEMENT_ACCEPTED)!! + val targetElement = + TargetElementUtil.findTargetElement(myFixture.editor, ELEMENT_NAME_ACCEPTED or REFERENCED_ELEMENT_ACCEPTED)!! @Suppress("DEPRECATION") val handler = Extensions.getExtensions(InlineActionHandler.EP_NAME).firstOrNull { it.canInlineElement(targetElement) } @@ -61,19 +62,16 @@ abstract class AbstractInlineTest : KotlinLightCodeInsightFixtureTestCase() { for ((extraPsiFile, extraFile) in extraFilesToPsi) { KotlinTestUtils.assertEqualsToFile(File("${extraFile.path}.after"), extraPsiFile.text) } - } - catch (e: CommonRefactoringUtil.RefactoringErrorHintException) { + } catch (e: CommonRefactoringUtil.RefactoringErrorHintException) { TestCase.assertFalse("Refactoring not available: ${e.message}", afterFileExists) TestCase.assertEquals("Expected errors", 1, expectedErrors.size) TestCase.assertEquals("Error message", expectedErrors[0].replace("\\n", "\n"), e.message) - } - catch (e: BaseRefactoringProcessor.ConflictsInTestsException) { + } catch (e: BaseRefactoringProcessor.ConflictsInTestsException) { TestCase.assertFalse("Conflicts: ${e.message}", afterFileExists) TestCase.assertEquals("Expected errors", 1, expectedErrors.size) TestCase.assertEquals("Error message", expectedErrors[0].replace("\\n", "\n"), e.message) } - } - else { + } else { TestCase.assertFalse("No refactoring handler available", afterFileExists) } } finally { diff --git a/idea/tests/org/jetbrains/kotlin/idea/refactoring/introduce/AbstractExtractionTest.kt b/idea/tests/org/jetbrains/kotlin/idea/refactoring/introduce/AbstractExtractionTest.kt index 94cd590c1e1..484adfba4d8 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/refactoring/introduce/AbstractExtractionTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/refactoring/introduce/AbstractExtractionTest.kt @@ -72,10 +72,10 @@ abstract class AbstractExtractionTest : KotlinLightCodeInsightFixtureTestCase() file as KtFile KotlinIntroduceVariableHandler.invoke( - fixture.project, - fixture.editor, - file, - DataManager.getInstance().getDataContext(fixture.editor.component) + fixture.project, + fixture.editor, + file, + DataManager.getInstance().getDataContext(fixture.editor.component) ) } } @@ -84,23 +84,21 @@ abstract class AbstractExtractionTest : KotlinLightCodeInsightFixtureTestCase() doTest(path) { file -> val fileText = file.text - open class HelperImpl: KotlinIntroduceParameterHelper { - override fun configure(descriptor: IntroduceParameterDescriptor): IntroduceParameterDescriptor { - return with (descriptor) { - val singleReplace = InTextDirectivesUtils.isDirectiveDefined(fileText, "// SINGLE_REPLACE") - val withDefaultValue = InTextDirectivesUtils.getPrefixedBoolean(fileText, "// WITH_DEFAULT_VALUE:") ?: true + open class HelperImpl : KotlinIntroduceParameterHelper { + override fun configure(descriptor: IntroduceParameterDescriptor): IntroduceParameterDescriptor = with(descriptor) { + val singleReplace = InTextDirectivesUtils.isDirectiveDefined(fileText, "// SINGLE_REPLACE") + val withDefaultValue = InTextDirectivesUtils.getPrefixedBoolean(fileText, "// WITH_DEFAULT_VALUE:") ?: true - copy(occurrencesToReplace = if (singleReplace) Collections.singletonList(originalOccurrence) else occurrencesToReplace, - withDefaultValue = withDefaultValue) - } + copy( + occurrencesToReplace = if (singleReplace) Collections.singletonList(originalOccurrence) else occurrencesToReplace, + withDefaultValue = withDefaultValue + ) } } - class LambdaHelperImpl: HelperImpl(), KotlinIntroduceLambdaParameterHelper { - override fun configureExtractLambda(descriptor: ExtractableCodeDescriptor): ExtractableCodeDescriptor { - return with(descriptor) { - if (name.isNullOrEmpty()) copy(suggestedNames = listOf("__dummyTestFun__")) else this - } + class LambdaHelperImpl : HelperImpl(), KotlinIntroduceLambdaParameterHelper { + override fun configureExtractLambda(descriptor: ExtractableCodeDescriptor): ExtractableCodeDescriptor = with(descriptor) { + if (name.isNullOrEmpty()) copy(suggestedNames = listOf("__dummyTestFun__")) else this } } @@ -109,14 +107,13 @@ abstract class AbstractExtractionTest : KotlinLightCodeInsightFixtureTestCase() } else { KotlinIntroduceParameterHandler(HelperImpl()) } - with (handler) { + with(handler) { val target = (file as KtFile).findElementByCommentPrefix("// TARGET:") as? KtNamedDeclaration if (target != null) { selectElement(fixture.editor, file, true, listOf(CodeInsightUtils.ElementKind.EXPRESSION)) { element -> invoke(fixture.project, fixture.editor, element as KtExpression, target) } - } - else { + } else { invoke(fixture.project, fixture.editor, file, null) } } @@ -138,22 +135,22 @@ abstract class AbstractExtractionTest : KotlinLightCodeInsightFixtureTestCase() var elementToWorkOn: ElementToWorkOn? = null ElementToWorkOn.processElementToWorkOn( - editor, - file, - "Introduce parameter", - null, - project, - object : ElementToWorkOn.ElementsProcessor { - override fun accept(e: ElementToWorkOn): Boolean { - return true - } + editor, + file, + "Introduce parameter", + null, + project, + object : ElementToWorkOn.ElementsProcessor { + override fun accept(e: ElementToWorkOn): Boolean { + return true + } - override fun pass(e: ElementToWorkOn?) { - if (e != null) { - elementToWorkOn = e - } + override fun pass(e: ElementToWorkOn?) { + if (e != null) { + elementToWorkOn = e } - }) + } + }) val expr = elementToWorkOn!!.expression val localVar = elementToWorkOn!!.localVariable @@ -165,41 +162,42 @@ abstract class AbstractExtractionTest : KotlinLightCodeInsightFixtureTestCase() val methodToSearchFor = if (applyToSuper) method.findDeepestSuperMethods()[0] else method val (initializer, occurrences) = - if (expr == null) { - localVar.initializer!! to CodeInsightUtil.findReferenceExpressions(method, localVar) - } - else { - expr to ExpressionOccurrenceManager(expr, method, null).findExpressionOccurrences() - } + if (expr == null) { + localVar.initializer!! to CodeInsightUtil.findReferenceExpressions(method, localVar) + } else { + expr to ExpressionOccurrenceManager(expr, method, null).findExpressionOccurrences() + } val type = initializer.type val parametersToRemove = Util.findParametersToRemove(method, initializer, occurrences) val codeStyleManager = JavaCodeStyleManager.getInstance(project) val info = codeStyleManager.suggestUniqueVariableName( - codeStyleManager.suggestVariableName(VariableKind.PARAMETER, localVar?.name, initializer, type), - expr, - true + codeStyleManager.suggestVariableName(VariableKind.PARAMETER, localVar?.name, initializer, type), + expr, + true ) val suggestedNames = AbstractJavaInplaceIntroducer.appendUnresolvedExprName( - JavaCompletionUtil.completeVariableNameForRefactoring(codeStyleManager, type, VariableKind.LOCAL_VARIABLE, info), - initializer + JavaCompletionUtil.completeVariableNameForRefactoring(codeStyleManager, type, VariableKind.LOCAL_VARIABLE, info), + initializer ) - IntroduceParameterProcessor(project, - method, - methodToSearchFor, - initializer, - expr, - localVar, - true, - suggestedNames.first(), - true, - IntroduceParameterRefactoring.REPLACE_FIELDS_WITH_GETTERS_NONE, - false, - false, - null, - parametersToRemove).run() + IntroduceParameterProcessor( + project, + method, + methodToSearchFor, + initializer, + expr, + localVar, + true, + suggestedNames.first(), + true, + IntroduceParameterRefactoring.REPLACE_FIELDS_WITH_GETTERS_NONE, + false, + false, + null, + parametersToRemove + ).run() editor.selectionModel.removeSelection() } @@ -217,17 +215,17 @@ abstract class AbstractExtractionTest : KotlinLightCodeInsightFixtureTestCase() override fun validate(descriptor: ExtractableCodeDescriptor) = descriptor.validate(extractionTarget) override fun configureAndRun( - project: Project, - editor: Editor, - descriptorWithConflicts: ExtractableCodeDescriptorWithConflicts, - onFinish: (ExtractionResult) -> Unit + project: Project, + editor: Editor, + descriptorWithConflicts: ExtractableCodeDescriptorWithConflicts, + onFinish: (ExtractionResult) -> Unit ) { doRefactor( - ExtractionGeneratorConfiguration( - descriptorWithConflicts.descriptor, - ExtractionGeneratorOptions.DEFAULT.copy(target = extractionTarget, delayInitialOccurrenceReplacement = true) - ), - onFinish + ExtractionGeneratorConfiguration( + descriptorWithConflicts.descriptor, + ExtractionGeneratorOptions.DEFAULT.copy(target = extractionTarget, delayInitialOccurrenceReplacement = true) + ), + onFinish ) } } @@ -268,11 +266,11 @@ abstract class AbstractExtractionTest : KotlinLightCodeInsightFixtureTestCase() val editor = fixture.editor object : KotlinIntroduceTypeAliasHandler() { override fun doInvoke( - project: Project, - editor: Editor, - elements: List, - targetSibling: PsiElement, - descriptorSubstitutor: ((IntroduceTypeAliasDescriptor) -> IntroduceTypeAliasDescriptor)? + project: Project, + editor: Editor, + elements: List, + targetSibling: PsiElement, + descriptorSubstitutor: ((IntroduceTypeAliasDescriptor) -> IntroduceTypeAliasDescriptor)? ) { super.doInvoke(project, editor, elements, explicitPreviousSibling ?: targetSibling) { it.copy(name = aliasName ?: it.name, visibility = aliasVisibility ?: it.visibility) @@ -292,20 +290,20 @@ abstract class AbstractExtractionTest : KotlinLightCodeInsightFixtureTestCase() val fileText = file.text val className = InTextDirectivesUtils.findStringWithPrefixes(fileText, "// NAME:")!! val targetFileName = InTextDirectivesUtils.findStringWithPrefixes(fileText, "// TARGET_FILE_NAME:") - ?: "$className.${KotlinFileType.EXTENSION}" + ?: "$className.${KotlinFileType.EXTENSION}" val editor = fixture.editor val originalClass = file.findElementAt(editor.caretModel.offset)?.getStrictParentOfType()!! val memberInfos = chooseMembers(extractClassMembers(originalClass)) val conflicts = ExtractSuperRefactoring.collectConflicts(originalClass, memberInfos, targetParent, className, isInterface) project.checkConflictsInteractively(conflicts) { val extractInfo = ExtractSuperInfo( - originalClass, - memberInfos, - targetParent, - targetFileName, - className, - isInterface, - DocCommentPolicy(DocCommentPolicy.ASIS) + originalClass, + memberInfos, + targetParent, + targetFileName, + className, + isInterface, + DocCommentPolicy(DocCommentPolicy.ASIS) ) ExtractSuperRefactoring(extractInfo).performRefactoring() } @@ -330,7 +328,6 @@ abstract class AbstractExtractionTest : KotlinLightCodeInsightFixtureTestCase() fixture.testDataPath = "${KotlinTestUtils.getHomeDirectory()}/${mainFile.parent}" - val mainFileName = mainFile.name val mainFileBaseName = FileUtil.getNameWithoutExtension(mainFileName) val extraFiles = mainFile.parentFile.listFiles { _, name -> @@ -349,8 +346,7 @@ abstract class AbstractExtractionTest : KotlinLightCodeInsightFixtureTestCase() try { checkExtract(ExtractTestFiles(path, fixture.configureByFile(mainFileName), extraFilesToPsi), checkAdditionalAfterdata, action) - } - finally { + } finally { ConfigLibraryUtil.unconfigureLibrariesByDirective(module, fileText) if (addKotlinRuntime) { @@ -364,10 +360,11 @@ abstract class AbstractExtractionTest : KotlinLightCodeInsightFixtureTestCase() } class ExtractTestFiles( - val mainFile: PsiFile, - val afterFile: File, - val conflictFile: File, - val extraFilesToPsi: Map = emptyMap()) { + val mainFile: PsiFile, + val afterFile: File, + val conflictFile: File, + val extraFilesToPsi: Map = emptyMap() +) { constructor(path: String, mainFile: PsiFile, extraFilesToPsi: Map = emptyMap()) : this(mainFile, File("$path.after"), File("$path.conflicts"), extraFilesToPsi) } @@ -387,15 +384,12 @@ fun checkExtract(files: ExtractTestFiles, checkAdditionalAfterdata: Boolean = fa KotlinTestUtils.assertEqualsToFile(File("${extraFile.path}.after"), extraPsiFile.text) } } - } - catch(e: ConflictsInTestsException) { + } catch (e: ConflictsInTestsException) { val message = e.messages.sorted().joinToString(" ").replace("\n", " ") KotlinTestUtils.assertEqualsToFile(conflictFile, message) - } - catch(e: CommonRefactoringUtil.RefactoringErrorHintException) { + } catch (e: CommonRefactoringUtil.RefactoringErrorHintException) { KotlinTestUtils.assertEqualsToFile(conflictFile, e.message!!) - } - catch(e: RuntimeException) { // RuntimeException is thrown by IDEA code in CodeInsightUtils.java + } catch (e: RuntimeException) { // RuntimeException is thrown by IDEA code in CodeInsightUtils.java if (e::class.java != RuntimeException::class.java) throw e KotlinTestUtils.assertEqualsToFile(conflictFile, e.message!!) } @@ -407,9 +401,9 @@ fun doExtractFunction(fixture: CodeInsightTestFixture, file: KtFile) { val expectedNames = InTextDirectivesUtils.findListWithPrefixes(fileText, "// SUGGESTED_NAMES: ") val expectedReturnTypes = InTextDirectivesUtils.findListWithPrefixes(fileText, "// SUGGESTED_RETURN_TYPES: ") val expectedDescriptors = - InTextDirectivesUtils.findLinesWithPrefixesRemoved(fileText, "// PARAM_DESCRIPTOR: ").joinToString() + InTextDirectivesUtils.findLinesWithPrefixesRemoved(fileText, "// PARAM_DESCRIPTOR: ").joinToString() val expectedTypes = - InTextDirectivesUtils.findLinesWithPrefixesRemoved(fileText, "// PARAM_TYPES: ").map { "[$it]" }.joinToString() + InTextDirectivesUtils.findLinesWithPrefixesRemoved(fileText, "// PARAM_TYPES: ").map { "[$it]" }.joinToString() val extractionOptions = InTextDirectivesUtils.findListWithPrefixes(fileText, "// OPTIONS: ").let { if (it.isNotEmpty()) { @@ -423,47 +417,50 @@ fun doExtractFunction(fixture: CodeInsightTestFixture, file: KtFile) { val editor = fixture.editor val handler = ExtractKotlinFunctionHandler( - helper = object : ExtractionEngineHelper(EXTRACT_FUNCTION) { - override fun adjustExtractionData(data: ExtractionData): ExtractionData { - return data.copy(options = extractionOptions) - } - - override fun configureAndRun( - project: Project, - editor: Editor, - descriptorWithConflicts: ExtractableCodeDescriptorWithConflicts, - onFinish: (ExtractionResult) -> Unit - ) { - val descriptor = descriptorWithConflicts.descriptor - val actualNames = descriptor.suggestedNames - val actualReturnTypes = descriptor.controlFlow.possibleReturnTypes.map { - IdeDescriptorRenderers.SOURCE_CODE.renderType(it) - } - val allParameters = listOfNotNull(descriptor.receiverParameter) + descriptor.parameters - val actualDescriptors = allParameters.map { renderer.render(it.originalDescriptor) }.joinToString() - val actualTypes = allParameters.map { - it.getParameterTypeCandidates().map { renderer.renderType(it) }.joinToString(", ", "[", "]") - }.joinToString() - - if (actualNames.size != 1 || expectedNames.isNotEmpty()) { - assertEquals(expectedNames, actualNames, "Expected names mismatch.") - } - if (actualReturnTypes.size != 1 || expectedReturnTypes.isNotEmpty()) { - assertEquals(expectedReturnTypes, actualReturnTypes, "Expected return types mismatch.") - } - KotlinLightCodeInsightFixtureTestCaseBase.assertEquals("Expected descriptors mismatch.", expectedDescriptors, actualDescriptors) - KotlinLightCodeInsightFixtureTestCaseBase.assertEquals("Expected types mismatch.", expectedTypes, actualTypes) - - val newDescriptor = if (descriptor.name == "") { - descriptor.copy(suggestedNames = Collections.singletonList("__dummyTestFun__")) - } - else { - descriptor - } - - doRefactor(ExtractionGeneratorConfiguration(newDescriptor, ExtractionGeneratorOptions.DEFAULT), onFinish) - } + helper = object : ExtractionEngineHelper(EXTRACT_FUNCTION) { + override fun adjustExtractionData(data: ExtractionData): ExtractionData { + return data.copy(options = extractionOptions) } + + override fun configureAndRun( + project: Project, + editor: Editor, + descriptorWithConflicts: ExtractableCodeDescriptorWithConflicts, + onFinish: (ExtractionResult) -> Unit + ) { + val descriptor = descriptorWithConflicts.descriptor + val actualNames = descriptor.suggestedNames + val actualReturnTypes = descriptor.controlFlow.possibleReturnTypes.map { + IdeDescriptorRenderers.SOURCE_CODE.renderType(it) + } + val allParameters = listOfNotNull(descriptor.receiverParameter) + descriptor.parameters + val actualDescriptors = allParameters.map { renderer.render(it.originalDescriptor) }.joinToString() + val actualTypes = allParameters.map { + it.getParameterTypeCandidates().map { renderer.renderType(it) }.joinToString(", ", "[", "]") + }.joinToString() + + if (actualNames.size != 1 || expectedNames.isNotEmpty()) { + assertEquals(expectedNames, actualNames, "Expected names mismatch.") + } + if (actualReturnTypes.size != 1 || expectedReturnTypes.isNotEmpty()) { + assertEquals(expectedReturnTypes, actualReturnTypes, "Expected return types mismatch.") + } + KotlinLightCodeInsightFixtureTestCaseBase.assertEquals( + "Expected descriptors mismatch.", + expectedDescriptors, + actualDescriptors + ) + KotlinLightCodeInsightFixtureTestCaseBase.assertEquals("Expected types mismatch.", expectedTypes, actualTypes) + + val newDescriptor = if (descriptor.name == "") { + descriptor.copy(suggestedNames = Collections.singletonList("__dummyTestFun__")) + } else { + descriptor + } + + doRefactor(ExtractionGeneratorConfiguration(newDescriptor, ExtractionGeneratorOptions.DEFAULT), onFinish) + } + } ) handler.selectElements(editor, file) { elements, previousSibling -> handler.doInvoke(editor, file, elements, explicitPreviousSibling ?: previousSibling) diff --git a/idea/tests/org/jetbrains/kotlin/idea/refactoring/move/AbstractMoveTest.kt b/idea/tests/org/jetbrains/kotlin/idea/refactoring/move/AbstractMoveTest.kt index 6230bce6eb0..dd3e1c3e33e 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/refactoring/move/AbstractMoveTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/refactoring/move/AbstractMoveTest.kt @@ -231,7 +231,9 @@ enum class MoveAction : AbstractMultifileRefactoringTest.RefactoringAction { createKotlinFile(guessNewFileName(elementsToMove)!!, moveDestination.getTargetDirectory(mainFile)) } } ?: config.getString("targetFile").let { filePath -> - KotlinMoveTargetForExistingElement(PsiManager.getInstance(project).findFile(rootDir.findFileByRelativePath(filePath)!!) as KtFile) + KotlinMoveTargetForExistingElement( + PsiManager.getInstance(project).findFile(rootDir.findFileByRelativePath(filePath)!!) as KtFile + ) } val descriptor = MoveDeclarationsDescriptor(project, MoveSource(elementsToMove), moveTarget, MoveDeclarationsDelegate.TopLevel) diff --git a/idea/tests/org/jetbrains/kotlin/idea/refactoring/move/AbstractMultiModuleMoveTest.kt b/idea/tests/org/jetbrains/kotlin/idea/refactoring/move/AbstractMultiModuleMoveTest.kt index ea5c5a1f4f2..6e4f9a79832 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/refactoring/move/AbstractMultiModuleMoveTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/refactoring/move/AbstractMultiModuleMoveTest.kt @@ -33,19 +33,17 @@ abstract class AbstractMultiModuleMoveTest : KotlinMultiFileTestCase() { val withRuntime = config["withRuntime"]?.asBoolean ?: false if (withRuntime) { val moduleManager = ModuleManager.getInstance(project) - modulesWithJvmRuntime = - (config["modulesWithRuntime"]?.asJsonArray?.map { moduleManager.findModuleByName(it.asString!!)!! } - ?: moduleManager.modules.toList()) + modulesWithJvmRuntime = (config["modulesWithRuntime"]?.asJsonArray?.map { moduleManager.findModuleByName(it.asString!!)!! } + ?: moduleManager.modules.toList()) modulesWithJvmRuntime.forEach { ConfigLibraryUtil.configureKotlinRuntimeAndSdk(it, PluginTestCaseBase.mockJdk()) } modulesWithJsRuntime = - (config["modulesWithJsRuntime"]?.asJsonArray?.map { moduleManager.findModuleByName(it.asString!!)!! } - ?: emptyList()) + (config["modulesWithJsRuntime"]?.asJsonArray?.map { moduleManager.findModuleByName(it.asString!!)!! } ?: emptyList()) modulesWithJsRuntime.forEach { ConfigLibraryUtil.configureKotlinJsRuntimeAndSdk(it, PluginTestCaseBase.mockJdk()) } modulesWithCommonRuntime = - (config["modulesWithCommonRuntime"]?.asJsonArray?.map { moduleManager.findModuleByName(it.asString!!)!! } - ?: emptyList()) + (config["modulesWithCommonRuntime"]?.asJsonArray?.map { moduleManager.findModuleByName(it.asString!!)!! } + ?: emptyList()) modulesWithCommonRuntime.forEach { ConfigLibraryUtil.configureKotlinCommonRuntime(it) } } else { modulesWithJvmRuntime = emptyList() @@ -55,8 +53,7 @@ abstract class AbstractMultiModuleMoveTest : KotlinMultiFileTestCase() { try { runMoveRefactoring(path, config, rootDir, project) - } - finally { + } finally { modulesWithJvmRuntime.forEach { ConfigLibraryUtil.unConfigureKotlinRuntimeAndSdk(it, PluginTestCaseBase.mockJdk()) } diff --git a/idea/tests/org/jetbrains/kotlin/idea/refactoring/move/MoveKotlinDeclarationsHandlerTest.kt b/idea/tests/org/jetbrains/kotlin/idea/refactoring/move/MoveKotlinDeclarationsHandlerTest.kt index 0187cd8ce1c..2432ff12965 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/refactoring/move/MoveKotlinDeclarationsHandlerTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/refactoring/move/MoveKotlinDeclarationsHandlerTest.kt @@ -120,9 +120,8 @@ class MoveKotlinDeclarationsHandlerTest : KotlinMultiFileTestCase() { } fun testMultipleTopLevelDeclarationsInDifferentFiles() = doTest { rootDir, handler -> - val declarations = listOf("test.kt", "test2.kt") - .flatMap { getElementsAtCarets(rootDir, it) } - .map { it.getNonStrictParentOfType()!! } + val declarations = listOf("test.kt", "test2.kt").flatMap { getElementsAtCarets(rootDir, it) } + .map { it.getNonStrictParentOfType()!! } assert(handler.canMove(declarations.toTypedArray(), null)) val files = listOf("test.kt", "test2.kt").map { getPsiFile(rootDir, it) } @@ -130,9 +129,8 @@ class MoveKotlinDeclarationsHandlerTest : KotlinMultiFileTestCase() { } fun testMultipleTopLevelDeclarationsInDifferentDirs() = doTest { rootDir, handler -> - val declarations = listOf("test1/test.kt", "test2/test2.kt") - .flatMap { getElementsAtCarets(rootDir, it) } - .map { it.getNonStrictParentOfType()!! } + val declarations = listOf("test1/test.kt", "test2/test2.kt").flatMap { getElementsAtCarets(rootDir, it) } + .map { it.getNonStrictParentOfType()!! } assert(!handler.canMove(declarations.toTypedArray(), null)) val files = listOf("test1/test.kt", "test2/test2.kt").map { getPsiFile(rootDir, it) } @@ -140,8 +138,10 @@ class MoveKotlinDeclarationsHandlerTest : KotlinMultiFileTestCase() { } fun testFileAndTopLevelDeclarations() = doTest { rootDir, handler -> - val elements = getElementsAtCarets(rootDir, "test.kt").map { it.getNonStrictParentOfType()!! } + - getPsiFile(rootDir, "test2.kt") + val elements = getElementsAtCarets(rootDir, "test.kt").map { it.getNonStrictParentOfType()!! } + getPsiFile( + rootDir, + "test2.kt" + ) assert(!handler.canMove(elements.toTypedArray(), null)) } diff --git a/idea/tests/org/jetbrains/kotlin/idea/refactoring/pullUp/AbstractPullUpTest.kt b/idea/tests/org/jetbrains/kotlin/idea/refactoring/pullUp/AbstractPullUpTest.kt index fb36781ea6c..90dd0dfbd44 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/refactoring/pullUp/AbstractPullUpTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/refactoring/pullUp/AbstractPullUpTest.kt @@ -27,7 +27,7 @@ abstract class AbstractPullUpTest : AbstractMemberPullPushTest() { protected fun doKotlinTest(path: String) { doTest(path) { file -> val targetClassName = getTargetClassName(file) - val helper = object: KotlinPullUpHandler.TestHelper { + val helper = object : KotlinPullUpHandler.TestHelper { override fun adjustMembers(members: List) = chooseMembers(members) override fun chooseSuperClass(superClasses: List): PsiNamedElement { @@ -59,13 +59,13 @@ abstract class AbstractPullUpTest : AbstractMemberPullPushTest() { val targetDirectory = targetClass.containingFile.containingDirectory val conflicts = PullUpConflictsUtil.checkConflicts( - memberInfos, - sourceClass, - targetClass, - targetDirectory.getPackage()!!, - targetDirectory, - { psiMethod : PsiMethod -> PullUpProcessor.checkedInterfacesContain(memberInfoList, psiMethod) }, - true + memberInfos, + sourceClass, + targetClass, + targetDirectory.getPackage()!!, + targetDirectory, + { psiMethod: PsiMethod -> PullUpProcessor.checkedInterfacesContain(memberInfoList, psiMethod) }, + true ) if (!conflicts.isEmpty) throw BaseRefactoringProcessor.ConflictsInTestsException(conflicts.values()) diff --git a/idea/tests/org/jetbrains/kotlin/idea/refactoring/pushDown/AbstractPushDownTest.kt b/idea/tests/org/jetbrains/kotlin/idea/refactoring/pushDown/AbstractPushDownTest.kt index cfaade319ec..6dd72acda2d 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/refactoring/pushDown/AbstractPushDownTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/refactoring/pushDown/AbstractPushDownTest.kt @@ -19,7 +19,7 @@ import org.jetbrains.kotlin.idea.refactoring.memberInfo.KotlinMemberInfo abstract class AbstractPushDownTest : AbstractMemberPullPushTest() { protected fun doKotlinTest(path: String) { doTest(path) { file -> - val helper = object: KotlinPushDownHandler.TestHelper { + val helper = object : KotlinPushDownHandler.TestHelper { override fun adjustMembers(members: List) = chooseMembers(members) } KotlinPushDownHandler().invoke(project, editor, file) { diff --git a/idea/tests/org/jetbrains/kotlin/idea/refactoring/rename/AbstractRenameTest.kt b/idea/tests/org/jetbrains/kotlin/idea/refactoring/rename/AbstractRenameTest.kt index ff1384882d0..294cbbb20e3 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/refactoring/rename/AbstractRenameTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/refactoring/rename/AbstractRenameTest.kt @@ -74,10 +74,11 @@ enum class RenameType { abstract class AbstractRenameTest : KotlinLightCodeInsightFixtureTestCase() { inner class TestContext( - val testFile: File, - val project: Project = getProject(), - val javaFacade: JavaPsiFacade = myFixture.javaFacade, - val module: Module = myFixture.module) + val testFile: File, + val project: Project = getProject(), + val javaFacade: JavaPsiFacade = myFixture.javaFacade, + val module: Module = myFixture.module + ) override fun getProjectDescriptor(): LightProjectDescriptor { if (KotlinTestUtils.isAllFilesPresentTest(getTestName(false))) return super.getProjectDescriptor() @@ -144,19 +145,16 @@ abstract class AbstractRenameTest : KotlinLightCodeInsightFixtureTestCase() { VfsUtilCore.visitChildrenRecursively(sourceRoot, visitor) } } - } - catch (e : Exception) { + } catch (e: Exception) { if (e !is RefactoringErrorHintException && e !is ConflictsInTestsException) throw e val hintExceptionUnquoted = StringUtil.unquoteString(e.message!!) if (hintDirective != null) { Assert.assertEquals(hintDirective, hintExceptionUnquoted) - } - else { + } else { Assert.fail("""Unexpected "hint: $hintExceptionUnquoted" """) } - } - finally { + } finally { fixtureClasses.forEach { TestFixtureExtension.unloadFixture(it) } } } @@ -209,15 +207,23 @@ abstract class AbstractRenameTest : KotlinLightCodeInsightFixtureTestCase() { private fun renameKotlinFunctionTest(renameParamsObject: JsonObject, context: TestContext) { val oldMethodName = Name.identifier(renameParamsObject.getString("oldName")) - doRenameInKotlinClassOrPackage(renameParamsObject, context) { - _, scope -> scope.getContributedFunctions(oldMethodName, NoLookupLocation.FROM_TEST).first() } + doRenameInKotlinClassOrPackage(renameParamsObject, context) { _, scope -> + scope.getContributedFunctions( + oldMethodName, + NoLookupLocation.FROM_TEST + ).first() + } } private fun renameKotlinPropertyTest(renameParamsObject: JsonObject, context: TestContext) { val oldPropertyName = Name.identifier(renameParamsObject.getString("oldName")) - doRenameInKotlinClassOrPackage(renameParamsObject, context) { - _, scope -> scope.getContributedVariables(oldPropertyName, NoLookupLocation.FROM_TEST).first() } + doRenameInKotlinClassOrPackage(renameParamsObject, context) { _, scope -> + scope.getContributedVariables( + oldPropertyName, + NoLookupLocation.FROM_TEST + ).first() + } } private fun renameKotlinClassTest(renameParamsObject: JsonObject, context: TestContext) { @@ -272,14 +278,15 @@ abstract class AbstractRenameTest : KotlinLightCodeInsightFixtureTestCase() { } private fun doRenameInKotlinClassOrPackage( - renameParamsObject: JsonObject, context: TestContext, findDescriptorToRename: (DeclarationDescriptor, MemberScope) -> DeclarationDescriptor + renameParamsObject: JsonObject, + context: TestContext, + findDescriptorToRename: (DeclarationDescriptor, MemberScope) -> DeclarationDescriptor ) { val classIdStr = renameParamsObject.getNullableString("classId") val packageFqnStr = renameParamsObject.getNullableString("packageFqn") if (classIdStr != null && packageFqnStr != null) { throw AssertionError("Both classId and packageFqn are defined. Where should I search: in class or in package?") - } - else if (classIdStr == null && packageFqnStr == null) { + } else if (classIdStr == null && packageFqnStr == null) { throw AssertionError("Define classId or packageFqn") } @@ -291,7 +298,7 @@ abstract class AbstractRenameTest : KotlinLightCodeInsightFixtureTestCase() { val module = ktFile.analyzeWithAllCompilerChecks().moduleDescriptor - val (declaration, scopeToSearch) = if (classIdStr != null) { + val (declaration, scopeToSearch) = if (classIdStr != null) { module.findClassAcrossModuleDependencies(classIdStr.toClassId())!!.let { it to it.defaultType.memberScope } } else { module.getPackage(FqName(packageFqnStr!!)).let { it to it.memberScope } @@ -349,14 +356,13 @@ abstract class AbstractRenameTest : KotlinLightCodeInsightFixtureTestCase() { if (handler is VariableInplaceRenameHandler) { val elementToRename = psiFile.findElementAt(currentCaret.offset)!!.getNonStrictParentOfType()!! CodeInsightTestUtil.doInlineRename(handler, newName, editor, elementToRename) - } - else { + } else { handler.invoke(project, editor, psiFile, dataContext) } } } - protected fun getTestDirName(lowercaseFirstLetter : Boolean) : String { + protected fun getTestDirName(lowercaseFirstLetter: Boolean): String { val testName = getTestName(lowercaseFirstLetter) return testName.substring(0, testName.indexOf('_')) } @@ -379,7 +385,7 @@ abstract class AbstractRenameTest : KotlinLightCodeInsightFixtureTestCase() { } } -private fun String.toClassId(): ClassId { +private fun String.toClassId(): ClassId { val relativeClassName = FqName(substringAfterLast('/')) val packageFqName = FqName(substringBeforeLast('/', "").replace('/', '.')) return ClassId(packageFqName, relativeClassName, false) @@ -394,12 +400,12 @@ fun loadTestConfiguration(testFile: File): JsonObject { } fun runRenameProcessor( - project: Project, - newName: String, - substitution: PsiElement?, - renameParamsObject: JsonObject, - isSearchInComments: Boolean, - isSearchTextOccurrences: Boolean + project: Project, + newName: String, + substitution: PsiElement?, + renameParamsObject: JsonObject, + isSearchInComments: Boolean, + isSearchTextOccurrences: Boolean ) { if (substitution == null) return @@ -407,7 +413,12 @@ fun runRenameProcessor( if (substitution is PsiPackage && substitution !is KtLightPackage) { val oldName = substitution.qualifiedName if (StringUtil.getPackageName(oldName) != StringUtil.getPackageName(newName)) { - return RenamePsiPackageProcessor.createRenameMoveProcessor(newName, substitution, isSearchInComments, isSearchTextOccurrences) + return RenamePsiPackageProcessor.createRenameMoveProcessor( + newName, + substitution, + isSearchInComments, + isSearchTextOccurrences + ) } } @@ -456,8 +467,7 @@ fun doRenameMarkedElement(renameParamsObject: JsonObject, psiFile: PsiFile) { } val toRename = if (isByRef) { TargetElementUtil.findTargetElement(currentEditor, TargetElementUtil.getInstance().allAccepted)!! - } - else { + } else { currentFile.findElementAt(marker)!!.getNonStrictParentOfType()!! } @@ -466,8 +476,7 @@ fun doRenameMarkedElement(renameParamsObject: JsonObject, psiFile: PsiFile) { val searchInComments = renameParamsObject["searchInComments"]?.asBoolean ?: true val searchInTextOccurrences = renameParamsObject["searchInTextOccurrences"]?.asBoolean ?: true runRenameProcessor(project, newName, substitution, renameParamsObject, searchInComments, searchInTextOccurrences) - } - finally { + } finally { if (shouldReleaseEditor) { editorFactory.releaseEditor(editor!!) } diff --git a/idea/tests/org/jetbrains/kotlin/idea/repl/IdeReplExecutionTest.kt b/idea/tests/org/jetbrains/kotlin/idea/repl/IdeReplExecutionTest.kt index 617e1436772..b98861d42fb 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/repl/IdeReplExecutionTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/repl/IdeReplExecutionTest.kt @@ -43,13 +43,18 @@ class IdeReplExecutionTest : PlatformTestCase() { } private fun checkOutput(expectedOutput: String) { - val output = getReplOutput(textOnTimeOut = { "Only ${consoleRunner.commandHistory.processedEntriesCount} commands were processed" }) { - consoleRunner.commandHistory.processedEntriesCount >= commandsSent - } + val output = getReplOutput(textOnTimeOut = { + "Only ${consoleRunner.commandHistory.processedEntriesCount} commands were processed" + }) { consoleRunner.commandHistory.processedEntriesCount >= commandsSent } assertTrue(output.trim().endsWith(expectedOutput), "'$expectedOutput' should be printed but document text is:\n$output") } - private fun getReplOutput(maxIterations: Int = 50, sleepTime: Long = 500, textOnTimeOut: () -> String, predicate: () -> Boolean): String { + private fun getReplOutput( + maxIterations: Int = 50, + sleepTime: Long = 500, + textOnTimeOut: () -> String, + predicate: () -> Boolean + ): String { for (i in 1..maxIterations) { UIUtil.dispatchAllInvocationEvents() if (predicate()) { @@ -73,9 +78,12 @@ class IdeReplExecutionTest : PlatformTestCase() { checkOutput(expectedOutput) } - @Test fun testRunPossibility() { + @Test + fun testRunPossibility() { val allOk = { x: String -> x.contains(":help for help") } - val hasErrors = { x: String -> x.contains("Process finished with exit code 1") || x.contains("Exception in") || x.contains("Error") } + val hasErrors = { x: String -> + x.contains("Process finished with exit code 1") || x.contains("Exception in") || x.contains("Error") + } val output = getReplOutput(textOnTimeOut = { "Repl startup timed out" }) { val editorText = refreshAndGetHistoryEditorText() @@ -97,22 +105,31 @@ class IdeReplExecutionTest : PlatformTestCase() { testRunPossibility() } - @Test fun testOnePlusOne() = testSimpleCommand("1 + 1", "2") - @Test fun testPrintlnText() = "Hello, console world!".let { testSimpleCommand("println(\"$it\")", it) } - @Test fun testDivisionByZeroException() = testSimpleCommand("1 / 0", "java.lang.ArithmeticException: / by zero") + @Test + fun testOnePlusOne() = testSimpleCommand("1 + 1", "2") - @Test fun testMultilineSupport() { + @Test + fun testPrintlnText() = "Hello, console world!".let { testSimpleCommand("println(\"$it\")", it) } + + @Test + fun testDivisionByZeroException() = testSimpleCommand("1 / 0", "java.lang.ArithmeticException: / by zero") + + @Test + fun testMultilineSupport() { val printText = "Print in multiline!" - sendCommand("fun f() {\n" + + sendCommand( + "fun f() {\n" + " println(\"$printText\")\n" + - "}\n") + "}\n" + ) sendCommand("f()") checkOutput(printText) } - @Test fun testReadLineSingle() { + @Test + fun testReadLineSingle() { val readLineText = "ReadMe!" sendCommand("val a = readLine()") @@ -121,12 +138,15 @@ class IdeReplExecutionTest : PlatformTestCase() { checkOutput(readLineText) } - @Test fun testReadLineMultiple() { + @Test + fun testReadLineMultiple() { val readLineTextA = "ReadMe A!" val readLineTextB = "ReadMe B!" - sendCommand("val a = readLine()\n" + - "val b = readLine()") + sendCommand( + "val a = readLine()\n" + + "val b = readLine()" + ) sendCommand(readLineTextA) sendCommand(readLineTextB) @@ -136,14 +156,16 @@ class IdeReplExecutionTest : PlatformTestCase() { checkOutput(readLineTextB) } - @Test fun testCorrectAfterError() { + @Test + fun testCorrectAfterError() { val message = "MyMessage" sendCommand("fun f() { println(x)\n println(y) ") sendCommand("println(\"$message\")") checkOutput(message) } - @Test fun testMultipleErrorsHandling() { + @Test + fun testMultipleErrorsHandling() { val veryLongTextWithErrors = "println($);".repeat(30) sendCommand(veryLongTextWithErrors) sendCommand(veryLongTextWithErrors) diff --git a/idea/tests/org/jetbrains/kotlin/idea/resolve/AbstractPartialBodyResolveTest.kt b/idea/tests/org/jetbrains/kotlin/idea/resolve/AbstractPartialBodyResolveTest.kt index d8ebdc73d4d..537d59b863f 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/resolve/AbstractPartialBodyResolveTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/resolve/AbstractPartialBodyResolveTest.kt @@ -129,24 +129,23 @@ abstract class AbstractPartialBodyResolveTest : KotlinLightCodeInsightFixtureTes } private data class ResolveData( - val target: DeclarationDescriptor?, - val type: KotlinType?, - val processedStatements: Collection + val target: DeclarationDescriptor?, + val type: KotlinType?, + val processedStatements: Collection ) private fun doResolve(expression: KtExpression, bindingContext: BindingContext): ResolveData { val target = if (expression is KtReferenceExpression) bindingContext[BindingContext.REFERENCE_TARGET, expression] else null val processedStatements = bindingContext.getSliceContents(BindingContext.PROCESSED) - .filter { it.value } - .map { it.key } - .filter { it.parent is KtBlockExpression } + .filter { it.value } + .map { it.key } + .filter { it.parent is KtBlockExpression } val receiver = (expression as? KtSimpleNameExpression)?.getReceiverExpression() val expressionWithType = if (receiver != null) { expression.parent as? KtExpression ?: expression - } - else { + } else { expression } val type = bindingContext.getType(expressionWithType) @@ -164,8 +163,7 @@ abstract class AbstractPartialBodyResolveTest : KotlinLightCodeInsightFixtureTes return "$s smart-cast to ${type.presentation()}" } - private fun KotlinType?.presentation() - = if (this != null) DescriptorRenderer.COMPACT.renderType(this) else "unknown type" + private fun KotlinType?.presentation() = if (this != null) DescriptorRenderer.COMPACT.renderType(this) else "unknown type" private fun KtExpression.compactPresentation(): String { val text = text diff --git a/idea/tests/org/jetbrains/kotlin/idea/resolve/AbstractReferenceResolveTest.kt b/idea/tests/org/jetbrains/kotlin/idea/resolve/AbstractReferenceResolveTest.kt index 1fd3c7263b6..fc206c7dec6 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/resolve/AbstractReferenceResolveTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/resolve/AbstractReferenceResolveTest.kt @@ -38,8 +38,7 @@ abstract class AbstractReferenceResolveTest : KotlinLightPlatformCodeInsightFixt protected fun performChecks() { if (InTextDirectivesUtils.isDirectiveDefined(myFixture.file.text, MULTIRESOLVE)) { doMultiResolveTest() - } - else { + } else { doSingleResolveTest() } } @@ -102,9 +101,11 @@ abstract class AbstractReferenceResolveTest : KotlinLightPlatformCodeInsightFixt if (shouldBeUnresolved) { Assert.assertTrue("REF: directives will be ignored for $REF_EMPTY test: $refs", refs.isEmpty()) referenceToString = "" - } - else { - assertTrue(refs.size == 1, "Must be a single ref: $refs.\nUse $MULTIRESOLVE if you need multiple refs\nUse $REF_EMPTY for an unresolved reference") + } else { + assertTrue( + refs.size == 1, + "Must be a single ref: $refs.\nUse $MULTIRESOLVE if you need multiple refs\nUse $REF_EMPTY for an unresolved reference" + ) referenceToString = refs.get(0) Assert.assertNotNull("Test data wasn't found, use \"// REF: \" directive", referenceToString) } @@ -119,30 +120,40 @@ abstract class AbstractReferenceResolveTest : KotlinLightPlatformCodeInsightFixt return InTextDirectivesUtils.findLinesWithPrefixesRemoved(text, prefix) } - fun checkReferenceResolve(expectedResolveData: ExpectedResolveData, offset: Int, psiReference: PsiReference?, checkResolvedTo: (PsiElement) -> Unit = {}) { + fun checkReferenceResolve( + expectedResolveData: ExpectedResolveData, + offset: Int, + psiReference: PsiReference?, + checkResolvedTo: (PsiElement) -> Unit = {} + ) { val expectedString = expectedResolveData.referenceString if (psiReference != null) { val resolvedTo = psiReference.resolve() if (resolvedTo != null) { checkResolvedTo(resolvedTo) val resolvedToElementStr = replacePlaceholders(resolvedTo.renderAsGotoImplementation()) - assertEquals("Found reference to '$resolvedToElementStr', but '$expectedString' was expected", expectedString, resolvedToElementStr) - } - else { + assertEquals( + "Found reference to '$resolvedToElementStr', but '$expectedString' was expected", + expectedString, + resolvedToElementStr + ) + } else { if (!expectedResolveData.shouldBeUnresolved()) { - assertNull("Element $psiReference (${psiReference.element.text}) wasn't resolved to anything, but $expectedString was expected", expectedString) + assertNull( + "Element $psiReference (${psiReference.element + .text}) wasn't resolved to anything, but $expectedString was expected", expectedString + ) } } - } - else { + } else { assertNull("No reference found at offset: $offset, but one resolved to $expectedString was expected", expectedString) } } private fun replacePlaceholders(actualString: String): String { val replaced = PathUtil.toSystemIndependentName(actualString) - .replace(PluginTestCaseBase.TEST_DATA_PROJECT_RELATIVE, "/") - .replace("//", "/") // additional slashes to fix discrepancy between windows and unix + .replace(PluginTestCaseBase.TEST_DATA_PROJECT_RELATIVE, "/") + .replace("//", "/") // additional slashes to fix discrepancy between windows and unix if ("!/" in replaced) { return replaced.replace(replaced.substringBefore("!/"), "") } diff --git a/idea/tests/org/jetbrains/kotlin/idea/run/KotlinConsoleFilterTest.kt b/idea/tests/org/jetbrains/kotlin/idea/run/KotlinConsoleFilterTest.kt index f6ee7c9a655..341d2ed23a9 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/run/KotlinConsoleFilterTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/run/KotlinConsoleFilterTest.kt @@ -26,7 +26,8 @@ class KotlinConsoleFilterTest : KotlinLightCodeInsightFixtureTestCase() { fun testLinuxPath() { val filter = KotlinConsoleFilter(project, GlobalSearchScope.allScope(project)) - val line = """e: /Users/Work/app-web/src/main/kotlin/services/teamDirectory/NewOrEditTeamPageDescriptor.kt: (58, 52): The boolean literal does not conform to the expected type TeamMemberBuilder.() -> Unit""" + val line = + """e: /Users/Work/app-web/src/main/kotlin/services/teamDirectory/NewOrEditTeamPageDescriptor.kt: (58, 52): The boolean literal does not conform to the expected type TeamMemberBuilder.() -> Unit""" val result = filter.applyFilter(line, line.length)!! val resultItem = result.resultItems.single() assertEquals(3, resultItem.getHighlightStartOffset()) diff --git a/idea/tests/org/jetbrains/kotlin/idea/run/RunConfigurationTest.kt b/idea/tests/org/jetbrains/kotlin/idea/run/RunConfigurationTest.kt index 9b5281fb5b0..87c4ccab149 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/run/RunConfigurationTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/run/RunConfigurationTest.kt @@ -16,7 +16,6 @@ import com.intellij.psi.PsiComment import com.intellij.psi.PsiManager import com.intellij.refactoring.RefactoringFactory import com.intellij.testFramework.MapDataContext -import com.intellij.testFramework.PsiTestUtil import org.jetbrains.kotlin.checkers.languageVersionSettingsFromText import org.jetbrains.kotlin.config.LanguageVersionSettingsImpl import org.jetbrains.kotlin.idea.MainFunctionDetector @@ -56,7 +55,9 @@ class RunConfigurationTest : AbstractRunConfigurationTest() { fun functionVisitor(function: KtNamedFunction) { val file = function.containingKtFile - val options = function.bodyExpression?.allChildren?.filterIsInstance()?.map { it.text.trim().replace("//", "").trim() }?.filter { it.isNotBlank() }?.toList() ?: emptyList() + val options = + function.bodyExpression?.allChildren?.filterIsInstance()?.map { it.text.trim().replace("//", "").trim() } + ?.filter { it.isNotBlank() }?.toList() ?: emptyList() if (options.isNotEmpty()) { val assertIsMain = "yes" in options val assertIsNotMain = "no" in options @@ -83,7 +84,9 @@ class RunConfigurationTest : AbstractRunConfigurationTest() { } else { try { createConfigurationFromMain(function.fqName?.asString()!!).checkConfiguration() - fail("$file: configuration for function ${function.fqName?.asString()} at least shouldn't pass checkConfiguration()") + fail( + "$file: configuration for function ${function.fqName?.asString()} at least shouldn't pass checkConfiguration()" + ) } catch (expected: Throwable) { } @@ -123,7 +126,8 @@ class RunConfigurationTest : AbstractRunConfigurationTest() { ModuleRootModificationUtil.setModuleSdk(moduleWithDependency, testProjectJdk) val moduleWithDependencySrcDir = configureModule( - moduleDirPath("moduleWithDependency"), moduleWithDependencyDir, configModule = moduleWithDependency).srcOutputDir + moduleDirPath("moduleWithDependency"), moduleWithDependencyDir, configModule = moduleWithDependency + ).srcOutputDir ModuleRootModificationUtil.addDependency(moduleWithDependency, module) @@ -220,34 +224,34 @@ class RunConfigurationTest : AbstractRunConfigurationTest() { val testFile = PsiManager.getInstance(getTestProject()).findFile(srcDir.findFileByRelativePath("test.kt")!!)!! testFile.accept( - object : KtTreeVisitorVoid() { - override fun visitComment(comment: PsiComment) { - val declaration = comment.getStrictParentOfType()!! - val text = comment.text ?: return - if (!text.startsWith(RUN_PREFIX)) return + object : KtTreeVisitorVoid() { + override fun visitComment(comment: PsiComment) { + val declaration = comment.getStrictParentOfType()!! + val text = comment.text ?: return + if (!text.startsWith(RUN_PREFIX)) return - val expectedClass = text.substring(RUN_PREFIX.length).trim() - if (expectedClass.isNotEmpty()) expectedClasses.add(expectedClass) + val expectedClass = text.substring(RUN_PREFIX.length).trim() + if (expectedClass.isNotEmpty()) expectedClasses.add(expectedClass) - val dataContext = MapDataContext() - dataContext.put(Location.DATA_KEY, PsiLocation(getTestProject(), declaration)) - val context = ConfigurationContext.getFromContext(dataContext) - val actualClass = (context.configuration?.configuration as? KotlinRunConfiguration)?.runClass - if (actualClass != null) { - actualClasses.add(actualClass) - } + val dataContext = MapDataContext() + dataContext.put(Location.DATA_KEY, PsiLocation(getTestProject(), declaration)) + val context = ConfigurationContext.getFromContext(dataContext) + val actualClass = (context.configuration?.configuration as? KotlinRunConfiguration)?.runClass + if (actualClass != null) { + actualClasses.add(actualClass) } } + } ) assertEquals(expectedClasses, actualClasses) - } - finally { + } finally { ConfigLibraryUtil.unConfigureKotlinRuntimeAndSdk(createModuleResult.module, mockJdk()) } } private fun createConfigurationFromMain(mainFqn: String): KotlinRunConfiguration { - val mainFunction = KotlinTopLevelFunctionFqnNameIndex.getInstance().get(mainFqn, getTestProject(), getTestProject().allScope()).first() + val mainFunction = + KotlinTopLevelFunctionFqnNameIndex.getInstance().get(mainFqn, getTestProject(), getTestProject().allScope()).first() return createConfigurationFromElement(mainFunction) as KotlinRunConfiguration } diff --git a/idea/tests/org/jetbrains/kotlin/idea/run/StandaloneScriptRunConfigurationTest.kt b/idea/tests/org/jetbrains/kotlin/idea/run/StandaloneScriptRunConfigurationTest.kt index 03f7b8a8681..9a696f58588 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/run/StandaloneScriptRunConfigurationTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/run/StandaloneScriptRunConfigurationTest.kt @@ -134,10 +134,10 @@ class StandaloneScriptRunConfigurationTest : KotlinCodeInsightTestCase() { ActionRunner.runInsideWriteAction { VfsUtil.createDirectoryIfMissing(scriptFile.virtualFile.parent, "dest") } MoveFilesOrDirectoriesProcessor( - project, - arrayOf(scriptFile), - JavaPsiFacade.getInstance(project).findPackage("dest")!!.directories[0], - false, true, null, null + project, + arrayOf(scriptFile), + JavaPsiFacade.getInstance(project).findPackage("dest")!!.directories[0], + false, true, null, null ).run() } diff --git a/idea/tests/org/jetbrains/kotlin/idea/run/runConfigurationTestUtil.kt b/idea/tests/org/jetbrains/kotlin/idea/run/runConfigurationTestUtil.kt index fef7b30258c..845650fd48f 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/run/runConfigurationTestUtil.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/run/runConfigurationTestUtil.kt @@ -30,7 +30,8 @@ import org.jetbrains.kotlin.idea.util.application.runWriteAction import org.junit.Assert fun getJavaRunParameters(configuration: RunConfiguration): JavaParameters { - val state = configuration.getState(MockExecutor, ExecutionEnvironmentBuilder.create(configuration.project, MockExecutor, MockProfile).build()) + val state = + configuration.getState(MockExecutor, ExecutionEnvironmentBuilder.create(configuration.project, MockExecutor, MockProfile).build()) Assert.assertNotNull(state) Assert.assertTrue(state is JavaCommandLine) diff --git a/idea/tests/org/jetbrains/kotlin/idea/script/AbstractScriptConfigurationLoadingTest.kt b/idea/tests/org/jetbrains/kotlin/idea/script/AbstractScriptConfigurationLoadingTest.kt index 460c6869b71..377e4542979 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/script/AbstractScriptConfigurationLoadingTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/script/AbstractScriptConfigurationLoadingTest.kt @@ -28,6 +28,7 @@ abstract class AbstractScriptConfigurationLoadingTest : AbstractScriptConfigurat companion object { private var occurredLoadings = 0 private var currentLoadingScriptConfigurationCallback: (() -> Unit)? = null + @JvmStatic @Suppress("unused") fun loadingScriptConfigurationCallback() { diff --git a/idea/tests/org/jetbrains/kotlin/idea/script/AbstractScriptConfigurationTest.kt b/idea/tests/org/jetbrains/kotlin/idea/script/AbstractScriptConfigurationTest.kt index 35939f91c5d..acf5d67bc72 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/script/AbstractScriptConfigurationTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/script/AbstractScriptConfigurationTest.kt @@ -51,6 +51,7 @@ import kotlin.script.experimental.api.ScriptDiagnostic private val validKeys = setOf("javaHome", "sources", "classpath", "imports", "template-classes-names") private const val useDefaultTemplate = "// DEPENDENCIES:" private const val templatesSettings = "// TEMPLATES: " + // some bugs can only be reproduced when some module and script have intersecting library dependencies private const val configureConflictingModule = "// CONFLICTING_MODULE" diff --git a/idea/tests/org/jetbrains/kotlin/idea/search/PsiBasedClassResolverTest.kt b/idea/tests/org/jetbrains/kotlin/idea/search/PsiBasedClassResolverTest.kt index c0182bb3ba1..c450506558f 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/search/PsiBasedClassResolverTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/search/PsiBasedClassResolverTest.kt @@ -96,8 +96,7 @@ class PsiBasedClassResolverTest : KotlinLightCodeInsightFixtureTestCaseBase() { private fun doTest(fileText: String, marker: String = "@Test"): Boolean? { val resolver = PsiBasedClassResolver("org.junit.Test") resolver.addConflict("org.testng.Test") - val file = PsiFileFactory.getInstance(project).createFileFromText("foo.kt", KotlinFileType.INSTANCE, - fileText) as KtFile + val file = PsiFileFactory.getInstance(project).createFileFromText("foo.kt", KotlinFileType.INSTANCE, fileText) as KtFile val index = fileText.indexOf(marker) val ref = file.findElementAt(index + marker.indexOf("Test"))!!.getParentOfType(false)!! val canBeTargetReference = resolver.canBeTargetReference(ref) diff --git a/idea/tests/org/jetbrains/kotlin/idea/slicer/AbstractSlicerTest.kt b/idea/tests/org/jetbrains/kotlin/idea/slicer/AbstractSlicerTest.kt index 5ca504d1db6..49505bdfd6d 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/slicer/AbstractSlicerTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/slicer/AbstractSlicerTest.kt @@ -37,7 +37,7 @@ abstract class AbstractSlicerTest : KotlinLightCodeInsightFixtureTestCase() { } companion object { - private val SliceNode.sortedChildren : List + private val SliceNode.sortedChildren: List get() = children.sortedBy { it.value.element?.startOffset ?: -1 } @JvmStatic @@ -76,11 +76,11 @@ abstract class AbstractSlicerTest : KotlinLightCodeInsightFixtureTestCase() { if (usage is KotlinSliceUsage) { append("[LAMBDA] ".repeat(usage.lambdaLevel)) } - chunks.slice(1..chunks.size - 1).joinTo( - this, - separator = "", - prefix = if (isDuplicated) "DUPLICATE: " else "", - postfix = "\n" + chunks.slice(1 until chunks.size).joinTo( + this, + separator = "", + prefix = if (isDuplicated) "DUPLICATE: " else "", + postfix = "\n" ) { it.render() } } } diff --git a/idea/tests/org/jetbrains/kotlin/idea/structureView/KotlinFileStructureTestBase.kt b/idea/tests/org/jetbrains/kotlin/idea/structureView/KotlinFileStructureTestBase.kt index 55ff1566fdb..f440e2ae527 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/structureView/KotlinFileStructureTestBase.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/structureView/KotlinFileStructureTestBase.kt @@ -21,7 +21,7 @@ abstract class KotlinFileStructureTestBase : KotlinLightCodeInsightFixtureTestCa protected abstract val fileExtension: String - open protected val treeFileName: String + protected open val treeFileName: String get() = getFileName("tree") override fun setUp() { @@ -37,14 +37,13 @@ abstract class KotlinFileStructureTestBase : KotlinLightCodeInsightFixtureTestCa try { Disposer.dispose(popupFixture) myPopupFixture = null - } - finally { + } finally { super.tearDown() } } protected fun getFileName(ext: String): String { - return getTestName(false) + if (StringUtil.isEmpty(ext)) "" else "." + ext + return getTestName(false) + if (StringUtil.isEmpty(ext)) "" else ".$ext" } @Suppress("unused") @@ -67,7 +66,7 @@ abstract class KotlinFileStructureTestBase : KotlinLightCodeInsightFixtureTestCa val printInfo = Queryable.PrintInfo(arrayOf("text"), arrayOf("location")) TreeUtil.expandAll(popupFixture.tree) { val popupText = StructureViewUtil.print(popupFixture.tree, false, printInfo, null).trim { it <= ' ' } - UsefulTestCase.assertSameLinesWithFile(testDataPath + "/" + treeFileName, popupText) + UsefulTestCase.assertSameLinesWithFile("$testDataPath/$treeFileName", popupText) } } } \ No newline at end of file diff --git a/idea/tests/org/jetbrains/kotlin/idea/stubs/AbstractMultiHighlightingTest.kt b/idea/tests/org/jetbrains/kotlin/idea/stubs/AbstractMultiHighlightingTest.kt index 634a43ca8f6..5948b82f5fb 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/stubs/AbstractMultiHighlightingTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/stubs/AbstractMultiHighlightingTest.kt @@ -33,7 +33,7 @@ abstract class AbstractMultiHighlightingTest : AbstractMultiModuleTest() { //to initialize caches if (!DumbService.isDumb(project)) { CacheManager.SERVICE.getInstance(myProject) - .getFilesWithWord("XXX", UsageSearchContext.IN_COMMENTS, GlobalSearchScope.allScope(myProject), true) + .getFilesWithWord("XXX", UsageSearchContext.IN_COMMENTS, GlobalSearchScope.allScope(myProject), true) } val infos = doHighlighting() diff --git a/idea/tests/org/jetbrains/kotlin/idea/stubs/AbstractStubBuilderTest.kt b/idea/tests/org/jetbrains/kotlin/idea/stubs/AbstractStubBuilderTest.kt index 7b72bfbc91f..32123b39b27 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/stubs/AbstractStubBuilderTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/stubs/AbstractStubBuilderTest.kt @@ -32,17 +32,15 @@ abstract class AbstractStubBuilderTest : KotlinLightCodeInsightFixtureTestCase() // Nodes are stored in form "NodeType:Node" and have too many repeating information for Kotlin stubs // Remove all repeating information (See KotlinStubBaseImpl.toString()) - return treeStr - .lines().map { - if (it.contains(STUB_TO_STRING_PREFIX)) { - it.takeWhile { it.isWhitespace() } + it.substringAfter("KotlinStub$") - } - else { - it - } + return treeStr.lines().map { + if (it.contains(STUB_TO_STRING_PREFIX)) { + it.takeWhile { it.isWhitespace() } + it.substringAfter("KotlinStub$") + } else { + it } - .joinToString(separator = "\n") - .replace(", [", "[") + } + .joinToString(separator = "\n") + .replace(", [", "[") } } } diff --git a/idea/tests/org/jetbrains/kotlin/idea/stubs/DebugTextByStubTest.kt b/idea/tests/org/jetbrains/kotlin/idea/stubs/DebugTextByStubTest.kt index bf5e356db17..b53a9e5efc3 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/stubs/DebugTextByStubTest.kt +++ b/idea/tests/org/jetbrains/kotlin/idea/stubs/DebugTextByStubTest.kt @@ -173,22 +173,27 @@ class DebugTextByStubTest : LightCodeInsightFixtureTestCase() { fun testClassInitializer() { val tree = createStubTree("class A {\n init {} }") - val initializer = tree.findChildStubByType(KtStubElementTypes.CLASS)!!.findChildStubByType(KtStubElementTypes.CLASS_BODY)!! - .findChildStubByType(KtStubElementTypes.CLASS_INITIALIZER) + val initializer = + tree.findChildStubByType(KtStubElementTypes.CLASS)!!.findChildStubByType(KtStubElementTypes.CLASS_BODY)!!.findChildStubByType( + KtStubElementTypes.CLASS_INITIALIZER + ) assertEquals("initializer in STUB: class A", KtClassInitializer(initializer as KotlinPlaceHolderStub).getDebugText()) } fun testClassObject() { val tree = createStubTree("class A { companion object Def {} }") - val companionObject = tree.findChildStubByType(KtStubElementTypes.CLASS)!!.findChildStubByType(KtStubElementTypes.CLASS_BODY)!! - .findChildStubByType(KtStubElementTypes.OBJECT_DECLARATION) + val companionObject = + tree.findChildStubByType(KtStubElementTypes.CLASS)!!.findChildStubByType(KtStubElementTypes.CLASS_BODY)!!.findChildStubByType( + KtStubElementTypes.OBJECT_DECLARATION + ) assertEquals("STUB: companion object Def", KtObjectDeclaration(companionObject as KotlinObjectStub).getDebugText()) } fun testPropertyAccessors() { val tree = createStubTree("var c: Int\nget() = 3\nset(i: Int) {}") val propertyStub = tree.findChildStubByType(KtStubElementTypes.PROPERTY)!! - val accessors = propertyStub.getChildrenByType(KtStubElementTypes.PROPERTY_ACCESSOR, KtStubElementTypes.PROPERTY_ACCESSOR.arrayFactory) + val accessors = + propertyStub.getChildrenByType(KtStubElementTypes.PROPERTY_ACCESSOR, KtStubElementTypes.PROPERTY_ACCESSOR.arrayFactory) assertEquals("getter for STUB: var c: Int", accessors[0].getDebugText()) assertEquals("setter for STUB: var c: Int", accessors[1].getDebugText()) } diff --git a/idea/tests/org/jetbrains/kotlin/projectModel/Parser.kt b/idea/tests/org/jetbrains/kotlin/projectModel/Parser.kt index f263419bb83..2e157913a8c 100644 --- a/idea/tests/org/jetbrains/kotlin/projectModel/Parser.kt +++ b/idea/tests/org/jetbrains/kotlin/projectModel/Parser.kt @@ -7,8 +7,8 @@ package org.jetbrains.kotlin.projectModel import com.intellij.util.text.nullize import org.jetbrains.kotlin.platform.CommonPlatforms -import org.jetbrains.kotlin.platform.jvm.JvmPlatforms import org.jetbrains.kotlin.platform.TargetPlatform +import org.jetbrains.kotlin.platform.jvm.JvmPlatforms import java.io.File import java.io.InputStreamReader import java.io.Reader @@ -128,7 +128,9 @@ open class ProjectStructureParser(private val projectRoot: File) { if (it == "JVM") JvmPlatforms.defaultJvmPlatform.single() else - platformsByPlatformName[it] ?: error("Unknown platform $it. Available platforms: ${platformsByPlatformName.keys.joinToString()}") + platformsByPlatformName[it] ?: error( + "Unknown platform $it. Available platforms: ${platformsByPlatformName.keys.joinToString()}" + ) }.toSet() return TargetPlatform(platforms) diff --git a/idea/tests/org/jetbrains/kotlin/psi/AbstractInjectionTest.kt b/idea/tests/org/jetbrains/kotlin/psi/AbstractInjectionTest.kt index b657311e361..568967a968b 100644 --- a/idea/tests/org/jetbrains/kotlin/psi/AbstractInjectionTest.kt +++ b/idea/tests/org/jetbrains/kotlin/psi/AbstractInjectionTest.kt @@ -32,16 +32,18 @@ abstract class AbstractInjectionTest : KotlinLightCodeInsightFixtureTestCase() { } data class ShredInfo( - val range: TextRange, - val hostRange: TextRange, - val prefix: String = "", - val suffix: String = "") { + val range: TextRange, + val hostRange: TextRange, + val prefix: String = "", + val suffix: String = "" + ) { } protected fun doInjectionPresentTest( - @Language("kotlin") text: String, @Language("Java") javaText: String? = null, - languageId: String? = null, unInjectShouldBePresent: Boolean = true, - shreds: List? = null) { + @Language("kotlin") text: String, @Language("Java") javaText: String? = null, + languageId: String? = null, unInjectShouldBePresent: Boolean = true, + shreds: List? = null + ) { if (javaText != null) { myFixture.configureByText("${getTestName(true)}.java", javaText.trimIndent()) } @@ -53,22 +55,24 @@ abstract class AbstractInjectionTest : KotlinLightCodeInsightFixtureTestCase() { if (shreds != null) { val actualShreds = SmartList().apply { val host = InjectedLanguageManager.getInstance(project).getInjectionHost(file.viewProvider) - InjectedLanguageManager.getInstance(project).enumerate(host, { _, placesInFile -> + InjectedLanguageManager.getInstance(project).enumerate(host) { _, placesInFile -> addAll(placesInFile.map { ShredInfo(it.range, it.rangeInsideHost, it.prefix, it.suffix) }) - }) + } } assertOrderedEquals( - actualShreds.sortedBy { it.range.startOffset }, - shreds.sortedBy { it.range.startOffset }) + actualShreds.sortedBy { it.range.startOffset }, + shreds.sortedBy { it.range.startOffset }) } } protected fun assertInjectionPresent(languageId: String?, unInjectShouldBePresent: Boolean) { - TestCase.assertFalse("Injection action is available. There's probably no injection at caret place", - InjectLanguageAction().isAvailable(project, myFixture.editor, myFixture.file)) + TestCase.assertFalse( + "Injection action is available. There's probably no injection at caret place", + InjectLanguageAction().isAvailable(project, myFixture.editor, myFixture.file) + ) if (languageId != null) { val injectedFile = (editor as? EditorWindow)?.injectedFile @@ -76,16 +80,20 @@ abstract class AbstractInjectionTest : KotlinLightCodeInsightFixtureTestCase() { } if (unInjectShouldBePresent) { - TestCase.assertTrue("UnInjection action is not available. There's no injection at caret place or some other troubles.", - UnInjectLanguageAction().isAvailable(project, myFixture.editor, myFixture.file)) + TestCase.assertTrue( + "UnInjection action is not available. There's no injection at caret place or some other troubles.", + UnInjectLanguageAction().isAvailable(project, myFixture.editor, myFixture.file) + ) } } protected fun assertNoInjection(@Language("kotlin") text: String) { myFixture.configureByText("${getTestName(true)}.kt", text.trimIndent()) - TestCase.assertTrue("Injection action is not available. There's probably some injection but nothing was expected.", - InjectLanguageAction().isAvailable(project, myFixture.editor, myFixture.file)) + TestCase.assertTrue( + "Injection action is not available. There's probably some injection but nothing was expected.", + InjectLanguageAction().isAvailable(project, myFixture.editor, myFixture.file) + ) } protected fun doRemoveInjectionTest(@Language("kotlin") before: String, @Language("kotlin") after: String) { @@ -112,8 +120,7 @@ abstract class AbstractInjectionTest : KotlinLightCodeInsightFixtureTestCase() { myFixture.configureByText("${getTestName(true)}.kt", before.trimIndent()) InjectLanguageAction.invokeImpl(project, myFixture.editor, myFixture.file, injectable) myFixture.checkResult(after.trimIndent()) - } - finally { + } finally { configuration.isSourceModificationAllowed = allowed } } diff --git a/idea/tests/org/jetbrains/kotlin/psi/KotlinInjectionTest.kt b/idea/tests/org/jetbrains/kotlin/psi/KotlinInjectionTest.kt index aee5a2628fb..95c5dbf64b2 100644 --- a/idea/tests/org/jetbrains/kotlin/psi/KotlinInjectionTest.kt +++ b/idea/tests/org/jetbrains/kotlin/psi/KotlinInjectionTest.kt @@ -19,94 +19,100 @@ import org.junit.runner.RunWith @RunWith(JUnit3WithIdeaConfigurationRunner::class) class KotlinInjectionTest : AbstractInjectionTest() { fun testInjectionOnJavaPredefinedMethodWithAnnotation() = doInjectionPresentTest( - """ + """ val test1 = java.util.regex.Pattern.compile("pattern") """, - RegExpLanguage.INSTANCE.id, - unInjectShouldBePresent = false + RegExpLanguage.INSTANCE.id, + unInjectShouldBePresent = false ) fun testInjectionOnJavaCustomInjectionWithAnnotation() { val customInjection = BaseInjection("java") customInjection.injectedLanguageId = HTMLLanguage.INSTANCE.id val elementPattern = customInjection.compiler.createElementPattern( - """psiParameter().ofMethod(2, psiMethod().withName("replace").withParameters("int", "int", "java.lang.String").definedInClass("java.lang.StringBuilder"))""", - "HTML temp rule") + """psiParameter().ofMethod(2, psiMethod().withName("replace").withParameters("int", "int", "java.lang.String").definedInClass("java.lang.StringBuilder"))""", + "HTML temp rule" + ) customInjection.setInjectionPlaces(InjectionPlace(elementPattern, true)) try { Configuration.getInstance().replaceInjections(listOf(customInjection), listOf(), true) doInjectionPresentTest( - """ + """ val stringBuilder = StringBuilder().replace(0, 0, "") """, - HTMLLanguage.INSTANCE.id, - unInjectShouldBePresent = false + HTMLLanguage.INSTANCE.id, + unInjectShouldBePresent = false ) - } - finally { + } finally { Configuration.getInstance().replaceInjections(listOf(), listOf(customInjection), true) } } fun testInjectionWithCommentOnProperty() = doInjectionPresentTest( - """ + """ //language=file-reference val test = "simple" - """) + """ + ) fun testInjectionWithUsageOnReceiverWithRuntime() = doInjectionPresentTest( - """ + """ val test = "some" fun foo() = test.toRegex() """, - languageId = RegExpLanguage.INSTANCE.id, unInjectShouldBePresent = false) + languageId = RegExpLanguage.INSTANCE.id, unInjectShouldBePresent = false + ) fun testInjectionWithUsageInParameterWithRuntime() = doInjectionPresentTest( - """ + """ val test = "some" fun foo() = Regex(test) """, - languageId = RegExpLanguage.INSTANCE.id, unInjectShouldBePresent = false) + languageId = RegExpLanguage.INSTANCE.id, unInjectShouldBePresent = false + ) fun testNoInjectionThoughSeveralAssignmentsWithRuntime() = assertNoInjection( - """ + """ val first = "some" val test = first fun foo() = Regex(test) - """) + """ + ) fun testInjectionWithMultipleCommentsOnFun() = doInjectionPresentTest( - """ + """ // Some comment // Other comment //language=file-reference fun test() = "simple" - """) + """ + ) fun testInjectionWithAnnotationOnPropertyWithAnnotation() = doInjectionPresentTest( - """ + """ @org.intellij.lang.annotations.Language("file-reference") val test = "simple" - """) + """ + ) fun testInjectWithCommentOnProperty() = doFileReferenceInjectTest( - """ + """ val test = "simple" """, - """ + """ //language=file-reference val test = "simple" """ ) fun testInjectWithCommentOnCommentedProperty() = doFileReferenceInjectTest( - """ + """ // Hello val test = "simple" """, - """ + """ // Hello //language=file-reference val test = "simple" @@ -114,13 +120,13 @@ class KotlinInjectionTest : AbstractInjectionTest() { ) fun testInjectWithCommentOnPropertyWithKDoc() = doFileReferenceInjectTest( - """ + """ /** * Hi */ val test = "simple" """, - """ + """ /** * Hi */ @@ -130,12 +136,12 @@ class KotlinInjectionTest : AbstractInjectionTest() { ) fun testInjectWithCommentOnExpression() = doFileReferenceInjectTest( - """ + """ fun test() { "" } """, - """ + """ fun test() { //language=file-reference "" @@ -144,12 +150,12 @@ class KotlinInjectionTest : AbstractInjectionTest() { ) fun testInjectWithCommentOnDeepExpression() = doFileReferenceInjectTest( - """ + """ fun test() { "" + "" } """, - """ + """ fun test() { "" + "" } @@ -157,10 +163,10 @@ class KotlinInjectionTest : AbstractInjectionTest() { ) fun testInjectOnPropertyWithAnnotation() = doFileReferenceInjectTest( - """ + """ val test = "simple" """, - """ + """ import org.intellij.lang.annotations.Language @Language("file-reference") @@ -169,12 +175,12 @@ class KotlinInjectionTest : AbstractInjectionTest() { ) fun testInjectWithOnExpressionWithAnnotation() = doFileReferenceInjectTest( - """ + """ fun test() { "" } """, - """ + """ fun test() { //language=file-reference "" @@ -185,13 +191,13 @@ class KotlinInjectionTest : AbstractInjectionTest() { // TODO: add test for non-default language annotation fun testRemoveInjectionWithAnnotation() = doRemoveInjectionTest( - """ + """ import org.intellij.lang.annotations.Language @Language("file-reference") val test = "simple" """, - """ + """ import org.intellij.lang.annotations.Language val test = "simple" @@ -199,48 +205,48 @@ class KotlinInjectionTest : AbstractInjectionTest() { ) fun testRemoveInjectionWithComment() = doRemoveInjectionTest( - """ + """ //language=file-reference val test = "simple" """, - """ + """ val test = "simple" """ ) fun testRemoveInjectionWithCommentNotFirst() = doRemoveInjectionTest( - """ + """ // Some comment. To do a language injection, add a line comment language=some instruction. // language=file-reference val test = "simple" """, - """ + """ // Some comment. To do a language injection, add a line comment language=some instruction. val test = "simple" """ ) fun testRemoveInjectionWithCommentAfterKDoc() = doRemoveInjectionTest( - """ + """ /**Property*/ // language=file-reference val test = "simple" """, - """ + """ /**Property*/ val test = "simple" """ ) fun testRemoveInjectionWithCommentInExpression() = doRemoveInjectionTest( - """ + """ fun test() { // This is my favorite part // language=RegExp "something" } """, - """ + """ fun test() { // This is my favorite part "something" @@ -249,7 +255,7 @@ class KotlinInjectionTest : AbstractInjectionTest() { ) fun testInjectionWithUsageInFunctionWithMarkedParameterWithAnnotation() = doInjectionPresentTest( - """ + """ import org.intellij.lang.annotations.Language val v = "some" @@ -258,151 +264,156 @@ class KotlinInjectionTest : AbstractInjectionTest() { fun other() { foo(v) } """, - languageId = HTMLLanguage.INSTANCE.id, unInjectShouldBePresent = false) + languageId = HTMLLanguage.INSTANCE.id, unInjectShouldBePresent = false + ) fun testInjectionOfCustomParameterWithAnnotation() = doInjectionPresentTest( - """ + """ import org.intellij.lang.annotations.Language fun foo(@Language("HTML") s: String) {} fun other() { foo("some") } """, - languageId = HTMLLanguage.INSTANCE.id, unInjectShouldBePresent = false) + languageId = HTMLLanguage.INSTANCE.id, unInjectShouldBePresent = false + ) fun testInjectionOfCustomParameterInConstructorWithAnnotation() = doInjectionPresentTest( - """ + """ import org.intellij.lang.annotations.Language class Test(@Language("HTML") val s: String) fun other() { Test("some") } """, - languageId = HTMLLanguage.INSTANCE.id, unInjectShouldBePresent = false) + languageId = HTMLLanguage.INSTANCE.id, unInjectShouldBePresent = false + ) fun testInjectionOfCustomParameterDefaultCallWithAnnotation() = doInjectionPresentTest( - """ + """ import org.intellij.lang.annotations.Language fun foo(@Language("HTML") s: String) {} fun other() { foo(s = "some") } """, - languageId = HTMLLanguage.INSTANCE.id, unInjectShouldBePresent = false) + languageId = HTMLLanguage.INSTANCE.id, unInjectShouldBePresent = false + ) fun testInjectionOfCustomParameterInJavaConstructorWithAnnotationWithAnnotation() = doInjectionPresentTest( - """ + """ fun bar() { Test("some") } """, - javaText = - """ + javaText = + """ import org.intellij.lang.annotations.Language; public class Test { public Test(@Language("HTML") String str) {} } """, - languageId = HTMLLanguage.INSTANCE.id, unInjectShouldBePresent = false + languageId = HTMLLanguage.INSTANCE.id, unInjectShouldBePresent = false ) fun testInjectionOfCustomParameterJavaWithAnnotation() = doInjectionPresentTest( - """ + """ fun bar() { Test.foo("some") } """, - javaText = - """ + javaText = + """ import org.intellij.lang.annotations.Language; public class Test { public static void foo(@Language("HTML") String str) {} } """, - languageId = HTMLLanguage.INSTANCE.id, unInjectShouldBePresent = false + languageId = HTMLLanguage.INSTANCE.id, unInjectShouldBePresent = false ) fun testInjectionOnInterpolationWithAnnotation() = doInjectionPresentTest( - """ + """ val b = 2 @org.intellij.lang.annotations.Language("HTML") val test = "simple${'$'}{b}.kt" """, - unInjectShouldBePresent = false, - shreds = listOf( - ShredInfo(range(0, 6), hostRange=range(1, 7)), - ShredInfo(range(6, 21), hostRange=range(11, 14), prefix="missingValue") - ) + unInjectShouldBePresent = false, + shreds = listOf( + ShredInfo(range(0, 6), hostRange = range(1, 7)), + ShredInfo(range(6, 21), hostRange = range(11, 14), prefix = "missingValue") + ) ) fun testInjectionOnInterpolatedStringWithComment() = doInjectionPresentTest( - """ + """ val some = 42 // language=HTML val test = "ml>${'$'}some" """, - languageId = HTMLLanguage.INSTANCE.id, unInjectShouldBePresent = false, - shreds = listOf( - ShredInfo(range(0, 6), hostRange = range(1, 7)), - ShredInfo(range(6, 17), hostRange = range(12, 19), prefix="some")) + languageId = HTMLLanguage.INSTANCE.id, unInjectShouldBePresent = false, + shreds = listOf( + ShredInfo(range(0, 6), hostRange = range(1, 7)), + ShredInfo(range(6, 17), hostRange = range(12, 19), prefix = "some") + ) ) fun testEditorShortShreadsInInterpolatedInjection() = doInjectionPresentTest( - """ + """ val s = 42 // language=TEXT val test = "${'$'}s text ${'$'}s${'$'}{s}${'$'}s text ${'$'}s" """, - languageId = PlainTextLanguage.INSTANCE.id, unInjectShouldBePresent = false, - shreds = listOf( - ShredInfo(range(0, 0), hostRange=range(1, 1)), - ShredInfo(range(0, 7), hostRange=range(3, 9), prefix="s"), - ShredInfo(range(7, 8), hostRange=range(11, 11), prefix="s"), - ShredInfo(range(8, 20), hostRange=range(15, 15), prefix="missingValue"), - ShredInfo(range(20, 27), hostRange=range(17, 23), prefix="s"), - ShredInfo(range(27, 28), hostRange=range(25, 25), prefix="s") - ) + languageId = PlainTextLanguage.INSTANCE.id, unInjectShouldBePresent = false, + shreds = listOf( + ShredInfo(range(0, 0), hostRange = range(1, 1)), + ShredInfo(range(0, 7), hostRange = range(3, 9), prefix = "s"), + ShredInfo(range(7, 8), hostRange = range(11, 11), prefix = "s"), + ShredInfo(range(8, 20), hostRange = range(15, 15), prefix = "missingValue"), + ShredInfo(range(20, 27), hostRange = range(17, 23), prefix = "s"), + ShredInfo(range(27, 28), hostRange = range(25, 25), prefix = "s") + ) ) fun testEditorLongShreadsInInterpolatedInjection() = doInjectionPresentTest( - """ + """ val s = 42 // language=TEXT val test = "${'$'}{s} text ${'$'}{s}${'$'}s${'$'}{s} text ${'$'}{s}" """, - languageId = PlainTextLanguage.INSTANCE.id, unInjectShouldBePresent = false, - shreds = listOf( - ShredInfo(range(0, 0), hostRange=range(1, 1)), - ShredInfo(range(0, 18), hostRange=range(5, 11), prefix="missingValue"), - ShredInfo(range(18, 30), hostRange=range(15, 15), prefix="missingValue"), - ShredInfo(range(30, 31), hostRange=range(17, 17), prefix="s"), - ShredInfo(range(31, 49), hostRange=range(21, 27), prefix="missingValue"), - ShredInfo(range(49, 61), hostRange=range(31, 31), prefix="missingValue") - ) + languageId = PlainTextLanguage.INSTANCE.id, unInjectShouldBePresent = false, + shreds = listOf( + ShredInfo(range(0, 0), hostRange = range(1, 1)), + ShredInfo(range(0, 18), hostRange = range(5, 11), prefix = "missingValue"), + ShredInfo(range(18, 30), hostRange = range(15, 15), prefix = "missingValue"), + ShredInfo(range(30, 31), hostRange = range(17, 17), prefix = "s"), + ShredInfo(range(31, 49), hostRange = range(21, 27), prefix = "missingValue"), + ShredInfo(range(49, 61), hostRange = range(31, 31), prefix = "missingValue") + ) ) fun testEditorShreadsWithEscapingInjection() = doInjectionPresentTest( - """ + """ // language=TEXT val test = "\rtext\ttext\n\t" """, - languageId = PlainTextLanguage.INSTANCE.id, unInjectShouldBePresent = false, - shreds = listOf( - ShredInfo(range(0, 12), hostRange=range(1, 17)) - ) + languageId = PlainTextLanguage.INSTANCE.id, unInjectShouldBePresent = false, + shreds = listOf( + ShredInfo(range(0, 12), hostRange = range(1, 17)) + ) ) fun testEditorShreadsInInterpolatedWithEscapingInjection() = doInjectionPresentTest( - """ + """ val s = 1 // language=TEXT val test = "\r${'$'}s text${'$'}s\ttext\n\t" """, - languageId = PlainTextLanguage.INSTANCE.id, unInjectShouldBePresent = false, - shreds = listOf( - ShredInfo(range(0, 1), hostRange=range(1, 3)), - ShredInfo(range(1, 7), hostRange=range(5, 10), prefix="s"), - ShredInfo(range(7, 15), hostRange=range(12, 22), prefix="s") - ) + languageId = PlainTextLanguage.INSTANCE.id, unInjectShouldBePresent = false, + shreds = listOf( + ShredInfo(range(0, 1), hostRange = range(1, 3)), + ShredInfo(range(1, 7), hostRange = range(5, 10), prefix = "s"), + ShredInfo(range(7, 15), hostRange = range(12, 22), prefix = "s") + ) ) fun testSuffixPrefixWithAnnotation() = doInjectionPresentTest( @@ -411,7 +422,7 @@ class KotlinInjectionTest : AbstractInjectionTest() { val test = "def" """, languageId = PlainTextLanguage.INSTANCE.id, unInjectShouldBePresent = false, - shreds = listOf(ShredInfo(range(0, 9), hostRange=range(1, 4), prefix = "abc", suffix = "ghi")) + shreds = listOf(ShredInfo(range(0, 9), hostRange = range(1, 4), prefix = "abc", suffix = "ghi")) ) fun testSuffixPrefixWithCallWithAnnotation() = doInjectionPresentTest( @@ -432,7 +443,7 @@ class KotlinInjectionTest : AbstractInjectionTest() { val test = "def" """, languageId = PlainTextLanguage.INSTANCE.id, unInjectShouldBePresent = false, - shreds = listOf(ShredInfo(range(0, 9), hostRange=range(1, 4), prefix = "abc", suffix = "ghi")) + shreds = listOf(ShredInfo(range(0, 9), hostRange = range(1, 4), prefix = "abc", suffix = "ghi")) ) fun testSuffixAfterInterpolationInMultiline() = doInjectionPresentTest( @@ -445,20 +456,22 @@ class KotlinInjectionTest : AbstractInjectionTest() { """, languageId = PlainTextLanguage.INSTANCE.id, unInjectShouldBePresent = false, shreds = listOf( - ShredInfo(range(0, 3), hostRange = range(3,6), prefix = "", suffix = ""), - ShredInfo(range(3, 23), hostRange = range(13,16), prefix= "missingValue", suffix = "check") + ShredInfo(range(0, 3), hostRange = range(3, 6), prefix = "", suffix = ""), + ShredInfo(range(3, 23), hostRange = range(13, 16), prefix = "missingValue", suffix = "check") ) ) fun testJavaAnnotationsPattern() { - myFixture.addClass(""" + myFixture.addClass( + """ @interface Matches { String value(); } - """) + """ + ) doAnnotationInjectionTest( - injectedLanguage = RegExpLanguage.INSTANCE.id, - pattern = """psiMethod().withName("value").withParameters().definedInClass("Matches")""", - kotlinCode = """ + injectedLanguage = RegExpLanguage.INSTANCE.id, + pattern = """psiMethod().withName("value").withParameters().definedInClass("Matches")""", + kotlinCode = """ @Matches("[A-Z][a-z]+") val name = "John" """ @@ -467,10 +480,10 @@ class KotlinInjectionTest : AbstractInjectionTest() { fun testKotlinAnnotationsPattern() { doAnnotationInjectionTest( - patternLanguage = "kotlin", - injectedLanguage = RegExpLanguage.INSTANCE.id, - pattern = """kotlinParameter().ofFunction(0, kotlinFunction().withName("Matches").definedInClass("Matches"))""", - kotlinCode = """ + patternLanguage = "kotlin", + injectedLanguage = RegExpLanguage.INSTANCE.id, + pattern = """kotlinParameter().ofFunction(0, kotlinFunction().withName("Matches").definedInClass("Matches"))""", + kotlinCode = """ annotation class Matches(val pattern: String) @Matches("[A-Z][a-z]+") @@ -496,17 +509,17 @@ class KotlinInjectionTest : AbstractInjectionTest() { fun testKotlinAnnotationsPatternNamed() { doAnnotationInjectionTest( - patternLanguage = "kotlin", - injectedLanguage = RegExpLanguage.INSTANCE.id, - pattern = """kotlinParameter().ofFunction(0, kotlinFunction().withName("Matches").definedInClass("Matches"))""", - kotlinCode = """ + patternLanguage = "kotlin", + injectedLanguage = RegExpLanguage.INSTANCE.id, + pattern = """kotlinParameter().ofFunction(0, kotlinFunction().withName("Matches").definedInClass("Matches"))""", + kotlinCode = """ annotation class Matches(val pattern: String) @Matches(pattern = "[A-Z][a-z]+") val name = "John" """ - ) - } + ) + } fun testKotlinAnnotationsPatternNamedArrayLiteral() { doAnnotationInjectionTest( @@ -548,76 +561,85 @@ class KotlinInjectionTest : AbstractInjectionTest() { ) doAnnotationInjectionTest( - injectedLanguage = HTMLLanguage.INSTANCE.id, - pattern = """psiMethod().withName("value").withParameters().definedInClass("InHtml")""", - kotlinCode = """ + injectedLanguage = HTMLLanguage.INSTANCE.id, + pattern = """psiMethod().withName("value").withParameters().definedInClass("InHtml")""", + kotlinCode = """ @InHtml("l>") fun foo() { } """, - additionalAsserts = { assertSameElements(myFixture.complete(CompletionType.BASIC).flatMap { it.allLookupStrings }, "html") } + additionalAsserts = { assertSameElements(myFixture.complete(CompletionType.BASIC).flatMap { it.allLookupStrings }, "html") } ) } fun testInjectionInJavaAnnotationWithNamedParam() { - myFixture.addClass(""" + myFixture.addClass( + """ package myinjection; @interface InHtml { String html(); } - """) + """ + ) doAnnotationInjectionTest( - injectedLanguage = HTMLLanguage.INSTANCE.id, - pattern = """psiMethod().withName("html").withParameters().definedInClass("myinjection.InHtml")""", - kotlinCode = """ + injectedLanguage = HTMLLanguage.INSTANCE.id, + pattern = """psiMethod().withName("html").withParameters().definedInClass("myinjection.InHtml")""", + kotlinCode = """ import myinjection.InHtml @InHtml(html = "l>") fun foo() { } - """) + """ + ) } fun testInjectionInJavaAnnotationWithNamedParamArray() { - myFixture.addClass(""" + myFixture.addClass( + """ package myinjection; @interface InHtml { String[] htmls(); } - """) + """ + ) doAnnotationInjectionTest( - injectedLanguage = HTMLLanguage.INSTANCE.id, - pattern = """psiMethod().withName("htmls").withParameters().definedInClass("myinjection.InHtml")""", - kotlinCode = """ + injectedLanguage = HTMLLanguage.INSTANCE.id, + pattern = """psiMethod().withName("htmls").withParameters().definedInClass("myinjection.InHtml")""", + kotlinCode = """ import myinjection.InHtml @InHtml(htmls = arrayOf("
    ", "l>")) fun foo() { } - """) + """ + ) } fun testInjectionInJavaAnnotationWithNamedParamLiterals() { - myFixture.addClass(""" + myFixture.addClass( + """ package myinjection; @interface InHtml { String[] htmls(); } - """) + """ + ) doAnnotationInjectionTest( - injectedLanguage = HTMLLanguage.INSTANCE.id, - pattern = """psiMethod().withName("htmls").withParameters().definedInClass("myinjection.InHtml")""", - kotlinCode = """ + injectedLanguage = HTMLLanguage.INSTANCE.id, + pattern = """psiMethod().withName("htmls").withParameters().definedInClass("myinjection.InHtml")""", + kotlinCode = """ import myinjection.InHtml @InHtml(htmls = ["
    ", "l>"]) fun foo() { } - """) + """ + ) } fun testInjectionInJavaNestedAnnotation() { @@ -654,15 +676,17 @@ class KotlinInjectionTest : AbstractInjectionTest() { } fun testInjectionInAliasedJavaAnnotation() { - myFixture.addClass(""" + myFixture.addClass( + """ @interface InHtml { String html(); } - """) + """ + ) doAnnotationInjectionTest( - injectedLanguage = HTMLLanguage.INSTANCE.id, - pattern = """psiMethod().withName("html").withParameters().definedInClass("InHtml")""", - kotlinCode = """ + injectedLanguage = HTMLLanguage.INSTANCE.id, + pattern = """psiMethod().withName("html").withParameters().definedInClass("InHtml")""", + kotlinCode = """ import InHtml as InHtmlAliased @InHtmlAliased(html = "l>") @@ -672,24 +696,30 @@ class KotlinInjectionTest : AbstractInjectionTest() { ) } - private fun doAnnotationInjectionTest(patternLanguage: String = "java", injectedLanguage: String, pattern: String, @Language("kotlin") kotlinCode: String, additionalAsserts: () -> Unit = {}) { + private fun doAnnotationInjectionTest( + patternLanguage: String = "java", + injectedLanguage: String, + pattern: String, + @Language("kotlin") kotlinCode: String, + additionalAsserts: () -> Unit = {} + ) { val customInjection = BaseInjection(patternLanguage) customInjection.injectedLanguageId = injectedLanguage val elementPattern = customInjection.compiler.createElementPattern( - pattern, - "temp rule") + pattern, + "temp rule" + ) customInjection.setInjectionPlaces(InjectionPlace(elementPattern, true)) try { Configuration.getInstance().replaceInjections(listOf(customInjection), listOf(), true) doInjectionPresentTest( - kotlinCode, null, - injectedLanguage, - unInjectShouldBePresent = false + kotlinCode, null, + injectedLanguage, + unInjectShouldBePresent = false ) additionalAsserts() - } - finally { + } finally { Configuration.getInstance().replaceInjections(listOf(), listOf(customInjection), true) } } diff --git a/idea/tests/org/jetbrains/kotlin/psi/KotlinLibInjectionTest.kt b/idea/tests/org/jetbrains/kotlin/psi/KotlinLibInjectionTest.kt index f90518bf57a..5c4a28194fb 100644 --- a/idea/tests/org/jetbrains/kotlin/psi/KotlinLibInjectionTest.kt +++ b/idea/tests/org/jetbrains/kotlin/psi/KotlinLibInjectionTest.kt @@ -22,23 +22,23 @@ class KotlinLibInjectionTest : AbstractInjectionTest() { } fun testFunInjection() = assertInjectionPresent( - """ + """ import injection.html fun test() { 12.html("") } """, - HTMLLanguage.INSTANCE.id + HTMLLanguage.INSTANCE.id ) fun testFunInjectionWithImportedAnnotation() = assertInjectionPresent( - """ + """ import injection.regexp fun test() { 12.regexp("test") } """, - RegExpLanguage.INSTANCE.id + RegExpLanguage.INSTANCE.id ) private fun assertInjectionPresent(@Language("kotlin") text: String, languageId: String) { @@ -48,9 +48,10 @@ class KotlinLibInjectionTest : AbstractInjectionTest() { override fun getProjectDescriptor(): LightProjectDescriptor { val ideaSdkPath = System.getProperty("idea.home.path")?.takeIf { File(it).isDirectory } - ?: throw RuntimeException("Unable to get a valid path from 'idea.home.path' property, please point it to the Idea location") + ?: throw RuntimeException("Unable to get a valid path from 'idea.home.path' property, please point it to the Idea location") return SdkAndMockLibraryProjectDescriptor( - PluginTestCaseBase.getTestDataPathBase() + "/injection/lib/", false, false, false, true, - listOf(File(ideaSdkPath, "lib/annotations.jar").absolutePath)) + PluginTestCaseBase.getTestDataPathBase() + "/injection/lib/", false, false, false, true, + listOf(File(ideaSdkPath, "lib/annotations.jar").absolutePath) + ) } } diff --git a/idea/tests/org/jetbrains/kotlin/psi/StringTemplateExpressionManipulatorTest.kt b/idea/tests/org/jetbrains/kotlin/psi/StringTemplateExpressionManipulatorTest.kt index 47f9264ab03..6ba853b0a51 100644 --- a/idea/tests/org/jetbrains/kotlin/psi/StringTemplateExpressionManipulatorTest.kt +++ b/idea/tests/org/jetbrains/kotlin/psi/StringTemplateExpressionManipulatorTest.kt @@ -49,8 +49,8 @@ class StringTemplateExpressionManipulatorTest : KotlinLightCodeInsightFixtureTes } fun testReplaceRange() { - doTestContentChange("\"abc\"", "x", range = TextRange(2,3), expected = "\"axc\"") - doTestContentChange("\"\"\"abc\"\"\"", "x", range = TextRange(4,5), expected = "\"\"\"axc\"\"\"") + doTestContentChange("\"abc\"", "x", range = TextRange(2, 3), expected = "\"axc\"") + doTestContentChange("\"\"\"abc\"\"\"", "x", range = TextRange(4, 5), expected = "\"\"\"axc\"\"\"") doTestContentChange( "\"
    \${foo(\"\")}
    \"", "custom", range = TextRange(16, 23), @@ -77,7 +77,11 @@ class StringTemplateExpressionManipulatorTest : KotlinLightCodeInsightFixtureTes private fun doTestContentChange(original: String, newContent: String, expected: String, range: TextRange? = null) { val expression = KtPsiFactory(project).createExpression(original) as KtStringTemplateExpression val manipulator = ElementManipulators.getNotNullManipulator(expression) - val newExpression = if (range == null) manipulator.handleContentChange(expression, newContent) else manipulator.handleContentChange(expression, range, newContent) + val newExpression = if (range == null) manipulator.handleContentChange(expression, newContent) else manipulator.handleContentChange( + expression, + range, + newContent + ) assertEquals(expected, newExpression?.text) } diff --git a/idea/tests/org/jetbrains/kotlin/psi/injection/StringInjectionHostTest.kt b/idea/tests/org/jetbrains/kotlin/psi/injection/StringInjectionHostTest.kt index 72644771d90..ee33911b0f4 100644 --- a/idea/tests/org/jetbrains/kotlin/psi/injection/StringInjectionHostTest.kt +++ b/idea/tests/org/jetbrains/kotlin/psi/injection/StringInjectionHostTest.kt @@ -18,15 +18,15 @@ import java.util.* @RunWith(JUnit3WithIdeaConfigurationRunner::class) class StringInjectionHostTest : KotlinTestWithEnvironment() { fun testRegular() { - with (quoted("")) { + with(quoted("")) { checkInjection("", mapOf(0 to 1)) assertOneLine() } - with (quoted("a")) { + with(quoted("a")) { checkInjection("a", mapOf(0 to 1, 1 to 2)) assertOneLine() } - with (quoted("ab")) { + with(quoted("ab")) { checkInjection("ab", mapOf(0 to 1, 1 to 2, 2 to 3)) checkInjection("a", mapOf(0 to 1, 1 to 2), rangeInHost = TextRange(1, 2)) checkInjection("b", mapOf(0 to 2, 1 to 3), rangeInHost = TextRange(2, 3)) @@ -45,14 +45,14 @@ class StringInjectionHostTest : KotlinTestWithEnvironment() { } fun testEscapeSequences() { - with (quoted("\\t")) { + with(quoted("\\t")) { checkInjection("\t", mapOf(0 to 1, 1 to 3)) assertNoInjection(TextRange(1, 2)) assertNoInjection(TextRange(2, 3)) assertOneLine() } - with (quoted("a\\tb")) { + with(quoted("a\\tb")) { checkInjection("a\tb", mapOf(0 to 1, 1 to 2, 2 to 4, 3 to 5)) checkInjection("a", mapOf(0 to 1, 1 to 2), rangeInHost = TextRange(1, 2)) assertNoInjection(TextRange(1, 3)) @@ -64,15 +64,15 @@ class StringInjectionHostTest : KotlinTestWithEnvironment() { } fun testTripleQuotes() { - with (tripleQuoted("")) { + with(tripleQuoted("")) { checkInjection("", mapOf(0 to 3)) assertMultiLine() } - with (tripleQuoted("a")) { + with(tripleQuoted("a")) { checkInjection("a", mapOf(0 to 3, 1 to 4)) assertMultiLine() } - with (tripleQuoted("ab")) { + with(tripleQuoted("ab")) { checkInjection("ab", mapOf(0 to 3, 1 to 4, 2 to 5)) checkInjection("a", mapOf(0 to 3, 1 to 4), rangeInHost = TextRange(3, 4)) checkInjection("b", mapOf(0 to 4, 1 to 5), rangeInHost = TextRange(4, 5)) @@ -81,7 +81,7 @@ class StringInjectionHostTest : KotlinTestWithEnvironment() { } fun testEscapeSequenceInTripleQuotes() { - with (tripleQuoted("\\t")) { + with(tripleQuoted("\\t")) { checkInjection("\\t", mapOf(0 to 3, 1 to 4, 2 to 5)) checkInjection("\\", mapOf(0 to 3, 1 to 4), rangeInHost = TextRange(3, 4)) checkInjection("t", mapOf(0 to 4, 1 to 5), rangeInHost = TextRange(4, 5)) @@ -90,7 +90,7 @@ class StringInjectionHostTest : KotlinTestWithEnvironment() { } fun testMultiLine() { - with (tripleQuoted("a\nb")) { + with(tripleQuoted("a\nb")) { checkInjection("a\nb", mapOf(0 to 3, 1 to 4, 2 to 5, 3 to 6)) assertMultiLine() } @@ -145,14 +145,14 @@ class StringInjectionHostTest : KotlinTestWithEnvironment() { } private fun checkAllRanges(str: String) { - with (quoted(str)) { + with(quoted(str)) { checkInjection(str, (0..str.length).keysToMap { it + 1 }) assertOneLine() } } private fun KtStringTemplateExpression.checkInjection( - decoded: String, targetToSourceOffsets: Map, rangeInHost: TextRange? = null + decoded: String, targetToSourceOffsets: Map, rangeInHost: TextRange? = null ) { assertTrue(isValidHost) for (prefix in listOf("", "prefix")) { diff --git a/idea/tests/org/jetbrains/kotlin/psi/patternMatching/AbstractPsiUnifierTest.kt b/idea/tests/org/jetbrains/kotlin/psi/patternMatching/AbstractPsiUnifierTest.kt index cafe63196a9..3572defdb32 100644 --- a/idea/tests/org/jetbrains/kotlin/psi/patternMatching/AbstractPsiUnifierTest.kt +++ b/idea/tests/org/jetbrains/kotlin/psi/patternMatching/AbstractPsiUnifierTest.kt @@ -34,11 +34,8 @@ abstract class AbstractPsiUnifierTest : KotlinLightCodeInsightFixtureTestCase() DirectiveBasedActionUtils.checkForUnexpectedErrors(file) val actualText = - findPattern(file) - .toRange() - .match(file, KotlinPsiUnifier.DEFAULT) - .map { it.range.getTextRange().substring(file.getText()!!) } - .joinToString("\n\n") + findPattern(file).toRange().match(file, KotlinPsiUnifier.DEFAULT).map { it.range.getTextRange().substring(file.getText()!!) } + .joinToString("\n\n") KotlinTestUtils.assertEqualsToFile(File(testDataPath, "${fileName()}.match"), actualText) } diff --git a/idea/tests/org/jetbrains/kotlin/search/KotlinReferencesSearchTest.kt b/idea/tests/org/jetbrains/kotlin/search/KotlinReferencesSearchTest.kt index 23f635b0e70..a31f70ffb59 100644 --- a/idea/tests/org/jetbrains/kotlin/search/KotlinReferencesSearchTest.kt +++ b/idea/tests/org/jetbrains/kotlin/search/KotlinReferencesSearchTest.kt @@ -20,7 +20,7 @@ import org.jetbrains.kotlin.psi.psiUtil.getParentOfType import org.junit.Assert import java.io.File -class KotlinReferencesSearchTest(): AbstractSearcherTest() { +class KotlinReferencesSearchTest() : AbstractSearcherTest() { override fun getTestDataPath(): String { return File(PluginTestCaseBase.getTestDataPathBase(), "/search/references").path + File.separator } @@ -58,7 +58,7 @@ class KotlinReferencesSearchTest(): AbstractSearcherTest() { // workaround for KT-9788 AssertionError from backand when we read field from inline function private val myFixtureProxy: JavaCodeInsightTestFixture get() = myFixture - private inline fun doTest(): List { + private inline fun doTest(): List { val psiFile = myFixtureProxy.configureByFile(fileName) val func = myFixtureProxy.elementAtCaret.getParentOfType(false)!! val refs = ReferencesSearch.search(func).findAll().sortedBy { it.element.textRange.startOffset } @@ -68,8 +68,7 @@ class KotlinReferencesSearchTest(): AbstractSearcherTest() { ExpressionsOfTypeProcessor.mode = ExpressionsOfTypeProcessor.Mode.PLAIN_WHEN_NEEDED val localRefs = ReferencesSearch.search(func, LocalSearchScope(psiFile)).findAll() Assert.assertEquals(refs.size, localRefs.size) - } - finally { + } finally { ExpressionsOfTypeProcessor.mode = ExpressionsOfTypeProcessor.Mode.ALWAYS_SMART } diff --git a/idea/tests/org/jetbrains/kotlin/shortenRefs/AbstractShortenRefsTest.kt b/idea/tests/org/jetbrains/kotlin/shortenRefs/AbstractShortenRefsTest.kt index 2ff4d9f8844..5185e92121d 100644 --- a/idea/tests/org/jetbrains/kotlin/shortenRefs/AbstractShortenRefsTest.kt +++ b/idea/tests/org/jetbrains/kotlin/shortenRefs/AbstractShortenRefsTest.kt @@ -13,8 +13,11 @@ abstract class AbstractShortenRefsTest : AbstractImportsTest() { override fun doTest(file: KtFile): String? { val selectionModel = myFixture.editor.selectionModel if (!selectionModel.hasSelection()) error("No selection in input file") - ShortenReferences { ShortenReferences.Options(removeThis = true, removeThisLabels = true) } - .process(file, selectionModel.selectionStart, selectionModel.selectionEnd) + ShortenReferences { ShortenReferences.Options(removeThis = true, removeThisLabels = true) }.process( + file, + selectionModel.selectionStart, + selectionModel.selectionEnd + ) selectionModel.removeSelection() return null } diff --git a/idea/tests/org/jetbrains/kotlin/test/CompatibilityVerifierVersionComparisonTest.kt b/idea/tests/org/jetbrains/kotlin/test/CompatibilityVerifierVersionComparisonTest.kt index e42377cfbf2..0ffc3f13d8a 100644 --- a/idea/tests/org/jetbrains/kotlin/test/CompatibilityVerifierVersionComparisonTest.kt +++ b/idea/tests/org/jetbrains/kotlin/test/CompatibilityVerifierVersionComparisonTest.kt @@ -13,8 +13,7 @@ import org.junit.runner.RunWith @RunWith(JUnit3WithIdeaConfigurationRunner::class) class CompatibilityVerifierVersionComparisonTest : LightPlatformTestCase() { fun testKotlinVersionParsing() { - val version = KotlinPluginVersion.parse("1.2.40-dev-193-Studio3.0-1") - ?: throw AssertionError("Version should not be null") + val version = KotlinPluginVersion.parse("1.2.40-dev-193-Studio3.0-1") ?: throw AssertionError("Version should not be null") assertEquals("1.2.40", version.kotlinVersion) assertEquals("dev", version.status) diff --git a/idea/tests/org/jetbrains/kotlin/test/util/ProjectStructureUtils.kt b/idea/tests/org/jetbrains/kotlin/test/util/ProjectStructureUtils.kt index 3251624ca43..0aad902b341 100644 --- a/idea/tests/org/jetbrains/kotlin/test/util/ProjectStructureUtils.kt +++ b/idea/tests/org/jetbrains/kotlin/test/util/ProjectStructureUtils.kt @@ -20,10 +20,10 @@ import org.jetbrains.kotlin.test.testFramework.runWriteAction import java.io.File fun PlatformTestCase.projectLibrary( - libraryName: String = "TestLibrary", - classesRoot: VirtualFile? = null, - sourcesRoot: VirtualFile? = null, - kind: PersistentLibraryKind<*>? = null + libraryName: String = "TestLibrary", + classesRoot: VirtualFile? = null, + sourcesRoot: VirtualFile? = null, + kind: PersistentLibraryKind<*>? = null ): Library { return runWriteAction { val modifiableModel = ProjectLibraryTable.getInstance(project).modifiableModel @@ -32,7 +32,7 @@ fun PlatformTestCase.projectLibrary( } finally { modifiableModel.commit() } - with (library.modifiableModel) { + with(library.modifiableModel) { classesRoot?.let { addRoot(it, OrderRootType.CLASSES) } sourcesRoot?.let { addRoot(it, OrderRootType.SOURCES) } commit() @@ -48,7 +48,7 @@ val File.jarRoot: VirtualFile } fun Module.addDependency( - library: Library, - dependencyScope: DependencyScope = DependencyScope.COMPILE, - exported: Boolean = false + library: Library, + dependencyScope: DependencyScope = DependencyScope.COMPILE, + exported: Boolean = false ) = ModuleRootModificationUtil.addDependency(this, library, dependencyScope, exported)