rem-command-line 0.1.0

CLI interface for the REM toolchain. Built to be implemented into the VSCode extension for REM
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
/*
 * Use of this source code is governed by the MIT license that can be
 * found in the LICENSE file.
 */

package org.rust.ide.refactoring.extractFunction

import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiParserFacade
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.elementType
import com.intellij.refactoring.RefactoringActionHandler
import com.intellij.refactoring.RefactoringBundle
import com.intellij.usageView.UsageInfo
import org.rust.ide.presentation.PsiRenderingOptions
import org.rust.ide.presentation.RsPsiRenderer
import org.rust.ide.presentation.renderTypeReference
import org.rust.ide.refactoring.RsRenameProcessor
import org.rust.ide.utils.GenericConstraints
import org.rust.ide.utils.import.RsImportHelper.importTypeReferencesFromTys
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.*
import org.rust.lang.core.psi.impl.RsMethodCallImpl
import org.rust.lang.core.psi.impl.RsFunctionImpl
import org.rust.lang.core.psi.impl.*
import org.rust.lang.core.resolve.RsCachedImplItem
import org.rust.lang.core.types.*
import org.rust.lang.core.types.ty.*
import org.rust.openapiext.runWriteCommandAction
import org.apache.commons.io.IOUtils
import java.io.File
import java.util.concurrent.TimeUnit

class RsExtractFunctionHandler : RefactoringActionHandler {
    override fun invoke(project: Project, elements: Array<out PsiElement>, dataContext: DataContext?) {
        //this doesn't get called from the editor.
    }

    override fun invoke(project: Project, editor: Editor?, file: PsiFile?, dataContext: DataContext?) {
        if (file !is RsFile) return
        val start = editor?.selectionModel?.selectionStart
        val end = editor?.selectionModel?.selectionEnd
        if (start === null || end === null) return
        val config = RsExtractFunctionConfig.create(file, start, end) ?: return
        extractFunctionDialog(project, config) {
            dump: Boolean ->
            extractFunction(project, file, config, dump)
        }
    }

    private fun extractFunction(project: Project, file: PsiFile, config: RsExtractFunctionConfig, dump: Boolean) {
        project.runWriteCommandAction(
            RefactoringBundle.message("extract.method.title"),
            file
        ) {
            val psiFactory = RsPsiFactory(project)
            val extractedFunction = addExtractedFunction(project, config, psiFactory) ?: return@runWriteCommandAction
            replaceOldStatementsWithCallExpr(config, psiFactory)
            val parameters = config.valueParameters.filter { it.isSelected }
            renameFunctionParameters(extractedFunction, parameters.map { it.name })
            val types = (parameters.map { it.type } + config.returnValue?.type).filterNotNull()
            importTypeReferencesFromTys(extractedFunction, types)
            if (dump) {
                if (dumpMethodCallTypes(project, extractedFunction, file, dump)) {
                    LOG.info("dumped call types completed successfully")
                }
            } else {
                if (dumpMethodCallTypes(project, extractedFunction, file, dump)) {
                    LOG.info("dumped call types completed successfully")
                    if (nonLocalController(project, config, file)){
                        LOG.info("controller completed successfully")
                        if (borrow(project, config, file)) {
                            LOG.info("borrow completed successfully")
                            if (repairLifetime(config, file, project, psiFactory)){
                                LOG.info("repairer completed successfully")
                            }
                        }
                    }
                }
            }
        }
    }

    private fun execAndGetVal(cmd: Array<String>) : Int {
        val proc = Runtime.getRuntime().exec(cmd)
        val stderr_r = proc.errorStream.bufferedReader()
        val stdout_r = proc.inputStream.bufferedReader()
        val stderr_reader = Thread {
            try {
                var tmp : String? = stderr_r.readLine()
                while (tmp != null) {
                    LOG.info("STDERR>$tmp")
                    tmp = stderr_r.readLine()
                }
            } catch (e : Exception) {
            }
        }

        val stdout_reader = Thread {
            try {
                var tmp : String? = stdout_r.readLine()
                while (tmp != null) {
                    LOG.info("STDOUT>$tmp")
                    tmp = stdout_r.readLine()
                }
            } catch (e : Exception) {
            }
        }
        stderr_reader.start()
        stdout_reader.start()
        proc.waitFor(5, TimeUnit.MINUTES)
        stderr_reader.join()
        stdout_reader.join()
        return proc.exitValue()
    }

    private fun failRepair(backupFile: String, filePath: String) {
        val newFileTxt = File(filePath).readText(Charsets.UTF_8)
        LOG.info("at failure: $newFileTxt")
        val cmd = arrayOf("cp", filePath, "/tmp/debug-repair")
        val proc = Runtime.getRuntime().exec(cmd)
        proc.waitFor(5, TimeUnit.MINUTES)
        val cmd2 = arrayOf("cp", backupFile, filePath)
        val proc2 = Runtime.getRuntime().exec(cmd2)
        proc2.waitFor(5, TimeUnit.MINUTES)
    }

    private fun dumpMethodCallTypes(project: Project, extractFn: RsFunction, file: PsiFile, dump: Boolean) : Boolean {
        val fileParent = file.getContainingDirectory().getVirtualFile().getPath()
        val fileName = file.name
        val filePath = "$fileParent/$fileName"
        LOG.info("file path: $filePath")

        var bak = "/tmp/${fileName}-ij-extract.bk"
        if (dump) {
            bak = "${filePath}_ORIGINAL"
        }

        execAndGetVal(arrayOf("cp", filePath, bak))

        var dumpFileName = "/tmp/method_call_mutability.txt"
        if (dump) {
            dumpFileName = "${filePath}_MUTABLE_METHOD_CALLS"
        }

        val dumpFile = File(dumpFileName)
        dumpFile.writeText("")
        val begin = System.currentTimeMillis()
        val visitor = object : RsVisitor() {
            override fun visitElement(o: RsElement) {
                o.acceptChildren(this)
            }

            override fun visitBlock(o: RsBlock) {
                LOG.debug("elem: ${o.text}")
                LOG.debug("elem type: $o")
                for (stmt in o.getStmtList()) {
                    stmt.acceptChildren(this)
                }
            }

            override fun visitDotExpr(o: RsDotExpr) {
                LOG.debug("dot expr: ${o.text}")
                super.visitDotExpr(o)
                val methodCall = o.getMethodCall()
                val inferred = methodCall?.inference?.getResolvedMethodType(methodCall)

                val selfTy = inferred?.paramTypes?.get(0)
                if (selfTy != null && selfTy is TyReference) {
                    if (selfTy.mutability.isMut) {
                        dumpFile.appendText("${o.text}\n")
                    }
                }
            }
        }
        try {
            extractFn.acceptChildren(visitor)
            val end = System.currentTimeMillis()
            LOG.info("dump method call elapsed time in milliseconds success: ${end?.minus(begin)}")
        } catch (e: Exception) {
            val end = System.currentTimeMillis()
            LOG.info("dump method call elapsed time in milliseconds failure: ${end?.minus(begin)}")
            LOG.error("dump method call failed: $e")
            if (!dump) {
                extractionFailed(project) {
                    failRepair(bak, filePath)
                }
            }
            return false
        }
        return true
    }

    private fun nonLocalController(project: Project, config: RsExtractFunctionConfig, file: PsiFile) : Boolean {
        val name = config.name
        val parentFn = config.function
        val fileParent = file.getContainingDirectory().getVirtualFile().getPath()
        val fileName = file.name
        val filePath = "$fileParent/$fileName"
        LOG.info("file path: $filePath")

        val bak = "/tmp/${fileName}-ij-extract.bk"
        val cmd1 = arrayOf("cp", filePath, bak)
        val proc1 = Runtime.getRuntime().exec(cmd1)
        proc1.waitFor(5, TimeUnit.MINUTES)

        //write the extracted fn
        File(filePath).writeText(file.text)

        var success = false
        val cmd : Array<String> = arrayOf("controller", "run", filePath, filePath, parentFn!!.name!!, name)
        var end : Long? = null
        val begin = System.currentTimeMillis()
        try {
            val exitValue = execAndGetVal(cmd)
            end = System.currentTimeMillis()
            LOG.info("exit val $exitValue")
            if (exitValue == 0) {
                LOG.info("nclf elapsed time in milliseconds success: ${end?.minus(begin)}")
                success = true
            }
        } catch (e: Exception) {
            end = System.currentTimeMillis()
            LOG.info("exception $e")
            LOG.info("nclf elapsed time in milliseconds failure: ${end?.minus(begin)}")
        } finally {
            VfsUtil.markDirtyAndRefresh(false, true, true, file.getVirtualFile())
            if (!success) {
                LOG.info("bad exit val restoring file")
                LOG.info("nclf elapsed time in milliseconds failure: ${end?.minus(begin)}")
                extractionFailed(project) {
                    failRepair(bak, filePath)
                }
            }
            return success
        }
    }

    private fun borrow(project: Project, config: RsExtractFunctionConfig, file: PsiFile) : Boolean {
        val name = config.name
        val parentFn = config.function
        val fileParent = file.getContainingDirectory().getVirtualFile().getPath()
        val fileName = file.name
        val filePath = "$fileParent/$fileName"
        LOG.info("file path: $filePath")

        val bak = "/tmp/${fileName}-ij-extract.bk"

        val dumpFileName = "/tmp/method_call_mutability.txt"

        val cmd : Array<String> = arrayOf("borrower", "run", filePath, filePath, dumpFileName, parentFn!!.name!!, name!!, bak)
        var success = false
        val begin = System.currentTimeMillis()
        var end: Long? = null
        try {
            val exitValue = execAndGetVal(cmd)
            end = System.currentTimeMillis()
            LOG.info("exit val $exitValue")
            if (exitValue == 0) {
                success = true
                LOG.info("borrow elapsed time in milliseconds success: ${end?.minus(begin)}")
            }
        } catch (e: Exception) {
            end = System.currentTimeMillis()
            LOG.info("exception $e")
            LOG.info("borrow elapsed time in milliseconds failure: ${end?.minus(begin)}")
        } finally {
            VfsUtil.markDirtyAndRefresh(false, true, true, file.getVirtualFile())
            if (!success) {
                LOG.info("bad exit val restoring file")
                LOG.info("borrow elapsed time in milliseconds failure: ${end?.minus(begin)}")
                extractionFailed(project) {
                    failRepair(bak, filePath)
                }
            }
            return success
        }
    }

    private fun repairLifetimeUsingRustc(config: RsExtractFunctionConfig, file: PsiFile, psiFactory: RsPsiFactory) : Boolean {

        val name = config.name
        val parentFnName = config.function.identifier.text
        LOG.info("parent fn name: $parentFnName, name: $name")
        var parentFn : RsFunction? = null


        val fileParent = file.getContainingDirectory().getVirtualFile().getPath()
        val filePath = "$fileParent/${file.name}"

        val fileAfterBorrowTxt = File(filePath).readText(Charsets.UTF_8)
        val fileAfterBorrow = psiFactory.createPsiFile(fileAfterBorrowTxt)
        var newFn : RsFunction? = null
        val initVisitor = object : RsVisitor() {
            override fun visitFunction(fn: RsFunction) {
                super.visitFunction(fn)
                LOG.info("found fn: ${fn.identifier.text}")
                if (fn.identifier.text == name){
                    newFn = fn
                }

                if (fn.identifier.text == parentFnName){
                    parentFn = fn
                }
            }
        }
        fileAfterBorrow.acceptChildren(initVisitor)

        if (parentFn == null || newFn == null) {
            LOG.info("rustc repair failure--did not run cannot find caller and callee fn")
            return false
        }

        val fnTxt = "#[allow(dead_code)]\n${parentFn!!.text}\n${newFn!!.text}"
        val fileName = "/tmp/pre_repair_extract.rs"
        val newFileName = "/tmp/post_repair_extract.rs"
        val mainTxt = "\nfn main() {}"
        File(fileName).writeText("$fnTxt$mainTxt")
        var end : Long? = null
        var success = false
        val cmd : Array<String> = arrayOf("repairer", "run", name, fileName, newFileName, "loosest-bounds-first")
        val begin = System.currentTimeMillis()
        try {
            val exitValue = execAndGetVal(cmd)
            end = System.currentTimeMillis()
            LOG.info("exit val $exitValue")
            if (exitValue == 0) {
                val newFileTxt = File(newFileName).readText(Charsets.UTF_8)
                val newFile = psiFactory.createPsiFile(newFileTxt)
                val visitor = object : RsVisitor() {
                    override fun visitFunction(fn: RsFunction) {
                        super.visitFunction(fn)
                        LOG.info("found fn: ${fn.identifier.text}")
                        if (fn.identifier.text == name){
                            LOG.info("set new fn: ${fn.identifier.text}")
                            newFn!!.replace(fn)
                        }

                        if (fn.identifier.text == parentFnName){
                            LOG.info("set new parent fn: ${fn.identifier.text}")
                            parentFn!!.replace(fn)
                        }
                    }
                }
                newFile.acceptChildren(visitor)
                success = true
                LOG.info("repair elapsed time in milliseconds rustc success: ${end?.minus(begin)}")
                File(filePath).writeText("${fileAfterBorrow.text}")
            } else {
                LOG.info("repair elapsed time in milliseconds rustc failure: ${end?.minus(begin)}")
            }
        } catch (e: Exception) {
            end = System.currentTimeMillis()
            LOG.info("exception $e")
            LOG.info("repair rustc elapsed time in milliseconds failure: ${end?.minus(begin)}")
        } finally {
            return success
        }
    }

    private fun repairLifetimeUsingCargo(config: RsExtractFunctionConfig, file: PsiFile, project: Project) : Boolean {
        val name = config.name
        val fileParent = file.getContainingDirectory().getVirtualFile().getPath()
        val fileName = file.name
        val filePath = "$fileParent/$fileName"
        LOG.info("file path: $filePath")

        val bak = "/tmp/${fileName}-ij-extract.bk"

        val baseDir = project.getBaseDir().getPath()

        // base manifest path too long compile time
        // val herePath = project.getBaseDir().getPath()
        // val manifestPath = "$herePath/Cargo.toml"
        var here = file.getContainingDirectory()
        while (here.findFile("Cargo.toml") == null && here.getVirtualFile().getPath() != baseDir) {
            here = here.getParentDirectory()
        }
        var revert = true
        if (here.findFile("Cargo.toml") == null) {
            noLifetimeFixMode(project, "No Cargo manifest file was found (we looked recursively until $baseDir), so no Cargo repair was done.  Do you want to proceed with possibly incorrect lifetimes?") {
                revert = false
            }
            if (revert) {
                failRepair(bak, filePath)
            }
            return false
        }
        val herePath = here.getVirtualFile().getPath()
        val manifestPath = "$herePath/Cargo.toml"
        LOG.info("manifest: $manifestPath")
        val cmd : Array<String> = arrayOf("repairer", "cargo", filePath, manifestPath, name, "loosest-bounds-first")
        var success = false
        var end : Long? = null
        val begin = System.currentTimeMillis()
        try {
            val exitValue = execAndGetVal(cmd)
            end = System.currentTimeMillis()

            LOG.info("exit val $exitValue")
            if (exitValue == 0) {
                success = true
                LOG.info("repair elapsed time in milliseconds cargo success: ${end?.minus(begin)}")
            }
        } catch (e: Exception) {
            end = System.currentTimeMillis()
            LOG.info("exception $e")
            LOG.info("repair cargo elapsed time in milliseconds failure: ${end?.minus(begin)}")
        } finally {
            VfsUtil.markDirtyAndRefresh(false, true, true, file.getVirtualFile())
            if (!success) {
                LOG.info("bad exit val restoring file")
                LOG.info("repair elapsed time in milliseconds cargo failure: ${end?.minus(begin)}")
                noLifetimeFixMode(project, "Lifetime repairs using Cargo has failed.  Do you want to proceed with possibly incorrect lifetimes?") {
                    revert = false
                }
                if (revert) {
                    failRepair(bak, filePath)
                }
            }
            return success
        }
    }

    private fun repairLifetime(config: RsExtractFunctionConfig, file: PsiFile, project: Project, psiFactory: RsPsiFactory) : Boolean {
        val fileParent = file.getContainingDirectory().getVirtualFile().getPath()
        val fileName = file.name
        val filePath = "$fileParent/$fileName"
        LOG.info("file path: $filePath")

        var cargoSuccess = false

        // if (repairLifetimeUsingRustc(config, file, psiFactory)) {
        //     LOG.info("lifetime repair using rustc succeeded")
        //     LOG.info("running cargo anyways for testing timing")
        //     repairLifetimeUsingCargo(config, file, project)
        // } else {
        //     cargoMode(project) {
        //         cargoSuccess = repairLifetimeUsingCargo(config, file, project)
        //     }
        // }
        cargoSuccess = repairLifetimeUsingCargo(config, file, project)
        return cargoSuccess
    }

    private fun addExtractedFunction(
        project: Project,
        config: RsExtractFunctionConfig,
        psiFactory: RsPsiFactory
    ): RsFunction? {
        val owner = config.function.owner
        val function = psiFactory.createFunction(config.functionText)
        val psiParserFacade = PsiParserFacade.getInstance(project)
        return when {
            owner is RsAbstractableOwner.Impl && !owner.isInherent -> {
                val impl = findExistingInherentImpl(owner.impl) ?: createNewInherentImpl(owner.impl) ?: return null
                val members = impl.members ?: return null
                members.addBefore(psiParserFacade.createWhiteSpaceFromText("\n\n"), members.rbrace)
                members.addBefore(function, members.rbrace) as? RsFunction
            }
            else -> {
                val newline = psiParserFacade.createWhiteSpaceFromText("\n\n")
                val end = config.function.block?.rbrace ?: return null
                config.function.addAfter(function, config.function.addAfter(newline, end)) as? RsFunction
            }
        }
    }

    /**
     * Finds inherent impl corresponding to [traitImpl].
     * Impls at same tree level are checked (e.g. if [traitImpl] is top-level impl, then top-level impls are checked).
     */
    private fun findExistingInherentImpl(traitImpl: RsImplItem): RsImplItem? {
        check(traitImpl.traitRef != null)
        val cachedTraitImpl = RsCachedImplItem.forImpl(traitImpl)
        return (traitImpl.parent as? RsItemsOwner)
            ?.childrenOfType<RsImplItem>()
            ?.firstOrNull { impl ->
                val cachedImpl = RsCachedImplItem.forImpl(impl)
                val (_, generics, constGenerics) = cachedImpl.typeAndGenerics ?: return@firstOrNull false
                cachedImpl.isInherent && cachedImpl.isValid && !cachedImpl.isNegativeImpl
                    && generics.isEmpty() && constGenerics.isEmpty()  // TODO: Support generics
                    && cachedImpl.typeAndGenerics == cachedTraitImpl.typeAndGenerics
            }
    }

    private fun createNewInherentImpl(traitImpl: RsImplItem): RsImplItem? {
        val parent = traitImpl.parent
        val psiFactory = RsPsiFactory(parent.project)

        val typeReference = traitImpl.typeReference!!
        val constraints = GenericConstraints.create(traitImpl).filterByTypeReferences(listOf(typeReference))

        val renderer = RsPsiRenderer(PsiRenderingOptions())

        val typeParameters = constraints.buildTypeParameters()
        val typeText = renderer.renderTypeReference(typeReference)
        val whereClause = constraints.buildWhereClause()

        val text = "impl$typeParameters $typeText $whereClause{}"
        val newImpl = psiFactory.tryCreateImplItem(text) ?: return null

        val newImplCopy = parent.addAfter(newImpl, traitImpl) as RsImplItem
        parent.addBefore(psiFactory.createWhitespace("\n\n"), newImplCopy)
        return newImplCopy
    }

    /**
     * Original function signature and body are inserted at first.
     * Then it is necessary to change the names of original parameters to the real (renamed) parameters' names.
     */
    private fun renameFunctionParameters(function: RsFunction, newNames: List<String>) {
        val parameters = function.rawValueParameters
            .map { it.pat }
            .filterIsInstance(RsPatIdent::class.java)
            .map { it.patBinding }

        for ((parameter, newName) in parameters.zip(newNames)) {
            if (newName != parameter.name) {
                val parameterUsages = ReferencesSearch.search(parameter, LocalSearchScope(function)).findAll()
                val usageInfo = parameterUsages.map { UsageInfo(it) }.toTypedArray()
                RsRenameProcessor().renameElement(parameter, newName, usageInfo, null)
            }
        }
    }

    private fun replaceOldStatementsWithCallExpr(config: RsExtractFunctionConfig, psiFactory: RsPsiFactory) {
        val stmt = StringBuilder()
        if (config.returnValue?.exprText != null) {
            stmt.append("let mut ${config.returnValue.exprText} = ")
        }
        val firstParameter = config.parameters.firstOrNull()
        stmt.append(if (firstParameter != null && firstParameter.isSelf) {
            "self.${config.name}(${config.argumentsText})"
        } else {
            val type = when (config.function.owner) {
                is RsAbstractableOwner.Impl,
                is RsAbstractableOwner.Trait -> "Self"
                else -> null
            }
            "${if (type != null) "$type::" else ""}${config.name}(${config.argumentsText})"
        })
        if (config.isAsync) {
            stmt.append(".await")
        }
        config.elements.forEachIndexed { index, psiElement ->
            if (index == config.elements.lastIndex) {
                when (psiElement) {
                    is RsExpr -> psiElement.replace(psiFactory.createExpression(stmt.toString()))
                    is RsExprStmt -> {
                        val needsSemicolon = config.returnValue == null || config.returnValue.exprText != null
                        if (needsSemicolon) {
                            stmt.append(";")
                        }
                        psiElement.replace(psiFactory.createStatement(stmt.toString()))
                    }
                    is RsStmt -> {
                        stmt.append(";")
                        psiElement.replace(psiFactory.createStatement(stmt.toString()))
                    }
                }
            } else {
                psiElement.delete()
            }
        }
    }

    companion object {
        val LOG: Logger = logger<RsExtractFunctionHandler>()
    }
}