Refactoring: Unnecessary variable inspection

This commit is contained in:
Mikhail Glukhikh
2017-11-23 16:11:13 +03:00
committed by Mikhail Glukhikh
parent 52053695fe
commit 844dd1c43c
@@ -67,30 +67,29 @@ class UnnecessaryVariableInspection : AbstractKotlinInspection() {
val enclosingElement = KtPsiUtil.getEnclosingElementForLocalDeclaration(property) ?: return null
val initializer = property.initializer ?: return null
if (!property.isVar && initializer is KtNameReferenceExpression && property.typeReference == null) {
val context = property.analyze()
val initializerDescriptor = context[REFERENCE_TARGET, initializer]
if (initializerDescriptor is VariableDescriptor) {
if (!initializerDescriptor.isVar && initializerDescriptor.containingDeclaration is FunctionDescriptor) {
if (ReferencesSearch.search(property, LocalSearchScope(enclosingElement)).findFirst() != null) {
return Status.EXACT_COPY
}
}
fun isExactCopy(): Boolean {
if (!property.isVar && initializer is KtNameReferenceExpression && property.typeReference == null) {
val context = property.analyze()
val initializerDescriptor = context[REFERENCE_TARGET, initializer] as? VariableDescriptor ?: return false
if (initializerDescriptor.isVar) return false
if (initializerDescriptor.containingDeclaration !is FunctionDescriptor) return false
return ReferencesSearch.search(property, LocalSearchScope(enclosingElement)).findFirst() != null
}
return false
}
val nextStatement = property.getNextSiblingIgnoringWhitespaceAndComments()
if (nextStatement is KtReturnExpression) {
val returned = nextStatement.returnedExpression
if (returned is KtNameReferenceExpression) {
val context = nextStatement.analyze()
if (context[REFERENCE_TARGET, returned] == context[DECLARATION_TO_DESCRIPTOR, property]) {
return Status.RETURN_ONLY
}
}
fun isReturnOnly(): Boolean {
val nextStatement = property.getNextSiblingIgnoringWhitespaceAndComments() as? KtReturnExpression ?: return false
val returned = nextStatement.returnedExpression as? KtNameReferenceExpression ?: return false
val context = nextStatement.analyze()
return context[REFERENCE_TARGET, returned] == context[DECLARATION_TO_DESCRIPTOR, property]
}
return null
return when {
isExactCopy() -> Status.EXACT_COPY
isReturnOnly() -> Status.RETURN_ONLY
else -> null
}
}
fun isActiveFor(property: KtProperty) = statusFor(property) != null