Naming convention inspections

This commit is contained in:
Dmitry Jemerov
2017-06-14 14:04:25 +02:00
parent 6a5d8dcc82
commit f7c17d6a64
29 changed files with 572 additions and 31 deletions
@@ -16,19 +16,18 @@
package org.jetbrains.kotlin.android.inspection
import com.intellij.codeInsight.FileModificationService
import com.intellij.codeInspection.*
import com.intellij.ide.DataManager
import com.intellij.codeInspection.LocalInspectionToolSession
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import com.intellij.refactoring.rename.RenameHandlerRegistry
import org.jetbrains.kotlin.android.getAndroidFacetForFile
import org.jetbrains.kotlin.idea.inspections.AbstractKotlinInspection
import org.jetbrains.kotlin.idea.quickfix.RenameIdentifierFix
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.KtPsiUtil
import org.jetbrains.kotlin.psi.KtVisitorVoid
class IllegalIdentifierInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor {
@@ -71,28 +70,4 @@ class IllegalIdentifierInspection : AbstractKotlinInspection() {
}
}
class RenameIdentifierFix : LocalQuickFix {
override fun getName() = "Rename"
override fun getFamilyName() = name
override fun startInWriteAction(): Boolean = false
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement ?: return
val file = element.containingFile ?: return
if (!FileModificationService.getInstance().prepareFileForWrite(file)) return
val editorManager = FileEditorManager.getInstance(project)
val fileEditor = editorManager.getSelectedEditor(file.virtualFile) ?: return
val dataContext = DataManager.getInstance().getDataContext(fileEditor.component)
val renameHandler = RenameHandlerRegistry.getInstance().getRenameHandler(dataContext)
val editor = editorManager.selectedTextEditor
if (editor != null) {
renameHandler?.invoke(project, editor, file, dataContext)
}
else {
renameHandler?.invoke(project, arrayOf(element.parent), dataContext)
}
}
}
}
@@ -0,0 +1,5 @@
<html>
<body>
Reports class names that do not follow the recommended naming conventions.
</body>
</html>
@@ -0,0 +1,5 @@
<html>
<body>
Reports <code>const</code> property names that do not follow the recommended naming conventions.
</body>
</html>
@@ -0,0 +1,5 @@
<html>
<body>
Reports enum entry names that do not follow the recommended naming conventions.
</body>
</html>
@@ -0,0 +1,5 @@
<html>
<body>
Reports function names that do not follow the recommended naming conventions.
</body>
</html>
@@ -0,0 +1,5 @@
<html>
<body>
Reports local variable names that do not follow the recommended naming conventions.
</body>
</html>
@@ -0,0 +1,5 @@
<html>
<body>
Reports names of properties in objects and companion objects that do not follow the recommended naming conventions.
</body>
</html>
@@ -0,0 +1,5 @@
<html>
<body>
Reports package names that do not follow the recommended naming conventions.
</body>
</html>
@@ -0,0 +1,5 @@
<html>
<body>
Reports private property names that do not follow the recommended naming conventions.
</body>
</html>
@@ -0,0 +1,5 @@
<html>
<body>
Reports property names that do not follow the recommended naming conventions.
</body>
</html>
+73
View File
@@ -2456,6 +2456,79 @@
language="kotlin"
/>
<localInspection implementationClass="org.jetbrains.kotlin.idea.inspections.ClassNameInspection"
language="kotlin"
groupPath="Kotlin"
groupName="Naming conventions"
enabledByDefault="true"
displayName="Class naming convention"
level="WEAK WARNING"/>
<localInspection implementationClass="org.jetbrains.kotlin.idea.inspections.EnumEntryNameInspection"
language="kotlin"
groupPath="Kotlin"
groupName="Naming conventions"
enabledByDefault="true"
displayName="Enum entry naming convention"
level="WEAK WARNING"/>
<localInspection implementationClass="org.jetbrains.kotlin.idea.inspections.FunctionNameInspection"
language="kotlin"
groupPath="Kotlin"
groupName="Naming conventions"
enabledByDefault="true"
displayName="Function naming convention"
level="WEAK WARNING"/>
<localInspection implementationClass="org.jetbrains.kotlin.idea.inspections.PropertyNameInspection"
language="kotlin"
groupPath="Kotlin"
groupName="Naming conventions"
enabledByDefault="true"
displayName="Property naming convention"
level="WEAK WARNING"/>
<localInspection implementationClass="org.jetbrains.kotlin.idea.inspections.ObjectPropertyNameInspection"
language="kotlin"
groupPath="Kotlin"
groupName="Naming conventions"
enabledByDefault="true"
displayName="Object property naming convention"
level="WEAK WARNING"/>
<localInspection implementationClass="org.jetbrains.kotlin.idea.inspections.PrivatePropertyNameInspection"
language="kotlin"
groupPath="Kotlin"
groupName="Naming conventions"
enabledByDefault="true"
displayName="Private property naming convention"
level="WEAK WARNING"/>
<localInspection implementationClass="org.jetbrains.kotlin.idea.inspections.ConstPropertyNameInspection"
language="kotlin"
groupPath="Kotlin"
groupName="Naming conventions"
enabledByDefault="true"
displayName="Const property naming convention"
level="WEAK WARNING"/>
<localInspection implementationClass="org.jetbrains.kotlin.idea.inspections.LocalVariableNameInspection"
language="kotlin"
groupPath="Kotlin"
groupName="Naming conventions"
enabledByDefault="true"
displayName="Local variable naming convention"
level="WEAK WARNING"/>
<localInspection implementationClass="org.jetbrains.kotlin.idea.inspections.PackageNameInspection"
language="kotlin"
groupPath="Kotlin"
groupName="Naming conventions"
enabledByDefault="true"
displayName="Package naming convention"
level="WEAK WARNING"/>
<referenceImporter implementation="org.jetbrains.kotlin.idea.quickfix.KotlinReferenceImporter"/>
<fileType.fileViewProviderFactory filetype="KJSM" implementationClass="com.intellij.psi.ClassFileViewProviderFactory"/>
@@ -0,0 +1,175 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.LocalInspectionToolSession
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.editor.event.DocumentAdapter
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.ui.LabeledComponent
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.PsiNameIdentifierOwner
import com.intellij.ui.EditorTextField
import com.siyeh.ig.psiutils.TestUtils
import org.intellij.lang.regexp.RegExpFileType
import org.jetbrains.kotlin.idea.quickfix.RenameIdentifierFix
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.visibilityModifierType
import java.awt.BorderLayout
import javax.swing.JPanel
abstract class NamingConventionInspection(private val entityName: String,
defaultNamePattern: String) : AbstractKotlinInspection() {
protected var nameRegex: Regex = defaultNamePattern.toRegex()
var namePattern: String = defaultNamePattern
set(value) {
field = value
nameRegex = value.toRegex()
}
protected fun verifyName(element: PsiNameIdentifierOwner, holder: ProblemsHolder) {
val name = element.name
val nameIdentifier = element.nameIdentifier
if (name != null && nameIdentifier != null && !nameRegex.matches(name)) {
holder.registerProblem(element.nameIdentifier!!,
"$entityName name <code>#ref</code> doesn't match regex '$namePattern' #loc",
RenameIdentifierFix())
}
}
override fun createOptionsPanel() = NamingConventionOptionsPanel(this)
}
class ClassNameInspection : NamingConventionInspection("Class", "[A-Z][A-Za-z\\d]*") {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return object : KtVisitorVoid() {
override fun visitClassOrObject(classOrObject: KtClassOrObject) {
verifyName(classOrObject, holder)
}
override fun visitEnumEntry(enumEntry: KtEnumEntry) {
// do nothing
}
}
}
}
class EnumEntryNameInspection : NamingConventionInspection("Enum entry", "[A-Z]([A-Za-z\\d]*|[A-Z_\\d]*)") {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return object : KtVisitorVoid() {
override fun visitEnumEntry(enumEntry: KtEnumEntry) {
verifyName(enumEntry, holder)
}
}
}
}
class FunctionNameInspection : NamingConventionInspection("Function", "[a-z][A-Za-z\\d]*") {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return object : KtVisitorVoid() {
override fun visitNamedFunction(function: KtNamedFunction) {
if (TestUtils.isInTestSourceContent(function) && function.nameIdentifier?.text?.startsWith("`") == true) {
return
}
verifyName(function, holder)
}
}
}
}
abstract class PropertyNameInspectionBase protected constructor(private val kind: PropertyKind,
entityName: String,
defaultNamePattern: String)
: NamingConventionInspection(entityName, defaultNamePattern) {
protected enum class PropertyKind { NORMAL, PRIVATE, OBJECT, CONST, LOCAL }
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return object : KtVisitorVoid() {
override fun visitProperty(property: KtProperty) {
if (property.getKind() == kind) {
verifyName(property, holder)
}
}
}
}
private fun KtProperty.getKind(): PropertyKind = when {
isLocal -> PropertyKind.LOCAL
containingClassOrObject is KtObjectDeclaration -> PropertyKind.OBJECT
hasModifier(KtTokens.CONST_KEYWORD) -> PropertyKind.CONST
visibilityModifierType() == KtTokens.PRIVATE_KEYWORD -> PropertyKind.PRIVATE
else -> PropertyKind.NORMAL
}
}
class PropertyNameInspection : PropertyNameInspectionBase(PropertyKind.NORMAL, "Property", "[a-z][A-Za-z\\d]*")
class ObjectPropertyNameInspection : PropertyNameInspectionBase(PropertyKind.OBJECT, "Object property", "[A-Za-z][_A-Za-z\\d]*")
class PrivatePropertyNameInspection : PropertyNameInspectionBase(PropertyKind.PRIVATE, "Private property", "_?[a-z][A-Za-z\\d]*")
class ConstPropertyNameInspection : PropertyNameInspectionBase(PropertyKind.CONST, "Const property", "[A-Z][_A-Z\\d]*")
class LocalVariableNameInspection : PropertyNameInspectionBase(PropertyKind.LOCAL, "Local variable", "[a-z][A-Za-z\\d]*")
class PackageNameInspection : NamingConventionInspection("Package", "[a-z][A-Za-z\\d\\.]*") {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor {
return object : KtVisitorVoid() {
override fun visitPackageDirective(directive: KtPackageDirective) {
val qualifiedName = directive.qualifiedName
if (qualifiedName.isNotEmpty() && !nameRegex.matches(qualifiedName)) {
holder.registerProblem(directive.packageNameExpression!!,
"Package name <code>#ref</code> doesn't match regex '$namePattern' #loc",
RenamePackageFix())
}
}
}
}
private class RenamePackageFix : RenameIdentifierFix() {
override fun getElementToRename(element: PsiElement): PsiElement? {
val packageDirective = element as? KtPackageDirective ?: return null
return JavaPsiFacade.getInstance(element.project).findPackage(packageDirective.qualifiedName)
}
}
}
class NamingConventionOptionsPanel(owner: NamingConventionInspection) : JPanel() {
init {
layout = BorderLayout()
val regexField = EditorTextField(owner.namePattern, null, RegExpFileType.INSTANCE).apply {
setOneLineMode(true)
}
regexField.document.addDocumentListener(object : DocumentAdapter() {
override fun documentChanged(e: DocumentEvent?) {
owner.namePattern = regexField.text
}
})
val labeledComponent = LabeledComponent.create(regexField, "Pattern:", BorderLayout.WEST)
add(labeledComponent, BorderLayout.NORTH)
}
}
@@ -0,0 +1,62 @@
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.FileModificationService
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.ide.DataManager
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.refactoring.RefactoringFactory
import com.intellij.refactoring.rename.RenameHandlerRegistry
open class RenameIdentifierFix : LocalQuickFix {
override fun getName() = "Rename"
override fun getFamilyName() = name
override fun startInWriteAction(): Boolean = false
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement ?: return
val file = element.containingFile ?: return
if (!FileModificationService.getInstance().prepareFileForWrite(file)) return
val editorManager = FileEditorManager.getInstance(project)
val fileEditor = editorManager.getSelectedEditor(file.virtualFile) ?: return renameWithoutEditor(element)
val dataContext = DataManager.getInstance().getDataContext(fileEditor.component)
val renameHandler = RenameHandlerRegistry.getInstance().getRenameHandler(dataContext)
val editor = editorManager.selectedTextEditor
if (editor != null) {
renameHandler?.invoke(project, editor, file, dataContext)
}
else {
val elementToRename = getElementToRename(element) ?: return
renameHandler?.invoke(project, arrayOf(elementToRename), dataContext)
}
}
protected open fun getElementToRename(element: PsiElement): PsiElement? = element.parent
private fun renameWithoutEditor(element: PsiElement) {
val elementToRename = getElementToRename(element)
val factory = RefactoringFactory.getInstance(element.project)
val renameRefactoring = factory.createRename(elementToRename, null, true, true)
renameRefactoring.run()
}
}
@@ -0,0 +1,26 @@
<problems>
<problem>
<file>test.kt</file>
<line>1</line>
<module>light_idea_test_case</module>
<entry_point TYPE="file" FQNAME="temp:///src/test.kt" />
<problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">Class naming convention</problem_class>
<description>Class name &lt;code&gt;a&lt;/code&gt; doesn't match regex '[A-Z][A-Za-z\d]*' #loc</description>
</problem>
<problem>
<file>test.kt</file>
<line>3</line>
<module>light_idea_test_case</module>
<entry_point TYPE="file" FQNAME="temp:///src/test.kt" />
<problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">Class naming convention</problem_class>
<description>Class name &lt;code&gt;b&lt;/code&gt; doesn''t match regex '[A-Z][A-Za-z\d]*' #loc</description>
</problem>
<problem>
<file>test.kt</file>
<line>5</line>
<module>light_idea_test_case</module>
<entry_point TYPE="file" FQNAME="temp:///src/test.kt" />
<problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">Class naming convention</problem_class>
<description>Class name &lt;code&gt;FOO_BAR&lt;/code&gt; doesn''t match regex '[A-Z][A-Za-z\d]*' #loc</description>
</problem>
</problems>
@@ -0,0 +1 @@
// INSPECTION_CLASS: org.jetbrains.kotlin.idea.inspections.ClassNameInspection
+13
View File
@@ -0,0 +1,13 @@
class a
object b
object FOO_BAR
enum class Foo {
BAR_BAZ,
BAZ_BAR,
GoodName,
_Foo,
quuxDoo,
}
@@ -0,0 +1,16 @@
<problems>
<problem>
<file>test.kt</file>
<line>11</line>
<module>light_idea_test_case</module>
<entry_point TYPE="file" FQNAME="temp:///src/test.kt" />
<description>Enum entry name &lt;code&gt;_Foo&lt;/code&gt; doesn't match regex '[A-Z]([A-Za-z\d]*|[A-Z_\d]*)' #loc</description>
</problem>
<problem>
<file>test.kt</file>
<line>12</line>
<module>light_idea_test_case</module>
<entry_point TYPE="file" FQNAME="temp:///src/test.kt" />
<description>Enum entry name &lt;code&gt;quuxDoo&lt;/code&gt; doesn't match regex '[A-Z]([A-Za-z\d]*|[A-Z_\d]*)' #loc</description>
</problem>
</problems>
@@ -0,0 +1 @@
// INSPECTION_CLASS: org.jetbrains.kotlin.idea.inspections.EnumEntryNameInspection
+13
View File
@@ -0,0 +1,13 @@
class a
object b
object FOO_BAR
enum class Foo {
BAR_BAZ,
BAZ_BAR,
GoodName,
_Foo,
quuxDoo,
}
@@ -0,0 +1,16 @@
<problems>
<problem>
<file>test.kt</file>
<line>1</line>
<module>light_idea_test_case</module>
<entry_point TYPE="file" FQNAME="temp:///src/test.kt" />
<description>Function name &lt;code&gt;Foo&lt;/code&gt; doesn't match regex '[a-z][A-Za-z\d]*' #loc</description>
</problem>
<problem>
<file>test.kt</file>
<line>3</line>
<module>light_idea_test_case</module>
<entry_point TYPE="file" FQNAME="temp:///src/test.kt" />
<description>Function name &lt;code&gt;FOO_BAR&lt;/code&gt; doesn't match regex '[a-z][A-Za-z\d]*' #loc</description>
</problem>
</problems>
@@ -0,0 +1 @@
// INSPECTION_CLASS: org.jetbrains.kotlin.idea.inspections.FunctionNameInspection
+5
View File
@@ -0,0 +1,5 @@
fun Foo() {}
fun FOO_BAR() {}
fun xyzzy() {}
@@ -0,0 +1,9 @@
<problems>
<problem>
<file>test.kt</file>
<line>23</line>
<module>light_idea_test_case</module>
<entry_point TYPE="file" FQNAME="temp:///src/test.kt" />
<description>Private property name &lt;code&gt;FOO_BAR&lt;/code&gt; doesn't match regex '[a-z][A-Za-z\d]*' #loc</description>
</problem>
</problems>
@@ -0,0 +1 @@
// INSPECTION_CLASS: org.jetbrains.kotlin.idea.inspections.PrivatePropertyNameInspection
@@ -0,0 +1,32 @@
val Foo: String = ""
var FOO_BAR: Int = 0
const val THREE = 3
val xyzzy = 1
fun foo() {
val XYZZY = 1
val BAR_BAZ = 2
}
object Foo {
val Foo: String = ""
var FOO_BAR: Int = 0
}
class D {
private val _foo: String
private val FOO_BAR: String
companion object {
val Foo: String = ""
var FOO_BAR: Int = 0
private val FOO_BAZ = 1
}
}
@@ -0,0 +1,16 @@
<problems>
<problem>
<file>test.kt</file>
<line>1</line>
<module>light_idea_test_case</module>
<entry_point TYPE="file" FQNAME="temp:///src/test.kt" />
<description>Property name &lt;code&gt;Foo&lt;/code&gt; doesn't match regex '[a-z][A-Za-z\d]*' #loc</description>
</problem>
<problem>
<file>test.kt</file>
<line>3</line>
<module>light_idea_test_case</module>
<entry_point TYPE="file" FQNAME="temp:///src/test.kt" />
<description>Property name &lt;code&gt;FOO_BAR&lt;/code&gt; doesn't match regex '[a-z][A-Za-z\d]*' #loc</description>
</problem>
</problems>
@@ -0,0 +1 @@
// INSPECTION_CLASS: org.jetbrains.kotlin.idea.inspections.PropertyNameInspection
+30
View File
@@ -0,0 +1,30 @@
val Foo: String = ""
var FOO_BAR: Int = 0
const val THREE = 3
val xyzzy = 1
fun foo() {
val XYZZY = 1
val BAR_BAZ = 2
}
object Foo {
val Foo: String = ""
var FOO_BAR: Int = 0
}
class D {
private val _foo: String
private val FOO_BAR: String
companion object {
val Foo: String = ""
var FOO_BAR: Int = 0
}
}
@@ -245,6 +245,36 @@ public class InspectionTestGenerated extends AbstractInspectionTest {
doTest(fileName);
}
@TestMetadata("naming/class/inspectionData/inspections.test")
public void testNaming_class_inspectionData_Inspections_test() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/inspections/naming/class/inspectionData/inspections.test");
doTest(fileName);
}
@TestMetadata("naming/enumEntry/inspectionData/inspections.test")
public void testNaming_enumEntry_inspectionData_Inspections_test() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/inspections/naming/enumEntry/inspectionData/inspections.test");
doTest(fileName);
}
@TestMetadata("naming/function/inspectionData/inspections.test")
public void testNaming_function_inspectionData_Inspections_test() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/inspections/naming/function/inspectionData/inspections.test");
doTest(fileName);
}
@TestMetadata("naming/privateProperty/inspectionData/inspections.test")
public void testNaming_privateProperty_inspectionData_Inspections_test() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/inspections/naming/privateProperty/inspectionData/inspections.test");
doTest(fileName);
}
@TestMetadata("naming/property/inspectionData/inspections.test")
public void testNaming_property_inspectionData_Inspections_test() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/inspections/naming/property/inspectionData/inspections.test");
doTest(fileName);
}
@TestMetadata("nullableBooleanElvis/inspectionData/inspections.test")
public void testNullableBooleanElvis_inspectionData_Inspections_test() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/inspections/nullableBooleanElvis/inspectionData/inspections.test");