KT-38831 Use safe casts in ReplaceWithOperatorAssignmentInspection

- Assigned expression can change between reporting of inspection and
applying it
- ^KT-38831 Fixed
This commit is contained in:
Roman Golyshev
2020-05-09 05:21:35 +03:00
committed by Roman Golyshev
parent 225d354604
commit 150708069c
@@ -50,7 +50,7 @@ class ReplaceWithOperatorAssignmentInspection : AbstractApplicabilityBasedInspec
if (!checkExpressionRepeat(left, right, bindingContext)) return false if (!checkExpressionRepeat(left, right, bindingContext)) return false
// now check that the resulting operator assignment will be resolved // now check that the resulting operator assignment will be resolved
val opAssign = buildOperatorAssignment(element) val opAssign = buildOperatorAssignment(element) ?: return false
opAssign.containingKtFile.doNotAnalyze = null //TODO: strange hack opAssign.containingKtFile.doNotAnalyze = null //TODO: strange hack
val newBindingContext = opAssign.analyzeAsReplacement(element, bindingContext) val newBindingContext = opAssign.analyzeAsReplacement(element, bindingContext)
return newBindingContext.diagnostics.forElement(opAssign.operationReference).isEmpty() return newBindingContext.diagnostics.forElement(opAssign.operationReference).isEmpty()
@@ -119,15 +119,15 @@ class ReplaceWithOperatorAssignmentInspection : AbstractApplicabilityBasedInspec
operationToken == KtTokens.PERC operationToken == KtTokens.PERC
override fun applyTo(element: KtBinaryExpression, project: Project, editor: Editor?) { override fun applyTo(element: KtBinaryExpression, project: Project, editor: Editor?) {
element.replace(buildOperatorAssignment(element)) val operatorAssignment = buildOperatorAssignment(element) ?: return
element.replace(operatorAssignment)
} }
private fun buildOperatorAssignment(element: KtBinaryExpression): KtBinaryExpression { private fun buildOperatorAssignment(element: KtBinaryExpression): KtBinaryExpression? {
val replacement = buildOperatorAssignmentText( val variableExpression = element.left as? KtNameReferenceExpression ?: return null
element.left as KtNameReferenceExpression, val assignedExpression = element.right as? KtBinaryExpression ?: return null
element.right as KtBinaryExpression,
"" val replacement = buildOperatorAssignmentText(variableExpression, assignedExpression, "")
)
return KtPsiFactory(element).createExpression(replacement) as KtBinaryExpression return KtPsiFactory(element).createExpression(replacement) as KtBinaryExpression
} }