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?,
labelCountArg: Int): Int {
var labelCount = labelCountArg
val startIndex = if (startLabel != null) startLabel.targetInstructionIndex else 0
val finishIndex = if (finishLabel != null)
finishLabel.targetInstructionIndex
else
originalPseudocode.mutableInstructionList.size
val startIndex = startLabel?.targetInstructionIndex ?: 0
val finishIndex = finishLabel?.targetInstructionIndex ?: originalPseudocode.mutableInstructionList.size
val originalToCopy = Maps.newLinkedHashMap<Label, PseudocodeLabel>()
val originalLabelsForInstruction = HashMultimap.create<Instruction, Label>()
@@ -196,7 +196,7 @@ private object DebugTextBuildingVisitor : KtVisitor<String, Unit>() {
override fun visitPropertyAccessor(accessor: KtPropertyAccessor, data: Unit?): String? {
val containingProperty = KtStubbedPsiUtil.getContainingDeclaration(accessor, KtProperty::class.java)
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? {
@@ -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 placeholderText = if (charOrNull(i) != ':' || charOrNull(i + 1) != '\'') {
if (arg is String) arg else "xyz"
arg as? String ?: "xyz"
}
else {
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) {
if (!checkIfProperty(annotated, annotation)) return
val isMutable = if (annotated is KtProperty)
annotated.isVar
else if (annotated is KtParameter)
annotated.isMutable
else false
val isMutable = when (annotated) {
is KtProperty -> annotated.isVar
is KtParameter -> annotated.isMutable
else -> false
}
if (!isMutable) {
report(INAPPLICABLE_TARGET_PROPERTY_IMMUTABLE.on(annotation, annotation.useSiteDescription()))
@@ -121,11 +121,11 @@ object AnnotationUseSiteTargetChecker {
}
private fun BindingTrace.checkIfProperty(annotated: KtAnnotated, annotation: KtAnnotationEntry): Boolean {
val isProperty = if (annotated is KtProperty)
!annotated.isLocal
else if (annotated is KtParameter)
annotated.hasValOrVar()
else false
val isProperty = when (annotated) {
is KtProperty -> !annotated.isLocal
is KtParameter -> annotated.hasValOrVar()
else -> false
}
if (!isProperty) report(INAPPLICABLE_TARGET_ON_PROPERTY.on(annotation, annotation.useSiteDescription()))
return isProperty
@@ -64,10 +64,7 @@ object OperatorModifierChecker {
return
}
val errorDescription = if (checkResult is CheckResult.IllegalSignature)
checkResult.error
else
"illegal function name"
val errorDescription = (checkResult as? CheckResult.IllegalSignature)?.error ?: "illegal function name"
diagnosticHolder.report(Errors.INAPPLICABLE_OPERATOR_MODIFIER.on(modifier, errorDescription))
}
@@ -100,10 +100,8 @@ class TypeAliasExpander(
val originalVariance =
if (originalProjection.projectionKind != Variance.INVARIANT)
originalProjection.projectionKind
else if (typeParameterDescriptor != null)
typeParameterDescriptor.variance
else
Variance.INVARIANT
typeParameterDescriptor?.variance ?: Variance.INVARIANT
val argumentVariance = typeAliasArgument.projectionKind
@@ -31,7 +31,7 @@ import org.jetbrains.kotlin.types.expressions.CaptureKind
class CapturingInClosureChecker : CallChecker {
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
if (variableDescriptor != null) {
checkCapturingInClosure(variableDescriptor, context.trace, context.scope)
@@ -33,11 +33,7 @@ object ProtectedConstructorCallChecker : CallChecker {
val constructorOwner = descriptor.containingDeclaration.original
val scopeOwner = context.scope.ownerDescriptor
val actualConstructor =
if (descriptor is TypeAliasConstructorDescriptor)
descriptor.underlyingConstructorDescriptor
else
descriptor
val actualConstructor = (descriptor as? TypeAliasConstructorDescriptor)?.underlyingConstructorDescriptor ?: descriptor
if (actualConstructor.visibility.normalize() != Visibilities.PROTECTED) return
// Error already reported
@@ -62,7 +62,7 @@ class CompoundConstraintPosition(vararg positions: ConstraintPosition) : Constra
get() = COMPOUND_CONSTRAINT_POSITION
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() }
@@ -82,12 +82,7 @@ internal class DelegatingDataFlowInfo private constructor(
key.immanentNullability
}
else {
nullabilityInfo[key] ?: if (parent != null) {
parent.getCollectedNullability(key)
}
else {
key.immanentNullability
}
nullabilityInfo[key] ?: parent?.getCollectedNullability(key) ?: key.immanentNullability
}
private fun putNullability(map: MutableMap<DataFlowValue, Nullability>, value: DataFlowValue,
@@ -134,8 +134,8 @@ open class KotlinScriptDefinitionFromAnnotatedTemplate(
}
private fun getAnnotationEntriesFromPsiFile(file: PsiFile) =
if (file is KtFile) file.annotationEntries
else throw IllegalArgumentException("Unable to extract kotlin annotations from ${file.name} (${file.fileType})")
(file as? KtFile)?.annotationEntries
?: throw IllegalArgumentException("Unable to extract kotlin annotations from ${file.name} (${file.fileType})")
private fun getAnnotationEntriesFromVirtualFile(file: VirtualFile, project: Project): Iterable<KtAnnotationEntry> {
val psiFile: PsiFile = PsiManager.getInstance(project).findFile(file)
@@ -127,7 +127,7 @@ class CheckPartialBodyResolveAction : AnAction() {
val offset = expression.textOffset
val line = document.getLineNumber(offset)
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})")
if (expression is KtReferenceExpression) {
@@ -103,7 +103,7 @@ class KotlinSourcePositionProvider: SourcePositionProvider() {
private fun findClassByType(project: Project, type: ReferenceType, context: DebuggerContextImpl): PsiElement? {
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 myClass = JavaPsiFacade.getInstance(project).findClass(className, scope)
@@ -155,7 +155,7 @@ class KotlinDebuggerCaches(project: Project) {
}
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 =
runReadAction {
@@ -327,10 +327,7 @@ private fun findElementBefore(contextElement: PsiElement): PsiElement? {
contextElement is KtDeclarationWithBody && contextElement.hasBlockBody() -> {
val block = contextElement.bodyExpression as KtBlockExpression
val last = block.statements.lastOrNull()
if (last is KtReturnExpression)
last
else
block.rBrace
last as? KtReturnExpression ?: block.rBrace
}
contextElement is KtWhenEntry -> {
val entryExpression = contextElement.expression
@@ -72,10 +72,8 @@ class ConvertAssertToIfWithThrowIntention : SelfTargetingIntention<KtCallExpress
ifCondition.baseExpression!!.replace(psiFactory.createExpression(conditionText))
val thrownExpression = ((ifExpression.then as KtBlockExpression).statements.single() as KtThrowExpression).thrownExpression
val assertionErrorCall = if (thrownExpression is KtCallExpression)
thrownExpression
else
(thrownExpression as KtDotQualifiedExpression).selectorExpression as KtCallExpression
val assertionErrorCall = thrownExpression as? KtCallExpression
?: (thrownExpression as KtDotQualifiedExpression).selectorExpression as KtCallExpression
val message = psiFactory.createExpression(
if (messageIsFunction && messageExpr is KtCallableReferenceExpression) {
@@ -116,9 +114,6 @@ class ConvertAssertToIfWithThrowIntention : SelfTargetingIntention<KtCallExpress
private fun replaceWithIfThenThrowExpression(original: KtCallExpression): KtIfExpression {
val replacement = KtPsiFactory(original).createExpression("if (!true) { throw kotlin.AssertionError(\"\") }") as KtIfExpression
val parent = original.parent
return if (parent is KtDotQualifiedExpression)
parent.replaced(replacement)
else
original.replaced(replacement)
return (parent as? KtDotQualifiedExpression)?.replaced(replacement) ?: original.replaced(replacement)
}
}
@@ -94,7 +94,7 @@ class ConvertLambdaToReferenceIntention : SelfTargetingOffsetIndependentIntentio
}
val callHasReceiver = explicitReceiver != null
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 (lambdaMustReturnUnit) {
calleeDescriptor.returnType.let {
@@ -41,7 +41,7 @@ class ConvertToForEachFunctionCallIntention : SelfTargetingIntention<KtForExpres
val body = element.body!!
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 foreachExpression = psiFactory.createExpressionByPattern(
@@ -110,7 +110,7 @@ class ConvertMemberToExtensionIntention : SelfTargetingRangeIntention<KtCallable
fun selectBody(declaration: KtDeclarationWithBody) {
if (bodyToSelect == null) {
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) {
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) {
current = declaration
}
@@ -171,12 +171,9 @@ object InitializePropertyQuickFixFactory : KotlinIntentionActionsFactory() {
if (constructor == null || !visitedElements.add(constructor)) return@runRefactoringWithPostprocessing
constructor.getValueParameters().lastOrNull()?.let { newParam ->
val psiFactory = KtPsiFactory(project)
if (constructor is KtSecondaryConstructor) {
constructor.getOrCreateBody().appendElement(psiFactory.createExpression("this.${element.name} = ${newParam.name!!}"))
}
else {
element.setInitializer(psiFactory.createExpression(newParam.name!!))
}
(constructor as? KtSecondaryConstructor)?.getOrCreateBody()?.appendElement(
psiFactory.createExpression("this.${element.name} = ${newParam.name!!}")
) ?: element.setInitializer(psiFactory.createExpression(newParam.name!!))
}
processConstructors(project, propertyDescriptor, descriptorsToProcess)
}
@@ -105,7 +105,7 @@ class MapPlatformClassToKotlinFix(
val replacedElements = ArrayList<PsiElement>()
for (usage in usages) {
val typeArguments = usage.typeArgumentList
val typeArgumentsString = if (typeArguments == null) "" else typeArguments.text
val typeArgumentsString = typeArguments?.text ?: ""
val replacementType = KtPsiFactory(project).createType(replacementClassName + typeArgumentsString)
val replacementTypeElement = replacementType.typeElement!!
val replacedElement = usage.replace(replacementTypeElement)
@@ -94,12 +94,11 @@ abstract class DeprecatedSymbolUsageFixBase(
else -> null
} ?: return null
*/
val nameExpression: KtSimpleNameExpression = (if (psiElement is KtSimpleNameExpression)
psiElement
else if (psiElement is KtConstructorCalleeExpression)
psiElement.constructorReferenceExpression
else
null) ?: return null
val nameExpression: KtSimpleNameExpression = when (psiElement) {
is KtSimpleNameExpression -> psiElement
is KtConstructorCalleeExpression -> psiElement.constructorReferenceExpression
else -> null
} ?: return null
val descriptor = DiagnosticFactory.cast(deprecatedDiagnostic, Errors.DEPRECATION, Errors.DEPRECATION_ERROR).a
val replacement = DeprecatedSymbolUsageFixBase.fetchReplaceWithPattern(descriptor, nameExpression.project) ?: return null
@@ -222,8 +222,7 @@ class KotlinChangeSignature(project: Project,
): KotlinChangeInfo? {
val jetChangeSignature = KotlinChangeSignature(project, callableDescriptor, configuration, defaultValueContext, null)
val declarations =
if (callableDescriptor is CallableMemberDescriptor) callableDescriptor.getDeepestSuperDeclarations()
else listOf(callableDescriptor)
(callableDescriptor as? CallableMemberDescriptor)?.getDeepestSuperDeclarations() ?: listOf(callableDescriptor)
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
val element1 = u1.element
val element2 = u2.element
val rank1 = if (element1 != null) element1.textOffset else -1
val rank2 = if (element2 != null) element2.textOffset else -1
val rank1 = element1?.textOffset ?: -1
val rank2 = element2?.textOffset ?: -1
rank2 - rank1 // Reverse order
}
refUsages.set(usageArray)
@@ -199,7 +199,7 @@ class ExtractSuperRefactoring(
.asSequence()
.flatMap {
val (element, info) = it
if (info != null) info.getChildrenToAnalyze().asSequence() else sequenceOf(element)
info?.getChildrenToAnalyze()?.asSequence() ?: sequenceOf(element)
}
.forEach { it.accept(visitor) }
}
@@ -263,13 +263,8 @@ open class KotlinIntroduceParameterHandler(
val parametersUsages = findInternalUsagesOfParametersAndReceiver(targetParent, functionDescriptor) ?: return
val forbiddenRanges =
if (targetParent is KtClass) {
targetParent.declarations.filter { isObjectOrNonInnerClass(it) }.map { it.textRange }
}
else {
Collections.emptyList()
}
val forbiddenRanges = (targetParent as? KtClass)?.declarations?.filter(::isObjectOrNonInnerClass)?.map { it.textRange }
?: Collections.emptyList()
val occurrencesToReplace = if (expression is KtProperty) {
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")
actionMap.put("invoke_impl", object : AbstractAction() {
override fun actionPerformed(e: ActionEvent) {
val editor = table.cellEditor
if (editor != null) {
editor.stopCellEditing()
}
else {
onEnterAction()
}
table.cellEditor?.stopCellEditing() ?: onEnterAction()
}
})
// make ESCAPE work when the table has focus
actionMap.put("doCancel", object : AbstractAction() {
override fun actionPerformed(e: ActionEvent) {
val editor = table.cellEditor
if (editor != null) {
editor.stopCellEditing()
}
else {
onCancelAction()
}
table.cellEditor?.stopCellEditing() ?: onCancelAction()
}
})
@@ -49,7 +49,7 @@ class KotlinClassMembersRefactoringSupport : ClassMembersRefactoringSupport {
private val pullUpData = superClass?.let { KotlinPullUpData(clazz as KtClassOrObject, it as PsiNamedElement, emptyList()) }
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) {
val referencedMember = expression.mainReference.resolve() as? KtNamedDeclaration ?: return
@@ -328,7 +328,7 @@ class KotlinPullUpHelper(
}
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 currentSpecifier = data.sourceClass.getSuperTypeEntryByDescriptor(classDescriptor, data.sourceClassContext) ?: return
when (data.targetClass) {
@@ -174,7 +174,7 @@ class RenameKotlinFunctionProcessor : RenameKotlinPsiProcessor() {
if (element is FunctionWithSupersWrapper) {
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
allRenames[declaration] = newName
if (psiMethod.containingClass != null) {
@@ -30,18 +30,11 @@ import org.jetbrains.kotlin.idea.util.application.runReadAction
open class KotlinDirectInheritorsSearcher() : QueryExecutorBase<PsiClass, DirectClassInheritorsSearch.SearchParameters>(true) {
override fun processQuery(queryParameters: DirectClassInheritorsSearch.SearchParameters, consumer: Processor<PsiClass>) {
val baseClass = queryParameters.classToProcess
if (baseClass == null) return
val name = baseClass.name
if (name == null) return
val name = baseClass.name ?: return
val originalScope = queryParameters.scope
val scope = if (originalScope is GlobalSearchScope)
originalScope
else
baseClass.containingFile?.let { file -> file.fileScope() }
if (scope == null) return
val scope = originalScope as? GlobalSearchScope ?: baseClass.containingFile?.fileScope() ?: return
runReadAction {
val noLibrarySourceScope = KotlinSourceFilterScope.projectSourceAndClassFiles(scope, baseClass.project)
@@ -825,7 +825,7 @@ class DefaultExpressionConverter : JavaElementVisitor(), ExpressionConverter {
else if (specialMethod != null) {
val factory = PsiElementFactory.SERVICE.getInstance(converter.project)
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
}
@@ -477,7 +477,7 @@ enum class SpecialMethod(val qualifiedClassName: String?, val methodName: String
private fun castQualifierToType(codeConverter: CodeConverter, qualifier: PsiExpression, type: String): TypeCastExpression? {
val convertedQualifier = codeConverter.convertExpression(qualifier)
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 newType = ClassType(referenceElement, Nullability.Default, codeConverter.settings).assignNoPrototype()
return TypeCastExpression(newType, convertedQualifier).assignNoPrototype()
@@ -191,10 +191,7 @@ class DefaultStatementConverter : JavaElementVisitor(), StatementConverter {
val blockConverted = codeConverter.convertBlock(block)
val annotations = converter.convertAnnotations(parameter)
val parameterType = parameter.type
val types = if (parameterType is PsiDisjunctionType)
parameterType.disjunctions
else
listOf(parameterType)
val types = (parameterType as? PsiDisjunctionType)?.disjunctions ?: listOf(parameterType)
for (t in types) {
val convertedType = codeConverter.typeConverter.convertType(t, Nullability.NotNull)
val convertedParameter = FunctionParameter(parameter.declarationIdentifier(),
@@ -94,7 +94,7 @@ class SwitchConverter(private val codeConverter: CodeConverter) {
}
else {
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 }
}
return if (fallsThrough) // we fall through into the next case
@@ -106,10 +106,8 @@ class FieldToPropertyProcessing(
is PsiPrefixExpression, is PsiPostfixExpression -> {
//TODO: what if it's used as value?
val operationType = if (parent is PsiPrefixExpression)
parent.operationTokenType
else
(parent as PsiPostfixExpression).operationTokenType
val operationType = (parent as? PsiPrefixExpression)?.operationTokenType
?: (parent as PsiPostfixExpression).operationTokenType
val opText = when (operationType) {
JavaTokenType.PLUSPLUS -> "+"
JavaTokenType.MINUSMINUS -> "-"