Add quick fix to sync typevar name with target name (PY-28243)

This commit is contained in:
Semyon Proshev
2018-06-13 23:12:45 +03:00
parent 32e16524aa
commit b7ec888a70
4 changed files with 30 additions and 2 deletions
@@ -128,8 +128,13 @@ class PyTypeHintsInspection : PyInspection() {
if (argument !is PyStringLiteralExpression) {
registerProblem(argument, "'TypeVar()' expects a string literal as first argument")
}
else if (target != null && argument.stringValue != target.name) {
registerProblem(argument, "The argument to 'TypeVar()' must be a string equal to the variable name to which it is assigned")
else {
val targetName = target?.name
if (targetName != null && targetName != argument.stringValue) {
registerProblem(argument,
"The argument to 'TypeVar()' must be a string equal to the variable name to which it is assigned",
ReplaceWithTargetNameQuickFix(targetName))
}
}
"covariant" -> covariant = PyEvaluator.evaluateAsBoolean(argument, false)
"contravariant" -> contravariant = PyEvaluator.evaluateAsBoolean(argument, false)
@@ -422,6 +427,18 @@ class PyTypeHintsInspection : PyInspection() {
}
companion object {
private class ReplaceWithTargetNameQuickFix(private val targetName: String) : LocalQuickFix {
override fun getFamilyName() = "Replace with target name"
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val old = descriptor.psiElement as? PyStringLiteralExpression ?: return
val new = PyElementGenerator.getInstance(project).createStringLiteral(old, targetName) ?: return
old.replace(new)
}
}
private class ReplaceWithSubscriptionQuickFix : LocalQuickFix {
override fun getFamilyName() = "Replace with square brackets"
@@ -0,0 +1,3 @@
from typing import TypeVar
T1 = TypeVar(<warning descr="The argument to 'TypeVar()' must be a string equal to the variable name to which it is assigned">'T<caret>2'</warning>)
@@ -0,0 +1,3 @@
from typing import TypeVar
T1 = TypeVar('T1')
@@ -36,4 +36,9 @@ class PyTypeHintsQuickFixTest : PyQuickFixTestCase() {
fun testParenthesesAndCustomTarget() {
doQuickFixTest(PyTypeHintsInspection::class.java, "Replace with square brackets", LanguageLevel.PYTHON35)
}
// PY-28243
fun testTypeVarAndTargetName() {
doQuickFixTest(PyTypeHintsInspection::class.java, "Replace with target name")
}
}