[extract method] prepare analyzer to be reused, simplify error handling

GitOrigin-RevId: 26054522329a8a1a4d84997fb39b957707de9737
This commit is contained in:
Alexandr Suhinin
2024-07-31 14:26:46 +00:00
committed by intellij-monorepo-bot
parent b46466d5b3
commit e18fb1db28
2 changed files with 28 additions and 16 deletions
@@ -269,5 +269,14 @@ class CodeFragmentAnalyzer(val elements: List<PsiElement>) {
val artificialExpression = requireNotNull(artificialReturn.returnValue)
return inferNullability(listOf(artificialExpression))
}
fun createAnalyzer(elements: List<PsiElement>): CodeFragmentAnalyzer? {
return try {
CodeFragmentAnalyzer(elements)
}
catch (e: ExtractException) {
null
}
}
}
}
@@ -60,24 +60,27 @@ class MethodExtractor {
return
}
val elements = ExtractSelector().suggestElementsToExtract(file, range)
if (elements.isEmpty()) {
showExtractErrorHint(editor, RefactoringBundle.message("selected.block.should.represent.a.set.of.statements.or.an.expression"))
return
}
try {
val analyzer = CodeFragmentAnalyzer(elements)
val outputVariables = analyzer.findOutputVariables().sortedBy { variable -> variable.textRange.startOffset }
if (outputVariables.size > 1) {
ResultObjectExtractor.run(editor, outputVariables, elements)
return
}
} catch (_: ExtractException) {
}
coroutineScope.launch {
withContext(Dispatchers.EDT) { //TODO minimize edt context
val elements = ExtractSelector().suggestElementsToExtract(file, range)
if (elements.isEmpty()) {
showExtractErrorHint(editor, RefactoringBundle.message("selected.block.should.represent.a.set.of.statements.or.an.expression"))
return@withContext
}
val analyzer = CodeFragmentAnalyzer.createAnalyzer(elements)
if (analyzer == null) {
showExtractErrorHint(editor, JavaRefactoringBundle.message("extract.method.control.flow.analysis.failed"))
return@withContext
}
val outputVariables = analyzer.findOutputVariables().sortedBy { variable -> variable.textRange.startOffset }
if (outputVariables.size > 1) {
ResultObjectExtractor.run(editor, outputVariables, elements)
return@withContext
}
val prepareStart = System.currentTimeMillis()
val descriptorsForAllTargetPlaces = prepareDescriptorsForAllTargetPlaces(file.project, editor, elements)
if (descriptorsForAllTargetPlaces.isEmpty()) return@withContext