JVM IR: add jvmLocalClassExtractionPhase to lift out local classes from initializers
Otherwise a local class in a field initializer or anonymous init block is copied into each constructor of the containing class (because InitializersLowering calls deepCopy). Since the code structure no longer resembles the original source code here, record a custom EnclosingMethod mapping before moving such classes, and use it in codegen.
This commit is contained in:
+15
-6
@@ -1,8 +1,14 @@
|
||||
/*
|
||||
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
|
||||
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
|
||||
*/
|
||||
|
||||
package org.jetbrains.kotlin.backend.common.lower
|
||||
|
||||
import org.jetbrains.kotlin.backend.common.BackendContext
|
||||
import org.jetbrains.kotlin.backend.common.FileLoweringPass
|
||||
import org.jetbrains.kotlin.backend.common.IrElementTransformerVoidWithContext
|
||||
import org.jetbrains.kotlin.backend.common.ScopeWithIr
|
||||
import org.jetbrains.kotlin.backend.common.ir.addChild
|
||||
import org.jetbrains.kotlin.ir.IrStatement
|
||||
import org.jetbrains.kotlin.ir.declarations.IrClass
|
||||
@@ -12,8 +18,7 @@ import org.jetbrains.kotlin.ir.declarations.IrScript
|
||||
import org.jetbrains.kotlin.ir.expressions.impl.IrCompositeImpl
|
||||
|
||||
//This lower takes part of old LocalDeclarationLowering job to pop up local classes from functions
|
||||
class LocalClassPopupLowering(val context: BackendContext) : FileLoweringPass {
|
||||
|
||||
open class LocalClassPopupLowering(val context: BackendContext) : FileLoweringPass {
|
||||
override fun lower(irFile: IrFile) {
|
||||
val extractedLocalClasses = arrayListOf<Pair<IrClass, IrDeclarationContainer>>()
|
||||
|
||||
@@ -21,9 +26,10 @@ class LocalClassPopupLowering(val context: BackendContext) : FileLoweringPass {
|
||||
|
||||
override fun visitClassNew(declaration: IrClass): IrStatement {
|
||||
val newDeclaration = super.visitClassNew(declaration)
|
||||
if (newDeclaration !is IrClass || !newDeclaration.isLocalNotInner()) {
|
||||
return newDeclaration
|
||||
}
|
||||
if (newDeclaration !is IrClass) return newDeclaration
|
||||
|
||||
val currentScope = allScopes[allScopes.lastIndex - 1]
|
||||
if (!shouldPopUp(declaration, currentScope)) return newDeclaration
|
||||
|
||||
val newContainer = allScopes.asReversed().drop(1/*skip self*/).firstOrNull {
|
||||
//find first class local or not;
|
||||
@@ -39,4 +45,7 @@ class LocalClassPopupLowering(val context: BackendContext) : FileLoweringPass {
|
||||
newContainer.addChild(local)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected open fun shouldPopUp(klass: IrClass, currentScope: ScopeWithIr?): Boolean =
|
||||
klass.isLocalNotInner()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user