From 8792825de46e10a32bdea55cb0dcbe3c1e8f6ff3 Mon Sep 17 00:00:00 2001 From: Ilya Muradyan Date: Tue, 3 Mar 2026 01:07:58 +0000 Subject: [PATCH] [scripts] KTNB-1391, KTNB-819, KTIJ-37776 Choose KtBlockExpression as a container for top-level script declarations We had all top-level refactoring-generated declarations inserted into KtScript element. However, the contract is that all declarations should be inserted into its child, KtBlockExpression. Merge-request: IJ-MR-193891 Merged-by: Ilya Muradyan (cherry picked from commit f4a388dc736bd8bb4396520124b27f34999aab8c) IJ-MR-194486 GitOrigin-RevId: 53cf4675dcdd6401f53b8903b05d21218348c6ff --- .../idea/refactoring/kotlinCommonRefactoringUtil.kt | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/plugins/kotlin/refactorings/kotlin.refactorings.common/src/org/jetbrains/kotlin/idea/refactoring/kotlinCommonRefactoringUtil.kt b/plugins/kotlin/refactorings/kotlin.refactorings.common/src/org/jetbrains/kotlin/idea/refactoring/kotlinCommonRefactoringUtil.kt index 2593e7088e58..5ee60fb31c7e 100644 --- a/plugins/kotlin/refactorings/kotlin.refactorings.common/src/org/jetbrains/kotlin/idea/refactoring/kotlinCommonRefactoringUtil.kt +++ b/plugins/kotlin/refactorings/kotlin.refactorings.common/src/org/jetbrains/kotlin/idea/refactoring/kotlinCommonRefactoringUtil.kt @@ -86,6 +86,7 @@ import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf import org.jetbrains.kotlin.psi.psiUtil.quoteIfNeeded import org.jetbrains.kotlin.psi.psiUtil.siblings import org.jetbrains.kotlin.psi.unpackFunctionLiteral +import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull import java.util.Collections import kotlin.math.min @@ -412,7 +413,16 @@ fun PsiElement.getExtractionContainers(strict: Boolean = true, includeAll: Boole return when (enclosingDeclaration) { is KtFile -> Collections.singletonList(enclosingDeclaration) - is KtScript -> Collections.singletonList(enclosingDeclaration) + is KtScript -> { + /** + * [KtScript] element is essentially a class, so it should always have + * a single child, which is a [KtBlockExpression]. Inserting an element as an immediate child + * of the [KtScript] element is a mistake. + */ + Collections.singletonList( + enclosingDeclaration.children.firstIsInstanceOrNull() ?: enclosingDeclaration + ) + } is KtClassBody -> getAllExtractionContainers(strict).filterIsInstance() else -> { val targetContainer = when (enclosingDeclaration) {