Code cleanup: unnecessary local variable applied

This commit is contained in:
Mikhail Glukhikh
2017-07-20 16:10:35 +03:00
parent 202fb19cf6
commit 951e8cd91a
57 changed files with 118 additions and 203 deletions
@@ -94,8 +94,7 @@ class JvmStaticInCompanionObjectGenerator(
CallableMemberDescriptor.Kind.SYNTHESIZED,
false
)
val staticFunctionDescriptor = copies[descriptor]!!
return staticFunctionDescriptor
return copies[descriptor]!!
}
}
}
@@ -111,12 +111,11 @@ class CoroutineTransformerMethodVisitor(
methodNode.instructions.apply {
val startLabel = LabelNode()
val defaultLabel = LabelNode()
val firstToInsertBefore = actualCoroutineStart
val tableSwitchLabel = LabelNode()
val lineNumber = CodegenUtil.getLineNumberForElement(element, false) ?: 0
// tableswitch(this.label)
insertBefore(firstToInsertBefore,
insertBefore(actualCoroutineStart,
insnListOf(
*withInstructionAdapter { loadCoroutineSuspendedMarker() }.toArray(),
tableSwitchLabel,
@@ -144,7 +144,7 @@ internal fun performRefinedTypeAnalysis(methodNode: MethodNode, thisName: String
}
})
val refinedFrames = Array(basicFrames.size) {
return Array(basicFrames.size) {
insnIndex ->
val current = Frame(basicFrames[insnIndex] ?: return@Array null)
@@ -158,8 +158,6 @@ internal fun performRefinedTypeAnalysis(methodNode: MethodNode, thisName: String
current
}
return refinedFrames
}
private fun AbstractInsnNode.isIntLoad() = opcode == Opcodes.ILOAD
@@ -716,10 +716,9 @@ class MethodInliner(
"Captured field template should start with $CAPTURED_FIELD_FOLD_PREFIX prefix"
}
val fin = FieldInsnNode(node.opcode, node.owner, node.name.substring(3), node.desc)
val field = fieldRemapper.findField(fin) ?: throw IllegalStateException(
return fieldRemapper.findField(fin) ?: throw IllegalStateException(
"Couldn't find captured field ${node.owner}.${node.name} in ${fieldRemapper.originalLambdaInternalName}"
)
return field
}
private fun analyzeMethodNodeWithoutMandatoryTransformations(node: MethodNode): Array<Frame<SourceValue>?> {
@@ -169,8 +169,7 @@ class PsiSourceCompilerForInline(private val codegen: ExpressionCodegen, overrid
val strategy = when (expression) {
is KtCallableReferenceExpression -> {
val callableReferenceExpression = expression
val receiverExpression = callableReferenceExpression.receiverExpression
val receiverExpression = expression.receiverExpression
val receiverType = if (receiverExpression != null && state.bindingContext.getType(receiverExpression) != null)
state.typeMapper.mapType(state.bindingContext.getType(receiverExpression)!!)
else
@@ -187,7 +186,7 @@ class PsiSourceCompilerForInline(private val codegen: ExpressionCodegen, overrid
FunctionReferenceGenerationStrategy(
state,
descriptor,
callableReferenceExpression.callableReference
expression.callableReference
.getResolvedCallWithAssert(state.bindingContext),
receiverType, null,
true
@@ -286,9 +286,8 @@ internal fun getMarkedReturnLabelOrNull(returnInsn: AbstractInsnNode): String? {
}
val previous = returnInsn.previous
if (previous is MethodInsnNode) {
val marker = previous
if (NON_LOCAL_RETURN == marker.owner) {
return marker.name
if (NON_LOCAL_RETURN == previous.owner) {
return previous.name
}
}
return null
@@ -457,13 +456,12 @@ private fun isInlineMarker(insn: AbstractInsnNode, name: String?): Boolean {
return false
}
val methodInsnNode = insn
return insn.getOpcode() == Opcodes.INVOKESTATIC &&
methodInsnNode.owner == INLINE_MARKER_CLASS_NAME &&
insn.owner == INLINE_MARKER_CLASS_NAME &&
if (name != null)
methodInsnNode.name == name
insn.name == name
else
methodInsnNode.name == INLINE_MARKER_BEFORE_METHOD_NAME || methodInsnNode.name == INLINE_MARKER_AFTER_METHOD_NAME
insn.name == INLINE_MARKER_BEFORE_METHOD_NAME || insn.name == INLINE_MARKER_AFTER_METHOD_NAME
}
internal fun isBeforeInlineMarker(insn: AbstractInsnNode): Boolean {
@@ -232,17 +232,15 @@ class CapturedVarsOptimizationMethodTransformer : MethodTransformer() {
}
private fun findCleanInstructions(refValue: CapturedVarDescriptor, oldVarIndex: Int, instructions: InsnList): List<VarInsnNode> {
val cleanInstructions =
InsnSequence(instructions).filterIsInstance<VarInsnNode>().filter {
it.opcode == Opcodes.ASTORE && it.`var` == oldVarIndex
}.filter {
it.previous?.opcode == Opcodes.ACONST_NULL
}.filter {
val operationIndex = instructions.indexOf(it)
val localVariableNode = refValue.localVar!!
instructions.indexOf(localVariableNode.start) < operationIndex && operationIndex < instructions.indexOf(localVariableNode.end)
}.toList()
return cleanInstructions
return InsnSequence(instructions).filterIsInstance<VarInsnNode>().filter {
it.opcode == Opcodes.ASTORE && it.`var` == oldVarIndex
}.filter {
it.previous?.opcode == Opcodes.ACONST_NULL
}.filter {
val operationIndex = instructions.indexOf(it)
val localVariableNode = refValue.localVar!!
instructions.indexOf(localVariableNode.start) < operationIndex && operationIndex < instructions.indexOf(localVariableNode.end)
}.toList()
}
private fun rewrite() {
@@ -59,14 +59,13 @@ abstract class KotlinJsr223JvmScriptEngineBase(protected val myFactory: ScriptEn
val codeLine = nextCodeLine(context, script)
val state = getCurrentState(context)
val result = replEvaluator.compileAndEval(state, codeLine, scriptArgs = overrideScriptArgs(context))
val ret = when (result) {
return when (result) {
is ReplEvalResult.ValueResult -> result.value
is ReplEvalResult.UnitResult -> null
is ReplEvalResult.Error -> throw ScriptException(result.message)
is ReplEvalResult.Incomplete -> throw ScriptException("error: incomplete code")
is ReplEvalResult.HistoryMismatch -> throw ScriptException("Repl history mismatch at line: ${result.lineNo}")
}
return ret
}
open fun compile(script: String, context: ScriptContext): CompiledScript {
@@ -91,14 +90,13 @@ abstract class KotlinJsr223JvmScriptEngineBase(protected val myFactory: ScriptEn
throw ScriptException(e)
}
val ret = when (result) {
return when (result) {
is ReplEvalResult.ValueResult -> result.value
is ReplEvalResult.UnitResult -> null
is ReplEvalResult.Error -> throw ScriptException(result.message)
is ReplEvalResult.Incomplete -> throw ScriptException("error: incomplete code")
is ReplEvalResult.HistoryMismatch -> throw ScriptException("Repl history mismatch at line: ${result.lineNo}")
}
return ret
}
class CompiledKotlinScript(val engine: KotlinJsr223JvmScriptEngineBase, val codeLine: ReplCodeLine, val compiledData: ReplCompileResult.CompiledClasses) : CompiledScript() {
@@ -44,8 +44,7 @@ class KtNameReferenceExpression : KtExpressionImplStub<KotlinNameReferenceExpres
}
override fun getReferencedNameElement(): PsiElement {
val element = findChildByType<PsiElement>(NAME_REFERENCE_EXPRESSIONS) ?: return this
return element
return findChildByType(NAME_REFERENCE_EXPRESSIONS) ?: this
}
override fun getIdentifier(): PsiElement? {
@@ -274,9 +274,7 @@ class KtPsiFactory @JvmOverloads constructor(private val project: Project, val m
val file = createFile(text)
val declarations = file.declarations
assert(declarations.size == 1) { "${declarations.size} declarations in $text" }
@Suppress("UNCHECKED_CAST")
val result = declarations.first() as TDeclaration
return result
return declarations.first() as TDeclaration
}
fun createNameIdentifier(name: String): PsiElement {
@@ -108,11 +108,10 @@ fun KtSimpleNameExpression.getReceiverExpression(): KtExpression? {
}
parent is KtCallExpression -> {
//This is in case `a().b()`
val callExpression = parent
val grandParent = callExpression.parent
val grandParent = parent.parent
if (grandParent is KtQualifiedExpression) {
val parentsReceiver = grandParent.receiverExpression
if (parentsReceiver != callExpression) {
if (parentsReceiver != parent) {
return parentsReceiver
}
}
@@ -44,7 +44,6 @@ import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.expressions.DataFlowAnalyzer
import java.util.*
import kotlin.collections.HashMap
class KotlinToResolvedCallTransformer(
@@ -112,7 +111,7 @@ class KotlinToResolvedCallTransformer(
return this
}
val resolvedCall = when (completedCall) {
return when (completedCall) {
is CompletedKotlinCall.Simple -> {
NewResolvedCallImpl<D>(completedCall).runIfTraceNotNull(this::bindResolvedCall).runIfTraceNotNull(this::runArgumentsChecks)
}
@@ -127,8 +126,6 @@ class KotlinToResolvedCallTransformer(
(resolvedCall as ResolvedCall<D>)
}
}
return resolvedCall
}
private fun runCallCheckers(resolvedCall: ResolvedCall<*>, callCheckerContext: CallCheckerContext) {
@@ -333,8 +330,7 @@ sealed class NewAbstractResolvedCall<D : CallableDescriptor>(): ResolvedCall<D>
if (argumentToParameterMap == null) {
argumentToParameterMap = argumentToParameterMap(resultingDescriptor, valueArguments)
}
val argumentMatch = argumentToParameterMap!![valueArgument] ?: return ArgumentUnmapped
return argumentMatch
return argumentToParameterMap!![valueArgument] ?: ArgumentUnmapped
}
override fun getDataFlowInfoForArguments() = object : DataFlowInfoForArguments {
@@ -463,11 +463,10 @@ class PSICallResolver(
val newDataFlowInfo = (lhsResult as? DoubleColonLHS.Expression)?.dataFlowInfo ?: startDataFlowInfo
// todo ChosenCallableReferenceDescriptor
val argument = CallableReferenceKotlinCallArgumentImpl(valueArgument, startDataFlowInfo, newDataFlowInfo,
ktExpression, argumentName, (lhsResult as? DoubleColonLHS.Type)?.type?.unwrap(),
ConstraintStorage.Empty) // todo
return argument
return CallableReferenceKotlinCallArgumentImpl(valueArgument, startDataFlowInfo, newDataFlowInfo,
ktExpression, argumentName, (lhsResult as? DoubleColonLHS.Type)?.type?.unwrap(),
ConstraintStorage.Empty)
}
// valueArgument.getArgumentExpression()!! instead of ktExpression is hack -- type info should be stored also for parenthesized expression
@@ -161,10 +161,9 @@ class PatternMatchingTypingVisitor internal constructor(facade: ExpressionTyping
private fun wrapWhenEntryExpressionsAsSpecialCallArguments(expression: KtWhenExpression): List<KtExpression> {
val psiFactory = KtPsiFactory(expression)
val wrappedArgumentExpressions = expression.entries.mapNotNull { whenEntry ->
return expression.entries.mapNotNull { whenEntry ->
whenEntry.expression?.let { psiFactory.wrapInABlockWrapper(it) }
}
return wrappedArgumentExpressions
}
private fun analyzeConditionsInWhenEntries(
@@ -126,9 +126,7 @@ class LocalFunctionsLowering(val context: BackendContext): DeclarationContainerL
val newCallee = localFunctionData.transformedDescriptor
val newCall = createNewCall(expression, newCallee).fillArguments(localFunctionData, expression)
return newCall
return createNewCall(expression, newCallee).fillArguments(localFunctionData, expression)
}
private fun <T : IrMemberAccessExpression> T.fillArguments(calleeContext: LocalFunctionContext, oldExpression: IrMemberAccessExpression): T {
@@ -160,15 +158,13 @@ class LocalFunctionsLowering(val context: BackendContext): DeclarationContainerL
val localFunctionData = localFunctions[oldCallee] ?: return expression
val newCallee = localFunctionData.transformedDescriptor
val newCallableReference = IrFunctionReferenceImpl(
return IrFunctionReferenceImpl(
expression.startOffset, expression.endOffset,
expression.type, // TODO functional type for transformed descriptor
newCallee,
remapTypeArguments(expression, newCallee),
expression.origin
).fillArguments(localFunctionData, expression)
return newCallableReference
}
override fun visitReturn(expression: IrReturn): IrExpression {
@@ -341,10 +341,9 @@ class ExpressionCodegen(
}
private fun findLocalIndex(descriptor: CallableDescriptor): Int {
val index = frame.getIndex(descriptor).apply {
return frame.getIndex(descriptor).apply {
if (this < 0) throw AssertionError("Non-mapped local variable descriptor: $descriptor")
}
return index
}
override fun visitGetObjectValue(expression: IrGetObjectValue, data: BlockInfo): StackValue {
@@ -453,13 +452,12 @@ class ExpressionCodegen(
}
else {
mv.iconst(size)
val asmType = elementType
newArrayInstruction(expression.type)
for ((i, element) in expression.elements.withIndex()) {
mv.dup()
StackValue.constant(i, Type.INT_TYPE).put(Type.INT_TYPE, mv)
val rightSide = gen(element, asmType, data)
StackValue.arrayElement(asmType, StackValue.onStack(asmType), StackValue.onStack(Type.INT_TYPE)).store(rightSide, mv)
val rightSide = gen(element, elementType, data)
StackValue.arrayElement(elementType, StackValue.onStack(elementType), StackValue.onStack(Type.INT_TYPE)).store(rightSide, mv)
}
}
return expression.onStack
@@ -125,14 +125,12 @@ class SpecialDescriptorsFactory(
private fun createObjectInstanceFieldDescriptor(objectDescriptor: ClassDescriptor): PropertyDescriptor {
assert(objectDescriptor.kind == ClassKind.OBJECT) { "Should be an object: $objectDescriptor" }
val instanceFieldDescriptor = PropertyDescriptorImpl.create(
return PropertyDescriptorImpl.create(
objectDescriptor,
Annotations.EMPTY, Modality.FINAL, Visibilities.PUBLIC, false,
Name.identifier("INSTANCE"),
CallableMemberDescriptor.Kind.SYNTHESIZED, SourceElement.NO_SOURCE, /* lateInit = */ false, /* isConst = */ false,
/* isHeader = */ false, /* isImpl = */ false, /* isExternal = */ false, /* isDelegated = */ false
).initialize(objectDescriptor.defaultType)
return instanceFieldDescriptor
}
}
@@ -99,11 +99,10 @@ open class IrIntrinsicFunction(
fun IrMemberAccessExpression.argTypes(context: JvmBackendContext): ArrayList<Type> {
val callableMethod = context.state.typeMapper.mapToCallableMethod(descriptor as FunctionDescriptor, false)
val args = arrayListOf<Type>().apply {
return arrayListOf<Type>().apply {
callableMethod.dispatchReceiverType?.let { add(it) }
addAll(callableMethod.getAsmMethod().argumentTypes)
}
return args
}
fun IrMemberAccessExpression.receiverAndArgs(): List<IrExpression> {
@@ -117,12 +117,11 @@ class EnumClassLowering(val context: JvmBackendContext) : ClassLoweringPass {
private fun transformEnumConstructor(enumConstructor: IrConstructor): IrConstructor {
val constructorDescriptor = enumConstructor.descriptor
val loweredConstructorDescriptor = lowerEnumConstructor(constructorDescriptor)
val loweredEnumConstructor = IrConstructorImpl(
return IrConstructorImpl(
enumConstructor.startOffset, enumConstructor.endOffset, enumConstructor.origin,
loweredConstructorDescriptor,
enumConstructor.body!! // will be transformed later
)
return loweredEnumConstructor
}
private fun lowerEnumConstructor(constructorDescriptor: ClassConstructorDescriptor): ClassConstructorDescriptor {
@@ -221,10 +220,9 @@ class EnumClassLowering(val context: JvmBackendContext) : ClassLoweringPass {
val irValuesInitializer = createSyntheticValuesFieldInitializerExpression()
val irField = IrFieldImpl(UNDEFINED_OFFSET, UNDEFINED_OFFSET, JvmLoweredDeclarationOrigin.FIELD_FOR_ENUM_VALUES,
valuesFieldDescriptor,
IrExpressionBodyImpl(UNDEFINED_OFFSET, UNDEFINED_OFFSET, irValuesInitializer))
return irField
return IrFieldImpl(UNDEFINED_OFFSET, UNDEFINED_OFFSET, JvmLoweredDeclarationOrigin.FIELD_FOR_ENUM_VALUES,
valuesFieldDescriptor,
IrExpressionBodyImpl(UNDEFINED_OFFSET, UNDEFINED_OFFSET, irValuesInitializer))
}
private fun createSyntheticValuesFieldInitializerExpression(): IrExpression =
@@ -173,13 +173,12 @@ class FunctionGenerator(declarationGenerator: DeclarationGenerator) : Declaratio
private fun generateReceiverExpressionForDefaultPropertyAccessor(ktProperty: KtElement, property: PropertyDescriptor): IrExpression? {
val containingDeclaration = property.containingDeclaration
val receiver = when (containingDeclaration) {
return when (containingDeclaration) {
is ClassDescriptor ->
IrGetValueImpl(ktProperty.startOffset, ktProperty.endOffset,
context.symbolTable.referenceValue(containingDeclaration.thisAsReceiverParameter))
else -> null
}
return receiver
}
fun generatePrimaryConstructor(
@@ -129,7 +129,6 @@ class PropertyGenerator(declarationGenerator: DeclarationGenerator) : Declaratio
private fun getPropertyDescriptor(ktProperty: KtProperty): PropertyDescriptor {
val variableDescriptor = getOrFail(BindingContext.VARIABLE, ktProperty)
val propertyDescriptor = variableDescriptor as? PropertyDescriptor ?: TODO("not a property?")
return propertyDescriptor
return variableDescriptor as? PropertyDescriptor ?: TODO("not a property?")
}
}
@@ -43,8 +43,7 @@ class SymbolTable {
unboundSymbols.remove(existing)
existing
}
val owner = createOwner(symbol)
return owner
return createOwner(symbol)
}
inline fun referenced(d: D, createSymbol: () -> S): S {
@@ -115,8 +114,7 @@ class SymbolTable {
inline fun declareLocal(d: D, createSymbol: () -> S, createOwner: (S) -> B): B {
val scope = currentScope ?: throw AssertionError("No active scope")
val symbol = scope.getLocal(d) ?: createSymbol().also { scope[d] = it }
val owner = createOwner(symbol)
return owner
return createOwner(symbol)
}
fun introduceLocal(descriptor: D, symbol: S) {