New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Added rule UnnecessaryInnerClass #4394
Merged
chao2zhang
merged 8 commits into
detekt:main
from
severn-everett:unnecessary_inner_class
Jan 23, 2022
Merged
Changes from 6 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
5367532
Added rule UnnecessaryInnerClass
severn-everett ca4c17e
Addressed Detekt issues; Added test case
severn-everett d60b718
Removed unnecessary code
severn-everett 5b16163
Addressing PR comment
severn-everett d12d4e9
Enabled rule for self-tests on the Detekt library
severn-everett 7ff4813
Fixing inner class issue in CognitiveComplexity
severn-everett 3306f4f
Merge branch 'master' into unnecessary_inner_class
severn-everett 1ce0a2d
Updated code comment
severn-everett File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
170 changes: 170 additions & 0 deletions
170
...es-style/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/style/UnnecessaryInnerClass.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,170 @@ | ||
package io.gitlab.arturbosch.detekt.rules.style | ||
|
||
import io.gitlab.arturbosch.detekt.api.CodeSmell | ||
import io.gitlab.arturbosch.detekt.api.Config | ||
import io.gitlab.arturbosch.detekt.api.Debt | ||
import io.gitlab.arturbosch.detekt.api.Entity | ||
import io.gitlab.arturbosch.detekt.api.Issue | ||
import io.gitlab.arturbosch.detekt.api.Rule | ||
import io.gitlab.arturbosch.detekt.api.Severity | ||
import io.gitlab.arturbosch.detekt.api.internal.RequiresTypeResolution | ||
import org.jetbrains.kotlin.backend.common.peek | ||
import org.jetbrains.kotlin.backend.common.pop | ||
import org.jetbrains.kotlin.descriptors.ClassifierDescriptor | ||
import org.jetbrains.kotlin.name.ClassId | ||
import org.jetbrains.kotlin.psi.KtBinaryExpression | ||
import org.jetbrains.kotlin.psi.KtCallExpression | ||
import org.jetbrains.kotlin.psi.KtClass | ||
import org.jetbrains.kotlin.psi.KtDotQualifiedExpression | ||
import org.jetbrains.kotlin.psi.KtElement | ||
import org.jetbrains.kotlin.psi.KtFile | ||
import org.jetbrains.kotlin.psi.KtIfExpression | ||
import org.jetbrains.kotlin.psi.KtNamedFunction | ||
import org.jetbrains.kotlin.psi.KtParameter | ||
import org.jetbrains.kotlin.psi.KtProperty | ||
import org.jetbrains.kotlin.psi.KtReferenceExpression | ||
import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType | ||
import org.jetbrains.kotlin.psi.psiUtil.containingClass | ||
import org.jetbrains.kotlin.resolve.BindingContext | ||
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall | ||
import org.jetbrains.kotlin.resolve.descriptorUtil.classId | ||
|
||
/** | ||
* This rule reports unnecessary inner classes. Nested classes that do not access members from the outer class do | ||
* not require the `inner` qualifier. | ||
* | ||
* <noncompliant> | ||
* class A { | ||
* val foo = "BAR" | ||
* | ||
* inner class B { | ||
* val fizz = "BUZZ" | ||
* | ||
* fun printFizz() { | ||
* println(fizz) | ||
* } | ||
* } | ||
* } | ||
* </noncompliant> | ||
*/ | ||
@Suppress("TooManyFunctions") | ||
@RequiresTypeResolution | ||
class UnnecessaryInnerClass(config: Config = Config.empty) : Rule(config) { | ||
|
||
private val candidateClasses = mutableMapOf<KtClass, Set<ClassId>>() | ||
private val classChain = ArrayDeque<KtClass>() | ||
|
||
override val issue: Issue = Issue( | ||
javaClass.simpleName, | ||
Severity.Style, | ||
"The 'inner' qualifier is unnecessary.", | ||
Debt.FIVE_MINS | ||
) | ||
|
||
override fun visit(root: KtFile) { | ||
if (bindingContext == BindingContext.EMPTY) return | ||
super.visit(root) | ||
} | ||
|
||
override fun visitClass(klass: KtClass) { | ||
classChain.add(klass) | ||
if (klass.isInner()) { | ||
candidateClasses[klass] = buildParentClassChain(klass) | ||
} | ||
|
||
// Visit the class to determine whether it contains any references | ||
// to outer class members. | ||
super.visitClass(klass) | ||
|
||
if (candidateClasses.contains(klass)) { | ||
report( | ||
CodeSmell( | ||
issue, | ||
Entity.Companion.from(klass), | ||
"Class '${klass.name}' does not require `inner` keyword." | ||
) | ||
) | ||
candidateClasses.remove(klass) | ||
} | ||
classChain.pop() | ||
} | ||
|
||
override fun visitProperty(property: KtProperty) { | ||
super.visitProperty(property) | ||
checkForOuterUsage { parentClasses -> | ||
property.initializer.belongsToParentClass(parentClasses) | ||
} | ||
} | ||
|
||
override fun visitNamedFunction(function: KtNamedFunction) { | ||
super.visitNamedFunction(function) | ||
checkForOuterUsage { parentClasses -> | ||
function.initializer.belongsToParentClass(parentClasses) | ||
} | ||
} | ||
|
||
override fun visitCallExpression(expression: KtCallExpression) { | ||
super.visitCallExpression(expression) | ||
checkForOuterUsage { parentClasses -> | ||
expression.belongsToParentClass(parentClasses) || | ||
expression.collectDescendantsOfType<KtReferenceExpression> { | ||
it.belongsToParentClass(parentClasses) | ||
}.isNotEmpty() | ||
} | ||
} | ||
|
||
override fun visitParameter(parameter: KtParameter) { | ||
super.visitParameter(parameter) | ||
checkForOuterUsage { parentClasses -> | ||
parameter.defaultValue.belongsToParentClass(parentClasses) | ||
} | ||
} | ||
|
||
override fun visitBinaryExpression(expression: KtBinaryExpression) { | ||
super.visitBinaryExpression(expression) | ||
checkForOuterUsage { parentClasses -> | ||
expression.left.belongsToParentClass(parentClasses) || | ||
expression.right.belongsToParentClass(parentClasses) | ||
} | ||
} | ||
|
||
override fun visitIfExpression(expression: KtIfExpression) { | ||
super.visitIfExpression(expression) | ||
checkForOuterUsage { parentClasses -> | ||
val condition = expression.condition | ||
condition is KtReferenceExpression && condition.belongsToParentClass(parentClasses) | ||
} | ||
} | ||
|
||
override fun visitDotQualifiedExpression(expression: KtDotQualifiedExpression) { | ||
super.visitDotQualifiedExpression(expression) | ||
checkForOuterUsage { parentClasses -> | ||
expression.receiverExpression.belongsToParentClass(parentClasses) | ||
} | ||
} | ||
|
||
// Replace this "contructor().apply{}" pattern with buildSet() when Kotlin is upgraded to 1.6 | ||
private fun buildParentClassChain(klass: KtClass) = HashSet<ClassId>().apply { | ||
var containingClass = klass.containingClass() | ||
while (containingClass != null) { | ||
containingClass.getClassId()?.let { add(it) } | ||
containingClass = containingClass.containingClass() | ||
} | ||
} | ||
|
||
private fun checkForOuterUsage(checkBlock: (Set<ClassId>) -> Boolean) { | ||
val containingClass = classChain.peek() ?: return | ||
val parentClasses = candidateClasses[containingClass] ?: return | ||
if (checkBlock.invoke(parentClasses)) { | ||
candidateClasses.remove(containingClass) | ||
} | ||
} | ||
|
||
private fun KtElement?.belongsToParentClass(parentClasses: Set<ClassId>): Boolean { | ||
return this?.getResolvedCall(bindingContext) | ||
?.resultingDescriptor | ||
?.containingDeclaration | ||
?.let { (it as? ClassifierDescriptor)?.classId } | ||
?.let(parentClasses::contains) == true | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can we replace it now? #4277
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeah, I'll swing back and fix this tomorrow.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It doesn't look like it's available until the API version is at 1.6; I'll update the note to reflect that