If then to elvis: applied in IDEA, front-end & J2K modules

This commit is contained in:
Mikhail Glukhikh
2016-10-27 15:04:47 +03:00
parent e7cef79709
commit 8edd33ee92
37 changed files with 61 additions and 120 deletions
@@ -369,11 +369,8 @@ class PseudocodeImpl(override val correspondingElement: KtElement) : Pseudocode
startLabel: Label?, finishLabel: Label?, startLabel: Label?, finishLabel: Label?,
labelCountArg: Int): Int { labelCountArg: Int): Int {
var labelCount = labelCountArg var labelCount = labelCountArg
val startIndex = if (startLabel != null) startLabel.targetInstructionIndex else 0 val startIndex = startLabel?.targetInstructionIndex ?: 0
val finishIndex = if (finishLabel != null) val finishIndex = finishLabel?.targetInstructionIndex ?: originalPseudocode.mutableInstructionList.size
finishLabel.targetInstructionIndex
else
originalPseudocode.mutableInstructionList.size
val originalToCopy = Maps.newLinkedHashMap<Label, PseudocodeLabel>() val originalToCopy = Maps.newLinkedHashMap<Label, PseudocodeLabel>()
val originalLabelsForInstruction = HashMultimap.create<Instruction, Label>() val originalLabelsForInstruction = HashMultimap.create<Instruction, Label>()
@@ -196,7 +196,7 @@ private object DebugTextBuildingVisitor : KtVisitor<String, Unit>() {
override fun visitPropertyAccessor(accessor: KtPropertyAccessor, data: Unit?): String? { override fun visitPropertyAccessor(accessor: KtPropertyAccessor, data: Unit?): String? {
val containingProperty = KtStubbedPsiUtil.getContainingDeclaration(accessor, KtProperty::class.java) val containingProperty = KtStubbedPsiUtil.getContainingDeclaration(accessor, KtProperty::class.java)
val what = (if (accessor.isGetter()) "getter" else "setter") val what = (if (accessor.isGetter()) "getter" else "setter")
return what + " for " + (if (containingProperty != null) containingProperty.getDebugText() else "...") return what + " for " + (containingProperty?.getDebugText() ?: "...")
} }
override fun visitClass(klass: KtClass, data: Unit?): String? { override fun visitClass(klass: KtClass, data: Unit?): String? {
@@ -225,7 +225,7 @@ private fun processPattern(pattern: String, args: List<Any>): PatternData {
val arg: Any? = if (n < args.size) args[n] else null /* report wrong number of arguments later */ val arg: Any? = if (n < args.size) args[n] else null /* report wrong number of arguments later */
val placeholderText = if (charOrNull(i) != ':' || charOrNull(i + 1) != '\'') { val placeholderText = if (charOrNull(i) != ':' || charOrNull(i + 1) != '\'') {
if (arg is String) arg else "xyz" arg as? String ?: "xyz"
} }
else { else {
check(arg !is String, "do not specify placeholder text for $$n - plain text argument passed") check(arg !is String, "do not specify placeholder text for $$n - plain text argument passed")
@@ -109,11 +109,11 @@ object AnnotationUseSiteTargetChecker {
private fun BindingTrace.checkIfMutableProperty(annotated: KtAnnotated, annotation: KtAnnotationEntry) { private fun BindingTrace.checkIfMutableProperty(annotated: KtAnnotated, annotation: KtAnnotationEntry) {
if (!checkIfProperty(annotated, annotation)) return if (!checkIfProperty(annotated, annotation)) return
val isMutable = if (annotated is KtProperty) val isMutable = when (annotated) {
annotated.isVar is KtProperty -> annotated.isVar
else if (annotated is KtParameter) is KtParameter -> annotated.isMutable
annotated.isMutable else -> false
else false }
if (!isMutable) { if (!isMutable) {
report(INAPPLICABLE_TARGET_PROPERTY_IMMUTABLE.on(annotation, annotation.useSiteDescription())) report(INAPPLICABLE_TARGET_PROPERTY_IMMUTABLE.on(annotation, annotation.useSiteDescription()))
@@ -121,11 +121,11 @@ object AnnotationUseSiteTargetChecker {
} }
private fun BindingTrace.checkIfProperty(annotated: KtAnnotated, annotation: KtAnnotationEntry): Boolean { private fun BindingTrace.checkIfProperty(annotated: KtAnnotated, annotation: KtAnnotationEntry): Boolean {
val isProperty = if (annotated is KtProperty) val isProperty = when (annotated) {
!annotated.isLocal is KtProperty -> !annotated.isLocal
else if (annotated is KtParameter) is KtParameter -> annotated.hasValOrVar()
annotated.hasValOrVar() else -> false
else false }
if (!isProperty) report(INAPPLICABLE_TARGET_ON_PROPERTY.on(annotation, annotation.useSiteDescription())) if (!isProperty) report(INAPPLICABLE_TARGET_ON_PROPERTY.on(annotation, annotation.useSiteDescription()))
return isProperty return isProperty
@@ -64,10 +64,7 @@ object OperatorModifierChecker {
return return
} }
val errorDescription = if (checkResult is CheckResult.IllegalSignature) val errorDescription = (checkResult as? CheckResult.IllegalSignature)?.error ?: "illegal function name"
checkResult.error
else
"illegal function name"
diagnosticHolder.report(Errors.INAPPLICABLE_OPERATOR_MODIFIER.on(modifier, errorDescription)) diagnosticHolder.report(Errors.INAPPLICABLE_OPERATOR_MODIFIER.on(modifier, errorDescription))
} }
@@ -100,10 +100,8 @@ class TypeAliasExpander(
val originalVariance = val originalVariance =
if (originalProjection.projectionKind != Variance.INVARIANT) if (originalProjection.projectionKind != Variance.INVARIANT)
originalProjection.projectionKind originalProjection.projectionKind
else if (typeParameterDescriptor != null)
typeParameterDescriptor.variance
else else
Variance.INVARIANT typeParameterDescriptor?.variance ?: Variance.INVARIANT
val argumentVariance = typeAliasArgument.projectionKind val argumentVariance = typeAliasArgument.projectionKind
@@ -31,7 +31,7 @@ import org.jetbrains.kotlin.types.expressions.CaptureKind
class CapturingInClosureChecker : CallChecker { class CapturingInClosureChecker : CallChecker {
override fun check(resolvedCall: ResolvedCall<*>, reportOn: PsiElement, context: CallCheckerContext) { override fun check(resolvedCall: ResolvedCall<*>, reportOn: PsiElement, context: CallCheckerContext) {
val variableResolvedCall = if (resolvedCall is VariableAsFunctionResolvedCall) resolvedCall.variableCall else resolvedCall val variableResolvedCall = (resolvedCall as? VariableAsFunctionResolvedCall)?.variableCall ?: resolvedCall
val variableDescriptor = variableResolvedCall.resultingDescriptor as? VariableDescriptor val variableDescriptor = variableResolvedCall.resultingDescriptor as? VariableDescriptor
if (variableDescriptor != null) { if (variableDescriptor != null) {
checkCapturingInClosure(variableDescriptor, context.trace, context.scope) checkCapturingInClosure(variableDescriptor, context.trace, context.scope)
@@ -33,11 +33,7 @@ object ProtectedConstructorCallChecker : CallChecker {
val constructorOwner = descriptor.containingDeclaration.original val constructorOwner = descriptor.containingDeclaration.original
val scopeOwner = context.scope.ownerDescriptor val scopeOwner = context.scope.ownerDescriptor
val actualConstructor = val actualConstructor = (descriptor as? TypeAliasConstructorDescriptor)?.underlyingConstructorDescriptor ?: descriptor
if (descriptor is TypeAliasConstructorDescriptor)
descriptor.underlyingConstructorDescriptor
else
descriptor
if (actualConstructor.visibility.normalize() != Visibilities.PROTECTED) return if (actualConstructor.visibility.normalize() != Visibilities.PROTECTED) return
// Error already reported // Error already reported
@@ -62,7 +62,7 @@ class CompoundConstraintPosition(vararg positions: ConstraintPosition) : Constra
get() = COMPOUND_CONSTRAINT_POSITION get() = COMPOUND_CONSTRAINT_POSITION
val positions: Collection<ConstraintPosition> = val positions: Collection<ConstraintPosition> =
positions.flatMap { if (it is CompoundConstraintPosition) it.positions else listOf(it) }.toSet() positions.flatMap { (it as? CompoundConstraintPosition)?.positions ?: listOf(it) }.toSet()
override fun isStrong() = positions.any { it.isStrong() } override fun isStrong() = positions.any { it.isStrong() }
@@ -82,12 +82,7 @@ internal class DelegatingDataFlowInfo private constructor(
key.immanentNullability key.immanentNullability
} }
else { else {
nullabilityInfo[key] ?: if (parent != null) { nullabilityInfo[key] ?: parent?.getCollectedNullability(key) ?: key.immanentNullability
parent.getCollectedNullability(key)
}
else {
key.immanentNullability
}
} }
private fun putNullability(map: MutableMap<DataFlowValue, Nullability>, value: DataFlowValue, private fun putNullability(map: MutableMap<DataFlowValue, Nullability>, value: DataFlowValue,
@@ -134,8 +134,8 @@ open class KotlinScriptDefinitionFromAnnotatedTemplate(
} }
private fun getAnnotationEntriesFromPsiFile(file: PsiFile) = private fun getAnnotationEntriesFromPsiFile(file: PsiFile) =
if (file is KtFile) file.annotationEntries (file as? KtFile)?.annotationEntries
else throw IllegalArgumentException("Unable to extract kotlin annotations from ${file.name} (${file.fileType})") ?: throw IllegalArgumentException("Unable to extract kotlin annotations from ${file.name} (${file.fileType})")
private fun getAnnotationEntriesFromVirtualFile(file: VirtualFile, project: Project): Iterable<KtAnnotationEntry> { private fun getAnnotationEntriesFromVirtualFile(file: VirtualFile, project: Project): Iterable<KtAnnotationEntry> {
val psiFile: PsiFile = PsiManager.getInstance(project).findFile(file) val psiFile: PsiFile = PsiManager.getInstance(project).findFile(file)
@@ -127,7 +127,7 @@ class CheckPartialBodyResolveAction : AnAction() {
val offset = expression.textOffset val offset = expression.textOffset
val line = document.getLineNumber(offset) val line = document.getLineNumber(offset)
val column = offset - document.getLineStartOffset(line) val column = offset - document.getLineStartOffset(line)
val exprName = if (expression is KtNameReferenceExpression) expression.getReferencedName() else expression.javaClass.simpleName val exprName = (expression as? KtNameReferenceExpression)?.getReferencedName() ?: expression.javaClass.simpleName
builder.append("$exprName at (${line + 1}:${column + 1})") builder.append("$exprName at (${line + 1}:${column + 1})")
if (expression is KtReferenceExpression) { if (expression is KtReferenceExpression) {
@@ -103,7 +103,7 @@ class KotlinSourcePositionProvider: SourcePositionProvider() {
private fun findClassByType(project: Project, type: ReferenceType, context: DebuggerContextImpl): PsiElement? { private fun findClassByType(project: Project, type: ReferenceType, context: DebuggerContextImpl): PsiElement? {
val session = context.debuggerSession val session = context.debuggerSession
val scope = if (session != null) session.searchScope else GlobalSearchScope.allScope(project) val scope = session?.searchScope ?: GlobalSearchScope.allScope(project)
val className = JvmClassName.byInternalName(type.name()).fqNameForClassNameWithoutDollars.asString() val className = JvmClassName.byInternalName(type.name()).fqNameForClassNameWithoutDollars.asString()
val myClass = JavaPsiFacade.getInstance(project).findClass(className, scope) val myClass = JavaPsiFacade.getInstance(project).findClass(className, scope)
@@ -155,7 +155,7 @@ class KotlinDebuggerCaches(project: Project) {
} }
private fun getElementToCreateTypeMapperForLibraryFile(element: PsiElement?) = private fun getElementToCreateTypeMapperForLibraryFile(element: PsiElement?) =
runReadAction { if (element is KtElement) element else PsiTreeUtil.getParentOfType(element, KtElement::class.java)!! } runReadAction { element as? KtElement ?: PsiTreeUtil.getParentOfType(element, KtElement::class.java)!! }
private fun createTypeMapperForLibraryFile(element: KtElement, file: KtFile): KotlinTypeMapper = private fun createTypeMapperForLibraryFile(element: KtElement, file: KtFile): KotlinTypeMapper =
runReadAction { runReadAction {
@@ -327,10 +327,7 @@ private fun findElementBefore(contextElement: PsiElement): PsiElement? {
contextElement is KtDeclarationWithBody && contextElement.hasBlockBody() -> { contextElement is KtDeclarationWithBody && contextElement.hasBlockBody() -> {
val block = contextElement.bodyExpression as KtBlockExpression val block = contextElement.bodyExpression as KtBlockExpression
val last = block.statements.lastOrNull() val last = block.statements.lastOrNull()
if (last is KtReturnExpression) last as? KtReturnExpression ?: block.rBrace
last
else
block.rBrace
} }
contextElement is KtWhenEntry -> { contextElement is KtWhenEntry -> {
val entryExpression = contextElement.expression val entryExpression = contextElement.expression
@@ -72,10 +72,8 @@ class ConvertAssertToIfWithThrowIntention : SelfTargetingIntention<KtCallExpress
ifCondition.baseExpression!!.replace(psiFactory.createExpression(conditionText)) ifCondition.baseExpression!!.replace(psiFactory.createExpression(conditionText))
val thrownExpression = ((ifExpression.then as KtBlockExpression).statements.single() as KtThrowExpression).thrownExpression val thrownExpression = ((ifExpression.then as KtBlockExpression).statements.single() as KtThrowExpression).thrownExpression
val assertionErrorCall = if (thrownExpression is KtCallExpression) val assertionErrorCall = thrownExpression as? KtCallExpression
thrownExpression ?: (thrownExpression as KtDotQualifiedExpression).selectorExpression as KtCallExpression
else
(thrownExpression as KtDotQualifiedExpression).selectorExpression as KtCallExpression
val message = psiFactory.createExpression( val message = psiFactory.createExpression(
if (messageIsFunction && messageExpr is KtCallableReferenceExpression) { if (messageIsFunction && messageExpr is KtCallableReferenceExpression) {
@@ -116,9 +114,6 @@ class ConvertAssertToIfWithThrowIntention : SelfTargetingIntention<KtCallExpress
private fun replaceWithIfThenThrowExpression(original: KtCallExpression): KtIfExpression { private fun replaceWithIfThenThrowExpression(original: KtCallExpression): KtIfExpression {
val replacement = KtPsiFactory(original).createExpression("if (!true) { throw kotlin.AssertionError(\"\") }") as KtIfExpression val replacement = KtPsiFactory(original).createExpression("if (!true) { throw kotlin.AssertionError(\"\") }") as KtIfExpression
val parent = original.parent val parent = original.parent
return if (parent is KtDotQualifiedExpression) return (parent as? KtDotQualifiedExpression)?.replaced(replacement) ?: original.replaced(replacement)
parent.replaced(replacement)
else
original.replaced(replacement)
} }
} }
@@ -94,7 +94,7 @@ class ConvertLambdaToReferenceIntention : SelfTargetingOffsetIndependentIntentio
} }
val callHasReceiver = explicitReceiver != null val callHasReceiver = explicitReceiver != null
if (descriptorHasReceiver != callHasReceiver) return false if (descriptorHasReceiver != callHasReceiver) return false
val callableArgumentsCount = if (callableExpression is KtCallExpression) callableExpression.valueArguments.size else 0 val callableArgumentsCount = (callableExpression as? KtCallExpression)?.valueArguments?.size ?: 0
if (calleeDescriptor.valueParameters.size != callableArgumentsCount) return false if (calleeDescriptor.valueParameters.size != callableArgumentsCount) return false
if (lambdaMustReturnUnit) { if (lambdaMustReturnUnit) {
calleeDescriptor.returnType.let { calleeDescriptor.returnType.let {
@@ -41,7 +41,7 @@ class ConvertToForEachFunctionCallIntention : SelfTargetingIntention<KtForExpres
val body = element.body!! val body = element.body!!
val loopParameter = element.loopParameter!! val loopParameter = element.loopParameter!!
val functionBodyArgument: Any = if (body is KtBlockExpression) body.contentRange() else body val functionBodyArgument: Any = (body as? KtBlockExpression)?.contentRange() ?: body
val psiFactory = KtPsiFactory(element) val psiFactory = KtPsiFactory(element)
val foreachExpression = psiFactory.createExpressionByPattern( val foreachExpression = psiFactory.createExpressionByPattern(
@@ -110,7 +110,7 @@ class ConvertMemberToExtensionIntention : SelfTargetingRangeIntention<KtCallable
fun selectBody(declaration: KtDeclarationWithBody) { fun selectBody(declaration: KtDeclarationWithBody) {
if (bodyToSelect == null) { if (bodyToSelect == null) {
val body = declaration.bodyExpression val body = declaration.bodyExpression
bodyToSelect = if (body is KtBlockExpression) body.statements.single() else body bodyToSelect = (body as? KtBlockExpression)?.statements?.single() ?: body
} }
} }
@@ -101,7 +101,7 @@ class KotlinSelectInProjectViewProvider(private val project: Project) : Selectab
if (current is KtFile) { if (current is KtFile) {
val declaration = current.declarations.singleOrNull() val declaration = current.declarations.singleOrNull()
val nameWithoutExtension = if (virtualFile != null) virtualFile.nameWithoutExtension else file.name val nameWithoutExtension = virtualFile?.nameWithoutExtension ?: file.name
if (declaration is KtClassOrObject && nameWithoutExtension == declaration.name) { if (declaration is KtClassOrObject && nameWithoutExtension == declaration.name) {
current = declaration current = declaration
} }
@@ -171,12 +171,9 @@ object InitializePropertyQuickFixFactory : KotlinIntentionActionsFactory() {
if (constructor == null || !visitedElements.add(constructor)) return@runRefactoringWithPostprocessing if (constructor == null || !visitedElements.add(constructor)) return@runRefactoringWithPostprocessing
constructor.getValueParameters().lastOrNull()?.let { newParam -> constructor.getValueParameters().lastOrNull()?.let { newParam ->
val psiFactory = KtPsiFactory(project) val psiFactory = KtPsiFactory(project)
if (constructor is KtSecondaryConstructor) { (constructor as? KtSecondaryConstructor)?.getOrCreateBody()?.appendElement(
constructor.getOrCreateBody().appendElement(psiFactory.createExpression("this.${element.name} = ${newParam.name!!}")) psiFactory.createExpression("this.${element.name} = ${newParam.name!!}")
} ) ?: element.setInitializer(psiFactory.createExpression(newParam.name!!))
else {
element.setInitializer(psiFactory.createExpression(newParam.name!!))
}
} }
processConstructors(project, propertyDescriptor, descriptorsToProcess) processConstructors(project, propertyDescriptor, descriptorsToProcess)
} }
@@ -105,7 +105,7 @@ class MapPlatformClassToKotlinFix(
val replacedElements = ArrayList<PsiElement>() val replacedElements = ArrayList<PsiElement>()
for (usage in usages) { for (usage in usages) {
val typeArguments = usage.typeArgumentList val typeArguments = usage.typeArgumentList
val typeArgumentsString = if (typeArguments == null) "" else typeArguments.text val typeArgumentsString = typeArguments?.text ?: ""
val replacementType = KtPsiFactory(project).createType(replacementClassName + typeArgumentsString) val replacementType = KtPsiFactory(project).createType(replacementClassName + typeArgumentsString)
val replacementTypeElement = replacementType.typeElement!! val replacementTypeElement = replacementType.typeElement!!
val replacedElement = usage.replace(replacementTypeElement) val replacedElement = usage.replace(replacementTypeElement)
@@ -94,12 +94,11 @@ abstract class DeprecatedSymbolUsageFixBase(
else -> null else -> null
} ?: return null } ?: return null
*/ */
val nameExpression: KtSimpleNameExpression = (if (psiElement is KtSimpleNameExpression) val nameExpression: KtSimpleNameExpression = when (psiElement) {
psiElement is KtSimpleNameExpression -> psiElement
else if (psiElement is KtConstructorCalleeExpression) is KtConstructorCalleeExpression -> psiElement.constructorReferenceExpression
psiElement.constructorReferenceExpression else -> null
else } ?: return null
null) ?: return null
val descriptor = DiagnosticFactory.cast(deprecatedDiagnostic, Errors.DEPRECATION, Errors.DEPRECATION_ERROR).a val descriptor = DiagnosticFactory.cast(deprecatedDiagnostic, Errors.DEPRECATION, Errors.DEPRECATION_ERROR).a
val replacement = DeprecatedSymbolUsageFixBase.fetchReplaceWithPattern(descriptor, nameExpression.project) ?: return null val replacement = DeprecatedSymbolUsageFixBase.fetchReplaceWithPattern(descriptor, nameExpression.project) ?: return null
@@ -222,8 +222,7 @@ class KotlinChangeSignature(project: Project,
): KotlinChangeInfo? { ): KotlinChangeInfo? {
val jetChangeSignature = KotlinChangeSignature(project, callableDescriptor, configuration, defaultValueContext, null) val jetChangeSignature = KotlinChangeSignature(project, callableDescriptor, configuration, defaultValueContext, null)
val declarations = val declarations =
if (callableDescriptor is CallableMemberDescriptor) callableDescriptor.getDeepestSuperDeclarations() (callableDescriptor as? CallableMemberDescriptor)?.getDeepestSuperDeclarations() ?: listOf(callableDescriptor)
else listOf(callableDescriptor)
val adjustedDescriptor = jetChangeSignature.adjustDescriptor(declarations) ?: return null val adjustedDescriptor = jetChangeSignature.adjustDescriptor(declarations) ?: return null
@@ -93,8 +93,8 @@ class KotlinChangeSignatureProcessor(project: Project,
if (u2 is KotlinImplicitReceiverUsage && u1 is KotlinFunctionCallUsage) return@sort 1 if (u2 is KotlinImplicitReceiverUsage && u1 is KotlinFunctionCallUsage) return@sort 1
val element1 = u1.element val element1 = u1.element
val element2 = u2.element val element2 = u2.element
val rank1 = if (element1 != null) element1.textOffset else -1 val rank1 = element1?.textOffset ?: -1
val rank2 = if (element2 != null) element2.textOffset else -1 val rank2 = element2?.textOffset ?: -1
rank2 - rank1 // Reverse order rank2 - rank1 // Reverse order
} }
refUsages.set(usageArray) refUsages.set(usageArray)
@@ -199,7 +199,7 @@ class ExtractSuperRefactoring(
.asSequence() .asSequence()
.flatMap { .flatMap {
val (element, info) = it val (element, info) = it
if (info != null) info.getChildrenToAnalyze().asSequence() else sequenceOf(element) info?.getChildrenToAnalyze()?.asSequence() ?: sequenceOf(element)
} }
.forEach { it.accept(visitor) } .forEach { it.accept(visitor) }
} }
@@ -263,13 +263,8 @@ open class KotlinIntroduceParameterHandler(
val parametersUsages = findInternalUsagesOfParametersAndReceiver(targetParent, functionDescriptor) ?: return val parametersUsages = findInternalUsagesOfParametersAndReceiver(targetParent, functionDescriptor) ?: return
val forbiddenRanges = val forbiddenRanges = (targetParent as? KtClass)?.declarations?.filter(::isObjectOrNonInnerClass)?.map { it.textRange }
if (targetParent is KtClass) { ?: Collections.emptyList()
targetParent.declarations.filter { isObjectOrNonInnerClass(it) }.map { it.textRange }
}
else {
Collections.emptyList()
}
val occurrencesToReplace = if (expression is KtProperty) { val occurrencesToReplace = if (expression is KtProperty) {
ReferencesSearch.search(expression).mapNotNullTo(SmartList(expression.toRange())) { it.element?.toRange() } ReferencesSearch.search(expression).mapNotNullTo(SmartList(expression.toRange())) { it.element?.toRange() }
@@ -123,26 +123,14 @@ abstract class AbstractParameterTablePanel<Param, UIParam : AbstractParameterTab
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "invoke_impl") inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "invoke_impl")
actionMap.put("invoke_impl", object : AbstractAction() { actionMap.put("invoke_impl", object : AbstractAction() {
override fun actionPerformed(e: ActionEvent) { override fun actionPerformed(e: ActionEvent) {
val editor = table.cellEditor table.cellEditor?.stopCellEditing() ?: onEnterAction()
if (editor != null) {
editor.stopCellEditing()
}
else {
onEnterAction()
}
} }
}) })
// make ESCAPE work when the table has focus // make ESCAPE work when the table has focus
actionMap.put("doCancel", object : AbstractAction() { actionMap.put("doCancel", object : AbstractAction() {
override fun actionPerformed(e: ActionEvent) { override fun actionPerformed(e: ActionEvent) {
val editor = table.cellEditor table.cellEditor?.stopCellEditing() ?: onCancelAction()
if (editor != null) {
editor.stopCellEditing()
}
else {
onCancelAction()
}
} }
}) })
@@ -49,7 +49,7 @@ class KotlinClassMembersRefactoringSupport : ClassMembersRefactoringSupport {
private val pullUpData = superClass?.let { KotlinPullUpData(clazz as KtClassOrObject, it as PsiNamedElement, emptyList()) } private val pullUpData = superClass?.let { KotlinPullUpData(clazz as KtClassOrObject, it as PsiNamedElement, emptyList()) }
private val possibleContainingClasses = private val possibleContainingClasses =
listOf(clazz) + if (clazz is KtClass) clazz.getCompanionObjects() else emptyList() listOf(clazz) + ((clazz as? KtClass)?.getCompanionObjects() ?: emptyList())
override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) {
val referencedMember = expression.mainReference.resolve() as? KtNamedDeclaration ?: return val referencedMember = expression.mainReference.resolve() as? KtNamedDeclaration ?: return
@@ -328,7 +328,7 @@ class KotlinPullUpHelper(
} }
private fun moveSuperInterface(member: PsiNamedElement, substitutor: PsiSubstitutor) { private fun moveSuperInterface(member: PsiNamedElement, substitutor: PsiSubstitutor) {
val realMemberPsi = if (member is KtPsiClassWrapper) member.psiClass else member val realMemberPsi = (member as? KtPsiClassWrapper)?.psiClass ?: member
val classDescriptor = data.memberDescriptors[member] as? ClassDescriptor ?: return val classDescriptor = data.memberDescriptors[member] as? ClassDescriptor ?: return
val currentSpecifier = data.sourceClass.getSuperTypeEntryByDescriptor(classDescriptor, data.sourceClassContext) ?: return val currentSpecifier = data.sourceClass.getSuperTypeEntryByDescriptor(classDescriptor, data.sourceClassContext) ?: return
when (data.targetClass) { when (data.targetClass) {
@@ -174,7 +174,7 @@ class RenameKotlinFunctionProcessor : RenameKotlinPsiProcessor() {
if (element is FunctionWithSupersWrapper) { if (element is FunctionWithSupersWrapper) {
allRenames.remove(element) allRenames.remove(element)
} }
for (declaration in (if (element is FunctionWithSupersWrapper) element.supers else listOf(element))) { for (declaration in ((element as? FunctionWithSupersWrapper)?.supers ?: listOf(element))) {
val psiMethod = wrapPsiMethod(declaration) ?: continue val psiMethod = wrapPsiMethod(declaration) ?: continue
allRenames[declaration] = newName allRenames[declaration] = newName
if (psiMethod.containingClass != null) { if (psiMethod.containingClass != null) {
@@ -30,18 +30,11 @@ import org.jetbrains.kotlin.idea.util.application.runReadAction
open class KotlinDirectInheritorsSearcher() : QueryExecutorBase<PsiClass, DirectClassInheritorsSearch.SearchParameters>(true) { open class KotlinDirectInheritorsSearcher() : QueryExecutorBase<PsiClass, DirectClassInheritorsSearch.SearchParameters>(true) {
override fun processQuery(queryParameters: DirectClassInheritorsSearch.SearchParameters, consumer: Processor<PsiClass>) { override fun processQuery(queryParameters: DirectClassInheritorsSearch.SearchParameters, consumer: Processor<PsiClass>) {
val baseClass = queryParameters.classToProcess val baseClass = queryParameters.classToProcess
if (baseClass == null) return
val name = baseClass.name val name = baseClass.name ?: return
if (name == null) return
val originalScope = queryParameters.scope val originalScope = queryParameters.scope
val scope = if (originalScope is GlobalSearchScope) val scope = originalScope as? GlobalSearchScope ?: baseClass.containingFile?.fileScope() ?: return
originalScope
else
baseClass.containingFile?.let { file -> file.fileScope() }
if (scope == null) return
runReadAction { runReadAction {
val noLibrarySourceScope = KotlinSourceFilterScope.projectSourceAndClassFiles(scope, baseClass.project) val noLibrarySourceScope = KotlinSourceFilterScope.projectSourceAndClassFiles(scope, baseClass.project)
@@ -825,7 +825,7 @@ class DefaultExpressionConverter : JavaElementVisitor(), ExpressionConverter {
else if (specialMethod != null) { else if (specialMethod != null) {
val factory = PsiElementFactory.SERVICE.getInstance(converter.project) val factory = PsiElementFactory.SERVICE.getInstance(converter.project)
val fakeReceiver = receiver?.let { val fakeReceiver = receiver?.let {
val psiExpression = if (qualifier is PsiExpression) qualifier else factory.createExpressionFromText("fakeReceiver", null) val psiExpression = qualifier as? PsiExpression ?: factory.createExpressionFromText("fakeReceiver", null)
psiExpression.convertedExpression = it.first psiExpression.convertedExpression = it.first
psiExpression psiExpression
} }
@@ -477,7 +477,7 @@ enum class SpecialMethod(val qualifiedClassName: String?, val methodName: String
private fun castQualifierToType(codeConverter: CodeConverter, qualifier: PsiExpression, type: String): TypeCastExpression? { private fun castQualifierToType(codeConverter: CodeConverter, qualifier: PsiExpression, type: String): TypeCastExpression? {
val convertedQualifier = codeConverter.convertExpression(qualifier) val convertedQualifier = codeConverter.convertExpression(qualifier)
val qualifierType = codeConverter.typeConverter.convertType(qualifier.type) val qualifierType = codeConverter.typeConverter.convertType(qualifier.type)
val typeArgs = if (qualifierType is ClassType) qualifierType.referenceElement.typeArgs else emptyList() val typeArgs = (qualifierType as? ClassType)?.referenceElement?.typeArgs ?: emptyList()
val referenceElement = ReferenceElement(Identifier.withNoPrototype(type), typeArgs).assignNoPrototype() val referenceElement = ReferenceElement(Identifier.withNoPrototype(type), typeArgs).assignNoPrototype()
val newType = ClassType(referenceElement, Nullability.Default, codeConverter.settings).assignNoPrototype() val newType = ClassType(referenceElement, Nullability.Default, codeConverter.settings).assignNoPrototype()
return TypeCastExpression(newType, convertedQualifier).assignNoPrototype() return TypeCastExpression(newType, convertedQualifier).assignNoPrototype()
@@ -191,10 +191,7 @@ class DefaultStatementConverter : JavaElementVisitor(), StatementConverter {
val blockConverted = codeConverter.convertBlock(block) val blockConverted = codeConverter.convertBlock(block)
val annotations = converter.convertAnnotations(parameter) val annotations = converter.convertAnnotations(parameter)
val parameterType = parameter.type val parameterType = parameter.type
val types = if (parameterType is PsiDisjunctionType) val types = (parameterType as? PsiDisjunctionType)?.disjunctions ?: listOf(parameterType)
parameterType.disjunctions
else
listOf(parameterType)
for (t in types) { for (t in types) {
val convertedType = codeConverter.typeConverter.convertType(t, Nullability.NotNull) val convertedType = codeConverter.typeConverter.convertType(t, Nullability.NotNull)
val convertedParameter = FunctionParameter(parameter.declarationIdentifier(), val convertedParameter = FunctionParameter(parameter.declarationIdentifier(),
@@ -94,7 +94,7 @@ class SwitchConverter(private val codeConverter: CodeConverter) {
} }
else { else {
val block = case.statements.singleOrNull() as? PsiBlockStatement val block = case.statements.singleOrNull() as? PsiBlockStatement
val statements = if (block != null) block.codeBlock.statements.toList() else case.statements val statements = block?.codeBlock?.statements?.toList() ?: case.statements
!statements.any { it is PsiBreakStatement || it is PsiContinueStatement || it is PsiReturnStatement || it is PsiThrowStatement } !statements.any { it is PsiBreakStatement || it is PsiContinueStatement || it is PsiReturnStatement || it is PsiThrowStatement }
} }
return if (fallsThrough) // we fall through into the next case return if (fallsThrough) // we fall through into the next case
@@ -106,10 +106,8 @@ class FieldToPropertyProcessing(
is PsiPrefixExpression, is PsiPostfixExpression -> { is PsiPrefixExpression, is PsiPostfixExpression -> {
//TODO: what if it's used as value? //TODO: what if it's used as value?
val operationType = if (parent is PsiPrefixExpression) val operationType = (parent as? PsiPrefixExpression)?.operationTokenType
parent.operationTokenType ?: (parent as PsiPostfixExpression).operationTokenType
else
(parent as PsiPostfixExpression).operationTokenType
val opText = when (operationType) { val opText = when (operationType) {
JavaTokenType.PLUSPLUS -> "+" JavaTokenType.PLUSPLUS -> "+"
JavaTokenType.MINUSMINUS -> "-" JavaTokenType.MINUSMINUS -> "-"