More cleanup: lift return / assignment out

This commit is contained in:
Mikhail Glukhikh
2017-07-07 13:57:36 +03:00
parent 9269de721e
commit dfe2c16bc7
116 changed files with 472 additions and 517 deletions
@@ -619,11 +619,11 @@ class MethodInliner(
}
private fun wrapException(originalException: Throwable, node: MethodNode, errorSuffix: String): RuntimeException {
if (originalException is InlineException) {
return InlineException("$errorPrefix: $errorSuffix", originalException)
return if (originalException is InlineException) {
InlineException("$errorPrefix: $errorSuffix", originalException)
}
else {
return InlineException("$errorPrefix: $errorSuffix\nCause: ${node.nodeText}", originalException)
InlineException("$errorPrefix: $errorSuffix\nCause: ${node.nodeText}", originalException)
}
}
@@ -679,11 +679,11 @@ class MethodInliner(
localReturns.add(LocalReturn(returnInsn, insertBeforeInsn, sourceValueFrame))
if (returnInsn.opcode != Opcodes.RETURN) {
if (returnInsn.opcode == Opcodes.LRETURN || returnInsn.opcode == Opcodes.DRETURN) {
returnVariableSize = 2
returnVariableSize = if (returnInsn.opcode == Opcodes.LRETURN || returnInsn.opcode == Opcodes.DRETURN) {
2
}
else {
returnVariableSize = 1
1
}
}
}
@@ -98,8 +98,8 @@ open class NestedSourceMapper(
override fun mapLineNumber(lineNumber: Int): Int {
val mappedLineNumber = visitedLines.get(lineNumber)
if (mappedLineNumber > 0) {
return mappedLineNumber
return if (mappedLineNumber > 0) {
mappedLineNumber
}
else {
val rangeForMapping =
@@ -111,7 +111,7 @@ open class NestedSourceMapper(
visitedLines.put(lineNumber, newLineNumber)
}
lastVisitedRange = rangeForMapping
return newLineNumber
newLineNumber
}
}
@@ -142,20 +142,20 @@ internal class FixStackAnalyzer(
}
override fun pop(): BasicValue {
if (extraStack.isNotEmpty()) {
return extraStack.pop()
return if (extraStack.isNotEmpty()) {
extraStack.pop()
}
else {
return super.pop()
super.pop()
}
}
override fun getStack(i: Int): BasicValue {
if (i < super.getMaxStackSize()) {
return super.getStack(i)
return if (i < super.getMaxStackSize()) {
super.getStack(i)
}
else {
return extraStack[i - maxStackSize]
extraStack[i - maxStackSize]
}
}
}
@@ -68,11 +68,11 @@ class ModuleVisibilityHelperImpl : ModuleVisibilityHelper {
private fun findModule(descriptor: DeclarationDescriptor, modules: Collection<Module>): Module? {
val sourceElement = getSourceElement(descriptor)
if (sourceElement is KotlinSourceElement) {
return modules.singleOrNull() ?: modules.firstOrNull { sourceElement.psi.containingKtFile.virtualFile.path in it.getSourceFiles() }
return if (sourceElement is KotlinSourceElement) {
modules.singleOrNull() ?: modules.firstOrNull { sourceElement.psi.containingKtFile.virtualFile.path in it.getSourceFiles() }
}
else {
return modules.firstOrNull { module ->
modules.firstOrNull { module ->
isContainedByCompiledPartOfOurModule(descriptor, File(module.getOutputDirectory())) ||
module.getFriendPaths().any { isContainedByCompiledPartOfOurModule(descriptor, File(it)) }
}
@@ -113,14 +113,14 @@ class ReplCodeAnalyzer(environment: KotlinCoreEnvironment) {
val diagnostics = trace.bindingContext.diagnostics
val hasErrors = diagnostics.any { it.severity == Severity.ERROR }
if (hasErrors) {
return if (hasErrors) {
replState.lineFailure(linePsi, codeLine)
return ReplLineAnalysisResult.WithErrors(diagnostics)
ReplLineAnalysisResult.WithErrors(diagnostics)
}
else {
val scriptDescriptor = context.scripts[linePsi.script]!!
replState.lineSuccess(linePsi, codeLine, scriptDescriptor)
return ReplLineAnalysisResult.Successful(scriptDescriptor, diagnostics)
ReplLineAnalysisResult.Successful(scriptDescriptor, diagnostics)
}
}
@@ -96,11 +96,11 @@ class ReplFromTerminal(
}
val lineResult = eval(line)
if (lineResult is ReplEvalResult.Incomplete) {
return WhatNextAfterOneLine.INCOMPLETE
return if (lineResult is ReplEvalResult.Incomplete) {
WhatNextAfterOneLine.INCOMPLETE
}
else {
return WhatNextAfterOneLine.READ_LINE
WhatNextAfterOneLine.READ_LINE
}
}
@@ -27,14 +27,14 @@ class JavaPropertyInitializerEvaluatorImpl : JavaPropertyInitializerEvaluator {
val evaluated = field.initializerValue ?: return null
val factory = ConstantValueFactory(descriptor.builtIns)
when (evaluated) {
//Note: evaluated expression may be of class that does not match field type in some cases
// tested for Int, left other checks just in case
return when (evaluated) {
//Note: evaluated expression may be of class that does not match field type in some cases
// tested for Int, left other checks just in case
is Byte, is Short, is Int, is Long -> {
return factory.createIntegerConstantValue((evaluated as Number).toLong(), descriptor.type)
factory.createIntegerConstantValue((evaluated as Number).toLong(), descriptor.type)
}
else -> {
return factory.createConstantValue(evaluated)
factory.createConstantValue(evaluated)
}
}
}
@@ -151,15 +151,13 @@ class PseudocodeVariablesData(val pseudocode: Pseudocode, private val bindingCon
val variableUseStatusData: Map<Instruction, Edges<UseControlFlowInfo>>
get() = pseudocodeVariableDataCollector.collectData(TraversalOrder.BACKWARD, UseControlFlowInfo()) {
instruction: Instruction, incomingEdgesData: Collection<UseControlFlowInfo> ->
val enterResult: UseControlFlowInfo
if (incomingEdgesData.size == 1) {
enterResult = incomingEdgesData.single()
val enterResult: UseControlFlowInfo = if (incomingEdgesData.size == 1) {
incomingEdgesData.single()
}
else {
enterResult = incomingEdgesData.fold(UseControlFlowInfo()) { result, edgeData ->
edgeData.iterator().fold(result) {
subResult, (variableDescriptor, variableUseState) ->
incomingEdgesData.fold(UseControlFlowInfo()) { result, edgeData ->
edgeData.iterator().fold(result) { subResult, (variableDescriptor, variableUseState) ->
subResult.put(variableDescriptor, variableUseState.merge(subResult.getOrNull(variableDescriptor)))
}
}
@@ -32,22 +32,22 @@ object EditCommaSeparatedListHelper {
fun <TItem: KtElement> addItemAfter(list: KtElement, allItems: List<TItem>, item: TItem, anchor: TItem?, prefix: KtToken = KtTokens.LPAR): TItem {
assert(anchor == null || anchor.parent == list)
if (allItems.isEmpty()) {
if (list.firstChild?.node?.elementType == prefix) {
return list.addAfter(item, list.firstChild) as TItem
return if (list.firstChild?.node?.elementType == prefix) {
list.addAfter(item, list.firstChild) as TItem
}
else {
return list.add(item) as TItem
list.add(item) as TItem
}
}
else {
var comma = KtPsiFactory(list).createComma()
if (anchor != null) {
return if (anchor != null) {
comma = list.addAfter(comma, anchor)
return list.addAfter(item, comma) as TItem
list.addAfter(item, comma) as TItem
}
else {
comma = list.addBefore(comma, allItems.first())
return list.addBefore(item, comma) as TItem
list.addBefore(item, comma) as TItem
}
}
}
@@ -55,18 +55,18 @@ object EditCommaSeparatedListHelper {
@JvmOverloads
fun <TItem: KtElement> addItemBefore(list: KtElement, allItems: List<TItem>, item: TItem, anchor: TItem?, prefix: KtToken = KtTokens.LPAR): TItem {
val anchorAfter: TItem?
if (allItems.isEmpty()) {
anchorAfter = if (allItems.isEmpty()) {
assert(anchor == null)
anchorAfter = null
null
}
else {
if (anchor != null) {
val index = allItems.indexOf(anchor)
assert(index >= 0)
anchorAfter = if (index > 0) allItems[index - 1] else null
if (index > 0) allItems[index - 1] else null
}
else {
anchorAfter = allItems[allItems.size - 1]
allItems[allItems.size - 1]
}
}
return addItemAfter(list, allItems, item, anchorAfter, prefix)
@@ -43,15 +43,15 @@ class KtObjectDeclaration : KtClassOrObject {
}
override fun setName(@NonNls name: String): PsiElement {
if (nameIdentifier == null) {
return if (nameIdentifier == null) {
val psiFactory = KtPsiFactory(project)
val result = addAfter(psiFactory.createIdentifier(name), getObjectKeyword()!!)
addAfter(psiFactory.createWhiteSpace(), getObjectKeyword()!!)
return result
result
}
else {
return super.setName(name)
super.setName(name)
}
}
@@ -660,13 +660,13 @@ class KtPsiFactory @JvmOverloads constructor(private val project: Project, val m
assert(name != CONSTRUCTOR_NAME || target == Target.CONSTRUCTOR)
sb.append(name)
when (target) {
state = when (target) {
Target.FUNCTION, Target.CONSTRUCTOR -> {
sb.append("(")
state = State.FIRST_PARAM
State.FIRST_PARAM
}
else ->
state = State.TYPE_CONSTRAINTS
State.TYPE_CONSTRAINTS
}
return this
@@ -41,12 +41,12 @@ class KtTypeAlias : KtTypeParameterListOwnerStub<KotlinTypeAliasStub>, KtNamedDe
@IfNotParsed
fun getTypeReference(): KtTypeReference? {
if (stub != null) {
return if (stub != null) {
val typeReferences = getStubOrPsiChildrenAsList<KtTypeReference, KotlinPlaceHolderStub<KtTypeReference>>(KtStubElementTypes.TYPE_REFERENCE)
return typeReferences[0]
typeReferences[0]
}
else {
return findChildByType(KtNodeTypes.TYPE_REFERENCE)
findChildByType(KtNodeTypes.TYPE_REFERENCE)
}
}
@@ -34,8 +34,8 @@ fun getTypeReference(declaration: KtCallableDeclaration): KtTypeReference? {
fun setTypeReference(declaration: KtCallableDeclaration, addAfter: PsiElement?, typeRef: KtTypeReference?): KtTypeReference? {
val oldTypeRef = getTypeReference(declaration)
if (typeRef != null) {
if (oldTypeRef != null) {
return oldTypeRef.replace(typeRef) as KtTypeReference
return if (oldTypeRef != null) {
oldTypeRef.replace(typeRef) as KtTypeReference
}
else {
val anchor = addAfter
@@ -43,7 +43,7 @@ fun setTypeReference(declaration: KtCallableDeclaration, addAfter: PsiElement?,
?: (declaration as? KtParameter)?.destructuringDeclaration
val newTypeRef = declaration.addAfter(typeRef, anchor) as KtTypeReference
declaration.addAfter(KtPsiFactory(declaration.project).createColon(), anchor)
return newTypeRef
newTypeRef
}
}
else {
@@ -49,10 +49,7 @@ fun PsiElement.siblings(forward: Boolean = true, withItself: Boolean = true): Se
override fun hasNext(): Boolean = next != null
override fun next(): PsiElement {
val result = next ?: throw NoSuchElementException()
if (forward)
next = result.nextSibling
else
next = result.prevSibling
next = if (forward) result.nextSibling else result.prevSibling
return result
}
}
@@ -347,7 +347,7 @@ class FunctionDescriptorResolver(
}
}
else {
if (isFunctionLiteral(functionDescriptor) || isFunctionExpression(functionDescriptor)) {
type = if (isFunctionLiteral(functionDescriptor) || isFunctionExpression(functionDescriptor)) {
val containsUninferredParameter = TypeUtils.contains(expectedType) {
TypeUtils.isDontCarePlaceholder(it) || ErrorUtils.isUninferredParameter(it)
}
@@ -355,11 +355,11 @@ class FunctionDescriptorResolver(
trace.report(CANNOT_INFER_PARAMETER_TYPE.on(valueParameter))
}
type = expectedType ?: TypeUtils.CANT_INFER_FUNCTION_PARAM_TYPE
expectedType ?: TypeUtils.CANT_INFER_FUNCTION_PARAM_TYPE
}
else {
trace.report(VALUE_PARAMETER_WITH_NO_TYPE_ANNOTATION.on(valueParameter))
type = ErrorUtils.createErrorType("Type annotation was missing for parameter ${valueParameter.nameAsSafeName}")
ErrorUtils.createErrorType("Type annotation was missing for parameter ${valueParameter.nameAsSafeName}")
}
}
@@ -44,11 +44,11 @@ data class ImportPath @JvmOverloads constructor(val fqName: FqName, val isAllUnd
companion object {
@JvmStatic fun fromString(pathStr: String): ImportPath {
if (pathStr.endsWith(".*")) {
return ImportPath(FqName(pathStr.substring(0, pathStr.length - 2)), isAllUnder = true)
return if (pathStr.endsWith(".*")) {
ImportPath(FqName(pathStr.substring(0, pathStr.length - 2)), isAllUnder = true)
}
else {
return ImportPath(FqName(pathStr), isAllUnder = false)
ImportPath(FqName(pathStr), isAllUnder = false)
}
}
@@ -199,11 +199,11 @@ object ModifierCheckerCore {
private fun deprecationRegister(vararg list: KtModifierKeywordToken) = compatibilityRegister(Compatibility.DEPRECATED, *list)
private fun compatibility(first: KtModifierKeywordToken, second: KtModifierKeywordToken): Compatibility {
if (first == second) {
return Compatibility.REPEATED
return if (first == second) {
Compatibility.REPEATED
}
else {
return mutualCompatibility[Pair(first, second)] ?: Compatibility.COMPATIBLE
mutualCompatibility[Pair(first, second)] ?: Compatibility.COMPATIBLE
}
}
@@ -799,11 +799,11 @@ class OverrideResolver(
val substitutedSuperReturnType = typeSubstitutor.substitute(superDescriptor.type, Variance.OUT_VARIANCE)!!
if (superDescriptor.isVar) {
return KotlinTypeChecker.DEFAULT.equalTypes(subDescriptor.type, substitutedSuperReturnType)
return if (superDescriptor.isVar) {
KotlinTypeChecker.DEFAULT.equalTypes(subDescriptor.type, substitutedSuperReturnType)
}
else {
return KotlinTypeChecker.DEFAULT.isSubtypeOf(subDescriptor.type, substitutedSuperReturnType)
KotlinTypeChecker.DEFAULT.isSubtypeOf(subDescriptor.type, substitutedSuperReturnType)
}
}
@@ -211,12 +211,7 @@ internal class DelegatingDataFlowInfo private constructor(
while (current != null) {
if (current is DelegatingDataFlowInfo) {
types.addAll(current.typeInfo.get(value))
if (value == current.valueWithGivenTypeInfo) {
current = null
}
else {
current = current.parent
}
current = if (value == current.valueWithGivenTypeInfo) null else current.parent
}
else {
types.addAll(current.getCollectedTypes(value))
@@ -262,11 +262,11 @@ class BindingContextSuppressCache(val context: BindingContext) : KotlinSuppressC
override fun getSuppressionAnnotations(annotated: KtAnnotated): List<AnnotationDescriptor> {
val descriptor = context.get(BindingContext.DECLARATION_TO_DESCRIPTOR, annotated)
if (descriptor != null) {
return descriptor.annotations.toList()
return if (descriptor != null) {
descriptor.annotations.toList()
}
else {
return annotated.annotationEntries.mapNotNull { context.get(BindingContext.ANNOTATION, it) }
annotated.annotationEntries.mapNotNull { context.get(BindingContext.ANNOTATION, it) }
}
}
}
@@ -119,11 +119,11 @@ internal class FunctionsTypingVisitor(facade: ExpressionTypingInternals) : Expre
components.identifierChecker.checkDeclaration(function, context.trace)
components.declarationsCheckerBuilder.withTrace(context.trace).checkFunction(function, functionDescriptor)
if (isDeclaration) {
return createTypeInfo(components.dataFlowAnalyzer.checkStatementType(function, context), context)
return if (isDeclaration) {
createTypeInfo(components.dataFlowAnalyzer.checkStatementType(function, context), context)
}
else {
return components.dataFlowAnalyzer.createCheckedTypeInfo(functionDescriptor.createFunctionType(), context, function)
components.dataFlowAnalyzer.createCheckedTypeInfo(functionDescriptor.createFunctionType(), context, function)
}
}
@@ -344,11 +344,11 @@ class PatternMatchingTypingVisitor internal constructor(facade: ExpressionTyping
val typeReference = condition.typeReference
if (typeReference != null) {
val result = checkTypeForIs(context, condition, condition.isNegated, subjectType, typeReference, subjectDataFlowValue)
if (condition.isNegated) {
newDataFlowInfo = ConditionalDataFlowInfo(result.elseInfo, result.thenInfo)
newDataFlowInfo = if (condition.isNegated) {
ConditionalDataFlowInfo(result.elseInfo, result.thenInfo)
}
else {
newDataFlowInfo = result
result
}
val rhsType = context.trace[BindingContext.TYPE, typeReference]
if (subjectExpression != null) {
@@ -49,11 +49,11 @@ fun resolveUnqualifiedSuperFromExpressionContext(
val calleeExpression = selectorExpression.calleeExpression
if (calleeExpression is KtSimpleNameExpression) {
val calleeName = calleeExpression.getReferencedNameAsName()
if (isCallingMethodOfAny(selectorExpression, calleeName)) {
return resolveSupertypesForMethodOfAny(supertypes, calleeName, anyType)
return if (isCallingMethodOfAny(selectorExpression, calleeName)) {
resolveSupertypesForMethodOfAny(supertypes, calleeName, anyType)
}
else {
return resolveSupertypesByCalleeName(supertypes, calleeName)
resolveSupertypesByCalleeName(supertypes, calleeName)
}
}
}
@@ -31,11 +31,11 @@ protected constructor(
fun get(): R {
val cached = cached.get() ?: return update()
val (app, extensions) = cached
if (app == ApplicationManager.getApplication()) {
return extensions
return if (app == ApplicationManager.getApplication()) {
extensions
}
else {
return update()
update()
}
}
@@ -903,11 +903,11 @@ class ExpressionCodegen(
}
if (descriptor is CallableMemberDescriptor && JvmCodegenUtil.getDirectMember(descriptor) is SyntheticJavaPropertyDescriptor) {
val propertyDescriptor = JvmCodegenUtil.getDirectMember(descriptor) as SyntheticJavaPropertyDescriptor
if (descriptor is PropertyGetterDescriptor) {
descriptor = propertyDescriptor.getMethod
descriptor = if (descriptor is PropertyGetterDescriptor) {
propertyDescriptor.getMethod
}
else {
descriptor = propertyDescriptor.setMethod!!
propertyDescriptor.setMethod!!
}
}
return typeMapper.mapToCallableMethod(descriptor as FunctionDescriptor, isSuper)
@@ -935,11 +935,11 @@ class ExpressionCodegen(
if (!isInline) return IrCallGenerator.DefaultCallGenerator
val original = unwrapInitialSignatureDescriptor(DescriptorUtils.unwrapFakeOverride(descriptor.original as FunctionDescriptor))
if (isDefaultCompilation) {
return TODO()
return if (isDefaultCompilation) {
TODO()
}
else {
return IrInlineCodegen(this, state, original, typeParameterMappings!!, IrSourceCompilerForInline(state, element))
IrInlineCodegen(this, state, original, typeParameterMappings!!, IrSourceCompilerForInline(state, element))
}
}
@@ -412,11 +412,11 @@ class EnumClassLowering(val context: JvmBackendContext) : ClassLoweringPass {
override fun visitGetValue(expression: IrGetValue): IrExpression {
val loweredParameter = loweredEnumConstructorParameters[expression.descriptor]
if (loweredParameter != null) {
return IrGetValueImpl(expression.startOffset, expression.endOffset, loweredParameter, expression.origin)
return if (loweredParameter != null) {
IrGetValueImpl(expression.startOffset, expression.endOffset, loweredParameter, expression.origin)
}
else {
return expression
expression
}
}
@@ -205,12 +205,12 @@ private fun tryToResolveInner(name: String,
private fun KtFile.tryToResolvePackageClass(name: String,
javac: JavacWrapper,
nameParts: List<String> = emptyList()): JavaClass? {
if (nameParts.size > 1) {
return find(FqName("${packageFqName.asString()}.${nameParts.first()}"), javac, nameParts)
return if (nameParts.size > 1) {
find(FqName("${packageFqName.asString()}.${nameParts.first()}"), javac, nameParts)
}
else {
return javac.findClass(FqName("${packageFqName.asString()}.$name"))
?: javac.getKotlinClassifier(FqName("${packageFqName.asString()}.$name"))
javac.findClass(FqName("${packageFqName.asString()}.$name"))
?: javac.getKotlinClassifier(FqName("${packageFqName.asString()}.$name"))
}
}
@@ -277,13 +277,12 @@ abstract class KtLightClassForSourceDeclaration(protected val classOrObject: KtC
override fun isInheritor(baseClass: PsiClass, checkDeep: Boolean): Boolean {
LightClassInheritanceHelper.getService(project).isInheritor(this, baseClass, checkDeep).ifSure { return it }
val qualifiedName: String?
if (baseClass is KtLightClassForSourceDeclaration) {
val qualifiedName: String? = if (baseClass is KtLightClassForSourceDeclaration) {
val baseDescriptor = baseClass.getDescriptor()
qualifiedName = if (baseDescriptor != null) DescriptorUtils.getFqName(baseDescriptor).asString() else null
if (baseDescriptor != null) DescriptorUtils.getFqName(baseDescriptor).asString() else null
}
else {
qualifiedName = baseClass.qualifiedName
baseClass.qualifiedName
}
val thisDescriptor = getDescriptor()
@@ -112,13 +112,9 @@ sealed class KtLightFieldImpl<D : PsiField>(
KtLightFieldImpl<PsiField>(origin, computeDelegate, containingClass, dummyDelegate)
companion object Factory {
fun create(origin: LightMemberOrigin?, delegate: PsiField, containingClass: KtLightClass): KtLightField {
when (delegate) {
is PsiEnumConstant -> {
return KtLightEnumConstant(origin, { delegate }, containingClass, null)
}
else -> return KtLightFieldForDeclaration(origin, { delegate }, containingClass, null)
}
fun create(origin: LightMemberOrigin?, delegate: PsiField, containingClass: KtLightClass): KtLightField = when (delegate) {
is PsiEnumConstant -> KtLightEnumConstant(origin, { delegate }, containingClass, null)
else -> KtLightFieldForDeclaration(origin, { delegate }, containingClass, null)
}
fun lazy(
@@ -167,22 +167,22 @@ fun <C : Candidate> createCallTowerProcessorForExplicitInvoke(
): ScopeTowerProcessor<C> {
val invokeExtensionDescriptor = scopeTower.getExtensionInvokeCandidateDescriptor(expressionForInvoke)
if (explicitReceiver != null) {
if (invokeExtensionDescriptor == null) {
return if (invokeExtensionDescriptor == null) {
// case 1.(foo())(), where foo() isn't extension function
return KnownResultProcessor(emptyList())
KnownResultProcessor(emptyList())
}
else {
return InvokeExtensionScopeTowerProcessor(functionContext, invokeExtensionDescriptor, explicitReceiver = explicitReceiver)
InvokeExtensionScopeTowerProcessor(functionContext, invokeExtensionDescriptor, explicitReceiver = explicitReceiver)
}
}
else {
val usualInvoke = ExplicitReceiverScopeTowerProcessor(scopeTower, functionContext, expressionForInvoke) { getFunctions(OperatorNameConventions.INVOKE, it) } // todo operator
if (invokeExtensionDescriptor == null) {
return usualInvoke
return if (invokeExtensionDescriptor == null) {
usualInvoke
}
else {
return CompositeScopeTowerProcessor(
CompositeScopeTowerProcessor(
usualInvoke,
InvokeExtensionScopeTowerProcessor(functionContext, invokeExtensionDescriptor, explicitReceiver = null)
)