From 1d2017b0fcb43617345f615865bcf668e7298ced Mon Sep 17 00:00:00 2001 From: Mikhail Glukhikh Date: Wed, 28 Jun 2017 15:19:20 +0300 Subject: [PATCH] Cleanup: apply "cascade if..." inspection (+ some others) --- .../jetbrains/kotlin/codegen/codegenUtil.kt | 12 +- .../codegen/forLoop/ForLoopGenerators.kt | 20 +- .../kotlin/codegen/inline/InlineCodegen.kt | 12 +- .../codegen/inline/SourceCompilerForInline.kt | 34 ++-- .../codegen/inline/inlineCodegenUtils.kt | 50 ++--- .../codegen/intrinsics/JavaClassProperty.kt | 30 +-- .../cfg/ControlFlowInformationProvider.kt | 13 +- .../jetbrains/kotlin/cfg/UnreachableCode.kt | 20 +- .../impl/SyntheticFieldDescriptor.kt | 6 +- .../kotlin/diagnostics/rendering/Renderers.kt | 6 +- .../kotlin/resolve/AnnotationChecker.kt | 54 +++-- .../kotlin/resolve/DeclarationsChecker.kt | 40 ++-- .../kotlin/resolve/DelegatingBindingTrace.kt | 11 +- .../resolve/FunctionDescriptorResolver.kt | 15 +- .../kotlin/resolve/ModifiersChecker.kt | 12 +- .../resolve/QualifiedExpressionResolver.kt | 20 +- .../resolve/calls/checkers/InlineChecker.kt | 28 +-- .../kotlin/resolve/calls/resolvedCallUtil.kt | 24 +-- .../smartcasts/DelegatingDataFlowInfo.kt | 8 +- .../diagnostics/KotlinSuppressCache.kt | 12 +- .../descriptors/AbstractLazyMemberScope.kt | 68 +++---- .../kotlin/types/expressions/LabelResolver.kt | 65 +++--- .../expressions/SenselessComparisonChecker.kt | 18 +- .../backend/jvm/codegen/ExpressionCodegen.kt | 40 ++-- .../psi2ir/generators/StatementGenerator.kt | 22 ++- .../calls/tower/ScopeTowerProcessors.kt | 38 ++-- .../types/checker/NewKotlinTypeChecker.kt | 26 +-- .../reflect/jvm/internal/RuntimeTypeMapper.kt | 44 +++-- .../src/org/jetbrains/eval4j/interpreter.kt | 11 +- .../idea/util/OptimizedImportsBuilder.kt | 27 ++- .../resolve/lazy/PartialBodyResolveFilter.kt | 14 +- .../lightClasses/IDELightClassContexts.kt | 36 ++-- .../kotlin/idea/findUsages/UsageTypeUtils.kt | 17 +- .../framework/CommonLibraryDetectionUtil.kt | 11 +- .../quickfix/KotlinSuppressIntentionAction.kt | 16 +- .../idea/search/PsiBasedClassResolver.kt | 24 +-- .../completion/BasicLookupElementFactory.kt | 11 +- .../CompletionBindingContextProvider.kt | 47 +++-- .../idea/completion/LookupElementFactory.kt | 23 +-- .../kotlin/idea/core/ExpectedInfos.kt | 22 +-- .../idea/core/ImportableFqNameClassifier.kt | 17 +- .../kotlin/idea/core/KotlinNameSuggester.kt | 108 ++++------ .../kotlin/idea/core/psiModificationUtils.kt | 33 ++-- .../maven/actions/MavenPluginSourcesSwap.kt | 12 +- .../KotlinWithLibraryConfigurator.kt | 18 +- .../debugger/DebuggerClassNameProvider.kt | 37 ++-- .../evaluate/KotlinEvaluationBuilder.kt | 15 +- .../editor/KotlinLiteralCopyPasteProcessor.kt | 50 ++--- .../idea/highlighter/KotlinRainbowVisitor.kt | 48 ++--- .../KotlinUnusedImportInspection.kt | 12 +- .../NullableBooleanElvisInspection.kt | 6 +- ...bleBooleanEqualityCheckToElvisIntention.kt | 6 +- .../branchedTransformations/IfThenUtils.kt | 11 +- .../result/MaxOrMinTransformation.kt | 36 ++-- .../presentation/DeclarationPresenters.kt | 12 +- .../quickfix/ChangeFunctionSignatureFix.kt | 16 +- .../quickfix/ReplaceInfixOrOperatorCallFix.kt | 20 +- .../idea/quickfix/SpecifyTypeExplicitlyFix.kt | 12 +- .../migration/MigrateExternalExtensionFix.kt | 77 ++++---- .../KotlinChangeSignatureData.kt | 45 ++--- .../ui/KotlinChangeSignatureDialog.kt | 30 +-- .../extractionEngine/extractorUtil.kt | 12 +- .../introduceTypeAliasImpl.kt | 15 +- .../run/KotlinRunConfigurationProducer.kt | 6 +- .../versions/OutdatedKotlinRuntimeChecker.kt | 22 ++- .../kotlin/j2k/ExpressionConverter.kt | 163 +++++++-------- .../org/jetbrains/kotlin/j2k/ForConverter.kt | 13 +- .../org/jetbrains/kotlin/j2k/TypeConverter.kt | 14 +- .../org/jetbrains/kotlin/j2k/TypeVisitor.kt | 16 +- j2k/src/org/jetbrains/kotlin/j2k/Utils.kt | 12 +- .../jetbrains/kotlin/j2k/ast/Expressions.kt | 11 +- .../jetbrains/kotlin/j2k/propertyDetection.kt | 36 ++-- .../FieldToPropertyProcessing.kt | 11 +- .../org/jetbrains/kotlin/js/dce/Analyzer.kt | 186 +++++++++--------- .../resolve/diagnostics/JsExternalChecker.kt | 16 +- .../clean/RedundantStatementElimination.kt | 20 +- .../processing/impl/KotlinElements.kt | 42 ++-- .../annotation/processing/impl/KotlinTypes.kt | 10 +- .../klint/SuppressLintIntentionAction.kt | 17 +- .../uast/kotlin/KotlinUastLanguagePlugin.kt | 19 +- 80 files changed, 1079 insertions(+), 1190 deletions(-) diff --git a/compiler/backend/src/org/jetbrains/kotlin/codegen/codegenUtil.kt b/compiler/backend/src/org/jetbrains/kotlin/codegen/codegenUtil.kt index 04882ea4f86..f509e2f2418 100644 --- a/compiler/backend/src/org/jetbrains/kotlin/codegen/codegenUtil.kt +++ b/compiler/backend/src/org/jetbrains/kotlin/codegen/codegenUtil.kt @@ -292,14 +292,10 @@ fun calcTypeForIEEE754ArithmeticIfNeeded(expression: KtExpression?, bindingConte val dataFlow = DataFlowValueFactory.createDataFlowValue(expression!!, ktType, bindingContext, descriptor) val stableTypes = bindingContext.getDataFlowInfoBefore(expression).getStableTypes(dataFlow) return stableTypes.firstNotNullResult { - if (KotlinBuiltIns.isDoubleOrNullableDouble(it)) { - TypeAndNullability(Type.DOUBLE_TYPE, TypeUtils.isNullableType(it)) - } - else if (KotlinBuiltIns.isFloatOrNullableFloat(it)) { - TypeAndNullability(Type.FLOAT_TYPE, TypeUtils.isNullableType(it)) - } - else { - null + when { + KotlinBuiltIns.isDoubleOrNullableDouble(it) -> TypeAndNullability(Type.DOUBLE_TYPE, TypeUtils.isNullableType(it)) + KotlinBuiltIns.isFloatOrNullableFloat(it) -> TypeAndNullability(Type.FLOAT_TYPE, TypeUtils.isNullableType(it)) + else -> null } } } diff --git a/compiler/backend/src/org/jetbrains/kotlin/codegen/forLoop/ForLoopGenerators.kt b/compiler/backend/src/org/jetbrains/kotlin/codegen/forLoop/ForLoopGenerators.kt index d6bbac3fdc6..f227d01f021 100644 --- a/compiler/backend/src/org/jetbrains/kotlin/codegen/forLoop/ForLoopGenerators.kt +++ b/compiler/backend/src/org/jetbrains/kotlin/codegen/forLoop/ForLoopGenerators.kt @@ -83,18 +83,16 @@ private fun ExpressionCodegen.createOptimizedForLoopGeneratorOrNull( private fun getLoopRangeResolvedCall(forExpression: KtForExpression, bindingContext: BindingContext): ResolvedCall? { val loopRange = KtPsiUtil.deparenthesize(forExpression.loopRange) - if (loopRange is KtQualifiedExpression) { - val qualifiedExpression = loopRange as KtQualifiedExpression? - val selector = qualifiedExpression!!.selectorExpression - if (selector is KtCallExpression || selector is KtSimpleNameExpression) { - return selector.getResolvedCall(bindingContext) + when (loopRange) { + is KtQualifiedExpression -> { + val qualifiedExpression = loopRange as KtQualifiedExpression? + val selector = qualifiedExpression!!.selectorExpression + if (selector is KtCallExpression || selector is KtSimpleNameExpression) { + return selector.getResolvedCall(bindingContext) + } } - } - else if (loopRange is KtSimpleNameExpression || loopRange is KtCallExpression) { - return loopRange.getResolvedCall(bindingContext) - } - else if (loopRange is KtBinaryExpression) { - return loopRange.operationReference.getResolvedCall(bindingContext) + is KtSimpleNameExpression, is KtCallExpression -> return loopRange.getResolvedCall(bindingContext) + is KtBinaryExpression -> return loopRange.operationReference.getResolvedCall(bindingContext) } return null diff --git a/compiler/backend/src/org/jetbrains/kotlin/codegen/inline/InlineCodegen.kt b/compiler/backend/src/org/jetbrains/kotlin/codegen/inline/InlineCodegen.kt index 8362b4485f5..dcf94f12a9b 100644 --- a/compiler/backend/src/org/jetbrains/kotlin/codegen/inline/InlineCodegen.kt +++ b/compiler/backend/src/org/jetbrains/kotlin/codegen/inline/InlineCodegen.kt @@ -610,14 +610,10 @@ class PsiInlineCodegen( override fun putClosureParametersOnStack(next: LambdaInfo, functionReferenceReceiver: StackValue?) { activeLambda = next - if (next is ExpressionLambda) { - codegen.pushClosureOnStack(next.classDescriptor, true, this, functionReferenceReceiver) - } - else if (next is DefaultLambda) { - rememberCapturedForDefaultLambda(next) - } - else { - throw RuntimeException("Unknown lambda: $next") + when (next) { + is ExpressionLambda -> codegen.pushClosureOnStack(next.classDescriptor, true, this, functionReferenceReceiver) + is DefaultLambda -> rememberCapturedForDefaultLambda(next) + else -> throw RuntimeException("Unknown lambda: $next") } activeLambda = null } diff --git a/compiler/backend/src/org/jetbrains/kotlin/codegen/inline/SourceCompilerForInline.kt b/compiler/backend/src/org/jetbrains/kotlin/codegen/inline/SourceCompilerForInline.kt index b9fe3d0aad5..ca7d1b46cc7 100644 --- a/compiler/backend/src/org/jetbrains/kotlin/codegen/inline/SourceCompilerForInline.kt +++ b/compiler/backend/src/org/jetbrains/kotlin/codegen/inline/SourceCompilerForInline.kt @@ -408,23 +408,27 @@ class PsiSourceCompilerForInline(private val codegen: ExpressionCodegen, overrid sourceFile ) - if (descriptor is ScriptDescriptor) { - val earlierScripts = state.replSpecific.earlierScriptsForReplInterpreter - return parent.intoScript( - descriptor, - earlierScripts ?: emptyList(), - descriptor as ClassDescriptor, state.typeMapper - ) - } - else if (descriptor is ClassDescriptor) { - val kind = if (DescriptorUtils.isInterface(descriptor)) OwnerKind.DEFAULT_IMPLS else OwnerKind.IMPLEMENTATION - return parent.intoClass(descriptor, kind, state) - } - else if (descriptor is FunctionDescriptor) { - return parent.intoFunction(descriptor) + return when (descriptor) { + is ScriptDescriptor -> { + val earlierScripts = state.replSpecific.earlierScriptsForReplInterpreter + parent.intoScript( + descriptor, + earlierScripts ?: emptyList(), + descriptor as ClassDescriptor, state.typeMapper + ) + } + is ClassDescriptor -> { + val kind = if (DescriptorUtils.isInterface(descriptor)) OwnerKind.DEFAULT_IMPLS else OwnerKind.IMPLEMENTATION + parent.intoClass(descriptor, kind, state) + } + is FunctionDescriptor -> { + parent.intoFunction(descriptor) + } + else -> { + throw IllegalStateException("Couldn't build context for " + descriptor) + } } - throw IllegalStateException("Couldn't build context for " + descriptor) } } } \ No newline at end of file diff --git a/compiler/backend/src/org/jetbrains/kotlin/codegen/inline/inlineCodegenUtils.kt b/compiler/backend/src/org/jetbrains/kotlin/codegen/inline/inlineCodegenUtils.kt index b6a460c1134..9bc08d4ab4f 100644 --- a/compiler/backend/src/org/jetbrains/kotlin/codegen/inline/inlineCodegenUtils.kt +++ b/compiler/backend/src/org/jetbrains/kotlin/codegen/inline/inlineCodegenUtils.kt @@ -171,33 +171,35 @@ private fun getInlineName( typeMapper: KotlinTypeMapper, fileClassesProvider: JvmFileClassesProvider ): String { - if (currentDescriptor is PackageFragmentDescriptor) { - val file = DescriptorToSourceUtils.getContainingFile(codegenContext.contextDescriptor) + when (currentDescriptor) { + is PackageFragmentDescriptor -> { + val file = DescriptorToSourceUtils.getContainingFile(codegenContext.contextDescriptor) - val implementationOwnerType: Type? = - if (file == null) { - CodegenContextUtil.getImplementationOwnerClassType(codegenContext) - } - else fileClassesProvider.getFileClassType(file) + val implementationOwnerType: Type? = + if (file == null) { + CodegenContextUtil.getImplementationOwnerClassType(codegenContext) + } + else fileClassesProvider.getFileClassType(file) - if (implementationOwnerType == null) { - val contextDescriptor = codegenContext.contextDescriptor - throw RuntimeException( - "Couldn't find declaration for " + - contextDescriptor.containingDeclaration!!.name + "." + contextDescriptor.name + - "; context: " + codegenContext - ) + if (implementationOwnerType == null) { + val contextDescriptor = codegenContext.contextDescriptor + throw RuntimeException( + "Couldn't find declaration for " + + contextDescriptor.containingDeclaration!!.name + "." + contextDescriptor.name + + "; context: " + codegenContext + ) + } + + return implementationOwnerType.internalName } - - return implementationOwnerType.internalName - } - else if (currentDescriptor is ClassifierDescriptor) { - return typeMapper.mapType(currentDescriptor).internalName - } - else if (currentDescriptor is FunctionDescriptor) { - val descriptor = typeMapper.bindingContext.get(CodegenBinding.CLASS_FOR_CALLABLE, currentDescriptor) - if (descriptor != null) { - return typeMapper.mapType(descriptor).internalName + is ClassifierDescriptor -> { + return typeMapper.mapType(currentDescriptor).internalName + } + is FunctionDescriptor -> { + val descriptor = typeMapper.bindingContext.get(CodegenBinding.CLASS_FOR_CALLABLE, currentDescriptor) + if (descriptor != null) { + return typeMapper.mapType(descriptor).internalName + } } } diff --git a/compiler/backend/src/org/jetbrains/kotlin/codegen/intrinsics/JavaClassProperty.kt b/compiler/backend/src/org/jetbrains/kotlin/codegen/intrinsics/JavaClassProperty.kt index 992c458a6b7..62a9df2a4d8 100644 --- a/compiler/backend/src/org/jetbrains/kotlin/codegen/intrinsics/JavaClassProperty.kt +++ b/compiler/backend/src/org/jetbrains/kotlin/codegen/intrinsics/JavaClassProperty.kt @@ -43,21 +43,23 @@ object JavaClassProperty : IntrinsicPropertyGetter() { fun generateImpl(v: InstructionAdapter, receiver: StackValue): Type { val type = receiver.type - if (type == Type.VOID_TYPE) { - receiver.put(Type.VOID_TYPE, v) - StackValue.unit().put(UNIT_TYPE, v) - v.invokevirtual("java/lang/Object", "getClass", "()Ljava/lang/Class;", false) - } - else if (isPrimitive(type)) { - if (!StackValue.couldSkipReceiverOnStaticCall(receiver)) { - receiver.put(type, v) - AsmUtil.pop(v, type) + when { + type == Type.VOID_TYPE -> { + receiver.put(Type.VOID_TYPE, v) + StackValue.unit().put(UNIT_TYPE, v) + v.invokevirtual("java/lang/Object", "getClass", "()Ljava/lang/Class;", false) + } + isPrimitive(type) -> { + if (!StackValue.couldSkipReceiverOnStaticCall(receiver)) { + receiver.put(type, v) + AsmUtil.pop(v, type) + } + v.getstatic(boxType(type).internalName, "TYPE", "Ljava/lang/Class;") + } + else -> { + receiver.put(type, v) + v.invokevirtual("java/lang/Object", "getClass", "()Ljava/lang/Class;", false) } - v.getstatic(boxType(type).internalName, "TYPE", "Ljava/lang/Class;") - } - else { - receiver.put(type, v) - v.invokevirtual("java/lang/Object", "getClass", "()Ljava/lang/Class;", false) } return getType(Class::class.java) diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowInformationProvider.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowInformationProvider.kt index c18796a82d8..b7d937998ea 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowInformationProvider.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowInformationProvider.kt @@ -1123,15 +1123,10 @@ class ControlFlowInformationProvider private constructor( kind } else { - if (check(kind, existingKind, IN_TRY, TAIL_CALL)) { - IN_TRY - } - else if (check(kind, existingKind, IN_TRY, NON_TAIL)) { - IN_TRY - } - else { - // TAIL_CALL, NON_TAIL - NON_TAIL + when { + check(kind, existingKind, IN_TRY, TAIL_CALL) -> IN_TRY + check(kind, existingKind, IN_TRY, NON_TAIL) -> IN_TRY + else -> NON_TAIL // TAIL_CALL, NON_TAIL } } } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/UnreachableCode.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/UnreachableCode.kt index fbb7b6394cf..40212a587b4 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/UnreachableCode.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/UnreachableCode.kt @@ -107,15 +107,17 @@ class UnreachableCodeImpl( currentTextRange, element -> val elementRange = element.textRange!! - if (currentTextRange == null) { - elementRange - } - else if (currentTextRange.endOffset == elementRange.startOffset) { - currentTextRange.union(elementRange) - } - else { - result.add(currentTextRange) - elementRange + when { + currentTextRange == null -> { + elementRange + } + currentTextRange.endOffset == elementRange.startOffset -> { + currentTextRange.union(elementRange) + } + else -> { + result.add(currentTextRange) + elementRange + } } } if (lastRange != null) { diff --git a/compiler/frontend/src/org/jetbrains/kotlin/descriptors/impl/SyntheticFieldDescriptor.kt b/compiler/frontend/src/org/jetbrains/kotlin/descriptors/impl/SyntheticFieldDescriptor.kt index 19daadf52f9..a0721619165 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/descriptors/impl/SyntheticFieldDescriptor.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/descriptors/impl/SyntheticFieldDescriptor.kt @@ -47,4 +47,8 @@ class SyntheticFieldDescriptor private constructor( } val DeclarationDescriptor.referencedProperty: PropertyDescriptor? - get() = if (this is SyntheticFieldDescriptor) this.propertyDescriptor else if (this is PropertyDescriptor) this else null + get() = when (this) { + is SyntheticFieldDescriptor -> this.propertyDescriptor + is PropertyDescriptor -> this + else -> null + } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/Renderers.kt b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/Renderers.kt index 6790afa0dc8..407c8613250 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/Renderers.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/Renderers.kt @@ -458,7 +458,11 @@ object Renderers { private fun renderTypeBounds(typeBounds: TypeBounds, short: Boolean): String { val renderBound = { bound: Bound -> - val arrow = if (bound.kind == LOWER_BOUND) ">: " else if (bound.kind == UPPER_BOUND) "<: " else ":= " + val arrow = when (bound.kind) { + LOWER_BOUND -> ">: " + UPPER_BOUND -> "<: " + else -> ":= " + } val renderer = if (short) DescriptorRenderer.SHORT_NAMES_IN_TYPES else DescriptorRenderer.FQ_NAMES_IN_TYPES val renderedBound = arrow + renderer.renderType(bound.constrainingType) + if (!bound.isProper) "*" else "" if (short) renderedBound else renderedBound + '(' + bound.position + ')' diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/AnnotationChecker.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/AnnotationChecker.kt index a9b06b21ec1..a71c45336d3 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/AnnotationChecker.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/AnnotationChecker.kt @@ -202,32 +202,28 @@ class AnnotationChecker(private val additionalCheckers: Iterable TargetLists.T_LOCAL_VARIABLE is KtProperty -> { - if (annotated.isLocal) - TargetLists.T_LOCAL_VARIABLE - else if (annotated.isMember) - TargetLists.T_MEMBER_PROPERTY(descriptor.hasBackingField(trace), annotated.hasDelegate()) - else - TargetLists.T_TOP_LEVEL_PROPERTY(descriptor.hasBackingField(trace), annotated.hasDelegate()) + when { + annotated.isLocal -> TargetLists.T_LOCAL_VARIABLE + annotated.isMember -> TargetLists.T_MEMBER_PROPERTY(descriptor.hasBackingField(trace), annotated.hasDelegate()) + else -> TargetLists.T_TOP_LEVEL_PROPERTY(descriptor.hasBackingField(trace), annotated.hasDelegate()) + } } is KtParameter -> { val destructuringDeclaration = annotated.destructuringDeclaration - if (destructuringDeclaration != null) - TargetLists.T_DESTRUCTURING_DECLARATION - else if (annotated.hasValOrVar()) - TargetLists.T_VALUE_PARAMETER_WITH_VAL - else - TargetLists.T_VALUE_PARAMETER_WITHOUT_VAL + when { + destructuringDeclaration != null -> TargetLists.T_DESTRUCTURING_DECLARATION + annotated.hasValOrVar() -> TargetLists.T_VALUE_PARAMETER_WITH_VAL + else -> TargetLists.T_VALUE_PARAMETER_WITHOUT_VAL + } } is KtConstructor<*> -> TargetLists.T_CONSTRUCTOR is KtFunction -> { - if (ExpressionTypingUtils.isFunctionExpression(descriptor)) - TargetLists.T_FUNCTION_EXPRESSION - else if (annotated.isLocal) - TargetLists.T_LOCAL_FUNCTION - else if (annotated.parent is KtClassOrObject || annotated.parent is KtClassBody) - TargetLists.T_MEMBER_FUNCTION - else - TargetLists.T_TOP_LEVEL_FUNCTION + when { + ExpressionTypingUtils.isFunctionExpression(descriptor) -> TargetLists.T_FUNCTION_EXPRESSION + annotated.isLocal -> TargetLists.T_LOCAL_FUNCTION + annotated.parent is KtClassOrObject || annotated.parent is KtClassBody -> TargetLists.T_MEMBER_FUNCTION + else -> TargetLists.T_TOP_LEVEL_FUNCTION + } } is KtTypeAlias -> TargetLists.T_TYPEALIAS is KtPropertyAccessor -> if (annotated.isGetter) TargetLists.T_PROPERTY_GETTER else TargetLists.T_PROPERTY_SETTER @@ -266,18 +262,20 @@ class AnnotationChecker(private val additionalCheckers: Iterable MEMBER_PROPERTY_WITH_BACKING_FIELD + delegate -> MEMBER_PROPERTY_WITH_DELEGATE + else -> MEMBER_PROPERTY_WITHOUT_FIELD_OR_DELEGATE + }, MEMBER_PROPERTY, PROPERTY) { propertyTargets(backingField, delegate) } fun T_TOP_LEVEL_PROPERTY(backingField: Boolean, delegate: Boolean) = - targetList(if (backingField) TOP_LEVEL_PROPERTY_WITH_BACKING_FIELD - else if (delegate) TOP_LEVEL_PROPERTY_WITH_DELEGATE - else TOP_LEVEL_PROPERTY_WITHOUT_FIELD_OR_DELEGATE, - TOP_LEVEL_PROPERTY, PROPERTY) { + targetList(when { + backingField -> TOP_LEVEL_PROPERTY_WITH_BACKING_FIELD + delegate -> TOP_LEVEL_PROPERTY_WITH_DELEGATE + else -> TOP_LEVEL_PROPERTY_WITHOUT_FIELD_OR_DELEGATE + }, TOP_LEVEL_PROPERTY, PROPERTY) { propertyTargets(backingField, delegate) } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/DeclarationsChecker.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/DeclarationsChecker.kt index bfa8280c07b..188bade8b44 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/DeclarationsChecker.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/DeclarationsChecker.kt @@ -418,19 +418,19 @@ class DeclarationsChecker( FiniteBoundRestrictionChecker.check(aClass, classDescriptor, trace) NonExpansiveInheritanceRestrictionChecker.check(aClass, classDescriptor, trace) - if (aClass.isInterface()) { - checkConstructorInInterface(aClass) - checkMethodsOfAnyInInterface(classDescriptor) - if (aClass.isLocal && classDescriptor.containingDeclaration !is ClassDescriptor) { - trace.report(LOCAL_INTERFACE_NOT_ALLOWED.on(aClass, classDescriptor)) + when { + aClass.isInterface() -> { + checkConstructorInInterface(aClass) + checkMethodsOfAnyInInterface(classDescriptor) + if (aClass.isLocal && classDescriptor.containingDeclaration !is ClassDescriptor) { + trace.report(LOCAL_INTERFACE_NOT_ALLOWED.on(aClass, classDescriptor)) + } } - } - else if (classDescriptor.kind == ClassKind.ANNOTATION_CLASS) { - checkAnnotationClassWithBody(aClass) - checkValOnAnnotationParameter(aClass) - } - else if (aClass is KtEnumEntry) { - checkEnumEntry(aClass, classDescriptor) + classDescriptor.kind == ClassKind.ANNOTATION_CLASS -> { + checkAnnotationClassWithBody(aClass) + checkValOnAnnotationParameter(aClass) + } + aClass is KtEnumEntry -> checkEnumEntry(aClass, classDescriptor) } } @@ -692,17 +692,11 @@ class DeclarationsChecker( val delegate = property.delegate val isHeader = propertyDescriptor.isHeader if (initializer != null) { - if (inInterface) { - trace.report(PROPERTY_INITIALIZER_IN_INTERFACE.on(initializer)) - } - else if (isHeader) { - trace.report(HEADER_PROPERTY_INITIALIZER.on(initializer)) - } - else if (!backingFieldRequired) { - trace.report(PROPERTY_INITIALIZER_NO_BACKING_FIELD.on(initializer)) - } - else if (property.receiverTypeReference != null) { - trace.report(EXTENSION_PROPERTY_WITH_BACKING_FIELD.on(initializer)) + when { + inInterface -> trace.report(PROPERTY_INITIALIZER_IN_INTERFACE.on(initializer)) + isHeader -> trace.report(HEADER_PROPERTY_INITIALIZER.on(initializer)) + !backingFieldRequired -> trace.report(PROPERTY_INITIALIZER_NO_BACKING_FIELD.on(initializer)) + property.receiverTypeReference != null -> trace.report(EXTENSION_PROPERTY_WITH_BACKING_FIELD.on(initializer)) } } else if (delegate != null) { diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/DelegatingBindingTrace.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/DelegatingBindingTrace.kt index a477b689273..30836400cb7 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/DelegatingBindingTrace.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/DelegatingBindingTrace.kt @@ -69,12 +69,11 @@ open class DelegatingBindingTrace( private val bindingContext = MyBindingContext() init { - this.mutableDiagnostics = if (filter.ignoreDiagnostics) - null - else if (withParentDiagnostics) - MutableDiagnosticsWithSuppression(bindingContext, parentContext.diagnostics) - else - MutableDiagnosticsWithSuppression(bindingContext) + this.mutableDiagnostics = when { + filter.ignoreDiagnostics -> null + withParentDiagnostics -> MutableDiagnosticsWithSuppression(bindingContext, parentContext.diagnostics) + else -> MutableDiagnosticsWithSuppression(bindingContext) + } } constructor(parentContext: BindingContext, diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/FunctionDescriptorResolver.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/FunctionDescriptorResolver.kt index e9b1be0fcc3..0d5ab0977f8 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/FunctionDescriptorResolver.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/FunctionDescriptorResolver.kt @@ -122,14 +122,13 @@ class FunctionDescriptorResolver( assert(function.typeReference == null) { "Return type must be initialized early for function: " + function.text + ", at: " + DiagnosticUtils.atLocation(function) } - val returnType = if (function.hasBlockBody()) { - builtIns.unitType - } - else if (function.hasBody()) { - descriptorResolver.inferReturnTypeFromExpressionBody(trace, scope, dataFlowInfo, function, functionDescriptor) - } - else { - ErrorUtils.createErrorType("No type, no body") + val returnType = when { + function.hasBlockBody() -> + builtIns.unitType + function.hasBody() -> + descriptorResolver.inferReturnTypeFromExpressionBody(trace, scope, dataFlowInfo, function, functionDescriptor) + else -> + ErrorUtils.createErrorType("No type, no body") } functionDescriptor.setReturnType(returnType) } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/ModifiersChecker.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/ModifiersChecker.kt index 6ad514333cd..0a3dfe8a284 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/ModifiersChecker.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/ModifiersChecker.kt @@ -340,14 +340,10 @@ object ModifierCheckerCore { checkCompatibility(trace, first, second, list.owner, incorrectNodes) } if (second !in incorrectNodes) { - if (!checkTarget(trace, second, actualTargets)) { - incorrectNodes += second - } - else if (!checkParent(trace, second, parentDescriptor)) { - incorrectNodes += second - } - else if (!checkLanguageLevelSupport(trace, second, languageVersionSettings, actualTargets)) { - incorrectNodes += second + when { + !checkTarget(trace, second, actualTargets) -> incorrectNodes += second + !checkParent(trace, second, parentDescriptor) -> incorrectNodes += second + !checkLanguageLevelSupport(trace, second, languageVersionSettings, actualTargets) -> incorrectNodes += second } } } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/QualifiedExpressionResolver.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/QualifiedExpressionResolver.kt index 9447311cce7..07cbcc361de 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/QualifiedExpressionResolver.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/QualifiedExpressionResolver.kt @@ -568,15 +568,17 @@ class QualifiedExpressionResolver { ) { if (descriptors.size > 1) { val visibleDescriptors = descriptors.filter { isVisible(it, shouldBeVisibleFrom, position) } - if (visibleDescriptors.isEmpty()) { - val descriptor = descriptors.first() as DeclarationDescriptorWithVisibility - trace.report(Errors.INVISIBLE_REFERENCE.on(referenceExpression, descriptor, descriptor.visibility, descriptor)) - } - else if (visibleDescriptors.size > 1) { - trace.record(BindingContext.AMBIGUOUS_REFERENCE_TARGET, referenceExpression, visibleDescriptors) - } - else { - storeResult(trace, referenceExpression, visibleDescriptors.single(), null, position, isQualifier) + when { + visibleDescriptors.isEmpty() -> { + val descriptor = descriptors.first() as DeclarationDescriptorWithVisibility + trace.report(Errors.INVISIBLE_REFERENCE.on(referenceExpression, descriptor, descriptor.visibility, descriptor)) + } + visibleDescriptors.size > 1 -> { + trace.record(BindingContext.AMBIGUOUS_REFERENCE_TARGET, referenceExpression, visibleDescriptors) + } + else -> { + storeResult(trace, referenceExpression, visibleDescriptors.single(), null, position, isQualifier) + } } } else { diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/checkers/InlineChecker.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/checkers/InlineChecker.kt index 81dc60598f0..db7fe55f759 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/checkers/InlineChecker.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/checkers/InlineChecker.kt @@ -155,21 +155,23 @@ internal class InlineChecker(private val descriptor: FunctionDescriptor) : CallC val varDescriptor: CallableDescriptor? val receiverExpression: KtExpression? - if (receiver is ExpressionReceiver) { - receiverExpression = receiver.expression - varDescriptor = getCalleeDescriptor(context, receiverExpression, true) - } - else if (receiver is ExtensionReceiver) { - val extension = receiver.declarationDescriptor + when (receiver) { + is ExpressionReceiver -> { + receiverExpression = receiver.expression + varDescriptor = getCalleeDescriptor(context, receiverExpression, true) + } + is ExtensionReceiver -> { + val extension = receiver.declarationDescriptor - varDescriptor = extension.extensionReceiverParameter - assert(varDescriptor != null) { "Extension should have receiverParameterDescriptor: " + extension } + varDescriptor = extension.extensionReceiverParameter + assert(varDescriptor != null) { "Extension should have receiverParameterDescriptor: " + extension } - receiverExpression = expression - } - else { - varDescriptor = null - receiverExpression = null + receiverExpression = expression + } + else -> { + varDescriptor = null + receiverExpression = null + } } if (inlinableParameters.contains(varDescriptor)) { diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/resolvedCallUtil.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/resolvedCallUtil.kt index 5ca2099225c..d00d3bd21f4 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/resolvedCallUtil.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/resolvedCallUtil.kt @@ -50,18 +50,18 @@ fun ResolvedCall<*>.hasThisOrNoDispatchReceiver( if (resultingDescriptor.dispatchReceiverParameter == null || dispatchReceiverValue == null) return true var dispatchReceiverDescriptor: DeclarationDescriptor? = null - if (dispatchReceiverValue is ImplicitReceiver) { - // foo() -- implicit receiver - dispatchReceiverDescriptor = dispatchReceiverValue.declarationDescriptor - } - else if (dispatchReceiverValue is ClassValueReceiver) { - dispatchReceiverDescriptor = dispatchReceiverValue.classQualifier.descriptor - } - else if (dispatchReceiverValue is ExpressionReceiver) { - val expression = KtPsiUtil.deparenthesize(dispatchReceiverValue.expression) - if (expression is KtThisExpression) { - // this.foo() -- explicit receiver - dispatchReceiverDescriptor = context.get(BindingContext.REFERENCE_TARGET, expression.instanceReference) + when (dispatchReceiverValue) { + is ImplicitReceiver -> // foo() -- implicit receiver + dispatchReceiverDescriptor = dispatchReceiverValue.declarationDescriptor + is ClassValueReceiver -> { + dispatchReceiverDescriptor = dispatchReceiverValue.classQualifier.descriptor + } + is ExpressionReceiver -> { + val expression = KtPsiUtil.deparenthesize(dispatchReceiverValue.expression) + if (expression is KtThisExpression) { + // this.foo() -- explicit receiver + dispatchReceiverDescriptor = context.get(BindingContext.REFERENCE_TARGET, expression.instanceReference) + } } } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/smartcasts/DelegatingDataFlowInfo.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/smartcasts/DelegatingDataFlowInfo.kt index 5e2d340c97e..562ab9ed95d 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/smartcasts/DelegatingDataFlowInfo.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/smartcasts/DelegatingDataFlowInfo.kt @@ -283,9 +283,11 @@ internal class DelegatingDataFlowInfo private constructor( private fun Set.containsNothing() = any { KotlinBuiltIns.isNothing(it) } private fun Set.intersect(other: Set) = - if (other.containsNothing()) this - else if (this.containsNothing()) other - else Sets.intersection(this, other) + when { + other.containsNothing() -> this + this.containsNothing() -> other + else -> Sets.intersection(this, other) + } override fun or(other: DataFlowInfo): DataFlowInfo { if (other === DataFlowInfo.EMPTY) return DataFlowInfo.EMPTY diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/diagnostics/KotlinSuppressCache.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/diagnostics/KotlinSuppressCache.kt index 98928b997fc..6629eb7ac66 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/diagnostics/KotlinSuppressCache.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/diagnostics/KotlinSuppressCache.kt @@ -145,14 +145,10 @@ abstract class KotlinSuppressCache { var suppressor: Suppressor? = suppressors[annotated] if (suppressor == null) { val strings = getSuppressingStrings(annotated) - if (strings.isEmpty()) { - suppressor = EmptySuppressor(annotated) - } - else if (strings.size == 1) { - suppressor = SingularSuppressor(annotated, strings.iterator().next()) - } - else { - suppressor = MultiSuppressor(annotated, strings) + suppressor = when { + strings.isEmpty() -> EmptySuppressor(annotated) + strings.size == 1 -> SingularSuppressor(annotated, strings.iterator().next()) + else -> MultiSuppressor(annotated, strings) } suppressors.put(annotated, suppressor) } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/descriptors/AbstractLazyMemberScope.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/descriptors/AbstractLazyMemberScope.kt index 3d638433f39..99836bac933 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/descriptors/AbstractLazyMemberScope.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/descriptors/AbstractLazyMemberScope.kt @@ -169,46 +169,48 @@ protected constructor( val declarations = declarationProvider.getDeclarations(kindFilter, nameFilter) val result = LinkedHashSet(declarations.size) for (declaration in declarations) { - if (declaration is KtClassOrObject) { - val name = declaration.nameAsSafeName - if (nameFilter(name)) { - result.addAll(classDescriptors(name)) + when (declaration) { + is KtClassOrObject -> { + val name = declaration.nameAsSafeName + if (nameFilter(name)) { + result.addAll(classDescriptors(name)) + } } - } - else if (declaration is KtFunction) { - val name = declaration.nameAsSafeName - if (nameFilter(name)) { - result.addAll(getContributedFunctions(name, location)) + is KtFunction -> { + val name = declaration.nameAsSafeName + if (nameFilter(name)) { + result.addAll(getContributedFunctions(name, location)) + } } - } - else if (declaration is KtProperty) { - val name = declaration.nameAsSafeName - if (nameFilter(name)) { - result.addAll(getContributedVariables(name, location)) + is KtProperty -> { + val name = declaration.nameAsSafeName + if (nameFilter(name)) { + result.addAll(getContributedVariables(name, location)) + } } - } - else if (declaration is KtParameter) { - val name = declaration.nameAsSafeName - if (nameFilter(name)) { - result.addAll(getContributedVariables(name, location)) + is KtParameter -> { + val name = declaration.nameAsSafeName + if (nameFilter(name)) { + result.addAll(getContributedVariables(name, location)) + } } - } - else if (declaration is KtTypeAlias) { - val name = declaration.nameAsSafeName - if (nameFilter(name)) { - result.addAll(getContributedTypeAliasDescriptors(name, location)) + is KtTypeAlias -> { + val name = declaration.nameAsSafeName + if (nameFilter(name)) { + result.addAll(getContributedTypeAliasDescriptors(name, location)) + } } - } - else if (declaration is KtScript) { - val name = declaration.nameAsSafeName - if (nameFilter(name)) { - result.addAll(classDescriptors(name)) + is KtScript -> { + val name = declaration.nameAsSafeName + if (nameFilter(name)) { + result.addAll(classDescriptors(name)) + } } + is KtDestructuringDeclaration -> { + // MultiDeclarations are not supported on global level + } + else -> throw IllegalArgumentException("Unsupported declaration kind: " + declaration) } - else if (declaration is KtDestructuringDeclaration) { - // MultiDeclarations are not supported on global level - } - else throw IllegalArgumentException("Unsupported declaration kind: " + declaration) } return result.toList() } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/LabelResolver.kt b/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/LabelResolver.kt index efeefd14a64..b8d4baab8e8 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/LabelResolver.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/LabelResolver.kt @@ -137,44 +137,45 @@ object LabelResolver { val declarationsByLabel = context.scope.getDeclarationsByLabel(labelName) val size = declarationsByLabel.size - if (size == 1) { - val declarationDescriptor = declarationsByLabel.single() - val thisReceiver = when (declarationDescriptor) { - is ClassDescriptor -> declarationDescriptor.thisAsReceiverParameter - is FunctionDescriptor -> declarationDescriptor.extensionReceiverParameter - is PropertyDescriptor -> declarationDescriptor.extensionReceiverParameter - else -> throw UnsupportedOperationException("Unsupported descriptor: " + declarationDescriptor) // TODO - } - - val element = DescriptorToSourceUtils.descriptorToDeclaration(declarationDescriptor) ?: error("No PSI element for descriptor: " + declarationDescriptor) - context.trace.record(LABEL_TARGET, targetLabel, element) - context.trace.record(REFERENCE_TARGET, referenceExpression, declarationDescriptor) - - if (declarationDescriptor is ClassDescriptor) { - if (!DescriptorResolver.checkHasOuterClassInstance(context.scope, context.trace, targetLabel, declarationDescriptor)) { - return LabeledReceiverResolutionResult.labelResolutionFailed() + when (size) { + 1 -> { + val declarationDescriptor = declarationsByLabel.single() + val thisReceiver = when (declarationDescriptor) { + is ClassDescriptor -> declarationDescriptor.thisAsReceiverParameter + is FunctionDescriptor -> declarationDescriptor.extensionReceiverParameter + is PropertyDescriptor -> declarationDescriptor.extensionReceiverParameter + else -> throw UnsupportedOperationException("Unsupported descriptor: " + declarationDescriptor) // TODO } - } - return LabeledReceiverResolutionResult.labelResolutionSuccess(thisReceiver) - } - else if (size == 0) { - val element = resolveNamedLabel(labelName, targetLabel, context.trace) - val declarationDescriptor = context.trace.bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, element] - if (declarationDescriptor is FunctionDescriptor) { - val thisReceiver = declarationDescriptor.extensionReceiverParameter - if (thisReceiver != null) { - context.trace.record(LABEL_TARGET, targetLabel, element) - context.trace.record(REFERENCE_TARGET, referenceExpression, declarationDescriptor) + val element = DescriptorToSourceUtils.descriptorToDeclaration(declarationDescriptor) + ?: error("No PSI element for descriptor: " + declarationDescriptor) + context.trace.record(LABEL_TARGET, targetLabel, element) + context.trace.record(REFERENCE_TARGET, referenceExpression, declarationDescriptor) + + if (declarationDescriptor is ClassDescriptor) { + if (!DescriptorResolver.checkHasOuterClassInstance(context.scope, context.trace, targetLabel, declarationDescriptor)) { + return LabeledReceiverResolutionResult.labelResolutionFailed() + } } + return LabeledReceiverResolutionResult.labelResolutionSuccess(thisReceiver) } - else { - context.trace.report(UNRESOLVED_REFERENCE.on(targetLabel, targetLabel)) + 0 -> { + val element = resolveNamedLabel(labelName, targetLabel, context.trace) + val declarationDescriptor = context.trace.bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, element] + if (declarationDescriptor is FunctionDescriptor) { + val thisReceiver = declarationDescriptor.extensionReceiverParameter + if (thisReceiver != null) { + context.trace.record(LABEL_TARGET, targetLabel, element) + context.trace.record(REFERENCE_TARGET, referenceExpression, declarationDescriptor) + } + return LabeledReceiverResolutionResult.labelResolutionSuccess(thisReceiver) + } + else { + context.trace.report(UNRESOLVED_REFERENCE.on(targetLabel, targetLabel)) + } } - } - else { - BindingContextUtils.reportAmbiguousLabel(context.trace, targetLabel, declarationsByLabel) + else -> BindingContextUtils.reportAmbiguousLabel(context.trace, targetLabel, declarationsByLabel) } return LabeledReceiverResolutionResult.labelResolutionFailed() } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/SenselessComparisonChecker.kt b/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/SenselessComparisonChecker.kt index adbed720be6..e8dc79cdc1d 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/SenselessComparisonChecker.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/types/expressions/SenselessComparisonChecker.kt @@ -38,9 +38,11 @@ object SenselessComparisonChecker { getNullability: (DataFlowValue) -> Nullability ) { val expr = - if (KtPsiUtil.isNullConstant(left)) right - else if (KtPsiUtil.isNullConstant(right)) left - else return + when { + KtPsiUtil.isNullConstant(left) -> right + KtPsiUtil.isNullConstant(right) -> left + else -> return + } val type = getType(expr) if (type == null || type.isError) return @@ -52,10 +54,12 @@ object SenselessComparisonChecker { val nullability = getNullability(value) val expressionIsAlways = - if (nullability == Nullability.NULL) equality - else if (nullability == Nullability.NOT_NULL) !equality - else if (nullability == Nullability.IMPOSSIBLE) false - else return + when (nullability) { + Nullability.NULL -> equality + Nullability.NOT_NULL -> !equality + Nullability.IMPOSSIBLE -> false + else -> return + } context.trace.report(Errors.SENSELESS_COMPARISON.on(expression, expression, expressionIsAlways)) } diff --git a/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/codegen/ExpressionCodegen.kt b/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/codegen/ExpressionCodegen.kt index 1de25920907..3b177164ab7 100644 --- a/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/codegen/ExpressionCodegen.kt +++ b/compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/codegen/ExpressionCodegen.kt @@ -632,22 +632,20 @@ class ExpressionCodegen( val stackElement = data.peek() - if (stackElement is TryInfo) { - //noinspection ConstantConditions - genFinallyBlockOrGoto(stackElement, null, afterBreakContinueLabel, data) - } - else if (stackElement is LoopInfo) { - val loop = expression.loop - //noinspection ConstantConditions - if (loop == stackElement.loop) { - val label = if (expression is IrBreak) stackElement.breakLabel else stackElement.continueLabel - mv.fixStackAndJump(label) - mv.mark(afterBreakContinueLabel) - return + when (stackElement) { + is TryInfo -> //noinspection ConstantConditions + genFinallyBlockOrGoto(stackElement, null, afterBreakContinueLabel, data) + is LoopInfo -> { + val loop = expression.loop + //noinspection ConstantConditions + if (loop == stackElement.loop) { + val label = if (expression is IrBreak) stackElement.breakLabel else stackElement.continueLabel + mv.fixStackAndJump(label) + mv.mark(afterBreakContinueLabel) + return + } } - } - else { - throw UnsupportedOperationException("Wrong BlockStackElement in processing stack") + else -> throw UnsupportedOperationException("Wrong BlockStackElement in processing stack") } data.pop() @@ -829,14 +827,12 @@ class ExpressionCodegen( private fun doFinallyOnReturn(afterReturnLabel: Label, data: BlockInfo) { if (!data.isEmpty()) { val stackElement = data.peek() - if (stackElement is TryInfo) { - genFinallyBlockOrGoto(stackElement, null, afterReturnLabel, data) - } - else if (stackElement is LoopInfo) { + when (stackElement) { + is TryInfo -> genFinallyBlockOrGoto(stackElement, null, afterReturnLabel, data) + is LoopInfo -> { - } - else { - throw UnsupportedOperationException("Wrong BlockStackElement in processing stack") + } + else -> throw UnsupportedOperationException("Wrong BlockStackElement in processing stack") } data.pop() diff --git a/compiler/ir/ir.psi2ir/src/org/jetbrains/kotlin/psi2ir/generators/StatementGenerator.kt b/compiler/ir/ir.psi2ir/src/org/jetbrains/kotlin/psi2ir/generators/StatementGenerator.kt index cbbb1ab9cf0..85e50677e4c 100644 --- a/compiler/ir/ir.psi2ir/src/org/jetbrains/kotlin/psi2ir/generators/StatementGenerator.kt +++ b/compiler/ir/ir.psi2ir/src/org/jetbrains/kotlin/psi2ir/generators/StatementGenerator.kt @@ -163,16 +163,18 @@ class StatementGenerator( } else { val label = expression.getTargetLabel() - if (label != null) { - val labelTarget = getOrFail(BindingContext.LABEL_TARGET, label) - val labelTargetDescriptor = getOrFail(BindingContext.DECLARATION_TO_DESCRIPTOR, labelTarget) - labelTargetDescriptor as CallableDescriptor - } - else if (ExpressionTypingUtils.isFunctionLiteral(scopeOwner)) { - BindingContextUtils.getContainingFunctionSkipFunctionLiterals(scopeOwner, true).first - } - else { - scopeOwnerAsCallable() + when { + label != null -> { + val labelTarget = getOrFail(BindingContext.LABEL_TARGET, label) + val labelTargetDescriptor = getOrFail(BindingContext.DECLARATION_TO_DESCRIPTOR, labelTarget) + labelTargetDescriptor as CallableDescriptor + } + ExpressionTypingUtils.isFunctionLiteral(scopeOwner) -> { + BindingContextUtils.getContainingFunctionSkipFunctionLiterals(scopeOwner, true).first + } + else -> { + scopeOwnerAsCallable() + } } } diff --git a/compiler/resolution/src/org/jetbrains/kotlin/resolve/calls/tower/ScopeTowerProcessors.kt b/compiler/resolution/src/org/jetbrains/kotlin/resolve/calls/tower/ScopeTowerProcessors.kt index fc59c88c473..32a0d531226 100644 --- a/compiler/resolution/src/org/jetbrains/kotlin/resolve/calls/tower/ScopeTowerProcessors.kt +++ b/compiler/resolution/src/org/jetbrains/kotlin/resolve/calls/tower/ScopeTowerProcessors.kt @@ -168,25 +168,27 @@ private fun createSimpleProcessor( classValueReceiver: Boolean, collectCandidates: CandidatesCollector ) : ScopeTowerProcessor { - if (explicitReceiver is ReceiverValueWithSmartCastInfo) { - return ExplicitReceiverScopeTowerProcessor(scopeTower, context, explicitReceiver, collectCandidates) - } - else if (explicitReceiver is QualifierReceiver) { - val qualifierProcessor = QualifierScopeTowerProcessor(scopeTower, context, explicitReceiver, collectCandidates) - if (!classValueReceiver) return qualifierProcessor - - // todo enum entry, object. - val classValue = explicitReceiver.classValueReceiverWithSmartCastInfo ?: return qualifierProcessor - return CompositeScopeTowerProcessor( - qualifierProcessor, - ExplicitReceiverScopeTowerProcessor(scopeTower, context, classValue, collectCandidates) - ) - } - else { - assert(explicitReceiver == null) { - "Illegal explicit receiver: $explicitReceiver(${explicitReceiver!!::class.java.simpleName})" + return when (explicitReceiver) { + is ReceiverValueWithSmartCastInfo -> { + ExplicitReceiverScopeTowerProcessor(scopeTower, context, explicitReceiver, collectCandidates) + } + is QualifierReceiver -> { + val qualifierProcessor = QualifierScopeTowerProcessor(scopeTower, context, explicitReceiver, collectCandidates) + if (!classValueReceiver) return qualifierProcessor + + // todo enum entry, object. + val classValue = explicitReceiver.classValueReceiverWithSmartCastInfo ?: return qualifierProcessor + CompositeScopeTowerProcessor( + qualifierProcessor, + ExplicitReceiverScopeTowerProcessor(scopeTower, context, classValue, collectCandidates) + ) + } + else -> { + assert(explicitReceiver == null) { + "Illegal explicit receiver: $explicitReceiver(${explicitReceiver!!::class.java.simpleName})" + } + NoExplicitReceiverScopeTowerProcessor(context, collectCandidates) } - return NoExplicitReceiverScopeTowerProcessor(context, collectCandidates) } } diff --git a/core/descriptors/src/org/jetbrains/kotlin/types/checker/NewKotlinTypeChecker.kt b/core/descriptors/src/org/jetbrains/kotlin/types/checker/NewKotlinTypeChecker.kt index a3e43294e31..659358638e1 100644 --- a/core/descriptors/src/org/jetbrains/kotlin/types/checker/NewKotlinTypeChecker.kt +++ b/core/descriptors/src/org/jetbrains/kotlin/types/checker/NewKotlinTypeChecker.kt @@ -252,19 +252,21 @@ object NewKotlinTypeChecker : KotlinTypeChecker { anySupertype(baseType, { false }) { val current = captureFromArguments(it, CaptureStatus.FOR_SUBTYPING) - if (areEqualTypeConstructors(current.constructor, constructor)) { - if (result == null) { - result = SmartList() - } - result!!.add(current) + when { + areEqualTypeConstructors(current.constructor, constructor) -> { + if (result == null) { + result = SmartList() + } + result!!.add(current) - SupertypesPolicy.None - } - else if (current.arguments.isEmpty()) { - SupertypesPolicy.LowerIfFlexible - } - else { - SupertypesPolicy.LowerIfFlexibleWithCustomSubstitutor(TypeConstructorSubstitution.create(current).buildSubstitutor()) + SupertypesPolicy.None + } + current.arguments.isEmpty() -> { + SupertypesPolicy.LowerIfFlexible + } + else -> { + SupertypesPolicy.LowerIfFlexibleWithCustomSubstitutor(TypeConstructorSubstitution.create(current).buildSubstitutor()) + } } } diff --git a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/RuntimeTypeMapper.kt b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/RuntimeTypeMapper.kt index 661aa0e4628..2d215a42530 100644 --- a/core/reflection.jvm/src/kotlin/reflect/jvm/internal/RuntimeTypeMapper.kt +++ b/core/reflection.jvm/src/kotlin/reflect/jvm/internal/RuntimeTypeMapper.kt @@ -208,29 +208,33 @@ internal object RuntimeTypeMapper { fun mapPropertySignature(possiblyOverriddenProperty: PropertyDescriptor): JvmPropertySignature { val property = DescriptorUtils.unwrapFakeOverride(possiblyOverriddenProperty).original - if (property is DeserializedPropertyDescriptor) { - val proto = property.proto - if (!proto.hasExtension(JvmProtoBuf.propertySignature)) { - // If this property has no JVM signature, it must be from built-ins - throw KotlinReflectionInternalError("Reflection on built-in Kotlin types is not yet fully supported. " + - "No metadata found for $property") - } - return JvmPropertySignature.KotlinProperty( - property, proto, proto.getExtension(JvmProtoBuf.propertySignature), property.nameResolver, property.typeTable - ) - } - else if (property is JavaPropertyDescriptor) { - val element = (property.source as? JavaSourceElement)?.javaElement - when (element) { - is ReflectJavaField -> return JvmPropertySignature.JavaField(element.member) - is ReflectJavaMethod -> return JvmPropertySignature.JavaMethodProperty( - element.member, - ((property.setter?.source as? JavaSourceElement)?.javaElement as? ReflectJavaMethod)?.member + return when (property) { + is DeserializedPropertyDescriptor -> { + val proto = property.proto + if (!proto.hasExtension(JvmProtoBuf.propertySignature)) { + // If this property has no JVM signature, it must be from built-ins + throw KotlinReflectionInternalError("Reflection on built-in Kotlin types is not yet fully supported. " + + "No metadata found for $property") + } + JvmPropertySignature.KotlinProperty( + property, proto, proto.getExtension(JvmProtoBuf.propertySignature), property.nameResolver, property.typeTable ) - else -> throw KotlinReflectionInternalError("Incorrect resolution sequence for Java field $property (source = $element)") + } + is JavaPropertyDescriptor -> { + val element = (property.source as? JavaSourceElement)?.javaElement + when (element) { + is ReflectJavaField -> JvmPropertySignature.JavaField(element.member) + is ReflectJavaMethod -> JvmPropertySignature.JavaMethodProperty( + element.member, + ((property.setter?.source as? JavaSourceElement)?.javaElement as? ReflectJavaMethod)?.member + ) + else -> throw KotlinReflectionInternalError("Incorrect resolution sequence for Java field $property (source = $element)") + } + } + else -> { + throw KotlinReflectionInternalError("Unknown origin of $property (${property.javaClass})") } } - else throw KotlinReflectionInternalError("Unknown origin of $property (${property.javaClass})") } private fun mapIntrinsicFunctionSignature(function: FunctionDescriptor): JvmFunctionSignature? { diff --git a/eval4j/src/org/jetbrains/eval4j/interpreter.kt b/eval4j/src/org/jetbrains/eval4j/interpreter.kt index eb97e5b57d7..2cb375f5b4a 100644 --- a/eval4j/src/org/jetbrains/eval4j/interpreter.kt +++ b/eval4j/src/org/jetbrains/eval4j/interpreter.kt @@ -181,13 +181,10 @@ class SingleInstructionInterpreter(private val eval: Eval) : Interpreter( CHECKCAST -> { val targetType = Type.getObjectType((insn as TypeInsnNode).desc) - if (value == NULL_VALUE) { - NULL_VALUE - } else if (eval.isInstanceOf(value, targetType)) { - ObjectValue(value.obj(), targetType) - } - else { - throwEvalException(ClassCastException("${value.asmType.className} cannot be cast to ${targetType.className}")) + when { + value == NULL_VALUE -> NULL_VALUE + eval.isInstanceOf(value, targetType) -> ObjectValue(value.obj(), targetType) + else -> throwEvalException(ClassCastException("${value.asmType.className} cannot be cast to ${targetType.className}")) } } diff --git a/idea/ide-common/src/org/jetbrains/kotlin/idea/util/OptimizedImportsBuilder.kt b/idea/ide-common/src/org/jetbrains/kotlin/idea/util/OptimizedImportsBuilder.kt index 4033db23719..f3ca8c680a8 100644 --- a/idea/ide-common/src/org/jetbrains/kotlin/idea/util/OptimizedImportsBuilder.kt +++ b/idea/ide-common/src/org/jetbrains/kotlin/idea/util/OptimizedImportsBuilder.kt @@ -212,14 +212,13 @@ class OptimizedImportsBuilder( val explicitImportPath = ImportPath(fqName, false) val starImportPath = ImportPath(fqName.parent(), true) val importPaths = file.importDirectives.map { it.importPath } - if (explicitImportPath in importPaths) { - importRules.add(ImportRule.Add(explicitImportPath)) - } - else if (starImportPath in importPaths) { - importRules.add(ImportRule.Add(starImportPath)) - } - else { // there is no import for this descriptor in the original import list, so do not allow to import it by star-import - importRules.add(ImportRule.DoNotAdd(starImportPath)) + when { + explicitImportPath in importPaths -> + importRules.add(ImportRule.Add(explicitImportPath)) + starImportPath in importPaths -> + importRules.add(ImportRule.Add(starImportPath)) + else -> // there is no import for this descriptor in the original import list, so do not allow to import it by star-import + importRules.add(ImportRule.DoNotAdd(starImportPath)) } } @@ -277,14 +276,10 @@ class OptimizedImportsBuilder( val iterator1 = tower1.iterator() val iterator2 = tower2.iterator() while (true) { - if (!iterator1.hasNext()) { - return !iterator2.hasNext() - } - else if (!iterator2.hasNext()) { - return false - } - else { - if (!areTargetsEqual(iterator1.next(), iterator2.next())) return false + when { + !iterator1.hasNext() -> return !iterator2.hasNext() + !iterator2.hasNext() -> return false + else -> if (!areTargetsEqual(iterator1.next(), iterator2.next())) return 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 09c8bae8be1..013146183d9 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 @@ -271,18 +271,18 @@ class PartialBodyResolveFilter( val left = condition.left ?: return emptyResult val right = condition.right ?: return emptyResult - fun smartCastInEq(): Pair, Set> { - if (left.isNullLiteral()) { - return Pair(setOf(), right.smartCastExpressionName().singletonOrEmptySet()) + fun smartCastInEq(): Pair, Set> = when { + left.isNullLiteral() -> { + Pair(setOf(), right.smartCastExpressionName().singletonOrEmptySet()) } - else if (right.isNullLiteral()) { - return Pair(setOf(), left.smartCastExpressionName().singletonOrEmptySet()) + right.isNullLiteral() -> { + Pair(setOf(), left.smartCastExpressionName().singletonOrEmptySet()) } - else { + else -> { val leftName = left.smartCastExpressionName() val rightName = right.smartCastExpressionName() val names = listOfNotNull(leftName, rightName).toSet() - return Pair(names, setOf()) + Pair(names, setOf()) } } diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/resolve/lightClasses/IDELightClassContexts.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/resolve/lightClasses/IDELightClassContexts.kt index c6489fcb63b..8c5d03c448d 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/resolve/lightClasses/IDELightClassContexts.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/caches/resolve/lightClasses/IDELightClassContexts.kt @@ -217,26 +217,26 @@ object IDELightClassContexts { } for (declaration in file.declarations) { - if (declaration is KtFunction) { - val name = declaration.nameAsSafeName - val functions = packageDescriptor.memberScope.getContributedFunctions(name, NoLookupLocation.FROM_IDE) - for (descriptor in functions) { - ForceResolveUtil.forceResolveAllContents(descriptor) + when (declaration) { + is KtFunction -> { + val name = declaration.nameAsSafeName + val functions = packageDescriptor.memberScope.getContributedFunctions(name, NoLookupLocation.FROM_IDE) + for (descriptor in functions) { + ForceResolveUtil.forceResolveAllContents(descriptor) + } } - } - else if (declaration is KtProperty) { - val name = declaration.nameAsSafeName - val properties = packageDescriptor.memberScope.getContributedVariables(name, NoLookupLocation.FROM_IDE) - for (descriptor in properties) { - ForceResolveUtil.forceResolveAllContents(descriptor) + is KtProperty -> { + val name = declaration.nameAsSafeName + val properties = packageDescriptor.memberScope.getContributedVariables(name, NoLookupLocation.FROM_IDE) + for (descriptor in properties) { + ForceResolveUtil.forceResolveAllContents(descriptor) + } } - } - else if (declaration is KtClassOrObject || declaration is KtTypeAlias || declaration is KtDestructuringDeclaration) { - // Do nothing: we are not interested in classes or type aliases, - // and all destructuring declarations are erroneous at top level - } - else { - LOG.error("Unsupported declaration kind: " + declaration + " in file " + file.name + "\n" + file.text) + is KtClassOrObject, is KtTypeAlias, is KtDestructuringDeclaration -> { + // Do nothing: we are not interested in classes or type aliases, + // and all destructuring declarations are erroneous at top level + } + else -> LOG.error("Unsupported declaration kind: " + declaration + " in file " + file.name + "\n" + file.text) } } 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 bb3566cab03..278fcfc3eae 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 @@ -101,11 +101,18 @@ object UsageTypeUtils { CLASS_CAST_TO with(refExpr.getNonStrictParentOfType()) { - if (this == null) false - else if (receiverExpression == refExpr) true - else - selectorExpression == refExpr - && getParentOfTypeAndBranch(strict = true) { receiverExpression } != null + when { + this == null -> { + false + } + receiverExpression == refExpr -> { + true + } + else -> { + selectorExpression == refExpr + && getParentOfTypeAndBranch(strict = true) { receiverExpression } != null + } + } } -> CLASS_OBJECT_ACCESS diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/framework/CommonLibraryDetectionUtil.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/framework/CommonLibraryDetectionUtil.kt index d63af1673a2..ba91aa214f5 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/framework/CommonLibraryDetectionUtil.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/framework/CommonLibraryDetectionUtil.kt @@ -49,12 +49,11 @@ object CommonLibraryDetectionUtil { var platform: TargetPlatform? = null VfsUtilCore.processFilesRecursively(root) { file -> - if (file.fileType == JavaClassFileType.INSTANCE) - platform = JvmPlatform - else if (isKotlinMetadataFile(file)) - platform = TargetPlatform.Default - else if (KotlinJavaScriptLibraryDetectionUtil.isJsFileWithMetadata(file)) - platform = JsPlatform + when { + file.fileType == JavaClassFileType.INSTANCE -> platform = JvmPlatform + isKotlinMetadataFile(file) -> platform = TargetPlatform.Default + KotlinJavaScriptLibraryDetectionUtil.isJsFileWithMetadata(file) -> platform = JsPlatform + } platform == null } diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/quickfix/KotlinSuppressIntentionAction.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/quickfix/KotlinSuppressIntentionAction.kt index 2de901bd436..c9a525b30eb 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/quickfix/KotlinSuppressIntentionAction.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/quickfix/KotlinSuppressIntentionAction.kt @@ -129,16 +129,12 @@ class KotlinSuppressIntentionAction private constructor( val args = entry.valueArgumentList val psiFactory = KtPsiFactory(entry) val newArgList = psiFactory.createCallArguments("($id)") - if (args == null) { - // new argument list - entry.addAfter(newArgList, entry.lastChild) - } - else if (args.arguments.isEmpty()) { - // replace '()' with a new argument list - args.replace(newArgList) - } - else { - args.addArgument(newArgList.arguments[0]) + when { + args == null -> // new argument list + entry.addAfter(newArgList, entry.lastChild) + args.arguments.isEmpty() -> // replace '()' with a new argument list + args.replace(newArgList) + else -> args.addArgument(newArgList.arguments[0]) } } 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 98377554335..991972b0e0c 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 @@ -151,14 +151,10 @@ class PsiBasedClassResolver @TestOnly constructor(private val targetClassFqName: val file = ref.containingKtFile var result: Result = Result.NothingFound val filePackage = file.packageFqName.asString() - if (filePackage == targetPackage) { - result = result.changeTo(Result.Found) - } - else if (filePackage in conflictingPackages) { - result = result.changeTo(Result.FoundOther) - } - else if (filePackage in packagesWithTypeAliases) { - return UNSURE + when (filePackage) { + targetPackage -> result = result.changeTo(Result.Found) + in conflictingPackages -> result = result.changeTo(Result.FoundOther) + in packagesWithTypeAliases -> return UNSURE } for (importPath in file.getDefaultImports()) { @@ -202,14 +198,10 @@ class PsiBasedClassResolver @TestOnly constructor(private val targetClassFqName: } } else { - if (qName?.asString() == targetPackage) { - return result.changeTo(Result.Found) - } - else if (qName?.asString() in conflictingPackages) { - return result.changeTo(Result.FoundOther) - } - else if (qName?.asString() in packagesWithTypeAliases) { - return Result.Ambiguity + when { + qName?.asString() == targetPackage -> return result.changeTo(Result.Found) + qName?.asString() in conflictingPackages -> return result.changeTo(Result.FoundOther) + qName?.asString() in packagesWithTypeAliases -> return Result.Ambiguity } } return result 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 a60c04a8527..43e36117548 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 @@ -276,12 +276,11 @@ class BasicLookupElementFactory( appendTailText(" for $receiverPresentation") val container = descriptor.containingDeclaration - val containerPresentation = if (container is ClassDescriptor) - DescriptorUtils.getFqNameFromTopLevelClass(container).toString() - else if (container is PackageFragmentDescriptor) - container.fqName.toString() - else - null + val containerPresentation = when (container) { + is ClassDescriptor -> DescriptorUtils.getFqNameFromTopLevelClass(container).toString() + is PackageFragmentDescriptor -> container.fqName.toString() + else -> null + } if (containerPresentation != null) { appendTailText(" in $containerPresentation") } 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 8d783150043..d329f87fffb 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 @@ -96,32 +96,29 @@ class CompletionBindingContextProvider(project: Project) { val psiElementsBeforeAndAfter = modificationScope?.let { collectPsiElementsBeforeAndAfter(modificationScope, inStatement) } val prevCompletionData = prevCompletionDataCache.value.data - if (prevCompletionData == null) { - log("No up-to-date data from previous completion\n") - } - else if (block != prevCompletionData.block) { - log("Not in the same block\n") - } - else if (prevStatement != prevCompletionData.prevStatement) { - log("Previous statement is not the same\n") - } - else if (psiElementsBeforeAndAfter != prevCompletionData.psiElementsBeforeAndAfter) { - log("PSI-tree has changed inside current scope\n") - } - else if (inStatement.isTooComplex()) { - log("Current statement is too complex to use optimization\n") - } - else { - log("Statement position is the same - analyzing only one statement:\n${inStatement.text.prependIndent(" ")}\n") - LOG.debug("Reusing data from completion of \"${prevCompletionData.debugText}\"") + when { + prevCompletionData == null -> + log("No up-to-date data from previous completion\n") + block != prevCompletionData.block -> + log("Not in the same block\n") + prevStatement != prevCompletionData.prevStatement -> + log("Previous statement is not the same\n") + psiElementsBeforeAndAfter != prevCompletionData.psiElementsBeforeAndAfter -> + log("PSI-tree has changed inside current scope\n") + inStatement.isTooComplex() -> + log("Current statement is too complex to use optimization\n") + else -> { + log("Statement position is the same - analyzing only one statement:\n${inStatement.text.prependIndent(" ")}\n") + 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) - // we do not update prevCompletionDataCache because the same data should work - return CompositeBindingContext.create(listOf(statementContext, prevCompletionData.bindingContext)) + //TODO: expected type? + 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) 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 c51a64413d7..45ac0abf328 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 @@ -381,20 +381,17 @@ class LookupElementFactory( return CallableWeight(bestWeight, receiverIndexToUse) } - private fun CallableDescriptor.callableWeightForReceiverType(receiverType: KotlinType, receiverParameterType: KotlinType): CallableWeightEnum? { - if (TypeUtils.equalTypes(receiverType, receiverParameterType)) { - return when { - isExtensionForTypeParameter() -> CallableWeightEnum.typeParameterExtension - isExtension -> CallableWeightEnum.thisTypeExtension - else -> CallableWeightEnum.thisClassMember - } - } - else if (receiverType.isSubtypeOf(receiverParameterType)) { - return if (isExtension) CallableWeightEnum.baseTypeExtension else CallableWeightEnum.baseClassMember - } - else { - return null + private fun CallableDescriptor.callableWeightForReceiverType( + receiverType: KotlinType, + receiverParameterType: KotlinType + ): CallableWeightEnum? = when { + TypeUtils.equalTypes(receiverType, receiverParameterType) -> when { + isExtensionForTypeParameter() -> CallableWeightEnum.typeParameterExtension + isExtension -> CallableWeightEnum.thisTypeExtension + else -> CallableWeightEnum.thisClassMember } + receiverType.isSubtypeOf(receiverParameterType) -> if (isExtension) CallableWeightEnum.baseTypeExtension else CallableWeightEnum.baseClassMember + else -> null } private fun CallableDescriptor.isExtensionForTypeParameter(): Boolean { 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 0dbe01bf5bd..47127b92591 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 @@ -343,12 +343,11 @@ class ExpectedInfos( } val tail = if (argumentName == null) { - if (parameter == parameters.last()) - rparenthTail - else if (parameters.dropWhile { it != parameter }.drop(1).any(::needCommaForParameter)) - Tail.COMMA - else - null + when { + parameter == parameters.last() -> rparenthTail + parameters.dropWhile { it != parameter }.drop(1).any(::needCommaForParameter) -> Tail.COMMA + else -> null + } } else { namedArgumentTail(argumentToParameter, argumentName, descriptor) @@ -404,12 +403,11 @@ class ExpectedInfos( 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 if (notUsedParameters.isEmpty()) - Tail.RPARENTH // named arguments no supported for [] - else if (notUsedParameters.all { it.hasDefaultValue() }) - null - else - Tail.COMMA + return when { + notUsedParameters.isEmpty() -> Tail.RPARENTH // named arguments no supported for [] + notUsedParameters.all { it.hasDefaultValue() } -> null + else -> Tail.COMMA + } } private fun calculateForEqAndAssignment(expressionWithType: KtExpression): Collection? { 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 2e7ec69aecc..c181989b130 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 @@ -35,15 +35,14 @@ class ImportableFqNameClassifier(private val file: KtFile) { for (import in file.importDirectives) { val importPath = import.importPath ?: continue val fqName = importPath.fqName - if (importPath.isAllUnder) { - allUnderImports.add(fqName) - } - else if (!importPath.hasAlias()) { - preciseImports.add(fqName) - preciseImportPackages.add(fqName.parent()) - } else { - excludedImports.add(fqName) - // TODO: support aliased imports in completion + when { + importPath.isAllUnder -> allUnderImports.add(fqName) + !importPath.hasAlias() -> { + preciseImports.add(fqName) + preciseImportPackages.add(fqName.parent()) + } + else -> excludedImports.add(fqName) + // TODO: support aliased imports in completion } } } diff --git a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/KotlinNameSuggester.kt b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/KotlinNameSuggester.kt index af78d37f708..e9997690574 100644 --- a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/KotlinNameSuggester.kt +++ b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/KotlinNameSuggester.kt @@ -174,79 +174,45 @@ object KotlinNameSuggester { val typeChecker = KotlinTypeChecker.DEFAULT if (ErrorUtils.containsErrorType(type)) return - if (typeChecker.equalTypes(builtIns.booleanType, type)) { - addName("b", validator) - } - else if (typeChecker.equalTypes(builtIns.intType, type)) { - addName("i", validator) - } - else if (typeChecker.equalTypes(builtIns.byteType, type)) { - addName("byte", validator) - } - else if (typeChecker.equalTypes(builtIns.longType, type)) { - addName("l", validator) - } - else if (typeChecker.equalTypes(builtIns.floatType, type)) { - addName("fl", validator) - } - else if (typeChecker.equalTypes(builtIns.doubleType, type)) { - addName("d", validator) - } - else if (typeChecker.equalTypes(builtIns.shortType, type)) { - addName("sh", validator) - } - else if (typeChecker.equalTypes(builtIns.charType, type)) { - addName("c", validator) - } - else if (typeChecker.equalTypes(builtIns.stringType, type)) { - addName("s", validator) - } - else if (KotlinBuiltIns.isArray(type) || KotlinBuiltIns.isPrimitiveArray(type)) { - val elementType = builtIns.getArrayElementType(type) - if (typeChecker.equalTypes(builtIns.booleanType, elementType)) { - addName("booleans", validator) - } - else if (typeChecker.equalTypes(builtIns.intType, elementType)) { - addName("ints", validator) - } - else if (typeChecker.equalTypes(builtIns.byteType, elementType)) { - addName("bytes", validator) - } - else if (typeChecker.equalTypes(builtIns.longType, elementType)) { - addName("longs", validator) - } - else if (typeChecker.equalTypes(builtIns.floatType, elementType)) { - addName("floats", validator) - } - else if (typeChecker.equalTypes(builtIns.doubleType, elementType)) { - addName("doubles", validator) - } - else if (typeChecker.equalTypes(builtIns.shortType, elementType)) { - addName("shorts", validator) - } - else if (typeChecker.equalTypes(builtIns.charType, elementType)) { - addName("chars", validator) - } - else if (typeChecker.equalTypes(builtIns.stringType, elementType)) { - addName("strings", validator) - } - else { - val classDescriptor = TypeUtils.getClassDescriptor(elementType) - if (classDescriptor != null) { - val className = classDescriptor.name - addName("arrayOf" + StringUtil.capitalize(className.asString()) + "s", validator) + when { + typeChecker.equalTypes(builtIns.booleanType, type) -> addName("b", validator) + typeChecker.equalTypes(builtIns.intType, type) -> addName("i", validator) + typeChecker.equalTypes(builtIns.byteType, type) -> addName("byte", validator) + typeChecker.equalTypes(builtIns.longType, type) -> addName("l", validator) + typeChecker.equalTypes(builtIns.floatType, type) -> addName("fl", validator) + typeChecker.equalTypes(builtIns.doubleType, type) -> addName("d", validator) + typeChecker.equalTypes(builtIns.shortType, type) -> addName("sh", validator) + typeChecker.equalTypes(builtIns.charType, type) -> addName("c", validator) + typeChecker.equalTypes(builtIns.stringType, type) -> addName("s", validator) + KotlinBuiltIns.isArray(type) || KotlinBuiltIns.isPrimitiveArray(type) -> { + val elementType = builtIns.getArrayElementType(type) + when { + typeChecker.equalTypes(builtIns.booleanType, elementType) -> addName("booleans", validator) + typeChecker.equalTypes(builtIns.intType, elementType) -> addName("ints", validator) + typeChecker.equalTypes(builtIns.byteType, elementType) -> addName("bytes", validator) + typeChecker.equalTypes(builtIns.longType, elementType) -> addName("longs", validator) + typeChecker.equalTypes(builtIns.floatType, elementType) -> addName("floats", validator) + typeChecker.equalTypes(builtIns.doubleType, elementType) -> addName("doubles", validator) + typeChecker.equalTypes(builtIns.shortType, elementType) -> addName("shorts", validator) + typeChecker.equalTypes(builtIns.charType, elementType) -> addName("chars", validator) + typeChecker.equalTypes(builtIns.stringType, elementType) -> addName("strings", validator) + else -> { + val classDescriptor = TypeUtils.getClassDescriptor(elementType) + if (classDescriptor != null) { + val className = classDescriptor.name + addName("arrayOf" + StringUtil.capitalize(className.asString()) + "s", validator) + } + } } } - } - else if (type.isFunctionType) { - addName("function", validator) - } - else { - val descriptor = type.constructor.declarationDescriptor - if (descriptor != null) { - val className = descriptor.name - if (!className.isSpecial) { - addCamelNames(className.asString(), validator) + type.isFunctionType -> addName("function", validator) + else -> { + val descriptor = type.constructor.declarationDescriptor + if (descriptor != null) { + val className = descriptor.name + if (!className.isSpecial) { + addCamelNames(className.asString(), validator) + } } } } 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 85df333aa40..cd16bd1f9ef 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 @@ -204,25 +204,24 @@ fun KtModifierListOwner.setVisibility(visibilityModifier: KtModifierKeywordToken } fun KtDeclaration.implicitVisibility(): KtModifierKeywordToken? = - if (this is KtConstructor<*>) { - val klass = getContainingClassOrObject() - if (klass is KtClass && (klass.isEnum() || klass.isSealed())) KtTokens.PRIVATE_KEYWORD - else KtTokens.DEFAULT_VISIBILITY_KEYWORD - } - else if (hasModifier(KtTokens.OVERRIDE_KEYWORD)) { - (resolveToDescriptor(BodyResolveMode.PARTIAL) as? CallableMemberDescriptor) - ?.overriddenDescriptors - ?.let { OverridingUtil.findMaxVisibility(it) } - ?.toKeywordToken() - } - else { - KtTokens.DEFAULT_VISIBILITY_KEYWORD + when { + this is KtConstructor<*> -> { + val klass = getContainingClassOrObject() + if (klass is KtClass && (klass.isEnum() || klass.isSealed())) KtTokens.PRIVATE_KEYWORD + else KtTokens.DEFAULT_VISIBILITY_KEYWORD + } + hasModifier(KtTokens.OVERRIDE_KEYWORD) -> { + (resolveToDescriptor(BodyResolveMode.PARTIAL) as? CallableMemberDescriptor) + ?.overriddenDescriptors + ?.let { OverridingUtil.findMaxVisibility(it) } + ?.toKeywordToken() + } + else -> { + KtTokens.DEFAULT_VISIBILITY_KEYWORD + } } -fun KtModifierListOwner.canBePrivate(): Boolean { - if (modifierList?.hasModifier(KtTokens.ABSTRACT_KEYWORD) ?: false) return false - return true -} +fun KtModifierListOwner.canBePrivate() = modifierList?.hasModifier(KtTokens.ABSTRACT_KEYWORD) != true fun KtModifierListOwner.canBeProtected(): Boolean { val parent = this.parent diff --git a/idea/idea-maven/src/org/jetbrains/kotlin/idea/maven/actions/MavenPluginSourcesSwap.kt b/idea/idea-maven/src/org/jetbrains/kotlin/idea/maven/actions/MavenPluginSourcesSwap.kt index 396c33a1b07..f7e86ac40e5 100644 --- a/idea/idea-maven/src/org/jetbrains/kotlin/idea/maven/actions/MavenPluginSourcesSwap.kt +++ b/idea/idea-maven/src/org/jetbrains/kotlin/idea/maven/actions/MavenPluginSourcesSwap.kt @@ -75,12 +75,12 @@ class MavenPluginSourcesMoveToExecutionIntention : PsiElementBaseIntentionAction val domElement = DomManager.getDomManager(project).getDomElement(tag) as? GenericDomValue<*> ?: return val dir = domElement.rawText ?: return - val relevantExecutions = if (domElement.getParentOfType(MavenDomBuild::class.java, false)?.sourceDirectory === domElement) { - pomFile.findKotlinExecutions(PomFile.KotlinGoals.Compile, PomFile.KotlinGoals.Js) - } else if (domElement.getParentOfType(MavenDomBuild::class.java, false)?.testSourceDirectory === domElement) { - pomFile.findKotlinExecutions(PomFile.KotlinGoals.TestCompile, PomFile.KotlinGoals.TestJs) - } else { - emptyList() + val relevantExecutions = when { + domElement.getParentOfType(MavenDomBuild::class.java, false)?.sourceDirectory === domElement -> + pomFile.findKotlinExecutions(PomFile.KotlinGoals.Compile, PomFile.KotlinGoals.Js) + domElement.getParentOfType(MavenDomBuild::class.java, false)?.testSourceDirectory === domElement -> + pomFile.findKotlinExecutions(PomFile.KotlinGoals.TestCompile, PomFile.KotlinGoals.TestJs) + else -> emptyList() } if (relevantExecutions.isNotEmpty()) { diff --git a/idea/src/org/jetbrains/kotlin/idea/configuration/KotlinWithLibraryConfigurator.kt b/idea/src/org/jetbrains/kotlin/idea/configuration/KotlinWithLibraryConfigurator.kt index e4324c6be26..d95fd5e9ab6 100644 --- a/idea/src/org/jetbrains/kotlin/idea/configuration/KotlinWithLibraryConfigurator.kt +++ b/idea/src/org/jetbrains/kotlin/idea/configuration/KotlinWithLibraryConfigurator.kt @@ -263,19 +263,11 @@ abstract class KotlinWithLibraryConfigurator internal constructor() : KotlinProj targetFile: File, jarType: OrderRootType, useBundled: Boolean - ): FileState { - if (targetFile.exists()) { - return FileState.EXISTS - } - else if (getPathFromLibrary(project, jarType) != null) { - return FileState.COPY - } - else if (useBundled) { - return FileState.DO_NOT_COPY - } - else { - return FileState.COPY - } + ): FileState = when { + targetFile.exists() -> FileState.EXISTS + getPathFromLibrary(project, jarType) != null -> FileState.COPY + useBundled -> FileState.DO_NOT_COPY + else -> FileState.COPY } private fun getPathToCopyFileTo( diff --git a/idea/src/org/jetbrains/kotlin/idea/debugger/DebuggerClassNameProvider.kt b/idea/src/org/jetbrains/kotlin/idea/debugger/DebuggerClassNameProvider.kt index 473c0429910..17b73c9e4da 100644 --- a/idea/src/org/jetbrains/kotlin/idea/debugger/DebuggerClassNameProvider.kt +++ b/idea/src/org/jetbrains/kotlin/idea/debugger/DebuggerClassNameProvider.kt @@ -120,26 +120,27 @@ class DebuggerClassNameProvider( } is KtClassOrObject -> { val enclosingElementForLocal = runReadAction { KtPsiUtil.getEnclosingElementForLocalDeclaration(element) } - if (enclosingElementForLocal != null) { // A local class - getOuterClassNamesForElement(enclosingElementForLocal) - } - else if (runReadAction { element.isObjectLiteral() }) { - getOuterClassNamesForElement(element.relevantParentInReadAction) - } - else { // Guaranteed to be non-local class or object - element.readAction { - if (it is KtClass && runReadAction { it.isInterface() }) { - val name = getNameForNonLocalClass(it) + when { + enclosingElementForLocal != null -> + // A local class + getOuterClassNamesForElement(enclosingElementForLocal) + runReadAction { element.isObjectLiteral() } -> + getOuterClassNamesForElement(element.relevantParentInReadAction) + else -> + // Guaranteed to be non-local class or object + element.readAction { + if (it is KtClass && runReadAction { it.isInterface() }) { + val name = getNameForNonLocalClass(it) - if (name != null) - Cached(listOf(name, name + JvmAbi.DEFAULT_IMPLS_SUFFIX)) - else - ComputedClassNames.EMPTY + if (name != null) + Cached(listOf(name, name + JvmAbi.DEFAULT_IMPLS_SUFFIX)) + else + ComputedClassNames.EMPTY + } + else { + getNameForNonLocalClass(it)?.let { ComputedClassNames.Cached(it) } ?: ComputedClassNames.EMPTY + } } - else { - getNameForNonLocalClass(it)?.let { ComputedClassNames.Cached(it) } ?: ComputedClassNames.EMPTY - } - } } } is KtProperty -> { diff --git a/idea/src/org/jetbrains/kotlin/idea/debugger/evaluate/KotlinEvaluationBuilder.kt b/idea/src/org/jetbrains/kotlin/idea/debugger/evaluate/KotlinEvaluationBuilder.kt index fafdcb770d8..c1ea26f6290 100644 --- a/idea/src/org/jetbrains/kotlin/idea/debugger/evaluate/KotlinEvaluationBuilder.kt +++ b/idea/src/org/jetbrains/kotlin/idea/debugger/evaluate/KotlinEvaluationBuilder.kt @@ -300,14 +300,13 @@ class KotlinEvaluator(val codeFragment: KtCodeFragment, val sourcePosition: Sour val jdiValue = when (this) { is ValueReturned -> result is ExceptionThrown -> { - if (this.kind == ExceptionThrown.ExceptionKind.FROM_EVALUATED_CODE) { - exception(InvocationException(this.exception.value as ObjectReference)) - } - else if (this.kind == ExceptionThrown.ExceptionKind.BROKEN_CODE) { - throw exception.value as Throwable - } - else { - exception(exception.toString()) + when { + this.kind == ExceptionThrown.ExceptionKind.FROM_EVALUATED_CODE -> + exception(InvocationException(this.exception.value as ObjectReference)) + this.kind == ExceptionThrown.ExceptionKind.BROKEN_CODE -> + throw exception.value as Throwable + else -> + exception(exception.toString()) } } is AbnormalTermination -> exception(message) diff --git a/idea/src/org/jetbrains/kotlin/idea/editor/KotlinLiteralCopyPasteProcessor.kt b/idea/src/org/jetbrains/kotlin/idea/editor/KotlinLiteralCopyPasteProcessor.kt index 95e2b982cfb..11b210b7e72 100644 --- a/idea/src/org/jetbrains/kotlin/idea/editor/KotlinLiteralCopyPasteProcessor.kt +++ b/idea/src/org/jetbrains/kotlin/idea/editor/KotlinLiteralCopyPasteProcessor.kt @@ -187,33 +187,33 @@ private class TemplateTokenSequence(private val inputString: String) : Sequence< val wrapped = '"' + input.substring(from) + '"' val lexer = KotlinLexer().apply { start(wrapped) }.apply { advance() } - if (lexer.tokenType == KtTokens.SHORT_TEMPLATE_ENTRY_START) { - lexer.advance() - return if (lexer.tokenType == KtTokens.IDENTIFIER) { - from + lexer.tokenEnd - 1 - } - else { - -1 - } - } - else if (lexer.tokenType == KtTokens.LONG_TEMPLATE_ENTRY_START) { - var depth = 0 - while (lexer.tokenType != null) { - if (lexer.tokenType == KtTokens.LONG_TEMPLATE_ENTRY_START) { - depth++ - } - else if (lexer.tokenType == KtTokens.LONG_TEMPLATE_ENTRY_END) { - depth-- - if (depth == 0) { - return from + lexer.currentPosition.offset - } - } + when (lexer.tokenType) { + KtTokens.SHORT_TEMPLATE_ENTRY_START -> { lexer.advance() + return if (lexer.tokenType == KtTokens.IDENTIFIER) { + from + lexer.tokenEnd - 1 + } + else { + -1 + } } - return -1 - } - else { - return -1 + KtTokens.LONG_TEMPLATE_ENTRY_START -> { + var depth = 0 + while (lexer.tokenType != null) { + if (lexer.tokenType == KtTokens.LONG_TEMPLATE_ENTRY_START) { + depth++ + } + else if (lexer.tokenType == KtTokens.LONG_TEMPLATE_ENTRY_END) { + depth-- + if (depth == 0) { + return from + lexer.currentPosition.offset + } + } + lexer.advance() + } + return -1 + } + else -> return -1 } } diff --git a/idea/src/org/jetbrains/kotlin/idea/highlighter/KotlinRainbowVisitor.kt b/idea/src/org/jetbrains/kotlin/idea/highlighter/KotlinRainbowVisitor.kt index ce7c98b83f0..353f689e8b0 100644 --- a/idea/src/org/jetbrains/kotlin/idea/highlighter/KotlinRainbowVisitor.kt +++ b/idea/src/org/jetbrains/kotlin/idea/highlighter/KotlinRainbowVisitor.kt @@ -40,32 +40,34 @@ class KotlinRainbowVisitor : RainbowVisitor() { override fun clone() = KotlinRainbowVisitor() override fun visit(element: PsiElement) { - if (element.isRainbowDeclaration()) { - val rainbowElement = (element as KtNamedDeclaration).nameIdentifier ?: return - addRainbowHighlight(element, rainbowElement) - } - else if (element is KtSimpleNameExpression) { - val qualifiedExpression = PsiTreeUtil.getParentOfType(element, KtQualifiedExpression::class.java, true, - KtLambdaExpression::class.java, KtValueArgumentList::class.java) - if (qualifiedExpression?.selectorExpression?.isAncestor(element) == true) return + when { + element.isRainbowDeclaration() -> { + val rainbowElement = (element as KtNamedDeclaration).nameIdentifier ?: return + addRainbowHighlight(element, rainbowElement) + } + element is KtSimpleNameExpression -> { + val qualifiedExpression = PsiTreeUtil.getParentOfType(element, KtQualifiedExpression::class.java, true, + KtLambdaExpression::class.java, KtValueArgumentList::class.java) + if (qualifiedExpression?.selectorExpression?.isAncestor(element) == true) return - val bindingContext = element.analyze(BodyResolveMode.PARTIAL_WITH_DIAGNOSTICS) - val targets = element.getReferenceTargets(bindingContext) - val targetVariable = targets.firstIsInstanceOrNull() - if (targetVariable != null) { - val targetElement = DescriptorToSourceUtils.getSourceFromDescriptor(targetVariable) - if (targetElement.isRainbowDeclaration()) { - addRainbowHighlight(targetElement!!, element) - } - else if (targetElement == null && element.getReferencedName() == "it") { - addRainbowHighlight(element, element) + val bindingContext = element.analyze(BodyResolveMode.PARTIAL_WITH_DIAGNOSTICS) + val targets = element.getReferenceTargets(bindingContext) + val targetVariable = targets.firstIsInstanceOrNull() + if (targetVariable != null) { + val targetElement = DescriptorToSourceUtils.getSourceFromDescriptor(targetVariable) + if (targetElement.isRainbowDeclaration()) { + addRainbowHighlight(targetElement!!, element) + } + else if (targetElement == null && element.getReferencedName() == "it") { + addRainbowHighlight(element, element) + } } } - } - else if (element is KDocName) { - val target = element.reference?.resolve() ?: return - if (target.isRainbowDeclaration()) { - addRainbowHighlight(target, element, KDOC_LINK) + element is KDocName -> { + val target = element.reference?.resolve() ?: return + if (target.isRainbowDeclaration()) { + addRainbowHighlight(target, element, KDOC_LINK) + } } } } diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/KotlinUnusedImportInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/KotlinUnusedImportInspection.kt index 77bd98cea76..7bffb2614cc 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/KotlinUnusedImportInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/KotlinUnusedImportInspection.kt @@ -95,14 +95,10 @@ class KotlinUnusedImportInspection : AbstractKotlinInspection() { val importPath = directive.importPath ?: continue if (importPath.alias != null) continue // highlighting of unused alias imports not supported yet - val isUsed = if (!importPaths.add(importPath)) { - false - } - else if (importPath.isAllUnder) { - importPath.fqName in parentFqNames - } - else { - importPath.fqName in fqNames + val isUsed = when { + !importPaths.add(importPath) -> false + importPath.isAllUnder -> importPath.fqName in parentFqNames + else -> importPath.fqName in fqNames } if (!isUsed) { diff --git a/idea/src/org/jetbrains/kotlin/idea/inspections/NullableBooleanElvisInspection.kt b/idea/src/org/jetbrains/kotlin/idea/inspections/NullableBooleanElvisInspection.kt index ad3bec2d180..ec8aab57b8c 100644 --- a/idea/src/org/jetbrains/kotlin/idea/inspections/NullableBooleanElvisInspection.kt +++ b/idea/src/org/jetbrains/kotlin/idea/inspections/NullableBooleanElvisInspection.kt @@ -72,7 +72,11 @@ class NullableBooleanElvisInspection : AbstractKotlinInspection(), CleanupLocalI val constPart = element.right as? KtConstantExpression ?: return val exprPart = element.left ?: return - val constValue = if (KtPsiUtil.isTrueConstant(constPart)) true else if (KtPsiUtil.isFalseConstant(constPart)) false else return + val constValue = when { + KtPsiUtil.isTrueConstant(constPart) -> true + KtPsiUtil.isFalseConstant(constPart) -> false + else -> return + } val equalityCheckExpression = element.replaced(KtPsiFactory(constPart).buildExpression { appendExpression(exprPart) appendFixedText(if (constValue) " != false" else " == true") diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/NullableBooleanEqualityCheckToElvisIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/NullableBooleanEqualityCheckToElvisIntention.kt index 749a01fe0fd..348380ed5fd 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/NullableBooleanEqualityCheckToElvisIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/NullableBooleanEqualityCheckToElvisIntention.kt @@ -47,7 +47,11 @@ class NullableBooleanEqualityCheckToElvisIntention : SelfTargetingIntention true + KtPsiUtil.isFalseConstant(constPart) -> false + else -> return + } val factory = KtPsiFactory(constPart) val elvis = factory.createExpressionByPattern("$0 ?: ${!constValue}", exprPart) diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/IfThenUtils.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/IfThenUtils.kt index 4ce7a3f8182..e58f17f6b27 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/IfThenUtils.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/IfThenUtils.kt @@ -168,14 +168,11 @@ data class IfThenToSelectData( if (condition is KtIsExpression) newReceiver!! else baseClause } else { - if (condition is KtIsExpression) { - (baseClause as KtDotQualifiedExpression).replaceFirstReceiver( + when { + condition is KtIsExpression -> (baseClause as KtDotQualifiedExpression).replaceFirstReceiver( factory, newReceiver!!, safeAccess = true) - } - else if (hasImplicitReceiver()) { - factory.createExpressionByPattern("this?.$0", baseClause).insertSafeCalls(factory) - } else { - baseClause.insertSafeCalls(factory) + hasImplicitReceiver() -> factory.createExpressionByPattern("this?.$0", baseClause).insertSafeCalls(factory) + else -> baseClause.insertSafeCalls(factory) } } } 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 fbe2887b410..d97c1fe0803 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 @@ -116,14 +116,10 @@ class MaxOrMinTransformation( val functionName = if (isMax) "max" else "min" val arguments = assignment.right.extractStaticFunctionCallArguments("java.lang.Math." + functionName) ?: return null if (arguments.size != 2) return null - val value = if (arguments[0].isVariableReference(variableInitialization.variable)) { - arguments[1] ?: return null - } - else if (arguments[1].isVariableReference(variableInitialization.variable)) { - arguments[0] ?: return null - } - else { - return null + val value = when { + arguments[0].isVariableReference(variableInitialization.variable) -> arguments[1] ?: return null + arguments[1].isVariableReference(variableInitialization.variable) -> arguments[0] ?: return null + else -> return null } val mapTransformation = if (value.isVariableReference(state.inputVariable)) @@ -148,14 +144,10 @@ class MaxOrMinTransformation( if (comparison !in setOf(KtTokens.GT, KtTokens.LT, KtTokens.GTEQ, KtTokens.LTEQ)) return null val left = condition.left as? KtNameReferenceExpression ?: return null val right = condition.right as? KtNameReferenceExpression ?: return null - val otherHand = if (left.isVariableReference(inputVariable)) { - right - } - else if (right.isVariableReference(inputVariable)) { - left - } - else { - return null + val otherHand = when { + left.isVariableReference(inputVariable) -> right + right.isVariableReference(inputVariable) -> left + else -> return null } val variableInitialization = otherHand.findVariableInitializationBeforeLoop(loop, checkNoOtherUsagesInLoop = false) @@ -163,14 +155,10 @@ class MaxOrMinTransformation( if (!assignmentTarget.isVariableReference(variableInitialization.variable)) return null - val valueToBeVariable = if (valueAssignedIfTrue.isVariableReference(inputVariable)) { - valueAssignedIfFalse - } - else if (valueAssignedIfFalse.isVariableReference(inputVariable)) { - valueAssignedIfTrue - } - else { - return null + val valueToBeVariable = when { + valueAssignedIfTrue.isVariableReference(inputVariable) -> valueAssignedIfFalse + valueAssignedIfFalse.isVariableReference(inputVariable) -> valueAssignedIfTrue + else -> return null } if (valueToBeVariable != null && !valueToBeVariable.isVariableReference(variableInitialization.variable)) return null diff --git a/idea/src/org/jetbrains/kotlin/idea/presentation/DeclarationPresenters.kt b/idea/src/org/jetbrains/kotlin/idea/presentation/DeclarationPresenters.kt index 820bc077e84..bb752f6f45a 100644 --- a/idea/src/org/jetbrains/kotlin/idea/presentation/DeclarationPresenters.kt +++ b/idea/src/org/jetbrains/kotlin/idea/presentation/DeclarationPresenters.kt @@ -54,14 +54,10 @@ open class KotlinDefaultNamedDeclarationPresentation(private val declaration: Kt qualifiedContainer } val receiverTypeRef = (declaration as? KtCallableDeclaration)?.receiverTypeReference - if (receiverTypeRef != null) { - return "(for " + receiverTypeRef.text + " in " + containerText + ")" - } - else if (parent is KtFile) { - return "(" + containerText + ")" - } - else { - return "(in " + containerText + ")" + return when { + receiverTypeRef != null -> "(for " + receiverTypeRef.text + " in " + containerText + ")" + parent is KtFile -> "($containerText)" + else -> "(in $containerText)" } } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeFunctionSignatureFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeFunctionSignatureFix.kt index 45b6975c602..9e18c8565cc 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeFunctionSignatureFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeFunctionSignatureFix.kt @@ -63,15 +63,13 @@ abstract class ChangeFunctionSignatureFix( val argumentName = argument.getArgumentName() val expression = argument.getArgumentExpression() - return if (argumentName != null) { - KotlinNameSuggester.suggestNameByName(argumentName.asName.asString(), validator) - } - else if (expression != null) { - val bindingContext = expression.analyze(BodyResolveMode.PARTIAL) - KotlinNameSuggester.suggestNamesByExpressionAndType(expression, null, bindingContext, validator, "param").first() - } - else { - KotlinNameSuggester.suggestNameByName("param", validator) + return when { + argumentName != null -> KotlinNameSuggester.suggestNameByName(argumentName.asName.asString(), validator) + expression != null -> { + val bindingContext = expression.analyze(BodyResolveMode.PARTIAL) + KotlinNameSuggester.suggestNamesByExpressionAndType(expression, null, bindingContext, validator, "param").first() + } + else -> KotlinNameSuggester.suggestNameByName("param", validator) } } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/ReplaceInfixOrOperatorCallFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/ReplaceInfixOrOperatorCallFix.kt index 4e5ebc35cb4..1d99a4ceded 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/ReplaceInfixOrOperatorCallFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/ReplaceInfixOrOperatorCallFix.kt @@ -100,16 +100,20 @@ class ReplaceInfixOrOperatorCallFix( val parent = expression.parent return when (parent) { is KtBinaryExpression -> { - if (parent.left == null || parent.right == null) null - else if (parent.operationToken == KtTokens.EQ) null - else if (parent.operationToken in OperatorConventions.COMPARISON_OPERATIONS) null - else ReplaceInfixOrOperatorCallFix(parent, parent.shouldHaveNotNullType()) + when { + parent.left == null || parent.right == null -> null + parent.operationToken == KtTokens.EQ -> null + parent.operationToken in OperatorConventions.COMPARISON_OPERATIONS -> null + else -> ReplaceInfixOrOperatorCallFix(parent, parent.shouldHaveNotNullType()) + } } is KtCallExpression -> { - if (parent.calleeExpression == null) null - else if (parent.parent is KtQualifiedExpression) null - else if (parent.getResolvedCall(parent.analyze())?.getImplicitReceiverValue() != null) null - else ReplaceInfixOrOperatorCallFix(parent, parent.shouldHaveNotNullType()) + when { + parent.calleeExpression == null -> null + parent.parent is KtQualifiedExpression -> null + parent.getResolvedCall(parent.analyze())?.getImplicitReceiverValue() != null -> null + else -> ReplaceInfixOrOperatorCallFix(parent, parent.shouldHaveNotNullType()) + } } else -> null } diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/SpecifyTypeExplicitlyFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/SpecifyTypeExplicitlyFix.kt index aba9c2ec751..d7cc380c843 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/SpecifyTypeExplicitlyFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/SpecifyTypeExplicitlyFix.kt @@ -41,14 +41,10 @@ class SpecifyTypeExplicitlyFix : PsiElementBaseIntentionAction() { override fun isAvailable(project: Project, editor: Editor, element: PsiElement): Boolean { val declaration = declarationByElement(element) - if (declaration is KtProperty) { - text = "Specify type explicitly" - } - else if (declaration is KtNamedFunction) { - text = "Specify return type explicitly" - } - else { - return false + text = when (declaration) { + is KtProperty -> "Specify type explicitly" + is KtNamedFunction -> "Specify return type explicitly" + else -> return false } return !SpecifyTypeExplicitlyIntention.getTypeForDeclaration(declaration).isError 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 ce90e0c8322..de37af54331 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/migration/MigrateExternalExtensionFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/migration/MigrateExternalExtensionFix.kt @@ -96,19 +96,23 @@ class MigrateExternalExtensionFix(declaration: KtNamedDeclaration) val nativeAnnotations = ArrayList() declaration.modifierList?.annotationEntries?.forEach { - if (it.isJsAnnotation(PredefinedAnnotation.NATIVE_GETTER)) { - isGetter = true - nativeAnnotations.add(it) - } else if (it.isJsAnnotation(PredefinedAnnotation.NATIVE_SETTER)) { - isSetter = true - nativeAnnotations.add(it) - } else if (it.isJsAnnotation(PredefinedAnnotation.NATIVE_INVOKE)) { - isInvoke = true - nativeAnnotations.add(it) - } else if (it.isJsAnnotation(PredefinedAnnotation.NATIVE)) { - nativeAnnotations.add(it) - nativeAnnotation = it - + when { + it.isJsAnnotation(PredefinedAnnotation.NATIVE_GETTER) -> { + isGetter = true + nativeAnnotations.add(it) + } + it.isJsAnnotation(PredefinedAnnotation.NATIVE_SETTER) -> { + isSetter = true + nativeAnnotations.add(it) + } + it.isJsAnnotation(PredefinedAnnotation.NATIVE_INVOKE) -> { + isInvoke = true + nativeAnnotations.add(it) + } + it.isJsAnnotation(PredefinedAnnotation.NATIVE) -> { + nativeAnnotations.add(it) + nativeAnnotation = it + } } } return JsNativeAnnotations(nativeAnnotations, nativeAnnotation, isGetter, isSetter, isInvoke) @@ -122,30 +126,35 @@ class MigrateExternalExtensionFix(declaration: KtNamedDeclaration) val ktPsiFactory = KtPsiFactory(declaration) val body = ktPsiFactory.buildExpression { appendName(Name.identifier("asDynamic")) - if (annotations.isGetter) { - appendFixedText("()") - if (declaration is KtNamedFunction) { - appendParameters(declaration, "[", "]") - } - } else if (annotations.isSetter) { - appendFixedText("()") - if (declaration is KtNamedFunction) { - appendParameters(declaration, "[", "]", skipLast = true) - declaration.valueParameters.last().nameAsName?.let { - appendFixedText(" = ") - appendName(it) + when { + annotations.isGetter -> { + appendFixedText("()") + if (declaration is KtNamedFunction) { + appendParameters(declaration, "[", "]") } } - } else if (annotations.isInvoke) { - appendFixedText("()") - if (declaration is KtNamedFunction) { - appendParameters(declaration, "(", ")") + annotations.isSetter -> { + appendFixedText("()") + if (declaration is KtNamedFunction) { + appendParameters(declaration, "[", "]", skipLast = true) + declaration.valueParameters.last().nameAsName?.let { + appendFixedText(" = ") + appendName(it) + } + } } - } else { - appendFixedText("().") - appendName(name) - if (declaration is KtNamedFunction) { - appendParameters(declaration, "(", ")") + annotations.isInvoke -> { + appendFixedText("()") + if (declaration is KtNamedFunction) { + appendParameters(declaration, "(", ")") + } + } + else -> { + appendFixedText("().") + appendName(name) + if (declaration is KtNamedFunction) { + appendParameters(declaration, "(", ")") + } } } } 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 6cbe28336db..c2083fa285e 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinChangeSignatureData.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinChangeSignatureData.kt @@ -122,33 +122,19 @@ class KotlinChangeSignatureData( } } - override fun getParameters(): List { - return parameters + override fun getParameters(): List = parameters + + override fun getName() = when (baseDescriptor) { + is ConstructorDescriptor -> baseDescriptor.containingDeclaration.name.asString() + is AnonymousFunctionDescriptor -> "" + else -> baseDescriptor.name.asString() } - override fun getName(): String { - if (baseDescriptor is ConstructorDescriptor) { - return baseDescriptor.containingDeclaration.name.asString() - } - else if (baseDescriptor is AnonymousFunctionDescriptor) { - return "" - } - else { - return baseDescriptor.name.asString() - } - } + override fun getParametersCount(): Int = baseDescriptor.valueParameters.size - override fun getParametersCount(): Int { - return baseDescriptor.valueParameters.size - } + override fun getVisibility(): Visibility = baseDescriptor.visibility - override fun getVisibility(): Visibility { - return baseDescriptor.visibility - } - - override fun getMethod(): PsiElement { - return baseDeclaration - } + override fun getMethod(): PsiElement = baseDeclaration override fun canChangeVisibility(): Boolean { if (DescriptorUtils.isLocal(baseDescriptor)) return false @@ -156,15 +142,10 @@ class KotlinChangeSignatureData( return !(baseDescriptor is AnonymousFunctionDescriptor || parent is ClassDescriptor && parent.kind == ClassKind.INTERFACE) } - override fun canChangeParameters(): Boolean { - return true - } + override fun canChangeParameters() = true - override fun canChangeName(): Boolean { - return !(baseDescriptor is ConstructorDescriptor || baseDescriptor is AnonymousFunctionDescriptor) - } + override fun canChangeName() = !(baseDescriptor is ConstructorDescriptor || baseDescriptor is AnonymousFunctionDescriptor) - override fun canChangeReturnType(): MethodDescriptor.ReadWriteOption { - return if (baseDescriptor is ConstructorDescriptor) MethodDescriptor.ReadWriteOption.None else MethodDescriptor.ReadWriteOption.ReadWrite - } + override fun canChangeReturnType(): MethodDescriptor.ReadWriteOption = + if (baseDescriptor is ConstructorDescriptor) MethodDescriptor.ReadWriteOption.None else MethodDescriptor.ReadWriteOption.ReadWrite } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/ui/KotlinChangeSignatureDialog.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/ui/KotlinChangeSignatureDialog.kt index 0105f44de5c..9c0758b73b8 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/ui/KotlinChangeSignatureDialog.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/ui/KotlinChangeSignatureDialog.kt @@ -248,16 +248,18 @@ class KotlinChangeSignatureDialog( return JBTableRow { column -> val columnInfo = parametersTableModel.columnInfos[column] - if (KotlinPrimaryConstructorParameterTableModel.isValVarColumn(columnInfo)) - (components[column] as @Suppress("NO_TYPE_ARGUMENTS_ON_RHS") JComboBox).selectedItem - else if (KotlinCallableParameterTableModel.isTypeColumn(columnInfo)) - item.typeCodeFragment - else if (KotlinCallableParameterTableModel.isNameColumn(columnInfo)) - (components[column] as EditorTextField).text - else if (KotlinCallableParameterTableModel.isDefaultValueColumn(columnInfo)) - item.defaultValueCodeFragment - else - null + when { + KotlinPrimaryConstructorParameterTableModel.isValVarColumn(columnInfo) -> + (components[column] as @Suppress("NO_TYPE_ARGUMENTS_ON_RHS") JComboBox).selectedItem + KotlinCallableParameterTableModel.isTypeColumn(columnInfo) -> + item.typeCodeFragment + KotlinCallableParameterTableModel.isNameColumn(columnInfo) -> + (components[column] as EditorTextField).text + KotlinCallableParameterTableModel.isDefaultValueColumn(columnInfo) -> + item.defaultValueCodeFragment + else -> + null + } } } @@ -291,9 +293,11 @@ class KotlinChangeSignatureDialog( override fun getPreferredFocusedComponent(): JComponent { val me = mouseEvent - val index = if (me != null) - getEditorIndex(me.point.getX().toInt()) - else if (myMethod.kind === Kind.PRIMARY_CONSTRUCTOR) 1 else 0 + val index = when { + me != null -> getEditorIndex(me.point.getX().toInt()) + myMethod.kind === Kind.PRIMARY_CONSTRUCTOR -> 1 + else -> 0 + } val component = components[index] return if (component is EditorTextField) component.focusTarget else component } diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/extractionEngine/extractorUtil.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/extractionEngine/extractorUtil.kt index 4a7c2c37107..1dcfe7ad7a2 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/extractionEngine/extractorUtil.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/extractionEngine/extractorUtil.kt @@ -353,16 +353,12 @@ private fun makeCall( ) is Jump -> { - if (outputValue.elementToInsertAfterCall == null) { - Collections.singletonList(psiFactory.createExpression(callText)) - } - else if (outputValue.conditional) { - Collections.singletonList( + when { + outputValue.elementToInsertAfterCall == null -> Collections.singletonList(psiFactory.createExpression(callText)) + outputValue.conditional -> Collections.singletonList( psiFactory.createExpression("if ($callText) ${outputValue.elementToInsertAfterCall.text}") ) - } - else { - listOf( + else -> listOf( psiFactory.createExpression(callText), newLine, psiFactory.createExpression(outputValue.elementToInsertAfterCall.text!!) diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceTypeAlias/introduceTypeAliasImpl.kt b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceTypeAlias/introduceTypeAliasImpl.kt index 67bf2bc8702..c5b22bc5ddd 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceTypeAlias/introduceTypeAliasImpl.kt +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceTypeAlias/introduceTypeAliasImpl.kt @@ -134,14 +134,13 @@ fun IntroduceTypeAliasDescriptor.validate(): IntroduceTypeAliasDescriptorWithCon val conflicts = MultiMap() val originalType = originalData.originalTypeElement - if (name.isEmpty()) { - conflicts.putValue(originalType, "No name provided for type alias") - } - else if (!KotlinNameSuggester.isIdentifier(name)) { - conflicts.putValue(originalType, "Type alias name must be a valid identifier: $name") - } - else if (originalData.getTargetScope().findClassifier(Name.identifier(name), NoLookupLocation.FROM_IDE) != null) { - conflicts.putValue(originalType, "Type $name already exists in the target scope") + when { + name.isEmpty() -> + conflicts.putValue(originalType, "No name provided for type alias") + !KotlinNameSuggester.isIdentifier(name) -> + conflicts.putValue(originalType, "Type alias name must be a valid identifier: $name") + originalData.getTargetScope().findClassifier(Name.identifier(name), NoLookupLocation.FROM_IDE) != null -> + conflicts.putValue(originalType, "Type $name already exists in the target scope") } if (typeParameters.distinctBy { it.name }.size != typeParameters.size) { diff --git a/idea/src/org/jetbrains/kotlin/idea/run/KotlinRunConfigurationProducer.kt b/idea/src/org/jetbrains/kotlin/idea/run/KotlinRunConfigurationProducer.kt index 6e4d5dea667..0d012d7399f 100644 --- a/idea/src/org/jetbrains/kotlin/idea/run/KotlinRunConfigurationProducer.kt +++ b/idea/src/org/jetbrains/kotlin/idea/run/KotlinRunConfigurationProducer.kt @@ -97,12 +97,14 @@ class KotlinRunConfigurationProducer : RunConfigurationProducer null is KtFile -> container.javaFileFacadeFqName.asString() is KtClassOrObject -> { - if (!container.isValid) + if (!container.isValid) { null + } else if (container is KtObjectDeclaration && container.isCompanion()) { val containerClass = container.getParentOfType(true) containerClass?.toLightClass()?.let { ClassUtil.getJVMClassName(it) } - } else { + } + else { container.toLightClass()?.let { ClassUtil.getJVMClassName(it) } } } diff --git a/idea/src/org/jetbrains/kotlin/idea/versions/OutdatedKotlinRuntimeChecker.kt b/idea/src/org/jetbrains/kotlin/idea/versions/OutdatedKotlinRuntimeChecker.kt index 4d034d484af..ccfe8afde45 100644 --- a/idea/src/org/jetbrains/kotlin/idea/versions/OutdatedKotlinRuntimeChecker.kt +++ b/idea/src/org/jetbrains/kotlin/idea/versions/OutdatedKotlinRuntimeChecker.kt @@ -115,17 +115,19 @@ fun notifyOutdatedKotlinRuntime(project: Project, outdatedLibraries: Collection< Notifications.Bus.notify(Notification(OUTDATED_RUNTIME_GROUP_DISPLAY_ID, "Outdated Kotlin Runtime", message, NotificationType.WARNING, NotificationListener { notification, event -> if (event.eventType == HyperlinkEvent.EventType.ACTIVATED) { - if ("update" == event.description) { - val outdatedLibraries = findOutdatedKotlinLibraries(project).map { it.library } - ApplicationManager.getApplication().invokeLater { - updateLibraries(project, outdatedLibraries) + when { + "update" == event.description -> { + val outdatedLibraries = findOutdatedKotlinLibraries(project).map { it.library } + ApplicationManager.getApplication().invokeLater { + updateLibraries(project, outdatedLibraries) + } + } + "ignore" == event.description -> { + PropertiesComponent.getInstance(project).setValue(SUPPRESSED_PROPERTY_NAME, pluginVersion) + } + else -> { + throw AssertionError() } - } - else if ("ignore" == event.description) { - PropertiesComponent.getInstance(project).setValue(SUPPRESSED_PROPERTY_NAME, pluginVersion) - } - else { - throw AssertionError() } notification.expire() } diff --git a/j2k/src/org/jetbrains/kotlin/j2k/ExpressionConverter.kt b/j2k/src/org/jetbrains/kotlin/j2k/ExpressionConverter.kt index 3c86275039a..3f48a468fa0 100644 --- a/j2k/src/org/jetbrains/kotlin/j2k/ExpressionConverter.kt +++ b/j2k/src/org/jetbrains/kotlin/j2k/ExpressionConverter.kt @@ -345,44 +345,44 @@ class DefaultExpressionConverter : JavaElementVisitor(), ExpressionConverter { if (target is KtLightMethod) { val origin = target.kotlinOrigin val isTopLevel = origin?.getStrictParentOfType() == null - if (origin is KtProperty || origin is KtPropertyAccessor || origin is KtParameter) { - val property = if (origin is KtPropertyAccessor) - origin.parent as KtProperty - else - origin as KtNamedDeclaration - val parameterCount = target.parameterList.parameters.size - if (parameterCount == arguments.size) { - val propertyName = Identifier.withNoPrototype(property.name!!, isNullable) - val isExtension = property.isExtensionDeclaration() - val propertyAccess = if (isTopLevel) { - if (isExtension) - QualifiedExpression(codeConverter.convertExpression(arguments.firstOrNull(), shouldParenthesize = true), propertyName, null).assignNoPrototype() - else + when (origin) { + is KtProperty, is KtPropertyAccessor, is KtParameter -> { + val property = if (origin is KtPropertyAccessor) + origin.parent as KtProperty + else + origin as KtNamedDeclaration + val parameterCount = target.parameterList.parameters.size + if (parameterCount == arguments.size) { + val propertyName = Identifier.withNoPrototype(property.name!!, isNullable) + val isExtension = property.isExtensionDeclaration() + val propertyAccess = if (isTopLevel) { + if (isExtension) + QualifiedExpression(codeConverter.convertExpression(arguments.firstOrNull(), shouldParenthesize = true), propertyName, null).assignNoPrototype() + else + propertyName + } + else if (qualifier != null) { + QualifiedExpression(codeConverter.convertExpression(qualifier), propertyName, dot).assignNoPrototype() + } + else { propertyName - } - else if (qualifier != null) { - QualifiedExpression(codeConverter.convertExpression(qualifier), propertyName, dot).assignNoPrototype() - } - else { - propertyName - } - - when(if (isExtension) parameterCount - 1 else parameterCount) { - 0 /* getter */ -> { - result = propertyAccess - return } - 1 /* setter */ -> { - val argument = codeConverter.convertExpression(arguments[if (isExtension) 1 else 0]) - result = AssignmentExpression(propertyAccess, argument, Operator.EQ) - return + when(if (isExtension) parameterCount - 1 else parameterCount) { + 0 /* getter */ -> { + result = propertyAccess + return + } + + 1 /* setter */ -> { + val argument = codeConverter.convertExpression(arguments[if (isExtension) 1 else 0]) + result = AssignmentExpression(propertyAccess, argument, Operator.EQ) + return + } } } } - } - else if (origin is KtFunction) { - if (isTopLevel) { + is KtFunction -> if (isTopLevel) { result = if (origin.isExtensionDeclaration()) { val qualifier = codeConverter.convertExpression(arguments.firstOrNull(), shouldParenthesize = true) MethodCallExpression.build(qualifier, @@ -401,27 +401,27 @@ class DefaultExpressionConverter : JavaElementVisitor(), ExpressionConverter { } return } - } - else if (origin == null){ - val resolvedQualifier = (methodExpr.qualifier as? PsiReferenceExpression)?.resolve() - if (isFacadeClassFromLibrary(resolvedQualifier)) { - result = if (target.isKotlinExtensionFunction()) { - val qualifier = codeConverter.convertExpression(arguments.firstOrNull(), shouldParenthesize = true) - MethodCallExpression.build(qualifier, - methodExpr.referenceName!!, - convertArguments(expression, isExtension = true), - typeArguments, - isNullable, - dot) + null -> { + val resolvedQualifier = (methodExpr.qualifier as? PsiReferenceExpression)?.resolve() + if (isFacadeClassFromLibrary(resolvedQualifier)) { + result = if (target.isKotlinExtensionFunction()) { + val qualifier = codeConverter.convertExpression(arguments.firstOrNull(), shouldParenthesize = true) + MethodCallExpression.build(qualifier, + methodExpr.referenceName!!, + convertArguments(expression, isExtension = true), + typeArguments, + isNullable, + dot) + } + else { + MethodCallExpression.build(null, + methodExpr.referenceName!!, + convertArguments(expression), + typeArguments, + isNullable) + } + return } - else { - MethodCallExpression.build(null, - methodExpr.referenceName!!, - convertArguments(expression), - typeArguments, - isNullable) - } - return } } } @@ -826,39 +826,40 @@ class DefaultExpressionConverter : JavaElementVisitor(), ExpressionConverter { val specialMethod = method?.let { SpecialMethod.match(it, callParams.size, converter.services) } val statement: Statement - if (expression.isConstructor) { - val argumentList = ArgumentList.withNoPrototype(callParams.map { it.first }) - statement = MethodCallExpression.buildNonNull(null, convertMethodReferenceQualifier(qualifier), argumentList) - } - else if (specialMethod != null) { - val factory = PsiElementFactory.SERVICE.getInstance(converter.project) - val fakeReceiver = receiver?.let { - val psiExpression = qualifier as? PsiExpression ?: factory.createExpressionFromText("fakeReceiver", null) - psiExpression.convertedExpression = it.first - psiExpression + when { + expression.isConstructor -> { + val argumentList = ArgumentList.withNoPrototype(callParams.map { it.first }) + statement = MethodCallExpression.buildNonNull(null, convertMethodReferenceQualifier(qualifier), argumentList) } - val fakeParams = callParams.mapIndexed { - i, param -> - with(factory.createExpressionFromText("fake$i", null)) { - this.convertedExpression = param.first - this + specialMethod != null -> { + val factory = PsiElementFactory.SERVICE.getInstance(converter.project) + val fakeReceiver = receiver?.let { + val psiExpression = qualifier as? PsiExpression ?: factory.createExpressionFromText("fakeReceiver", null) + psiExpression.convertedExpression = it.first + psiExpression } - } - val patchedConverter = codeConverter.withSpecialExpressionConverter(object : SpecialExpressionConverter { - override fun convertExpression(expression: PsiExpression, codeConverter: CodeConverter): Expression? { - val convertedExpression = expression.convertedExpression - expression.convertedExpression = null - return convertedExpression + val fakeParams = callParams.mapIndexed { i, param -> + with(factory.createExpressionFromText("fake$i", null)) { + this.convertedExpression = param.first + this + } } - }) + val patchedConverter = codeConverter.withSpecialExpressionConverter(object : SpecialExpressionConverter { + override fun convertExpression(expression: PsiExpression, codeConverter: CodeConverter): Expression? { + val convertedExpression = expression.convertedExpression + expression.convertedExpression = null + return convertedExpression + } + }) - val callData = SpecialMethod.ConvertCallData(fakeReceiver, fakeParams, emptyList(), null, null, null, patchedConverter) - statement = specialMethod.convertCall(callData)!! - } - else { - val referenceName = expression.referenceName!! - val argumentList = ArgumentList.withNoPrototype(callParams.map { it.first }) - statement = MethodCallExpression.buildNonNull(receiver?.first, referenceName, argumentList) + val callData = SpecialMethod.ConvertCallData(fakeReceiver, fakeParams, emptyList(), null, null, null, patchedConverter) + statement = specialMethod.convertCall(callData)!! + } + else -> { + val referenceName = expression.referenceName!! + val argumentList = ArgumentList.withNoPrototype(callParams.map { it.first }) + statement = MethodCallExpression.buildNonNull(receiver?.first, referenceName, argumentList) + } } statement.assignNoPrototype() diff --git a/j2k/src/org/jetbrains/kotlin/j2k/ForConverter.kt b/j2k/src/org/jetbrains/kotlin/j2k/ForConverter.kt index 82ac0859669..897e2fed54a 100644 --- a/j2k/src/org/jetbrains/kotlin/j2k/ForConverter.kt +++ b/j2k/src/org/jetbrains/kotlin/j2k/ForConverter.kt @@ -104,13 +104,14 @@ class ForConverter( statement.isInSingleLine()).assignNoPrototype() if (initializationConverted.isEmpty) return whileStatement - val kind = if (statement.parents.filter { it !is PsiLabeledStatement }.first() !is PsiCodeBlock) { - WhileWithInitializationPseudoStatement.Kind.WITH_BLOCK + val kind = when { + statement.parents.filter { it !is PsiLabeledStatement }.first() !is PsiCodeBlock -> + WhileWithInitializationPseudoStatement.Kind.WITH_BLOCK + hasNameConflict() -> + WhileWithInitializationPseudoStatement.Kind.WITH_RUN_BLOCK + else -> + WhileWithInitializationPseudoStatement.Kind.SIMPLE } - else if (hasNameConflict()) - WhileWithInitializationPseudoStatement.Kind.WITH_RUN_BLOCK - else - WhileWithInitializationPseudoStatement.Kind.SIMPLE return WhileWithInitializationPseudoStatement(initializationConverted, whileStatement, kind) } diff --git a/j2k/src/org/jetbrains/kotlin/j2k/TypeConverter.kt b/j2k/src/org/jetbrains/kotlin/j2k/TypeConverter.kt index 810f3b741ef..63e22254861 100644 --- a/j2k/src/org/jetbrains/kotlin/j2k/TypeConverter.kt +++ b/j2k/src/org/jetbrains/kotlin/j2k/TypeConverter.kt @@ -266,12 +266,14 @@ class TypeConverter(val converter: Converter) { override fun fromAnnotations(owner: PsiModifierListOwner): Nullability { val manager = NullableNotNullManager.getInstance(owner.project) - return if (manager.isNotNull(owner, false/* we do not check bases because they are checked by callers of this method*/)) - Nullability.NotNull - else if (manager.isNullable(owner, false)) - Nullability.Nullable - else - Nullability.Default + return when { + manager.isNotNull(owner, false/* we do not check bases because they are checked by callers of this method*/) -> + Nullability.NotNull + manager.isNullable(owner, false) -> + Nullability.Nullable + else -> + Nullability.Default + } } override fun forVariableTypeBeforeUsageSearch(variable: PsiVariable): Nullability { diff --git a/j2k/src/org/jetbrains/kotlin/j2k/TypeVisitor.kt b/j2k/src/org/jetbrains/kotlin/j2k/TypeVisitor.kt index 67810c417d4..f17c5dbaa6e 100644 --- a/j2k/src/org/jetbrains/kotlin/j2k/TypeVisitor.kt +++ b/j2k/src/org/jetbrains/kotlin/j2k/TypeVisitor.kt @@ -40,17 +40,11 @@ class TypeVisitor( override fun visitPrimitiveType(primitiveType: PsiPrimitiveType): Type { val name = primitiveType.canonicalText - return if (name == "void") { - UnitType() - } - else if (PRIMITIVE_TYPES_NAMES.contains(name)) { - PrimitiveType(Identifier.withNoPrototype(StringUtil.capitalize(name))) - } - else if (name == "null") { - NullType() - } - else { - PrimitiveType(Identifier.withNoPrototype(name)) + return when { + name == "void" -> UnitType() + PRIMITIVE_TYPES_NAMES.contains(name) -> PrimitiveType(Identifier.withNoPrototype(StringUtil.capitalize(name))) + name == "null" -> NullType() + else -> PrimitiveType(Identifier.withNoPrototype(name)) } } diff --git a/j2k/src/org/jetbrains/kotlin/j2k/Utils.kt b/j2k/src/org/jetbrains/kotlin/j2k/Utils.kt index 4f1cc61245e..9180e3d9c30 100644 --- a/j2k/src/org/jetbrains/kotlin/j2k/Utils.kt +++ b/j2k/src/org/jetbrains/kotlin/j2k/Utils.kt @@ -27,20 +27,16 @@ fun quoteKeywords(packageName: String): String = packageName.split('.').joinToSt fun getDefaultInitializer(property: Property): Expression? { val t = property.type - val result = if (t.isNullable) { - LiteralExpression("null") - } - else if (t is PrimitiveType) { - when (t.name.name) { + val result = when { + t.isNullable -> LiteralExpression("null") + t is PrimitiveType -> when (t.name.name) { "Boolean" -> LiteralExpression("false") "Char" -> LiteralExpression("' '") "Double" -> MethodCallExpression.buildNonNull(LiteralExpression("0").assignNoPrototype(), OperatorConventions.DOUBLE.toString()) "Float" -> MethodCallExpression.buildNonNull(LiteralExpression("0").assignNoPrototype(), OperatorConventions.FLOAT.toString()) else -> LiteralExpression("0") } - } - else { - null + else -> null } return result?.assignNoPrototype() } diff --git a/j2k/src/org/jetbrains/kotlin/j2k/ast/Expressions.kt b/j2k/src/org/jetbrains/kotlin/j2k/ast/Expressions.kt index 04750b0d0ba..226799a221e 100644 --- a/j2k/src/org/jetbrains/kotlin/j2k/ast/Expressions.kt +++ b/j2k/src/org/jetbrains/kotlin/j2k/ast/Expressions.kt @@ -279,11 +279,10 @@ class ClassLiteralExpression(val type: Type): Expression() { fun createArrayInitializerExpression(arrayType: ArrayType, initializers: List, needExplicitType: Boolean = true) : MethodCallExpression { val elementType = arrayType.elementType - val createArrayFunction = if (elementType is PrimitiveType) - (elementType.toNotNullType().canonicalCode() + "ArrayOf").decapitalize() - else if (needExplicitType) - "arrayOf<" + arrayType.elementType.canonicalCode() + ">" - else - "arrayOf" + val createArrayFunction = when { + elementType is PrimitiveType -> (elementType.toNotNullType().canonicalCode() + "ArrayOf").decapitalize() + needExplicitType -> "arrayOf<" + arrayType.elementType.canonicalCode() + ">" + else -> "arrayOf" + } return MethodCallExpression.buildNonNull(null, createArrayFunction, ArgumentList.withNoPrototype(initializers)) } diff --git a/j2k/src/org/jetbrains/kotlin/j2k/propertyDetection.kt b/j2k/src/org/jetbrains/kotlin/j2k/propertyDetection.kt index 2faac6d725d..16f5ccb7b43 100644 --- a/j2k/src/org/jetbrains/kotlin/j2k/propertyDetection.kt +++ b/j2k/src/org/jetbrains/kotlin/j2k/propertyDetection.kt @@ -387,14 +387,10 @@ private class PropertyDetector( modifiers.add(Modifier.OVERRIDE) } - if (getMethod != null) { - modifiers.addIfNotNull(getterModifiers.accessModifier()) - } - else if (setMethod != null) { - modifiers.addIfNotNull(getterModifiers.accessModifier()) - } - else { - modifiers.addIfNotNull(fieldModifiers.accessModifier()) + when { + getMethod != null -> modifiers.addIfNotNull(getterModifiers.accessModifier()) + setMethod != null -> modifiers.addIfNotNull(getterModifiers.accessModifier()) + else -> modifiers.addIfNotNull(fieldModifiers.accessModifier()) } val prototypes = listOfNotNull(field, getMethod, setMethod) @@ -432,16 +428,20 @@ private class PropertyDetector( val superMethod = converter.services.superMethodsSearcher.findDeepestSuperMethods(getOrSetMethod).firstOrNull() ?: return null val containingClass = superMethod.containingClass!! - if (converter.inConversionScope(containingClass)) { - val propertyInfo = converter.propertyDetectionCache[containingClass][superMethod] - return if (propertyInfo != null) SuperInfo.Property(propertyInfo.isVar, propertyInfo.name, propertyInfo.modifiers.contains(Modifier.ABSTRACT)) else SuperInfo.Function - } - else if (superMethod is KtLightMethod) { - val origin = superMethod.kotlinOrigin - return if (origin is KtProperty) SuperInfo.Property(origin.isVar, origin.name ?: "", origin.hasModifier(KtTokens.ABSTRACT_KEYWORD)) else SuperInfo.Function - } - else { - return SuperInfo.Function + return when { + converter.inConversionScope(containingClass) -> { + val propertyInfo = converter.propertyDetectionCache[containingClass][superMethod] + if (propertyInfo != null) SuperInfo.Property(propertyInfo.isVar, propertyInfo.name, propertyInfo.modifiers.contains(Modifier.ABSTRACT)) + else SuperInfo.Function + } + superMethod is KtLightMethod -> { + val origin = superMethod.kotlinOrigin + if (origin is KtProperty) SuperInfo.Property(origin.isVar, origin.name ?: "", origin.hasModifier(KtTokens.ABSTRACT_KEYWORD)) + else SuperInfo.Function + } + else -> { + SuperInfo.Function + } } } diff --git a/j2k/src/org/jetbrains/kotlin/j2k/usageProcessing/FieldToPropertyProcessing.kt b/j2k/src/org/jetbrains/kotlin/j2k/usageProcessing/FieldToPropertyProcessing.kt index 111bc545e81..e1c7249e96c 100644 --- a/j2k/src/org/jetbrains/kotlin/j2k/usageProcessing/FieldToPropertyProcessing.kt +++ b/j2k/src/org/jetbrains/kotlin/j2k/usageProcessing/FieldToPropertyProcessing.kt @@ -37,12 +37,11 @@ class FieldToPropertyProcessing( if (field.name != propertyName || replaceReadWithFieldReference || replaceWriteWithFieldReference) MyConvertedCodeProcessor() else null override var javaCodeProcessors = - if (field.hasModifierProperty(PsiModifier.PRIVATE)) - emptyList() - else if (field.name != propertyName) - listOf(ElementRenamedCodeProcessor(propertyName), UseAccessorsJavaCodeProcessor()) - else - listOf(UseAccessorsJavaCodeProcessor()) + when { + field.hasModifierProperty(PsiModifier.PRIVATE) -> emptyList() + field.name != propertyName -> listOf(ElementRenamedCodeProcessor(propertyName), UseAccessorsJavaCodeProcessor()) + else -> listOf(UseAccessorsJavaCodeProcessor()) + } override val kotlinCodeProcessors = if (field.name != propertyName) diff --git a/js/js.dce/src/org/jetbrains/kotlin/js/dce/Analyzer.kt b/js/js.dce/src/org/jetbrains/kotlin/js/dce/Analyzer.kt index 16d7967a578..75073325bfd 100644 --- a/js/js.dce/src/org/jetbrains/kotlin/js/dce/Analyzer.kt +++ b/js/js.dce/src/org/jetbrains/kotlin/js/dce/Analyzer.kt @@ -56,54 +56,50 @@ class Analyzer(private val context: Context) : JsVisitor() { override fun visitExpressionStatement(x: JsExpressionStatement) { val expression = x.expression - if (expression is JsBinaryOperation) { - if (expression.operator == JsBinaryOperator.ASG) { + when (expression) { + is JsBinaryOperation -> if (expression.operator == JsBinaryOperator.ASG) { processAssignment(x, expression.arg1, expression.arg2)?.let { // Mark this statement with FQN extracted from assignment. // Later, we eliminate such statements if corresponding FQN is reachable nodeMap[x] = it } } - } - else if (expression is JsFunction) { - expression.name?.let { context.nodes[it]?.original }?.let { + is JsFunction -> expression.name?.let { context.nodes[it]?.original }?.let { nodeMap[x] = it it.functions += expression } - } - else if (expression is JsInvocation) { - val function = expression.qualifier + is JsInvocation -> { + val function = expression.qualifier - // (function(params) { ... })(arguments), assume that params = arguments and walk its body - if (function is JsFunction) { - enterFunction(function, expression.arguments) - return - } - - // f(arguments), where f is a parameter of outer function and it always receives function() { } as an argument. - if (function is JsNameRef && function.qualifier == null) { - val postponedFunction = function.name?.let { postponedFunctions[it] } - if (postponedFunction != null) { - enterFunction(postponedFunction, expression.arguments) - invocationsToSkip += expression + // (function(params) { ... })(arguments), assume that params = arguments and walk its body + if (function is JsFunction) { + enterFunction(function, expression.arguments) return } - } - // Object.defineProperty() - if (context.isObjectDefineProperty(function)) { - handleObjectDefineProperty(x, expression.arguments.getOrNull(0), expression.arguments.getOrNull(1), - expression.arguments.getOrNull(2)) - } + // f(arguments), where f is a parameter of outer function and it always receives function() { } as an argument. + if (function is JsNameRef && function.qualifier == null) { + val postponedFunction = function.name?.let { postponedFunctions[it] } + if (postponedFunction != null) { + enterFunction(postponedFunction, expression.arguments) + invocationsToSkip += expression + return + } + } - // Kotlin.defineModule() - else if (context.isDefineModule(function)) { - // (just remove it) - astNodesToEliminate += x - } + // Object.defineProperty() + when { + context.isObjectDefineProperty(function) -> + handleObjectDefineProperty(x, expression.arguments.getOrNull(0), expression.arguments.getOrNull(1), + expression.arguments.getOrNull(2)) - else if (context.isAmdDefine(function)) { - handleAmdDefine(expression, expression.arguments) + // Kotlin.defineModule() + context.isDefineModule(function) -> + // (just remove it) + astNodesToEliminate += x + context.isAmdDefine(function) -> + handleAmdDefine(expression, expression.arguments) + } } } } @@ -201,77 +197,75 @@ class Analyzer(private val context: Context) : JsVisitor() { } else if (leftNode != null) { // lhs = foo() - if (rhs is JsInvocation) { - val function = rhs.qualifier + when { + rhs is JsInvocation -> { + val function = rhs.qualifier - // lhs = function(params) { ... }(arguments) - // see corresponding case in visitExpressionStatement - if (function is JsFunction) { - enterFunction(function, rhs.arguments) - astNodesToSkip += lhs - return null - } - - // lhs = foo(arguments), where foo is a parameter of outer function that always take function literal - // see corresponding case in visitExpressionStatement - if (function is JsNameRef && function.qualifier == null) { - function.name?.let { postponedFunctions[it] }?.let { - enterFunction(it, rhs.arguments) + // lhs = function(params) { ... }(arguments) + // see corresponding case in visitExpressionStatement + if (function is JsFunction) { + enterFunction(function, rhs.arguments) astNodesToSkip += lhs return null } - } - // lhs = Object.create(constructor) - if (context.isObjectFunction(function, "create")) { - // Do not alias lhs and constructor, make unidirectional dependency lhs -> constructor instead. - // Motivation: reachability of a base class does not imply reachability of its derived class - handleObjectCreate(leftNode, rhs.arguments.getOrNull(0)) - return leftNode - } - - // lhs = Kotlin.defineInlineFunction('fqn', function() { ... }) - if (context.isDefineInlineFunction(function) && rhs.arguments.size == 2) { - leftNode.functions += rhs.arguments[1] as JsFunction - val defineInlineFunctionNode = context.extractNode(function) - if (defineInlineFunctionNode != null) { - leftNode.dependencies += defineInlineFunctionNode - } - return leftNode - } - } - else if (rhs is JsBinaryOperation) { - // Detect lhs = parent.child || (parent.child = {}), which is used to declare packages. - // Assume lhs = parent.child - if (rhs.operator == JsBinaryOperator.OR) { - val secondNode = context.extractNode(rhs.arg1) - val reassignment = rhs.arg2 - if (reassignment is JsBinaryOperation && reassignment.operator == JsBinaryOperator.ASG) { - val reassignNode = context.extractNode(reassignment.arg1) - val reassignValue = reassignment.arg2 - if (reassignNode == secondNode && reassignNode != null && reassignValue is JsObjectLiteral && - reassignValue.propertyInitializers.isEmpty() - ) { - return processAssignment(node, lhs, rhs.arg1) + // lhs = foo(arguments), where foo is a parameter of outer function that always take function literal + // see corresponding case in visitExpressionStatement + if (function is JsNameRef && function.qualifier == null) { + function.name?.let { postponedFunctions[it] }?.let { + enterFunction(it, rhs.arguments) + astNodesToSkip += lhs + return null } } + + // lhs = Object.create(constructor) + if (context.isObjectFunction(function, "create")) { + // Do not alias lhs and constructor, make unidirectional dependency lhs -> constructor instead. + // Motivation: reachability of a base class does not imply reachability of its derived class + handleObjectCreate(leftNode, rhs.arguments.getOrNull(0)) + return leftNode + } + + // lhs = Kotlin.defineInlineFunction('fqn', function() { ... }) + if (context.isDefineInlineFunction(function) && rhs.arguments.size == 2) { + leftNode.functions += rhs.arguments[1] as JsFunction + val defineInlineFunctionNode = context.extractNode(function) + if (defineInlineFunctionNode != null) { + leftNode.dependencies += defineInlineFunctionNode + } + return leftNode + } } - } - else if (rhs is JsFunction) { - // lhs = function() { ... } - // During reachability tracking phase: eliminate it if lhs is unreachable, traverse function otherwise - leftNode.functions += rhs - return leftNode - } - else if (leftNode.qualifier?.memberName == Namer.METADATA) { - // lhs.$metadata$ = expression - // During reachability tracking phase: eliminate it if lhs is unreachable, traverse expression - // It's commonly used to supply class's metadata - leftNode.expressions += rhs - return leftNode - } - else if (rhs is JsObjectLiteral && rhs.propertyInitializers.isEmpty()) { - return leftNode + rhs is JsBinaryOperation -> // Detect lhs = parent.child || (parent.child = {}), which is used to declare packages. + // Assume lhs = parent.child + if (rhs.operator == JsBinaryOperator.OR) { + val secondNode = context.extractNode(rhs.arg1) + val reassignment = rhs.arg2 + if (reassignment is JsBinaryOperation && reassignment.operator == JsBinaryOperator.ASG) { + val reassignNode = context.extractNode(reassignment.arg1) + val reassignValue = reassignment.arg2 + if (reassignNode == secondNode && reassignNode != null && reassignValue is JsObjectLiteral && + reassignValue.propertyInitializers.isEmpty() + ) { + return processAssignment(node, lhs, rhs.arg1) + } + } + } + rhs is JsFunction -> { + // lhs = function() { ... } + // During reachability tracking phase: eliminate it if lhs is unreachable, traverse function otherwise + leftNode.functions += rhs + return leftNode + } + leftNode.qualifier?.memberName == Namer.METADATA -> { + // lhs.$metadata$ = expression + // During reachability tracking phase: eliminate it if lhs is unreachable, traverse expression + // It's commonly used to supply class's metadata + leftNode.expressions += rhs + return leftNode + } + rhs is JsObjectLiteral && rhs.propertyInitializers.isEmpty() -> return leftNode } val nodeInitializedByEmptyObject = extractVariableInitializedByEmptyObject(rhs) diff --git a/js/js.frontend/src/org/jetbrains/kotlin/js/resolve/diagnostics/JsExternalChecker.kt b/js/js.frontend/src/org/jetbrains/kotlin/js/resolve/diagnostics/JsExternalChecker.kt index 10ff42cb812..70be2d9fe35 100644 --- a/js/js.frontend/src/org/jetbrains/kotlin/js/resolve/diagnostics/JsExternalChecker.kt +++ b/js/js.frontend/src/org/jetbrains/kotlin/js/resolve/diagnostics/JsExternalChecker.kt @@ -222,15 +222,13 @@ object JsExternalChecker : SimpleDeclarationChecker { private fun KtDeclarationWithBody.hasValidExternalBody(bindingContext: BindingContext): Boolean { if (!hasBody()) return true val body = bodyExpression!! - return if (!hasBlockBody()) { - body.isDefinedExternallyExpression(bindingContext) - } - else if (body is KtBlockExpression) { - val statement = body.statements.singleOrNull() ?: return false - statement.isDefinedExternallyExpression(bindingContext) - } - else { - false + return when { + !hasBlockBody() -> body.isDefinedExternallyExpression(bindingContext) + body is KtBlockExpression -> { + val statement = body.statements.singleOrNull() ?: return false + statement.isDefinedExternallyExpression(bindingContext) + } + else -> false } } diff --git a/js/js.inliner/src/org/jetbrains/kotlin/js/inline/clean/RedundantStatementElimination.kt b/js/js.inliner/src/org/jetbrains/kotlin/js/inline/clean/RedundantStatementElimination.kt index 58c32bc312e..57c01c39e06 100644 --- a/js/js.inliner/src/org/jetbrains/kotlin/js/inline/clean/RedundantStatementElimination.kt +++ b/js/js.inliner/src/org/jetbrains/kotlin/js/inline/clean/RedundantStatementElimination.kt @@ -66,15 +66,17 @@ class RedundantStatementElimination(private val root: JsFunction) { private fun replace(expression: JsExpression): List { return when (expression) { is JsNameRef -> { - if (expression.name in localVars) { - listOf() - } - else if (expression.sideEffects != SideEffectKind.AFFECTS_STATE) { - val qualifier = expression.qualifier - if (qualifier != null) replace(qualifier) else listOf() - } - else { - listOf(expression) + when { + expression.name in localVars -> { + listOf() + } + expression.sideEffects != SideEffectKind.AFFECTS_STATE -> { + val qualifier = expression.qualifier + if (qualifier != null) replace(qualifier) else listOf() + } + else -> { + listOf(expression) + } } } diff --git a/plugins/annotation-processing/src/org/jetbrains/kotlin/annotation/processing/impl/KotlinElements.kt b/plugins/annotation-processing/src/org/jetbrains/kotlin/annotation/processing/impl/KotlinElements.kt index 98b93f41d29..6ecb554d9a0 100644 --- a/plugins/annotation-processing/src/org/jetbrains/kotlin/annotation/processing/impl/KotlinElements.kt +++ b/plugins/annotation-processing/src/org/jetbrains/kotlin/annotation/processing/impl/KotlinElements.kt @@ -190,35 +190,27 @@ object Constants { private fun formatChar(c: Char) = '\'' + quote(c) + '\'' private fun formatString(s: String) = '"' + quote(s) + '"' - private fun formatFloat(f: Float): String { - if (java.lang.Float.isNaN(f)) - return "0.0f/0.0f" - else if (java.lang.Float.isInfinite(f)) - return if (f < 0) "-1.0f/0.0f" else "1.0f/0.0f" - else - return "${f}f" + private fun formatFloat(f: Float): String = when { + java.lang.Float.isNaN(f) -> "0.0f/0.0f" + java.lang.Float.isInfinite(f) -> if (f < 0) "-1.0f/0.0f" else "1.0f/0.0f" + else -> "${f}f" } - private fun formatDouble(d: Double): String { - if (java.lang.Double.isNaN(d)) - return "0.0/0.0" - else if (java.lang.Double.isInfinite(d)) - return if (d < 0) "-1.0/0.0" else "1.0/0.0" - else - return d.toString() + private fun formatDouble(d: Double): String = when { + java.lang.Double.isNaN(d) -> "0.0/0.0" + java.lang.Double.isInfinite(d) -> if (d < 0) "-1.0/0.0" else "1.0/0.0" + else -> d.toString() } - fun quote(ch: Char): String { - return when (ch) { - '\b' -> "\\b" - '\n' -> "\\n" - '\r' -> "\\r" - '\t' -> "\\t" - '\'' -> "\\'" - '\"' -> "\\\"" - '\\' -> "\\\\" - else -> if (isPrintableAscii(ch)) ch.toString() else String.format("\\u%04x", ch.toInt()) - } + fun quote(ch: Char): String = when (ch) { + '\b' -> "\\b" + '\n' -> "\\n" + '\r' -> "\\r" + '\t' -> "\\t" + '\'' -> "\\'" + '\"' -> "\\\"" + '\\' -> "\\\\" + else -> if (isPrintableAscii(ch)) ch.toString() else String.format("\\u%04x", ch.toInt()) } fun quote(s: String): String { diff --git a/plugins/annotation-processing/src/org/jetbrains/kotlin/annotation/processing/impl/KotlinTypes.kt b/plugins/annotation-processing/src/org/jetbrains/kotlin/annotation/processing/impl/KotlinTypes.kt index 02ca5dc11f3..6e6dc8e6728 100644 --- a/plugins/annotation-processing/src/org/jetbrains/kotlin/annotation/processing/impl/KotlinTypes.kt +++ b/plugins/annotation-processing/src/org/jetbrains/kotlin/annotation/processing/impl/KotlinTypes.kt @@ -95,12 +95,10 @@ class KotlinTypes( if (extendsBound != null && extendsBound !is JePsiType) illegalArg("extendsBound should have PsiType") if (superBound != null && superBound !is JePsiType) illegalArg("superBound should have PsiType") - return JeWildcardType(if (extendsBound != null) { - PsiWildcardType.createExtends(psiManager(), (extendsBound as JePsiType).psiType) - } else if (superBound != null) { - PsiWildcardType.createSuper(psiManager(), (superBound as JePsiType).psiType) - } else { - PsiWildcardType.createUnbounded(psiManager()) + return JeWildcardType(when { + extendsBound != null -> PsiWildcardType.createExtends(psiManager(), (extendsBound as JePsiType).psiType) + superBound != null -> PsiWildcardType.createSuper(psiManager(), (superBound as JePsiType).psiType) + else -> PsiWildcardType.createUnbounded(psiManager()) }, isRaw = false) } diff --git a/plugins/lint/lint-idea/src/org/jetbrains/android/inspections/klint/SuppressLintIntentionAction.kt b/plugins/lint/lint-idea/src/org/jetbrains/android/inspections/klint/SuppressLintIntentionAction.kt index ec770839cfb..0d8d7501612 100644 --- a/plugins/lint/lint-idea/src/org/jetbrains/android/inspections/klint/SuppressLintIntentionAction.kt +++ b/plugins/lint/lint-idea/src/org/jetbrains/android/inspections/klint/SuppressLintIntentionAction.kt @@ -80,16 +80,13 @@ class SuppressLintIntentionAction(val id: String, val element: PsiElement) : Int val args = entry.valueArgumentList val psiFactory = KtPsiFactory(entry) val newArgList = psiFactory.createCallArguments("($argument)") - if (args == null) { - // new argument list - entry.addAfter(newArgList, entry.lastChild) - } - else if (args.arguments.isEmpty()) { - // replace '()' with a new argument list - args.replace(newArgList) - } - else if (args.arguments.none { it.textMatches(argument) }) { - args.addArgument(newArgList.arguments[0]) + when { + args == null -> // new argument list + entry.addAfter(newArgList, entry.lastChild) + args.arguments.isEmpty() -> // replace '()' with a new argument list + args.replace(newArgList) + args.arguments.none { it.textMatches(argument) } -> + args.addArgument(newArgList.arguments[0]) } return true diff --git a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/KotlinUastLanguagePlugin.kt b/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/KotlinUastLanguagePlugin.kt index 32be6d5e13f..ce081566875 100644 --- a/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/KotlinUastLanguagePlugin.kt +++ b/plugins/uast-kotlin/src/org/jetbrains/uast/kotlin/KotlinUastLanguagePlugin.kt @@ -286,15 +286,16 @@ internal object KotlinConverter { is KtVariableDeclaration -> expr(build(::convertVariablesDeclaration)) is KtStringTemplateExpression -> { - if (expression.entries.isEmpty()) { - val parent = if (parentCallback == null) null else (parentCallback() ?: return null) - expr { KotlinStringULiteralExpression(expression, parent, "") } - } - else if (expression.entries.size == 1) - convertEntry(expression.entries[0], parentCallback, requiredType) - else { - val parent = if (parentCallback == null) null else (parentCallback() ?: return null) - expr { KotlinStringTemplateUPolyadicExpression(expression, parent) } + when { + expression.entries.isEmpty() -> { + val parent = if (parentCallback == null) null else (parentCallback() ?: return null) + expr { KotlinStringULiteralExpression(expression, parent, "") } + } + expression.entries.size == 1 -> convertEntry(expression.entries[0], parentCallback, requiredType) + else -> { + val parent = if (parentCallback == null) null else (parentCallback() ?: return null) + expr { KotlinStringTemplateUPolyadicExpression(expression, parent) } + } } } is KtDestructuringDeclaration -> expr {